Skip to content
Merged
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
22 changes: 22 additions & 0 deletions client/e2e/dataflow.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,28 @@ const box = (page: Page, label: string) => page.locator("[data-box]").filter({ h
const boxLabelled = (page: Page, label: string) => page.locator(`[data-box][data-label^="${label}"]`).first();

test.describe("Data flow on solid-route", () => {
test("a failed new anchor request does not redisplay the previous graph", async ({ page }) => {
const originalAnchor = "src/components/ViewerCard.tsx@ViewerCard:3";
await page.goto(url({ view: "graph", anchor: originalAnchor, dir: "backward" }));
await expect(status(page)).toContainText("upstream", { timeout: 90_000 });
await page.locator('[data-box][data-label="viewer"]').first().click();
const trace = page.getByLabel("Data flow inspector").locator("[data-trace-from]");
await expect(trace).toBeVisible();
await page.route("**/api/dataflow/anchor-graph", (route) => route.fulfill({
status: 404, contentType: "application/json", body: JSON.stringify({ detail: "No program element test-missing-anchor" }),
}));
// Re-anchoring is navigation; the direction toggle only replaces the current entry.
await trace.click();
await expect(page).toHaveURL(/anchor=[^&]*%40el%3A/);
await expect(page.getByText(/Anchor graph failed.*test-missing-anchor/)).toBeVisible();
await expect(page.locator("[data-box]")).toHaveCount(0);
await expect(page.getByLabel("Data flow inspector")).toHaveCount(0);
await page.unroute("**/api/dataflow/anchor-graph");
await page.goBack();
await expect(page).toHaveURL((url) => url.searchParams.get("anchor") === originalAnchor && url.searchParams.get("dir") === "backward");
await expect(page.locator("[data-box]").first()).toBeVisible({ timeout: 90_000 });
});

test("switches trace direction without stale canvas work", async ({ page }) => {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
Expand Down
57 changes: 57 additions & 0 deletions client/src/viz/deps/flow/FlowInspector.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// @vitest-environment jsdom
import { createComponent } from "solid-js";
import { render } from "solid-js/web";
import { describe, expect, it, vi } from "vitest";
import fixture from "../../../../../engine/test/srcly/__fixtures__/solid-route.anchor-graph.json";
import type { AnchorGraphResult } from "../../../dataflow/contract.generated";
import { anchorGraphToViewModel } from "./anchorAdapter";
import { canAnchorBox } from "./inspectorModel";
import { FlowInspector } from "./FlowInspector";

vi.mock("lucide-solid", () => ({ ExternalLink: () => null, X: () => null }));
const graph = fixture as unknown as AnchorGraphResult;

describe("anchor continuation actions", () => {
it("keeps frontier source recovery but never offers its synthetic id as an anchor", () => {
const frontier = { ...graph.nodes[1], id: "frontier:end:program-element:example", kind: "frontier" as const, reason: "unbound-read" };
const withFrontier = { ...graph, nodes: [...graph.nodes, frontier] };
expect(frontier).toBeDefined();
const container = document.createElement("div");
document.body.append(container);
const open = vi.fn();
const dispose = render(() => createComponent(FlowInspector, { graph: null, model: anchorGraphToViewModel(withFrontier), rootPath: "/root", selected: frontier.id, reach: null, open: [], onOpen: open, onSelect: () => {}, onPickOrigin: () => {}, onToggleFrame: () => {}, onClose: () => {}, onTraceFrom: vi.fn(), onAddAnchor: vi.fn() }), container);
try {
expect(container.querySelector("[data-trace-from]")).toBeNull();
expect(container.textContent).not.toContain("Add to the trace");
expect(container.textContent).toContain("Open its source");
(container.querySelector('[title="Open in the code viewer"]') as HTMLButtonElement).click();
expect(open).toHaveBeenCalledWith(frontier.absPath, frontier.line);
} finally { dispose(); container.remove(); }
});
});

it("only permits actual anchor-graph nodes as continuation targets", () => {
const node = graph.nodes.find((n) => n.kind !== "scope" && n.kind !== "anchor")!;
expect(canAnchorBox(node)).toBe(true);
expect(canAnchorBox({ ...node, id: "frontier:end:" + node.id, kind: "frontier" })).toBe(false);
expect(canAnchorBox(undefined)).toBe(false);
});

it("keeps both continuation actions for a real program element", () => {
const node = graph.nodes.find((n) => n.kind !== "scope" && n.kind !== "anchor")!;
const container = document.createElement("div");
document.body.append(container);
const trace = vi.fn(), add = vi.fn();
const dispose = render(() => createComponent(FlowInspector, {
graph: null, model: anchorGraphToViewModel(graph), rootPath: "/root", selected: node.id, reach: null, open: [],
onOpen: () => {}, onSelect: () => {}, onPickOrigin: () => {}, onToggleFrame: () => {}, onClose: () => {},
onTraceFrom: trace, onAddAnchor: add,
}), container);
try {
(container.querySelector("[data-trace-from]") as HTMLButtonElement).click();
const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add to the trace"))!;
addButton.click();
expect(trace).toHaveBeenCalledWith(node.id);
expect(add).toHaveBeenCalledWith(node.id);
} finally { dispose(); container.remove(); }
});
10 changes: 8 additions & 2 deletions client/src/viz/deps/flow/FlowInspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Button } from "../../../components/ui/Button";
import { IconButton } from "../../../components/ui/IconButton";
import type { FlowBox, FlowViewModel } from "./adapter";
import { FlowMarkGlyph } from "./FlowMark";
import { anchorOverview, nodeDetails, routeOverview, STATUS_WORD, type AnchorOverview, type GapGroup, type GapPlace, type NeighborRow } from "./inspectorModel";
import { canAnchorBox, anchorOverview, nodeDetails, routeOverview, STATUS_WORD, type AnchorOverview, type GapGroup, type GapPlace, type NeighborRow } from "./inspectorModel";
import { FLOW_MARKS, REPETITION_BADGE, STOP_REASONS, type FlowMark } from "./marks";
import type { Reach } from "./reach";
import { createEffectsQuery, EffectsPanel } from "../../../dataflow/EffectsPanel";
Expand Down Expand Up @@ -184,7 +184,7 @@ export function FlowInspector(props: {
{/* A stop srcly words is already said by its detail line; any other reason shows as the engine names it. */}
<Show when={d().node.reason && !STOP_REASONS[d().node.reason!] ? d().node.reason : null}>{(r) => <div class="pl-5 text-[11px] text-[var(--plc-warning)]">{r()}</div>}</Show>
<Where file={d().node.file} line={d().node.line} onOpen={() => props.onOpen(d().node.absPath, d().node.line)} />
<Show when={(props.onTraceFrom || props.onAddAnchor) && d().node.kind !== "anchor"}>
<Show when={(props.onTraceFrom || props.onAddAnchor) && d().node.kind !== "anchor" && canAnchorBox(d().node)}>
<div class="flex gap-1.5 pl-5 pt-1">
{/* A folded function opens instead: its own anchor shows only its parameters and returns. */}
<Show when={props.onTraceFrom && d().node.kind !== "scope"}>
Expand All @@ -200,6 +200,12 @@ export function FlowInspector(props: {
</div>
</Show>

<Show when={(props.onTraceFrom || props.onAddAnchor) && d().node.kind === "frontier"}>
<div data-trace-unavailable="" class="pl-5 pt-1 text-[11px] text-[var(--plc-on-muted)]">
This stop is not a traceable program element. Open its source to select an expression to trace.
</div>
</Show>

<Show when={props.reach}>
{(r) => section("Reach", (
<div class="space-y-px">
Expand Down
10 changes: 5 additions & 5 deletions client/src/viz/deps/flow/FlowView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { FlowLegend } from "./FlowLegend";
import { DepthControl, DirectionSwitch, FlowModeSwitch, ModelSwitch, ReachModeSwitch, REACH_OF_DIRECTION, RecentFlowMenu, RouteLensSwitch } from "./FlowTools";
import { createFetch } from "./fetchSignal";
import { FlowProgress } from "./FlowProgress";
import { stopsOf } from "./inspectorModel";
import { canAnchorBox, stopsOf } from "./inspectorModel";
import { PythonApps } from "./PythonApps";
import { reachFrom, REACH_MODES, type ReachMode } from "./reach";
import { RoutePicker } from "./RoutePicker";
Expand Down Expand Up @@ -142,7 +142,7 @@ export default function FlowView(props: {
const spec = parseAnchor(raw)!;
if ("exports" in spec) throw new Error("An exports anchor has no single graph");
return watchProgress(path, fetchAnchorGraph({ path, direction: direction as Direction, ...anchorFields(spec), ...(gen ? { expectedGeneration: Number(gen) } : {}) }));
});
}, { keepPrevious: false });
const anchorGraph = anchorFetch.value;
// The other anchors (T20): each its own query, one at a time, kept by generation so a Return does not refetch.
type ExtraAnchor = { raw: string; graph: AnchorGraphResult | null; outcome: string; reason: string | null };
Expand Down Expand Up @@ -190,7 +190,7 @@ export default function FlowView(props: {
const addAnchorFrom = (id: string) => {
const box = model()?.byId.get(id);
const specs = anchorSpecs();
if (!box || !specs.length || specs.length >= MAX_ANCHORS || exportsSpec()) return;
if (!box || !canAnchorBox(box) || !specs.length || specs.length >= MAX_ANCHORS || exportsSpec()) return;
// By element id: the engine anchors at the very element the box stands for, so the traces share ids by construction.
const next: Anchor = { file: box.file, element: id };
if (specs.some((a) => encodeAnchor(a) === encodeAnchor(next))) return;
Expand All @@ -200,7 +200,7 @@ export default function FlowView(props: {
/** Re-anchor on a drawn box by its element id, keeping the direction. */
const traceFrom = (id: string) => {
const box = model()?.byId.get(id);
if (!box || !("side" in box) || box.kind === "scope") return;
if (!box || !canAnchorBox(box) || box.kind === "scope") return;
setSelected(null);
go({ anchor: encodeAnchor({ file: box.file, element: id }), open: undefined });
};
Expand Down Expand Up @@ -360,9 +360,9 @@ export default function FlowView(props: {

let token = 0;
createEffect(() => {
const mine = ++token;
const m = model();
if (!m) return setLayout(null);
const mine = ++token;
const rect = host?.getBoundingClientRect();
const viewport = rect && rect.height > 0 ? { width: rect.width, height: rect.height } : undefined;
const aspectRatio = viewport ? viewport.width / viewport.height : 1.6;
Expand Down
30 changes: 30 additions & 0 deletions client/src/viz/deps/flow/fetchSignal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,33 @@ describe("createFetch", () => {
dispose();
});
});

it("clears an anchor's previous result while loading and after failure, ignoring late replies", async () => {
const pending = new Map<string, { resolve: (value: string) => void; reject: (error: Error) => void }>();
const { fetch, setKey, dispose } = createRoot((dispose) => {
const [key, setKey] = createSignal("first");
return { fetch: createFetch(key, (k) => new Promise<string>((resolve, reject) => pending.set(k, { resolve, reject })), { keepPrevious: false }), setKey, dispose };
});
try {
pending.get("first")!.resolve("first graph");
await Promise.resolve();
expect(fetch.value()).toBe("first graph");
setKey("second");
expect(fetch.loading()).toBe(true);
expect(fetch.value()).toBeUndefined();
setKey("third");
pending.get("third")!.reject(new Error("No program element"));
await Promise.resolve();
expect(fetch.error()?.message).toBe("No program element");
expect(fetch.value()).toBeUndefined();
pending.get("second")!.resolve("late second graph");
await Promise.resolve();
expect(fetch.value()).toBeUndefined();
expect(fetch.error()?.message).toBe("No program element");
fetch.retry();
expect(fetch.error()).toBeNull();
pending.get("third")!.resolve("retried graph");
await Promise.resolve();
expect(fetch.value()).toBe("retried graph");
} finally { dispose(); }
});
4 changes: 3 additions & 1 deletion client/src/viz/deps/flow/fetchSignal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createEffect, createSignal, on } from "solid-js";
* reading it never suspends: the graph view sits under the treemap's
* Suspense, which would swap the whole view for its fallback.
*/
export function createFetch<S, T>(source: () => S | null | undefined, fetcher: (key: S) => Promise<T>) {
export function createFetch<S, T>(source: () => S | null | undefined, fetcher: (key: S) => Promise<T>, options: { keepPrevious?: boolean } = {}) {
const [value, setValue] = createSignal<T | undefined>();
const [loading, setLoading] = createSignal(false);
const [error, setError] = createSignal<Error | null>(null);
Expand All @@ -16,6 +16,8 @@ export function createFetch<S, T>(source: () => S | null | undefined, fetcher: (
on([source, attempt], ([key]) => {
const mine = ++token;
setError(null);
// Anchor requests must not present a previous graph as the new request.
if (options.keepPrevious === false) setValue(undefined);
if (key === null || key === undefined) {
setValue(undefined);
setLoading(false);
Expand Down
5 changes: 5 additions & 0 deletions client/src/viz/deps/flow/inspectorModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import { isAssumedProof } from "../../../dataflow/outcome";
import type { FlowBox, FlowViewModel } from "./adapter";
import { humanizeDetail, MARK_OF_ANCHOR_KIND, MARK_OF_KIND, STOP_REASONS, stopWord, type FlowMark } from "./marks";

/** Frontiers describe where a walk stopped; their display ids are not program elements. */
export function canAnchorBox(box: FlowBox | undefined): boolean {
return !!box && "side" in box && box.kind !== "frontier";
}

/** Route mode words for the render backbone; anchor mode names the engine's relation (`argument`, `return value`, …). */
export type EdgeKindWord = "renders" | "rendered by" | "handoff" | "field" | "structural" | (string & {});

Expand Down
Loading