Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .chronus/changes/playground-multi-file-output-snapshot.md
Original file line number Diff line number Diff line change
@@ -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.
117 changes: 117 additions & 0 deletions packages/playground/src/react/compilation/output-snapshot.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>;
}

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<string, string>,
maxChars = MULTI_FILE_OUTPUT_SNAPSHOT_CHAR_BUDGET,
): Map<string, string> {
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<string, string>();
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<Map<string, string> | undefined> {
const contents = new Map<string, string>();
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<string, string> | 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;
Comment on lines +105 to +111

const displayed: CompileResult =
state.outputFiles.length > 0 && snapshot ? { ...state, outputFileContents: snapshot } : state;

return { displayed, retained: nextRetained, isOutputStale: false };
}
48 changes: 26 additions & 22 deletions packages/playground/src/react/hooks/use-compilation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -31,11 +37,11 @@ export function useCompilation({
const [compilationState, setCompilationState] = useState<CompilationState | undefined>(undefined);
const [isCompiling, setIsCompiling] = useState(false);
const [isOutputStale, setIsOutputStale] = useState(false);
const lastSuccessfulOutputRef = useRef<string[]>([]);
const retainedOutputRef = useRef<RetainedOutput>(emptyRetainedOutput());

// Clear preserved output when switching emitters
useEffect(() => {
lastSuccessfulOutputRef.current = [];
retainedOutputRef.current = emptyRetainedOutput();
setIsOutputStale(false);
}, [selectedEmitter]);

Expand Down Expand Up @@ -69,33 +75,31 @@ 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<string, string> | undefined;
if ("program" in state && state.outputFiles.length > 0) {
try {
snapshot = await readOutputSnapshot(host, state.outputFiles);
} catch {
snapshot = undefined;
}
}

isCompilingRef.current = false;
setIsCompiling(false);

// Discard stale results from an older compilation
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),
Expand Down
11 changes: 5 additions & 6 deletions packages/playground/src/react/output-view/file-viewer.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -13,6 +13,7 @@ import style from "./output-view.module.css";
const FileViewerComponent = ({
program,
outputFiles,
outputFileContents,
fileViewers,
}: OutputViewerProps & {
fileViewers: Record<string, FileOutputViewer>;
Expand All @@ -28,20 +29,18 @@ const FileViewerComponent = ({
[outputFiles],
);

const lastContentsRef = useRef(new Map<string, string>());

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(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ const OutputViewInternal: FunctionComponent<{
<viewer.render
program={compilationResult.program}
outputFiles={compilationResult.outputFiles}
outputFileContents={compilationResult.outputFileContents}
viewerState={viewerState}
onViewerStateChange={onViewerStateChange}
onRevealSource={onRevealSource}
Expand Down
13 changes: 13 additions & 0 deletions packages/playground/src/react/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ export type CompileResult = {
* 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.
* Present after a successful emission, and on a later failed compilation that
* kept the previous file list, so every retained file can be shown after
* `tsp-output` is cleared. Multi-file snapshots are size-limited; omitted
* names were dropped to stay within that budget.
*/
readonly outputFileContents?: ReadonlyMap<string, string>;
};
/** Distinguish an exception from a returned program by checking for `internalCompilerError`. */
export type CompilationState = CompileResult | CompilationCrashed;
Expand All @@ -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<string, string>;
/** Playground-owned state shared with program viewers; the playground supplies `{}` when no state is stored. */
readonly viewerState?: Record<string, any>;
/** Request replacement of the viewer-state record; merge any entries that should be retained. */
Expand Down
102 changes: 102 additions & 0 deletions packages/playground/test/file-viewer.test.tsx
Original file line number Diff line number Diff line change
@@ -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<string, string>, 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<string, string>,
) {
return (
<FluentProvider theme={webLightTheme}>
{viewer.render({ program, outputFiles, outputFileContents })}
</FluentProvider>
);
}

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"));
});
Loading