Skip to content

Commit 08544ba

Browse files
juliusmarmingeclaudeYash-Singh1
authored
fix(web): open documents no longer reload after every agent command (#32693)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Yash Singh <[email protected]>
1 parent e4025c8 commit 08544ba

2 files changed

Lines changed: 154 additions & 19 deletions

File tree

‎apps/web/src/components/files/FilePreviewPanel.browser.test.tsx‎

Lines changed: 86 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ const state = vi.hoisted(() => ({
1717
file: null as ProjectReadFileResult | null,
1818
optimistic: null as ProjectReadFileResult | null,
1919
writeFile: vi.fn(),
20+
assetUrl: { _tag: "Loading" } as import("~/assets/assetUrls").AssetUrlState,
21+
mintUrl: vi.fn<() => Promise<string | null>>(),
2022
}));
2123

2224
vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
@@ -58,6 +60,15 @@ vi.mock(import("~/hooks/useTheme"), async (original) => ({
5860
vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({
5961
useWorkspaceMutationRefresh: vi.fn(),
6062
}));
63+
vi.mock(import("~/assets/assetUrls"), async (original) => ({
64+
...(await original()),
65+
useAssetUrlRefresh: () => state.mintUrl,
66+
useAssetUrlState: () => state.assetUrl,
67+
}));
68+
// The Word engine compiles a large WebAssembly bundle; these tests only need the URL it loads.
69+
vi.mock(import("./OfficeFilePreview"), () => ({
70+
OfficeFilePreview: ({ src }: { src: string }) => <div data-testid="office-preview">{src}</div>,
71+
}));
6172
vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <></> }));
6273
vi.mock(import("./FileBrowserPanel"), () => ({
6374
default: () => (
@@ -109,6 +120,9 @@ function setup() {
109120
localStorage.setItem(keys[1]!, "true");
110121
state.file = null;
111122
state.optimistic = null;
123+
state.assetUrl = { _tag: "Loading" };
124+
let mints = 0;
125+
state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`);
112126
state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
113127
return {
114128
[Symbol.dispose]() {
@@ -131,7 +145,7 @@ function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of
131145
return filePreview("tasks.md");
132146
}
133147

134-
function filePreview(relativePath: string) {
148+
function filePreview(relativePath: string, workspaceMutationId: string | null = null) {
135149
return (
136150
<FilePreviewPanel
137151
environmentId={environmentId}
@@ -150,11 +164,22 @@ function filePreview(relativePath: string) {
150164
folderTrail={undefined}
151165
onPendingChange={vi.fn()}
152166
selectedFilePending={false}
153-
workspaceMutationId={null}
167+
workspaceMutationId={workspaceMutationId}
154168
/>
155169
);
156170
}
157171

172+
function documentPreview(workspaceMutationId: string, fileRevision: string) {
173+
state.file = null;
174+
state.assetUrl = {
175+
_tag: "Success",
176+
url: "/assets/report.docx",
177+
expiresAt: Number.MAX_SAFE_INTEGER,
178+
fileRevision,
179+
};
180+
return filePreview("report.docx", workspaceMutationId);
181+
}
182+
158183
function deepActiveElement() {
159184
let active = document.activeElement;
160185
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
@@ -279,6 +304,65 @@ describe("rendered Markdown task saves", () => {
279304
});
280305
});
281306

307+
describe("workspace document previews", () => {
308+
it("keeps an unchanged document loaded when another workspace change lands", async () => {
309+
using _settings = setup();
310+
await using screen = await render(documentPreview("mutation-1", "revision-1"));
311+
const preview = screen.getByTestId("office-preview");
312+
await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
313+
const loaded = preview.element();
314+
315+
await screen.rerender(documentPreview("mutation-2", "revision-1"));
316+
317+
expect(state.mintUrl, "an unchanged document re-minted its URL").toHaveBeenCalledOnce();
318+
expect(screen.container.contains(loaded), "an unchanged document was remounted").toBe(true);
319+
});
320+
321+
it("keeps an unchanged document mounted while its revision check reloads", async () => {
322+
using _settings = setup();
323+
await using screen = await render(documentPreview("mutation-1", "revision-1"));
324+
const preview = screen.getByTestId("office-preview");
325+
await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
326+
const loaded = preview.element();
327+
328+
state.assetUrl = { _tag: "Loading" };
329+
await screen.rerender(filePreview("report.docx", "mutation-1"));
330+
await screen.rerender(documentPreview("mutation-1", "revision-1"));
331+
332+
expect(
333+
state.mintUrl,
334+
"a reloading revision check re-minted the document URL",
335+
).toHaveBeenCalledOnce();
336+
expect(
337+
screen.container.contains(loaded),
338+
"a reloading revision check remounted the document",
339+
).toBe(true);
340+
});
341+
342+
it("reloads the document when its URL can no longer be minted", async () => {
343+
using _settings = setup();
344+
await using screen = await render(documentPreview("mutation-1", "revision-1"));
345+
const preview = screen.getByTestId("office-preview");
346+
await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
347+
348+
state.assetUrl = { _tag: "Failure" };
349+
await screen.rerender(filePreview("report.docx", "mutation-2"));
350+
351+
await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
352+
});
353+
354+
it("loads the new bytes when the document itself changes", async () => {
355+
using _settings = setup();
356+
await using screen = await render(documentPreview("mutation-1", "revision-1"));
357+
const preview = screen.getByTestId("office-preview");
358+
await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
359+
360+
await screen.rerender(documentPreview("mutation-2", "revision-2"));
361+
362+
await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
363+
});
364+
});
365+
282366
describe("rendered Markdown select all", () => {
283367
it("selects only the rendered file, including after a task toggle", async () => {
284368
using _settings = setup();

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 68 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,64 @@ function WorkspaceAudioPreview(props: {
398398
);
399399
}
400400

401+
function WorkspaceDocumentPreview(props: {
402+
readonly environmentId: EnvironmentId;
403+
readonly threadRef: ScopedThreadRef;
404+
readonly draft: boolean;
405+
readonly document: boolean;
406+
readonly absolutePath: string;
407+
readonly workspaceRoot: string;
408+
readonly name: string;
409+
readonly workspaceMutationId: string | null;
410+
readonly refreshRevision: number;
411+
}) {
412+
const resource =
413+
props.draft && props.document
414+
? {
415+
_tag: "draft-workspace-file" as const,
416+
cwd: props.workspaceRoot,
417+
path: props.absolutePath,
418+
}
419+
: {
420+
_tag: "media-file" as const,
421+
threadId: props.threadRef.threadId,
422+
path: props.absolutePath,
423+
...(props.document ? {} : { disposition: "attachment" as const }),
424+
};
425+
// Drafts keep reloading on every workspace mutation, as before.
426+
const revisioned = resource._tag === "media-file";
427+
const assetUrl = useAssetUrlState(
428+
props.environmentId,
429+
revisioned ? resource : null,
430+
props.workspaceMutationId ?? undefined,
431+
);
432+
const resolved =
433+
assetUrl._tag === "Success" ? (assetUrl.fileRevision ?? props.workspaceMutationId) : undefined;
434+
// A reconnect reports Loading and keeps the last revision, so the open file stays loaded;
435+
// a failure (say the file was deleted) remounts so the preview shows its error.
436+
const [shown, setShown] = useState(resolved);
437+
if (resolved !== undefined && resolved !== shown) setShown(resolved);
438+
const revision = !revisioned
439+
? props.workspaceMutationId
440+
: assetUrl._tag === "Failure"
441+
? `failure:${props.workspaceMutationId}`
442+
: (resolved ?? shown);
443+
// Waiting on the first revision keeps the preview from mounting twice when it opens.
444+
if (revisioned && revision === undefined && assetUrl._tag === "Loading") {
445+
return <FileSurfaceLoading />;
446+
}
447+
return (
448+
<AttachmentFilePreview
449+
key={`${revision}:${props.refreshRevision}`}
450+
name={props.name}
451+
mimeType="application/octet-stream"
452+
sizeBytes={0}
453+
asset={{ environmentId: props.environmentId, resource }}
454+
origin="File"
455+
/>
456+
);
457+
}
458+
401459
function clampFileLine(contents: string, requestedLine: number): number {
402460
let lineCount = 1;
403461
for (let index = 0; index < contents.length; index += 1) {
@@ -1538,24 +1596,17 @@ export default function FilePreviewPanel({
15381596
) : relativePath &&
15391597
absolutePath &&
15401598
(isDocument || file.readError?.failure === "binary_file") ? (
1541-
<AttachmentFilePreview
1542-
key={`${environmentId}:${absolutePath}:${workspaceMutationId}:${fileRefreshRevision}`}
1599+
<WorkspaceDocumentPreview
1600+
key={`${environmentId}:${absolutePath}`}
1601+
environmentId={environmentId}
1602+
threadRef={threadRef}
1603+
draft={draft}
1604+
document={isDocument}
1605+
absolutePath={absolutePath}
1606+
workspaceRoot={cwd}
15431607
name={relativePath.split(/[\\/]/).at(-1) || relativePath}
1544-
mimeType="application/octet-stream"
1545-
sizeBytes={0}
1546-
asset={{
1547-
environmentId,
1548-
resource:
1549-
draft && isDocument
1550-
? { _tag: "draft-workspace-file", cwd, path: absolutePath }
1551-
: {
1552-
_tag: "media-file",
1553-
threadId: threadRef.threadId,
1554-
path: absolutePath,
1555-
...(isDocument ? {} : { disposition: "attachment" as const }),
1556-
},
1557-
}}
1558-
origin="File"
1608+
workspaceMutationId={workspaceMutationId}
1609+
refreshRevision={fileRefreshRevision}
15591610
/>
15601611
) : relativePath && file.error && file.data === null ? (
15611612
<div

0 commit comments

Comments
 (0)