Skip to content

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!

fix: cancel AI imports and explain missing conversations

Amruth Pillai19c7dbe5e90d
diff --git a/apps/web/src/libs/orpc/fetch.test.ts b/apps/web/src/libs/orpc/fetch.test.ts
index 5ee15f40d..88d18cc06 100644
--- a/apps/web/src/libs/orpc/fetch.test.ts
+++ b/apps/web/src/libs/orpc/fetch.test.ts
@@ -66,6 +66,23 @@ describe("RPC fetch", () => {
expect(fetchMock.mock.calls[1]?.[1]?.keepalive).toBe(false);
});
+ it("lets an explicitly authorized AI request disconnect without changing ordinary write delivery", async () => {
+ fetchMock.mockResolvedValue(new Response("ok"));
+ const { rpcFetch } = await import("./fetch");
+ const controller = new AbortController();
+ await rpcFetch(
+ "https://resume.test/api/rpc/ai/parseDocx",
+ { method: "POST", body: "fictional import", signal: controller.signal },
+ { context: { aiDestination: "approved-destination" } },
+ );
+ const sent = fetchMock.mock.calls[0]?.[1];
+ expect(sent?.keepalive).toBe(false);
+ controller.abort();
+ expect(sent?.signal?.aborted).toBe(true);
+ await rpcFetch(rpcUrl, { method: "POST", body: "small draft" });
+ expect(fetchMock.mock.calls[1]?.[1]?.keepalive).toBe(true);
+ });
+
it("uploads large wire bytes to Blob, then sends a tiny reference to the original RPC", async () => {
queueStaging();
const { setAccountScope } = await import("@/libs/auth/account-scope");
diff --git a/apps/web/src/libs/orpc/fetch.ts b/apps/web/src/libs/orpc/fetch.ts
index 899be59dd..ff1084a99 100644
--- a/apps/web/src/libs/orpc/fetch.ts
+++ b/apps/web/src/libs/orpc/fetch.ts
@@ -8,7 +8,7 @@ let stagingUnavailable = false;
export async function rpcFetch(
input: RequestInfo | URL,
init?: RequestInit,
- options?: { context: { defer?: DeferredFetch } },
+ options?: { context: { defer?: DeferredFetch; aiDestination?: string } },
): Promise<Response> {
const defer = options?.context.defer;
const request = new Request(input, { ...init, credentials: "include" });
@@ -27,7 +27,8 @@ export async function rpcFetch(
method: "POST",
headers: request.headers,
body,
- keepalive: body.byteLength <= 60 * 1024,
+ // Cancel must disconnect AI work; ordinary small writes still survive leaving the page.
+ keepalive: !options?.context.aiDestination && body.byteLength <= 60 * 1024,
credentials: "include",
signal: request.signal,
});
diff --git a/apps/web/src/routes/agent/$threadId.tsx b/apps/web/src/routes/agent/$threadId.tsx
index deb5e9d62..f4e199969 100644
--- a/apps/web/src/routes/agent/$threadId.tsx
+++ b/apps/web/src/routes/agent/$threadId.tsx
@@ -1,5 +1,6 @@
import { t } from "@lingui/core/macro";
import { createFileRoute, redirect } from "@tanstack/react-router";
+import { useEffect, useRef } from "react";
import { toast } from "@reactive-resume/ui/components/toast";
import { orpc } from "@/libs/orpc/client";
@@ -39,13 +40,33 @@ export const Route = createFileRoute("/agent/$threadId")({
params: { conversationId: params.threadId },
replace: true,
});
- // An old link lands on Documents with the reason, instead of silently.
- toast.add({
- type: "error",
- description: detail
- ? t`That conversation's document was deleted.`
- : t`That conversation isn't available. It may have been deleted.`,
- });
- throw redirect({ to: "/dashboard", replace: true });
+ return { documentDeleted: detail !== null };
},
+ component: UnavailableConversation,
});
+
+function UnavailableConversation() {
+ const { documentDeleted } = Route.useLoaderData();
+ const { threadId } = Route.useParams();
+ const navigate = Route.useNavigate();
+ const notified = useRef<string | null>(null);
+ useEffect(() => {
+ let active = true;
+ // The root toaster subscribes in a sibling mount effect; let those effects finish before notifying.
+ queueMicrotask(() => {
+ if (!active || notified.current === threadId) return;
+ notified.current = threadId;
+ toast.add({
+ type: "error",
+ description: documentDeleted
+ ? t`That conversation's document was deleted.`
+ : t`That conversation isn't available. It may have been deleted.`,
+ });
+ void navigate({ to: "/dashboard", replace: true });
+ });
+ return () => {
+ active = false;
+ };
+ }, [documentDeleted, navigate, threadId]);
+ return null;
+}
diff --git a/docs/guides/importing-resumes.mdx b/docs/guides/importing-resumes.mdx
index b8b013e96..659fe55d4 100644
--- a/docs/guides/importing-resumes.mdx
+++ b/docs/guides/importing-resumes.mdx
@@ -43,7 +43,7 @@ A cover letter exported from Reactive Resume as JSON imports as a letter, not a
On web, PDF offers **Read on this device (free)**. On mobile, the AI switch is off by default and the text layer is read on your server without an AI provider. Choose AI reading only if you want the complete PDF sent to the named provider. After you choose a Word file, the dialog explains that it needs AI and offers **Set up AI** without leaving your task. AI reading asks you to approve the destination before sending; Word sends extracted document text. JSON and LinkedIn imports never use an AI provider.
</Step>
<Step title="Wait for the three steps">
- The dialog shows **Reading the file**, **Finding sections** and **Filling in entries**, with a note beside each as it finishes. JSON and LinkedIn files take a moment; PDF and Word files read by an AI provider can take longer. Select **Cancel** to stop.
+ The dialog shows **Reading the file**, **Finding sections** and **Filling in entries**, with a note beside each as it finishes. JSON and LinkedIn files take a moment; PDF and Word files read by an AI provider can take longer. Select **Cancel**, or close the import, to stop reading. An AI reading disconnects from the provider; the provider may still charge for work already performed. No resume is created until you select **Create resume**.
</Step>
<Step title="Check what was found">
For PDF and Word files, nothing is created until you've seen what came in. The dialog lists each section it found with its number of entries. On web and mobile, it also lists any readable lines of your file that didn't land in a section, such as a Patents section or a reference. Keep **Add them as a section called “More from your file” to sort later** on to bring them in as one section you can move or delete, or turn it off to leave them out. If no name, email or phone came through, it says so: add them in Basics. Select **Create resume**, or **Choose another file**.
diff --git a/docs/guides/using-the-assistant.mdx b/docs/guides/using-the-assistant.mdx
index 92d74a172..664363feb 100644
--- a/docs/guides/using-the-assistant.mdx
+++ b/docs/guides/using-the-assistant.mdx
@@ -287,7 +287,14 @@ Each conversation belongs to one document. Opening the assistant continues that
Conversations are titled by the first set of edits the assistant proposed ("Tailor summary to payments roles"), or by your first message until there is one. A one-line preview of your original first message appears below the title on web and mobile, followed by the time and how many edits you accepted. This uses the saved message, without another AI request. An attachment-only opening has no message preview. While a conversation is open, its address is in the page's URL, so reloading the page reopens it. Conversations about your other documents appear under **Other documents**; opening one takes you to that document. To delete a conversation, hover over it, select **×**, then confirm. Its messages and attachments are deleted, but edits you accepted stay in your document.
-On a locked document the assistant still answers questions and writes drafts, such as a follow-up email or interview notes, but proposes no edits. The note above the message box offers **Unlock**. A deleted document keeps its conversation read-only, and an old link to a deleted conversation opens Documents with a note saying so. If a provider is off, broken or deleted, history and pending edits stay readable. You can accept saved edits and undo document changes while sending pauses. Repair the connection through **Set up AI**, or choose another model and approve its destination. The app never moves a conversation automatically.
+On a locked document the assistant still answers questions and writes drafts, such as a follow-up email or interview notes, but proposes no edits. The note above the message box offers **Unlock**. A deleted document keeps its conversation read-only. Opening an old conversation link, including in a new tab, returns to Documents with a note explaining that the conversation is unavailable or its document was deleted. Reloading Documents doesn't repeat that note. If a provider is off, broken or deleted, history and pending edits stay readable. You can accept saved edits and undo document changes while sending pauses. Repair the connection through **Set up AI**, or choose another model and approve its destination. The app never moves a conversation automatically.
+
+<Frame caption="An unavailable conversation link returns to Documents with an explanation">
+ <img
+ src="/images/guides/using-the-assistant/unavailable-conversation.png"
+ alt="Documents for a fictional test account, with a notification saying the conversation is unavailable and may have been deleted"
+ />
+</Frame>
<Info>
Replies stream while the conversation is open. On instances without Redis (some self-hosted setups), a reply that's
diff --git a/docs/images/guides/using-the-assistant/unavailable-conversation.png b/docs/images/guides/using-the-assistant/unavailable-conversation.png
new file mode 100644
index 000000000..df2a4f8c2
Binary files /dev/null and b/docs/images/guides/using-the-assistant/unavailable-conversation.png differ
diff --git a/tests/e2e/specs/assistant-import-cancellation.spec.ts b/tests/e2e/specs/assistant-import-cancellation.spec.ts
new file mode 100644
index 000000000..399c7e589
--- /dev/null
+++ b/tests/e2e/specs/assistant-import-cancellation.spec.ts
@@ -0,0 +1,129 @@
+import type { Page } from "@playwright/test";
+import { randomUUID } from "node:crypto";
+import { createServer } from "node:http";
+import { strToU8, zipSync } from "fflate";
+import { startAiStub } from "../fixtures/ai-stub";
+import { twoPagePdf } from "../fixtures/attachment-pdf";
+import { expect, test } from "../fixtures/test";
+
+test.skip(process.env.FLAG_ALLOW_UNSAFE_AI_BASE_URL !== "true", "Needs an isolated local AI provider");
+
+async function connect(page: Page, baseURL: string) {
+ const response = await page.request.post("/api/openapi/ai-providers", {
+ data: { label: "Fictional import AI", provider: "openai-compatible", model: "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();
+}
+
+for (const format of ["Word", "PDF"] as const)
+ for (const exit of ["Cancel", "close"] as const)
+ test(`${exit} ${format} import disconnects the provider and saves no document`, async ({ authPage: page }) => {
+ let pending = false;
+ let closed = false;
+ const server = createServer((request, response) => {
+ let body = "";
+ request.on("data", (chunk) => (body += chunk));
+ request.on("end", () => {
+ const input = JSON.parse(body) as { messages: unknown };
+ if (JSON.stringify(input.messages).includes("Use the following JSON as a template")) {
+ pending = true;
+ response.on("close", () => (closed = true));
+ return;
+ }
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(
+ JSON.stringify({
+ id: "fictional",
+ object: "chat.completion",
+ created: 0,
+ model: "stub",
+ choices: [{ index: 0, message: { role: "assistant", content: "1" }, finish_reason: "stop" }],
+ }),
+ );
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing local provider port");
+ await connect(page, `http://127.0.0.1:${address.port}/v1`);
+ await page.goto("/dashboard");
+ await page.getByRole("button", { name: "New", exact: true }).click();
+ const dialog = page.getByRole("dialog");
+ const word = Buffer.from(
+ zipSync({
+ "word/document.xml": strToU8(
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Avery Morgan, fictional resume</w:t></w:r></w:p></w:body></w:document>',
+ ),
+ }),
+ );
+ await dialog.getByLabel("Choose a file to import").setInputFiles({
+ name: format === "Word" ? "fictional.docx" : "fictional.pdf",
+ mimeType:
+ format === "Word"
+ ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+ : "application/pdf",
+ buffer: format === "Word" ? word : twoPagePdf(),
+ });
+ await dialog.getByRole("button", { name: "Read with AI", exact: true }).click();
+ const approval = page.getByRole("alertdialog");
+ await expect(approval).toContainText("127.0.0.1");
+ await approval.getByRole("button", { name: "Allow this operation", exact: true }).click();
+ await expect.poll(() => pending).toBe(true);
+ if (exit === "Cancel") await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
+ else await page.keyboard.press("Escape");
+ await expect.poll(() => closed).toBe(true);
+ const resumes = await page.request.get("/api/openapi/resumes");
+ await expect(resumes).toBeOK();
+ expect(await resumes.json()).toEqual([]);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
+ }
+ });
+
+for (const missing of ["conversation", "document"] as const)
+ test(`a cold link explains its missing ${missing} after redirect, once`, async ({ authPage: page }, info) => {
+ let id = randomUUID();
+ if (missing === "document") {
+ const provider = await startAiStub();
+ try {
+ await connect(page, provider.baseURL);
+ const resume = await page.request.post("/api/openapi/resumes", {
+ data: { name: "Fictional removed resume", tags: [] },
+ });
+ await expect(resume).toBeOK();
+ const resumeId = await resume.json();
+ const thread = await page.request.post("/api/rpc/agent/threads/start", { data: { json: { resumeId } } });
+ await expect(thread).toBeOK();
+ id = (await thread.json()).json.id;
+ await page.goto(`/agent/${id}`);
+ await page.waitForURL(
+ (url) => url.pathname === `/builder/${resumeId}` && url.searchParams.get("assistant") === id,
+ );
+ await expect(page.getByRole("region", { name: "Assistant", exact: true })).toBeVisible();
+ await expect(await page.request.delete(`/api/openapi/resumes/${resumeId}`)).toBeOK();
+ await expect(
+ await page.request.post("/api/rpc/documents/purge", { data: { json: { type: "resume", id: resumeId } } }),
+ ).toBeOK();
+ } finally {
+ await provider.close();
+ }
+ }
+ await page.goto(`/agent/${id}`);
+ await page.waitForURL("**/dashboard");
+ const notice =
+ missing === "document"
+ ? "That conversation's document was deleted."
+ : "That conversation isn't available. It may have been deleted.";
+ await expect(page.getByText(notice, { exact: true })).toBeVisible();
+ await expect(page.getByText(notice, { exact: true })).toHaveCount(1);
+ await expect(page.getByRole("button", { name: "New", exact: true })).toBeVisible();
+ if (missing === "conversation")
+ await page.screenshot({ path: info.outputPath("unavailable-conversation.png"), animations: "disabled" });
+ await page.reload();
+ await expect(page.getByRole("button", { name: "New", exact: true })).toBeVisible();
+ await expect(page.getByText(notice, { exact: true })).toHaveCount(0);
+ });