Skip to content
Closed
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
12 changes: 12 additions & 0 deletions apps/web/src/components/diffs/parsePatch.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { getRenderablePatch } from "~/lib/diffRendering";

self.addEventListener(
"message",
(event: MessageEvent<{ id: number; patch: string; scope: string }>) => {
const { id, patch, scope } = event.data;
self.postMessage(
{ id, patch: getRenderablePatch(patch, scope, { compactPartialHunkOffsets: true }) },
{ transfer: [] },
);
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { expect, it, vi } from "vite-plus/test";

import { getRenderablePatch } from "~/lib/diffRendering";
import { parsePatchOffMainThread } from "./parsePatchOffMainThread";

const PATCH = [
"diff --git a/a.ts b/a.ts",
"--- a/a.ts",
"+++ b/a.ts",
"@@ -1,2 +1,2 @@",
" keep",
"-old",
"+new",
"diff --git a/b.ts b/b.ts",
"new file mode 100644",
"--- /dev/null",
"+++ b/b.ts",
"@@ -0,0 +1 @@",
"+added",
"",
].join("\n");

// These run first: the module keeps a working worker, and browser mode cannot reset modules.
it.each([
{
name: "the worker cannot be created",
FailingWorker: function () {
throw new Error("blocked");
},
},
{
name: "posting to the worker throws",
FailingWorker: class extends EventTarget {
postMessage() {
throw new Error("could not post");
}
terminate() {}
},
},
{
name: "the worker reports an error",
FailingWorker: class extends EventTarget {
postMessage() {
queueMicrotask(() => this.dispatchEvent(new Event("error")));
}
terminate() {}
},
},
])("parses on the main thread when $name", async ({ FailingWorker }) => {
vi.stubGlobal("Worker", FailingWorker);
try {
await expect(
Promise.all([
parsePatchOffMainThread(PATCH, "fallback"),
parsePatchOffMainThread(PATCH, "fallback"),
]),
).resolves.toEqual(
Array(2).fill(getRenderablePatch(PATCH, "fallback", { compactPartialHunkOffsets: true })),
);
} finally {
vi.unstubAllGlobals();
}
});

it("parses in the worker exactly as on the main thread", async () => {
const NativeWorker = globalThis.Worker;
let workerReplies = 0;
vi.stubGlobal(
"Worker",
class extends NativeWorker {
constructor(...args: ConstructorParameters<typeof Worker>) {
super(...args);
this.addEventListener("message", () => workerReplies++);
}
},
);
try {
const [first, second] = await Promise.all([
parsePatchOffMainThread(PATCH, "test"),
parsePatchOffMainThread("", "test"),
]);

// The fallback returns the same values, so equal output alone would not prove the worker ran.
expect(workerReplies).toBe(2);
expect(first).toEqual(getRenderablePatch(PATCH, "test", { compactPartialHunkOffsets: true }));
expect(second).toBeNull();
} finally {
vi.unstubAllGlobals();
}
});
47 changes: 47 additions & 0 deletions apps/web/src/components/diffs/parsePatchOffMainThread.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { getRenderablePatch, type RenderablePatch } from "~/lib/diffRendering";

let worker: Worker | null = null;
let nextId = 0;
const pending = new Map<
number,
{ patch: string; scope: string; resolve: (patch: RenderablePatch | null) => void }
>();

function parsePendingOnMainThread() {
const requests = [...pending.values()];
pending.clear();
worker?.terminate();
worker = null;
for (const { patch, scope, resolve } of requests) {
resolve(getRenderablePatch(patch, scope, { compactPartialHunkOffsets: true }));
}
}

function parserWorker() {
if (worker) return worker;
const created = new Worker(new URL("./parsePatch.worker.ts", import.meta.url), {
type: "module",
});
created.addEventListener(
"message",
(event: MessageEvent<{ id: number; patch: RenderablePatch | null }>) => {
pending.get(event.data.id)?.resolve(event.data.patch);
pending.delete(event.data.id);
},
);
created.addEventListener("error", parsePendingOnMainThread);
worker = created;
return created;
}

export function parsePatchOffMainThread(patch: string, scope: string) {
return new Promise<RenderablePatch | null>((resolve) => {
const id = nextId++;
pending.set(id, { patch, scope, resolve });
try {
parserWorker().postMessage({ id, patch, scope }, { transfer: [] });
} catch {
parsePendingOnMainThread();
}
});
}
181 changes: 156 additions & 25 deletions apps/web/src/components/diffs/useReviewFilePatches.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,169 @@
import { RegistryContext } from "@effect/atom-react";
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
import { EnvironmentId } from "@t3tools/contracts";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { EnvironmentId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, AtomRegistry } from "effect/reactivity";
import { expect, it, vi } from "vite-plus/test";
import { userEvent } from "vite-plus/test/browser";

import { act, render } from "../../../test/render";
import { resolveFileDiffPath } from "~/lib/diffRendering";

const mocks = vi.hoisted(() => ({ requests: [] as string[], parses: [] as string[] }));

const patchQuery = await vi.hoisted(async () => {
const { AsyncResult, Atom } = await import("effect/reactivity");
return Atom.family((path: string) =>
Atom.writable(
(get) => {
mocks.requests.push(path);
return AsyncResult.waitingFrom(
get.self<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(),
);
},
(get, value: AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>) => get.setSelf(value),
).pipe(Atom.setIdleTTL(5 * 60_000)),
);
});

type PatchAtom = Atom.Writable<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>;
const state = vi.hoisted(() => ({ patches: new Map<string, PatchAtom>() }));
vi.mock("~/state/review", () => ({
reviewEnvironment: {
diffFilePatch: (target: {
input: { cacheKey: string; request: { file: { path: string } } };
}) => {
const key = JSON.stringify([target.input.cacheKey, target.input.request.file.path]);
let atom = state.patches.get(key);
if (!atom) {
atom = Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource, Error>>(
AsyncResult.initial(),
);
state.patches.set(key, atom);
}
return atom;
},
diffFilePatch: (target: { input: { request: { file: { path: string } } } }) =>
patchQuery(target.input.request.file.path),
},
}));

vi.mock("./parsePatchOffMainThread", async () => {
const { getRenderablePatch } = await import("~/lib/diffRendering");
return {
parsePatchOffMainThread: async (patch: string, scope: string) => {
mocks.parses.push(patch);
return getRenderablePatch(patch, scope, { compactPartialHunkOffsets: true });
},
};
});

import { useReviewFilePatches } from "./useReviewFilePatches";

function previewSource(paths: string[]): ReviewDiffPreviewSource {
return {
id: "working-tree",
kind: "working-tree",
title: "Uncommitted",
baseRef: null,
headRef: null,
diff: "preview",
diffHash: "hash",
truncated: true,
files: paths.map((path) => ({ path, previousPath: null, additions: 1, deletions: 0 })),
};
}

type HookResult = ReturnType<typeof useReviewFilePatches>;

function Harness(props: {
source: ReviewDiffPreviewSource;
onResult: (result: HookResult) => void;
}) {
const result = useReviewFilePatches({
environmentId: EnvironmentId.make("test"),
cwd: "/repo",
source: props.source,
baseRef: null,
ignoreWhitespace: false,
theme: "dark",
previewInput: { cwd: "/repo" },
preview: null,
});
props.onResult(result);
return (
<ul>
{result.renderableFiles.map((file) => (
<li key={resolveFileDiffPath(file)}>
{resolveFileDiffPath(file)} {file.additionLines.join(",") || "pending"}
</li>
))}
</ul>
);
}

function setup(paths = ["a.ts"]) {
mocks.requests = [];
mocks.parses = [];
const registry = AtomRegistry.make();
const source = previewSource(paths);
const results: HookResult[] = [];
return {
ui: () => (
<RegistryContext.Provider value={registry}>
<Harness source={source} onResult={(result) => results.push(result)} />
</RegistryContext.Provider>
),
latest: () => results.at(-1)!,
refresh: (path: string) => registry.refresh(patchQuery(path)),
requestsFor: (path: string) => mocks.requests.filter((request) => request === path).length,
complete(path: string, contents: string) {
registry.set(
patchQuery(path),
AsyncResult.success({
...source,
diff: `diff --git a/${path} b/${path}
new file mode 100644
--- /dev/null
+++ b/${path}
@@ -0,0 +1 @@
+${contents}
`,
truncated: false,
}),
);
},
};
}

it("reopening keeps the parse while source queries revalidate", async () => {
const h = setup();
{
await using screen = await render(h.ui());
h.complete("a.ts", "first");
await expect.element(screen.getByText("a.ts first")).toBeInTheDocument();
}
const parsed = h.latest().renderableFiles[0];
await using screen = await render(h.ui());
expect(h.latest().renderableFiles[0]).toBe(parsed);
expect(mocks.requests).toEqual(["a.ts"]);

h.refresh("a.ts");
expect(mocks.requests).toEqual(["a.ts", "a.ts"]);
await vi.waitFor(() => expect(h.latest().isPending).toBe(true));
expect(h.latest().renderableFiles[0]).toBe(parsed);
h.complete("a.ts", "first");
await vi.waitFor(() => expect(h.latest().isPending).toBe(false));
expect(h.latest().renderableFiles[0]).toBe(parsed);
expect(mocks.parses).toHaveLength(1);

h.refresh("a.ts");
h.complete("a.ts", "changed");
await expect.element(screen.getByText("a.ts changed")).toBeInTheDocument();
expect(mocks.parses).toHaveLength(2);
});

it("keeps a later file's parse while its source query refreshes", async () => {
const h = setup(["a.ts", "b.ts", "c.ts", "d.ts", "e.ts"]);
await using screen = await render(h.ui());
h.latest().requestFile("e.ts");
await vi.waitFor(() => expect(h.requestsFor("e.ts")).toBe(1));
h.complete("e.ts", "first");
await expect.element(screen.getByText("e.ts first")).toBeInTheDocument();
const parsed = h.latest().renderableFiles[4];

h.refresh("e.ts");
await vi.waitFor(() => expect(h.requestsFor("e.ts")).toBe(2));
expect(h.latest().renderableFiles[4]).toBe(parsed);
h.complete("e.ts", "changed");
await expect.element(screen.getByText("e.ts changed")).toBeInTheDocument();
expect(h.latest().renderableFiles[4]).not.toBe(parsed);
});

function source(paths: string[], hash: string): ReviewDiffPreviewSource {
return {
id: "working-tree",
Expand Down Expand Up @@ -72,7 +207,6 @@ function Probe({ source }: { source: ReviewDiffPreviewSource }) {
}

it("retains automatic and explicitly opened files through metadata insertion, refresh failure and retry", async () => {
state.patches.clear();
const registry = AtomRegistry.make();
using _registry = { [Symbol.dispose]: () => registry.dispose() };
const tracked = source(["b.txt", "c.txt", "d.txt", "e.txt", "f.txt"], "tracked");
Expand All @@ -83,18 +217,17 @@ it("retains automatic and explicitly opened files through metadata insertion, re
);
await using screen = await render(view(tracked));
await userEvent.click(screen.getByRole("button", { name: "Open f" }));
const atom = [...state.patches].find(([key]) => JSON.parse(key)[1] === "f.txt")![1];
const atom = patchQuery("f.txt");
const loaded = AsyncResult.success({
...tracked,
diff: "diff --git a/f.txt b/f.txt\n--- a/f.txt\n+++ b/f.txt\n@@ -1 +1 @@\n-old\n+new\n",
files: tracked.files!.filter((f) => f.path === "f.txt"),
});
await act(() => registry.set(atom, loaded));
await expect.element(screen.getByText("f.txt:loaded")).toBeVisible();
const automatic = [...state.patches].find(([key]) => JSON.parse(key)[1] === "e.txt")![1];
await act(() =>
registry.set(
automatic,
patchQuery("e.txt"),
AsyncResult.success({
...loaded.value,
diff: loaded.value.diff.replaceAll("f.txt", "e.txt"),
Expand All @@ -120,7 +253,6 @@ it("retains automatic and explicitly opened files through metadata insertion, re
});

it("preserves deletion and addition patches for a file replaced by a symlink", async () => {
state.patches.clear();
const registry = AtomRegistry.make();
using _registry = { [Symbol.dispose]: () => registry.dispose() };
const metadata = source(["entry"], "type-change");
Expand All @@ -129,10 +261,9 @@ it("preserves deletion and addition patches for a file replaced by a symlink", a
<Probe source={metadata} />
</RegistryContext.Provider>,
);
const atom = [...state.patches.values()][0]!;
await act(() =>
registry.set(
atom,
patchQuery("entry"),
AsyncResult.success({
...metadata,
diff: "diff --git a/entry b/entry\ndeleted file mode 100644\n--- a/entry\n+++ /dev/null\n@@ -1 +0,0 @@\n-before\ndiff --git a/entry b/entry\nnew file mode 120000\n--- /dev/null\n+++ b/entry\n@@ -0,0 +1 @@\n+target\n\\ No newline at end of file\n",
Expand Down
Loading
Loading