From d7cf9e91e7c5703078a6a5fca64cd2905dcf6cfb Mon Sep 17 00:00:00 2001 From: Muhammad Ahsan <60807660+ahsansheikh94@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:09:00 +0000 Subject: [PATCH] fix(playground): keep multi-file output consistent after a failed compilation Snapshot every emitted file after a successful compile and reuse that snapshot when a later compile fails and clears tsp-output. --- .../playground-multi-file-output-snapshot.md | 7 + .../src/react/compilation/output-snapshot.ts | 117 ++++++++++++++ .../src/react/hooks/use-compilation.ts | 48 +++--- .../src/react/output-view/file-viewer.tsx | 11 +- .../src/react/output-view/output-view.tsx | 1 + packages/playground/src/react/types.ts | 13 ++ packages/playground/test/file-viewer.test.tsx | 102 ++++++++++++ .../playground/test/output-snapshot.test.ts | 145 ++++++++++++++++++ 8 files changed, 416 insertions(+), 28 deletions(-) create mode 100644 .chronus/changes/playground-multi-file-output-snapshot.md create mode 100644 packages/playground/src/react/compilation/output-snapshot.ts create mode 100644 packages/playground/test/file-viewer.test.tsx create mode 100644 packages/playground/test/output-snapshot.test.ts diff --git a/.chronus/changes/playground-multi-file-output-snapshot.md b/.chronus/changes/playground-multi-file-output-snapshot.md new file mode 100644 index 00000000000..3342ec7224d --- /dev/null +++ b/.chronus/changes/playground-multi-file-output-snapshot.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/playground" +--- + +Keep every retained output file on the latest successful compilation after a later compile fails. Multi-file output could previously show an older copy of a file, or be blank if that file had not been opened. diff --git a/packages/playground/src/react/compilation/output-snapshot.ts b/packages/playground/src/react/compilation/output-snapshot.ts new file mode 100644 index 00000000000..8a562f4bae8 --- /dev/null +++ b/packages/playground/src/react/compilation/output-snapshot.ts @@ -0,0 +1,117 @@ +import type { CompilationState, CompileResult } from "../types.js"; + +/** + * Character budget for a multi-file output snapshot. + * A single emitted file is always retained so the one-file fallback stays intact. + * Further files are kept, in output order, while they fit entirely in the budget. + */ +export const MULTI_FILE_OUTPUT_SNAPSHOT_CHAR_BUDGET = 32 * 1024 * 1024; + +/** File list and text from the latest compilation whose output was fully readable. */ +export interface RetainedOutput { + readonly outputFiles: readonly string[]; + readonly outputFileContents: ReadonlyMap; +} + +export interface OutputSnapshotHost { + readFile(path: string): Promise<{ readonly text: string }>; +} + +export function emptyRetainedOutput(): RetainedOutput { + return { outputFiles: [], outputFileContents: new Map() }; +} + +/** + * Keep one consistent snapshot. Multi-file output that would exceed `maxChars` + * drops the files that do not fit instead of growing without a bound. + */ +export function boundOutputSnapshot( + outputFiles: readonly string[], + contents: ReadonlyMap, + maxChars = MULTI_FILE_OUTPUT_SNAPSHOT_CHAR_BUDGET, +): Map { + if (outputFiles.length <= 1) { + const only = outputFiles[0]; + const text = only === undefined ? undefined : contents.get(only); + return text === undefined ? new Map() : new Map([[only, text]]); + } + + const bounded = new Map(); + let used = 0; + for (const path of outputFiles) { + const text = contents.get(path); + if (text === undefined) continue; + if (text.length > maxChars || used + text.length > maxChars) continue; + bounded.set(path, text); + used += text.length; + } + return bounded; +} + +/** + * Read every emitted file. Returns undefined if any file is missing so the caller + * keeps the previous snapshot instead of mixing two compilations. + */ +export async function readOutputSnapshot( + host: OutputSnapshotHost, + outputFiles: readonly string[], + maxChars = MULTI_FILE_OUTPUT_SNAPSHOT_CHAR_BUDGET, +): Promise | undefined> { + const contents = new Map(); + for (const path of outputFiles) { + try { + const file = await host.readFile("./tsp-output/" + path); + contents.set(path, file.text); + } catch { + return undefined; + } + } + return boundOutputSnapshot(outputFiles, contents, maxChars); +} + +export interface DisplayedOutput { + readonly displayed: CompilationState; + readonly retained: RetainedOutput; + readonly isOutputStale: boolean; +} + +/** + * Choose the output shown in the playground. + * A failed compilation that emitted nothing keeps the previous file list and the + * snapshot taken when those files were actually written. + */ +export function resolveDisplayedOutput( + state: CompilationState, + retained: RetainedOutput, + snapshot: ReadonlyMap | undefined, +): DisplayedOutput { + if (!("program" in state)) { + return { displayed: state, retained, isOutputStale: false }; + } + + if ( + state.program.hasError() && + state.outputFiles.length === 0 && + retained.outputFiles.length > 0 + ) { + const displayed: CompileResult = { + ...state, + outputFiles: [...retained.outputFiles], + outputFileContents: retained.outputFileContents, + }; + return { displayed, retained, isOutputStale: true }; + } + + const nextRetained: RetainedOutput = + state.outputFiles.length > 0 + ? { + outputFiles: [...state.outputFiles], + outputFileContents: snapshot ?? retained.outputFileContents, + } + : retained; + + const displayed: CompileResult = + state.outputFiles.length > 0 && snapshot ? { ...state, outputFileContents: snapshot } : state; + + return { displayed, retained: nextRetained, isOutputStale: false }; +} diff --git a/packages/playground/src/react/hooks/use-compilation.ts b/packages/playground/src/react/hooks/use-compilation.ts index 3b1c2a404d1..dca7f515056 100644 --- a/packages/playground/src/react/hooks/use-compilation.ts +++ b/packages/playground/src/react/hooks/use-compilation.ts @@ -4,6 +4,12 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { getMonacoRange, updateDiagnosticsForCodeFixes } from "../../services.js"; import type { BrowserHost } from "../../types.js"; import { compile } from "../compilation/compile.js"; +import { + emptyRetainedOutput, + readOutputSnapshot, + resolveDisplayedOutput, + type RetainedOutput, +} from "../compilation/output-snapshot.js"; import { debugGlobals } from "../debug.js"; import type { CompilationState } from "../types.js"; @@ -31,11 +37,11 @@ export function useCompilation({ const [compilationState, setCompilationState] = useState(undefined); const [isCompiling, setIsCompiling] = useState(false); const [isOutputStale, setIsOutputStale] = useState(false); - const lastSuccessfulOutputRef = useRef([]); + const retainedOutputRef = useRef(emptyRetainedOutput()); // Clear preserved output when switching emitters useEffect(() => { - lastSuccessfulOutputRef.current = []; + retainedOutputRef.current = emptyRetainedOutput(); setIsOutputStale(false); }, [selectedEmitter]); @@ -69,6 +75,18 @@ export function useCompilation({ } return; } + // Snapshot while this compile still holds the lock. The next compile clears + // tsp-output before emitting, so this is the last moment every emitted file + // is readable together. + let snapshot: ReadonlyMap | undefined; + if ("program" in state && state.outputFiles.length > 0) { + try { + snapshot = await readOutputSnapshot(host, state.outputFiles); + } catch { + snapshot = undefined; + } + } + isCompilingRef.current = false; setIsCompiling(false); @@ -76,26 +94,12 @@ export function useCompilation({ if (compileId !== compileIdRef.current) return; // When compilation has errors and produced no output files, preserve the - // previous successful output so the user doesn't lose their selected file - // while typing (transient syntax errors). - if ( - "program" in state && - state.program.hasError() && - state.outputFiles.length === 0 && - lastSuccessfulOutputRef.current.length > 0 - ) { - setIsOutputStale(true); - setCompilationState({ - ...state, - outputFiles: lastSuccessfulOutputRef.current, - }); - } else { - setIsOutputStale(false); - if ("program" in state && state.outputFiles.length > 0) { - lastSuccessfulOutputRef.current = state.outputFiles; - } - setCompilationState(state); - } + // previous successful output and its snapshotted file text so transient + // syntax errors don't leave multi-file output stale or blank. + const resolved = resolveDisplayedOutput(state, retainedOutputRef.current, snapshot); + retainedOutputRef.current = resolved.retained; + setIsOutputStale(resolved.isOutputStale); + setCompilationState(resolved.displayed); if ("program" in state) { const markers: editor.IMarkerData[] = state.program.diagnostics.map((diag) => ({ ...getMonacoRange(typespecCompiler, diag.target), diff --git a/packages/playground/src/react/output-view/file-viewer.tsx b/packages/playground/src/react/output-view/file-viewer.tsx index 0828f4be477..73c995c8ed7 100644 --- a/packages/playground/src/react/output-view/file-viewer.tsx +++ b/packages/playground/src/react/output-view/file-viewer.tsx @@ -1,6 +1,6 @@ import { FolderListRegular } from "@fluentui/react-icons"; import { Pane, SplitPane } from "@typespec/react-components"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import { FileBreadcrumb } from "../breadcrumb/index.js"; import { FileOutput } from "../file-output/file-output.js"; import { FileTreeExplorer } from "../file-tree/index.js"; @@ -13,6 +13,7 @@ import style from "./output-view.module.css"; const FileViewerComponent = ({ program, outputFiles, + outputFileContents, fileViewers, }: OutputViewerProps & { fileViewers: Record; @@ -28,20 +29,18 @@ const FileViewerComponent = ({ [outputFiles], ); - const lastContentsRef = useRef(new Map()); - const loadOutputFile = useCallback( async (path: string) => { try { const contents = await program.host.readFile("./tsp-output/" + path); - lastContentsRef.current.set(path, contents.text); setContent(contents.text); } catch { // Failed compilations keep the previous file list after tsp-output was emptied. - setContent(lastContentsRef.current.get(path) ?? ""); + // The snapshot is every file from that compilation, not only files opened since. + setContent(outputFileContents?.get(path) ?? ""); } }, - [program.host], + [outputFileContents, program.host], ); useEffect(() => { diff --git a/packages/playground/src/react/output-view/output-view.tsx b/packages/playground/src/react/output-view/output-view.tsx index 3fa565875cd..f731d9f238b 100644 --- a/packages/playground/src/react/output-view/output-view.tsx +++ b/packages/playground/src/react/output-view/output-view.tsx @@ -168,6 +168,7 @@ const OutputViewInternal: FunctionComponent<{ ; }; /** Distinguish an exception from a returned program by checking for `internalCompilerError`. */ export type CompilationState = CompileResult | CompilationCrashed; @@ -36,6 +44,11 @@ export interface OutputViewerProps { * through `program.host.readFile("./tsp-output/" + name)` rather than resolving the names as paths. */ readonly outputFiles: string[]; + /** + * Text of {@link outputFiles} from the compilation that produced those names. + * Use it when `program.host.readFile` can no longer read `tsp-output`. + */ + readonly outputFileContents?: ReadonlyMap; /** Playground-owned state shared with program viewers; the playground supplies `{}` when no state is stored. */ readonly viewerState?: Record; /** Request replacement of the viewer-state record; merge any entries that should be retained. */ diff --git a/packages/playground/test/file-viewer.test.tsx b/packages/playground/test/file-viewer.test.tsx new file mode 100644 index 00000000000..14cb4eb1ba0 --- /dev/null +++ b/packages/playground/test/file-viewer.test.tsx @@ -0,0 +1,102 @@ +import { FluentProvider, webLightTheme } from "@fluentui/react-components"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { createElement } from "react"; +import { expect, it, vi } from "vitest"; +import type { OutputViewerProps } from "../src/react/types.js"; + +vi.mock("../src/react/typespec-editor.js", () => ({ + OutputEditor: ({ value }: { value: string }) => + createElement("pre", { "data-testid": "output" }, value), +})); + +import { createFileViewer } from "../src/react/output-view/file-viewer.js"; + +const outputFiles = ["a.yaml", "b.yaml"]; +const viewer = createFileViewer([]); + +function createProgram(files: Record, failing: { current: boolean }) { + return { + host: { + readFile: vi.fn(async (path: string) => { + if (failing.current) { + throw new Error(`File ${path} not found.`); + } + const name = path.slice("./tsp-output/".length); + const text = files[name]; + if (text === undefined) { + throw new Error(`File ${path} not found.`); + } + return { text }; + }), + }, + } as OutputViewerProps["program"]; +} + +function renderOutput( + program: OutputViewerProps["program"], + outputFileContents: ReadonlyMap, +) { + return ( + + {viewer.render({ program, outputFiles, outputFileContents })} + + ); +} + +it("shows the latest snapshot for a file that was not open during the last successful compile", async () => { + const files = { "a.yaml": "a1", "b.yaml": "b1" }; + const failing = { current: false }; + const program = createProgram(files, failing); + const view = render(renderOutput(program, new Map(Object.entries(files)))); + + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("a1")); + fireEvent.click(screen.getByRole("tab", { name: "b.yaml" })); + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("b1")); + fireEvent.click(screen.getByRole("tab", { name: "a.yaml" })); + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("a1")); + + files["b.yaml"] = "b2"; + view.rerender(renderOutput(program, new Map(Object.entries(files)))); + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("a1")); + + failing.current = true; + view.rerender(renderOutput(program, new Map(Object.entries(files)))); + fireEvent.click(screen.getByRole("tab", { name: "b.yaml" })); + + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("b2")); +}); + +it("shows snapshot text for an emitted file that was never opened", async () => { + const files = { "a.yaml": "a1", "b.yaml": "never-opened" }; + const failing = { current: false }; + const program = createProgram(files, failing); + const view = render(renderOutput(program, new Map(Object.entries(files)))); + + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("a1")); + + failing.current = true; + view.rerender(renderOutput(program, new Map(Object.entries(files)))); + fireEvent.click(screen.getByRole("tab", { name: "b.yaml" })); + + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("never-opened")); +}); + +it("prefers text still on disk over the snapshot", async () => { + const files = { "a.yaml": "a1", "b.yaml": "from-disk" }; + const failing = { current: false }; + const program = createProgram(files, failing); + render( + renderOutput( + program, + new Map([ + ["a.yaml", "a1"], + ["b.yaml", "from-snapshot"], + ]), + ), + ); + + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("a1")); + fireEvent.click(screen.getByRole("tab", { name: "b.yaml" })); + + await waitFor(() => expect(screen.getByTestId("output")).toHaveTextContent("from-disk")); +}); diff --git a/packages/playground/test/output-snapshot.test.ts b/packages/playground/test/output-snapshot.test.ts new file mode 100644 index 00000000000..389fe9334ed --- /dev/null +++ b/packages/playground/test/output-snapshot.test.ts @@ -0,0 +1,145 @@ +import { expect, it } from "vitest"; +import { + boundOutputSnapshot, + emptyRetainedOutput, + readOutputSnapshot, + resolveDisplayedOutput, + type DisplayedOutput, +} from "../src/react/compilation/output-snapshot.js"; + +function compiled(outputFiles: string[], hasError: boolean) { + return { + program: { hasError: () => hasError }, + outputFiles, + } as Parameters[0]; +} + +function snapshotText(displayed: DisplayedOutput["displayed"], path: string) { + if (!("outputFileContents" in displayed)) { + return undefined; + } + return displayed.outputFileContents?.get(path); +} + +it("retains every file from the latest successful compilation after a failed compile", () => { + let retained = emptyRetainedOutput(); + + retained = resolveDisplayedOutput( + compiled(["a.yaml", "b.yaml"], false), + retained, + new Map([ + ["a.yaml", "a1"], + ["b.yaml", "b1"], + ]), + ).retained; + + retained = resolveDisplayedOutput( + compiled(["a.yaml", "b.yaml"], false), + retained, + new Map([ + ["a.yaml", "a1"], + ["b.yaml", "b2"], + ]), + ).retained; + + const failed = resolveDisplayedOutput(compiled([], true), retained, undefined); + + expect(failed.isOutputStale).toBe(true); + expect(failed.displayed).toMatchObject({ outputFiles: ["a.yaml", "b.yaml"] }); + expect(snapshotText(failed.displayed, "a.yaml")).toBe("a1"); + expect(snapshotText(failed.displayed, "b.yaml")).toBe("b2"); +}); + +it("keeps text for a file that was emitted but never required to be selected", async () => { + const disk = new Map([ + ["./tsp-output/a.yaml", "alpha"], + ["./tsp-output/b.yaml", "beta"], + ]); + const host = { + readFile: async (path: string) => { + const text = disk.get(path); + if (text === undefined) { + throw new Error(`File ${path} not found.`); + } + return { text }; + }, + }; + + const snapshot = await readOutputSnapshot(host, ["a.yaml", "b.yaml"]); + const retained = resolveDisplayedOutput( + compiled(["a.yaml", "b.yaml"], false), + emptyRetainedOutput(), + snapshot, + ).retained; + + disk.clear(); + const failed = resolveDisplayedOutput(compiled([], true), retained, undefined); + + expect(snapshotText(failed.displayed, "b.yaml")).toBe("beta"); +}); + +it("does not keep a partial snapshot when a later file cannot be read", async () => { + const reads: string[] = []; + const snapshot = await readOutputSnapshot( + { + readFile: async (path: string) => { + reads.push(path); + if (path.endsWith("b.yaml")) { + throw new Error("missing"); + } + return { text: "a" }; + }, + }, + ["a.yaml", "b.yaml"], + ); + + expect(snapshot).toBeUndefined(); + expect(reads).toEqual(["./tsp-output/a.yaml", "./tsp-output/b.yaml"]); +}); + +it("keeps the previous snapshot when a newer emission cannot be read", () => { + const retained = { + outputFiles: ["a.yaml"], + outputFileContents: new Map([["a.yaml", "previous"]]), + }; + + const resolved = resolveDisplayedOutput(compiled(["a.yaml"], false), retained, undefined); + + expect(resolved.isOutputStale).toBe(false); + expect(resolved.retained.outputFiles).toEqual(["a.yaml"]); + expect(resolved.retained.outputFileContents.get("a.yaml")).toBe("previous"); + expect(snapshotText(resolved.displayed, "a.yaml")).toBeUndefined(); +}); + +it("does not restore output when the failed compile is the first compile", () => { + const failed = resolveDisplayedOutput(compiled([], true), emptyRetainedOutput(), undefined); + + expect(failed.isOutputStale).toBe(false); + expect(failed.displayed).toMatchObject({ outputFiles: [] }); +}); + +it("always retains a single emitted file", () => { + const snapshot = boundOutputSnapshot( + ["only.yaml"], + new Map([["only.yaml", "x".repeat(100)]]), + 10, + ); + + expect(snapshot.get("only.yaml")).toHaveLength(100); +}); + +it("skips multi-file output that does not fit in the snapshot budget", () => { + const snapshot = boundOutputSnapshot( + ["a.yaml", "b.yaml", "c.yaml"], + new Map([ + ["a.yaml", "aaaa"], + ["b.yaml", "bbbbb"], + ["c.yaml", "c"], + ]), + 5, + ); + + expect([...snapshot.keys()]).toEqual(["a.yaml", "c.yaml"]); + expect(snapshot.get("a.yaml")).toBe("aaaa"); + expect(snapshot.get("c.yaml")).toBe("c"); +});