A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: keep New document choices stable during AI lookup (#3834)
Amruth Pillai28595bb304f6
diff --git a/apps/web/src/features/documents/new-document-dialog-provider.test.tsx b/apps/web/src/features/documents/new-document-dialog-provider.test.tsxindex 0a64649dd..450b9a346 100644--- a/apps/web/src/features/documents/new-document-dialog-provider.test.tsx+++ b/apps/web/src/features/documents/new-document-dialog-provider.test.tsx@@ -10,6 +10,7 @@ import { Dialog } from "@reactive-resume/ui/components/dialog";const api = vi.hoisted(() => ({providers: vi.fn(),importResume: vi.fn(),+ createResume: vi.fn(),parsePdf: vi.fn(),parseDocx: vi.fn(),readPdfResume: vi.fn(),@@ -34,7 +35,7 @@ vi.mock("@/libs/orpc/client", () => ({},documents: { key: () => ["documents"], list: { queryKey: () => ["documents", "list"] } },resume: {- create: { mutationOptions: () => ({ mutationFn: vi.fn() }) },+ create: { mutationOptions: () => ({ mutationFn: api.createResume }) },list: { queryOptions: () => ({ queryKey: ["resume", "list"], queryFn: async () => [] }) },},coverLetters: { create: { mutationOptions: () => ({ mutationFn: api.createLetter }) } },@@ -145,3 +146,27 @@ it("numbers a new letter while untitled ones exist, so the library can tell themawait vi.waitFor(() => expect(api.createLetter).toHaveBeenCalledOnce());expect(api.createLetter.mock.calls[0]?.[0]).toMatchObject({ name: "Untitled letter 3" });});++it("keeps lookup failure recovery available on New and retries without creating a document", async () => {+ mount();+ await screen.findByRole("alert");+ expect(screen.getByText("Couldn't load AI connections. Your saved connections haven't changed.")).toBeVisible();+ let finishLookup = () => {};+ api.providers.mockReturnValue(+ new Promise((resolve) => {+ finishLookup = () => resolve([]);+ }),+ );+ const lookupCalls = api.providers.mock.calls.length;+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));+ await screen.findByRole("status", { name: "Loading AI connections…" });+ expect(api.providers.mock.calls.length).toBeGreaterThan(lookupCalls);+ await act(async () => finishLookup());+ await vi.waitFor(() => expect(screen.queryByRole("status")).toBeNull());+ expect(screen.queryByRole("alert")).toBeNull();+ expect(screen.getByRole("button", { name: /Import a resume/ })).toBeEnabled();+ expect(screen.getByRole("button", { name: /Start blank/ })).toBeEnabled();+ expect(api.importResume).not.toHaveBeenCalled();+ expect(api.createLetter).not.toHaveBeenCalled();+ expect(api.createResume).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/documents/new-document-dialog.tsx b/apps/web/src/features/documents/new-document-dialog.tsxindex fbc3573c5..f72870626 100644--- a/apps/web/src/features/documents/new-document-dialog.tsx+++ b/apps/web/src/features/documents/new-document-dialog.tsx@@ -244,6 +244,7 @@ export function NewDocumentDialog({ data }: { data?: NewDocumentDialogData | undconst markNew = useNewDocumentsStore((state) => state.markNew);const [step, setStep] = useState<Step>({ name: data?.step ?? "choose" } as Step);const inputRef = useRef<HTMLInputElement>(null);+ const importDescriptionId = useId();// A copy made for a job opens with the assistant ready to tailor it.const openResume = (resumeId: string, { withAssistant = false, importedFrom }: OpenResumeOptions = {}) => {@@ -287,7 +288,7 @@ export function NewDocumentDialog({ data }: { data?: NewDocumentDialogData | undreturn (<DialogContent closeLabel={t`Close`} className="sm:max-w-[640px]">- <AiProviderLoadState state={providerState} />+ {step.name !== "choose" && <AiProviderLoadState state={providerState} />}<inputref={inputRef}type="file"@@ -417,6 +418,8 @@ export function NewDocumentDialog({ data }: { data?: NewDocumentDialogData | und<buttontype="button"onClick={chooseFile}+ aria-label={t`Import a resume`}+ aria-describedby={importDescriptionId}onDragOver={(event) => event.preventDefault()}onDrop={(event) => {event.preventDefault();@@ -426,13 +429,17 @@ export function NewDocumentDialog({ data }: { data?: NewDocumentDialogData | undclassName="flex items-start gap-4 rounded-xl border-[1.5px] border-dashed border-line-2 p-5 text-start transition-[background-color,border-color,scale] duration-quick ease-enter hover:border-accent hover:bg-accent-soft active:scale-[0.98]"><span className="grid size-11 shrink-0 place-items-center rounded-lg bg-sunken text-ink-2">- <Icon name="file-arrow-up" size={24} />+ {providerState.isLoading ? (+ <Spinner className="size-6" aria-label={t`Loading AI connections…`} />+ ) : (+ <Icon name="file-arrow-up" size={24} />+ )}</span><span className="grid gap-1"><span className="text-[15px] font-semibold"><Trans>Import a resume</Trans></span>- <span className="text-[13px] leading-[19px] text-ink-2">+ <span id={importDescriptionId} className="text-[13px] leading-[19px] text-ink-2"><Trans>Drop a file here or browse. PDF, Word (needs AI), Reactive Resume or JSON Resume. Sections come inready to edit. For a PDF or Word file, anything that couldn't be placed is listed before you create@@ -485,6 +492,7 @@ export function NewDocumentDialog({ data }: { data?: NewDocumentDialogData | und<Trans>Try with a sample resume</Trans></button></div>+ <AiProviderLoadState state={providerState} reserveErrorSpace /></div>)}</DialogContent>diff --git a/apps/web/src/features/settings/integrations/ai-provider-load-state.tsx b/apps/web/src/features/settings/integrations/ai-provider-load-state.tsxindex fe447d2b5..5f897cd71 100644--- a/apps/web/src/features/settings/integrations/ai-provider-load-state.tsx+++ b/apps/web/src/features/settings/integrations/ai-provider-load-state.tsx@@ -1,23 +1,33 @@import { Trans } from "@lingui/react/macro";import { Button } from "@reactive-resume/ui/components/button";import { Spinner } from "@reactive-resume/ui/components/spinner";+import { cn } from "@reactive-resume/utils/style";type AiProviderLoadStateProps = {state: { isLoading: boolean; error: unknown; retry: () => void };+ /** Keep localized recovery content measured while hidden so nearby actions cannot move. */+ reserveErrorSpace?: boolean;};/** Loading and lookup failures must not be presented as missing saved connections. */-export function AiProviderLoadState({ state }: AiProviderLoadStateProps) {- if (state.isLoading)+export function AiProviderLoadState({ state, reserveErrorSpace = false }: AiProviderLoadStateProps) {+ if (state.isLoading && !reserveErrorSpace)return (<p role="status" className="flex items-center gap-2 p-3 text-sm text-ink-2"><Spinner decorative className="size-4" /><Trans>Loading AI connections…</Trans></p>);- if (!state.error) return null;+ if (!state.error && !reserveErrorSpace) return null;return (- <div role="alert" className="grid justify-items-start gap-2 rounded-lg border border-line p-3 text-sm text-ink-2">+ <div+ role="alert"+ aria-hidden={!state.error}+ className={cn(+ "grid justify-items-start gap-2 rounded-lg border border-line p-3 text-sm text-ink-2",+ !state.error && "invisible",+ )}+ ><p><Trans>Couldn't load AI connections. Your saved connections haven't changed.</Trans></p>diff --git a/docs/guides/importing-resumes.mdx b/docs/guides/importing-resumes.mdxindex 647a78417..171e24aa7 100644--- a/docs/guides/importing-resumes.mdx+++ b/docs/guides/importing-resumes.mdx@@ -29,7 +29,7 @@ A cover letter exported from Reactive Resume as JSON imports as a letter, not a<Steps><Step title="Open the import">- On Documents, select **New** in the sidebar (or press <kbd>N</kbd>), then select **Import a resume** and pick your file. On your first visit, the empty Documents page has a **Choose a file** button that opens your device's file picker directly; the import starts as soon as you pick a file.+ On Documents, select **New** in the sidebar (or press <kbd>N</kbd>), then select **Import a resume** and pick your file. On web, while AI connections load, a spinner occupies the import tile icon; the choices stay in place and remain available. A connection lookup failure appears below the choices with **Try again**; its space is kept so the choices stay steady through retry too. On your first visit, the empty Documents page has a **Choose a file** button that opens your device's file picker directly; the import starts as soon as you pick a file.</Step><Step title="Or drop the file">Drag the file from your computer anywhere onto the Documents page. The page shows **Drop to import**; let go and choose how to read it.@@ -61,6 +61,20 @@ A cover letter exported from Reactive Resume as JSON imports as a letter, not a</Step></Steps>+<Frame caption="AI connection lookup uses the import tile's icon space">+ <img+ src="/images/guides/importing-resumes/new-loading.png"+ alt="New dialog with a spinner in the Import a resume icon space, alongside Copy a resume for a job and Start blank choices"+ />+</Frame>++<Frame caption="Retry a connection lookup without moving the New choices">+ <img+ src="/images/guides/importing-resumes/new-lookup-error.png"+ alt="New dialog with its AI connection lookup failure and Try again button below the document choices"+ />+</Frame>+## Review what came inWhen you open an imported resume from the dialog, the **Write** panel starts with a note naming the file you imported and counting its sections and entries.diff --git a/docs/images/guides/importing-resumes/new-loading.png b/docs/images/guides/importing-resumes/new-loading.pngnew file mode 100644index 000000000..226f9f07fBinary files /dev/null and b/docs/images/guides/importing-resumes/new-loading.png differdiff --git a/docs/images/guides/importing-resumes/new-lookup-error.png b/docs/images/guides/importing-resumes/new-lookup-error.pngnew file mode 100644index 000000000..ac5b3c3d3Binary files /dev/null and b/docs/images/guides/importing-resumes/new-lookup-error.png differdiff --git a/tests/e2e/specs/new-document-layout.spec.ts b/tests/e2e/specs/new-document-layout.spec.tsnew file mode 100644index 000000000..8137213b1--- /dev/null+++ b/tests/e2e/specs/new-document-layout.spec.ts@@ -0,0 +1,165 @@+import type { Locator } from "@playwright/test";+import { startAiStub } from "../fixtures/ai-stub";+import { failRpcProcedure } from "../fixtures/rpc-failure";+import { expect, test } from "../fixtures/test";++test.skip(process.env.FLAG_ALLOW_UNSAFE_AI_BASE_URL !== "true", "Needs local stub URL permission");+let stub: Awaited<ReturnType<typeof startAiStub>>;+test.beforeAll(async () => {+ stub = await startAiStub();+});+test.afterAll(async () => {+ await stub?.close();+});++/** Wait for finite ancestor motion, including replacement or cancelled transitions, before measuring targets. */+async function settledBoxes(dialog: Locator, targets: Locator[]) {+ await dialog.evaluate(() => document.fonts.ready);+ await expect+ .poll(() =>+ dialog.evaluate(+ (element) =>+ element+ .getAnimations({ subtree: true })+ .filter(+ (animation) =>+ animation.effect?.getComputedTiming().iterations !== Infinity &&+ (animation.pending || animation.playState === "running"),+ ).length,+ ),+ )+ .toBe(0);+ return Promise.all(+ targets.map(async (target) => {+ const box = await target.boundingBox();+ if (!box) throw new Error("Visible target has no bounds");+ return box;+ }),+ );+}++for (const lookup of ["empty", "ready", "failed"] as const) {+ for (const width of [1440, 390]) {+ test(`New targets stay put through ${lookup} AI lookup at ${width}px`, async ({ authPage: page }, info) => {+ if (lookup === "ready") {+ const response = await page.request.post("/api/openapi/ai-providers", {+ data: {+ label: "Fictional import connection",+ provider: "openai-compatible",+ model: "stub",+ baseURL: stub.baseURL,+ apiKey: "stub-key",+ },+ });+ await expect(response).toBeOK();+ const { id } = await response.json();+ await expect(await page.request.post(`/api/openapi/ai-providers/${id}/test`)).toBeOK();+ }+ await page.setViewportSize({ width, height: 1000 });+ await page.goto("/dashboard");+ let failLookup = lookup === "failed";+ let returnedProviders: unknown;+ let release = () => {};+ const held = new Promise<void>((resolve) => {+ release = resolve;+ });+ await page.route("**/api/rpc/**", async (route) => {+ const request = route.request();+ const batched = new URL(request.url()).pathname.endsWith("/__batch__");+ const entries: { url: string }[] = batched ? request.postDataJSON() : [{ url: request.url() }];+ const providerIndex = entries.findIndex((entry) => new URL(entry.url).pathname === "/api/rpc/aiProviders/list");+ if (providerIndex < 0) {+ await route.continue();+ return;+ }+ if (failLookup) {+ await held;+ await failRpcProcedure(route, "/api/rpc/aiProviders/list", "Synthetic connection lookup failure");+ return;+ }+ // Hold the real response, including every sibling event; no lookup result is fabricated.+ const response = await route.fetch();+ const payload = batched+ ? (await response.text())+ .split("\n")+ .filter((line) => line.startsWith("data: "))+ .map((line) => JSON.parse(line.slice(6)))+ .find((event) => event.index === providerIndex)?.body+ : await response.json();+ returnedProviders = payload?.json;+ await held;+ await route.fulfill({ response });+ });+ try {+ await page.getByRole("heading", { name: "Documents", level: 1 }).click();+ await page.keyboard.press("n");+ const dialog = page.getByRole("dialog", { name: "New", exact: true });+ await expect(dialog.getByRole("status")).toBeVisible();+ const title = dialog.getByRole("heading", { name: "New", exact: true });+ const start = dialog.getByRole("button", { name: /^Start blank/ });+ const targets = [+ dialog,+ title,+ dialog.getByRole("button", { name: /^Import a resume/ }),+ dialog.getByRole("button", { name: /^Copy a resume for a job/ }),+ start,+ ];+ const before = await settledBoxes(dialog, targets);+ await dialog.screenshot({ path: info.outputPath("new-pending.png") });+ release();+ await expect(dialog.getByRole("status")).toHaveCount(0);+ if (lookup === "failed") await expect(dialog.getByRole("alert")).toBeVisible();+ if (lookup !== "failed") {+ expect(returnedProviders).toEqual(+ lookup === "ready"+ ? expect.arrayContaining([+ expect.objectContaining({+ label: "Fictional import connection",+ enabled: true,+ testStatus: "success",+ }),+ ])+ : [],+ );+ }+ const after = await settledBoxes(dialog, targets);+ await info.attach("target-geometry", {+ body: JSON.stringify({ before, after }, null, 2),+ contentType: "application/json",+ });+ for (const [index, box] of after.entries()) {+ const previous = before[index];+ if (!previous) throw new Error("Missing pending target bounds");+ for (const axis of ["x", "y", "width", "height"] as const)+ expect(Math.abs(box[axis] - previous[axis]), `target ${index} ${axis} moved`).toBeLessThanOrEqual(1);+ }+ await dialog.screenshot({ path: info.outputPath("new-ready.png") });+ if (lookup === "failed") {+ failLookup = false;+ await dialog.getByRole("button", { name: "Try again", exact: true }).click();+ await expect(dialog.getByRole("alert")).toHaveCount(0);+ await expect(dialog.getByRole("status")).toHaveCount(0);+ expect(returnedProviders).toEqual([]);+ const recovered = await settledBoxes(dialog, targets);+ for (const [index, box] of recovered.entries()) {+ const previous = before[index];+ if (!previous) throw new Error("Missing pending target bounds");+ for (const axis of ["x", "y", "width", "height"] as const)+ expect(+ Math.abs(box[axis] - previous[axis]),+ `recovered target ${index} ${axis} moved`,+ ).toBeLessThanOrEqual(1);+ }+ }+ // A click aimed while lookup was pending still opens the intended action after it finishes.+ const button = before[4];+ if (!button) throw new Error("Missing Start blank bounds");+ await page.mouse.click(button.x + button.width / 2, button.y + button.height / 2);+ await page.waitForURL(/\/builder\/.+/);+ await expect(page.getByRole("textbox", { name: "Full name", exact: true })).toBeVisible();+ } finally {+ release();+ }+ });+ }+}