@fungi.computer/computer 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,10 +52,11 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
52
52
  });
53
53
  import { patchInputSchema, patchOutputSchema, } from "@fungi.computer/computer-contract";
54
54
  import { boundExecStream } from "./exec-output.js";
55
+ import { workspaceRoot } from "./files.js";
55
56
  /** The packaged, pinned Codex engine owns patch parsing and the Workspace jail. */
56
57
  const nativePatch = {
57
58
  executable: "/opt/fungi/fungi-apply-patch",
58
- cwd: "/workspace",
59
+ cwd: workspaceRoot,
59
60
  timeoutMs: 30_000,
60
61
  mismatchExitCode: 23,
61
62
  };
package/dist/files.d.ts CHANGED
@@ -3,6 +3,16 @@ import type { SQLiteWorkspaceProvider, WorkspaceClient } from "@fungi.computer/c
3
3
  export type WorkspaceFiles = Pick<WorkspaceClient, "fs">;
4
4
  import type { FilesPort } from "@fungi.computer/knapsack";
5
5
  import { type ComputerFileGlobInput, type ComputerFileGrepInput, type ComputerFileListInput, type ComputerFileReplacement, type ComputerFileReplacementResult } from "@fungi.computer/computer-contract";
6
+ /**
7
+ * The guest's mount of the Workspace filesystem, and the working directory of
8
+ * exec and apply_patch. It is the one root an Agent's relative path means.
9
+ */
10
+ export declare const workspaceRoot = "/workspace";
11
+ /**
12
+ * The Workspace path an Agent's Files path names: what a shell in
13
+ * {@link workspaceRoot} would resolve. Absolute paths pass through unchanged.
14
+ */
15
+ export declare function agentWorkspacePath(path: string): string;
6
16
  export type WorkspaceFilesOwner = Readonly<{
7
17
  replaceFileIfUnchanged: (input: ComputerFileReplacement) => Promise<ComputerFileReplacementResult>;
8
18
  }>;
package/dist/files.js CHANGED
@@ -4,6 +4,18 @@ import { SearchVisibility } from "@fungi.computer/knapsack/files-search";
4
4
  import { imageReadResult, imageSniffBytes, imageTooLargeMessage, maximumImageBytes, sniffImageMimeType, } from "@fungi.computer/knapsack/files-read";
5
5
  import { replaceOutputSchema, } from "@fungi.computer/computer-contract";
6
6
  const utf8 = new TextEncoder();
