Skip to content

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

The System knows its identity and start time; open with and the opening dialog; startup set and remove; under and over drawings fix to the viewport or the plane, and the Desktop announces the plane's size; a Node connection closing mid-event no longer stops the System; Sprout wallpapers

zohayrslileh7ff535aec967
diff --git a/assets/bundled/dark-wallpaper.png b/assets/bundled/dark-wallpaper.png
deleted file mode 100644
index d847b30..0000000
Binary files a/assets/bundled/dark-wallpaper.png and /dev/null differ
diff --git a/assets/bundled/light-wallpaper.png b/assets/bundled/light-wallpaper.png
deleted file mode 100644
index 25c705c..0000000
Binary files a/assets/bundled/light-wallpaper.png and /dev/null differ
diff --git a/assets/bundled/seed-dark.webp b/assets/bundled/seed-dark.webp
new file mode 100644
index 0000000..bfd4085
Binary files /dev/null and b/assets/bundled/seed-dark.webp differ
diff --git a/assets/bundled/seed-light.webp b/assets/bundled/seed-light.webp
new file mode 100644
index 0000000..6504151
Binary files /dev/null and b/assets/bundled/seed-light.webp differ
diff --git a/assets/bundled/sprout-dark.webp b/assets/bundled/sprout-dark.webp
new file mode 100644
index 0000000..4affe5f
Binary files /dev/null and b/assets/bundled/sprout-dark.webp differ
diff --git a/assets/bundled/sprout-light.webp b/assets/bundled/sprout-light.webp
new file mode 100644
index 0000000..c1ffa2b
Binary files /dev/null and b/assets/bundled/sprout-light.webp differ
diff --git a/package.json b/package.json
index 3e4e403..f31023e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,5 @@
{
"name": "phreshos",
- "displayName": "PhreshOS",
"version": "0.1.108",
"description": "The PhreshOS server, desktop, and authoritative system runtime.",
"type": "module",
diff --git a/scripts/dev.ts b/scripts/dev.ts
index 2f22235..371c9d0 100644
--- a/scripts/dev.ts
+++ b/scripts/dev.ts
@@ -1,4 +1,4 @@
-import { displayName, name, version } from "@/package.json"
+import { name } from "@/package.json"
import doors from "@server/view/http/doors"
import view from "@server/view/view"
import { defaultHome, defaultHostname, defaultPorts, environmentHome, environmentHostname, environmentPorts } from "@server/view/configuration"
@@ -8,12 +8,6 @@ const home = environmentHome(name, process.env) ?? defaultHome(true)
const host = await view({
- name,
-
- displayName,
-
- version,
-
mode: "development",
hostname: environmentHostname(name, process.env) ?? defaultHostname(),
diff --git a/source/client/core/application.ts b/source/client/core/application.ts
index a101e33..ccb76c6 100644
--- a/source/client/core/application.ts
+++ b/source/client/core/application.ts
@@ -7,23 +7,11 @@ import type { FileStat, Upload } from "@phreshos/core"
export default class Application {
- public readonly name: string
-
- public readonly displayName: string
-
- public readonly version: string
-
public readonly doors: Doors
public readonly httpClient: HttpClient
- public constructor(name: string, displayName: string, version: string, doors: Doors) {
-
- this.name = name
-
- this.displayName = displayName
-
- this.version = version
+ public constructor(doors: Doors) {
this.doors = doors
diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.ts
index c312e4a..c75bf61 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -6,6 +6,7 @@ import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
import ShellManager from "./shell-manager"
import PermissionManager from "./permission-manager"
+import OpeningManager from "./opening-manager"
import StreamRelay from "@client/core/link-manager/stream-relay"
import { type StorageChange } from "@phreshos/core"
@@ -23,6 +24,8 @@ export default class AuthManager extends TheLink {
public readonly permissionManager: PermissionManager
+ public readonly openingManager: OpeningManager
+
public readonly shellManager: ShellManager
private readonly storageChanges = new StreamRelay("Storage changes", storageChange)
@@ -45,6 +48,8 @@ export default class AuthManager extends TheLink {
this.permissionManager = new PermissionManager(this, payload.permissionManager)
+ this.openingManager = new OpeningManager(this, payload.openingManager)
+
this.shellManager = new ShellManager(this)
}
@@ -131,6 +136,18 @@ export default class AuthManager extends TheLink {
return await this.$outbound.publishFirst("/permission/request", ...values)
}
+ /** Opens one target for a Client, as that Client's Process. */
+ public async open(process: string, target: unknown) {
+
+ await this.$outbound.publishFirst("/opening/open", process, target)
+ }
+
+ /** What a Client's Process was started to open, or null. */
+ public async opened(process: string) {
+
+ return await this.$outbound.publishFirst("/opening/opened", process)
+ }
+
public disconnect() {
this.disconnectFrom(this.linkManager, "/auth")
diff --git a/source/client/core/link-manager/auth-manager/opening-manager.ts b/source/client/core/link-manager/auth-manager/opening-manager.ts
new file mode 100644
index 0000000..003fb46
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/opening-manager.ts
@@ -0,0 +1,73 @@
+import type { OpenRequestSnapshot } from "@phreshos/core"
+import { Publish, Subscribe } from "@the-link/core/decorators"
+import { TheLink } from "@the-link/core"
+import type { OpeningManagerSnapshot } from "@server/core/opening-manager"
+import type AuthManager from "./auth-manager"
+
+/** Synchronized Desktop view of open requests waiting for the owner's choice. */
+export default class OpeningManager extends TheLink {
+
+ public readonly requests: Map<string, OpenRequestSnapshot>
+
+ public constructor(authManager: AuthManager, payload: OpeningManagerSnapshot) {
+
+ super()
+
+ this.requests = new Map(payload.requests)
+
+ this.connectTo(authManager, "/opening")
+ }
+
+ public list() {
+
+ return [...this.requests.values()]
+ }
+
+ public pending(identity: string) {
+
+ return this.requests.has(identity)
+ }
+
+ public async choose(identity: string, program: string, options?: Readonly<{ always?: boolean }>) {
+
+ await this.$outbound.publishFirst("/choose", identity, program, options)
+ }
+
+ public async cancel(identity: string) {
+
+ await this.$outbound.publishFirst("/cancel", identity)
+ }
+
+ public async defaults() {
+
+ return await this.$outbound.publishFirst("/defaults") as Readonly<Record<string, string>>
+ }
+
+ public async setDefault(type: unknown, program: unknown) {
+
+ await this.$outbound.publishFirst("/set-default", type, program)
+ }
+
+ public async clearDefault(type: unknown) {
+
+ await this.$outbound.publishFirst("/clear-default", type)
+ }
+
+ @Subscribe("/request")
+ @Publish("/requests", "inbound")
+ protected async requested(request: OpenRequestSnapshot) {
+
+ this.requests.set(request.identity, request)
+
+ return this.list()
+ }
+
+ @Subscribe("/resolve")
+ @Publish("/requests", "inbound")
+ protected async resolved(request: OpenRequestSnapshot, _program: string | null) {
+
+ this.requests.delete(request.identity)
+
+ return this.list()
+ }
+}
diff --git a/source/client/main.ts b/source/client/main.ts
index f0e6984..8b2a51e 100644
--- a/source/client/main.ts
+++ b/source/client/main.ts
@@ -1,5 +1,4 @@
-import { displayName, name, version } from "@/package.json"
import doors from "@server/view/http/doors"
import view from "./view/view"
-view({ name, displayName, version, doors, document })
+view({ doors, document })
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 0709204..e478eb4 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -16,6 +16,7 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
const programs = ReactTunnel.useFactory(authManager.programManager.$inbound)
const authentication = ReactTunnel.useFactory(authManager.$inbound)
const permissions = ReactTunnel.useFactory(authManager.permissionManager.$inbound)
+ const opening = ReactTunnel.useFactory(authManager.openingManager.$inbound)
const logs = ReactTunnel.useFactory(authManager.$inbound)
@@ -219,6 +220,17 @@ export default function useAnnouncements(authManager: AuthManager, panes: Map<st
postVisible(access => access.systemLogs(), "host-log", "log", "system", record)
}, [postVisible]))
+ // Open requests belong to whoever may decide them: frames with complete authority.
+ opening.useSubscribe("/request", useCallback((request: unknown) => {
+
+ postVisible(access => access.all(), "host-opening", "request", "system", request)
+ }, [postVisible]))
+
+ opening.useSubscribe("/resolve", useCallback((request: unknown, program: unknown) => {
+
+ postVisible(access => access.all(), "host-opening", "resolve", "system", request, program)
+ }, [postVisible]))
+
permissions.useSubscribe("/request", useCallback((request: unknown) => {
const program = permissionProgram(request)
diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.ts
index c5ef6b7..7063685 100644
--- a/source/client/view/components/desktop-host/client-host.ts
+++ b/source/client/view/components/desktop-host/client-host.ts
@@ -1,3 +1,4 @@
+import { planeSize } from "@client/view/components/window-manager/window-geometry"
import { ReactTunnel } from "@the-link/react"
import { type DesktopSize } from "@phreshos/core"
import useAnnouncements from "./announcements"
@@ -96,6 +97,9 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
for (const identity of sources.keys()) {
traffic.emit(identity, "host-desktop-viewport", "resize", size).catch(() => undefined)
+
+ // The plane grows and shrinks with the Desktop.
+ traffic.emit(identity, "host-desktop-plane", "resize", planeSize(size)).catch(() => undefined)
}
}
diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.ts
index 60767df..1b45b18 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -1097,6 +1097,8 @@ export default class ClientProcessBoundary extends TheLink {
if (drawing.interactive !== before.interactive) this.deliver("host-presentation", "changeInteractive", drawing.interactive).catch(() => undefined)
if (JSON.stringify(drawing.surface) !== JSON.stringify(before.surface)) this.deliver("host-presentation", "changeSurface", drawing.surface).catch(() => undefined)
+
+ if (drawing.anchor !== before.anchor) this.deliver("host-presentation", "changeAnchor", drawing.anchor).catch(() => undefined)
})
}
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index b675ba9..63a94fc 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -1,3 +1,5 @@
+import { planeSize } from "@client/view/components/window-manager/window-geometry"
+import { name, release, version } from "@/source/identity"
import {
type DesktopOffset,
type DesktopViewportState,
@@ -736,6 +738,56 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
)]
}
+ if (word === "about") return [Object.freeze({ name, version, release })]
+
+ if (word === "open") {
+
+ await authManager.open(pane, args[0])
+
+ return []
+ }
+
+ if (word === "opened") return [await authManager.opened(pane)]
+
+ if (word === "host-opening-requests") {
+
+ await access.requireAll()
+
+ return [authManager.openingManager.list()]
+ }
+
+ if (typeof word === "string" && word.startsWith("opening-request-")) {
+
+ await access.requireAll()
+
+ const operation = word.slice("opening-request-".length)
+ const identity = String(args[0])
+
+ if (operation === "pending") return [authManager.openingManager.pending(identity)]
+ if (operation === "choose") await authManager.openingManager.choose(identity, String(args[1]), args[2] as { always?: boolean } | undefined)
+ else if (operation === "cancel") await authManager.openingManager.cancel(identity)
+ else throw new Error(`The System does not know the OpenRequest operation "${operation}"`)
+
+ return []
+ }
+
+ if (word === "host-opening-defaults") {
+
+ await access.requireAll()
+
+ return [await authManager.openingManager.defaults()]
+ }
+
+ if (word === "host-opening-set-default" || word === "host-opening-clear-default") {
+
+ await access.requireAll()
+
+ if (word === "host-opening-set-default") await authManager.openingManager.setDefault(args[0], args[1])
+ else await authManager.openingManager.clearDefault(args[0])
+
+ return []
+ }
+
if (word === "host-permission-requests") {
await access.requireAll()
@@ -821,7 +873,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
const program = await permittedProgram(args[0])
const operation = String(args[1])
- const launch = operation === "enable" ? await access.launch(args[2]) : args[2]
+ const launch = operation === "set" ? await access.launch(args[2]) : args[2]
return [await programManager.startup(address(program), operation, launch)]
}
@@ -975,6 +1027,13 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
return []
}
+ if (word === "presentationAnchor") {
+ const target = presentationProcess(args[0])
+ if (args[1] !== "viewport" && args[1] !== "plane") throw new Error("A presentation anchor is \"viewport\" or \"plane\"")
+ presentation.setAnchor(target.identity, args[1])
+ return []
+ }
+
if (word === "presentationRaise") {
const target = presentationProcess(args[0])
@@ -1238,6 +1297,8 @@ export default function host(authManager: AuthManager, pane: string, viewport: D
// fact, and the gutter remains private desktop layout state.
if (word === "desktopViewport") return [viewport.state()]
+ if (word === "desktopPlane") return [planeSize(viewport.state().size)]
+
if (word === "moveDesktopViewport") {
await access.require("desktopViewport", [])
diff --git a/source/client/view/components/desktop-host/presentation.ts b/source/client/view/components/desktop-host/presentation.ts
index cd4e5e1..5d5b988 100644
--- a/source/client/view/components/desktop-host/presentation.ts
+++ b/source/client/view/components/desktop-host/presentation.ts
@@ -5,6 +5,7 @@ import {
type PresentationMoveGestureStart,
type PresentationMovePoint,
type PresentationGeometry,
+ type PresentationAnchor,
type PresentationPosition,
type PresentationSize,
type PresentationSurface,
@@ -45,6 +46,7 @@ export interface DesktopMoveGesture {
/** How one Client is actually drawn on this Desktop, as its presentation reads it. */
export type PresentationState = Readonly<{
layer: WindowLayer
+ anchor: PresentationAnchor
position: PresentationPosition
size: PresentationSize
front: boolean
@@ -66,6 +68,7 @@ export interface PresentationHost {
setGeometry(identity: string, geometry: PresentationGeometry, transaction?: PresentationTransactionRequest): Promise<void>
setSurface(identity: string, surface: PresentationSurface, transaction?: PresentationTransactionRequest): Promise<void>
setInteractive(identity: string, interactive: boolean): void
+ setAnchor(identity: string, anchor: PresentationAnchor): void
raise(identity: string): void
complete(identity: string, kind: "geometry" | "surface", revision: number): void
}
diff --git a/source/client/view/components/window-manager/presentations.ts b/source/client/view/components/window-manager/presentations.ts
index e05c4fd..e49399b 100644
--- a/source/client/view/components/window-manager/presentations.ts
+++ b/source/client/view/components/window-manager/presentations.ts
@@ -4,6 +4,7 @@ import type {
Size,
WindowGeometry,
WindowLayer,
+ PresentationAnchor,
PresentationGeometry,
PresentationPosition,
PresentationSize,
@@ -18,7 +19,7 @@ import type {
PresentationHost
} from "../desktop-host/presentation"
import { resolveWindowGeometry, type WindowRegion } from "./window-geometry"
-import { requireRawPresentation, requirePresentationMoveGesture } from "@shared/window-layers"
+import { requireRawPresentation, requirePresentationMoveGesture, requireAnchorable } from "@shared/window-layers"
export interface PresentationEntry {
identity: string
@@ -36,6 +37,8 @@ export interface PresentedWindow {
maximized: boolean
interactive: boolean
layer: WindowLayer
+ /** What the drawing is fixed to: its position is counted from the viewport's center or the plane's. */
+ anchor: PresentationAnchor
depth: number
surfaceAnimation: PresentationAnimation | null
geometryAnimation: PresentationAnimation | null
@@ -67,6 +70,8 @@ export default class Presentations implements PresentationHost {
private readonly watching = new Map<string, () => void>()
private fronts = 0
private revision = 0
+ /** How far this Desktop's view is moved across the plane, in pixels. */
+ private view = { x: 0, y: 0 }
private changed: (windows: ReadonlyMap<string, PresentedWindow>) => void = () => undefined
public constructor(initial: ReadonlyMap<string, PresentationEntry>, private readonly client: (process: string) => ClientState | null) {
@@ -134,6 +139,13 @@ export default class Presentations implements PresentationHost {
public projection(process: string) { return this.existing(process).state }
+ /** Where this Desktop looks on the plane, which drawings fixed to it are shown against. */
+ public follow(view: Readonly<{ x: number, y: number }>) {
+ if (view.x === this.view.x && view.y === this.view.y) return
+ this.view = { x: view.x, y: view.y }
+ this.notify()
+ }
+
/** Hears every change to what this Desktop draws, so a Client can learn how its own drawing changed. */
public observe(listener: () => void) {
this.observers.add(listener)
@@ -152,9 +164,12 @@ export default class Presentations implements PresentationHost {
const height = surface?.offsetHeight ?? 0
const box = this.representations.get(identity)?.read() ?? resolveWindowGeometry(state.position, state.size, { width, height })
const inside = offsetWithin(frame, "[data-window-box]")
+ // Counted from the center of what the drawing is fixed to: the viewport, or the plane.
+ const from = state.anchor === "plane" ? this.view : { x: 0, y: 0 }
return {
layer: state.layer,
- position: { x: box.x + inside.x - width / 2, y: box.y + inside.y - height / 2 },
+ anchor: state.anchor,
+ position: { x: box.x + inside.x - width / 2 + from.x, y: box.y + inside.y - height / 2 + from.y },
size: { width: frame.offsetWidth, height: frame.offsetHeight },
front: frontmost(this.windows, state.layer) === identity,
interactive: state.interactive,
@@ -278,6 +293,19 @@ export default class Presentations implements PresentationHost {
this.replace(identity, { ...state, interactive })
}
+ /**
+ * Fixes a drawing to the viewport or to the plane. It stays where it is in the viewport: its position
+ * is counted again from the center of what it is now fixed to, so nothing moves.
+ */
+ public setAnchor(process: string, anchor: PresentationAnchor) {
+ const { identity, state } = this.raw(process)
+ requireAnchorable(state.layer)
+ if (state.anchor === anchor) return
+ const shift = anchor === "plane" ? 1 : -1
+ const position = state.position as PresentationPosition
+ this.replace(identity, { ...state, anchor, position: { x: position.x + shift * this.view.x, y: position.y + shift * this.view.y } })
+ }
+
public raise(process: string) {
const { identity, state } = this.raw(process)
if (frontmost(this.windows, state.layer) === identity) return
@@ -451,6 +479,7 @@ function initialPresentationState(client: ClientState): PresentedWindow {
maximized: window.maximized,
interactive: true,
layer,
+ anchor: "plane",
depth: window.depth,
surfaceAnimation: null,
geometryAnimation: null,
@@ -466,6 +495,7 @@ function initialPresentationState(client: ClientState): PresentedWindow {
maximized: true,
interactive: true,
layer,
+ anchor: "viewport",
depth: 0,
surfaceAnimation: null,
geometryAnimation: null,
@@ -483,6 +513,7 @@ function initialPresentationState(client: ClientState): PresentedWindow {
maximized: false,
interactive: true,
layer,
+ anchor: "viewport",
depth: window.depth,
surfaceAnimation: null,
geometryAnimation: null,
diff --git a/source/client/view/components/window-manager/window-geometry.ts b/source/client/view/components/window-manager/window-geometry.ts
index 6596a53..2d96c97 100644
--- a/source/client/view/components/window-manager/window-geometry.ts
+++ b/source/client/view/components/window-manager/window-geometry.ts
@@ -64,6 +64,12 @@ export function resolveWindowGeometry(position: Position, size: Size, surface: W
/** How many whole views the plane of standard Windows reaches from its center, in each direction. */
export const planeReach = 2
+/** The plane of standard Windows: as many views across and down as the view reaches on both sides, and its own. */
+export function planeSize(desktop: Readonly<{ width: number, height: number }>) {
+ const views = planeReach * 2 + 1
+ return { width: desktop.width * views, height: desktop.height * views }
+}
+
/** The largest a standard Window is shown, in views, in each dimension. */
export const largestWindowViews = 2
diff --git a/source/client/view/structure/authentication/authentication.tsx b/source/client/view/structure/authentication/authentication.tsx
index f3020c2..7dfadda 100644
--- a/source/client/view/structure/authentication/authentication.tsx
+++ b/source/client/view/structure/authentication/authentication.tsx
@@ -87,9 +87,9 @@ export default function () {
{sessionAuthenticate.solve.authentication.signedUp
- ? <WallpaperStage file={signInWallpaper}><SignIn /></WallpaperStage>
+ ? <WallpaperStage place="signIn" file={signInWallpaper}><SignIn /></WallpaperStage>
- : <WallpaperStage file={signInWallpaper}>
+ : <WallpaperStage place="signIn" file={signInWallpaper}>
<SignUp state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} />
diff --git a/source/client/view/structure/authentication/credentials-form.tsx b/source/client/view/structure/authentication/credentials-form.tsx
index 2331aef..9862712 100644
--- a/source/client/view/structure/authentication/credentials-form.tsx
+++ b/source/client/view/structure/authentication/credentials-form.tsx
@@ -5,15 +5,14 @@ import { motion } from "motion/react"
import { Button, Heading, Input, resolveSpacing, Surface, Text, useAppearance } from "@phreshos/react-ui"
import Alert from "../../components/alert"
import { useId, useState, type SyntheticEvent } from "react"
-import { ApplicationContext } from "../../contexts"
import logo from "@/assets/bundled/logo.png"
+import { name, version } from "@/source/identity"
/** The common username-and-password welcome for sign-up and sign-in: the first thing a System shows. */
export default function CredentialsForm({ title, description, submitLabel, passwordAutocomplete, requirements, error, pending, onEdit, onSubmit }: CredentialsFormProps) {
const reducedMotion = useReducedMotion()
const { transaction, spacing } = useAppearance()
- const application = ApplicationContext.useValue()
const [password, setPassword] = useState("")
const titleId = useId()
const passwordReady = requirements === undefined || [...password].length >= requirements.password.minimumLength
@@ -140,9 +139,9 @@ export default function CredentialsForm({ title, description, submitLabel, passw
>{pending ? `${submitLabel}…` : submitLabel}</Button>
- <Text size="small" tone="secondary" className="text-center select-none tabular-nums" aria-label={`${application.displayName} version ${application.version}`}>
+ <Text size="small" tone="secondary" className="text-center select-none tabular-nums" aria-label={`${name} version ${version}`}>
- {application.displayName} {application.version}
+ {name} {version}
</Text>
diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsx
index 0e00feb..9f99267 100644
--- a/source/client/view/structure/desktop/desktop.tsx
+++ b/source/client/view/structure/desktop/desktop.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
import { ApplicationContext, AuthManagerContext, LinkManagerContext } from "../../contexts"
import useClientHost from "../../components/desktop-host/client-host"
import DesktopLayers, { desktopMargins } from "./layers/desktop-layers"
@@ -21,7 +21,7 @@ import { LaunchPlacementContext, type LaunchPlacement } from "./launch-placement
import { boundedGeometry, planeGeometry, recordedPosition, resolveWindowGeometry, shiftPosition, viewOfGeometry, type WindowRegion } from "@client/view/components/window-manager/window-geometry"
import { type MappedWindow } from "./layers/shell/taskbar/viewport/viewport-control"
import type Process from "@client/core/link-manager/auth-manager/process-manager/process"
-import { type Layer, type Position, type Size } from "@phreshos/core"
+import { type Layer, type Position, type PresentationAnchor, type Size } from "@phreshos/core"
export default function Workspace() {
@@ -80,6 +80,15 @@ export default function Workspace() {
// Recorded in views, so a Window stays in its view on a Desktop of any size.
const back = { x: views.x, y: views.y }
+ // Drawings fixed to the plane are shown against where this Desktop looks, in pixels.
+ useLayoutEffect(() => windows.presentation.follow(offset), [windows.presentation, offset.x, offset.y])
+
+ /** Where a raw drawing is shown: fixed to the viewport as written, or fixed to the plane and moved by the viewport. */
+ function shownRaw(position: Position, anchor: PresentationAnchor): Position {
+ if (anchor === "viewport" || typeof position.x !== "number" || typeof position.y !== "number") return position
+ return { x: position.x - offset.x, y: position.y - offset.y }
+ }
+
// Standard Windows measure in the whole Desktop; the space they keep from its edges is painted.
const margins = useMemo(() => desktopMargins(appearance.spacing, appearance.taskbar), [appearance.spacing, appearance.taskbar])
@@ -118,13 +127,18 @@ export default function Workspace() {
const move = useCallback(function (record: Process, x: number, y: number) {
// A raw drawing moved by hand stays this Desktop's drawing; only a standard Window's place is the System's.
- if (windows.presentation.projection(record.identity).layer !== "window") return windows.presentation.move(record.identity, { x, y }).then(() => true)
+ // One fixed to the plane is written where it is on the plane.
+ const drawn = windows.presentation.projection(record.identity)
+ if (drawn.layer !== "window") {
+ const from = drawn.anchor === "plane" ? offset : { x: 0, y: 0 }
+ return windows.presentation.move(record.identity, { x: x + from.x, y: y + from.y }).then(() => true)
+ }
const recorded = shiftPosition({ x, y }, back)
return windows.move(record, recorded.x, recorded.y)
- }, [windows.move, windows.presentation, back.x, back.y])
+ }, [windows.move, windows.presentation, back.x, back.y, offset.x, offset.y])
const resize = useCallback((record: Process, width: number, height: number, position: { x: number, y: number } | null) => windows.resize(record, width, height, position && shiftPosition(position, back)), [windows.resize, back.x, back.y])
@@ -202,7 +216,7 @@ export default function Workspace() {
icon={icon(record)}
- position={presentation.layer === "window" ? shownPosition(bounded.position) : presentation.position}
+ position={presentation.layer === "window" ? shownPosition(bounded.position) : shownRaw(presentation.position, presentation.anchor)}
size={presentation.layer === "window" ? bounded.size : presentation.size}
@@ -454,7 +468,7 @@ export default function Workspace() {
const wallpaper = hasWallpaperClient
? renderWindows("wallpaper")
- : <WallpaperBackground file={desktopWallpaper} onReady={fileWallpaperLoaded} />
+ : <WallpaperBackground place="desktop" file={desktopWallpaper} onReady={fileWallpaperLoaded} />
const shell = hasShellClient
? renderWindows("shell")
diff --git a/source/client/view/structure/desktop/layers/shell/default-shell.tsx b/source/client/view/structure/desktop/layers/shell/default-shell.tsx
index 9ceebd7..7b6b2d4 100644
--- a/source/client/view/structure/desktop/layers/shell/default-shell.tsx
+++ b/source/client/view/structure/desktop/layers/shell/default-shell.tsx
@@ -2,6 +2,7 @@ import { type AppearanceTaskbar } from "@phreshos/core"
import { useState, type ReactNode } from "react"
import SystemErrors from "./dialogs/system-errors"
import PermissionRequests from "./dialogs/permission-requests"
+import OpenRequests from "./dialogs/open-requests"
import StartMenu, { StartMenuButton, StartMenuProvider, useStartMenuOpen } from "./start-menu/start-menu"
import SignOut from "./taskbar/sign-out"
import Taskbar from "./taskbar/taskbar"
@@ -35,6 +36,8 @@ export default function DefaultShell({ spacing, taskbar, viewport, mappedWindows
<PermissionRequests />
+ <OpenRequests />
+
</>
}
diff --git a/source/client/view/structure/desktop/layers/shell/dialogs/open-requests.tsx b/source/client/view/structure/desktop/layers/shell/dialogs/open-requests.tsx
new file mode 100644
index 0000000..906e601
--- /dev/null
+++ b/source/client/view/structure/desktop/layers/shell/dialogs/open-requests.tsx
@@ -0,0 +1,102 @@
+import type { OpenRequestSnapshot } from "@phreshos/core"
+import { ReactTunnel } from "@the-link/react"
+import { surfaceLifecyclePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
+import { useReducedMotion } from "@libs/react-motion"
+import { motion } from "motion/react"
+import { useEffect, useId, useRef, useState } from "react"
+import { ApplicationContext, AuthManagerContext } from "@client/view/contexts"
+import ShellSurface, { shellSurfaceClassName } from "../shell-surface"
+import usePromise from "@libs/react-promise"
+import Alert from "@client/view/components/alert"
+import usePrograms from "@client/view/structure/desktop/programs/programs"
+import programIcon from "@client/view/structure/desktop/programs/program-icon"
+import { Button, Checkbox, Text, useAppearance, useScale } from "@phreshos/react-ui"
+
+/** The default Shell's choice of a Program for something that has no default one. */
+export default function OpenRequests() {
+
+ const manager = AuthManagerContext.useValue().openingManager
+ const inbound = ReactTunnel.useFactory(manager.$inbound)
+ const requests = inbound.useFirstState("/requests", manager.list())
+ const request = requests[0]
+ const surface = useRef<HTMLDialogElement>(null)
+ const title = useId()
+ const reducedMotion = useReducedMotion()
+ const transaction = useAppearance().transaction
+
+ useEffect(() => {
+
+ const element = surface.current
+
+ if (!request || !element || element.open) return
+
+ element.showModal()
+
+ return () => { if (element.open) element.close() }
+ }, [request?.identity])
+
+ if (!request) return null
+
+ return <motion.dialog
+ ref={surface}
+ aria-modal="true"
+ aria-labelledby={title}
+ initial={reducedMotion ? surfaceLifecyclePose.visible : surfaceLifecyclePose.hidden}
+ animate={surfaceLifecyclePose.visible}
+ transition={surfacePresenceTransition(reducedMotion, transaction)}
+ onCancel={event => { event.preventDefault(); void manager.cancel(request.identity).catch(() => undefined) }}
+ className={`${shellSurfaceClassName} pointer-events-auto fixed inset-0 m-auto h-fit w-[min(24rem,calc(100vw-var(--desktop-gutter)*2))] backdrop:bg-transparent`}
+ >
+ <ShellSurface material="full" label="Open with" labelId={title}>
+ <OpenRequestView key={request.identity} request={request} />
+ </ShellSurface>
+ </motion.dialog>
+}
+
+function OpenRequestView({ request }: Readonly<{ request: OpenRequestSnapshot }>) {
+
+ const manager = AuthManagerContext.useValue().openingManager
+ const application = ApplicationContext.useValue()
+ const space = useScale(useAppearance().spacing)
+ const installed = usePrograms()
+ const [always, setAlways] = useState(false)
+ const decision = usePromise((program: string | null) => program === null
+ ? manager.cancel(request.identity)
+ : manager.choose(request.identity, program, { always }))
+ const programs = request.programs.map(offered => installed.find(program => program.identity === offered.identity)).filter(program => program !== undefined)
+
+ return <div className="grid" style={{ gap: space.medium }}>
+
+ <div className="grid" style={{ gap: space.xsmall }}>
+ <span className="truncate" title={request.target.uri}><Text style={{ fontWeight: 500 }}>{describe(request.target.uri)}</Text></span>
+ <Text tone="secondary" size="small">{request.from ? `${request.from.process.program.name} asks to open it` : "Opened from outside the Desktop"} · {request.target.type}</Text>
+ </div>
+
+ <div className="grid" style={{ gap: space.xsmall }}>
+ {programs.map(program => <Button key={program.identity} disabled={decision.isPending} onPress={() => decision.safeExecute(program.identity)}
+ style={{ justifyContent: "flex-start" }}>
+ <img src={programIcon(application.doors.program, program.assetId)} alt="" draggable={false} className="shrink-0 object-contain" style={{ width: space.large, height: space.large }} />
+ {program.name}
+ </Button>)}
+ </div>
+
+ <Checkbox size="small" checked={always} onChange={setAlways} label={`Always open ${request.target.type} with it`} />
+
+ <div className="flex justify-end">
+ <Button size="small" autoFocus disabled={decision.isPending} onPress={() => decision.safeExecute(null)}>Cancel</Button>
+ </div>
+
+ {decision.exception && <Alert className="text-sm">{String(decision.exception.current)}</Alert>}
+ </div>
+}
+
+/** A short name for what is being opened: a file's name, or the address itself. */
+function describe(uri: string) {
+
+ try {
+ const url = new URL(uri)
+ if (url.protocol === "file:") return decodeURIComponent(url.pathname.split("/").filter(Boolean).at(-1) ?? url.pathname)
+ return uri
+ }
+ catch { return uri }
+}
diff --git a/source/client/view/structure/desktop/layers/shell/start-menu/start-menu-panel.tsx b/source/client/view/structure/desktop/layers/shell/start-menu/start-menu-panel.tsx
index 7eadc6e..24196dd 100644
--- a/source/client/view/structure/desktop/layers/shell/start-menu/start-menu-panel.tsx
+++ b/source/client/view/structure/desktop/layers/shell/start-menu/start-menu-panel.tsx
@@ -9,6 +9,7 @@ import Processes from "./processes/processes"
import { categories, categoryIcon, categoryOf } from "./programs/categories"
import { matchesProcess, matchesProgram, searchTerms } from "./search"
import useLive from "./live"
+import { name, version } from "@/source/identity"
import type Program from "@client/core/link-manager/auth-manager/program-manager/program"
type Show = "programs" | "processes"
@@ -21,10 +22,8 @@ const all = "every-category"
* chooses between the Programs and the Processes and among the Programs' categories; beside it, the
* search and the way the Programs are shown, the list recessed below them, and a status line under it.
*/
-export default function StartMenuPanel({ labelId, name, version, onChoose }: Readonly<{
+export default function StartMenuPanel({ labelId, onChoose }: Readonly<{
labelId: string
- name: string
- version: string
/** Called when a Program is chosen, before it opens. */
onChoose: () => void
}>) {
diff --git a/source/client/view/structure/desktop/layers/shell/start-menu/start-menu.tsx b/source/client/view/structure/desktop/layers/shell/start-menu/start-menu.tsx
index 0d7d989..da861f1 100644
--- a/source/client/view/structure/desktop/layers/shell/start-menu/start-menu.tsx
+++ b/source/client/view/structure/desktop/layers/shell/start-menu/start-menu.tsx
@@ -1,7 +1,7 @@
import PhreshOSIcon from "@client/view/components/phreshos-icon"
import { createContext, memo, useCallback, useContext, useEffect, useId, useRef, useState, type CSSProperties, type PropsWithChildren, type RefObject } from "react"
import StartMenuPanel from "./start-menu-panel"
-import { ApplicationContext } from "@client/view/contexts"
+import { name } from "@/source/identity"
import { type AppearanceTaskbar } from "@phreshos/core"
import { useReducedMotion } from "@libs/react-motion"
import { motion } from "motion/react"
@@ -84,20 +84,18 @@ export function StartMenuProvider({ taskbar, spacing, children }: PropsWithChild
/** The Start Menu's Taskbar-owned anchor and toggle. */
export const StartMenuButton = memo(function StartMenuButton({ showLabel = true }: Readonly<{ showLabel?: boolean }>) {
- const application = ApplicationContext.useValue()
-
const control = useStartMenuControl()
return <TaskbarButton
icon={<PhreshOSIcon className="block size-full" />}
- label={application.displayName}
+ label={name}
showLabel={showLabel}
color="default:base"
material="extended"
aria-controls={control.id}
aria-expanded={control.open}
aria-haspopup="dialog"
- aria-label={application.displayName}
+ aria-label={name}
onPressStart={control.beginToggle}
onPress={control.toggle}
/>
@@ -106,8 +104,6 @@ export const StartMenuButton = memo(function StartMenuButton({ showLabel = true
/** Independent Start Menu surface in the default Shell. */
export default memo(function StartMenu() {
- const application = ApplicationContext.useValue()
-
const control = useStartMenuControl()
const reducedMotion = useReducedMotion()
@@ -148,8 +144,6 @@ export default memo(function StartMenu() {
<StartMenuPanel
labelId={`${control.id}-label`}
- name={application.displayName}
- version={application.version}
onChoose={control.close}
/>
diff --git a/source/client/view/structure/desktop/layers/wallpaper/wallpaper.tsx b/source/client/view/structure/desktop/layers/wallpaper/wallpaper.tsx
index 1864ca8..72fab45 100644
--- a/source/client/view/structure/desktop/layers/wallpaper/wallpaper.tsx
+++ b/source/client/view/structure/desktop/layers/wallpaper/wallpaper.tsx
@@ -1,5 +1,7 @@
-import darkWallpaper from "@/assets/bundled/dark-wallpaper.png"
-import lightWallpaper from "@/assets/bundled/light-wallpaper.png"
+import seedDark from "@/assets/bundled/seed-dark.webp"
+import seedLight from "@/assets/bundled/seed-light.webp"
+import sproutDark from "@/assets/bundled/sprout-dark.webp"
+import sproutLight from "@/assets/bundled/sprout-light.webp"
import { ApplicationContext } from "@client/view/contexts"
import { useEffect, useEffectEvent, useRef, useState, type ReactNode, type TransitionEvent } from "react"
import Loading from "@client/view/components/loading"
@@ -10,7 +12,17 @@ import { useReducedMotion } from "@libs/react-motion"
import { cssEasing } from "@client/view/appearance/motion"
import { wallpaperKind, type WallpaperKind } from "@shared/wallpaper"
-const bundledWallpapers = [darkWallpaper, lightWallpaper] as const
+/** Where a wallpaper is shown. */
+export type WallpaperPlace = "signIn" | "desktop"
+
+/**
+ * What each place shows until its owner chooses a wallpaper: the seed before you sign in, and the
+ * release's own wallpaper once you are in. Both follow the theme.
+ */
+const bundledWallpapers: Readonly<Record<WallpaperPlace, Readonly<Record<"light" | "dark", string>>>> = {
+ signIn: { light: seedLight, dark: seedDark },
+ desktop: { light: sproutLight, dark: sproutDark }
+}
type WallpaperSource = Readonly<{
identity: string
@@ -25,11 +37,11 @@ type WallpaperLayers = Readonly<{
}>
/** Displays one completely loaded wallpaper source. */
-export function WallpaperBackground({ file, onReady }: WallpaperBackgroundProps) {
+export function WallpaperBackground({ place, file, onReady }: WallpaperBackgroundProps) {
const application = ApplicationContext.useValue()
const { theme } = usePreferences()
const reducedMotion = useReducedMotion()
- const desired = resolveWallpaper(file, theme, application.doors.uploads)
+ const desired = resolveWallpaper(place, file, theme, application.doors.uploads)
const [layers, setLayers] = useState<WallpaperLayers>({
displayed: null,
incoming: desired,
@@ -43,11 +55,12 @@ export function WallpaperBackground({ file, onReady }: WallpaperBackgroundProps)
const ready = useEffectEvent(() => onReady?.())
useEffect(() => {
- for (const wallpaper of bundledWallpapers) {
+ // Both themes of this place's default, so a change of theme shows at once.
+ for (const wallpaper of Object.values(bundledWallpapers[place])) {
const image = new Image()
image.src = wallpaper
}
- }, [])
+ }, [place])
useEffect(() => {
cancelSwitch(frame)
@@ -176,12 +189,8 @@ function WallpaperLayer({ source, visible, onLoad, onError, onTransitionEnd }: R
</div>
}
-function resolveWallpaper(file: string | null, theme: "light" | "dark", uploads: string): WallpaperSource {
- if (file === null) {
- const url = theme === "dark" ? darkWallpaper : lightWallpaper
-
- return { identity: `bundled:${theme}`, kind: "image", url }
- }
+function resolveWallpaper(place: WallpaperPlace, file: string | null, theme: "light" | "dark", uploads: string): WallpaperSource {
+ if (file === null) return { identity: `bundled:${place}:${theme}`, kind: "image", url: bundledWallpapers[place][theme] }
const kind = wallpaperKind(file) ?? "image"
const path = kind === "html" ? `${uploads}/wallpaper/${encodeURIComponent(file)}` : `${uploads}/${encodeURIComponent(file)}`
@@ -197,12 +206,12 @@ function cancelSwitch(frame: { current: number | null }) {
}
/** A complete surface whose content sits above one file-backed wallpaper. */
-export function WallpaperStage({ file, children }: WallpaperStageProps) {
+export function WallpaperStage({ place, file, children }: WallpaperStageProps) {
const [readyFile, setReadyFile] = useState<string | null>()
const ready = readyFile === file
return <div className="relative isolate grid min-h-0">
- <WallpaperBackground file={file} onReady={() => setReadyFile(file)} />
+ <WallpaperBackground place={place} file={file} onReady={() => setReadyFile(file)} />
<div className="pointer-events-none relative z-1 grid min-h-0">
{children}
@@ -220,11 +229,13 @@ export function ReadyWallpaper() {
}
interface WallpaperStageProps {
+ place: WallpaperPlace
file: string | null
children: ReactNode
}
interface WallpaperBackgroundProps {
+ place: WallpaperPlace
file: string | null
onReady?: () => void
}
diff --git a/source/client/view/view.tsx b/source/client/view/view.tsx
index 8df97ec..c4ba816 100644
--- a/source/client/view/view.tsx
+++ b/source/client/view/view.tsx
@@ -4,10 +4,11 @@ import { ApplicationContext } from "./contexts"
import Structure from "./structure/structure"
import client from "react-dom/client"
import logo from "@/assets/bundled/logo.png"
+import { name, version } from "@/source/identity"
export default function (config: Config) {
- config.document.title = `${config.displayName} v${config.version}`
+ config.document.title = `${name} v${version}`
const link = config.document.createElement("link")
@@ -17,7 +18,7 @@ export default function (config: Config) {
config.document.head.appendChild(link)
- const application = new Application(config.name, config.displayName, config.version, config.doors)
+ const application = new Application(config.doors)
const root = client.createRoot(config.document.body)
@@ -36,11 +37,5 @@ export interface Config {
doors: Doors
- name: string
-
- displayName: string
-
- version: string
-
document: Document
}
diff --git a/source/identity.ts b/source/identity.ts
new file mode 100644
index 0000000..320fb20
--- /dev/null
+++ b/source/identity.ts
@@ -0,0 +1,13 @@
+import { version } from "@/package.json"
+
+/** How PhreshOS names itself to people. */
+export const name = "PhreshOS"
+
+/** The version, as package.json holds it: a release bumps it there, and nowhere else. */
+export { version }
+
+/**
+ * The name of this major version, and the Program that looks after it: it receives the owner when the
+ * System is installed or upgraded to this version, and follows the System until the next one.
+ */
+export const release = Object.freeze({ name: "Sprout", program: "sprout" })
diff --git a/source/server/core/application.ts b/source/server/core/application.ts
index 206fde7..4f14a83 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -13,12 +13,6 @@ import SystemLogs from "./logs"
export default class Application {
- public readonly name: string
-
- public readonly displayName: string
-
- public readonly version: string
-
/** Filesystem-owned fallback used by the authoritative Program icon service. */
public readonly defaultProgramIcon: string
@@ -49,12 +43,6 @@ export default class Application {
private constructor(payload: ApplicationPayload) {
- this.name = payload.name
-
- this.displayName = payload.displayName
-
- this.version = payload.version
-
this.defaultProgramIcon = payload.defaultProgramIcon
this.storage = payload.storage
@@ -78,7 +66,7 @@ export default class Application {
this.system = new System(this)
}
- public static async initialize(name: string, displayName: string, version: string, homePath: string, defaultProgramIcon: string) {
+ public static async initialize(homePath: string, defaultProgramIcon: string) {
const storage = new FileManager(homePath)
@@ -92,7 +80,7 @@ export default class Application {
const appearanceManager = await AppearanceManager.open(store, uploads)
- const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, authentication, appearanceManager, uploads })
+ const application = new Application({ defaultProgramIcon, storage, home, store, authentication, appearanceManager, uploads })
await application.linkManager.authManager.programManager.initialize()
@@ -102,12 +90,6 @@ export default class Application {
interface ApplicationPayload {
- name: string
-
- displayName: string
-
- version: string
-
defaultProgramIcon: string
storage: FileManager
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
index 196004a..792f059 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -7,6 +7,7 @@ import LinkManager from "../link-manager"
import { parsePermissionName, type PermissionRequestInput } from "@phreshos/core"
import ShellManager from "./shell-manager"
import PermissionManager from "../../permission-manager"
+import OpeningManager from "../../opening-manager"
export default class AuthManager extends TheLink {
@@ -20,6 +21,8 @@ export default class AuthManager extends TheLink {
public readonly permissionManager: PermissionManager
+ public readonly openingManager: OpeningManager
+
public readonly shellManager: ShellManager
public constructor(linkManager: LinkManager) {
@@ -30,6 +33,8 @@ export default class AuthManager extends TheLink {
this.permissionManager = new PermissionManager(this)
+ this.openingManager = new OpeningManager(this)
+
this.programManager = new ProgramManager(this)
this.processManager = new ProcessManager(this)
@@ -224,6 +229,40 @@ export default class AuthManager extends TheLink {
return this.uploads.stat(String(file))
}
+ @Subscribe("/about")
+ protected about() {
+
+ return this.linkManager.application.system.about()
+ }
+
+ /** A Client's request to open something, forwarded by the Desktop showing it. */
+ @Subscribe("/opening/open")
+ protected async openForClient(process: unknown, target: unknown) {
+
+ if (typeof process !== "string") throw new Error("An open request is invalid")
+
+ const held = this.processManager.processes.get(process)
+
+ if (!held) throw new Error("The Process that asked has exited")
+
+ await this.openingManager.open(target, { process: held, endpoint: "client" })
+ }
+
+ @Subscribe("/opening/opened")
+ protected openedForClient(process: unknown) {
+
+ if (typeof process !== "string") throw new Error("An opened read is invalid")
+
+ return this.processManager.processes.get(process)?.opened ?? null
+ }
+
+ /** The owner opens something from outside, such as a Node script. */
+ @Subscribe("/open")
+ protected async openForOwner(target: unknown) {
+
+ await this.openingManager.open(target, null, this.linkManager.connection().signal)
+ }
+
@Subscribe("/appearance/update")
protected async changeAppearance(value: unknown) {
@@ -435,15 +474,14 @@ export default class AuthManager extends TheLink {
await connection.link.$outbound.publish(`/auth${event}`, ...values)
}
+ // Each boundary receives on its own: one that disconnects while an event is on its way receives
+ // nothing more, and neither stops the others nor fails the event.
@Forward("outbound", undefined, "/auth")
protected async broadcastToAuthorizedBoundaries(event: string, ...values: unknown[]) {
- for (const connection of this.linkManager.boundaries.values()) {
-
- if (!connection.external && !connection.session) continue
-
- await connection.link.$outbound.publish(event, ...values)
- }
+ await Promise.allSettled([...this.linkManager.boundaries.values()]
+ .filter(connection => connection.external || connection.session)
+ .map(connection => connection.link.$outbound.publish(event, ...values)))
}
public toJSON() {
@@ -456,7 +494,9 @@ export default class AuthManager extends TheLink {
processManager: this.processManager,
- permissionManager: this.permissionManager
+ permissionManager: this.permissionManager,
+
+ openingManager: this.openingManager
}
}
}
@@ -512,4 +552,5 @@ export interface AuthManagerSnapshot {
processManager: import("./process-manager/process-manager").ProcessManagerSnapshot
permissionManager: import("../../permission-manager").PermissionManagerSnapshot
+ openingManager: import("../../opening-manager").OpeningManagerSnapshot
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
index 0b7b112..1c13890 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
@@ -50,4 +50,4 @@ type Subscriber = (delivery: object, event: string, ...values: unknown[]) => unk
export type HostDomain = Domain
-type Domain = "program" | "process" | "window" | "connection" | "session" | "service" | "permission" | "log" | "programLog" | "clientMemory"
+type Domain = "program" | "process" | "window" | "connection" | "session" | "service" | "permission" | "opening" | "log" | "programLog" | "clientMemory"
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 9385c33..b66009e 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
@@ -983,13 +983,13 @@ export default class ProcessManager extends TheLink {
return server
}
- private serverHostVisible(process: Process, domain: "program" | "process" | "connection" | "session" | "service" | "window" | "permission" | "log" | "programLog" | "clientMemory", subject: string | null) {
+ private serverHostVisible(process: Process, domain: "program" | "process" | "connection" | "session" | "service" | "window" | "permission" | "opening" | "log" | "programLog" | "clientMemory", subject: string | null) {
const access = new SystemAccess(this, process)
if (domain === "connection" || domain === "session") return access.canAuthentication()
- if (domain === "permission") return access.all()
+ if (domain === "permission" || domain === "opening") return access.all()
if (domain === "log") return this.grants(process.identity, "logs", [])
@@ -1764,13 +1764,13 @@ export default class ProcessManager extends TheLink {
}
/** Announces one fact only through an authoritative Host registry. */
- public async announceHost(domain: "program" | "process" | "connection" | "session" | "service" | "permission" | "log" | "programLog", event: string, subject: string, ...values: unknown[]) {
+ public async announceHost(domain: "program" | "process" | "connection" | "session" | "service" | "permission" | "opening" | "log" | "programLog", event: string, subject: string, ...values: unknown[]) {
await this.hostTraffic.emitHost(domain, event, subject, ...values)
}
/** Announces one fact only to observers of an exact Program or Process subject. */
- public async announceSubject(domain: "program" | "process" | "connection" | "session" | "service" | "permission" | "log" | "programLog", event: string, subject: string, ...values: unknown[]) {
+ public async announceSubject(domain: "program" | "process" | "connection" | "session" | "service" | "permission" | "opening" | "log" | "programLog", event: string, subject: string, ...values: unknown[]) {
await this.hostTraffic.emitSubject(domain, event, subject, ...values)
}
@@ -1994,6 +1994,53 @@ export default class ProcessManager extends TheLink {
)]
}
+ if (word === "open") {
+
+ await this.authManager.openingManager.open(rest[0], { process, endpoint: "server" })
+
+ return []
+ }
+
+ if (word === "opened") return [process.opened]
+
+ if (word === "host-opening-requests") {
+
+ access.requireAll()
+
+ return [this.authManager.openingManager.requests()]
+ }
+
+ if (typeof word === "string" && word.startsWith("opening-request-")) {
+
+ access.requireAll()
+
+ const operation = word.slice("opening-request-".length)
+
+ if (operation === "pending") return [this.authManager.openingManager.pending(String(rest[0]))]
+ if (operation === "choose") await this.authManager.openingManager.choose(rest[0], rest[1], rest[2])
+ else if (operation === "cancel") await this.authManager.openingManager.cancel(rest[0])
+ else throw new Error(`The System does not know the OpenRequest operation "${operation}"`)
+
+ return []
+ }
+
+ if (word === "host-opening-defaults") {
+
+ access.requireAll()
+
+ return [await this.authManager.openingManager.defaults()]
+ }
+
+ if (word === "host-opening-set-default" || word === "host-opening-clear-default") {
+
+ access.requireAll()
+
+ if (word === "host-opening-set-default") await this.authManager.openingManager.setDefault(rest[0], rest[1])
+ else await this.authManager.openingManager.clearDefault(rest[0])
+
+ return []
+ }
+
if (word === "host-permission-requests") {
access.requireAll()
@@ -2076,7 +2123,7 @@ export default class ProcessManager extends TheLink {
const program = heldProgram(rest[0])
- const value = rest[1] === "enable" ? access.launch(rest[2]) : rest[2]
+ const value = rest[1] === "set" ? access.launch(rest[2]) : rest[2]
return [await this.system.programStartup(program, String(rest[1]), value)]
}
@@ -2129,6 +2176,8 @@ export default class ProcessManager extends TheLink {
return [this.system.requireProgram(created.identity)]
}
+ if (word === "about") return [this.system.about()]
+
if (word === "appearance") return [this.system.appearance]
if (word === "update-appearance") {
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 f8225d2..964f9a9 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
@@ -1,3 +1,4 @@
+import type { OpenTarget } from "@phreshos/core"
import { Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
import Window, { Position, Size } from "./window"
@@ -93,6 +94,9 @@ export default class Process {
private exitProcess: (() => Promise<unknown>) | null = null
+ /** What this Process was started to open, set before either Endpoint runs; `null` when it was not. */
+ public opened: OpenTarget | null = null
+
public constructor(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, parent: Process | null, hostTraffic: HostTraffic, window: Window | null = null) {
this.identity = identity
diff --git a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
index 96177d7..86b0cc6 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
@@ -373,6 +373,7 @@ export default class ServerProcessBoundary extends TheLink {
: route === "host-session" || route === "session-host" ? "session"
: route === "host-service" || route === "service-host" ? "service"
: route === "host-permission" || route === "permission-host" ? "permission"
+ : route === "host-opening" || route === "opening-host" ? "opening"
: route === "host-log" ? "log"
: route === "program-log" ? "programLog"
: route === "host-client-memory" ? "clientMemory"
@@ -539,4 +540,4 @@ export type { Stream } from "@server/core/server-runtime"
export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void
-export type HostVisibility = (domain: "program" | "process" | "connection" | "session" | "service" | "window" | "permission" | "log" | "programLog" | "clientMemory", subject: string | null) => boolean
+export type HostVisibility = (domain: "program" | "process" | "connection" | "session" | "service" | "window" | "permission" | "opening" | "log" | "programLog" | "clientMemory", subject: string | null) => boolean
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 70a5137..127d5cc 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -11,6 +11,7 @@ import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
import { isValue, layers } from "./config"
import { parseLaunch, parseProgramDefinition, parseProgramInstallOptions, parseProgramUninstallOptions, parseRelativeValue, type ProgramInstallOptions, type ProgramUninstallOptions, type ClientLaunch, type Launch, type Position, type ProgramCommandChunk, type ProgramDefinition, type Size, type Value } from "@phreshos/core"
+import type { OpenTarget } 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"
@@ -653,7 +654,7 @@ export default class ProgramManager extends TheLink {
return launch
}
- /** Read or change the system-managed startup launch for one Program. */
+ /** Read, set, or remove the one launch a Program starts when the System starts. */
public async startup(program: Program, operation: string, value?: unknown): Promise<Launch | null | void> {
const state = new ProgramStateStorage(program)
@@ -669,7 +670,7 @@ export default class ProgramManager extends TheLink {
return launch
}
- if (operation === "enable") {
+ if (operation === "set") {
await program.validate()
@@ -684,7 +685,7 @@ export default class ProgramManager extends TheLink {
return
}
- if (operation === "disable") {
+ if (operation === "remove") {
if (state.startup() === null) return
state.setStartup(null)
@@ -1431,7 +1432,7 @@ export default class ProgramManager extends TheLink {
return { options, server, client, shape, windowShape, intent }
}
- private async start(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null, transitionOwnsIdentity = false, prepared?: ReturnType<ProgramManager["resolveLaunch"]>) {
+ private async start(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null, transitionOwnsIdentity = false, prepared?: ReturnType<ProgramManager["resolveLaunch"]>, opened: OpenTarget | null = null) {
if (!transitionOwnsIdentity && this.changing.has(program.identity)) throw new Error("This program is changing and cannot create a process")
@@ -1488,6 +1489,8 @@ export default class ProgramManager extends TheLink {
await this.authManager.processManager.register(identity, launch.name ?? null, program, options, resolved.intent, runtime, client !== null, shape, parent, {
window: resolved.windowShape,
prepare: record => {
+ // Known before either Endpoint runs, so its first read already has it.
+ record.opened = opened
record.onServerStart(server => server.onOutput((stream, text) => logs.printed(identity, stream === "err" ? "stderr" : "stdout", text)))
record.onServerStop((code, signal) => logs.endpointExited(identity, "server", code, signal))
record.onClientStop(() => logs.endpointExited(identity, "client", null, null))
@@ -1503,6 +1506,12 @@ export default class ProgramManager extends TheLink {
return identity
}
+ /** Starts one Process of a Program with its default launch, to open one target. */
+ public async open(program: Program, target: OpenTarget) {
+
+ return await this.start(program, {}, undefined, null, false, undefined, target)
+ }
+
/** Creates one fresh execution runtime for a Server endpoint. */
public serverRuntime(program: Program) {
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 218aeb8..ff564d4 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -4,7 +4,7 @@ import { dirname, isAbsolute, normalize, relative, resolve, sep } from "node:pat
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
import { validateIcon } from "./icon"
-import { defaultProgramVersion, parseLaunch, parseProgramDefinition, type ProgramCommandChunk, type ProgramDefinition, type ProgramSnapshot } from "@phreshos/core"
+import { defaultProgramVersion, parseLaunch, parseOpens, parseProgramDefinition, type ProgramCommandChunk, type ProgramDefinition, type ProgramSnapshot } from "@phreshos/core"
import { permissionCatalog, type DeclaredPermissions } from "@server/core/permissions"
/**
@@ -211,6 +211,8 @@ export default class Program {
keywords: this.config.keywords ?? [],
+ opens: this.config.opens ?? [],
+
hasAgent: this.agentPath !== null,
server: server && {
@@ -362,6 +364,8 @@ function coherent(config: ProgramConfig) {
catch { throw new Error("A program's website must be a valid URL") }
}
+ if (config.opens !== undefined) parseOpens(config.opens)
+
for (const [field, maximum] of [["categories", 20], ["keywords", 50]] as const) {
const values = config[field]
diff --git a/source/server/core/opening-manager.ts b/source/server/core/opening-manager.ts
new file mode 100644
index 0000000..977adb0
--- /dev/null
+++ b/source/server/core/opening-manager.ts
@@ -0,0 +1,255 @@
+import { TheLink } from "@the-link/core"
+import { Subscribe } from "@the-link/core/decorators"
+import { opensType, parseOpenTarget, type OpenRequestSnapshot, type OpenTarget } from "@phreshos/core"
+import shortIdentity from "@libs/short-identity"
+import type AuthManager from "./link-manager/auth-manager/auth-manager"
+import type Process from "./link-manager/auth-manager/process-manager/process"
+import { endpointReference } from "./link-manager/auth-manager/process-manager/endpoint-reference"
+
+/** Where the default Program of each media type is kept. */
+const defaultsKey = "opening-defaults"
+
+/** How long a request waits for the owner to choose before it ends with nothing opened. */
+export const openRequestTimeout = 120_000
+
+/**
+ * Opening: something to open goes to its type's default Program, or waits as a request until the
+ * owner chooses one. The System only records requests and choices; how a request is shown is up to the
+ * Shell.
+ */
+export default class OpeningManager extends TheLink {
+
+ private readonly pendingRequests = new Map<string, PendingOpenRequest>()
+
+ public constructor(private readonly authManager: AuthManager) {
+
+ super()
+
+ this.connectTo(authManager, "/opening")
+ }
+
+ public requests() {
+
+ return [...this.pendingRequests.values()].map(request => request.snapshot)
+ }
+
+ public pending(identity: string) {
+
+ return this.pendingRequests.has(identity)
+ }
+
+ /** The installed Programs that open this exact type, by identity. */
+ public programsFor(type: string): string[] {
+
+ return [...this.authManager.programManager.programs.values()]
+ .filter(entry => entry.installed && opensType(entry.program.config.opens ?? [], type))
+ .map(entry => entry.identity)
+ }
+
+ /**
+ * Opens one target for an Endpoint, or for the owner when `from` is null. It resolves once a
+ * Process is started for it, and rejects when no Program opens it or nothing is chosen. A request
+ * from outside ends with the connection that asked, through `signal`.
+ */
+ public async open(value: unknown, from: Readonly<{ process: Process, endpoint: "server" | "client" }> | null, signal?: AbortSignal) {
+
+ const target = parseOpenTarget(value)
+ const programs = this.programsFor(target.type)
+
+ if (!programs.length) throw new Error(`No Program opens ${target.type}`)
+
+ const chosen = (await this.chosen())[target.type]
+
+ if (chosen && programs.includes(chosen)) {
+ await this.launch(chosen, target)
+ return
+ }
+
+ const identity = shortIdentity()
+ const snapshot = Object.freeze({
+ identity,
+ from: from ? endpointReference(from.process, from.endpoint) : null,
+ createdAt: new Date(),
+ target,
+ programs: Object.freeze(programs.map(program => this.record(program)))
+ }) satisfies OpenRequestSnapshot
+
+ let settle: (program: string | null) => void = () => undefined
+ const result = new Promise<string | null>(resolve => { settle = resolve })
+ // A request belongs to the Endpoint run that asked: when it stops, nobody waits for the answer.
+ const end = () => { this.cancel(identity).catch(() => undefined) }
+ const cancelEndpoint = from ? from.endpoint === "server" ? from.process.onServerStop(end) : from.process.onClientStop(end)
+ : signal ? (signal.addEventListener("abort", end), () => signal.removeEventListener("abort", end)) : () => undefined
+
+ this.pendingRequests.set(identity, { snapshot, settle, cancelEndpoint, timer: null, resolving: false })
+
+ await Promise.all([
+ this.authManager.processManager.announceHost("opening", "request", "system", snapshot).catch(() => undefined),
+ this.$outbound.publish("/request", snapshot).catch(() => undefined)
+ ])
+
+ const pending = this.pendingRequests.get(identity)
+
+ // Observable before it can expire, as a permission request is.
+ if (pending) pending.timer = setTimeout(() => { this.cancel(identity).catch(() => undefined) }, openRequestTimeout)
+
+ if (await result === null) throw new Error(`Nothing was chosen to open ${target.type}`)
+ }
+
+ @Subscribe("/requests")
+ protected listRequests() {
+
+ return this.requests()
+ }
+
+ @Subscribe("/pending")
+ protected requestPending(identity: unknown) {
+
+ return typeof identity === "string" && this.pending(identity)
+ }
+
+ /** Opens the request's target with one of its Programs; `always` makes that Program the type's default. */
+ @Subscribe("/choose")
+ public async choose(identity: unknown, program: unknown, options: unknown) {
+
+ const request = this.claim(identity)
+
+ try {
+
+ if (typeof program !== "string" || !request.snapshot.programs.some(entry => entry.identity === program)) {
+ throw new Error("That Program does not open this")
+ }
+
+ if ((options as { always?: unknown } | undefined)?.always === true) await this.setDefault(request.snapshot.target.type, program)
+
+ await this.launch(program, request.snapshot.target)
+ await this.finish(request, program)
+ }
+ catch (error) {
+ if (this.pendingRequests.get(request.snapshot.identity) === request) request.resolving = false
+ throw error
+ }
+ }
+
+ @Subscribe("/cancel")
+ public async cancel(identity: unknown) {
+
+ const request = this.claim(identity)
+
+ try { await this.finish(request, null) }
+ catch (error) {
+ if (this.pendingRequests.get(request.snapshot.identity) === request) request.resolving = false
+ throw error
+ }
+ }
+
+ /** The default Program of each media type, as the Programs themselves; one no longer known is left out. */
+ @Subscribe("/defaults")
+ public async defaults() {
+
+ return Object.fromEntries(Object.entries(await this.chosen())
+ .filter(([, program]) => this.authManager.programManager.programs.has(program))
+ .map(([type, program]) => [type, this.record(program)]))
+ }
+
+ /** The default Program of each media type, by identity, as stored. */
+ private async chosen(): Promise<Readonly<Record<string, string>>> {
+
+ const stored = await this.store.get(defaultsKey) ?? {}
+
+ if (!stored || typeof stored !== "object" || Array.isArray(stored) || Object.values(stored).some(program => typeof program !== "string")) {
+ throw new Error("The stored opening defaults are invalid")
+ }
+
+ return stored as Record<string, string>
+ }
+
+ @Subscribe("/set-default")
+ public async setDefault(type: unknown, program: unknown) {
+
+ const target = parseOpenTarget({ type, uri: "about:blank" })
+
+ if (typeof program !== "string" || !this.programsFor(target.type).includes(program)) {
+ throw new Error(`That Program does not open ${target.type}`)
+ }
+
+ await this.store.set(defaultsKey, { ...await this.chosen(), [target.type]: program })
+ }
+
+ @Subscribe("/clear-default")
+ public async clearDefault(type: unknown) {
+
+ const target = parseOpenTarget({ type, uri: "about:blank" })
+ const { [target.type]: _cleared, ...kept } = await this.chosen()
+
+ await this.store.set(defaultsKey, kept)
+ }
+
+ /** What every Endpoint may know of a Program it is offered: its public record. */
+ private record(program: string) {
+
+ const entry = this.authManager.programManager.programs.get(program)
+
+ if (!entry) throw new Error("That Program is not known")
+
+ return entry.program.record()
+ }
+
+ private get store() {
+
+ return this.authManager.linkManager.application.store
+ }
+
+ private async launch(program: string, target: OpenTarget) {
+
+ const entry = this.authManager.programManager.programs.get(program)
+
+ if (!entry?.installed) throw new Error("That Program is not installed")
+
+ await this.authManager.programManager.open(entry.program, target)
+ }
+
+ private claim(identity: unknown) {
+
+ const request = typeof identity === "string" ? this.pendingRequests.get(identity) : undefined
+
+ if (!request || request.resolving) throw new Error("The open request does not exist")
+
+ // Claimed at once, so two choices can never both open the same request.
+ request.resolving = true
+
+ return request
+ }
+
+ private async finish(request: PendingOpenRequest, program: string | null) {
+
+ const chosen = program === null ? null : this.record(program)
+
+ if (!this.pendingRequests.delete(request.snapshot.identity)) throw new Error("The open request does not exist")
+
+ if (request.timer) clearTimeout(request.timer)
+ request.cancelEndpoint()
+
+ await Promise.all([
+ this.authManager.processManager.announceHost("opening", "resolve", "system", request.snapshot, chosen).catch(() => undefined),
+ this.$outbound.publish("/resolve", request.snapshot, chosen).catch(() => undefined)
+ ])
+
+ request.settle(program)
+ }
+
+ public toJSON() {
+
+ return { requests: new Map(this.requests().map(request => [request.identity, request])) }
+ }
+}
+
+interface PendingOpenRequest {
+ readonly snapshot: OpenRequestSnapshot
+ readonly settle: (program: string | null) => void
+ readonly cancelEndpoint: () => void
+ timer: ReturnType<typeof setTimeout> | null
+ resolving: boolean
+}
+
+export type OpeningManagerSnapshot = ReturnType<OpeningManager["toJSON"]>
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index 0606b64..2e83515 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -1,4 +1,5 @@
import type Application from "./application"
+import { name, release, version } from "@/source/identity"
import type Entry from "./link-manager/auth-manager/program-manager/entry"
import type Program from "./link-manager/auth-manager/program-manager/program"
import type Process from "./link-manager/auth-manager/process-manager/process"
@@ -9,6 +10,7 @@ import type {
Launch,
ProgramInstallOptions,
ProgramUninstallOptions,
+ SystemAbout,
SystemProgramListOptions,
PermissionInput,
PermissionName,
@@ -18,6 +20,7 @@ import type {
Size,
WindowGeometry
} from "@phreshos/core"
+import { opensType } from "@phreshos/core"
import type { Half, TrafficKind } from "./link-manager/auth-manager/process-manager/process-traffic"
import { processReference, type ProcessReference } from "./link-manager/auth-manager/process-manager/endpoint-reference"
import type { Area, Watching } from "./link-manager/auth-manager/program-manager/program-manager"
@@ -36,6 +39,9 @@ type ProgramSource = Parameters<Application["linkManager"]["authManager"]["progr
*/
export default class System {
+ /** When this System started: its uptime is counted from here. */
+ private readonly startedAt = new Date()
+
public constructor(private readonly application: Application) {}
public shell(command: string, options: ShellOptions = {}) {
@@ -45,7 +51,9 @@ export default class System {
public listPrograms(options: SystemProgramListOptions = {}) {
- return [...this.programManager.programs.values()].filter(entry => options.installed === undefined || entry.installed === options.installed)
+ return [...this.programManager.programs.values()].filter(entry =>
+ (options.installed === undefined || entry.installed === options.installed)
+ && (options.opens === undefined || opensType(entry.program.config.opens ?? [], options.opens)))
}
public findProgram(identity: string) {
@@ -442,6 +450,12 @@ export default class System {
})
}
+ /** What this System is, as its identity declares it, and when it started. Anyone may read it: it is not a secret. */
+ public about(): SystemAbout {
+
+ return Object.freeze({ name, version, release, startedAt: this.startedAt })
+ }
+
public get appearance() {
return this.application.appearanceManager.value
diff --git a/source/server/main.ts b/source/server/main.ts
index d0ef82b..25cbcf9 100644
--- a/source/server/main.ts
+++ b/source/server/main.ts
@@ -1,4 +1,4 @@
-import { displayName, name, version } from "@/package.json"
+import { name } from "@/package.json"
import view from "./view/view"
import { defaultHome, defaultHostname, defaultPorts, environmentHome, environmentHostname, environmentPorts, requestedHome, requestedPorts } from "./view/configuration"
import { fileURLToPath } from "node:url"
@@ -12,12 +12,6 @@ const home = environmentHome(name, process.env)
await view({
- name,
-
- displayName,
-
- version,
-
mode: "production",
// A published container port cannot reach a listener confined to the
diff --git a/source/server/view/gateway/gateway.ts b/source/server/view/gateway/gateway.ts
index 33b02d2..186f36a 100644
--- a/source/server/view/gateway/gateway.ts
+++ b/source/server/view/gateway/gateway.ts
@@ -42,12 +42,11 @@ async function connect(linkManager: LinkManager, peer: GatewayPeer) {
})
}
- catch (error) {
+ // A connection that closes before it is ready is simply gone: nothing waits for it to succeed.
+ catch {
await close()
- await peer.disconnect()
-
- throw error
+ await peer.disconnect().catch(() => undefined)
}
}
diff --git a/source/server/view/view.ts b/source/server/view/view.ts
index 68efe19..2e86d66 100644
--- a/source/server/view/view.ts
+++ b/source/server/view/view.ts
@@ -16,19 +16,20 @@ import { resolve } from "node:path"
import { writeFile } from "node:fs/promises"
import { styleText } from "node:util"
import { listenOnPorts } from "./configuration"
+import { name, version } from "@/source/identity"
export default async function (config: Config) {
const debugging = config.mode === "development"
- cfonts.say(`${config.displayName} v${config.version}`, {
+ cfonts.say(`${name} v${version}`, {
colors: ["blue", "white"],
font: "simple"
})
- const application = await Application.initialize(config.name, config.displayName, config.version, config.home, resolve("assets/default-icon.png"))
+ const application = await Application.initialize(config.home, resolve("assets/default-icon.png"))
// One server, five doors, each at its own name. A program's client
// is still not the API — it is files a browser reads, with no link,
@@ -77,12 +78,6 @@ export default async function (config: Config) {
export interface Config {
- name: string
-
- displayName: string
-
- version: string
-
mode: "development" | "production"
/** Absolute authoritative state root selected by Main. */
diff --git a/source/shared/window-layers.ts b/source/shared/window-layers.ts
index 2504449..19cd6b6 100644
--- a/source/shared/window-layers.ts
+++ b/source/shared/window-layers.ts
@@ -8,6 +8,11 @@ export function requireRawPresentation(layer: WindowLayer) {
if (!isRawPresentationLayer(layer)) throw new Error(`The ${layer} layer does not support raw presentation operations`)
}
+/** Only drawings in `under` and `over` choose what they are fixed to: standard Windows are on the plane, and the wallpaper and the Shell on the screen. */
+export function requireAnchorable(layer: WindowLayer) {
+ if (layer !== "under" && layer !== "over") throw new Error(`The ${layer} layer is always fixed to the ${layer === "window" ? "plane" : "viewport"}`)
+}
+
/** A move gesture hands a pointer move to the Desktop in every layer but the wallpaper, which has nowhere to move. */
export function requirePresentationMoveGesture(layer: WindowLayer) {
if (layer === "wallpaper") throw new Error("The wallpaper has nowhere to move")
diff --git a/tests/authentication-domains.test.ts b/tests/authentication-domains.test.ts
index fc6b350..d66ff14 100644
--- a/tests/authentication-domains.test.ts
+++ b/tests/authentication-domains.test.ts
@@ -8,9 +8,6 @@ import Application from "@server/core/application"
test("browser Connections and Sessions form one authoritative lifecycle", async () => {
const home = await mkdtemp(join(tmpdir(), "phreshos-authentication-"))
const application = await Application.initialize(
- "phreshos",
- "PhreshOS",
- "test",
home,
join(home, "icon.png")
)
diff --git a/tests/authorized-broadcast.test.ts b/tests/authorized-broadcast.test.ts
new file mode 100644
index 0000000..b710286
--- /dev/null
+++ b/tests/authorized-broadcast.test.ts
@@ -0,0 +1,15 @@
+import { expect, test, vi } from "vitest"
+import AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
+
+test("a connection closed while an event is on its way neither fails the event nor stops the others", async () => {
+ const closed = { external: true, session: null, link: { $outbound: { publish: vi.fn(async () => { throw new Error("The IPC connection is closed") }) } } }
+ const open = { external: false, session: "session", link: { $outbound: { publish: vi.fn(async () => undefined) } } }
+ const signedOut = { external: false, session: null, link: { $outbound: { publish: vi.fn(async () => undefined) } } }
+ const manager = { linkManager: { boundaries: new Map<string, unknown>([["closed", closed], ["open", open], ["signed-out", signedOut]]) } }
+ const broadcast = (AuthManager.prototype as unknown as { broadcastToAuthorizedBoundaries: (event: string, ...values: unknown[]) => Promise<void> }).broadcastToAuthorizedBoundaries
+
+ await expect(broadcast.call(manager, "/program/install", "notes")).resolves.toBeUndefined()
+
+ expect(open.link.$outbound.publish).toHaveBeenCalledWith("/program/install", "notes")
+ expect(signedOut.link.$outbound.publish).not.toHaveBeenCalled()
+})
diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.ts
index 7d9e48b..0bad79c 100644
--- a/tests/client-layer-permissions.test.ts
+++ b/tests/client-layer-permissions.test.ts
@@ -80,7 +80,7 @@ test.each(restrictedLayers)("Client launch routes check %s before delegation", a
const operations = [
["program-create-process", program, launch],
["program-find-or-create-process", program, launch],
- ["startup", program, "enable", launch],
+ ["startup", program, "set", launch],
["start-endpoint", process, "client", { layer }]
] as const
const anotherLayer = restrictedLayers.find(candidate => candidate !== layer)!
@@ -146,7 +146,7 @@ test("Client layer authorization validates explicit choices without reinterpreti
await expect(access.launch({ client: { layer: "invalid" } })).rejects.toThrow("layer")
await expect(access.clientLaunch(false)).rejects.toThrow("object")
await f.answer("startup", null, "get")
- await f.answer("startup", null, "disable")
+ await f.answer("startup", null, "remove")
await f.answer("start-endpoint", null, "server")
await f.answer("program-create-process", null, {})
expect(f.createProcess).toHaveBeenCalledOnce()
diff --git a/tests/link-request-routing.test.ts b/tests/link-request-routing.test.ts
index b299d68..85617af 100644
--- a/tests/link-request-routing.test.ts
+++ b/tests/link-request-routing.test.ts
@@ -11,7 +11,7 @@ import { test } from "vitest"
test("an RPC result returns only to its requesting boundary", async () => {
const home = await mkdtemp(join(tmpdir(), "phreshos-request-routing-"))
- const application = await Application.initialize("phreshos", "PhreshOS", "test", home, join(home, "icon.png"))
+ const application = await Application.initialize(home, join(home, "icon.png"))
const link = new TheLink()
const boundary = application.linkManager.addExternalConnection(link)
const broadcasts: unknown[][] = []
diff --git a/tests/opening.test.ts b/tests/opening.test.ts
new file mode 100644
index 0000000..304a66a
--- /dev/null
+++ b/tests/opening.test.ts
@@ -0,0 +1,107 @@
+import { TheLink } from "@the-link/core"
+import { expect, test, vi } from "vitest"
+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"
+import OpeningManager from "@server/core/opening-manager"
+
+function fixture() {
+ const program = (identity: string, opens: string[], installed = true) => [identity, { identity, installed, program: { identity, config: { opens }, record: () => ({ identity }) } }] as const
+ const stored = new Map<string, unknown>()
+ const open = vi.fn(async () => "process")
+ const auth = Object.assign(new TheLink(), {
+ linkManager: { application: { store: { get: async (key: string) => stored.get(key), set: async (key: string, value: unknown) => { stored.set(key, value) } } } },
+ programManager: {
+ programs: new Map([program("preview", ["image/*"]), program("paint", ["image/png"]), program("files", ["inode/directory"]), program("old", ["image/png"], false)]),
+ open
+ },
+ processManager: { announceHost: vi.fn(async () => undefined) }
+ }) as unknown as AuthManager
+ return { manager: new OpeningManager(auth), open, stored }
+}
+
+const png = { type: "image/png", uri: "file:///home/me/a.png" }
+
+test("the installed Programs that open a type, wildcards included", () => {
+ const { manager } = fixture()
+
+ expect(manager.programsFor("image/png")).toEqual(["preview", "paint"])
+ expect(manager.programsFor("image/jpeg")).toEqual(["preview"])
+ expect(manager.programsFor("text/plain")).toEqual([])
+})
+
+test("nothing to open with, or a malformed target, is refused", async () => {
+ const { manager } = fixture()
+
+ await expect(manager.open({ type: "text/plain", uri: "file:///a.txt" }, null)).rejects.toThrow(/No Program opens text\/plain/)
+ await expect(manager.open({ type: "image/*", uri: "file:///a.png" }, null)).rejects.toThrow(/exact media type/)
+ await expect(manager.open({ type: "image/png", uri: "not a uri" }, null)).rejects.toThrow(/URI/)
+})
+
+test("a default Program opens it at once, with no request", async () => {
+ const { manager, open, stored } = fixture()
+ stored.set("opening-defaults", { "image/png": "paint" })
+
+ await manager.open(png, null)
+
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({ identity: "paint" }), png)
+ expect(manager.requests()).toEqual([])
+})
+
+test("without a default, a request waits; choosing always opens it and makes the default", async () => {
+ const { manager, open } = fixture()
+
+ const opening = manager.open(png, null)
+ await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))
+ const [request] = manager.requests()
+
+ // Offered as the Programs themselves, so whoever decides reads them as any Program.
+ expect(request!.programs).toEqual([{ identity: "preview" }, { identity: "paint" }])
+ await expect(manager.choose(request!.identity, "files", {})).rejects.toThrow(/does not open this/)
+ expect(manager.pending(request!.identity)).toBe(true)
+
+ await manager.choose(request!.identity, "preview", { always: true })
+ await opening
+
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({ identity: "preview" }), png)
+ expect(await manager.defaults()).toEqual({ "image/png": { identity: "preview" } })
+ expect(manager.pending(request!.identity)).toBe(false)
+})
+
+test("a cancelled request opens nothing and tells the one who asked", async () => {
+ const { manager, open } = fixture()
+
+ const opening = manager.open(png, null)
+ await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))
+ await manager.cancel(manager.requests()[0]!.identity)
+
+ await expect(opening).rejects.toThrow(/Nothing was chosen/)
+ expect(open).not.toHaveBeenCalled()
+})
+
+test("a default whose Program is no longer known is left out", async () => {
+ const { manager, stored } = fixture()
+ stored.set("opening-defaults", { "image/png": "gone", "inode/directory": "files" })
+
+ expect(await manager.defaults()).toEqual({ "inode/directory": { identity: "files" } })
+})
+
+test("a default must be a Program that opens that type", async () => {
+ const { manager } = fixture()
+
+ await expect(manager.setDefault("image/png", "files")).rejects.toThrow(/does not open image\/png/)
+ await manager.setDefault("image/png", "paint")
+ await manager.clearDefault("image/png")
+ expect(await manager.defaults()).toEqual({})
+})
+
+test("a request from outside ends when the connection that asked closes", async () => {
+ const { manager, open } = fixture()
+ const connection = new AbortController()
+
+ const opening = manager.open(png, null, connection.signal)
+ await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))
+ connection.abort()
+
+ await expect(opening).rejects.toThrow(/Nothing was chosen/)
+ await vi.waitFor(() => expect(manager.requests()).toEqual([]))
+ expect(open).not.toHaveBeenCalled()
+})
diff --git a/tests/panel.test.tsx b/tests/panel.test.tsx
index cfd1519..bec688e 100644
--- a/tests/panel.test.tsx
+++ b/tests/panel.test.tsx
@@ -10,9 +10,10 @@ import Taskbar from "@client/view/structure/desktop/layers/shell/taskbar/taskbar
import { ApplicationContext } from "@client/view/contexts"
import Application from "@client/core/application"
import { test } from "vitest"
+import { name, version } from "@/source/identity"
test("panel contract", async () => {
- const application = new Application("phreshos", "Example System", "1.2.3", {
+ const application = new Application({
link: "/link",
proxy: "/proxy",
storage: "/storage",
@@ -70,7 +71,7 @@ test("panel contract", async () => {
assert.match(authentication, /<label[^>]*>Password<\/label>/)
assert.match(authentication, /type="submit"/)
assert.match(authentication, /<h1[^>]*>Sign in<\/h1>/)
- assert.match(authentication, /Example System version 1.2.3/)
+ assert(authentication.includes(`${name} version ${version}`))
assert.doesNotMatch(authentication, /backdrop-blur/)
const authenticationError = markup(<CredentialsForm title="Sign up" description="Welcome" submitLabel="Continue" passwordAutocomplete="new-password" pending={false}
diff --git a/tests/permission-synchronization.test.ts b/tests/permission-synchronization.test.ts
index a68a3db..a1c2940 100644
--- a/tests/permission-synchronization.test.ts
+++ b/tests/permission-synchronization.test.ts
@@ -16,6 +16,7 @@ function record(permissions: ProgramRecord["permissions"]): ProgramRecord {
description: null,
categories: [],
keywords: [],
+ opens: [],
hasAgent: false,
server: null,
client: null,
diff --git a/tests/presentation-layers.test.ts b/tests/presentation-layers.test.ts
index 91da435..c057139 100644
--- a/tests/presentation-layers.test.ts
+++ b/tests/presentation-layers.test.ts
@@ -88,3 +88,34 @@ test("a standard Window shows a change at once and follows the System once its r
await new Promise(resolve => setTimeout(resolve))
expect(presentations.projection("own")).toMatchObject({ maximized: false })
})
+
+test("each layer starts fixed to what it lives on", () => {
+ expect(fixture("window").presentations.projection("own").anchor).toBe("plane")
+ for (const layer of ["wallpaper", "under", "over", "shell"] as const) expect(fixture(layer).presentations.projection("own").anchor).toBe("viewport")
+})
+
+test.each(["under", "over"] as const)("a drawing in %s is fixed to the plane where it stands on the screen", async layer => {
+ const { presentations } = fixture(layer)
+ await presentations.setGeometry("own", { x: 10, y: 20, width: 400, height: 300 })
+ presentations.follow({ x: 1440, y: -900 })
+
+ // Its position is counted again from the plane's center, so it does not move on the screen.
+ presentations.setAnchor("own", "plane")
+ expect(presentations.projection("own")).toMatchObject({ anchor: "plane", position: { x: 1450, y: -880 } })
+
+ presentations.follow({ x: 0, y: 0 })
+ presentations.setAnchor("own", "viewport")
+ expect(presentations.projection("own")).toMatchObject({ anchor: "viewport", position: { x: 1450, y: -880 } })
+})
+
+test("only under and over choose what they are fixed to", () => {
+ expect(() => fixture("window").presentations.setAnchor("own", "viewport")).toThrow(/does not support raw/)
+ expect(() => fixture("wallpaper").presentations.setAnchor("own", "plane")).toThrow(/does not support raw/)
+ expect(() => fixture("shell").presentations.setAnchor("own", "plane")).toThrow(/always fixed to the viewport/)
+})
+
+test("the plane is five views across and down, whatever the Desktop's size", async () => {
+ const { planeSize } = await import("@client/view/components/window-manager/window-geometry")
+ expect(planeSize({ width: 1440, height: 900 })).toEqual({ width: 7200, height: 4500 })
+ expect(planeSize({ width: 1024, height: 768 })).toEqual({ width: 5120, height: 3840 })
+})
diff --git a/tests/program-creation.test.ts b/tests/program-creation.test.ts
index 2ea854d..1e3d1b7 100644
--- a/tests/program-creation.test.ts
+++ b/tests/program-creation.test.ts
@@ -66,7 +66,7 @@ test("startup and pinned state share one file without overwriting each other", a
const program = await manager.create(definition())
const startup = { name: "background", options: { mode: "quiet" } }
- await manager.startup(program, "enable", startup)
+ await manager.startup(program, "set", startup)
await manager.pinned(program, "pin")
await manager.setPermission(program, "network", false)
@@ -79,7 +79,7 @@ test("startup and pinned state share one file without overwriting each other", a
permissions: { network: false }
})
- await manager.startup(program, "disable")
+ await manager.startup(program, "remove")
await manager.pinned(program, "unpin")
expect(await manager.startup(program, "get")).toBeNull()
expect(await manager.pinned(program, "get")).toBe(false)
@@ -93,12 +93,12 @@ test("Program state mutations do not rewrite an already-satisfied value", async
const permissionWrite = vi.spyOn(ProgramStateStorage.prototype, "setPermission")
context.onTestFinished(() => { startupWrite.mockRestore(); permissionWrite.mockRestore() })
- await manager.startup(program, "enable", { name: "background" })
- await manager.startup(program, "enable", { name: "background" })
+ await manager.startup(program, "set", { name: "background" })
+ await manager.startup(program, "set", { name: "background" })
await manager.setPermission(program, "network", false)
await manager.setPermission(program, "network", false)
- await manager.startup(program, "disable")
- await manager.startup(program, "disable")
+ await manager.startup(program, "remove")
+ await manager.startup(program, "remove")
expect(startupWrite).toHaveBeenCalledTimes(2)
expect(permissionWrite).toHaveBeenCalledTimes(1)
diff --git a/tests/program-installation-lifecycle.test.ts b/tests/program-installation-lifecycle.test.ts
index 4e9bea7..9b547d4 100644
--- a/tests/program-installation-lifecycle.test.ts
+++ b/tests/program-installation-lifecycle.test.ts
@@ -119,7 +119,7 @@ test("a reinstall starts the Program's startup launch again, as the System does
const start = vi.spyOn(manager as unknown as { start(program: Program, launch: Launch, watching?: unknown, parent?: unknown, transitionOwnsIdentity?: boolean): Promise<string> }, "start").mockResolvedValue("process")
const first = await manager.install(definition())
- await manager.startup(first.program, "enable", { name: "panel" })
+ await manager.startup(first.program, "set", { name: "panel" })
await manager.install(definition())
// The first install had no startup launch; the reinstall ended the Processes and starts that one again.
diff --git a/tests/system-about.test.ts b/tests/system-about.test.ts
new file mode 100644
index 0000000..14dd1f9
--- /dev/null
+++ b/tests/system-about.test.ts
@@ -0,0 +1,23 @@
+import assert from "node:assert/strict"
+import { mkdtemp, rm } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { test } from "vitest"
+import Application from "@server/core/application"
+import { name, release, version } from "@/source/identity"
+
+test("the System says what it is from its identity, and when it started", async () => {
+ const home = await mkdtemp(join(tmpdir(), "phreshos-about-"))
+ try {
+ const before = Date.now()
+ const application = await Application.initialize(home, join(home, "icon.png"))
+ const about = application.system.about()
+
+ assert.deepEqual(about, { name, version, release, startedAt: about.startedAt })
+ assert(Object.isFrozen(about))
+ // It started while it was being initialized, and stays the same for every reader.
+ assert(about.startedAt.getTime() >= before && about.startedAt.getTime() <= Date.now())
+ assert.equal(application.system.about().startedAt.getTime(), about.startedAt.getTime())
+ }
+ finally { await rm(home, { recursive: true, force: true }) }
+}, 60_000)
diff --git a/tests/wallpaper-source.test.tsx b/tests/wallpaper-source.test.tsx
index 43403f5..9f7d690 100644
--- a/tests/wallpaper-source.test.tsx
+++ b/tests/wallpaper-source.test.tsx
@@ -4,11 +4,11 @@ import { UIProvider } from "@phreshos/react-ui"
import { defaultAppearance } from "@phreshos/core"
import { ApplicationContext } from "@client/view/contexts"
import Application from "@client/core/application"
-import { WallpaperBackground } from "@client/view/structure/desktop/layers/wallpaper/wallpaper"
+import { WallpaperBackground, type WallpaperPlace } from "@client/view/structure/desktop/layers/wallpaper/wallpaper"
import { test } from "vitest"
test("wallpaper source contract", () => {
- const application = new Application("phreshos", "PhreshOS", "1.0.0", {
+ const application = new Application({
link: "/link",
proxy: "/proxy",
storage: "/storage",
@@ -16,14 +16,18 @@ test("wallpaper source contract", () => {
program: "/program"
})
- function render(file: string) {
+ function render(file: string | null, place: WallpaperPlace = "desktop") {
return renderToStaticMarkup(<ApplicationContext.Provider value={application}>
<UIProvider appearance={defaultAppearance} preferences={{ theme: "dark", animations: true }}>
- <WallpaperBackground file={file} />
+ <WallpaperBackground place={place} file={file} />
</UIProvider>
</ApplicationContext.Provider>)
}
+ // Without a chosen wallpaper, the sign-in screen shows the seed and the Desktop the release's own.
+ assert.match(render(null, "signIn"), /seed-dark/)
+ assert.match(render(null, "desktop"), /sprout-dark/)
+
const image = render("00000000-0000-0000-0000-000000000000.png")
assert.match(image, /<img/)
assert.match(image, /src="\/uploads\/00000000-0000-0000-0000-000000000000\.png"/)