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: remove unsent attachments and protect sent files

Amruth Pillai005ae2b542e5
diff --git a/apps/web/src/features/assistant/assistant-panel.test.tsx b/apps/web/src/features/assistant/assistant-panel.test.tsx
index f38a29e04..c624348f9 100644
--- a/apps/web/src/features/assistant/assistant-panel.test.tsx
+++ b/apps/web/src/features/assistant/assistant-panel.test.tsx
@@ -47,7 +47,10 @@ vi.mock("@/libs/orpc/client", () => ({
},
}));
vi.mock("@reactive-resume/ui/components/toast", () => ({ toast: { add: vi.fn() } }));
-vi.mock("./chat", () => ({ fileToBase64: async () => "Zm9v" }));
+vi.mock("./chat", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./chat")>()),
+ fileToBase64: async () => "Zm9v",
+}));
import { AssistantPanel } from "./assistant-panel";
diff --git a/apps/web/src/features/assistant/chat.ts b/apps/web/src/features/assistant/chat.ts
index f36a6da90..5d09ac758 100644
--- a/apps/web/src/features/assistant/chat.ts
+++ b/apps/web/src/features/assistant/chat.ts
@@ -18,6 +18,14 @@ export type MessageContext = {
export type ChatAttachment = { id: string; filename: string; mediaType: string };
+/** Name the upload limit that was reached in every conversation composer. */
+export const attachmentErrorMessages = () => ({
+ AGENT_ATTACHMENT_LIMIT: t`Attach up to 10 files per message.`,
+ AGENT_ATTACHMENT_TOO_LARGE: t`Files can be up to 25 MB.`,
+ AGENT_THREAD_ATTACHMENTS_FULL: t`A conversation's files can total up to 100 MB. Start a new conversation.`,
+ AGENT_ACCOUNT_ATTACHMENTS_FULL: t`Your assistant files can total up to 1 GB. Delete conversations you no longer need.`,
+});
+
export const attachmentPart = (attachment: ChatAttachment): FileUIPart => ({
type: "file",
url: `agent-attachment:${attachment.id}`,
diff --git a/apps/web/src/features/assistant/conversation.test.tsx b/apps/web/src/features/assistant/conversation.test.tsx
index 81506af1b..6dc7bc8e2 100644
--- a/apps/web/src/features/assistant/conversation.test.tsx
+++ b/apps/web/src/features/assistant/conversation.test.tsx
@@ -42,7 +42,8 @@ vi.mock("@/libs/orpc/client", () => ({
vi.mock("@reactive-resume/ui/components/toast", () => ({ toast: { add: vi.fn() } }));
vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn(), useSearch: () => ({}) }));
vi.mock("./use-assistant-chat", () => ({ useAssistantChat: mocks.chat }));
-vi.mock("./chat", () => ({
+vi.mock("./chat", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./chat")>()),
fileToBase64: async () => "Zm9v",
attachmentPart: (file: { id: string; filename: string; mediaType: string }) => ({
type: "file",
diff --git a/apps/web/src/features/assistant/conversation.tsx b/apps/web/src/features/assistant/conversation.tsx
index 321322a81..0fdbe0ef7 100644
--- a/apps/web/src/features/assistant/conversation.tsx
+++ b/apps/web/src/features/assistant/conversation.tsx
@@ -38,13 +38,14 @@ import { Spinner } from "@reactive-resume/ui/components/spinner";
import { toast } from "@reactive-resume/ui/components/toast";
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@reactive-resume/ui/components/trace";
import { cn } from "@reactive-resume/utils/style";
-import { attachmentPart, fileToBase64, transcriptOf } from "./chat";
+import { attachmentErrorMessages, attachmentPart, fileToBase64, transcriptOf } from "./chat";
import { ChatComposer } from "./chat-chrome";
import { AssistantMarkdown } from "./markdown";
import { QuestionCard } from "./question-card";
import { SavePosting } from "./save-posting";
import { ToolApprovals } from "./tool-approvals";
import { useAssistantChat } from "./use-assistant-chat";
+import { useAttachmentRemoval } from "./use-attachment-removal";
import { UsedChip } from "./used-chip";
import { useDialogStore } from "@/dialogs/store";
import { ContextChip } from "@/features/career/shared";
@@ -1042,12 +1043,15 @@ export function Composer(props: ComposerProps) {
const openDialog = useDialogStore((state) => state.openDialog);
const [text, setText] = useState(props.initialText ?? "");
const [attachments, setAttachments] = useState<ChatAttachment[]>([]);
+ const removal = useAttachmentRemoval(`${document.kind}:${document.id}:${props.threadId ?? "draft"}`, (id) =>
+ setAttachments((current) => current.filter((item) => item.id !== id)),
+ );
const [uploading, setUploading] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
const hasText = text.trim().length > 0;
const submit = () => {
- if (!hasText || streaming || disabled || uploading) return;
+ if (!hasText || streaming || disabled || uploading || removal.isPending) return;
props.onSend(text.trim(), attachments);
setText("");
setAttachments([]);
@@ -1163,7 +1167,7 @@ export function Composer(props: ComposerProps) {
value={text}
onValueChange={setText}
disabled={disabled}
- sendDisabled={!hasText || disabled || uploading}
+ sendDisabled={!hasText || disabled || uploading || removal.isPending}
streaming={streaming}
onSend={submit}
onStop={props.onStop}
@@ -1210,7 +1214,8 @@ export function Composer(props: ComposerProps) {
label={attachment.filename}
maxWidth="max-w-[140px]"
removeLabel={t`Remove ${attachment.filename}`}
- onRemove={() => setAttachments((current) => current.filter((item) => item.id !== attachment.id))}
+ disabled={disabled || streaming || uploading || removal.isPending}
+ onRemove={() => void removal.remove(attachment.id)}
/>
))}
</>
@@ -1223,7 +1228,7 @@ export function Composer(props: ComposerProps) {
icon="paperclip"
label={t`Attach a file`}
size="icon-sm"
- disabled={disabled || uploading}
+ disabled={disabled || uploading || removal.isPending}
className="text-ink-2"
onClick={() => fileInput.current?.click()}
/>
@@ -1258,14 +1263,6 @@ export function Composer(props: ComposerProps) {
);
}
-/** The upload limits by name: which one was reached, rather than "try again". */
-const attachmentErrorMessages = () => ({
- AGENT_ATTACHMENT_LIMIT: t`Attach up to 10 files per message.`,
- AGENT_ATTACHMENT_TOO_LARGE: t`Files can be up to 25 MB.`,
- AGENT_THREAD_ATTACHMENTS_FULL: t`A conversation's files can total up to 100 MB. Start a new conversation.`,
- AGENT_ACCOUNT_ATTACHMENTS_FULL: t`Your assistant files can total up to 1 GB. Delete conversations you no longer need.`,
-});
-
type RemovableChipProps = {
icon: IconName;
label: string;
@@ -1273,9 +1270,10 @@ type RemovableChipProps = {
maxWidth: string;
removeLabel: string;
onRemove: () => void;
+ disabled?: boolean;
};
-function RemovableChip({ icon, label, maxWidth, removeLabel, onRemove }: RemovableChipProps) {
+function RemovableChip({ icon, label, maxWidth, removeLabel, onRemove, disabled }: RemovableChipProps) {
return (
<span className="flex h-[26px] items-center gap-1 rounded-md bg-sunken ps-2 text-xs text-ink-2">
<Icon name={icon} size={15} />
@@ -1284,6 +1282,7 @@ function RemovableChip({ icon, label, maxWidth, removeLabel, onRemove }: Removab
type="button"
aria-label={removeLabel}
onClick={onRemove}
+ disabled={disabled}
className="touch-target relative grid size-5 place-items-center rounded text-ink-3 transition-colors hover:bg-hover hover:text-ink"
>
<Icon name="x" size={14} />
diff --git a/apps/web/src/features/assistant/use-attachment-removal.test.tsx b/apps/web/src/features/assistant/use-attachment-removal.test.tsx
new file mode 100644
index 000000000..b370340d4
--- /dev/null
+++ b/apps/web/src/features/assistant/use-attachment-removal.test.tsx
@@ -0,0 +1,88 @@
+// @vitest-environment happy-dom
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+import { i18n } from "@lingui/core";
+import { invalidateAccountScope, setAccountScope } from "@/libs/auth/account-scope";
+
+const mocks = vi.hoisted(() => ({ remove: vi.fn(), error: vi.fn() }));
+vi.mock("@/libs/orpc/client", () => ({ client: { agent: { attachments: { delete: mocks.remove } } } }));
+vi.mock("@/libs/error-message", () => ({ toastError: mocks.error }));
+
+import { useAttachmentRemoval } from "./use-attachment-removal";
+
+function deferred() {
+ let resolve = () => {};
+ let reject = (_error: Error) => {};
+ const promise = new Promise<void>((done, failed) => {
+ resolve = done;
+ reject = failed;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ setAccountScope("alice");
+ i18n.loadAndActivate({ locale: "en-US", messages: {} });
+});
+afterEach(() => {
+ cleanup();
+ invalidateAccountScope();
+});
+
+it("waits for deletion, refuses duplicate removal, and keeps a failed file available for retry", async () => {
+ const request = deferred();
+ mocks.remove.mockReturnValueOnce(request.promise).mockResolvedValueOnce(undefined);
+ const removed = vi.fn();
+ const { result } = renderHook(() => useAttachmentRemoval("thread-1", removed));
+ let removing: Promise<void> = Promise.resolve();
+ act(() => {
+ removing = result.current.remove("file-1");
+ void result.current.remove("file-1");
+ });
+ expect(result.current.isPending).toBe(true);
+ expect(mocks.remove).toHaveBeenCalledExactlyOnceWith({ id: "file-1" }, { context: { accountId: "alice" } });
+ expect(removed).not.toHaveBeenCalled();
+ await act(async () => {
+ request.reject(new Error("Storage unavailable"));
+ await removing;
+ });
+ expect(removed).not.toHaveBeenCalled();
+ expect(mocks.error).toHaveBeenCalledOnce();
+ expect(result.current.isPending).toBe(false);
+ await act(async () => result.current.remove("file-1"));
+ expect(removed).toHaveBeenCalledExactlyOnceWith("file-1");
+});
+
+it.each(
+ ["draft", "account", "reauthentication", "unmount"].flatMap((change) =>
+ ["success", "failure"].map((outcome) => ({ change, outcome })),
+ ),
+)("a late deletion $outcome cannot affect the composer after $change changes", async ({ change, outcome }) => {
+ const request = deferred();
+ mocks.remove.mockReturnValueOnce(request.promise);
+ const removed = vi.fn();
+ const view = renderHook(({ scope }) => useAttachmentRemoval(scope, removed), {
+ initialProps: { scope: "thread-1" },
+ });
+ let removing: Promise<void> = Promise.resolve();
+ const staleRemove = view.result.current.remove;
+ act(() => {
+ removing = staleRemove("file-1");
+ });
+ if (change === "draft") view.rerender({ scope: "thread-2" });
+ else if (change === "account") setAccountScope("bob");
+ else if (change === "reauthentication") {
+ invalidateAccountScope();
+ setAccountScope("alice");
+ } else view.unmount();
+ await act(async () => {
+ if (outcome === "failure") request.reject(new Error("Storage unavailable"));
+ else request.resolve();
+ await removing;
+ await staleRemove("file-2");
+ });
+ expect(removed).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ expect(mocks.remove).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/features/assistant/use-attachment-removal.ts b/apps/web/src/features/assistant/use-attachment-removal.ts
new file mode 100644
index 000000000..8361e1829
--- /dev/null
+++ b/apps/web/src/features/assistant/use-attachment-removal.ts
@@ -0,0 +1,49 @@
+import { t } from "@lingui/core/macro";
+import { useLayoutEffect, useMemo, useRef, useState } from "react";
+import { getAccountGeneration, getAccountId } from "@/libs/auth/account-scope";
+import { toastError } from "@/libs/error-message";
+import { client } from "@/libs/orpc/client";
+
+type RemovalScope = {
+ key: string;
+ accountId: string | null;
+ generation: number;
+};
+
+/** Keep an unsent file available for retry until its owner confirms deletion. */
+export function useAttachmentRemoval(key: string, onRemoved: (id: string) => void) {
+ const accountId = getAccountId();
+ const generation = getAccountGeneration();
+ const owner = useMemo<RemovalScope>(() => ({ key, accountId, generation }), [key, accountId, generation]);
+ const active = useRef<{ owner: RemovalScope; busy: boolean } | null>(null);
+ const [pending, setPending] = useState<RemovalScope | null>(null);
+ useLayoutEffect(() => {
+ active.current = { owner, busy: false };
+ return () => {
+ active.current = null;
+ };
+ }, [owner]);
+
+ const current = () =>
+ active.current?.owner === owner &&
+ getAccountId() === owner.accountId &&
+ getAccountGeneration() === owner.generation;
+
+ const remove = async (id: string) => {
+ const scope = active.current;
+ if (!owner.accountId || !scope || scope.busy || !current()) return;
+ scope.busy = true;
+ setPending(owner);
+ try {
+ await client.agent.attachments.delete({ id }, { context: { accountId: owner.accountId } });
+ if (current()) onRemoved(id);
+ } catch (error) {
+ if (current()) toastError(error, t`Couldn't save that change. Try again.`);
+ } finally {
+ scope.busy = false;
+ if (current()) setPending(null);
+ }
+ };
+
+ return { remove, isPending: pending === owner };
+}
diff --git a/apps/web/src/features/career/coach-thread.tsx b/apps/web/src/features/career/coach-thread.tsx
index 41df6ca43..dd2cec083 100644
--- a/apps/web/src/features/career/coach-thread.tsx
+++ b/apps/web/src/features/career/coach-thread.tsx
@@ -22,8 +22,9 @@ import { cn } from "@reactive-resume/utils/style";
import { useSessionDraft } from "./hooks";
import { MemoryCard } from "./knowledge/facts";
import { ContextChip, useCareerTime, useNow, withUndo } from "./shared";
-import { fileToBase64 } from "@/features/assistant/chat";
+import { attachmentErrorMessages, fileToBase64 } from "@/features/assistant/chat";
import { ChatComposer } from "@/features/assistant/chat-chrome";
+import { useAttachmentRemoval } from "@/features/assistant/use-attachment-removal";
import { toastError } from "@/libs/error-message";
import { client, orpc } from "@/libs/orpc/client";
@@ -349,12 +350,15 @@ export function Composer(props: ComposerProps) {
const text = draft.value;
const setText = draft.setValue;
const [attachments, setAttachments] = useState<Upload[]>([]);
+ const removal = useAttachmentRemoval(props.draftKey ?? "draft", (id) =>
+ setAttachments((current) => current.filter((item) => item.id !== id)),
+ );
const [uploading, setUploading] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
const submit = async () => {
const value = text.trim();
- if (!value || props.streaming || props.disabled || uploading) return;
+ if (!value || props.streaming || props.disabled || uploading || removal.isPending) return;
const sent = await props.onSend(
value,
attachments.map(({ size: _size, ...attachment }) => attachment),
@@ -383,7 +387,7 @@ export function Composer(props: ComposerProps) {
);
setAttachments((current) => [...current, ...uploaded]);
} catch (error) {
- toastError(error, t`Couldn't attach the file. Try again.`);
+ toastError(error, t`Couldn't attach the file. Try again.`, { byCode: attachmentErrorMessages() });
} finally {
setUploading(false);
if (fileInput.current) fileInput.current.value = "";
@@ -402,7 +406,7 @@ export function Composer(props: ComposerProps) {
value={text}
onValueChange={setText}
disabled={props.disabled}
- sendDisabled={!text.trim() || props.disabled || uploading}
+ sendDisabled={!text.trim() || props.disabled || uploading || removal.isPending}
streaming={props.streaming}
onSend={() => void submit()}
onStop={props.onStop}
@@ -421,7 +425,8 @@ export function Composer(props: ComposerProps) {
<button
type="button"
aria-label={t`Remove ${attachment.filename}`}
- onClick={() => setAttachments((current) => current.filter((item) => item.id !== attachment.id))}
+ onClick={() => void removal.remove(attachment.id)}
+ disabled={props.disabled || props.streaming || uploading || removal.isPending}
className="grid size-6 place-items-center rounded-sm text-ink-3 transition-colors duration-quick hover:bg-hover hover:text-ink"
>
<Icon name="x" size={14} />
@@ -436,7 +441,7 @@ export function Composer(props: ComposerProps) {
icon="paperclip"
label={t`Attach a file`}
size="icon-sm"
- disabled={props.disabled || uploading}
+ disabled={props.disabled || uploading || removal.isPending}
loading={uploading}
className="text-ink-2"
onClick={() => fileInput.current?.click()}
diff --git a/docs/guides/using-the-assistant.mdx b/docs/guides/using-the-assistant.mdx
index 1a27884bf..5ef26c754 100644
--- a/docs/guides/using-the-assistant.mdx
+++ b/docs/guides/using-the-assistant.mdx
@@ -197,6 +197,15 @@ When you select **Interview prep** from an application's detail panel, the assis
Select the paperclip in the message box to attach files, such as a job description PDF or your notes. You can attach them before your first message or later in the conversation. The file picker offers the types the assistant can read. Each file shows as a chip; select its **×** to remove it before sending, which also deletes the uploaded file.
+On the web, the file stays in the box until removal is confirmed. Sending and further file changes wait while removal is pending. If removal fails, your message and file stay available; select **×** again to retry. The same applies in Career and application coach conversations. Files already sent stay with their messages until you delete the conversation.
+
+<Frame caption="A failed web removal keeps the fictional job-notes file and unsent message available for retry.">
+ <img
+ src="/images/guides/using-the-assistant/attachment-removal.png"
+ alt="Web assistant showing a fictional attachment chip and typed message after a removal error."
+ />
+</Frame>
+
- Plain text, Markdown, JSON and Word (`.docx`) files are read as text (up to the first 40,000 characters). A Word file's page headers and footers are read too. If a Word file is damaged or has no text, the step shows **Couldn't read the attachment**.
- Images, PDFs and MP3 or WAV audio are passed to the model directly. Whether the model can use them depends on your provider.
- You can attach up to 10 files per message, each up to 25 MB, 100 MB per conversation and 1 GB across all your conversations. When you reach a limit, the message names it.
diff --git a/docs/images/guides/using-the-assistant/attachment-removal.png b/docs/images/guides/using-the-assistant/attachment-removal.png
new file mode 100644
index 000000000..a3d9fbb55
Binary files /dev/null and b/docs/images/guides/using-the-assistant/attachment-removal.png differ
diff --git a/packages/api/src/features/agent/review.integration.test.ts b/packages/api/src/features/agent/review.integration.test.ts
index 201bf0f4d..648018d7d 100644
--- a/packages/api/src/features/agent/review.integration.test.ts
+++ b/packages/api/src/features/agent/review.integration.test.ts
@@ -179,6 +179,111 @@ describe.skipIf(!databaseUrl)("document assistant review on PostgreSQL", () => {
return agent.threads.get({ id: threadId, userId });
}
+ it("removes only owned unsent files, retaining failed deletions and sent attachments", async () => {
+ const db = fixture.db;
+ if (!db) throw new Error("Missing fixture database");
+ const thread = await agent.threads.start({ userId, resumeId: copyId });
+ const { getStorageService } = await import("../storage/service");
+ const remove = vi.spyOn(getStorageService(), "delete").mockResolvedValue(true);
+ try {
+ const [message] = await db
+ .insert(tables.agentMessage)
+ .values({ userId, threadId: thread.id, role: "user", sequence: 0, uiMessage: { role: "user", parts: [] } })
+ .returning();
+ if (!message) throw new Error("Missing sent message");
+ const [unsent, sent] = await db
+ .insert(tables.agentAttachment)
+ .values([
+ {
+ userId,
+ threadId: thread.id,
+ storageKey: "fiction-unsent",
+ filename: "notes.txt",
+ mediaType: "text/plain",
+ size: 4,
+ },
+ {
+ userId,
+ threadId: thread.id,
+ storageKey: "fiction-sent",
+ filename: "sent.txt",
+ mediaType: "text/plain",
+ size: 4,
+ messageId: message.id,
+ },
+ ])
+ .returning();
+ if (!unsent || !sent) throw new Error("Missing attachments");
+ await agent.attachments.delete({ id: unsent.id, userId: "another-account" });
+ await expect(agent.attachments.delete({ id: sent.id, userId })).rejects.toMatchObject({ code: "CONFLICT" });
+ expect(remove).not.toHaveBeenCalled();
+ remove.mockRejectedValueOnce(new Error("Storage unavailable"));
+ await expect(agent.attachments.delete({ id: unsent.id, userId })).rejects.toThrow("Storage unavailable");
+ expect((await pool.query("select id from agent_attachments where thread_id=$1", [thread.id])).rowCount).toBe(2);
+ await agent.attachments.delete({ id: unsent.id, userId });
+ await agent.attachments.delete({ id: unsent.id, userId });
+ expect(remove).toHaveBeenCalledTimes(2);
+ expect(remove).toHaveBeenLastCalledWith("fiction-unsent");
+ expect((await pool.query("select id from agent_attachments where thread_id=$1", [thread.id])).rows).toEqual([
+ { id: sent.id },
+ ]);
+ } finally {
+ remove.mockRestore();
+ }
+ });
+
+ it("waits for a concurrent sent-file claim before deciding whether removal may delete its bytes", async () => {
+ const db = fixture.db;
+ if (!db) throw new Error("Missing fixture database");
+ const thread = await agent.threads.start({ userId, resumeId: copyId });
+ const [message] = await db
+ .insert(tables.agentMessage)
+ .values({ userId, threadId: thread.id, role: "user", sequence: 0, uiMessage: { role: "user", parts: [] } })
+ .returning();
+ const [attachment] = await db
+ .insert(tables.agentAttachment)
+ .values({
+ userId,
+ threadId: thread.id,
+ storageKey: "fiction-race",
+ filename: "notes.txt",
+ mediaType: "text/plain",
+ size: 4,
+ })
+ .returning();
+ if (!message || !attachment) throw new Error("Missing message or attachment");
+ const { getStorageService } = await import("../storage/service");
+ const remove = vi.spyOn(getStorageService(), "delete").mockResolvedValue(true);
+ const holder = await pool.connect();
+ let removal: Promise<unknown> = Promise.resolve();
+ try {
+ await holder.query("BEGIN");
+ const pid = (await holder.query<{ pid: number }>("select pg_backend_pid() as pid")).rows[0]?.pid;
+ if (!pid) throw new Error("Missing lock holder");
+ await holder.query("UPDATE agent_attachments SET message_id=$1 WHERE id=$2", [message.id, attachment.id]);
+ removal = agent.attachments.delete({ id: attachment.id, userId }).catch((error: unknown) => error);
+ await vi.waitFor(async () => {
+ const blocked = await admin.query(
+ "select pid from pg_stat_activity where $1=any(pg_blocking_pids(pid)) and query ilike '%select%agent_attachments%for update%'",
+ [pid],
+ );
+ expect(blocked.rowCount).toBe(1);
+ });
+ expect(remove).not.toHaveBeenCalled();
+ await holder.query("COMMIT");
+ await expect(removal).resolves.toMatchObject({ code: "CONFLICT" });
+ expect(remove).not.toHaveBeenCalled();
+ expect((await pool.query("select message_id from agent_attachments where id=$1", [attachment.id])).rows).toEqual([
+ { message_id: message.id },
+ ]);
+ } finally {
+ await holder.query("ROLLBACK");
+ holder.release();
+ await removal;
+ remove.mockRestore();
+ }
+ });
+
const proposalOf = (messages: UIMessage[]) => {
for (const message of messages)
for (const part of message.parts)
diff --git a/packages/api/src/features/agent/service.ts b/packages/api/src/features/agent/service.ts
index f4813947d..8472c6fac 100644
--- a/packages/api/src/features/agent/service.ts
+++ b/packages/api/src/features/agent/service.ts
@@ -2258,18 +2258,24 @@ export const agentService = {
delete: async (input: { id: string; userId: string }) => {
assertAgentEnvironment();
- const [attachment] = await db
- .select()
- .from(schema.agentAttachment)
- .where(and(eq(schema.agentAttachment.id, input.id), eq(schema.agentAttachment.userId, input.userId)))
- .limit(1);
-
- if (!attachment) return;
-
- await getStorageService().delete(attachment.storageKey);
- await db
- .delete(schema.agentAttachment)
- .where(and(eq(schema.agentAttachment.id, input.id), eq(schema.agentAttachment.userId, input.userId)));
+ await db.transaction(async (tx) => {
+ // Sending claims this same row; a sent file must never lose its bytes to a late Remove.
+ const [attachment] = await tx
+ .select()
+ .from(schema.agentAttachment)
+ .where(and(eq(schema.agentAttachment.id, input.id), eq(schema.agentAttachment.userId, input.userId)))
+ .limit(1)
+ .for("update");
+ if (!attachment) return;
+ if (attachment.messageId)
+ throw new ORPCError("CONFLICT", {
+ message: "This file was already sent. Delete its conversation to remove it.",
+ });
+ await getStorageService().delete(attachment.storageKey);
+ await tx
+ .delete(schema.agentAttachment)
+ .where(and(eq(schema.agentAttachment.id, input.id), eq(schema.agentAttachment.userId, input.userId)));
+ });
},
},
};
diff --git a/tests/e2e/specs/assistant-attachment-removal.spec.ts b/tests/e2e/specs/assistant-attachment-removal.spec.ts
new file mode 100644
index 000000000..89c93c94e
--- /dev/null
+++ b/tests/e2e/specs/assistant-attachment-removal.spec.ts
@@ -0,0 +1,182 @@
+import type { Page, TestInfo } from "@playwright/test";
+import { Pool } from "pg";
+import { startAiStub } from "../fixtures/ai-stub";
+import { createAuthenticatedContext } from "../fixtures/auth";
+import { createAccount } from "../fixtures/data";
+import { deleteE2EUser } from "../fixtures/db";
+import { expect, test } from "../fixtures/test";
+
+let stub: Awaited<ReturnType<typeof startAiStub>>;
+test.beforeAll(async () => {
+ stub = await startAiStub();
+});
+test.afterAll(async () => {
+ await stub?.close();
+});
+
+async function openComposer(page: Page, area: "assistant" | "coach") {
+ const created = await page.request.post("/api/openapi/ai-providers", {
+ data: {
+ label: "Fictional connection",
+ provider: "openai-compatible",
+ model: "stub",
+ baseURL: stub.baseURL,
+ apiKey: "stub-key",
+ },
+ });
+ await expect(created).toBeOK();
+ const { id } = await created.json();
+ await expect(await page.request.post(`/api/openapi/ai-providers/${id}/test`)).toBeOK();
+ if (area === "coach") return page.goto("/dashboard/career/coach");
+ const resume = await page.request.post("/api/openapi/resumes", {
+ data: { name: "Avery's fictional resume", tags: [], withSampleData: true },
+ });
+ await expect(resume).toBeOK();
+ await page.goto(`/builder/${await resume.json()}`);
+ await page.getByRole("button", { name: "Assistant", exact: true }).click();
+}
+
+async function approve(page: Page) {
+ const dialog = page.getByRole("alertdialog");
+ await expect(dialog).toContainText("127.0.0.1");
+ await dialog.getByRole("button", { name: "Allow this operation", exact: true }).click();
+}
+
+async function attach(page: Page, names: string[]) {
+ await page
+ .locator('input[type="file"][multiple]')
+ .setInputFiles(
+ names.map((name) => ({ name, mimeType: "text/plain", buffer: Buffer.from("Fictional job notes.") })),
+ );
+ for (const _name of names) {
+ const uploaded = page.waitForResponse((response) => response.url().includes("/agent/attachments/create"));
+ await approve(page);
+ expect((await uploaded).ok()).toBe(true);
+ }
+ for (const name of names)
+ await expect(page.getByRole("button", { name: `Remove ${name}`, exact: true })).toBeVisible();
+}
+
+for (const area of ["assistant", "coach"] as const)
+ test(`${area} attachment removal releases durable quota before the next upload`, async ({
+ authPage: page,
+ account,
+ }) => {
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
+ try {
+ await openComposer(page, area);
+ const names = Array.from({ length: 10 }, (_, index) => `fictional-notes-${index}.txt`);
+ await attach(page, names);
+ const count = async () =>
+ Number(
+ (
+ await pool.query(
+ 'select count(*) as n from agent_attachments a join "user" u on u.id=a.user_id where u.email=$1 and a.message_id is null',
+ [account.email],
+ )
+ ).rows[0].n,
+ );
+ expect(await count()).toBe(10);
+ const refused = page.waitForResponse((response) => response.url().includes("/agent/attachments/create"));
+ await page.locator('input[type="file"][multiple]').setInputFiles({
+ name: "beyond-limit.txt",
+ mimeType: "text/plain",
+ buffer: Buffer.from("Fictional extra notes."),
+ });
+ await approve(page);
+ expect((await refused).status()).toBe(400);
+ await expect(page.getByText("Attach up to 10 files per message.", { exact: true })).toBeVisible();
+ expect(await count()).toBe(10);
+ for (const name of names) {
+ const removed = page.waitForResponse((response) => response.url().includes("/agent/attachments/delete"));
+ await page.getByRole("button", { name: `Remove ${name}`, exact: true }).click();
+ expect((await removed).ok()).toBe(true);
+ await expect(page.getByRole("button", { name: `Remove ${name}`, exact: true })).toHaveCount(0);
+ }
+ expect(await count()).toBe(0);
+ await attach(page, ["next-fictional-notes.txt"]);
+ expect(await count()).toBe(1);
+ } finally {
+ await pool.end();
+ }
+ });
+
+test("failed removal keeps the file and typed message, blocks send until acknowledged, and retries", async ({
+ authPage: page,
+}, info) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await openComposer(page, "assistant");
+ await attach(page, ["fictional-job-notes.txt"]);
+ const message = page.getByRole("textbox", { name: "Message the assistant", exact: true });
+ await message.fill("Compare these fictional job notes with my resume.");
+ let release = () => {};
+ let entered = () => {};
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const requested = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ await page.route("**/api/rpc/agent/attachments/delete", async (route) => {
+ entered();
+ await held;
+ await route.fulfill({ status: 503, contentType: "text/plain", body: "Synthetic storage failure" });
+ });
+ try {
+ await page.getByRole("button", { name: "Remove fictional-job-notes.txt", exact: true }).click();
+ await requested;
+ await expect(page.getByRole("button", { name: "Send", exact: true })).toBeDisabled();
+ await expect(page.getByRole("button", { name: "Remove fictional-job-notes.txt", exact: true })).toBeDisabled();
+ await expect(message).toHaveValue("Compare these fictional job notes with my resume.");
+ release();
+ await expect(page.getByText("Couldn't save that change. Try again.", { exact: true })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Remove fictional-job-notes.txt", exact: true })).toBeEnabled();
+ await expect(message).toHaveValue("Compare these fictional job notes with my resume.");
+ await page.evaluate(() => document.fonts.ready);
+ await page.screenshot({ path: info.outputPath("attachment-removal.png"), animations: "disabled" });
+ } finally {
+ release();
+ await page.unroute("**/api/rpc/agent/attachments/delete");
+ }
+ const removed = page.waitForResponse((response) => response.url().includes("/agent/attachments/delete"));
+ await page.getByRole("button", { name: "Remove fictional-job-notes.txt", exact: true }).click();
+ expect((await removed).ok()).toBe(true);
+ await expect(page.getByRole("button", { name: "Remove fictional-job-notes.txt", exact: true })).toHaveCount(0);
+ await expect(message).toHaveValue("Compare these fictional job notes with my resume.");
+});
+
+test("foreign deletion cannot remove an upload, and sent attachments survive late removal", async ({
+ authPage: page,
+ account,
+ browser,
+ request,
+}, info: TestInfo) => {
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
+ const stranger = createAccount(info);
+ const other = await createAuthenticatedContext(browser, request, stranger, String(info.project.use.baseURL));
+ try {
+ await openComposer(page, "assistant");
+ await attach(page, ["sent-fictional-notes.txt"]);
+ const rows = async () =>
+ (
+ await pool.query(
+ 'select a.id,a.message_id from agent_attachments a join "user" u on u.id=a.user_id where u.email=$1',
+ [account.email],
+ )
+ ).rows;
+ const id = (await rows())[0].id;
+ await expect(await other.request.delete(`/api/openapi/agent/attachments/${id}`)).toBeOK();
+ expect(await rows()).toHaveLength(1);
+ await page.getByRole("textbox", { name: "Message the assistant", exact: true }).fill("Read these fictional notes.");
+ await page.getByRole("button", { name: "Send", exact: true }).click();
+ await approve(page);
+ await expect.poll(async () => (await rows())[0]?.message_id ?? null).not.toBeNull();
+ const late = await page.request.delete(`/api/openapi/agent/attachments/${id}`);
+ expect(late.status()).toBe(409);
+ expect(await rows()).toHaveLength(1);
+ } finally {
+ await other.close();
+ await deleteE2EUser(stranger);
+ await pool.end();
+ }
+});