Skip to content

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

Keep window surfaces local and geometry atomic

zohayrslilehd3356cf337d6
diff --git a/bun.lock b/bun.lock
index 0c1bca7..3e2c63b 100644
--- a/bun.lock
+++ b/bun.lock
@@ -25,7 +25,7 @@
"devDependencies": {
"@babel/core": "^7.29.7",
"@babel/plugin-proposal-decorators": "^7.29.7",
- "@phreshos/core": "^0.1.4",
+ "@phreshos/core": "^0.1.5",
"@phreshos/react-ui": "^0.1.1",
"@rolldown/plugin-babel": "^0.2.3",
"@tailwindcss/vite": "^4.3.3",
@@ -229,7 +229,7 @@
"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],
- "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-qg4Uo+yH9KySygNQRmY7KSxpmNPt2oqkzAJcZBfitw+3g9zllwVzMHbUx3rU8gKZoY4hx1kZVdCd1ZiYo+TF5Q=="],
+ "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-BJx9OkyhWYJCHc2NElH/RI/oZ9cqCHAIIecoWGPz5vjcSJb6UFhmIds+UHBPBh3pgia9G+WzXicSMRqkhVFaNQ=="],
"@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "react-aria-components": "^1.20.0" }, "peerDependencies": { "@phreshos/core": "^0.1.4", "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-mj6+xizG/mlPOsEPydI4vlxeeFcu836/lHs7fxK169Jbhnc7oM3xsdV+tUpFaYcPtl4oDZdjMD4UDuW5jr+hhQ=="],
diff --git a/package.json b/package.json
index dec3518..1a0d203 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "phreshos",
"displayName": "PhreshOS",
- "version": "0.1.8",
+ "version": "0.1.9",
"description": "The PhreshOS server, desktop, and authoritative system runtime.",
"type": "module",
"private": true,
@@ -30,7 +30,7 @@
"build": "vite-node --config vite.server.ts source/build.ts",
"start": "node --run build && node dist/server/main.js",
"pack": "node --run build && vite-node --config vite.server.ts source/pack.ts",
- "verify:contracts": "vite-node --config vite.server.ts scripts/verify-client-launch.mjs && vite-node --config vite.server.ts scripts/verify-readiness.mjs && vite-node --config vite.server.ts scripts/verify-endpoint-services.mjs && vite-node --config vite.server.ts scripts/verify-intake-address.mjs",
+ "verify:contracts": "vite-node --config vite.server.ts scripts/verify-client-launch.mjs && vite-node --config vite.server.ts scripts/verify-client-surface.mjs && vite-node --config vite.server.ts scripts/verify-window-geometry.mjs && vite-node --config vite.server.ts scripts/verify-readiness.mjs && vite-node --config vite.server.ts scripts/verify-endpoint-services.mjs && vite-node --config vite.server.ts scripts/verify-intake-address.mjs",
"verify:distribution": "node scripts/verify-distribution.mjs",
"verify": "node --run check && node --run verify:contracts && node --run verify:distribution"
},
@@ -55,7 +55,7 @@
"devDependencies": {
"@babel/core": "^7.29.7",
"@babel/plugin-proposal-decorators": "^7.29.7",
- "@phreshos/core": "^0.1.4",
+ "@phreshos/core": "^0.1.5",
"@phreshos/react-ui": "^0.1.1",
"@rolldown/plugin-babel": "^0.2.3",
"@tailwindcss/vite": "^4.3.3",
diff --git a/scripts/verify-client-surface.mjs b/scripts/verify-client-surface.mjs
new file mode 100644
index 0000000..a97cc73
--- /dev/null
+++ b/scripts/verify-client-surface.mjs
@@ -0,0 +1,92 @@
+import assert from "node:assert/strict"
+import ClientProcessBoundary from "../source/client/view/desktop/client-host/client-process-boundary.ts"
+import { clientSurfaceSettings, removeClientSurface, setClientSurface } from "../source/client/view/desktop/client-host/client-surface.ts"
+import host from "../source/client/view/desktop/client-host/host.ts"
+import ServerWindow from "../source/server/core/link-manager/auth-manager/process-manager/window.ts"
+
+const authoritativeWindow = new ServerWindow(
+ { title: "Target", url: null, layer: "over", location: "/" },
+ { x: 0, y: 0 },
+ { width: 100, height: 100 },
+ 1,
+ false
+)
+
+assert.equal("surface" in authoritativeWindow, false)
+assert.equal("surface" in authoritativeWindow.toJSON(), false)
+
+const settings = clientSurfaceSettings({ opacity: 0.5, radius: "large", transaction: { duration: 240, easing: "ease-out" } })
+
+let firstDesktop = new Map()
+let secondDesktop = new Map()
+
+firstDesktop = setClientSurface(firstDesktop, "target", settings)
+
+assert.equal(firstDesktop.get("target")?.revision, 1)
+assert.equal(secondDesktop.has("target"), false)
+assert.equal(setClientSurface(firstDesktop, "target", settings), firstDesktop)
+
+firstDesktop = removeClientSurface(firstDesktop, "target")
+
+assert.equal(firstDesktop.has("target"), false)
+assert.equal(removeClientSurface(firstDesktop, "target"), firstDesktop)
+
+assert.throws(() => clientSurfaceSettings({ opacity: 2 }), /from 0 to 1/)
+assert.throws(() => clientSurfaceSettings({ radius: -1 }), /ScaleLevel/)
+assert.throws(() => clientSurfaceSettings({ transaction: { duration: 60_001 } }), /0 to 60000/)
+assert.throws(() => clientSurfaceSettings({ unknown: true }), /no "unknown" field/)
+
+const requester = {
+ identity: "requester",
+ reference: "requester-reference",
+ program: "program",
+ client: { window: { process: "requester", layer: "over" } }
+}
+
+const target = {
+ identity: "target",
+ reference: "target-reference",
+ program: "program",
+ client: { window: { process: "target", layer: "under" } }
+}
+
+const processes = new Map([[requester.identity, requester], [target.identity, target]])
+const calls = []
+const surface = {
+ set(identity, value) { calls.push(["set", identity, value]) },
+ remove(identity) { calls.push(["remove", identity]) }
+}
+
+const authManager = {
+ processManager: { processes },
+ programManager: { programs: new Map() }
+}
+
+const request = host(authManager, requester.identity, () => ({ width: 1, height: 1 }), () => "owner", {}, surface)
+
+await request("surfaceSet", { identity: target.identity, reference: target.reference }, settings)
+await request("surfaceRemove", { identity: target.identity, reference: target.reference })
+
+assert.deepEqual(calls, [["set", "target", settings], ["remove", "target"]])
+
+target.client.window.layer = "window"
+
+await assert.rejects(request("surfaceSet", { identity: target.identity, reference: target.reference }, {}), /window-layer/)
+
+const lifecycle = []
+const boundary = new ClientProcessBoundary(
+ "target",
+ { contentWindow: null },
+ authManager,
+ () => ({ width: 1, height: 1 }),
+ {},
+ {},
+ { set() {}, remove(identity) { lifecycle.push(identity) } }
+)
+
+boundary.receive(["boundary", "document", "first-document"])
+boundary.receive(["boundary", "document", "first-document"])
+boundary.receive(["boundary", "document", "second-document"])
+await boundary.release()
+
+assert.deepEqual(lifecycle, ["target", "target"])
diff --git a/scripts/verify-window-geometry.mjs b/scripts/verify-window-geometry.mjs
new file mode 100644
index 0000000..da12cae
--- /dev/null
+++ b/scripts/verify-window-geometry.mjs
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict"
+import ClientWindow from "../source/client/core/link-manager/auth-manager/process-manager/window.ts"
+import ProcessManager from "../source/server/core/link-manager/auth-manager/process-manager/process-manager.ts"
+import ServerWindow from "../source/server/core/link-manager/auth-manager/process-manager/window.ts"
+
+const initial = {
+ position: { x: 10, y: 20 },
+ size: { width: 300, height: 200 }
+}
+
+const authority = new ServerWindow(
+ { title: "Geometry", url: null, layer: "window", location: "/" },
+ initial.position,
+ initial.size,
+ 1,
+ false
+)
+
+assert.throws(() => authority.setGeometry({
+ position: { x: 40, y: 50 },
+ size: { width: Number.NaN, height: 240 }
+}), /width/)
+assert.deepEqual(authority.position, initial.position)
+assert.deepEqual(authority.size, initial.size)
+
+const next = {
+ position: { x: "1/4", y: 30 },
+ size: { width: "1/2", height: 240 }
+}
+const events = []
+const echoes = []
+const manager = {
+ $outbound: {
+ publish(...echo) {
+ echoes.push(echo)
+ }
+ },
+ mutableWindowOf(identity) {
+ assert.equal(identity, "process")
+ return authority
+ },
+ said(...event) {
+ events.push(event)
+ }
+}
+
+const echo = await ProcessManager.prototype.setGeometry.call(manager, "process", next)
+
+assert.deepEqual(authority.position, next.position)
+assert.deepEqual(authority.size, next.size)
+assert.deepEqual(events, [
+ ["process", "geometry", next],
+ ["process", "move", next.position],
+ ["process", "resize", next.size]
+])
+assert.deepEqual(echoes, [["/geometry", { identity: "process", window: authority }]])
+assert.equal(echo.identity, "process")
+assert.equal(echo.window, authority)
+
+const publications = []
+const counterpart = new ClientWindow(
+ { $outbound: { publish: (...publication) => publications.push(publication) } },
+ "process",
+ authority.toJSON()
+)
+const draft = {
+ position: { x: 5, y: 6 },
+ size: { width: 700, height: 500 }
+}
+
+counterpart.localSetGeometry(draft)
+assert.deepEqual(counterpart.position, draft.position)
+assert.deepEqual(counterpart.size, draft.size)
+
+await counterpart.setGeometry(next)
+assert.deepEqual(publications, [["/geometry", "process", next]])
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 aa3f84e..458dfe5 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
@@ -198,11 +198,11 @@ export default class ProcessManager extends TheLink {
// Any window change arrives in one shape: the process it belongs to,
// and the window whole.
- private followed(payload: { identity: string, window: TransmittedWindow } | null, surfaceChanged = false) {
+ private followed(payload: { identity: string, window: TransmittedWindow } | null) {
if (!payload) return
- this.processes.get(payload.identity)?.client?.window.follow(payload.window, surfaceChanged)
+ this.processes.get(payload.identity)?.client?.window.follow(payload.window)
return this.list()
}
@@ -305,6 +305,13 @@ export default class ProcessManager extends TheLink {
return this.followed(payload)
}
+ @Subscribe("/geometry")
+ @Publish("/processes", "inbound")
+ protected async geometryHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+
+ return this.followed(payload)
+ }
+
@Subscribe("/raise")
@Publish("/processes", "inbound")
protected async raiseHandle(payload: { identity: string, window: TransmittedWindow } | null) {
@@ -326,13 +333,6 @@ export default class ProcessManager extends TheLink {
return this.followed(payload)
}
- @Subscribe("/surface")
- @Publish("/processes", "inbound")
- protected async surfaceHandle(payload: { identity: string, window: TransmittedWindow } | null) {
-
- return this.followed(payload, true)
- }
-
@Subscribe("/end-end")
protected async endEndHandle(identity: string, json: 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 fd6b124..498deef 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 TransmittedWindow, type Position, type Size } from "@server/core/link-manager/auth-manager/process-manager/window"
-import { isRelativeValue, type WindowLayer, type WindowSurfaceSettings } from "@phreshos/core"
+import { isRelativeValue, type WindowGeometry, type WindowLayer } from "@phreshos/core"
import ProcessManager from "./process-manager"
/**
@@ -25,13 +25,6 @@ export default class Window {
public minimized: boolean
- // Authoritative host material echoed from the server. The revision is
- // desktop-local delivery knowledge: zero marks an initial snapshot, while
- // later values let rendering animate only live changes.
- public surface: WindowSurfaceSettings | null
-
- public surfaceRevision = 0
-
// 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
@@ -68,11 +61,10 @@ export default class Window {
this.minimized = payload.minimized
- this.surface = payload.surface
}
// What the echo carries, applied whole: one shape for any change.
- public follow(payload: TransmittedWindow, surfaceChanged = false) {
+ public follow(payload: TransmittedWindow) {
this.title = payload.title
@@ -90,12 +82,6 @@ export default class Window {
this.minimized = payload.minimized
- if (surfaceChanged) {
-
- this.surface = payload.surface
-
- this.surfaceRevision += 1
- }
}
// A local geometry change is a draft held by this desktop. It redraws
@@ -119,14 +105,20 @@ export default class Window {
this.size = size
}
- public async setSurface(settings: WindowSurfaceSettings) {
+ /** Applies a complete desktop-local draft in one notification cycle. */
+ public localSetGeometry(geometry: WindowGeometry) {
- await this.processManager.$outbound.publish("/surface", this.process, settings)
- }
+ validate(geometry.position.x, "x")
+
+ validate(geometry.position.y, "y")
- public async removeSurface() {
+ validate(geometry.size.width, "width")
- await this.processManager.$outbound.publish("/surface", this.process, null)
+ validate(geometry.size.height, "height")
+
+ this.position = geometry.position
+
+ this.size = geometry.size
}
public async move(position: Position) {
@@ -139,6 +131,11 @@ export default class Window {
await this.processManager.$outbound.publish("/resize", this.process, size)
}
+ public async setGeometry(geometry: WindowGeometry) {
+
+ await this.processManager.$outbound.publish("/geometry", this.process, geometry)
+ }
+
public async changeTitle(title: string) {
await this.processManager.$outbound.publish("/change-title", this.process, title)
diff --git a/source/client/view/desktop/client-host/client-host.ts b/source/client/view/desktop/client-host/client-host.ts
index a8e760a..f3a84a8 100644
--- a/source/client/view/desktop/client-host/client-host.ts
+++ b/source/client/view/desktop/client-host/client-host.ts
@@ -5,9 +5,10 @@ import { type Space } from "./host"
import DesktopPointer from "./pointer"
import ClientProcessBoundary from "./client-process-boundary"
import ClientTraffic from "./client-traffic"
-import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
+import { type RefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
import { AuthManagerContext } from "../../contexts"
import { isPermissionName } from "@phreshos/core"
+import { removeClientSurface, setClientSurface, type ClientSurfaceHost, type ClientSurfaceState } from "./client-surface"
/**
* The browser boundary between a program pane and the desktop that hosts it.
@@ -32,6 +33,22 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
const [windowSurfaceSize, setWindowSurfaceSize] = useState<SurfaceSize>({ width: 0, height: 0 })
+ const [clientSurfaces, setClientSurfaces] = useState<ReadonlyMap<string, ClientSurfaceState>>(() => new Map())
+
+ const clientSurface = useMemo<ClientSurfaceHost>(() => ({
+
+ set(identity, settings) {
+
+ setClientSurfaces(current => setClientSurface(current, identity, settings))
+ },
+
+ remove(identity) {
+
+ setClientSurfaces(current => removeClientSurface(current, identity))
+ }
+
+ }), [])
+
// Read by the gate at the moment a pane asks, so the answer is
// never a render behind.
const latest = useRef<Record<WindowLayer, Space>>({
@@ -223,7 +240,7 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
boundaries.current.get(identity)?.release().catch(() => undefined)
- boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, layer => latest.current[layer], pointer, traffic))
+ boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, layer => latest.current[layer], pointer, traffic, clientSurface))
return
}
@@ -238,7 +255,7 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
boundary?.release().catch(() => undefined)
- }, [authManager, pointer, sources, traffic])
+ }, [authManager, clientSurface, pointer, sources, traffic])
const frameLoaded = useCallback(function (identity: string, element: HTMLIFrameElement) {
@@ -309,7 +326,7 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
}, [authManager, pointer, sources])
- return { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded }
+ return { windowSurfaceRef, windowSurfaceSize, clientSurfaces, frame, frameLoaded }
}
export interface SurfaceSize {
diff --git a/source/client/view/desktop/client-host/client-process-boundary.ts b/source/client/view/desktop/client-host/client-process-boundary.ts
index 9f1502a..0ae330d 100644
--- a/source/client/view/desktop/client-host/client-process-boundary.ts
+++ b/source/client/view/desktop/client-host/client-process-boundary.ts
@@ -7,6 +7,7 @@ import ClientTraffic from "./client-traffic"
import { failed, succeeded } from "@server/core/outcome"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { isPermissionName, type PermissionName } from "@phreshos/core"
+import { type ClientSurfaceHost } from "./client-surface"
/** The desktop boundary around one iframe execution endpoint. */
export default class ClientProcessBoundary extends TheLink {
@@ -23,6 +24,8 @@ export default class ClientProcessBoundary extends TheLink {
private readonly traffic: ClientTraffic
+ private readonly clientSurface: ClientSurfaceHost
+
private readonly subscriptions = new Map<string, EndpointSubscription>()
private readonly blockedSubscriptions = new Map<string, EndpointSubscription>()
@@ -56,7 +59,7 @@ export default class ClientProcessBoundary extends TheLink {
private document: string | null = null
- public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, space: (layer: WindowLayer) => Space, pointer: PointerHost, traffic: ClientTraffic) {
+ public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, space: (layer: WindowLayer) => Space, pointer: PointerHost, traffic: ClientTraffic, clientSurface: ClientSurfaceHost) {
super()
@@ -72,6 +75,8 @@ export default class ClientProcessBoundary extends TheLink {
this.traffic = traffic
+ this.clientSurface = clientSurface
+
this.$outbound.forwardTo((route, ...values) => {
this.element.contentWindow?.postMessage([route, ...values], "*")
@@ -98,6 +103,8 @@ export default class ClientProcessBoundary extends TheLink {
public async release() {
+ this.clientSurface.remove(this.pane)
+
const owner = this.leased
this.owner = null
@@ -203,7 +210,7 @@ export default class ClientProcessBoundary extends TheLink {
return
}
- host(this.authManager, this.pane, this.space, () => this.owner, this.pointer)(values[0], ...values.slice(1)).catch((error: Error) => {
+ host(this.authManager, this.pane, this.space, () => this.owner, this.pointer, this.clientSurface)(values[0], ...values.slice(1)).catch((error: Error) => {
if (values[0] === "observe" && typeof values[1] === "string" && values[6] === true) {
@@ -282,6 +289,11 @@ export default class ClientProcessBoundary extends TheLink {
if (typeof args[0] !== "string" || args[0] === this.document) return
+ // The first document establishes this already-mounted iframe
+ // representation. A later document replaces it and therefore
+ // destroys the previous representation's local Surface.
+ if (this.document !== null) this.clientSurface.remove(this.pane)
+
this.document = args[0]
this.resetEndpoint()
@@ -437,7 +449,7 @@ export default class ClientProcessBoundary extends TheLink {
return
}
- this.answerRequest(question, host(this.authManager, this.pane, this.space, () => this.owner, this.pointer)(args[0], ...args.slice(1)))
+ this.answerRequest(question, host(this.authManager, this.pane, this.space, () => this.owner, this.pointer, this.clientSurface)(args[0], ...args.slice(1)))
}
private answerRequest(question: string, operation: Promise<unknown[] | TransferredAnswer>, cancel: () => void = () => undefined) {
diff --git a/source/client/view/desktop/client-host/client-surface.ts b/source/client/view/desktop/client-host/client-surface.ts
new file mode 100644
index 0000000..9f82a21
--- /dev/null
+++ b/source/client/view/desktop/client-host/client-surface.ts
@@ -0,0 +1,121 @@
+import { isScaleLevel, type ClientSurfaceEasing, type ClientSurfaceSettings, type ClientSurfaceTransaction, type ScaleLevel } from "@phreshos/core"
+
+/** Desktop-local Surface commands applied to one exact iframe representation. */
+export interface ClientSurfaceHost {
+
+ set(identity: string, settings: ClientSurfaceSettings): void
+
+ remove(identity: string): void
+}
+
+/** Render target retained only while one iframe representation is alive. */
+export interface ClientSurfaceState {
+
+ settings: ClientSurfaceSettings
+
+ revision: number
+}
+
+export function setClientSurface(current: ReadonlyMap<string, ClientSurfaceState>, identity: string, settings: ClientSurfaceSettings) {
+
+ const previous = current.get(identity)
+
+ if (previous && JSON.stringify(previous.settings) === JSON.stringify(settings)) return current
+
+ const next = new Map(current)
+
+ next.set(identity, { settings, revision: (previous?.revision ?? 0) + 1 })
+
+ return next
+}
+
+export function removeClientSurface(current: ReadonlyMap<string, ClientSurfaceState>, identity: string) {
+
+ if (!current.has(identity)) return current
+
+ const next = new Map(current)
+
+ next.delete(identity)
+
+ return next
+}
+
+/** Rejects malformed representation input before it can enter desktop state. */
+export function clientSurfaceSettings(value: unknown): ClientSurfaceSettings {
+
+ const record = plain(value, "Surface settings")
+
+ fields(record, ["opacity", "radius", "transaction"], "Surface settings")
+
+ const settings: { opacity?: number, radius?: ScaleLevel | number | "full", transaction?: ClientSurfaceTransaction } = {}
+
+ if ("opacity" in record) {
+
+ if (!finite(record.opacity) || record.opacity < 0 || record.opacity > 1) throw new Error("Surface opacity must be a finite number from 0 to 1")
+
+ settings.opacity = record.opacity
+ }
+
+ if ("radius" in record) {
+
+ if (record.radius !== "full" && !isScaleLevel(record.radius) && (!finite(record.radius) || record.radius < 0)) throw new Error('Surface radius must be a ScaleLevel, a finite nonnegative pixel number, or "full"')
+
+ settings.radius = record.radius
+ }
+
+ if ("transaction" in record) settings.transaction = transaction(record.transaction)
+
+ return Object.freeze(settings)
+}
+
+function transaction(value: unknown): ClientSurfaceTransaction {
+
+ const record = plain(value, "Surface transaction")
+
+ fields(record, ["duration", "easing"], "Surface transaction")
+
+ const result: { duration?: number, easing?: ClientSurfaceEasing } = {}
+
+ if ("duration" in record) {
+
+ if (!finite(record.duration) || record.duration < 0 || record.duration > 60_000) throw new Error("Surface transaction duration must be finite milliseconds from 0 to 60000")
+
+ result.duration = record.duration
+ }
+
+ if ("easing" in record) result.easing = easing(record.easing)
+
+ return Object.freeze(result)
+}
+
+function easing(value: unknown): ClientSurfaceEasing {
+
+ if (value === "linear" || value === "ease" || value === "ease-in" || value === "ease-out" || value === "ease-in-out") return value
+
+ if (!Array.isArray(value) || value.length !== 4 || !value.every(finite) || value[0] < 0 || value[0] > 1 || value[2] < 0 || value[2] > 1) throw new Error("Surface transaction easing must be a standard easing name or four cubic Bézier numbers with x values from 0 to 1")
+
+ return Object.freeze([...value]) as [number, number, number, number]
+}
+
+function plain(value: unknown, name: string): Record<string, unknown> {
+
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${name} must be an object`)
+
+ const prototype = Object.getPrototypeOf(value)
+
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${name} must be an object`)
+
+ return value as Record<string, unknown>
+}
+
+function fields(record: Record<string, unknown>, allowed: string[], name: string) {
+
+ const unknown = Object.keys(record).find(field => !allowed.includes(field))
+
+ if (unknown) throw new Error(`${name} has no "${unknown}" field`)
+}
+
+function finite(value: unknown): value is number {
+
+ return typeof value === "number" && Number.isFinite(value)
+}
diff --git a/source/client/view/desktop/client-host/host.ts b/source/client/view/desktop/client-host/host.ts
index 4550d22..ddfc807 100644
--- a/source/client/view/desktop/client-host/host.ts
+++ b/source/client/view/desktop/client-host/host.ts
@@ -7,6 +7,7 @@ import { type PointerHost } from "./pointer"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { sdkProcess, sdkProgram } from "./sdk-records"
import { isPermissionName, isServiceKey, type ProgramIconSize } from "@phreshos/core"
+import { clientSurfaceSettings, type ClientSurfaceHost } from "./client-surface"
/** A host answer whose stream must be transferred rather than cloned. */
export class TransferredAnswer {
@@ -48,7 +49,7 @@ export interface Space {
* no prototypes and refuses functions — so every word answers with plain
* values built here, never with an instance the desktop holds.
*/
-export default function host(authManager: AuthManager, pane: string, space: (layer: WindowLayer) => Space, frameOwner: () => string | null, pointer: PointerHost) {
+export default function host(authManager: AuthManager, pane: string, space: (layer: WindowLayer) => Space, frameOwner: () => string | null, pointer: PointerHost, clientSurface: ClientSurfaceHost) {
const { processManager, programManager } = authManager
@@ -109,6 +110,17 @@ export default function host(authManager: AuthManager, pane: string, space: (lay
return found
}
+ function surfaceWindow(named: unknown) {
+
+ const found = window(named)
+
+ if (found.layer === "window") throw new Error("A window-layer Window cannot own a Surface")
+
+ if (found.layer === "wallpaper") throw new Error("A wallpaper-layer Window cannot own a Surface")
+
+ return found
+ }
+
function declared(found: ReturnType<typeof process>, half: "server" | "client") {
return (programManager.programs.get(found.program)?.[half] ?? null) !== null
@@ -627,6 +639,13 @@ export default function host(authManager: AuthManager, pane: string, space: (lay
return [pane]
}
+ if (word === "setGeometry") {
+
+ await mutableWindow(args[0]).setGeometry(args[1] as never)
+
+ return [pane]
+ }
+
if (word === "localResize") {
mutableWindow(args[0]).localResize(args[1] as never)
@@ -638,14 +657,18 @@ export default function host(authManager: AuthManager, pane: string, space: (lay
if (word === "surfaceSet") {
- await window(args[0]).setSurface(args[1] === undefined ? {} : args[1] as never)
+ const target = surfaceWindow(args[0])
+
+ clientSurface.set(target.process, clientSurfaceSettings(args[1] === undefined ? {} : args[1]))
return [pane]
}
if (word === "surfaceRemove") {
- await window(args[0]).removeSurface()
+ const target = surfaceWindow(args[0])
+
+ clientSurface.remove(target.process)
return [pane]
}
diff --git a/source/client/view/desktop/window-manager/process-window.tsx b/source/client/view/desktop/window-manager/process-window.tsx
index 7544617..6e908e8 100644
--- a/source/client/view/desktop/window-manager/process-window.tsx
+++ b/source/client/view/desktop/window-manager/process-window.tsx
@@ -1,6 +1,7 @@
import Process from "@client/core/link-manager/auth-manager/process-manager/process"
import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
import { type WindowSurfaceSize } from "./window-geometry"
+import { type ClientSurfaceState } from "../client-host/client-surface"
import { type ProgramAccess } from "../program-access"
import { type Position, type Size } from "@phreshos/core"
import Loading from "../../components/loading"
@@ -17,7 +18,7 @@ const loadingExitDuration = 200
* 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, client, title, icon, position, size, windowSurface, windowSurfaceRevision, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, onFrame, onFrameLoad, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+export default memo(function ({ identity, record, client, title, icon, position, size, clientSurface, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, onFrame, onFrameLoad, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
const activate = useCallback(() => onRaise(record), [onRaise, record])
@@ -95,9 +96,7 @@ export default memo(function ({ identity, record, client, title, icon, position,
size={size}
- windowSurface={windowSurface}
-
- windowSurfaceRevision={windowSurfaceRevision}
+ clientSurface={clientSurface}
paintSurfaceSize={paintSurfaceSize}
@@ -174,9 +173,7 @@ interface ProcessWindowProps {
size: Size
- windowSurface: ClientState["window"]["surface"]
-
- windowSurfaceRevision: number
+ clientSurface?: ClientSurfaceState
paintSurfaceSize?: WindowSurfaceSize
diff --git a/source/client/view/desktop/window-manager/window-manager.ts b/source/client/view/desktop/window-manager/window-manager.ts
index a98b89c..a0ff9a3 100644
--- a/source/client/view/desktop/window-manager/window-manager.ts
+++ b/source/client/view/desktop/window-manager/window-manager.ts
@@ -258,18 +258,20 @@ export default function useWindows() {
if (!window) return
- window.localResize({ width, height })
-
if (!position) {
+ window.localResize({ width, height })
+
commit(window.resize({ width, height }))
return
}
- window.localMove(position)
+ const geometry = { position, size: { width, height } }
- commit(window.move(position).then(() => window.resize({ width, height })))
+ window.localSetGeometry(geometry)
+
+ commit(window.setGeometry(geometry))
}, [commit])
@@ -279,11 +281,11 @@ export default function useWindows() {
if (!window) return
- window.localMove(position)
+ const geometry = { position, size }
- window.localResize(size)
+ window.localSetGeometry(geometry)
- commit(window.move(position).then(() => window.resize(size)))
+ commit(window.setGeometry(geometry))
}, [commit])
@@ -301,9 +303,7 @@ export default function useWindows() {
filled.current.delete(process.identity)
- move(process, was.position.x, was.position.y)
-
- resize(process, was.size.width, was.size.height, null)
+ snap(process, was.position, was.size)
return
}
@@ -312,7 +312,7 @@ export default function useWindows() {
snap(process, { x: "0/1", y: "0/1" }, { width: "1/1", height: "1/1" })
- }, [move, resize, snap])
+ }, [snap])
// Every window on the desktop, in one list and one order.
//
diff --git a/source/client/view/desktop/window-manager/window-surface.tsx b/source/client/view/desktop/window-manager/window-surface.tsx
index fb5ae97..96a63a9 100644
--- a/source/client/view/desktop/window-manager/window-surface.tsx
+++ b/source/client/view/desktop/window-manager/window-surface.tsx
@@ -1,5 +1,5 @@
import { useReducedMotion } from "@libs/react-motion"
-import { isScaleLevel, scale, type WindowSurfaceEasing, type WindowSurfaceSettings } from "@phreshos/core"
+import { isScaleLevel, scale, type ClientSurfaceEasing, type ClientSurfaceSettings } from "@phreshos/core"
import { GlassSurface, useTheme } from "@phreshos/react-ui"
import { useLayoutEffect, useRef, useState } from "react"
@@ -7,7 +7,7 @@ const systemDuration = 240
const systemEasing = "ease-out"
-/** Projects one authoritative target and animates only live replacements. */
+/** Projects one representation-local target and animates explicit replacements. */
export default function WindowSurface({ revision, settings }: WindowSurfaceProps) {
const element = useRef<HTMLDivElement>(null)
@@ -104,7 +104,7 @@ export default function WindowSurface({ revision, settings }: WindowSurfaceProps
/>
}
-function values(settings: WindowSurfaceSettings, themeRadius: number) {
+function values(settings: ClientSurfaceSettings, themeRadius: number) {
const radius = settings.radius
@@ -116,7 +116,7 @@ function values(settings: WindowSurfaceSettings, themeRadius: number) {
}
}
-function easing(value: WindowSurfaceEasing | undefined) {
+function easing(value: ClientSurfaceEasing | undefined) {
if (typeof value === "string") return value
@@ -125,8 +125,8 @@ function easing(value: WindowSurfaceEasing | undefined) {
interface WindowSurfaceProps {
- settings: WindowSurfaceSettings
+ settings: ClientSurfaceSettings
- /** Zero is an initial snapshot; positive revisions are live changes. */
+ /** Every positive revision came from an explicit live Client command. */
revision: number
}
diff --git a/source/client/view/desktop/window-manager/window.tsx b/source/client/view/desktop/window-manager/window.tsx
index ecd9a93..8f5bc87 100644
--- a/source/client/view/desktop/window-manager/window.tsx
+++ b/source/client/view/desktop/window-manager/window.tsx
@@ -3,9 +3,10 @@ import { useReducedMotion } from "@libs/react-motion"
import { enterSurface, prepareSurfaceEntrance, restSurface } from "../../appearance/surface-presence"
import { GlassSurface, useTheme } from "@phreshos/react-ui"
import { absoluteWindowGeometry, resolveWindowValue, wholeWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "./window-geometry"
-import { numericScale, type Position, type Size, type WindowSurfaceSettings } from "@phreshos/core"
+import { numericScale, type Position, type Size } from "@phreshos/core"
import WindowHeader from "./window-header"
import WindowSurface from "./window-surface"
+import { type ClientSurfaceState } from "../client-host/client-surface"
import gsap from "gsap"
/**
@@ -48,7 +49,7 @@ const settle = ["left", "top", "width", "height", "transform"].map(property => `
const morphing = ["left", "top", "width", "height"].map(property => `${property} 0.22s cubic-bezier(0.33, 1, 0.68, 1)`).join(", ")
-export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, windowSurface = null, windowSurfaceRevision = 0, 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, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, clientSurface, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
const frame = useRef<HTMLDivElement>(null)
@@ -562,7 +563,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
{/* A bare Client cannot refract the desktop through its iframe.
Its host surface is therefore a sibling behind the frame,
with its own radius and no clipping parent. */}
- {bare && windowSurface && <WindowSurface settings={windowSurface} revision={windowSurfaceRevision} />}
+ {bare && clientSurface && <WindowSurface settings={clientSurface.settings} revision={clientSurface.revision} />}
{/* LAYER 1 — the shared Theme-driven glass material. */}
{!bare && <GlassSurface aria-hidden="true" radius="inherit" className="pointer-events-none absolute inset-0" />}
@@ -680,11 +681,8 @@ interface WindowProps extends Omit<ComponentProps<"div">, "title"> {
size?: Size
- /** Authoritative host Surface target behind a bare iframe. */
- windowSurface?: WindowSurfaceSettings | null
-
- /** Desktop delivery revision used to distinguish live changes from snapshots. */
- windowSurfaceRevision?: number
+ /** Surface target owned by this live iframe representation. */
+ clientSurface?: ClientSurfaceState
/** Surface used only to decide which painted edges receive an inset. */
paintSurfaceSize?: WindowSurfaceSize
diff --git a/source/client/view/desktop/workspace.tsx b/source/client/view/desktop/workspace.tsx
index 599c838..6d26801 100644
--- a/source/client/view/desktop/workspace.tsx
+++ b/source/client/view/desktop/workspace.tsx
@@ -47,7 +47,7 @@ export default function Workspace() {
// lets the desktop announce the surface that actually contains it.
const sources = useRef(new Map<string, HTMLIFrameElement | null>())
- const { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded } = useClientHost(desktop, sources.current)
+ const { windowSurfaceRef, windowSurfaceSize, clientSurfaces, frame, frameLoaded } = useClientHost(desktop, sources.current)
const wallpaperLoaded = useCallback((event: SyntheticEvent<HTMLIFrameElement>) => {
@@ -98,9 +98,7 @@ export default function Workspace() {
size={client.window.size}
- windowSurface={client.window.surface}
-
- windowSurfaceRevision={client.window.surfaceRevision}
+ clientSurface={clientSurfaces.get(record.identity)}
// Only system-painted windows need to know which paint edges
// touch their surface. Positioning is identical in every layer.
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 26a3e44..ab89957 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
@@ -18,7 +18,7 @@ import { failed, succeeded, type Outcome } from "@server/core/outcome"
import { endpointReference, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
import EndpointServices from "./endpoint-services"
-import { isPermissionName, isServiceKey, type PermissionName, type WindowLayer } from "@phreshos/core"
+import { isPermissionName, isServiceKey, type PermissionName, type WindowGeometry, type WindowLayer } from "@phreshos/core"
/**
* The core's processes: the wire and the collection. Each process owns
@@ -157,17 +157,6 @@ export default class ProcessManager extends TheLink {
return window
}
- private surfaceWindowOf(identity: string) {
-
- const window = this.windowOf(identity)
-
- if (window.layer === "window") throw new Error("A window-layer Window cannot own a Surface")
-
- if (window.layer === "wallpaper") throw new Error("A wallpaper-layer Window cannot own a Surface")
-
- return window
- }
-
// A server runtime is a ProcessLink. Speaking through its outbound
// tunnel keeps IPC as a transport detail and leaves a stopped child as
// fire-and-forget: there is no receiver to promise once it has gone.
@@ -1668,20 +1657,11 @@ export default class ProcessManager extends TheLink {
return [target]
}
- if (word === "surfaceSet") {
-
- const target = this.heldWindow(rest[0], process).process.identity
-
- await this.surface(target, rest[1] === undefined ? {} : rest[1])
-
- return [target]
- }
-
- if (word === "surfaceRemove") {
+ if (word === "setGeometry") {
const target = this.heldWindow(rest[0], process).process.identity
- await this.surface(target, null)
+ await this.setGeometry(target, rest[1] as WindowGeometry)
return [target]
}
@@ -2158,26 +2138,30 @@ export default class ProcessManager extends TheLink {
return { identity, window }
}
- @Connect("/change-title")
- public async changeTitle(identity: string, title: string) {
+ @Connect("/geometry")
+ public async setGeometry(identity: string, geometry: WindowGeometry) {
const window = this.mutableWindowOf(identity)
- window.changeTitle(title)
+ window.setGeometry(geometry)
- this.said(identity, "changeTitle", window.title)
+ this.said(identity, "geometry", { position: window.position, size: window.size })
+
+ this.said(identity, "move", window.position)
+
+ this.said(identity, "resize", window.size)
return { identity, window }
}
- @Connect("/surface")
- public async surface(identity: string, settings: unknown) {
+ @Connect("/change-title")
+ public async changeTitle(identity: string, title: string) {
- const window = this.surfaceWindowOf(identity)
+ const window = this.mutableWindowOf(identity)
- const changed = settings === null ? window.removeSurface() : window.setSurface(settings)
+ window.changeTitle(title)
- if (!changed) return null
+ this.said(identity, "changeTitle", window.title)
return { identity, window }
}
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 0b7ee70..3fcb7d3 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,4 +1,4 @@
-import { isRelativeValue, isScaleLevel, type Position, type ScaleLevel, type Size, type Value, type WindowLayer, type WindowSurfaceEasing, type WindowSurfaceSettings, type WindowSurfaceTransaction } from "@phreshos/core"
+import { isRelativeValue, type Position, type Size, type Value, type WindowGeometry, type WindowLayer } from "@phreshos/core"
import { Transmitted } from "@libs/superjson"
/**
@@ -72,10 +72,6 @@ export default class Window {
// first frame is not the same as shown once and then hidden.
public minimized: boolean
- // Optional host material is Window state like geometry: born absent,
- // changed only here, and echoed whole to every desktop counterpart.
- public surface: WindowSurfaceSettings | null = null
-
// What a person reads on it. Born from the program, the window's
// own afterwards.
public title: string
@@ -152,33 +148,29 @@ export default class Window {
this.size = size
}
- public changeTitle(title: string) {
-
- const said = String(title ?? "").trim()
-
- if (!said) throw new Error("A window's title is something a person can read")
+ /** Validates and commits a complete geometry without an intermediate state. */
+ public setGeometry(geometry: WindowGeometry) {
- this.title = said
- }
+ validate(geometry.position.x, "x")
- public setSurface(value: unknown) {
+ validate(geometry.position.y, "y")
- const surface = validateSurface(value)
+ validate(geometry.size.width, "width")
- if (sameSurface(this.surface, surface)) return false
+ validate(geometry.size.height, "height")
- this.surface = surface
+ this.position = geometry.position
- return true
+ this.size = geometry.size
}
- public removeSurface() {
+ public changeTitle(title: string) {
- if (this.surface === null) return false
+ const said = String(title ?? "").trim()
- this.surface = null
+ if (!said) throw new Error("A window's title is something a person can read")
- return true
+ this.title = said
}
public toJSON() {
@@ -199,99 +191,11 @@ export default class Window {
depth: this.depth,
- minimized: this.minimized,
-
- surface: this.surface
+ minimized: this.minimized
}
}
}
-function validateSurface(value: unknown): WindowSurfaceSettings {
-
- if (value === undefined) return Object.freeze({})
-
- const record = plain(value, "Surface settings")
-
- fields(record, ["opacity", "radius", "transaction"], "Surface settings")
-
- const surface: { opacity?: number, radius?: ScaleLevel | number | "full", transaction?: WindowSurfaceTransaction } = {}
-
- if ("opacity" in record) {
-
- if (!finite(record.opacity) || record.opacity < 0 || record.opacity > 1) throw new Error("Surface opacity must be a finite number from 0 to 1")
-
- surface.opacity = record.opacity
- }
-
- if ("radius" in record) {
-
- if (record.radius !== "full" && !isScaleLevel(record.radius) && (!finite(record.radius) || record.radius < 0)) throw new Error('Surface radius must be a ScaleLevel, a finite nonnegative pixel number, or "full"')
-
- surface.radius = record.radius
- }
-
- if ("transaction" in record) surface.transaction = validateTransaction(record.transaction)
-
- return Object.freeze(surface)
-}
-
-function validateTransaction(value: unknown): WindowSurfaceTransaction {
-
- const record = plain(value, "Surface transaction")
-
- fields(record, ["duration", "easing"], "Surface transaction")
-
- const transaction: { duration?: number, easing?: WindowSurfaceEasing } = {}
-
- if ("duration" in record) {
-
- if (!finite(record.duration) || record.duration < 0 || record.duration > 60_000) throw new Error("Surface transaction duration must be finite milliseconds from 0 to 60000")
-
- transaction.duration = record.duration
- }
-
- if ("easing" in record) transaction.easing = validateEasing(record.easing)
-
- return Object.freeze(transaction)
-}
-
-function validateEasing(value: unknown): WindowSurfaceEasing {
-
- if (value === "linear" || value === "ease" || value === "ease-in" || value === "ease-out" || value === "ease-in-out") return value
-
- if (!Array.isArray(value) || value.length !== 4 || !value.every(finite) || value[0] < 0 || value[0] > 1 || value[2] < 0 || value[2] > 1) throw new Error("Surface transaction easing must be a standard easing name or four cubic Bézier numbers with x values from 0 to 1")
-
- return Object.freeze([...value]) as [number, number, number, number]
-}
-
-function plain(value: unknown, name: string): Record<string, unknown> {
-
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${name} must be an object`)
-
- const prototype = Object.getPrototypeOf(value)
-
- if (prototype !== Object.prototype && prototype !== null) throw new Error(`${name} must be an object`)
-
- return value as Record<string, unknown>
-}
-
-function fields(record: Record<string, unknown>, allowed: string[], name: string) {
-
- const unknown = Object.keys(record).find(field => !allowed.includes(field))
-
- if (unknown) throw new Error(`${name} has no "${unknown}" field`)
-}
-
-function finite(value: unknown): value is number {
-
- return typeof value === "number" && Number.isFinite(value)
-}
-
-function sameSurface(left: WindowSurfaceSettings | null, right: WindowSurfaceSettings) {
-
- return JSON.stringify(left) === JSON.stringify(right)
-}
-
// A value is pixels or one linear relative expression; anything else is
// refused where it is written, not where it is rendered.
function validate(value: Value, name: string) {