The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
fix(web): stop reloading unchanged file previews during agent commands (#39736)
Co-authored-by: PixPMusic <PixPMusic@users.noreply.github.com>
Julius Marminge committed
Nov 20, 2026 at 06:26 UTC
391f93fc8fd851a4c2a655ffb8ea64698470d2e2
8 files changed
+390
-31
apps/server/src/assets/AssetAccess.test.ts
+90
@@ -26,6 +26,7 @@ import { HttpClientRequest, HttpClientResponse, HttpServerResponse } from "effec
26
import { vi } from "vite-plus/test";
27
28
import * as AssetSigner from "./AssetSigner.ts";
29
+import * as WorkspacePreviewRevisions from "./WorkspacePreviewRevisions.ts";
30
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
31
import * as ServerConfig from "../config.ts";
32
import { makeFakeWslHost } from "../testUtils/fakeWsl.ts";
@@ -125,6 +126,7 @@ const layerTest = Layer.mergeAll(
126
AssetSigner.layer.pipe(
127
Layer.provideMerge(ServerSecretStore.layer.pipe(Layer.provide(layerConfig))),
128
),
129
+ WorkspacePreviewRevisions.layer,
130
).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
131
132
describe("AssetAccess", () => {
@@ -1278,6 +1280,94 @@ describe("AssetAccess", () => {
1280
}).pipe(Effect.provide(layerTest)),
1281
);
1282
1283
+ it.effect("moves an HTML preview's revision only for the page and the files it requested", () =>
1284
+ Effect.gen(function* () {
1285
+ const fileSystem = yield* FileSystem.FileSystem;
1286
+ const path = yield* Path.Path;
1287
+ const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-asset-revision-" });
1288
+ const pages = path.join(root, "pages");
1289
+ yield* fileSystem.makeDirectory(pages);
1290
+ const write = (name: string, text: string) =>
1291
+ fileSystem.writeFileString(path.join(pages, name), text);
1292
+ yield* write("a.html", '<link rel="stylesheet" href="a.css"><script src="late.js"></script>');
1293
+ yield* write("a.css", "body { color: red; }");
1294
+ yield* write("b.html", "<h1>b</h1>");
1295
+ const mint = (name: string) =>
1296
+ issueAssetUrl({
1297
+ resource: {
1298
+ _tag: "workspace-file",
1299
+ threadId: ThreadId.make("thread-1"),
1300
+ path: path.join(pages, name),
1301
+ },
1302
+ workspaceRoot: root,
1303
+ });
1304
+ const load = Effect.fn(function* (name: string, requests: ReadonlyArray<string>) {
1305
+ const { relativeUrl } = yield* mint(name);
1306
+ const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1307
+ for (const request of requests) {
1308
+ yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), request);
1309
+ }
1310
+ });
1311
+ const revisions = Effect.fn(function* () {
1312
+ return [(yield* mint("a.html")).fileRevision, (yield* mint("b.html")).fileRevision];
1313
+ });
1314
+
1315
+ // Two tabs each load a page; a.html also asks for a script that does not exist yet.
1316
+ const opened = yield* revisions();
1317
+ expect(opened[0]).toBeDefined();
1318
+ expect(opened[1]).not.toBe(opened[0]);
1319
+ yield* load("a.html", ["a.html", "a.css", "late.js"]);
1320
+ yield* load("b.html", ["b.html"]);
1321
+ expect(yield* revisions()).toEqual(opened);
1322
+
1323
+ // Files no page asked for leave both previews alone.
1324
+ yield* write("unrelated.css", "p {}");
1325
+ yield* fileSystem.writeFileString(path.join(root, "notes.md"), "notes");
1326
+ expect(yield* revisions()).toEqual(opened);
1327
+
1328
+ // An edit to one page leaves the page beside it alone.
1329
+ yield* write("b.html", "<h1>B</h1>");
1330
+ const afterPageEdit = yield* revisions();
1331
+ expect(afterPageEdit[0]).toBe(opened[0]);
1332
+ expect(afterPageEdit[1]).not.toBe(opened[1]);
1333
+
1334
+ // A same-size edit to a requested stylesheet reloads only the page that uses it.
1335
+ yield* write("a.css", "body { color: blue }");
1336
+ const afterStyleEdit = yield* revisions();
1337
+ expect(afterStyleEdit[0]).not.toBe(afterPageEdit[0]);
1338
+ expect(afterStyleEdit[1]).toBe(afterPageEdit[1]);
1339
+
1340
+ // So does a requested file that appears, and one that goes away.
1341
+ yield* write("late.js", "document.title = 'late';");
1342
+ const afterCreate = yield* revisions();
1343
+ expect(afterCreate[0]).not.toBe(afterStyleEdit[0]);
1344
+ yield* fileSystem.remove(path.join(pages, "a.css"));
1345
+ const afterRemove = yield* revisions();
1346
+ expect(afterRemove[0]).not.toBe(afterCreate[0]);
1347
+ expect(afterRemove[1]).toBe(afterPageEdit[1]);
1348
+
1349
+ // Overlapping mints after one edit agree, so the edit reloads the page once.
1350
+ yield* write("late.js", "document.title = 'later';");
1351
+ const overlapping = yield* Effect.all(
1352
+ Array.from({ length: 8 }, () => mint("a.html")),
1353
+ { concurrency: "unbounded" },
1354
+ );
1355
+ expect(new Set(overlapping.map((minted) => minted.fileRevision)).size).toBe(1);
1356
+ expect(overlapping[0]?.fileRevision).not.toBe(afterRemove[0]);
1357
+
1358
+ // A page that loads more files than are tracked falls back to the client's own reloads.
1359
+ yield* load(
1360
+ "b.html",
1361
+ Array.from(
1362
+ { length: WorkspacePreviewRevisions.MAX_TRACKED_FILES_PER_DOCUMENT },
1363
+ (_, index) => `chunk-${index}.js`,
1364
+ ),
1365
+ );
1366
+ expect((yield* mint("b.html")).fileRevision).toBeUndefined();
1367
+ expect((yield* mint("a.html")).fileRevision).toBe(overlapping[0]?.fileRevision);
1368
+ }).pipe(Effect.provide(layerTest)),
1369
+ );
1370
+
1371
it.effect("rejects workspace files outside the authorized root", () =>
1372
Effect.gen(function* () {
1373
const fileSystem = yield* FileSystem.FileSystem;
apps/server/src/assets/AssetAccess.ts
+49
-18
@@ -63,7 +63,13 @@ import { toHostDrivePath } from "../workspace/hostDrivePath.ts";
63
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
64
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
65
import { extractIcnsPng } from "./icns.ts";
66
-import { openMediaFile, readMediaFileHeader, type OpenMediaFile } from "./MediaFile.ts";
66
+import {
67
+ mediaFileRevision,
68
+ openMediaFile,
69
+ readMediaFileHeader,
70
+ type OpenMediaFile,
71
+} from "./MediaFile.ts";
72
+import * as WorkspacePreviewRevisions from "./WorkspacePreviewRevisions.ts";
73
import * as HostProcess from "@t3tools/shared/HostProcess";
74
75
export const ASSET_ROUTE_PREFIX = "/api/assets";
@@ -129,6 +135,8 @@ const AssetClaimsSchema = Schema.Union([
135
kind: Schema.Literal("workspace-file"),
136
workspaceRoot: Schema.String,
137
baseRelativePath: Schema.String,
138
+ /** The opened page, which the files it requests are tracked under; absent on older URLs. */
139
+ entryFileName: Schema.optionalKey(Schema.String),
140
expiresAt: Schema.Number,
141
}),
142
Schema.Struct({
@@ -449,7 +457,7 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
457
: Effect.succeed(null),
458
(dimensions) => ({
459
identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
452
- fileRevision: `${file.info.dev}:${file.info.ino}:${file.info.size}:${file.info.mtimeNs}:${file.info.ctimeNs}`,
460
+ fileRevision: mediaFileRevision(file.info),
461
dimensions,
462
}),
463
),
@@ -558,25 +566,36 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
566
)
567
? yield* readImageDimensionsFromHeader(canonicalFile)
568
: null;
569
+ if (!/\.html?$/i.test(resolved.relativePath)) {
570
+ return {
571
+ claims: {
572
+ version: 1 as const,
573
+ kind: "workspace-file-exact" as const,
574
+ workspaceRoot: canonicalWorkspaceRoot,
575
+ relativePath: resolved.relativePath,
576
+ expiresAt: input.expiresAt,
577
+ },
578
+ fileName: path.basename(resolved.relativePath),
579
+ imageDimensions,
580
+ fileRevision: undefined,
581
+ };
582
+ }
583
+ const revisions = yield* WorkspacePreviewRevisions.WorkspacePreviewRevisions;
584
return {
562
- claims: !/\.html?$/i.test(resolved.relativePath)
563
- ? {
564
- version: 1 as const,
565
- kind: "workspace-file-exact" as const,
566
- workspaceRoot: canonicalWorkspaceRoot,
567
- relativePath: resolved.relativePath,
568
- expiresAt: input.expiresAt,
569
- }
570
- : {
571
- version: 1 as const,
572
- kind: "workspace-file" as const,
573
- workspaceRoot: canonicalWorkspaceRoot,
574
- baseRelativePath: path.dirname(resolved.relativePath),
575
- expiresAt: input.expiresAt,
576
- },
585
+ claims: {
586
+ version: 1 as const,
587
+ kind: "workspace-file" as const,
588
+ workspaceRoot: canonicalWorkspaceRoot,
589
+ baseRelativePath: path.dirname(resolved.relativePath),
590
+ entryFileName: path.basename(resolved.relativePath),
591
+ expiresAt: input.expiresAt,
592
+ },
593
fileName: path.basename(resolved.relativePath),
594
imageDimensions,
579
- fileRevision: undefined,
595
+ fileRevision: yield* revisions.revision({
596
+ workspaceRoot: canonicalWorkspaceRoot,
597
+ entryRelativePath: resolved.relativePath,
598
+ }),
599
};
600
},
601
);
@@ -654,6 +673,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
673
claims = finalized.claims;
674
fileName = finalized.fileName;
675
imageDimensions = finalized.imageDimensions;
676
+ fileRevision = finalized.fileRevision;
677
break;
678
}
679
case "draft-workspace-file": {
@@ -1105,6 +1125,17 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
1125
if (!isPreviewDependencyPath(decodedPath, path)) return null;
1126
const joinedRelativePath =
1127
claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
1128
+ if (claims.entryFileName !== undefined) {
1129
+ // Before the file is resolved and read, so the recorded state is never newer than the response.
1130
+ const revisions = yield* WorkspacePreviewRevisions.WorkspacePreviewRevisions;
1131
+ yield* revisions.observe(
1132
+ {
1133
+ workspaceRoot: claims.workspaceRoot,
1134
+ entryRelativePath: path.join(claims.baseRelativePath, claims.entryFileName),
1135
+ },
1136
+ joinedRelativePath,
1137
+ );
1138
+ }
1139
const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1140
workspaceRoot: claims.workspaceRoot,
1141
relativePath: joinedRelativePath,
apps/server/src/assets/MediaFile.ts
+10
@@ -93,6 +93,16 @@ export const openMediaFile = Effect.fn("openMediaFile")(function* (
93
);
94
});
95
96
+/** Identity, size and nanosecond times, so it moves whenever the file is edited or replaced. */
97
+export const mediaFileRevision = (info: NodeFS.BigIntStats) =>
98
+ `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
99
+
100
+/** Follows links, as serving the path does. Null when nothing can be read there. */
101
+export const readFileRevision = (filePath: string) =>
102
+ Effect.promise(() =>
103
+ NodeFSP.stat(filePath, { bigint: true }).then(mediaFileRevision, () => null),
104
+ );
105
+
106
export const readMediaFileHeader = (filePath: string, file: OpenMediaFile, byteCount: number) =>
107
Effect.tryPromise({
108
try: async () => {
apps/server/src/assets/WorkspacePreviewRevisions.ts
new
+118
@@ -0,0 +1,118 @@
1
+import * as Context from "effect/Context";
2
+import * as SecureRandom from "effect/crypto/SecureRandom";
3
+import * as Effect from "effect/Effect";
4
+import * as Layer from "effect/Layer";
5
+import * as Path from "effect/Path";
6
+import * as Semaphore from "effect/Semaphore";
7
+
8
+import { readFileRevision } from "./MediaFile.ts";
9
+
10
+const MAX_TRACKED_DOCUMENTS = 64;
11
+export const MAX_TRACKED_FILES_PER_DOCUMENT = 256;
12
+const REVISION_READ_CONCURRENCY = 8;
13
+
14
+/** One opened HTML page: the canonical workspace root and the page's path below it. */
15
+export interface PreviewDocument {
16
+ readonly workspaceRoot: string;
17
+ readonly entryRelativePath: string;
18
+}
19
+
20
+interface DocumentState {
21
+ version: number;
22
+ /** The page loads more files than are tracked, so no revision can speak for it. */
23
+ overflowed: boolean;
24
+ /** What each file the page asked for looked like when last compared; null while it is missing. */
25
+ readonly files: Map<string, string | null>;
26
+ /** Reads are recorded one batch at a time, so an older read never overwrites a newer one. */
27
+ readonly comparing: Semaphore.Semaphore;
28
+}
29
+
30
+/**
31
+ * Tells an unchanged HTML preview from an edited one. A page's revision covers the page and the
32
+ * files it has requested, and no other file: an edit elsewhere, even next to it, leaves it alone.
33
+ */
34
+export class WorkspacePreviewRevisions extends Context.Service<
35
+ WorkspacePreviewRevisions,
36
+ {
37
+ /** Undefined when the page cannot be tracked; the client then reloads on workspace changes. */
38
+ readonly revision: (document: PreviewDocument) => Effect.Effect<string | undefined>;
39
+ /** Records a file the page requested, found or not, as part of the page. */
40
+ readonly observe: (document: PreviewDocument, relativePath: string) => Effect.Effect<void>;
41
+ }
42
+>()("t3/assets/WorkspacePreviewRevisions") {}
43
+
44
+const make = Effect.gen(function* () {
45
+ const path = yield* Path.Path;
46
+ // Tracked files are forgotten on restart, so revisions from an earlier process must not match.
47
+ const processId = yield* (yield* SecureRandom.SecureRandom).uuidV4();
48
+ // Insertion order is recency: the least recently minted document is dropped first.
49
+ const documents = new Map<string, DocumentState>();
50
+ // One counter for all documents, so a document tracked again never repeats a revision.
51
+ let versions = 0;
52
+
53
+ const documentKey = (document: PreviewDocument) =>
54
+ JSON.stringify([document.workspaceRoot, document.entryRelativePath]);
55
+
56
+ const record = (state: DocumentState, relativePath: string, revision: string | null) => {
57
+ if (!state.files.has(relativePath)) {
58
+ if (state.files.size >= MAX_TRACKED_FILES_PER_DOCUMENT) state.overflowed = true;
59
+ else state.files.set(relativePath, revision);
60
+ return;
61
+ }
62
+ if (state.files.get(relativePath) === revision) return;
63
+ state.files.set(relativePath, revision);
64
+ state.version = ++versions;
65
+ };
66
+
67
+ const revision = Effect.fn("WorkspacePreviewRevisions.revision")(function* (
68
+ document: PreviewDocument,
69
+ ) {
70
+ const key = documentKey(document);
71
+ const state = documents.get(key) ?? {
72
+ version: ++versions,
73
+ overflowed: false,
74
+ files: new Map<string, string | null>(),
75
+ comparing: Semaphore.makeUnsafe(1),
76
+ };
77
+ documents.delete(key);
78
+ documents.set(key, state);
79
+ if (documents.size > MAX_TRACKED_DOCUMENTS) {
80
+ for (const oldest of documents.keys()) {
81
+ documents.delete(oldest);
82
+ break;
83
+ }
84
+ }
85
+ return yield* state.comparing.withPermits(1)(
86
+ Effect.gen(function* () {
87
+ const relativePaths = [...new Set([document.entryRelativePath, ...state.files.keys()])];
88
+ const revisions = yield* Effect.forEach(
89
+ relativePaths,
90
+ (relativePath) => readFileRevision(path.join(document.workspaceRoot, relativePath)),
91
+ { concurrency: REVISION_READ_CONCURRENCY },
92
+ );
93
+ for (const [index, relativePath] of relativePaths.entries()) {
94
+ record(state, relativePath, revisions[index] ?? null);
95
+ }
96
+ return state.overflowed ? undefined : `${processId}:${state.version}`;
97
+ }),
98
+ );
99
+ });
100
+
101
+ const observe = Effect.fn("WorkspacePreviewRevisions.observe")(function* (
102
+ document: PreviewDocument,
103
+ relativePath: string,
104
+ ) {
105
+ // A document nobody minted here gets a new revision on its next mint, which reloads it.
106
+ const state = documents.get(documentKey(document));
107
+ if (state === undefined) return;
108
+ yield* state.comparing.withPermits(1)(
109
+ Effect.map(readFileRevision(path.join(document.workspaceRoot, relativePath)), (revision) =>
110
+ record(state, relativePath, revision),
111
+ ),
112
+ );
113
+ });
114
+
115
+ return WorkspacePreviewRevisions.of({ revision, observe });
116
+});
117
+
118
+export const layer = Layer.effect(WorkspacePreviewRevisions, make);
apps/server/src/server.ts
+4
-1
@@ -3,6 +3,7 @@ import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay
3
import * as Random from "effect/Random";
4
import * as EnvironmentKeys from "./cloud/environmentKeys.ts";
5
import * as AssetSigner from "./assets/AssetSigner.ts";
6
+import * as WorkspacePreviewRevisions from "./assets/WorkspacePreviewRevisions.ts";
7
import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
8
import * as StorageCleanup from "./storageCleanup.ts";
9
import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
@@ -799,7 +800,9 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe(
800
Layer.provideMerge(CodexManagedTokenBroker.layer),
801
Layer.provideMerge(layerServerEnvironment),
802
Layer.provideMerge(layerAuth),
802
- Layer.provideMerge(Layer.mergeAll(AssetSigner.layer, EnvironmentKeys.layer)),
803
+ Layer.provideMerge(
804
+ Layer.mergeAll(AssetSigner.layer, EnvironmentKeys.layer, WorkspacePreviewRevisions.layer),
805
+ ),
806
Layer.provideMerge(ServerSecretStore.layer),
807
Layer.provideMerge(
808
Layer.mergeAll(
apps/server/src/ws.test.ts
+2
@@ -69,6 +69,7 @@ import * as Statement from "effect/sql/Statement";
69
import { vi } from "vite-plus/test";
70
71
import * as AssetSigner from "./assets/AssetSigner.ts";
72
+import * as WorkspacePreviewRevisions from "./assets/WorkspacePreviewRevisions.ts";
73
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
74
import * as ServerBrowser from "./preview/ServerBrowser.ts";
75
import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
@@ -900,6 +901,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
901
const layerConfigSources = Layer.mergeAll(
902
Keybindings.layer,
903
AssetSigner.layer.pipe(Layer.provide(ServerSecretStore.layer)),
904
+ WorkspacePreviewRevisions.layer,
905
ServerSettings.layer.pipe(
906
Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
907
),
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+53
-1
@@ -1,5 +1,5 @@
1
import DocumentPages, { sanitizeDocumentHtml } from "./DocumentPages";
2
-import { act, render, stubGlobal, type Screen } from "../../../test/render";
2
+import { act, fakeTimers, render, stubGlobal, type Screen } from "../../../test/render";
3
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4
import { describe, expect, it, vi } from "vite-plus/test";
5
import { page, userEvent } from "vite-plus/test/browser";
@@ -1592,6 +1592,58 @@ it("loads an edited HTML file outside the workspace from a renewed URL", async (
1592
);
1593
});
1594
1595
+it("keeps an unchanged workspace HTML page loaded across commands and renews its grant", async () => {
1596
+ const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel");
1597
+ const preview = (mutation: string) => (
1598
+ <WorkspaceBrowserPreview
1599
+ environmentId={EnvironmentId.make("test")}
1600
+ threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }}
1601
+ draft={false}
1602
+ workspaceRoot="/repo"
1603
+ absolutePath="/repo/report.html"
1604
+ title="Report"
1605
+ workspaceMutationId={mutation}
1606
+ />
1607
+ );
1608
+ const minted = (url: string, fileRevision: string, expiresAt: number) =>
1609
+ assetUrlState.mockReturnValue({ _tag: "Success", url, expiresAt, fileRevision });
1610
+ const shownSrc = (screen: Screen) =>
1611
+ screen.container.querySelector("iframe")?.getAttribute("src");
1612
+ refresh.mockReset();
1613
+ using _timers = fakeTimers();
1614
+ vi.setSystemTime(0);
1615
+ const expiresAt = 60 * 60_000;
1616
+ minted("data:text/html,original", "one", expiresAt);
1617
+ await using screen = await render(preview("first"));
1618
+ const opened = screen.container.querySelector("iframe");
1619
+ expect(shownSrc(screen)).toMatch(/^data:text\/html,original/);
1620
+
1621
+ // Agent commands re-mint the URL; the page and everything it loaded are unchanged.
1622
+ minted("data:text/html,renewed", "one", expiresAt + 30 * 60_000);
1623
+ await screen.rerender(preview("second"));
1624
+ await screen.rerender(preview("third"));
1625
+ expect(screen.container.querySelector("iframe")).toBe(opened);
1626
+ expect(shownSrc(screen)).toMatch(/^data:text\/html,original/);
1627
+ expect(refresh).not.toHaveBeenCalled();
1628
+
1629
+ // Its grant is about to expire, so the page moves to the URL minted since.
1630
+ await act(() => vi.advanceTimersByTime(59 * 60_000));
1631
+ expect(shownSrc(screen)).toMatch(/^data:text\/html,renewed/);
1632
+ expect(refresh).not.toHaveBeenCalled();
1633
+
1634
+ // With no command since, the page asks for a fresh URL itself and moves to it.
1635
+ refresh.mockResolvedValue(null);
1636
+ await act(() => vi.advanceTimersByTime(30 * 60_000));
1637
+ expect(refresh).toHaveBeenCalledTimes(1);
1638
+ minted("data:text/html,renewed-again", "one", expiresAt + 90 * 60_000);
1639
+ await screen.rerender(preview("third"));
1640
+ expect(shownSrc(screen)).toMatch(/^data:text\/html,renewed-again/);
1641
+
1642
+ minted("data:text/html,edited", "two", expiresAt + 90 * 60_000);
1643
+ await screen.rerender(preview("fourth"));
1644
+ expect(shownSrc(screen)).toMatch(/^data:text\/html,edited/);
1645
+});
1646
+
1647
function planningPdf(
1648
titles = ["Quarterly outlook", "Delivery milestones", "Budget and risks"],
1649
firstHeight = 140,
apps/web/src/components/files/FilePreviewPanel.tsx
+64
-11
@@ -55,6 +55,7 @@ import {
55
lazy,
56
Suspense,
57
useEffect,
58
+ useEffectEvent,
59
useRef,
60
useState,
61
type KeyboardEvent as ReactKeyboardEvent,
@@ -237,6 +238,33 @@ function WorkspaceImagePreview(props: {
238
);
239
}
240
241
+interface HtmlPreviewFrame {
242
+ readonly revision: string | null;
243
+ readonly url: string;
244
+ /** When the loaded page's grant is about to expire and a fresh URL has to replace it. */
245
+ readonly renewAt: number;
246
+}
247
+
248
+const HTML_PREVIEW_RENEW_BEFORE_EXPIRY_MS = 2 * 60_000;
249
+// Grants last an hour. A client clock far from the server's would otherwise renew at once, forever.
250
+const HTML_PREVIEW_MIN_GRANT_HOLD_MS = 3 * 60_000;
251
+const HTML_PREVIEW_MAX_GRANT_HOLD_MS = 60 * 60_000;
252
+
253
+const htmlPreviewFrame = (
254
+ minted: { readonly revision: string | null; readonly url: string; readonly expiresAt: number },
255
+ now: number,
256
+): HtmlPreviewFrame => ({
257
+ revision: minted.revision,
258
+ url: minted.url,
259
+ renewAt: Math.min(
260
+ Math.max(
261
+ minted.expiresAt - HTML_PREVIEW_RENEW_BEFORE_EXPIRY_MS,
262
+ now + HTML_PREVIEW_MIN_GRANT_HOLD_MS,
263
+ ),
264
+ now + HTML_PREVIEW_MAX_GRANT_HOLD_MS,
265
+ ),
266
+});
267
+
268
export function WorkspaceBrowserPreview(props: {
269
readonly environmentId: EnvironmentId;
270
readonly threadRef: ScopedThreadRef;
@@ -257,21 +285,45 @@ export function WorkspaceBrowserPreview(props: {
285
// Each workspace mutation re-mints the URL: a file outside the workspace is signed by its
286
// inode, which an atomic replace changes.
287
const assetUrl = useAssetUrlState(props.environmentId, resource, props.workspaceMutationId);
260
- // The HTML frame keeps its first URL per key, so the key moves only once the re-minted URL arrives.
261
- const [settledMutationId, setSettledMutationId] = useState(props.workspaceMutationId);
288
+ const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
289
+ // Servers that report the file's revision let an unchanged page stay loaded; older ones only
290
+ // offer the workspace mutation, which changes after every command.
291
+ const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined;
292
+ const latestRevision = fileRevision ?? props.workspaceMutationId;
293
+ // The HTML frame keeps the URL it loaded, so it moves only once a re-minted URL has arrived.
294
+ const [frame, setFrame] = useState<HtmlPreviewFrame | null>(null);
295
+ const [endingGrant, setEndingGrant] = useState<string | null>(null);
296
+ const grantEnding = frame !== null && endingGrant === frame.url;
297
if (
298
+ !pdf &&
299
assetUrl._tag === "Success" &&
264
- !assetUrl.waiting &&
265
- settledMutationId !== props.workspaceMutationId
300
+ (frame === null ||
301
+ (!assetUrl.waiting &&
302
+ (frame.revision !== latestRevision || (grantEnding && frame.url !== assetUrl.url))))
303
) {
267
- setSettledMutationId(props.workspaceMutationId);
304
+ const { url, expiresAt } = assetUrl;
305
+ setFrame(() => htmlPreviewFrame({ revision: latestRevision, url, expiresAt }, Date.now()));
306
}
269
- const fileRevision = pdf && assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined;
270
- const revision = fileRevision ?? (pdf ? props.workspaceMutationId : settledMutationId);
307
+ const renewGrant = useEffectEvent((url: string) => {
308
+ setEndingGrant(url);
309
+ // A command may have minted the next URL already; otherwise ask for it.
310
+ if (assetUrl._tag === "Success" && assetUrl.url === url) {
311
+ void refreshAssetUrl().catch(() => undefined);
312
+ }
313
+ });
314
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mints a fresh URL shortly before the loaded page's grant expires
315
+ useEffect(() => {
316
+ if (frame === null) return;
317
+ const timer = setTimeout(() => renewGrant(frame.url), frame.renewAt - Date.now());
318
+ return () => clearTimeout(timer);
319
+ }, [frame]);
320
+ const revision = pdf ? latestRevision : (frame?.revision ?? latestRevision);
321
+ const url =
322
+ assetUrl._tag !== "Success" ? null : pdf ? assetUrl.url : (frame?.url ?? assetUrl.url);
323
const revisionSuffix =
324
revision === null
325
? ""
274
- : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}${fileRevision !== undefined ? "file" : "workspace"}-revision=${encodeURIComponent(revision)}`;
326
+ : `${url?.includes("?") ? "&" : "?"}${fileRevision !== undefined ? "file" : "workspace"}-revision=${encodeURIComponent(revision)}`;
327
328
if (assetUrl._tag === "Failure") {
329
return (
@@ -290,11 +342,12 @@ export function WorkspaceBrowserPreview(props: {
342
</div>
343
);
344
}
345
+ const documentId = `${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}`;
346
return (
347
<BrowserDocumentFrame
295
- src={`${assetUrl.url}${revisionSuffix}`}
296
- documentKey={`${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}:${revision}`}
297
- documentId={`${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}`}
348
+ src={`${url}${revisionSuffix}`}
349
+ documentKey={`${documentId}:${revision}${pdf ? "" : `:${frame?.renewAt}`}`}
350
+ documentId={documentId}
351
title={props.title}
352
pdf={pdf}
353
pdfActions={