7
+ /**
8
+ * The guest's mount of the Workspace filesystem, and the working directory of
9
+ * exec and apply_patch. It is the one root an Agent's relative path means.
10
+ */
11
+ export const workspaceRoot = "/workspace";
12
+ /**
13
+ * The Workspace path an Agent's Files path names: what a shell in
14
+ * {@link workspaceRoot} would resolve. Absolute paths pass through unchanged.
15
+ */
16
+ export function agentWorkspacePath(path) {
17
+ return posix.resolve(workspaceRoot, path);
18
+ }
7
19
  function entryType(entry) {
8
20
  if (entry.isSymbolicLink)
9
21
  return "symlink";
@@ -70,7 +82,8 @@ export function readBoundedWorkspaceText(provider, path, maximumBytes) {
70
82
  export function createWorkspaceFilesPort(workspace, owner) {
71
83
  const port = {
72
84
  async read(input) {
73
- const stat = await workspace.fs.stat(input.path);
85
+ const target = agentWorkspacePath(input.path);
86
+ const stat = await workspace.fs.stat(target);
74
87
  if (!stat.isFile)
75
88
  throw new Error(`Files path is not a file: ${input.path}`);
76
89
  if (input.offset > stat.size) {
@@ -86,7 +99,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
86
99
  };
87
100
  }
88
101
  // The first read covers the sniff window whatever the caller's limit.
89
- const windowBytes = await readBytes(workspace, input.path, input.offset, Math.min(input.offset === 0
102
+ const windowBytes = await readBytes(workspace, target, input.offset, Math.min(input.offset === 0
90
103
  ? Math.max(input.limit, imageSniffBytes)
91
104
  : input.limit, stat.size - input.offset));
92
105
  if (windowBytes.byteLength === 0) {
@@ -98,7 +111,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
98
111
  throw new Error(imageTooLargeMessage(input.path, stat.size, maximumImageBytes));
99
112
  return imageReadResult(input.path, mimeType, windowBytes.byteLength === stat.size
100
113
  ? windowBytes
101
- : await readBytes(workspace, input.path, 0, stat.size));
114
+ : await readBytes(workspace, target, 0, stat.size));
102
115
  }
103
116
  const pageBytes = windowBytes.subarray(0, input.limit);
104
117
  const page = decodeUtf8Page(pageBytes, input.path, input.offset + pageBytes.byteLength < stat.size);
@@ -123,7 +136,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
123
136
  };
124
137
  },
125
138
  async glob(input, context) {
126
- const output = await visibleSearch(workspace, workspacePath(input.path), input.limit, (options) => workspace.fs.find(workspacePath(input.path), input.pattern, options), (entry) => entry.type === "dir", context?.signal);
139
+ const output = await visibleSearch(workspace, agentWorkspacePath(input.path), input.limit, (options) => workspace.fs.find(agentWorkspacePath(input.path), input.pattern, options), (entry) => entry.type === "dir", context?.signal);
127
140
  return {
128
141
  path: input.path,
129
142
  ...output,
@@ -141,7 +154,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
141
154
  };
142
155
  if (input.include !== undefined)
143
156
  options.include = input.include;
144
- const output = await visibleSearch(workspace, workspacePath(input.path), input.limit, (page) => workspace.fs.grep(input.pattern, workspacePath(input.path), {
157
+ const output = await visibleSearch(workspace, agentWorkspacePath(input.path), input.limit, (page) => workspace.fs.grep(input.pattern, agentWorkspacePath(input.path), {
145
158
  ...options,
146
159
  ...page,
147
160
  }), () => false, context?.signal);
@@ -156,7 +169,10 @@ export function createWorkspaceFilesPort(workspace, owner) {
156
169
  };
157
170
  },
158
171
  async replace(input) {
159
- return replaceOutputSchema.parse(await owner.replaceFileIfUnchanged(input));
172
+ return replaceOutputSchema.parse(await owner.replaceFileIfUnchanged({
173
+ ...input,
174
+ path: agentWorkspacePath(input.path),
175
+ }));
160
176
  },
161
177
  };
162
178
  return Object.freeze({
@@ -185,7 +201,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
185
201
  });
186
202
  }
187
203
  function searchWorkspaceDirectory(workspace, input, signal) {
188
- const path = workspacePath(input.path);
204
+ const path = agentWorkspacePath(input.path);
189
205
  return visibleSearch(workspace, path, input.limit, async (options) => (await workspace.fs.readdir(path, options)).map((entry) => ({
190
206
  ...entry,
191
207
  path: childPath(path, entry.name),
@@ -209,12 +225,6 @@ export async function listWorkspaceFiles(workspace, input) {
209
225
  nextOffset: output.truncated === null ? null : input.offset + output.results.length,
210
226
  };
211
227
  }
212
- /** Computer wire paths are absolute within its Workspace, even for relative Files inputs. */
213
- function workspacePath(path) {
214
- if (path === ".")
215
- return "/";
216
- return path.startsWith("/") ? path : `/${path}`;
217
- }
218
228
  const missingSchema = z.object({ code: z.literal("ENOENT") });
219
229
  /** A regular file's stat, or null when the path is absent or not a file. */
220
230
  async function fileStat(workspace, path) {
package/dist/index.d.ts CHANGED
@@ -145,6 +145,12 @@ declare class ContainerComputer extends ContainerComputerBase {
145
145
  * write there must not depend on a guest having booted first.
146
146
  */
147
147
  protected readyWorkspace(): Promise<Workspace>;
148
+ /**
149
+ * A host's one-time work before the first Files operation reaches the
150
+ * Workspace. It runs outside the file queue, so an implementation may use
151
+ * {@link copyWorkspaceFileIfFree}. It must never throw.
152
+ */
153
+ protected prepareFiles(): Promise<void>;
148
154
  /** `getWorkspace(stub)` reaches the current generation through this door. */
149
155
  __getWorkspaceStub(): Promise<WorkspaceStub>;
150
156
  /**
@@ -227,6 +233,15 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
227
233
  * placeholder origin and a path/query with the Hub route prefix removed.
228
234
  */
229
235
  protected portPreviewAfterAcceptance(portInput: number, request: Request, accept: () => void): Promise<Response>;
236
+ /**
237
+ * Copy one Workspace file to a path nothing occupies, keeping the original,
238
+ * and say what it found. It runs in the file queue and first pulls every
239
+ * attached guest, so a guest that is ahead of the Workspace is seen before
240
+ * the copy and the next push cannot overwrite what the guest changed. A guest
241
+ * whose state cannot be read (a runtime whose pull fails, or an attached
242
+ * machine that is offline) makes the answer "unknown": nothing is copied.
243
+ */
244
+ protected copyWorkspaceFileIfFree(from: string, to: string): Promise<"copied" | "absent" | "conflict" | "unknown">;
230
245
  getCapabilities(): Promise<{
231
246
  id: string;
232
247
  name: string;
package/dist/index.js CHANGED
@@ -51,6 +51,7 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
51
51
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
52
  });
53
53
  import { boundExecStream } from "./exec-output.js";
54
+ import { portPreviewFailure, portPreviewReply } from "./port-failure.js";
54
55
  export { createLocalBackendReplayStore } from "./local-backend-replay.js";
55
56
  import { computerInternetAccess } from "./internet-access.js";
56
57
  import { createComputerVaultReferences, isVaultExecutionContext, vaultExecutionHooks, } from "./vault-references.js";
@@ -66,7 +67,7 @@ import { SystemTrustContainerBackend } from "./container-system-trust.js";
66
67
  import { computerTransportBackend } from "./transport-backend.js";
67
68
  import { PullPendingTracker } from "./pull-pending.js";
68
69
  import { ComputerFileConflict, ComputerFileRangeError, ComputerFileTooLargeError, capabilityNameSchema, computerValueSchema, computerCapabilities, computerPortInputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, computerPortsOutputSchema, computerPortSchema, ComputerPortLimitError, ComputerPortReservedError, computerTerminalPort, isComputerReservedPort, maximumExposedPorts, maximumProcessRecords, execInputSchema, execOutputSchema, computerToolResult, computerExecutionRequestSchema, genericComputerExecutionBudget, mintComputerRequestId, listInputSchema, listOutputSchema, maximumFileBytes, mkdirInputSchema, mkdirOutputSchema, moveInputSchema, moveOutputSchema, ComputerFileMoveError, ComputerFileRemoveError, removeInputSchema, removeOutputSchema, readInputSchema, readBytesInputSchema, readOutputSchema, replaceInputSchema, writeInputSchema, writeOutputSchema, processIdInputSchema, processKillOutputSchema, processListOutputSchema, processLogsInputSchema, processLogsOutputSchema, processWaitInputSchema, processWaitOutputSchema, maximumProcessLogLines, processStartInputSchema, processStartToolInputSchema, ComputerProcessNotFoundError, } from "@fungi.computer/computer-contract";
69
- import { createWorkspaceFilesPort, readBoundedWorkspaceText, workspaceFileExists, listWorkspaceFiles, } from "./files.js";
70
+ import { agentWorkspacePath, createWorkspaceFilesPort, readBoundedWorkspaceText, workspaceRoot, workspaceFileExists, listWorkspaceFiles, } from "./files.js";
70
71
  import { computerExecutionResult } from "./execution-result.js";
71
72
  import { ComputerOperationRecord } from "./operation-record.js";
72
73
  import { createComputerExecutionLifecycle } from "./execution-lifecycle.js";
@@ -270,9 +271,6 @@ class ComputerDurableObject extends DurableObject {
270
271
  }
271
272
  }
272
273
  const ContainerComputerBase = withWorkspaceContainer(ComputerDurableObject);
273
- /** One Workspace built for one attached-backend set. */
274
- /** The directory every Computer backend mounts as its guest workspace. */
275
- const workspaceMountRoot = "/workspace";
276
274
  /** A VM's container upgrade, rewritten by the verified on-box ingress door. */
277
275
  const vmUpgradePath = /^\/__vm\/([a-z0-9][a-z0-9-]{0,62})(\/ws)$/;
278
276
  /**
@@ -552,13 +550,22 @@ class ContainerComputer extends ContainerComputerBase {
552
550
  const workspace = this.workspace();
553
551
  await workspace.ready();
554
552
  if (!this.#rootedWorkspaces.has(workspace)) {
555
- await workspace.fs.mkdir(workspaceMountRoot, { recursive: true });
553
+ await workspace.fs.mkdir(workspaceRoot, { recursive: true });
556
554
  this.#rootedWorkspaces.add(workspace);
557
555
  }
558
556
  return workspace;
559
557
  }
558
+ /**
559
+ * A host's one-time work before the first Files operation reaches the
560
+ * Workspace. It runs outside the file queue, so an implementation may use
561
+ * {@link copyWorkspaceFileIfFree}. It must never throw.
562
+ */
563
+ prepareFiles() {
564
+ return Promise.resolve();
565
+ }
560
566
  /** `getWorkspace(stub)` reaches the current generation through this door. */
561
567
  async __getWorkspaceStub() {
568
+ await this.prepareFiles();
562
569
  return (await this.readyWorkspace()).stub();
563
570
  }
564
571
  /**
@@ -897,13 +904,11 @@ export class ComputerDO extends ContainerComputer {
897
904
  const response = await this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
898
905
  .port(port)
899
906
  .fetch(new Request(forwarded, { headers })));
900
- const safe = new Response(response.body, response);
901
- safe.headers.delete("set-cookie");
902
- return safe;
907
+ return await portPreviewReply(response, request, port);
903
908
  }
904
909
  catch (cause) {
905
910
  console.error("Computer runtime operation failed", cause);
906
- return Response.json({ error: "Computer port service is unavailable" }, { status: 502 });
911
+ return await portPreviewFailure("unreachable", request, port);
907
912
  }
908
913
  }
909
914
  async #withBinaryFile(operation) {
@@ -949,6 +954,52 @@ export class ComputerDO extends ContainerComputer {
949
954
  console.error(`Computer Workspace ${direction} failed`, cause);
950
955
  }
951
956
  }
957
+ /**
958
+ * Copy one Workspace file to a path nothing occupies, keeping the original,
959
+ * and say what it found. It runs in the file queue and first pulls every
960
+ * attached guest, so a guest that is ahead of the Workspace is seen before
961
+ * the copy and the next push cannot overwrite what the guest changed. A guest
962
+ * whose state cannot be read (a runtime whose pull fails, or an attached
963
+ * machine that is offline) makes the answer "unknown": nothing is copied.
964
+ */
965
+ async copyWorkspaceFileIfFree(from, to) {
966
+ return await this.#withBinaryFile(async () => {
967
+ const workspace = await this.readyWorkspace();
968
+ for (const backend of this.attachedBackends()) {
969
+ const id = attachedBackendId(backend);
970
+ try {
971
+ if (backend.kind === "local") {
972
+ if (!this.localConnections.online(id))
973
+ return "unknown";
974
+ }
975
+ else if (!(await this.containerRunning(backend)))
976
+ continue;
977
+ await workspace.pull(id);
978
+ }
979
+ catch (cause) {
980
+ if (cause instanceof ComputerContainersPausedError)
981
+ continue;
982
+ console.error(`Computer Workspace pull before a copy failed`, cause);
983
+ return "unknown";
984
+ }
985
+ }
986
+ const provider = new SQLiteWorkspaceProvider(workspace.fs.db);
987
+ const outcome = this.state.storage.transactionSync(() => {
988
+ if (!workspaceFileExists(provider, from))
989
+ return "absent";
990
+ if (workspaceFileExists(provider, to))
991
+ return "conflict";
992
+ const stat = provider.statSync(from);
993
+ if (!stat.isFile())
994
+ return "absent";
995
+ provider.writeFileSync(to, new Uint8Array(provider.readRangeSync(from, 0, stat.size)));
996
+ return "copied";
997
+ });
998
+ if (outcome === "copied")
999
+ await this.#syncRunningHosted("push");
1000
+ return outcome;
1001
+ });
1002
+ }
952
1003
  /** One loop per Computer while any terminal socket is attached. */
953
1004
  #startTerminalSync(backing) {
954
1005
  if (this.#terminalSync !== undefined)
@@ -991,6 +1042,7 @@ export class ComputerDO extends ContainerComputer {
991
1042
  /** Resource hosts may accept authority after the file queue and Workspace are ready. */
992
1043
  async readFileAfterAcceptance(input, accept, maximumBytes = maximumFileBytes) {
993
1044
  const { path, byteOffset = 0, byteLength, } = readBytesInputSchema.parse(input);
1045
+ await this.prepareFiles();
994
1046
  return await this.#withBinaryFile(async () => {
995
1047
  const workspace = await this.readyWorkspace();
996
1048
  accept();
@@ -1057,6 +1109,7 @@ export class ComputerDO extends ContainerComputer {
1057
1109
  /** Resource hosts may accept authority after the file queue and Workspace are ready. */
1058
1110
  async writeFileAfterAcceptance(input, content, accept) {
1059
1111
  const { path } = readInputSchema.parse(input);
1112
+ await this.prepareFiles();
1060
1113
  await this.#withBinaryFile(async () => {
1061
1114
  const workspace = await this.readyWorkspace();
1062
1115
  accept();
@@ -1066,6 +1119,7 @@ export class ComputerDO extends ContainerComputer {
1066
1119
  }
1067
1120
  /** Keep one Workspace lease around one authorized structured Files operation. */
1068
1121
  async withFilesAfterAcceptance(accept, operation) {
1122
+ await this.prepareFiles();
1069
1123
  const workspace = await this.readyWorkspace();
1070
1124
  accept();
1071
1125
  await this.#syncRunningHosted("pull");
@@ -1122,6 +1176,7 @@ export class ComputerDO extends ContainerComputer {
1122
1176
  case "wait_process":
1123
1177
  return await this.waitProcessAfterAcceptance(input, accept);
1124
1178
  }
1179
+ await this.prepareFiles();
1125
1180
  const workspace = await this.readyWorkspace();
1126
1181
  accept();
1127
1182
  switch (selected) {
@@ -1721,6 +1776,7 @@ export class ComputerDO extends ContainerComputer {
1721
1776
  /** Stale-safe replacement with authority checked at the transaction boundary. */
1722
1777
  async replaceFileIfUnchangedAfterAcceptance(input, accept) {
1723
1778
  const replacement = replaceInputSchema.parse(input);
1779
+ await this.prepareFiles();
1724
1780
  const workspace = await this.readyWorkspace();
1725
1781
  await this.#syncRunningHosted("pull");
1726
1782
  const provider = new SQLiteWorkspaceProvider(workspace.fs.db);
@@ -1775,7 +1831,10 @@ export function createComputerFilesPort(computer) {
1775
1831
  grep: (input) => withFiles((files) => files.grep(input)),
1776
1832
  replace: async (input, context) => {
1777
1833
  context.signal.throwIfAborted();
1778
- return await computer.replaceFileIfUnchanged(input);
1834
+ return await computer.replaceFileIfUnchanged({
1835
+ ...input,
1836
+ path: agentWorkspacePath(input.path),
1837
+ });
1779
1838
  },
1780
1839
  };
1781
1840
  }
@@ -0,0 +1,21 @@
1
+ import * as Schema from "effect/Schema";
2
+ declare const hostRefusalSchema: Schema.Literals<readonly ["not_running", "not_listening", "unreachable"]>;
3
+ /**
4
+ * Why a Computer port preview has nothing to show. `not_running`: the
5
+ * Computer is asleep (a preview never wakes it). `not_listening`: nothing in
6
+ * the Computer answers on that port. `unreachable`: Fungi could not reach the
7
+ * Computer. `expired`: the preview link's five-minute ticket ran out.
8
+ */
9
+ export type PortPreviewFailure = Schema.Schema.Type<typeof hostRefusalSchema> | "unreachable" | "expired";
10
+ /**
11
+ * The one answer a failed preview gives: a styled page in plain words for a
12
+ * browser document, or `{ error: reason }` for a script's request. Raw
13
+ * upstream text never reaches the viewer.
14
+ */
15
+ export declare function portPreviewFailure(reason: PortPreviewFailure, request: Request, port?: number): Promise<Response>;
16
+ /**
17
+ * What a preview answers for a forwarded port reply: the VM host's own
18
+ * refusal in plain words, or the guest's reply as it is, minus cookies.
19
+ */
20
+ export declare function portPreviewReply(response: Response, request: Request, port: number): Promise<Response>;
21
+ export {};
@@ -0,0 +1,106 @@
1
+ import { html, raw } from "hono/html";
2
+ import * as Option from "effect/Option";
3
+ import * as Schema from "effect/Schema";
4
+ /**
5
+ * Names the VM host's own refusal of a port request (vmd's `refusePort` in
6
+ * tooling/celld-platform/computer-vm/vmd-proxy.mjs, which strips it from
7
+ * guest replies), so a preview can tell it from the guest's answer.
8
+ */
9
+ const portFailureHeader = "x-fungi-port-failure";
10
+ const hostRefusalSchema = Schema.Literals([
11
+ "not_running",
12
+ "not_listening",
13
+ "unreachable",
14
+ ]);
15
+ /**
16
+ * The VM host's typed refusal, or null when the reply is the guest's own.
17
+ * vmd pipes an upgrade's bytes raw, so on an upgrade request the header could
18
+ * be the guest's and is never read.
19
+ */
20
+ function hostPortRefusal(response, request) {
21
+ if (request.headers.has("upgrade"))
22
+ return null;
23
+ const named = Schema.decodeUnknownOption(hostRefusalSchema)(response.headers.get(portFailureHeader));
24
+ return Option.isSome(named) ? named.value : null;
25
+ }
26
+ const copy = {
27
+ not_running: () => ({
28
+ title: "This Computer is asleep",
29
+ detail: "Start it from Fungi, then reload this page to see the preview.",
30
+ }),
31
+ not_listening: (port) => ({
32
+ title: port === undefined
33
+ ? "Nothing is answering on this port"
34
+ : `Nothing is answering on port ${String(port)}`,
35
+ detail: "Start the server on this Computer, or check its port, then reload this page.",
36
+ }),
37
+ unreachable: () => ({
38
+ title: "Fungi couldn't reach this Computer",
39
+ detail: "Reload in a moment. If it keeps happening, report it.",
40
+ }),
41
+ expired: () => ({
42
+ title: "This preview link has expired",
43
+ detail: "Open the preview again from Fungi to get a fresh link.",
44
+ }),
45
+ };
46
+ const statuses = {
47
+ not_running: 503,
48
+ not_listening: 502,
49
+ unreachable: 502,
50
+ expired: 403,
51
+ };
52
+ // The preview origin is isolated and loads no Fungi asset, so the page's
53
+ // styling travels inline and follows the viewer's light or dark scheme.
54
+ const style = raw(`<style>
55
+ :root{color-scheme:light dark;--bg:#faf8f4;--card:#fff;--ink:#2a2622;--muted:#6f675e;--line:#e4ded4;--accent:#1f6f54;--accent-ink:#fff}
56
+ @media (prefers-color-scheme:dark){:root{--bg:#171512;--card:#211e1a;--ink:#f0ebe3;--muted:#a39a8e;--line:#3a352e;--accent:#58c29b;--accent-ink:#0f1a15}}
57
+ *{box-sizing:border-box}
58
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;padding:1rem}
59
+ main{width:100%;max-width:28rem;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:1.5rem}
60
+ h1{font-size:1.25rem;margin:0 0 .5rem}
61
+ p{margin:0 0 1rem;color:var(--muted)}
62
+ a{display:inline-block;font-weight:600;border-radius:8px;padding:.45rem 1rem;background:var(--accent);color:var(--accent-ink);text-decoration:none}
63
+ a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
64
+ </style>`);
65
+ /**
66
+ * The one answer a failed preview gives: a styled page in plain words for a
67
+ * browser document, or `{ error: reason }` for a script's request. Raw
68
+ * upstream text never reaches the viewer.
69
+ */
70
+ export async function portPreviewFailure(reason, request, port) {
71
+ const headers = { "Cache-Control": "no-store" };
72
+ const status = statuses[reason];
73
+ if (request.headers.get("sec-fetch-dest") !== "document")
74
+ return Response.json({ error: reason }, { status, headers });
75
+ const { title, detail } = copy[reason](port);
76
+ const page = await html `<!doctype html>
77
+ <html lang="en">
78
+ <meta charset="utf-8" />
79
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
80
+ <title>${title}</title>
81
+ ${style}
82
+ <main>
83
+ <h1>${title}</h1>
84
+ <p>${detail}</p>
85
+ ${reason === "expired" ? "" : html `<a href="">Reload</a>`}
86
+ </main>
87
+ </html>`;
88
+ return new Response(page, {
89
+ status,
90
+ headers: { ...headers, "Content-Type": "text/html; charset=utf-8" },
91
+ });
92
+ }
93
+ /**
94
+ * What a preview answers for a forwarded port reply: the VM host's own
95
+ * refusal in plain words, or the guest's reply as it is, minus cookies.
96
+ */
97
+ export async function portPreviewReply(response, request, port) {
98
+ const refused = hostPortRefusal(response, request);
99
+ if (refused !== null) {
100
+ await response.body?.cancel();
101
+ return await portPreviewFailure(refused, request, port);
102
+ }
103
+ const safe = new Response(response.body, response);
104
+ safe.headers.delete("set-cookie");
105
+ return safe;
106
+ }
package/dist/preview.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { LONG, nanoid } from "@fungi.computer/cairn";
2
2
  import * as Schema from "effect/Schema";
3
3
  import * as Option from "effect/Option";
4
+ import { portPreviewFailure } from "./port-failure.js";
4
5
  const storedClaimsSchema = Schema.Struct({
5
6
  claims: Schema.String,
6
7
  expires_at: Schema.Number,
@@ -108,8 +109,9 @@ export class ComputerPortPreview {
108
109
  }
109
110
  async dispatchSigned(signature, request, forward) {
110
111
  const claims = await this.resolve(signature);
112
+ // An expired, unknown or altered ticket: the viewer needs a fresh link.
111
113
  if (claims === null)
112
- return new Response(null, { status: 403 });
114
+ return await portPreviewFailure("expired", request);
113
115
  return await forward(claims.selector, claims.port, request);
114
116
  }
115
117
  ensureTable() {
@@ -146,6 +148,6 @@ export async function computerPortPreviewRequest(request, origin, host) {
146
148
  return await host.forward(computerId, new Request(destination, forwarded));
147
149
  }
148
150
  catch {
149
- return new Response(null, { status: 503 });
151
+ return await portPreviewFailure("unreachable", request);
150
152
  }
151
153
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.16.0",
3
+ "version": "0.16.2",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Cloudflare Computer host for one durable Fungi Computer",
6
6
  "type": "module",
@@ -79,6 +79,7 @@
79
79
  "esbuild": "0.28.2",
80
80
  "eslint": "10.9.1",
81
81
  "oxlint": "1.78.0",
82
+ "playwright": "1.62.1",
82
83
  "tsx": "4.23.12",
83
84
  "typescript": "5.9.3",
84
85
  "uuid": "11.1.1",
@@ -125,8 +126,9 @@
125
126
  "test:nightly": "bash ../../tooling/proof-runner/run-proof.sh node test/egress-proof.mjs",
126
127
  "test:app-method-execution": "node test/app-method-execution-proof.mjs",
127
128
  "test:home-patch": "node test/home-instructions-patch-proof.mjs",
129
+ "test:preview-failure:browser": "node test/preview-failure.browser.mjs",
128
130
  "test:execution-lifecycle": "node test/execution-lifecycle-proof.mjs",
129
- "test:unit": "bash ../../tooling/proof-runner/hermetic-host.sh -- sh -c \"node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/egress-policy.test.mjs test/preview.test.mjs test/port-access.test.mjs test/process-wait.test.mjs test/fleet.test.mjs test/proof-worker.test.mjs test/proof-client.test.mjs test/native-readiness.test.mjs test/workspace-sync.test.mjs test/runtime-observer.test.mjs test/files-patch.test.mjs test/exec-output.test.mjs && node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/seam-signature.test.mjs test/local-backend-replay.test.mjs test/machine-link-reopen-replay.test.mjs test/computer-backends.test.mjs test/terminal-welcome.test.mjs test/on-box-vm.test.mjs && node test/terminal-protocol.test.mjs && node test/container-policy.test.mjs && node test/files-adapter-proof.mjs && node test/operation-record-proof.mjs && node test/process-inventory-proof.mjs\"",
131
+ "test:unit": "bash ../../tooling/proof-runner/hermetic-host.sh -- sh -c \"node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/egress-policy.test.mjs test/preview.test.mjs test/port-failure.test.mjs test/port-access.test.mjs test/process-wait.test.mjs test/fleet.test.mjs test/proof-worker.test.mjs test/proof-client.test.mjs test/native-readiness.test.mjs test/workspace-sync.test.mjs test/runtime-observer.test.mjs test/files-patch.test.mjs test/exec-output.test.mjs && node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/seam-signature.test.mjs test/local-backend-replay.test.mjs test/machine-link-reopen-replay.test.mjs test/computer-backends.test.mjs test/terminal-welcome.test.mjs test/on-box-vm.test.mjs && node test/terminal-protocol.test.mjs && node test/container-policy.test.mjs && node test/files-adapter-proof.mjs && node test/operation-record-proof.mjs && node test/process-inventory-proof.mjs\"",
130
132
  "test:fleet-native": "node test/fleet.native.mjs",
131
133
  "assemble:image": "node scripts/assemble-image.mjs"
132
134
  }