Skip to content

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

Unify permission authority and window presentation state

zohayrslileh34cccd3e3085
diff --git a/bun.lock b/bun.lock
index c9b3615..8a58835 100644
--- a/bun.lock
+++ b/bun.lock
@@ -24,7 +24,6 @@
"sharp": "^0.35.3",
"uuid": "^14.0.1",
"ws": "^8.21.3",
- "zod": "^4.4.3",
},
"devDependencies": {
"@babel/core": "^7.29.7",
@@ -513,7 +512,6 @@
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
- "zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
diff --git a/package.json b/package.json
index e04f790..ca4f42f 100644
--- a/package.json
+++ b/package.json
@@ -53,8 +53,7 @@
"react-dom": "^19.2.8",
"sharp": "^0.35.3",
"uuid": "^14.0.1",
- "ws": "^8.21.3",
- "zod": "^4.4.3"
+ "ws": "^8.21.3"
},
"devDependencies": {
"@babel/core": "^7.29.7",
diff --git a/scripts/contracts/appearance.ts b/scripts/contracts/appearance.ts
index 40dcb80..cabcacb 100644
--- a/scripts/contracts/appearance.ts
+++ b/scripts/contracts/appearance.ts
@@ -1,28 +1,28 @@
import assert from "node:assert/strict"
import Keyv from "keyv"
-import { defaultAppearance } from "@phreshos/core"
-import AppearanceManager, { appearanceSchema } from "@server/core/appearance-manager"
+import { defaultAppearance, parseAppearance } from "@phreshos/core"
+import AppearanceManager from "@server/core/appearance-manager"
import FileManager from "@libs/file-manager"
import UploadManager from "@server/core/upload-manager"
import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
-assert.deepEqual(appearanceSchema.parse(defaultAppearance), defaultAppearance)
-assert.throws(() => appearanceSchema.parse({}))
-assert.throws(() => appearanceSchema.parse({
+assert.deepEqual(parseAppearance(defaultAppearance), defaultAppearance)
+assert.throws(() => parseAppearance({}))
+assert.throws(() => parseAppearance({
...defaultAppearance,
colors: { ...defaultAppearance.colors, accent: defaultAppearance.colors.light.primary }
}))
-assert.throws(() => appearanceSchema.parse({ ...defaultAppearance, spacing: { light: 12, dark: 12 } }))
-assert.throws(() => appearanceSchema.parse({
+assert.throws(() => parseAppearance({ ...defaultAppearance, spacing: { light: 12, dark: 12 } }))
+assert.throws(() => parseAppearance({
...defaultAppearance,
material: {
...defaultAppearance.material,
dark: { ...defaultAppearance.material.dark, grain: 1.01 }
}
}))
-assert.throws(() => appearanceSchema.parse({
+assert.throws(() => parseAppearance({
...defaultAppearance,
transaction: { duration: 120 }
}))
diff --git a/scripts/contracts/client-surface.ts b/scripts/contracts/client-surface.ts
index c16a58e..6da936c 100644
--- a/scripts/contracts/client-surface.ts
+++ b/scripts/contracts/client-surface.ts
@@ -104,19 +104,71 @@ first.complete("bare", "geometry", followRevision)
await following
assert.deepEqual(first.state("bare").position, first.state("ordinary").position)
+// Following reads authority, never another Desktop-local representation.
await first.move("ordinary", { x: 150, y: 160 })
-assert.deepEqual(first.state("bare").position, { x: 150, y: 160 })
+assert.deepEqual(first.state("bare").position, ordinary.window.position)
+ordinary.window.position = { x: 170, y: 180 }
+first.reconcile(clients)
+assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })
-const unfollowing = first.unfollow("bare", transaction)
-const unfollowRevision = represented(first, "bare:0").geometryAnimation!.revision
-first.complete("bare", "geometry", unfollowRevision)
-await unfollowing
-assert.deepEqual(first.state("bare").position, { x: 120, y: 130 })
+await first.unfollow("bare", transaction)
+assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })
+ordinary.window.position = { x: 190, y: 200 }
+first.reconcile(clients)
+assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })
+// Default following can be disabled on ordinary windows and enabled on bare ones.
+await first.unfollow("ordinary")
+ordinary.window.position = { x: 210, y: 220 }
+first.reconcile(clients)
+assert.deepEqual(first.state("ordinary").position, { x: 190, y: 200 })
+await first.follow("ordinary", "ordinary")
+assert.deepEqual(first.state("ordinary").position, { x: 210, y: 220 })
await first.follow("bare", "ordinary")
await first.move("bare", { x: 125, y: 135 })
-await first.move("ordinary", { x: 155, y: 165 })
+ordinary.window.title = "Renamed"
+first.reconcile(clients)
+assert.equal(first.state("bare").title, "Renamed")
assert.deepEqual(first.state("bare").position, { x: 125, y: 135 })
+ordinary.window.position = { x: 230, y: 240 }
+first.reconcile(clients)
+assert.deepEqual(first.state("bare").position, ordinary.window.position)
+
+// Stored geometry cannot cancel an in-progress maximize presentation.
+const maximizing = first.maximize("bare", true, transaction)
+const maximizeRevision = represented(first, "bare:0").geometryAnimation!.revision
+await first.move("bare", { x: 9, y: 10 }, transaction)
+assert.equal(represented(first, "bare:0").geometryAnimation!.revision, maximizeRevision)
+first.complete("bare", "geometry", maximizeRevision)
+await maximizing
+await first.maximize("bare", false)
+const toInterrupt = first.maximize("bare", true, transaction)
+await first.minimize("bare", true)
+await assert.rejects(toInterrupt, /was minimized/)
+await first.minimize("bare", false)
+await first.maximize("bare", false)
+
+// Minimize and maximize never overwrite the retained geometry or each other.
+await first.maximize("bare", true)
+await first.minimize("bare", true)
+await first.geometry("bare", { position: { x: 11, y: 12 }, size: { width: 111, height: 112 } }, transaction)
+assert.equal(first.projection("bare").geometryAnimation, null)
+assert.equal(first.state("bare").maximized, true)
+assert.equal(first.state("bare").minimized, true)
+await first.minimize("bare", false)
+assert.equal(first.state("bare").maximized, true)
+await first.maximize("bare", false)
+assert.deepEqual(first.state("bare").position, { x: 11, y: 12 })
+assert.deepEqual(first.state("bare").size, { width: 111, height: 112 })
+await first.follow("bare", "ordinary")
+ordinary.window.maximized = true
+ordinary.window.minimized = true
+first.reconcile(clients)
+assert.equal(first.state("bare").maximized, true)
+assert.equal(first.state("bare").minimized, true)
+ordinary.window.maximized = false
+ordinary.window.minimized = false
+first.reconcile(clients)
const surfaceWaiting = first.addSurface("bare", visibility)
const surfaceRevision = surface(first, "bare:0").transition!.revision
@@ -227,7 +279,9 @@ await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress, undefine
await assert.rejects(request("windowLocalSurfaceAdd", targetAddress), /current Client Context/)
await assert.rejects(request("windowLocalSurfaceAdd", { ...requesterAddress, reference: "wrong" }), /represented by this handle does not exist/)
requester.client.window.layer = "window"
-await assert.rejects(request("windowLocalMove", requesterAddress, { x: 0, y: 0 }), /window-layer Process/)
+await request("windowLocalMove", requesterAddress, { x: 0, y: 0 })
+await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress), /already owns its host Surface/)
+await assert.rejects(request("windowLocalSurfaceRemove", requesterAddress), /already owns its host Surface/)
requester.client.window.layer = "over"
const lifecycle: string[] = []
@@ -252,7 +306,7 @@ function client(layer: WindowLayer) {
title: "Window",
position: { x: 0, y: 0 },
size: { width: 300, height: 200 },
- minimized: false,
+ minimized: false, maximized: false,
layer,
depth: 1
}
diff --git a/scripts/contracts/permission-requests.ts b/scripts/contracts/permission-requests.ts
index b382632..9e2d08a 100644
--- a/scripts/contracts/permission-requests.ts
+++ b/scripts/contracts/permission-requests.ts
@@ -1,8 +1,8 @@
import assert from "node:assert/strict"
-import { mkdtempSync, readFileSync, rmSync } from "node:fs"
+import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
-import type { PermissionName, PermissionRequest, Permissions } from "@phreshos/core"
+import type { 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"
@@ -46,63 +46,41 @@ try {
const request = <Name extends PermissionName>(name: Name, value: PermissionRequest<Name> = true) => (
processManager.requestPermission("process", "request", name, value)
)
- async function covered<Name extends PermissionName>(permissions: Permissions, name: Name, requested: PermissionRequest<Name>, expected: unknown) {
- writePermissions(program, permissions)
- const stored = readFileSync(join(temporary, "permissions.json"), "utf8")
- const before = dialogs
- assert.deepEqual(await request(name, requested), expected)
- assert.equal(dialogs, before)
- assert.equal(readFileSync(join(temporary, "permissions.json"), "utf8"), stored)
- }
-
- await covered({ services: [] }, "services", ["browser"], ["browser"])
- await covered({ services: ["browser", "editor"] }, "services", ["browser"], ["browser"])
- await covered({ programs: [] }, "services", ["browser"], ["browser"])
- await covered({ programs: ["browser"] }, "services", ["browser"], ["browser"])
- await covered({ programs: ["browser"], services: ["editor"] }, "services", ["browser", "editor"], ["browser", "editor"])
- await covered({ programs: [], services: false }, "services", ["browser"], ["browser"])
- await covered({ all: [] }, "services", ["browser"], ["browser"])
- await covered({ all: [] }, "network", ["https://example.test"], ["https://example.test"])
- await covered({ network: ["https://example.test/**"] }, "network", ["https://example.test/api"], ["https://example.test/api"])
- await covered({ storage: ["Documents/**"] }, "storage", ["read:Documents/report.txt"], ["read:Documents/report.txt"])
- await covered({ services: [] }, "services", true, [])
- await covered({}, "services", ["example"], ["example"])
- await covered({}, "programs", ["example"], ["example"])
-
- writePermissions(program, { services: false })
- assert.equal(await request("services", ["browser"]), false)
- assert.equal(dialogs, 0)
-
- writePermissions(program, {})
+ // Stored authority never bypasses approval, even for a narrower request.
+ writePermissions(program, { services: ["browser", "editor"] })
assert.equal(await request("services", ["browser"]), null)
assert.equal(dialogs, 1)
- assert.deepEqual(readPermissions(program), {})
+ assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })
choice = false
assert.equal(await request("services", ["browser"]), false)
assert.equal(dialogs, 2)
- assert.deepEqual(readPermissions(program), {})
+ assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })
+ // Approval replaces the exact permission instead of widening or merging it.
choice = true
- writePermissions(program, { services: ["editor"] })
assert.deepEqual(await request("services", ["browser"]), ["browser"])
assert.equal(dialogs, 3)
- assert.deepEqual(readPermissions(program), { services: ["editor", "browser"] })
+ assert.deepEqual(readPermissions(program), { services: ["browser"] })
- // A pending request must not overwrite a grant saved by another request.
- writePermissions(program, {})
+ // A concurrent edit cannot turn one approved request into a broader grant.
whilePending = () => writePermissions(program, { services: ["editor"] })
assert.deepEqual(await request("services", ["browser"]), ["browser"])
- assert.deepEqual(readPermissions(program), { services: ["editor", "browser"] })
+ assert.deepEqual(readPermissions(program), { 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: [] })
+ 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"]))
+
+ // Program declarations are installation input, never a second live source.
const declared = new Program({ identity: "declared", storage: temporary, client: { location: ".", permissions: { programs: ["browser"] } } })
writePermissions(declared, { services: ["editor"] })
- assert(programManager.grantsPermission(declared, "services", ["browser", "editor"]))
- assert(!programManager.allowsPermission(declared, "services", ["browser"]))
- assert(programManager.allowsPermission(declared, "services", ["editor"]))
- writePermissions(declared, { programs: ["browser"] })
- assert(programManager.allowsPermission(declared, "services", ["browser"]))
+ assert(!programManager.grantsPermission(declared, "services", ["browser"]))
+ assert(programManager.grantsPermission(declared, "services", ["editor"]))
// The iframe policy is synchronized independently of permission request results.
writePermissions(program, {})
diff --git a/scripts/contracts/permissions.ts b/scripts/contracts/permissions.ts
index a6a53cd..363f4ac 100644
--- a/scripts/contracts/permissions.ts
+++ b/scripts/contracts/permissions.ts
@@ -112,30 +112,18 @@ assert(catalog.allows("services", ["browser"], { services: ["browser"] }))
assert(catalog.allows("services", ["browser"], { programs: [] }))
assert(catalog.allows("services", [], { programs: [] }))
assert(catalog.allows("services", ["browser"], { programs: ["browser"] }))
-assert(catalog.allows("services", ["browser", "editor"], { programs: ["browser"], services: ["editor"] }))
-assert(catalog.allows("services", ["browser", "editor"], { programs: ["browser"] }, { services: ["editor"] }))
+assert(!catalog.allows("services", ["browser", "editor"], { programs: ["browser"], services: ["editor"] }))
+assert(catalog.allows("services", ["editor"], { programs: ["browser"], services: ["editor"] }))
assert(!catalog.allows("services", ["editor"], { programs: ["browser"] }))
assert(!catalog.allows("services", [], { programs: ["browser"] }))
assert(!catalog.allows("programs", ["browser"], { services: [] }))
-assert(catalog.allows("services", ["browser"], { programs: [], services: false }))
-assert.equal(catalog.combine("all", null, false), null)
-assert.deepEqual(catalog.combine("all", []), [])
-assert.deepEqual(catalog.combine("services", ["flambo"], ["terminal"]), ["flambo", "terminal"])
-assert.deepEqual(catalog.combine("services", ["flambo"], []), [])
-assert.deepEqual(catalog.combine("network", ["https://api.example.com"], ["wss://events.example.com"]), [
- "https://api.example.com",
- "wss://events.example.com"
-])
-assert.equal(catalog.effective("all", null, false), false)
-assert.deepEqual(catalog.effective("all", [], false), [])
-assert.deepEqual(catalog.merge("all", null, []), [])
-assert.deepEqual(catalog.merge("services", ["flambo"], ["terminal"]), ["flambo", "terminal"])
-assert.deepEqual(catalog.merge("services", ["flambo"], []), [])
-assert.deepEqual(catalog.merge("services", [], ["flambo"]), [])
-assert.deepEqual(catalog.merge("network", ["https://api.example.com"], ["wss://events.example.com"]), [
- "https://api.example.com",
- "wss://events.example.com"
-])
+assert(!catalog.allows("services", ["browser"], { programs: [], services: false }))
+assert(!catalog.allows("network", ["https://elsewhere.example"], { all: [], network: ["https://api.example.com"] }))
+assert(catalog.allows("network", ["https://api.example.com/v1"], { all: [], network: ["https://api.example.com"] }))
+assert(catalog.allowsStorage([], null, "Documents/report.txt", "read"))
+assert(catalog.allowsStorage([], ["read:Documents/**"], "Documents/report.txt", "read"))
+assert(!catalog.allowsStorage([], ["read:Documents/**"], "Pictures/photo.png", "read"))
+assert(!catalog.allowsStorage([], false, "Documents/report.txt", "read"))
assert(!catalog.changed([], []))
assert(!catalog.changed(["flambo", "terminal"], ["terminal", "flambo"]))
assert(catalog.changed(["flambo"], []))
diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.ts
index 6c5db0a..cb59a59 100644
--- a/scripts/contracts/process-lifecycle.ts
+++ b/scripts/contracts/process-lifecycle.ts
@@ -111,10 +111,10 @@ async function register(manager: ProcessManager, identity: string) {
null,
client,
{},
- { ...launch, client: { title: "Partial", position: null, size: null, layer: "window", minimize: false, service: false } },
+ { ...launch, client: { title: "Partial", position: null, size: null, layer: "window", minimize: false, maximize: false, service: false } },
null,
true,
- { title: "Partial", position: { x: 0, y: 0 }, size: { width: 320, height: 240 }, layer: "window", minimize: false },
+ { title: "Partial", position: { x: 0, y: 0 }, size: { width: 320, height: 240 }, layer: "window", minimize: false, maximize: false },
null
), /creation publication failed/)
diff --git a/scripts/contracts/program-install.ts b/scripts/contracts/program-install.ts
index 8bc3da1..b1297f8 100644
--- a/scripts/contracts/program-install.ts
+++ b/scripts/contracts/program-install.ts
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os"
import { join } from "node:path"
import Program from "@server/core/link-manager/auth-manager/program-manager/program"
import { copyProgram } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { installPermissions, readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"
import type { ProgramCommandChunk } from "@phreshos/core"
const temporary = mkdtempSync(join(tmpdir(), "phresh-program-install-"))
@@ -30,7 +31,8 @@ try {
startCommand: "true"
},
client: {
- location: join(source, "client")
+ location: join(source, "client"),
+ permissions: { network: ["https://api.example.test/**"] }
}
})
@@ -48,6 +50,12 @@ try {
assert.equal(readFileSync(join(installed, "agent.md"), "utf8"), "Program operating knowledge")
const installedProgram = new Program(join(installed, "program.json"))
+ writePermissions(installedProgram, { network: ["https://old.example.test/**"], appearance: [] })
+ const rollbackPermissions = installPermissions(installedProgram)
+ assert.deepEqual(readPermissions(installedProgram), { network: ["https://api.example.test"] })
+ rollbackPermissions()
+ assert.deepEqual(readPermissions(installedProgram), { network: ["https://old.example.test"], appearance: [] })
+ installPermissions(installedProgram)
const installation: ProgramCommandChunk[] = []
const uninstallation: ProgramCommandChunk[] = []
diff --git a/scripts/contracts/window-geometry.ts b/scripts/contracts/window-geometry.ts
index 8c624fe..db2e73f 100644
--- a/scripts/contracts/window-geometry.ts
+++ b/scripts/contracts/window-geometry.ts
@@ -67,3 +67,22 @@ const counterpart = new ClientWindow(
)
await counterpart.setGeometry(next)
assert.deepEqual(publications, [["/geometry", "process", next]])
+
+authority.minimized = true
+await ProcessManager.prototype.maximize.call(manager as unknown as ProcessManager, "process", true)
+assert.equal(authority.maximized, true)
+assert.equal(authority.minimized, true)
+assert.deepEqual(authority.position, next.position)
+assert.deepEqual(authority.size, next.size)
+assert.deepEqual(events.at(-1), ["process", "maximize", true])
+const stored = { position: { x: 44, y: 55 }, size: { width: 440, height: 550 } }
+authority.setGeometry(stored)
+await ProcessManager.prototype.maximize.call(manager as unknown as ProcessManager, "process", false)
+assert.equal(authority.minimized, true)
+assert.equal(authority.maximized, false)
+assert.deepEqual(authority.position, stored.position)
+assert.deepEqual(authority.size, stored.size)
+await counterpart.maximize(true)
+assert.deepEqual(publications.at(-1), ["/maximize", "process", true])
+counterpart.follow(authority.toJSON())
+assert.equal(counterpart.maximized, false)
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 d4b244a..1328055 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
@@ -339,6 +339,13 @@ export default class ProcessManager extends TheLink {
return this.followed(payload)
}
+ @Subscribe("/maximize")
+ @Publish("/processes", "inbound")
+ protected async maximizeHandle(payload: { identity: string, window: WindowSnapshot } | null) {
+
+ return this.followed(payload)
+ }
+
@Subscribe("/minimize")
@Publish("/processes", "inbound")
protected async minimizeHandle(payload: { identity: string, window: WindowSnapshot } | null) {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process.ts b/source/client/core/link-manager/auth-manager/process-manager/process.ts
index 9ea8ad1..b256489 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process.ts
@@ -31,7 +31,7 @@ export default class Process {
// Retained lineage from creation. It remains sufficient to reconstruct
// the same Process handle after the parent leaves the live registry.
- public readonly parent: ProcessRecord | null
+ public readonly parent: ProcessLineage | null
// What its launch said, carried for its whole life.
public readonly options: Record<string, string>
@@ -113,7 +113,8 @@ export default class Process {
}
}
-export interface ProcessRecord {
+/** Retained identity needed only to reconstruct a departed parent handle. */
+export interface ProcessLineage {
readonly reference: string
diff --git a/source/client/core/link-manager/auth-manager/process-manager/window.ts b/source/client/core/link-manager/auth-manager/process-manager/window.ts
index bd2590c..0d93275 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/window.ts
@@ -1,5 +1,5 @@
import { type WindowSnapshot, type Position, type Size } from "@server/core/link-manager/auth-manager/process-manager/window"
-import { type WindowGeometry, type WindowLayer } from "@phreshos/core"
+import { type WindowGeometry, type WindowLayer, type WindowState } from "@phreshos/core"
import ProcessManager from "./process-manager"
/**
@@ -11,7 +11,7 @@ import ProcessManager from "./process-manager"
* Its own instance, rebuilt from what crossed. It shares no code with
* the core's window; they are alike because they are the same idea.
*/
-export default class Window {
+export default class Window implements Omit<WindowState, "front"> {
public readonly processManager: ProcessManager
@@ -25,6 +25,8 @@ export default class Window {
public minimized: boolean
+ public maximized: boolean
+
// What is shown on it, born from its program when the window was
// made. Not looked up again: how a thing is shown is not a fact
// about whether its program is installed. Changeable, because the
@@ -52,6 +54,8 @@ export default class Window {
this.minimized = payload.minimized
+ this.maximized = payload.maximized
+
}
// What the echo carries, applied whole: one shape for any change.
@@ -69,6 +73,8 @@ export default class Window {
this.minimized = payload.minimized
+ this.maximized = payload.maximized
+
}
public async move(position: Position) {
@@ -99,6 +105,11 @@ export default class Window {
await this.processManager.$outbound.publish("/raise", this.process)
}
+ public async maximize(maximized: boolean) {
+
+ await this.processManager.$outbound.publish("/maximize", this.process, maximized)
+ }
+
public async minimize(minimized: boolean) {
await this.processManager.$outbound.publish("/minimize", this.process, minimized)
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index bf7a2f1..9b28802 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -27,7 +27,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [authManager, panes, traffic])
- processes.useSubscribe("/created", useCallback((payload: ProcessRecord | null) => {
+ processes.useSubscribe("/created", useCallback((payload: HostedProcessRecord | null) => {
if (!payload) return
@@ -38,7 +38,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [authManager, post]))
- processes.useSubscribe("/exited", useCallback((payload: ProcessRecord | null, code: number | null, signal: string | null) => {
+ processes.useSubscribe("/exited", useCallback((payload: HostedProcessRecord | null, code: number | null, signal: string | null) => {
if (!payload) return
@@ -50,7 +50,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [authManager, post]))
- const endpoint = useCallback((event: "endpointStart" | "endpointStop", endpoint: "server" | "client", payload: ProcessRecord | null) => {
+ const endpoint = useCallback((event: "endpointStart" | "endpointStop", endpoint: "server" | "client", payload: HostedProcessRecord | null) => {
if (!payload) return
@@ -58,10 +58,10 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
}, [authManager, post])
- processes.useSubscribe("/server-start", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStart", "server", payload), [endpoint]))
- processes.useSubscribe("/server-stop", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStop", "server", payload), [endpoint]))
- processes.useSubscribe("/client-start", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStart", "client", payload), [endpoint]))
- processes.useSubscribe("/client-stop", useCallback((_identity: unknown, payload: ProcessRecord | null) => endpoint("endpointStop", "client", payload), [endpoint]))
+ processes.useSubscribe("/server-start", useCallback((_identity: unknown, payload: HostedProcessRecord | null) => endpoint("endpointStart", "server", payload), [endpoint]))
+ processes.useSubscribe("/server-stop", useCallback((_identity: unknown, payload: HostedProcessRecord | null) => endpoint("endpointStop", "server", payload), [endpoint]))
+ processes.useSubscribe("/client-start", useCallback((_identity: unknown, payload: HostedProcessRecord | null) => endpoint("endpointStart", "client", payload), [endpoint]))
+ processes.useSubscribe("/client-stop", useCallback((_identity: unknown, payload: HostedProcessRecord | null) => endpoint("endpointStop", "client", payload), [endpoint]))
processes.useSubscribe("/said", useCallback((identity: string, event: string, value: unknown) => {
@@ -90,7 +90,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
programs.useSubscribe("/forgotten", useCallback((entry: ProgramRecord | null) => programEvent("forget", entry), [programEvent]))
}
-function processRecord(authManager: AuthManager, process: ProcessRecord) {
+function processRecord(authManager: AuthManager, process: HostedProcessRecord) {
return sdkProcess(process, program(authManager, process.program))
}
@@ -104,7 +104,7 @@ function program(authManager: AuthManager, identity: string) {
return found
}
-type ProcessRecord = {
+type HostedProcessRecord = {
reference: string
identity: string
program: string
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index d7f3d26..2fafbfd 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -1,6 +1,7 @@
import {
type DesktopViewportSnapshot,
- type Launch
+ type Launch,
+ type WindowState
} from "@phreshos/core"
import { type ProxyRequest } from "@server/core/protocol/proxy"
import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
@@ -22,7 +23,7 @@ import {
localGeometry,
localPosition,
localSize,
- requireLocalWindowLayer,
+ requireLocalSurfaceLayer,
parseLocalWindowTransaction,
type LocalWindowHost
} from "./local-window"
@@ -681,12 +682,13 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
size: shown.size,
minimized: shown.minimized,
+ maximized: shown.maximized,
front: processManager.front(shown.layer) === target.identity,
// Which structurally isolated Desktop layer contains it.
layer: shown.layer
- }]
+ } satisfies WindowState]
}
if (word === "move") {
@@ -713,7 +715,6 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalMove") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
await localWindow.move(target.identity, localPosition(args[1]), parseLocalWindowTransaction(args[2]))
return []
@@ -722,7 +723,6 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalResize") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
await localWindow.resize(target.identity, localSize(args[1]), parseLocalWindowTransaction(args[2]))
return []
@@ -731,7 +731,6 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalGeometry") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
await localWindow.geometry(target.identity, localGeometry(args[1]), parseLocalWindowTransaction(args[2]))
return []
@@ -740,7 +739,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalSurfaceAdd") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
+ requireLocalSurfaceLayer(target.client!.window.layer)
await localWindow.addSurface(target.identity, parseLocalWindowTransaction(args[2]))
return []
@@ -749,16 +748,30 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalSurfaceRemove") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
+ requireLocalSurfaceLayer(target.client!.window.layer)
await localWindow.removeSurface(target.identity, parseLocalWindowTransaction(args[2]))
return []
}
+ if (word === "windowLocalTitle") {
+ const target = localProcess(args[0])
+ const title = String(args[1] ?? "").trim()
+ if (!title) throw new Error("A Window title must not be empty")
+ localWindow.title(target.identity, title)
+ return []
+ }
+
+ if (word === "windowLocalMaximize") {
+ const target = localProcess(args[0])
+ if (typeof args[1] !== "boolean") throw new Error("Local Window maximize takes a boolean state")
+ await localWindow.maximize(target.identity, args[1], parseLocalWindowTransaction(args[2]))
+ return []
+ }
+
if (word === "windowLocalMinimize") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
if (typeof args[1] !== "boolean") throw new Error("Local Window minimize takes a boolean state")
@@ -770,7 +783,6 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalFollow") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
const followed = await permittedProcess(args[1])
clientOf(followed)
await localWindow.follow(target.identity, followed.identity, parseLocalWindowTransaction(args[2]))
@@ -781,7 +793,6 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalUnfollow") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
await localWindow.unfollow(target.identity, parseLocalWindowTransaction(args[1]))
return []
@@ -790,7 +801,6 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "windowLocalRaise") {
const target = localProcess(args[0])
- requireLocalWindowLayer(target.client!.window.layer)
localWindow.raise(target.identity)
return []
@@ -810,6 +820,11 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return [pane]
}
+ if (word === "maximize") {
+ await clientOf(await permittedProcess(args[0])).window.maximize(args[1] !== false)
+ return [pane]
+ }
+
if (word === "minimize") {
await clientOf(await permittedProcess(args[0])).window.minimize(args[1] !== false)
diff --git a/source/client/view/components/desktop-host/local-window.ts b/source/client/view/components/desktop-host/local-window.ts
index 3b9cb60..ecf7827 100644
--- a/source/client/view/components/desktop-host/local-window.ts
+++ b/source/client/view/components/desktop-host/local-window.ts
@@ -35,6 +35,7 @@ export interface LocalWindowHost {
move(identity: string, position: Position, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
resize(identity: string, size: Size, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
geometry(identity: string, geometry: WindowGeometry, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
+ maximize(identity: string, maximized: boolean, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
minimize(identity: string, minimized: boolean, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
follow(identity: string, target: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
unfollow(identity: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
@@ -92,9 +93,9 @@ export function parseLocalWindowTransaction(value: unknown): AppearanceTransacti
return Object.freeze(result)
}
-export function requireLocalWindowLayer(layer: WindowLayer) {
+export function requireLocalSurfaceLayer(layer: WindowLayer) {
- if (layer === "window") throw new Error("A window-layer Process cannot change its local Window representation")
+ if (layer === "window") throw new Error("A standard Window already owns its host Surface")
}
function easing(value: unknown): Easing {
diff --git a/source/client/view/components/window-manager/local-windows.ts b/source/client/view/components/window-manager/local-windows.ts
index da738f6..58c96b5 100644
--- a/source/client/view/components/window-manager/local-windows.ts
+++ b/source/client/view/components/window-manager/local-windows.ts
@@ -18,7 +18,7 @@ export default class LocalWindows implements LocalWindowHost {
public windows: ReadonlyMap<string, LocalWindowState>
private readonly live = new Map<string, string>()
- private readonly authoritative = new Map<string, string>()
+ private readonly authoritative = new Map<string, LocalWindowState>()
private readonly waiting = new Map<string, WaitingAnimation>()
private readonly readers = new Map<string, LocalGeometryReader>()
private readonly following = new Map<string, FollowingWindow>()
@@ -36,49 +36,57 @@ export default class LocalWindows implements LocalWindowHost {
this.changed = changed
}
- /** Projects new authority only where the ordinary Window layer delegates it. */
+ /** Following projects authoritative property changes, independent of Desktop layer. */
public reconcile(current: ReadonlyMap<string, LocalWindowEntry>) {
-
for (const [process, identity] of this.live) {
-
if (current.get(process)?.identity === identity) continue
-
this.cancel(identity, "geometry", "The local Window representation was removed")
-
this.cancel(identity, "minimize", "The local Window representation was removed")
-
this.cancel(identity, "surface", "The local Window representation was removed")
+ this.following.delete(identity)
+ this.authoritative.delete(identity)
}
this.live.clear()
const next = new Map(this.windows)
-
for (const [process, { identity, client }] of current) {
-
this.live.set(process, identity)
- const previous = next.get(identity)
- const signature = authoritativeSignature(client)
-
- if (!previous) next.set(identity, localState(client))
- else if (client.window.layer === "window" && this.authoritative.get(identity) !== signature) {
-
- const geometryChanged = JSON.stringify([previous.position, previous.size]) !== JSON.stringify([client.window.position, client.window.size])
- if (geometryChanged) this.cancel(identity, "geometry", "The local Window animation was replaced by authoritative state")
- next.set(identity, projectAuthoritative(previous, client, geometryChanged))
+ const snapshot = localState(client)
+ if (!this.authoritative.has(identity) && client.window.layer === "window") {
+ this.following.set(identity, { target: identity, snapshot })
}
-
- this.authoritative.set(identity, signature)
+ if (!next.has(identity)) next.set(identity, snapshot)
+ this.authoritative.set(identity, snapshot)
}
- const liveIdentities = new Set(this.live.values())
-
+ const alive = new Set(this.live.values())
for (const [identity, relation] of this.following) {
-
- if (!liveIdentities.has(identity) || !liveIdentities.has(relation.target)) this.following.delete(identity)
+ if (!alive.has(identity) || !alive.has(relation.target)) {
+ this.following.delete(identity)
+ continue
+ }
+ const state = next.get(identity)!
+ const target = this.authoritative.get(relation.target)!
+ const previous = relation.snapshot
+ const changes: { -readonly [Key in keyof LocalWindowState]?: LocalWindowState[Key] } = {}
+ for (const key of ["title", "position", "size", "minimized", "maximized", "depth"] as const) {
+ if (JSON.stringify(previous[key]) !== JSON.stringify(target[key])) Object.assign(changes, { [key]: target[key] })
+ }
+ const maximized = changes.maximized ?? state.maximized
+ const minimized = changes.minimized ?? state.minimized
+ const geometryChanged = ("position" in changes && JSON.stringify(state.position) !== JSON.stringify(changes.position))
+ || ("size" in changes && JSON.stringify(state.size) !== JSON.stringify(changes.size))
+ if (maximized !== state.maximized || (!maximized && geometryChanged) || (minimized && !state.minimized)) {
+ this.cancel(identity, "geometry", "The followed Window presentation changed")
+ changes.geometryAnimation = null
+ }
+ if ("minimized" in changes && state.minimized !== changes.minimized) {
+ this.cancel(identity, "minimize", "The followed Window visibility changed")
+ changes.minimizeAnimation = null
+ }
+ next.set(identity, { ...state, ...changes })
+ relation.snapshot = target
}
-
- projectFollowing(next, this.following, (identity, kind) => this.cancel(identity, kind, "The followed Window changed"))
-
this.publish(next)
}
@@ -123,88 +131,69 @@ export default class LocalWindows implements LocalWindowHost {
public move(process: string, position: WindowState["position"], transaction?: RequestedTransaction) {
const { identity, state } = this.existing(process)
- this.following.delete(identity)
return this.changeGeometry(identity, { position, size: state.size }, transaction)
}
public resize(process: string, size: WindowState["size"], transaction?: RequestedTransaction) {
const { identity, state } = this.existing(process)
- this.following.delete(identity)
return this.changeGeometry(identity, { position: state.position, size }, transaction)
}
public geometry(process: string, value: WindowGeometry, transaction?: RequestedTransaction) {
const { identity } = this.existing(process)
- this.following.delete(identity)
return this.changeGeometry(identity, value, transaction)
}
public minimize(process: string, minimized: boolean, transaction?: RequestedTransaction) {
const { identity } = this.existing(process)
- this.following.delete(identity)
return this.changeMinimized(identity, minimized, transaction)
}
- public follow(process: string, targetProcess: string, transaction?: RequestedTransaction) {
+ public maximize(process: string, maximized: boolean, transaction?: RequestedTransaction) {
+ const { identity, state } = this.existing(process)
+ if (state.maximized === maximized) return Promise.resolve()
+ this.cancel(identity, "geometry")
+ const animation = transaction && !state.minimized ? localAnimation(++this.revision, transaction) : null
+ this.replace(identity, { ...state, maximized, geometryAnimation: animation })
+ return this.waitFor(identity, "geometry", animation, transaction)
+ }
- const follower = this.existing(process)
+ public follow(process: string, targetProcess: string, transaction?: RequestedTransaction) {
+ const { identity } = this.existing(process)
const target = this.existing(targetProcess)
-
- if (follower.identity === target.identity) throw new Error("A local Window cannot follow itself")
-
- for (let identity: string | undefined = target.identity; identity; identity = this.following.get(identity)?.target) {
-
- if (identity === follower.identity) throw new Error("Local Windows cannot form a following cycle")
- }
-
- const current = this.following.get(follower.identity)
-
- if (current?.target === target.identity) return Promise.resolve()
-
- this.following.set(follower.identity, {
-
- target: target.identity,
-
- restore: current?.restore ?? {
-
- position: follower.state.position,
-
- size: follower.state.size,
-
- minimized: follower.state.minimized
- }
+ const snapshot = this.authoritative.get(target.identity)!
+ this.following.set(identity, { target: target.identity, snapshot })
+ const current = this.windows.get(identity)!
+ const geometryChanged = JSON.stringify([current.position, current.size, current.maximized]) !== JSON.stringify([snapshot.position, snapshot.size, snapshot.maximized])
+ const visibilityChanged = current.minimized !== snapshot.minimized
+ this.cancel(identity, "geometry")
+ this.cancel(identity, "minimize")
+ const geometryAnimation = geometryChanged && !snapshot.minimized && transaction ? localAnimation(++this.revision, transaction) : null
+ const minimizeAnimation = visibilityChanged && transaction ? localAnimation(++this.revision, transaction) : null
+ this.replace(identity, {
+ ...current,
+ title: snapshot.title,
+ position: snapshot.position,
+ size: snapshot.size,
+ minimized: snapshot.minimized,
+ maximized: snapshot.maximized,
+ depth: snapshot.depth,
+ geometryAnimation,
+ minimizeAnimation
})
-
- const targetState = this.presented(target.identity, target.state)
-
return Promise.all([
-
- this.changeGeometry(follower.identity, { position: targetState.position, size: targetState.size }, transaction),
-
- this.changeMinimized(follower.identity, targetState.minimized, transaction)
-
+ this.waitFor(identity, "geometry", geometryAnimation, transaction),
+ this.waitFor(identity, "minimize", minimizeAnimation, transaction)
]).then(() => undefined)
}
- public unfollow(process: string, transaction?: RequestedTransaction) {
-
+ public unfollow(process: string, _transaction?: RequestedTransaction) {
const { identity } = this.existing(process)
- const relation = this.following.get(identity)
-
- if (!relation) return Promise.resolve()
-
this.following.delete(identity)
-
- return Promise.all([
-
- this.changeGeometry(identity, { position: relation.restore.position, size: relation.restore.size }, transaction),
-
- this.changeMinimized(identity, relation.restore.minimized, transaction)
-
- ]).then(() => undefined)
+ return Promise.resolve()
}
public title(process: string, title: string) {
@@ -279,10 +268,10 @@ export default class LocalWindows implements LocalWindowHost {
const client = this.client(process)
if (!client) return
- this.authoritative.set(identity, authoritativeSignature(client))
+ this.authoritative.set(identity, localState(client))
this.following.delete(identity)
+ if (client.window.layer === "window") this.following.set(identity, { target: identity, snapshot: localState(client) })
this.replace(identity, localState(client))
- this.projectFollowers(identity)
}
private existing(process: string) {
@@ -301,59 +290,35 @@ export default class LocalWindows implements LocalWindowHost {
this.publish(next)
}
- private changeGeometry(identity: string, value: WindowGeometry, transaction?: RequestedTransaction, project = true) {
+ private changeGeometry(identity: string, value: WindowGeometry, transaction?: RequestedTransaction) {
const state = this.windows.get(identity)
if (!state) throw new Error("This Client has no local Window representation")
if (JSON.stringify([state.position, state.size]) === JSON.stringify([value.position, value.size])) return Promise.resolve()
+ if (state.minimized || state.maximized) {
+ this.replace(identity, { ...state, position: value.position, size: value.size })
+ return Promise.resolve()
+ }
this.cancel(identity, "geometry")
const animation = transaction ? localAnimation(++this.revision, transaction) : null
this.replace(identity, { ...state, position: value.position, size: value.size, geometryAnimation: animation })
- if (project) this.projectFollowers(identity, transaction)
return this.waitFor(identity, "geometry", animation, transaction)
}
- private changeMinimized(identity: string, minimized: boolean, transaction?: RequestedTransaction, project = true) {
+ private changeMinimized(identity: string, minimized: boolean, transaction?: RequestedTransaction) {
const state = this.windows.get(identity)
if (!state) throw new Error("This Client has no local Window representation")
if (state.minimized === minimized) return Promise.resolve()
this.cancel(identity, "minimize")
+ if (minimized) this.cancel(identity, "geometry", "The local Window was minimized")
const animation = transaction ? localAnimation(++this.revision, transaction) : null
- this.replace(identity, { ...state, minimized, minimizeAnimation: animation })
- if (project) this.projectFollowers(identity, transaction)
+ this.replace(identity, { ...state, minimized, minimizeAnimation: animation, geometryAnimation: minimized ? null : state.geometryAnimation })
return this.waitFor(identity, "minimize", animation, transaction)
}
- private projectFollowers(target: string, transaction?: RequestedTransaction, visited = new Set<string>()) {
-
- if (visited.has(target)) return
- visited.add(target)
-
- const targetState = this.windows.get(target)
- if (!targetState) return
-
- const selected = transaction ? baseTransaction(transaction) : undefined
-
- for (const [identity, relation] of this.following) {
-
- if (relation.target !== target) continue
-
- void this.changeGeometry(identity, { position: targetState.position, size: targetState.size }, selected, false)
- void this.changeMinimized(identity, targetState.minimized, selected, false)
- this.projectFollowers(identity, selected, visited)
- }
- }
-
- private presented(identity: string, state: LocalWindowState) {
-
- const geometry = this.readers.get(identity)?.()
-
- return geometry ? { ...state, position: geometry.position, size: geometry.size } : state
- }
-
private publish(next: ReadonlyMap<string, LocalWindowState>) {
this.windows = next
@@ -390,11 +355,7 @@ interface WaitingAnimation {
interface FollowingWindow {
target: string
- restore: Readonly<{
- position: WindowState["position"]
- size: WindowState["size"]
- minimized: boolean
- }>
+ snapshot: LocalWindowState
}
function animationKey(identity: string, kind: AnimationKind) {
@@ -420,6 +381,7 @@ function localState(client: ClientState): LocalWindowState {
position: window.position,
size: window.size,
minimized: window.minimized,
+ maximized: window.maximized,
front: false,
layer: window.layer,
depth: window.depth,
@@ -429,22 +391,6 @@ function localState(client: ClientState): LocalWindowState {
}
}
-function projectAuthoritative(local: LocalWindowState, client: ClientState, replaceGeometry: boolean): LocalWindowState {
-
- const window = client.window
- return {
- ...local,
- title: window.title,
- position: window.position,
- size: window.size,
- minimized: window.minimized,
- layer: window.layer,
- depth: window.depth,
- geometryAnimation: replaceGeometry ? null : local.geometryAnimation,
- minimizeAnimation: local.minimizeAnimation
- }
-}
-
function windowState(local: LocalWindowState, front: boolean, geometry?: Readonly<{ position: WindowState["position"], size: WindowState["size"] }>): WindowState {
return {
@@ -452,6 +398,7 @@ function windowState(local: LocalWindowState, front: boolean, geometry?: Readonl
position: geometry?.position ?? local.position,
size: geometry?.size ?? local.size,
minimized: local.minimized,
+ maximized: local.maximized,
front,
layer: local.layer,
}
@@ -462,12 +409,6 @@ export type LocalGeometryReader = () => Readonly<{
size: WindowState["size"]
}>
-function authoritativeSignature(client: ClientState) {
-
- const window = client.window
- return JSON.stringify([window.title, window.position, window.size, window.minimized, window.layer, window.depth])
-}
-
function frontmost(windows: ReadonlyMap<string, LocalWindowState>, layer: LocalWindowState["layer"]) {
let best: [string, LocalWindowState] | null = null
@@ -479,48 +420,3 @@ function frontmost(windows: ReadonlyMap<string, LocalWindowState>, layer: LocalW
}
return best?.[0] ?? null
}
-
-function projectFollowing(
- windows: Map<string, LocalWindowState>,
- following: ReadonlyMap<string, FollowingWindow>,
- changed: (identity: string, kind: "geometry" | "minimize") => void
-) {
-
- const projected = new Set<string>()
-
- function project(identity: string, stack = new Set<string>()): LocalWindowState | undefined {
-
- const state = windows.get(identity)
- const relation = following.get(identity)
-
- if (!state || !relation) return state
- if (stack.has(identity)) return state
-
- stack.add(identity)
- const target = project(relation.target, stack)
- stack.delete(identity)
-
- if (!target) return state
-
- const geometryChanged = JSON.stringify([state.position, state.size]) !== JSON.stringify([target.position, target.size])
- const minimizedChanged = state.minimized !== target.minimized
-
- if (geometryChanged) changed(identity, "geometry")
- if (minimizedChanged) changed(identity, "minimize")
-
- const next = {
- ...state,
- position: target.position,
- size: target.size,
- minimized: target.minimized,
- geometryAnimation: geometryChanged ? target.geometryAnimation : state.geometryAnimation,
- minimizeAnimation: minimizedChanged ? target.minimizeAnimation : state.minimizeAnimation
- }
-
- windows.set(identity, next)
- projected.add(identity)
- return next
- }
-
- for (const identity of following.keys()) if (!projected.has(identity)) project(identity)
-}
diff --git a/source/client/view/components/window-manager/window-geometry.ts b/source/client/view/components/window-manager/window-geometry.ts
index c4dc654..0e2e46a 100644
--- a/source/client/view/components/window-manager/window-geometry.ts
+++ b/source/client/view/components/window-manager/window-geometry.ts
@@ -43,12 +43,6 @@ export function absoluteWindowGeometry(position: Position, size: Size) {
return [position.x, position.y, size.width, size.height].every(value => relative(value).relative === 0)
}
-/** Returns whether the geometry exactly fills its containing block. */
-export function wholeWindowGeometry(position: Position, size: Size) {
-
- return equal(position.x, 0, 0) && equal(position.y, 0, 0) && equal(size.width, 1, 0) && equal(size.height, 1, 0)
-}
-
/** Resolves one declarative Window geometry inside a measured surface. */
export function resolveWindowGeometry(position: Position, size: Size, surface: WindowSurfaceSize): WindowRegion {
diff --git a/source/client/view/components/window-manager/window-manager.ts b/source/client/view/components/window-manager/window-manager.ts
index 35fd28e..a2eef3c 100644
--- a/source/client/view/components/window-manager/window-manager.ts
+++ b/source/client/view/components/window-manager/window-manager.ts
@@ -5,7 +5,6 @@ import { Layer } from "@server/core/link-manager/auth-manager/program-manager/co
import { type Position, type Size, type Value } from "@phreshos/core"
import { useCallback, useRef, useState } from "react"
import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"
-import { wholeWindowGeometry } from "./window-geometry"
import LocalWindows from "./local-windows"
/**
@@ -14,8 +13,8 @@ import LocalWindows from "./local-windows"
* whether it is shown — nothing else is consulted.
*
* The local representation and authoritative counterpart are distinct.
- * Ordinary windows project authoritative changes automatically; under and
- * over windows retain their local projection after its initial seed.
+ * Following starts enabled for ordinary windows and disabled for under/over.
+ * Each Client can subsequently follow an authoritative Window or detach.
*
* Departure is representation. The truth drops a stopped client and its
* Window at once; the exit still has to play, so the last desktop-owned
@@ -85,15 +84,6 @@ export default function useWindows(authManager: AuthManager) {
// orders are not one list, and their concatenation is not this.
const [order, setOrder] = useState<string[]>(() => [...initialClients.values()].map(({ identity }) => identity))
- // Where a window was before it was made to fill the surface.
- //
- // The system stopped remembering this when `maximize` stopped being
- // a state: filling the surface is a size like any other now, so
- // nothing there can undo it. The button that offers the undo keeps
- // what it needs to honour it — a ref rather than state, because
- // nothing is drawn from it.
- const filled = useRef(new Map<string, { position: Position, size: Size }>())
-
// Departures are derived at the moment the truth arrives — the same
// event updates both lists in one batch, so no render ever shows a
// window in neither.
@@ -304,33 +294,12 @@ export default function useWindows(authManager: AuthManager) {
}, [commit])
const fill = useCallback(function (process: Process) {
-
const window = process.client?.window
-
if (!window || window.layer !== "window") return
-
- const shown = localWindow.state(process.identity)
-
- const projection = localWindow.projection(process.identity)
-
- const was = filled.current.get(process.identity)
-
- const whole = wholeWindowGeometry(projection.position, projection.size)
-
- if (whole && was) {
-
- filled.current.delete(process.identity)
-
- snap(process, was.position, was.size)
-
- return
- }
-
- filled.current.set(process.identity, { position: shown.position, size: shown.size })
-
- snap(process, { x: "0/1", y: "0/1" }, { width: "1/1", height: "1/1" })
-
- }, [snap])
+ const maximized = !localWindow.projection(process.identity).maximized
+ void localWindow.maximize(process.identity, maximized)
+ commit(window.maximize(maximized))
+ }, [commit])
// Every window on the desktop, in one list and one order.
//
diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsx
index 077424f..6f8ccf4 100644
--- a/source/client/view/structure/desktop/desktop.tsx
+++ b/source/client/view/structure/desktop/desktop.tsx
@@ -149,6 +149,8 @@ export default function Workspace() {
minimized={local.minimized}
+ maximized={local.maximized}
+
closing={closing}
stopping={stopping}
@@ -211,11 +213,11 @@ export default function Workspace() {
record={record}
- title={record.client!.window.title}
+ title={windows.localWindow.projection(record.identity).title}
icon={icon(record)}
- active={!record.client!.window.minimized && fronts.window?.identity === record.identity}
+ active={fronts.window?.identity === record.identity}
onElement={focus.taskbarItem}
diff --git a/source/client/view/structure/desktop/windows/process-window.tsx b/source/client/view/structure/desktop/windows/process-window.tsx
index dd20177..3db2ceb 100644
--- a/source/client/view/structure/desktop/windows/process-window.tsx
+++ b/source/client/view/structure/desktop/windows/process-window.tsx
@@ -17,7 +17,7 @@ const settleDelay = 80
* props so memoization can see which process actually changed even though
* the peer deliberately keeps each Process instance alive and mutates it.
*/
-export default memo(function ({ identity, record, assetId, client, title, icon, position, size, localSurface, geometryAnimation, minimizeAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+export default memo(function ({ identity, record, assetId, client, title, icon, position, size, localSurface, geometryAnimation, minimizeAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, maximized, closing, stopping, entering, bare, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
const activate = useCallback(() => onRaise(record), [onRaise, record])
@@ -116,6 +116,8 @@ export default memo(function ({ identity, record, assetId, client, title, icon,
minimized={minimized}
+ maximized={maximized}
+
closing={closing}
stopping={stopping}
@@ -228,6 +230,8 @@ interface ProcessWindowProps {
minimized: boolean
+ maximized: boolean
+
closing: boolean
stopping: boolean
diff --git a/source/client/view/structure/desktop/windows/window-geometry-motion.ts b/source/client/view/structure/desktop/windows/window-geometry-motion.ts
index bee4e0f..20c6718 100644
--- a/source/client/view/structure/desktop/windows/window-geometry-motion.ts
+++ b/source/client/view/structure/desktop/windows/window-geometry-motion.ts
@@ -74,11 +74,16 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
const options = motionTransition(transaction)
+ let remaining = 4
+ const completed = () => {
+ if (--remaining === 0) complete?.()
+ }
+ const timing = { ...options, onComplete: completed }
controls.current = [
- animate(x, region.x, { ...options, onComplete: complete }),
- animate(y, region.y, options),
- animate(width, region.width, options),
- animate(height, region.height, options)
+ animate(x, region.x, timing),
+ animate(y, region.y, timing),
+ animate(width, region.width, timing),
+ animate(height, region.height, timing)
]
}
@@ -107,7 +112,10 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
return
}
- if (target.current && sameRegion(target.current, region)) return
+ if (target.current && sameRegion(target.current, region) && sameRegion(read(), region)) {
+ if (revision !== undefined) onComplete?.(revision)
+ return
+ }
transition(region, animation?.transaction, revision === undefined ? undefined : () => onComplete?.(revision))
diff --git a/source/client/view/structure/desktop/windows/window.tsx b/source/client/view/structure/desktop/windows/window.tsx
index 9dcff1d..bd20c93 100644
--- a/source/client/view/structure/desktop/windows/window.tsx
+++ b/source/client/view/structure/desktop/windows/window.tsx
@@ -2,7 +2,7 @@ import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useEffect
import { useReducedMotion } from "@libs/react-motion"
import { surfacePresencePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
import WindowPanel from "./window-panel"
-import { absoluteWindowGeometry, resolveWindowGeometry, wholeWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"
+import { absoluteWindowGeometry, resolveWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"
import { type Position, type Size } from "@phreshos/core"
import WindowHeader from "./window-header"
import WindowSurface from "./window-surface"
@@ -53,16 +53,22 @@ const surfacePose = {
closing: { scale: 0.86, y: 12, opacity: 0 }
}
-export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onLocalAnimationComplete, onLocalRepresentation, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, localSurface, geometryAnimation, minimizeAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
+export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onLocalAnimationComplete, onLocalRepresentation, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, maximized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, localSurface, geometryAnimation, minimizeAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
const reducedMotion = useReducedMotion()
const appearanceTransaction = useAppearance().transaction
+ // Hidden windows retain their last presentation while lower-priority state changes.
+ const presented = useRef({ position, size })
+ if (!minimized) presented.current = maximized
+ ? { position: { x: "0%", y: "0%" }, size: { width: "100%", height: "100%" } }
+ : { position, size }
+
const geometryMotion = useWindowGeometryMotion({
- position,
- size,
+ position: presented.current.position,
+ size: presented.current.size,
animation: geometryAnimation,
- immediate: bare || reducedMotion,
+ immediate: reducedMotion || (bare && !geometryAnimation),
onComplete: revision => onLocalAnimationComplete?.("geometry", revision)
})
@@ -102,13 +108,9 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
}
// A window is absolute when none of its expressions depends on the surface.
- const absolute = absoluteWindowGeometry(position, size)
+ const absolute = absoluteWindowGeometry(presented.current.position, presented.current.size)
- // Whether it is filling the surface — read off the geometry, for
- // this button's own label and nothing else. The system has no such
- // state any more: filling the surface is a size like any other, and
- // this is the interface recognising a size it offered to set.
- const whole = wholeWindowGeometry(position, size)
+ const whole = maximized
const [presenceHidden, setPresenceHidden] = useState(minimized)
@@ -144,7 +146,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
const revision = minimizeAnimation?.revision
- if (!bare || revision === undefined || minimizeTransaction && !reducedMotion) return
+ if (revision === undefined || minimizeTransaction && !reducedMotion) return
onLocalAnimationComplete?.("minimize", revision)
@@ -176,7 +178,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
const revision = minimizeAnimation?.revision
- if (bare && revision !== undefined && minimizeTransaction && !reducedMotion) {
+ if (revision !== undefined && minimizeTransaction && !reducedMotion) {
onLocalAnimationComplete?.("minimize", revision)
}
@@ -184,6 +186,8 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
function grab(event: ReactPointerEvent<HTMLElement>, edge: WindowEdge | null) {
+ if (maximized && edge !== null) return
+
// A cancelled pointerdown suppresses double-click synthesis, and
// a shared window restores by double-click; absolute ones keep
// it to block native drags.
@@ -290,6 +294,12 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
const ratio = Math.min(Math.max((pointerX - origin.x) / origin.width, 0), 1)
+ if (maximized) {
+ const stored = resolveWindowGeometry(position, size, bounds)
+ origin = { ...origin, width: stored.width, height: stored.height }
+ onMaximize?.()
+ }
+
origin = { x: pointerX - origin.width * ratio, y: pointerY - Math.min(Math.max(pointerY - origin.y, 0), 40), width: origin.width, height: origin.height }
current = { ...origin }
@@ -407,7 +417,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
// ------------------------------------------------------------ render
- const paintedInsets = windowPaintInsets(position, size, paintSurfaceSize, windowPaintInset, gesture?.current)
+ const paintedInsets = windowPaintInsets(presented.current.position, presented.current.size, paintSurfaceSize, windowPaintInset, gesture?.current)
return <>
@@ -574,6 +584,8 @@ interface WindowProps extends Omit<ComponentProps<"div">, "onAnimationStart" | "
minimized?: boolean
+ maximized?: boolean
+
// Whether mounting this element represents a newly opened window.
animateEntrance?: boolean
diff --git a/source/server/core/appearance-manager.ts b/source/server/core/appearance-manager.ts
index 2442f32..dbec79a 100644
--- a/source/server/core/appearance-manager.ts
+++ b/source/server/core/appearance-manager.ts
@@ -1,75 +1,11 @@
-import { extname } from "node:path"
import Keyv from "keyv"
-import { z } from "zod"
-import {
- appearanceLimits,
- createAppearanceSnapshot,
- defaultAppearance,
- type Appearance,
- type AppearanceRange
-} from "@phreshos/core"
+import { extname } from "node:path"
+import { defaultAppearance, parseAppearance, type Appearance } from "@phreshos/core"
import UploadManager from "./upload-manager"
-const servedFileSchema = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/)
-const wallpaperSchema = servedFileSchema.nullable()
-const wallpaperExtensions = new Set(["avif", "bmp", "gif", "jpeg", "jpg", "png", "svg", "webp"])
-
-const materialSchema = z.strictObject({
- grain: bounded(appearanceLimits.material.grain),
- grainAmount: bounded(appearanceLimits.material.grainAmount),
- backdrop: bounded(appearanceLimits.material.backdrop),
- opacity: bounded(appearanceLimits.material.opacity),
- distortion: bounded(appearanceLimits.material.distortion),
- saturation: bounded(appearanceLimits.material.saturation)
-})
-
-const shadowSchema = z.strictObject({
- x: bounded(appearanceLimits.shadow.x),
- y: bounded(appearanceLimits.shadow.y),
- blur: bounded(appearanceLimits.shadow.blur),
- spread: bounded(appearanceLimits.shadow.spread),
- opacity: bounded(appearanceLimits.shadow.opacity)
-})
-
-const easingSchema = z.union([
- z.enum(["linear", "ease", "ease-in", "ease-out", "ease-in-out"]),
- z.tuple([
- z.number().min(0).max(1),
- z.number(),
- z.number().min(0).max(1),
- z.number()
- ])
-])
-
-const transactionSchema = z.strictObject({
- duration: bounded(appearanceLimits.transaction.duration),
- easing: easingSchema
-})
-
-const colorsSchema = z.strictObject({
- background: z.string().min(1),
- foreground: z.string().min(1),
- primary: z.string().min(1),
- secondary: z.string().min(1),
- success: z.string().min(1),
- warning: z.string().min(1),
- danger: z.string().min(1),
- info: z.string().min(1)
-})
-
-/** The sole schema for authoritative System Appearance state. */
-export const appearanceSchema: z.ZodType<Appearance> = z.strictObject({
- colors: themed(colorsSchema),
- spacing: bounded(appearanceLimits.spacing),
- radius: bounded(appearanceLimits.radius),
- shadow: themed(shadowSchema),
- material: themed(materialSchema),
- transaction: transactionSchema,
- signInWallpaper: themed(wallpaperSchema),
- desktopWallpaper: themed(wallpaperSchema)
-})
-
const storageKey = "appearance"
+const servedFile = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/
+const wallpaperExtensions = new Set(["avif", "bmp", "gif", "jpeg", "jpg", "png", "svg", "webp"])
/** Durable, complete Appearance state owned by Server Core. */
export default class AppearanceManager {
@@ -81,7 +17,7 @@ export default class AppearanceManager {
public static async open(store: Keyv, uploads: UploadManager) {
const stored = await store.get(storageKey)
- const appearance = createAppearanceSnapshot(appearanceSchema.parse(stored ?? defaultAppearance))
+ const appearance = parseAppearance(stored ?? defaultAppearance)
if (stored === undefined) await store.set(storageKey, appearance)
@@ -91,7 +27,7 @@ export default class AppearanceManager {
public get value() { return this.current }
public async update(value: unknown) {
- const appearance = createAppearanceSnapshot(appearanceSchema.parse(value))
+ const appearance = parseAppearance(value)
this.validateWallpaper(appearance.signInWallpaper.light)
this.validateWallpaper(appearance.signInWallpaper.dark)
@@ -106,15 +42,8 @@ export default class AppearanceManager {
private validateWallpaper(file: string | null) {
if (file === null) return
+ if (!servedFile.test(file)) throw new Error("A wallpaper must be a system upload")
if (!wallpaperExtensions.has(extname(file).slice(1))) throw new Error("A wallpaper must be an image file")
if (!this.uploads.stat(file)) throw new Error("The wallpaper upload does not exist")
}
}
-
-function themed<Schema extends z.ZodType>(schema: Schema) {
- return z.strictObject({ light: schema, dark: schema })
-}
-
-function bounded(range: AppearanceRange) {
- return z.number().min(range.minimum).max(range.maximum)
-}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
index 959984e..94cb196 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
@@ -1,10 +1,8 @@
+import type { EndpointReference as CoreEndpointReference, ProcessSnapshot } from "@phreshos/core"
import { type Half } from "./process-traffic"
-import Process, { type ProcessRecord } from "./process"
+import Process from "./process"
-export type ProcessReference = Omit<ProcessRecord, "program"> & Readonly<{
-
- program: ReturnType<Process["program"]["record"]>
-}>
+export type ProcessReference = ProcessSnapshot
/**
* An endpoint identity carried only between trusted boundaries and SDKs.
@@ -13,12 +11,7 @@ export type ProcessReference = Omit<ProcessRecord, "program"> & Readonly<{
* Program code can therefore receive a real Endpoint handle without being
* able to forge the sender or destination attached to application traffic.
*/
-export interface EndpointReference {
-
- readonly kind: Half
-
- readonly process: ProcessReference
-}
+export type EndpointReference = CoreEndpointReference
export function processReference(process: Process): ProcessReference {
@@ -27,5 +20,5 @@ export function processReference(process: Process): ProcessReference {
export function endpointReference(process: Process, kind: Half): EndpointReference {
- return { kind, process: processReference(process) }
+ return { kind, process: processReference(process) } satisfies CoreEndpointReference
}
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 9f0dee6..f133526 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
@@ -29,7 +29,8 @@ import {
type ServerLaunch,
type ServiceKey,
type WindowGeometry,
- type WindowLayer
+ type WindowLayer,
+ type WindowState
} from "@phreshos/core"
import type { ServerRuntime } from "@server/core/server-runtime"
import { permissionCatalog } from "@server/core/permissions"
@@ -157,7 +158,7 @@ export default class ProcessManager extends TheLink {
private get system() { return this.authManager.linkManager.application.system }
/** Complete public Window state, shared by every representation. */
- public windowSnapshot(identity: string) {
+ public windowSnapshot(identity: string): WindowState {
const process = this.find(identity)
const window = this.windowOf(identity)
@@ -167,6 +168,7 @@ export default class ProcessManager extends TheLink {
position: window.position,
size: window.size,
minimized: window.minimized,
+ maximized: window.maximized,
front: this.front(window.layer) === process.identity,
layer: window.layer
})
@@ -902,7 +904,7 @@ export default class ProcessManager extends TheLink {
const shown = { title: shape.title, layer: shape.layer }
- return new Window(shown, shape.position, shape.size, ++this.highest, shape.minimize)
+ return new Window(shown, shape.position, shape.size, ++this.highest, shape.minimize, shape.maximize)
}
public async register(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, runtime: ServerRuntime | null, client: boolean, shape: Shape | null, parent: Process | null, registration?: ProcessRegistration) {
@@ -945,14 +947,7 @@ export default class ProcessManager extends TheLink {
this.hostTraffic,
- permissionCatalog.granted(permissionCatalog.effective(
-
- "all",
-
- program.clientPermissions.all ?? null,
-
- this.authManager.programManager.permission(program, "all")
- ))
+ permissionCatalog.granted(this.authManager.programManager.permission(program, "all"))
)
this.processes.set(identity, process)
@@ -1540,7 +1535,7 @@ export default class ProcessManager extends TheLink {
return this.authManager.programManager.grantsStorage(process.program, path, operation)
}
- /** Resolves one permission request through declarations, grants, then the owner. */
+ /** Requests owner approval and replaces the authoritative stored permission. */
public async requestPermission<Name extends PermissionName>(
identity: string,
request: string,
@@ -1556,19 +1551,11 @@ export default class ProcessManager extends TheLink {
if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")
- if (this.authManager.programManager.grantsPermission(process.program, name, requested)) return requested
-
- const stored = this.authManager.programManager.permission(process.program, name)
- const effective = this.authManager.programManager.effectivePermission(process.program, name, stored)
-
- if (effective === false) return false
-
const choice = await this.authManager.dialogManager.requestPermission(process, request, name, requested)
if (choice === true) {
- const permission = permissionCatalog.merge(name, this.authManager.programManager.permission(process.program, name), requested)
- await this.authManager.programManager.setPermission(process.program, name, permission)
+ await this.authManager.programManager.setPermission(process.program, name, requested)
return requested
}
@@ -1579,7 +1566,7 @@ export default class ProcessManager extends TheLink {
/** Keeps each live Client's iframe access policy aligned with its Program. */
public async updateClientAccess(program: Program) {
- const sameOrigin = permissionCatalog.granted(this.authManager.programManager.effectivePermission(program, "all"))
+ const sameOrigin = permissionCatalog.granted(this.authManager.programManager.permission(program, "all"))
for (const process of this.processes.values()) {
@@ -2000,6 +1987,13 @@ export default class ProcessManager extends TheLink {
return [target.identity]
}
+ if (word === "maximize") {
+
+ const target = this.heldWindow(rest[0], process).process
+ await this.system.maximizeWindow(target, rest[1] !== false)
+ return [target.identity]
+ }
+
if (word === "minimize") {
const target = this.heldWindow(rest[0], process).process
@@ -2639,9 +2633,20 @@ export default class ProcessManager extends TheLink {
// Shown, or not shown. Nothing else: the order is untouched, so a
// window hidden and shown again comes back exactly where it was in
// its layer rather than on top of it.
+ @Connect("/maximize")
+ public async maximize(identity: string, maximized: boolean) {
+
+ if (typeof maximized !== "boolean") throw new Error("Window maximize takes a boolean state")
+ const window = this.mutableWindowOf(identity)
+ window.maximized = maximized
+ this.said(identity, "maximize", maximized)
+ return { identity, window }
+ }
+
@Connect("/minimize")
public async minimize(identity: string, minimized: boolean) {
+ if (typeof minimized !== "boolean") throw new Error("Window minimize takes a boolean state")
const window = this.mutableWindowOf(identity)
const front = this.front(window.layer)
@@ -2832,6 +2837,8 @@ interface ShapeBase {
size: Size
minimize: boolean
+
+ maximize: boolean
}
export interface StandardShape extends ShapeBase {
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.ts
index a2cd64a..04ca633 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
@@ -385,6 +385,7 @@ export interface ProcessLaunch {
layer: Layer
minimize: boolean
+ maximize: boolean
service: boolean
}> | null
diff --git a/source/server/core/link-manager/auth-manager/process-manager/window.ts b/source/server/core/link-manager/auth-manager/process-manager/window.ts
index 1c0ab1d..c3fd32d 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/window.ts
@@ -1,41 +1,6 @@
-import { isRelativeValue, type Position, type Size, type Value, type WindowGeometry, type WindowLayer } from "@phreshos/core"
-
-/**
- * How a process is shown. Every value is either a number of pixels or a
- * linear expression of workspace-relative and pixel terms — so a window can
- * be absolute in one axis and relative in the other, and arrangements no
- * vocabulary anticipated (a third-width sidebar, a full-width dock sixty
- * pixels tall) are simply values.
- *
- * A share is resolved by each client in its own layer workspace. Margins
- * and gutters are presentation outside this value, so pixels and shares
- * use one coordinate space and neither carries desktop arithmetic.
- *
- * **Geometry, visibility and order are three questions**, and no word
- * here answers two of them. A hidden window can be moved, resized and
- * reordered, and none of that shows it; showing it shows it wherever it
- * now is and wherever the order now puts it. There is nothing to
- * remember and nothing to restore, which is why the two `previous`
- * fields are gone: they existed to undo `maximize`, and filling the
- * surface is a size like any other now.
- *
- * **What is shown lives here, not on the process.** A title is "how this
- * is shown", the same kind of fact as a size — and `client.size` already
- * becomes `window.size`, so `title` becomes `window.title` by the same
- * road. A process with no window needs none of them, and had to carry them
- * all while they sat on the process.
- *
- * The title is the window's own from the moment it opens: born from what
- * the client half declared, or the program's name when it declared
- * nothing, and changeable afterwards.
- *
- * **Front is not kept here.** Which window is at the front is a fact about
- * all of them at once — the un-minimized one with the greatest depth —
- * so it is answered where every window is in view, and a flag stored
- * per window could disagree with what is drawn. `depth` is how that is
- * worked out and stays the host's: a number a program could read but
- * never interpret is a mechanism leaking through the contract.
- */
+import { isRelativeValue, type Position, type Size, type Value, type WindowGeometry, type WindowLayer, type WindowState } from "@phreshos/core"
+
+/** Authoritative geometry, visibility, maximization, title, and layer ordering. */
// What a Window says about the Program behind it. Resolved when the Process
// first gains Window state and again only when a stopped client is restarted
// with explicit overrides; ordinary live Window operations remain narrower.
@@ -48,7 +13,7 @@ export interface Shown {
}
-export default class Window {
+export default class Window implements Omit<WindowState, "front"> {
public position: Position
@@ -61,6 +26,8 @@ export default class Window {
// first frame is not the same as shown once and then hidden.
public minimized: boolean
+ public maximized: boolean
+
// What a person reads on it. Born from the program, the window's
// own afterwards.
public title: string
@@ -68,7 +35,7 @@ export default class Window {
// The Window's authoritative Desktop layer.
public readonly layer: WindowLayer
- public constructor(shown: Shown, position: Position, size: Size, depth: number, minimized: boolean) {
+ public constructor(shown: Shown, position: Position, size: Size, depth: number, minimized: boolean, maximized = false) {
this.title = shown.title
@@ -89,23 +56,10 @@ export default class Window {
this.depth = depth
this.minimized = minimized
+
+ this.maximized = maximized
}
- // ── The primitives, and each does only its own work ──────────────
- //
- // Geometry, visibility and order are three questions, and no word
- // here answers two of them. A window that is moved while hidden is
- // moved; showing it again shows it where it now is, because nothing
- // was remembered to put it back to. Raising a hidden window changes
- // where it will appear, not whether it appears.
- //
- // Filling the surface used to be an act with a name, and a name
- // needed a memory: `previousPosition` and `previousSize` existed to
- // undo `maximize` and were read by nothing else. Both are gone. A
- // window that wants the whole surface asks for the whole surface —
- // and the button that does it in the interface keeps its own memory
- // of where the window was, which is the window manager's business
- // and not the system's.
public move(position: Position) {
validate(position.x, "x")
@@ -163,7 +117,9 @@ export default class Window {
depth: this.depth,
- minimized: this.minimized
+ minimized: this.minimized,
+
+ maximized: this.maximized
}
}
}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/config.ts b/source/server/core/link-manager/auth-manager/program-manager/config.ts
index deb124a..166507c 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/config.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/config.ts
@@ -1,148 +1,23 @@
-import { type ClientPermissionDeclarations, type Layer, type Position, type Size } from "@phreshos/core"
+import type { ClientDefinition, ProgramDefinition, ServerDefinition } from "@phreshos/core"
/**
- * What a program says it is.
+ * A Program definition as stored in `program.json`.
*
- * A definition, and nothing that acts. It arrives either as a
- * `program.json` beside the things it names, or as an object built in
- * code — a program the system owns has no file to be read from.
- *
- * The union is the contract's one hard rule wearing a type: a program
- * has a server half, a client half, or both, and a definition with
- * neither cannot be written down.
+ * Creation consumes Core's exact `ProgramDefinition`. Installation removes
+ * `storage`, because the System then owns the Program's canonical storage
+ * location. This is the only difference in the durable representation.
*/
-export type ProgramConfig = (ProgramConfigBase & { server: ServerConfig, client?: ClientConfig }) | (ProgramConfigBase & { server?: ServerConfig, client: ClientConfig })
-
-interface ProgramConfigBase {
-
- // What addresses it. Kebab-case, because it is also the name of the
- // directory the system lays the program out in — so it is a path
- // component, and every path component from outside is checked.
- //
- // Never shown. What a person reads is `name`, and keeping the two
- // apart is what every operating system does — an identifier that is
- // also a label ends up being one or the other badly.
- identity: string
-
- // What a person reads. Free-form, addresses nothing, and absent
- // means the identity serves for both.
- name?: string
-
- version?: string
-
- description?: string
-
- // One PNG source from which hosting derives every standard size. How a
- // Program is shown belongs to the Program rather than its client half — a
- // headless Program is shown too.
- icon?: string
-
- // Program-specific operating knowledge for agents. Any source path is
- // accepted here; installation canonicalizes it to agent.md.
- agent?: string
-
- // Optional public catalog information. These values describe a release;
- // they do not affect whether or how the Program runs.
- categories?: string[]
-
- keywords?: string[]
-
- website?: string
-
- // Where it keeps what it keeps. Absent means the system decides.
- storage?: string
-}
-
-interface ServerConfigBase {
-
- // Where this half is. Empty names the program's own root.
- location: string
-
- // Whether a Process starts this endpoint by default. True when omitted.
- start?: boolean
-
- // Default service role for each new Server incarnation. False when omitted.
- service?: boolean
-
- // Run once before the program is first started, in that directory.
- installCommand?: string
-
- // Run while uninstalling, before the installed files are removed.
- uninstallCommand?: string
-
-}
+export type ProgramConfig = ProgramDefinition extends infer Definition
+ ? Definition extends ProgramDefinition
+ ? Omit<Definition, "storage"> & Readonly<{ storage?: string }>
+ : never
+ : never
-export type ServerConfig = ServerConfigBase & ({
-
- // Run an isolated operating-system process through the shell.
- startCommand: string
-
- entryFile?: never
-
-} | {
-
- startCommand?: never
-
- // Load this module as a worker owned by the System.
- entryFile: string
-})
-
-export interface ClientConfig {
-
- // Where this half is: a directory holding index.html, or a URL.
- // Empty names the program's own root. Not `path`, because a path cannot
- // be a URL; one field accepts both readings so a program under development
- // can be framed from a live dev server.
- location: string
-
- // Whether a Process starts this endpoint by default. True when omitted.
- start?: boolean
-
- // Default service role for each new Client incarnation. False when omitted.
- service?: boolean
-
- // What its window is called when it opens. The window owns its title
- // from then on and may change it; this is what it is born with, so
- // there is no moment of showing the wrong thing while the half
- // starts. Absent means the program's own name.
- title?: string
-
- // How its window opens. Absent means the system decides.
- size?: Size
-
- position?: Position
-
- // Which of the desktop's three layers its window lives in, and so
- // whether it is a window at all.
- //
- // `window` is one: in the taskbar, wearing the system's chrome,
- // focused by a click before the click reaches the program. The other
- // two are not — no taskbar entry, no paint of any kind, no controls,
- // and no click-catcher — so a program's own content is the whole of
- // what is on the screen. `under` sits below every window and can
- // never rise above one; `over` sits above every window and none can
- // rise above it. The taskbar is above all three.
- //
- // Absent means `window`, said as an absence rather than written down
- // twice: what a definition leaves unsaid, the system decides.
- layer?: Layer
-
- // Whether its window opens hidden. Absent means shown.
- //
- // A state at birth rather than an act to perform afterwards: a
- // program that opens hidden and shows itself when it is ready has
- // nothing to undo, where one that opens shown and hides itself has
- // already been seen.
- minimize?: boolean
-
- // Initial grants fixed for this Program entity. Process launches cannot
- // add to or replace them.
- permissions?: ClientPermissionDeclarations
-}
+export type ServerConfig = ServerDefinition
+export type ClientConfig = ClientDefinition
export { layers, type Layer, type Position, type Size, type Value } from "@phreshos/core"
+export { isRelativeValue as isValue } from "@phreshos/core"
-// An identity is a directory's name before it is anything else.
+/** Stable Program identities are also safe directory names. */
export const kebab = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
-
-export { isRelativeValue as isValue } from "@phreshos/core"
diff --git a/source/server/core/link-manager/auth-manager/program-manager/entry.ts b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
index 7cb203f..d531a7a 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/entry.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
@@ -1,4 +1,5 @@
import Program from "./program"
+import type { ProgramSnapshot } from "@phreshos/core"
/**
* One program in the runtime registry. Installation is a state of this
@@ -37,7 +38,7 @@ export default class Entry {
...this.program.record(),
installed: this.installed
- }
+ } satisfies ProgramSnapshot
}
public toJSON() {
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.ts
index a4d55bf..0cf8616 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/permissions.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/permissions.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
+import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs"
import { randomUUID } from "node:crypto"
import { join } from "node:path"
import type Program from "./program"
@@ -7,7 +7,28 @@ import type { Permissions } from "@phreshos/core"
const file = "permissions.json"
-/** Reads one Program's system-managed persistent user grants. */
+/** Replaces runtime permission state with this installation's declaration. */
+export function installPermissions(program: Program) {
+
+ const directory = program.storagePath
+ const path = join(directory, file)
+ const directoryExisted = existsSync(directory)
+ const previous = existsSync(path) ? readFileSync(path) : null
+
+ writePermissions(program, program.installationPermissions)
+
+ return function rollbackPermissionInstallation() {
+
+ if (previous === null) rmSync(path, { force: true })
+ else atomicWrite(directory, path, previous)
+
+ if (!directoryExisted && existsSync(directory) && readdirSync(directory).length === 0) {
+ rmSync(directory, { recursive: true, force: true })
+ }
+ }
+}
+
+/** Reads one Program's authoritative permission state. */
export function readPermissions(program: Program): Permissions {
const path = join(program.storagePath, file)
@@ -24,17 +45,23 @@ export function readPermissions(program: Program): Permissions {
}
}
-/** Atomically replaces one Program's persistent user grants. */
+/** Atomically replaces one Program's authoritative permission state. */
export function writePermissions(program: Program, permissions: Permissions) {
- mkdirSync(program.storagePath, { recursive: true })
+ 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) {
- const path = join(program.storagePath, file)
- const temporary = join(program.storagePath, `.${file}.${randomUUID()}`)
+ mkdirSync(directory, { recursive: true })
+
+ const temporary = join(directory, `.${file}.${randomUUID()}`)
try {
- writeFileSync(temporary, `${JSON.stringify(permissions, null, 2)}\n`)
+ 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.ts
index e957537..749282c 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
@@ -10,8 +10,8 @@ import AuthManager from "../auth-manager"
import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
-import { isValue, layers, type ProgramConfig } from "./config"
-import { type ClientLaunch, type Launch, type ProgramCommandChunk } from "@phreshos/core"
+import { isValue, layers } from "./config"
+import { parseProgramDefinition, type ClientLaunch, type Launch, type ProgramCommandChunk, type ProgramDefinition } from "@phreshos/core"
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
import { type StandardShape } from "../process-manager/process-manager"
import Program, { type CommandOutput, type InstallOutput } from "./program"
@@ -20,7 +20,7 @@ import Keyv from "keyv"
import { isIconSize, ProgramIcons } from "./icon"
import { readStartup, removeStartup, writeStartup } from "./startup"
import { permissionCatalog } from "@server/core/permissions"
-import { readPermissions, writePermissions } from "./permissions"
+import { installPermissions, readPermissions, writePermissions } from "./permissions"
import {
parsePermissionName,
type Permission,
@@ -158,13 +158,13 @@ export default class ProgramManager extends TheLink {
return entry
}
- /** Reads one Program's stored user grant without deriving effective access. */
+ /** Reads one Program's authoritative value for an exact permission. */
public permission<Name extends PermissionName>(program: Program, name: Name): Permission<Name> {
return clonePermission(readPermissions(program)[name] ?? null)
}
- /** Returns an independent snapshot of one Program's stored user grants. */
+ /** Returns an independent snapshot of one Program's permission state. */
public permissions(program: Program): Permissions {
return clonePermissions(readPermissions(program))
@@ -190,17 +190,7 @@ export default class ProgramManager extends TheLink {
)
}
- /** Resolves one permission from this Program's declaration and stored value. */
- public effectivePermission<Name extends PermissionName>(
- program: Program,
- name: Name,
- stored = this.permission(program, name)
- ) {
-
- return permissionCatalog.effective(name, program.clientPermissions[name] ?? null, stored)
- }
-
- /** Tests one request against this Program's complete effective authority. */
+ /** Tests one request against this Program's authoritative stored permission. */
public grantsPermission<Name extends PermissionName>(
program: Program,
name: Name,
@@ -210,8 +200,6 @@ export default class ProgramManager extends TheLink {
return permissionCatalog.allows(
name,
requested,
- { programs: [program.identity] },
- program.clientPermissions,
readPermissions(program)
)
}
@@ -220,14 +208,14 @@ export default class ProgramManager extends TheLink {
public grantsStorage(program: Program, path: string, operation?: "read" | "write" | "delete") {
return permissionCatalog.allowsStorage(
- this.effectivePermission(program, "all"),
- this.effectivePermission(program, "storage"),
+ this.permission(program, "all"),
+ this.permission(program, "storage"),
path,
operation
)
}
- /** Stores one canonical user grant and propagates its effective access change. */
+ /** Stores one canonical permission and propagates its access change. */
public async setPermission<Name extends PermissionName>(
program: Program,
name: Name,
@@ -247,7 +235,7 @@ export default class ProgramManager extends TheLink {
}
}
- /** Removes one stored user grant without changing Program declarations. */
+ /** Removes one permission assignment from authoritative state. */
public async deletePermission<Name extends PermissionName>(program: Program, name: Name): Promise<void> {
const permissions = readPermissions(program)
@@ -292,13 +280,13 @@ export default class ProgramManager extends TheLink {
}
@Connect("/create-program")
- protected async createProgram(source: ProgramConfig | string) {
+ protected async createProgram(source: ProgramDefinition | string) {
return (await this.create(source)).identity
}
@Connect("/force-create-program")
- protected async forceCreateProgram(source: ProgramConfig | string, asker: string) {
+ protected async forceCreateProgram(source: ProgramDefinition | string, asker: string) {
return (await this.forceCreate(source, asker)).identity
}
@@ -351,7 +339,7 @@ export default class ProgramManager extends TheLink {
// into a repository through exactly that resolution. A path form
// resolves against the program.json it names, so it only has to be
// absolute itself.
- public async create(source: ProgramConfig | string) {
+ public async create(source: ProgramDefinition | string) {
const entry = await this.register(this.runtimeProgram(source), false)
@@ -361,7 +349,7 @@ export default class ProgramManager extends TheLink {
}
/** Atomically replace the runtime occupant of one Program identity. */
- public async forceCreate(source: ProgramConfig | string, asker: string | null = null) {
+ public async forceCreate(source: ProgramDefinition | string, asker: string | null = null) {
const program = this.runtimeProgram(source)
@@ -401,7 +389,7 @@ export default class ProgramManager extends TheLink {
}
/** Resolve one external runtime source without consulting System cwd. */
- private runtimeProgram(source: ProgramConfig | string) {
+ private runtimeProgram(source: ProgramDefinition | string) {
if (typeof source === "string") {
@@ -412,24 +400,26 @@ export default class ProgramManager extends TheLink {
return new Program(path)
}
+ const definition = parseProgramDefinition(source)
+
// Storage is where what it keeps outlives its processes, and
// "absent means the system decides" is an installed program's
// deal — the system has no directory to decide for a program it
// is not holding on disk.
- if (typeof source.storage !== "string") throw new Error("A created program names its storage")
+ if (typeof definition.storage !== "string") throw new Error("A created program names its storage")
- for (const [what, place] of [["storage", source.storage], ["icon", source.icon], ["agent", source.agent], ["server", source.server?.location]] as const) {
+ for (const [what, place] of [["storage", definition.storage], ["icon", definition.icon], ["agent", definition.agent], ["server", definition.server?.location]] as const) {
if (place === undefined) continue
if (!isAbsolute(place)) throw new Error(`A created program's ${what} must be an absolute filesystem path`)
}
- const client = source.client?.location
+ const client = definition.client?.location
if (client !== undefined && !/^https?:\/\//i.test(client) && !isAbsolute(client)) throw new Error("A created program's client must be an absolute filesystem path or an HTTP(S) URL")
- return new Program(source)
+ return new Program(definition)
}
public async fork(program: Program, identity: string) {
@@ -1006,6 +996,8 @@ export default class ProgramManager extends TheLink {
let createdHere = false
+ let restorePermissions: (() => void) | null = null
+
try {
copyProgram(source, staged)
@@ -1042,6 +1034,10 @@ export default class ProgramManager extends TheLink {
// the registry claims the install succeeded.
await installed.installServer(output)
+ // Installation establishes the only permission source of
+ // truth. Reinstalling deliberately replaces prior owner edits.
+ restorePermissions = installPermissions(installed)
+
let entry = this.programs.get(source.identity)
if (entry) {
@@ -1062,6 +1058,8 @@ export default class ProgramManager extends TheLink {
committed = true
+ restorePermissions = null
+
if (createdHere) await this.created(entry)
await this.authManager.processManager.announceHost("program", "install", entry.identity, entry)
@@ -1078,11 +1076,13 @@ export default class ProgramManager extends TheLink {
catch (exception) {
- // Restore the prior program files after any failure in
- // the swap or install command. Storage never entered the
- // transaction and is therefore neither copied nor moved.
+ // Restore the prior program files and permission source after
+ // any failure in the swap or install command. Other storage
+ // never enters the transaction and is neither copied nor moved.
if (swapping && !committed) {
+ restorePermissions?.()
+
for (const what of installedParts) rmSync(join(home, what), { recursive: true, force: true })
for (const what of readdirSync(backup)) renameSync(join(backup, what), join(home, what))
@@ -1447,6 +1447,8 @@ export default class ProgramManager extends TheLink {
if (asked.minimize !== undefined && typeof asked.minimize !== "boolean") throw new Error("A launch client's minimize state must be true or false")
+ if (asked.maximize !== undefined && typeof asked.maximize !== "boolean") throw new Error("A launch client's maximize state must be true or false")
+
const shift = this.authManager.processManager.processes.size % 8 * 32
return {
@@ -1459,7 +1461,9 @@ export default class ProgramManager extends TheLink {
layer: asked.layer ?? client.layer ?? "window",
- minimize: asked.minimize ?? client.minimize ?? false
+ minimize: asked.minimize ?? client.minimize ?? false,
+
+ maximize: asked.maximize ?? client.maximize ?? false
}
}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.ts
index 63a6fb9..d3f7005 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
@@ -3,10 +3,9 @@ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"
import { dirname, isAbsolute, normalize, relative, resolve, sep } from "node:path"
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
-import { isDeepStrictEqual } from "node:util"
import { validateIcon } from "./icon"
-import type { ClientPermissions, ProgramCommandChunk } from "@phreshos/core"
-import { permissionCatalog } from "@server/core/permissions"
+import { parseProgramDefinition, type ProgramCommandChunk, type ProgramSnapshot } from "@phreshos/core"
+import { permissionCatalog, type DeclaredPermissions } from "@server/core/permissions"
/**
* A program: a description, and the things it names.
@@ -46,16 +45,12 @@ export default class Program {
public config: ProgramConfig
- public readonly clientPermissions: ClientPermissions
-
public constructor(source: string | ProgramConfig, root?: string) {
const [config, where] = typeof source === "string" ? read(source) : [source, process.cwd()]
this.config = coherent(config)
- this.clientPermissions = permissionCatalog.declarations(this.config.client?.permissions)
-
this.identity = this.config.identity
// Given only when a program is made from another: the same
@@ -79,8 +74,6 @@ export default class Program {
if (source.identity !== this.identity) throw new Error("A program cannot change its identity")
- if (!isDeepStrictEqual(source.clientPermissions, this.clientPermissions)) throw new Error("A Program's Client permissions cannot change during its lifetime")
-
this.config = source.config
this.root = source.root
@@ -117,10 +110,15 @@ export default class Program {
...this.config.client,
start: this.config.client.start ?? true,
service: this.config.client.service ?? false,
- permissions: this.clientPermissions
} : null
}
+ /** Canonical permissions copied into authoritative storage when installed. */
+ public get installationPermissions(): DeclaredPermissions {
+
+ return permissionCatalog.declarations(this.config.client?.permissions)
+ }
+
// A client half may name a URL instead of a directory. The Program asset
// view proxies that development source beneath the same browser address
// used for installed files. An installed program cannot name a URL.
@@ -226,10 +224,9 @@ export default class Program {
layer: client.layer ?? null,
minimize: client.minimize ?? null,
-
- permissions: client.permissions
+ maximize: client.maximize ?? null
}
- }
+ } satisfies ProgramSnapshot
}
private place(declared: string | undefined, fallback = "") {
@@ -299,9 +296,27 @@ function read(path: string): [ProgramConfig, string] {
if (!existsSync(file)) throw new Error(`There is no program at ${file}`)
- try { return [JSON.parse(readFileSync(file, "utf-8")) as ProgramConfig, dirname(file)] }
+ let value: unknown
+
+ try { value = JSON.parse(readFileSync(file, "utf-8")) }
catch (exception) { throw new Error(`${file} is not valid JSON: ${exception instanceof Error ? exception.message : "unreadable"}`) }
+
+ return [storedDefinition(value), dirname(file)]
+}
+
+function storedDefinition(value: unknown): ProgramConfig {
+
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("A stored Program definition must be an object")
+
+ const source = value as Record<string, unknown>
+ const definition = parseProgramDefinition({ ...source, storage: source.storage ?? "./storage" })
+
+ if (source.storage !== undefined) return definition
+
+ const { storage: _storage, ...installed } = definition
+
+ return installed satisfies ProgramConfig
}
// What a description must be for a program to exist at all. Nothing
@@ -374,6 +389,7 @@ function coherent(config: ProgramConfig) {
if (config.client?.title !== undefined && typeof config.client.title !== "string") throw new Error("A client half's title must be text")
+ if (config.client?.maximize !== undefined && typeof config.client.maximize !== "boolean") throw new Error("A client half's maximize default must be true or false")
if (config.client?.minimize !== undefined && typeof config.client.minimize !== "boolean") throw new Error("A client half's minimize default must be true or false")
for (const [what, value] of [["size", config.client?.size], ["position", config.client?.position]] as const) {
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
index f2868fd..617e5e0 100644
--- a/source/server/core/permissions.ts
+++ b/source/server/core/permissions.ts
@@ -3,10 +3,7 @@ import {
networkScopeCovers,
parsePermission,
parsePermissionName,
- type ClientPermissions,
type Permission,
- type PermissionDefinition,
- type PermissionDefinitions,
type PermissionName,
type PermissionValue,
type PermissionValueDomain,
@@ -96,7 +93,7 @@ export class PermissionCatalog {
throw new Error(`Permission "${name}" contains an unknown value`)
}
- public declarations(value: unknown): ClientPermissions {
+ public declarations(value: unknown): DeclaredPermissions {
if (value === undefined) return Object.freeze({})
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("A Client's permissions must be a record")
@@ -113,7 +110,7 @@ export class PermissionCatalog {
resolved[name] = Object.freeze(permission)
}
- return Object.freeze(resolved) as ClientPermissions
+ return Object.freeze(resolved) as DeclaredPermissions
}
public stored(value: unknown): Permissions {
@@ -157,24 +154,28 @@ export class PermissionCatalog {
return Array.isArray(permission)
}
- /** Tests complete authority, including grants implied by another permission. */
+ /** Tests one request against the authoritative permission state. */
public allows<Name extends PermissionName>(
name: Name,
requested: readonly PermissionValue<Name>[],
- ...sources: PermissionGrants[]
+ permissions: Permissions
) {
this.definition(name)
- const effective = (key: PermissionName) => this.effective(key, ...sources.map(source => source[key] ?? null))
+ const assigned = permissions[name]
- if (this.granted(effective("all"))) return true
+ // An exact assignment is the owner's final decision for that
+ // permission. Broader fallback grants must never undo a restriction.
+ if (assigned !== undefined && assigned !== null) return this.grants(name, assigned, requested)
- const permission = name === "services"
- ? this.combine("services", effective("services"), effective("programs"))
- : effective(name)
+ if (name === "services" && Array.isArray(permissions.programs)) {
+ return this.grants(name, permissions.programs, requested)
+ }
+
+ if (name !== "all" && this.granted(permissions.all ?? null)) return true
- return this.grants(name, permission, requested)
+ return false
}
/** Tests one native Storage path against the complete effective authority. */
@@ -185,39 +186,18 @@ export class PermissionCatalog {
operation?: StoragePermissionOperation
) {
- if (this.granted(all)) return true
- if (!Array.isArray(storage)) return false
- if (storage.length === 0) return true
-
- return storage.some(scope => nativeStorageScopeAccesses(scope, path, operation))
- }
-
- public combine<Name extends PermissionName>(name: Name, ...grants: PermissionGrant[]): Permission<Name> {
-
- const present = grants.filter((grant): grant is readonly string[] => Array.isArray(grant))
+ // Storage uses path-aware containment, but assignment priority remains
+ // identical to every other permission: an exact value is final and
+ // `all` is only a fallback when Storage is unassigned.
+ if (storage !== null) {
- if (present.length === 0) return null
- if (!valued(this.definition(name).valueDomain)) return []
- if (present.some(grant => grant.length === 0)) return []
-
- return this.resolve(name, present.flat()) as PermissionValue<Name>[]
- }
-
- public effective<Name extends PermissionName>(name: Name, ...grants: PermissionGrant[]): Permission<Name> {
-
- return this.combine(name, ...grants) ?? (grants.includes(false) ? false : null)
- }
+ if (!Array.isArray(storage)) return false
+ if (storage.length === 0) return true
- public merge<Name extends PermissionName>(
- name: Name,
- grant: PermissionGrant,
- requested: readonly PermissionValue<Name>[]
- ): PermissionValue<Name>[] {
-
- if (!Array.isArray(grant)) return [...requested]
- if (valued(this.definition(name).valueDomain) && (grant.length === 0 || requested.length === 0)) return []
+ return storage.some(scope => nativeStorageScopeAccesses(scope, path, operation))
+ }
- return this.resolve(name, [...grant, ...requested]) as PermissionValue<Name>[]
+ return this.granted(all)
}
public changed<Name extends PermissionName>(left: Permission<Name>, right: Permission<Name>) {
@@ -231,7 +211,20 @@ export class PermissionCatalog {
type PermissionGrant = readonly string[] | false | null
-type PermissionGrants = Readonly<Partial<Record<PermissionName, PermissionGrant>>>
+type PermissionDefinition<Name extends PermissionName = PermissionName> = Readonly<{
+ valueDomain: PermissionValueDomain<Name>
+ default: readonly PermissionValue<Name>[]
+ title: string
+ description: string
+}>
+
+type PermissionDefinitions = Readonly<{
+ [Name in PermissionName]: PermissionDefinition<Name>
+}>
+
+export type DeclaredPermissions = Readonly<{
+ [Name in PermissionName]?: readonly PermissionValue<Name>[]
+}>
type PermissionRule<Name extends PermissionName> = Omit<PermissionDefinition<Name>, "valueDomain">
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index a95ce08..b1e8820 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -265,6 +265,11 @@ export default class System {
await this.processManager.setGeometry(process.identity, geometry)
}
+ public async maximizeWindow(process: Process, maximized: boolean) {
+
+ await this.processManager.maximize(process.identity, maximized)
+ }
+
public async minimizeWindow(process: Process, minimized: boolean) {
await this.processManager.minimize(process.identity, minimized)
@@ -302,7 +307,7 @@ export default class System {
position: program.client.position ?? null,
layer: program.client.layer ?? null,
minimize: program.client.minimize ?? null,
- permissions: program.client.permissions
+ maximize: program.client.maximize ?? null
}) : null
})
}