From 4814d1ab691c176170510a93a175dafdc9e021c7 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Mon, 2 Nov 2026 17:35:32 -0600
Subject: [PATCH] fix(ui): show composer images as rounded thumbnails (#18689)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - People use the new-task and thread composers to send text and files.
> - Images currently enter the text editor or appear with other files.
> - Large images interrupt text entry and make the two composers
inconsistent.
> - This pull request puts image previews above the text in both
composers.
> - People can check and remove images while they continue to edit the
text.
## Linked Issues or Issue Description
Refs: #13206. Related shared-composer work: #15091.
**What existing behavior does this improve?**
Image selection, paste, and drop in the new-task and thread composers.
**Current behavior**
Thread images enter the editor at the text cursor. New-task images can
appear inline or with file attachments. Images do not have one preview
size.
**Proposed behavior**
Show images above the text as 80 by 80 previews with rounded corners.
Use the existing spacing and radius tokens. Keep file attachments in
their current row. Add image references when the thread message is sent.
**Reason and benefit**
People can review images without moving or deleting message text. One
shared image row keeps both composers consistent.
**Breaking changes**
New image uploads stay outside the editor until send. Old inline-image
drafts remain readable. No server API or database changes are required.
## What Changed
- Add `ComposerImageAttachments` for local previews, removal, upload
status, and retry.
- Let `TaskChatComposer` own the image row and all image input paths.
Keep attachment IDs in the existing send flow.
- Let `NewIssueDialog` stage images and upload retained files after task
creation. Save file bytes in browser IndexedDB by account and company.
Restore them after reload. Clear them after creation. Show storage
errors. Merge saved file changes in one IndexedDB transaction. Delete
only the files removed by that draft. This keeps files saved by other
open tabs.
- Keep rich editing for old image Markdown. Use the same MIME and
filename checks for image previews in both composers.
- Save optional MIME data with thread draft attachments. Existing draft
records remain valid.
- Add desktop and mobile Storybook examples. Update the task feature map
and component tests.
## Verification
- `pnpm exec playwright test --config tests/e2e/playwright.config.ts
tests/e2e/board-attachment-receipts.spec.ts`: all 14 Chromium tests pass
against the real local Board, API, storage, and disposable database. The
suite proves image recovery in two open tabs after saves and task
creation, new-task image recovery after reload, byte-for-byte upload
content, cleanup after creation, rich editing of old image drafts,
upload receipt recovery, and removal during pending uploads.
- The first local browser attempt could not start because Chromium was
absent. Chromium was installed. A later run passed 12 tests but the new
legacy-draft fixture restored an empty body. That fixture wrote storage
while an empty composer was mounted. It now seeds before React startup
and uses a real uploaded image. The complete 13-test rerun passes. Early
component runs also exposed the new restore timing. Submit and file
controls now wait for restoration. The test helper now waits for React
effects.
- 316 focused tests pass across `TaskChatComposer`, `NewIssueDialog`,
`MarkdownEditor`, `composer-draft`, and `useStagedIssueFiles`. The tests
cover explicit file removal, file recovery, account and company changes,
storage failures, MIME-empty images, upload retries, and removal.
- The two-tab browser test failed on the previous commit: the second
save erased the first image. The fix merges files in one read/write
transaction and records explicit removals. The first fixed run reached
the final create step but had no text request after the other tab
cleared the shared text draft. The test now enters a fresh request
before that step. The full 14-test rerun passes.
- `pnpm check:token-gates`, `node scripts/check-maps.mjs`, `node
scripts/storybook-catalog.mjs`, and `git diff --check` pass.
- `pnpm --filter @paperclipai/ui typecheck` and `pnpm --filter
@paperclipai/ui build` pass after building the local plugin SDK
dependency. Repository typecheck and build stop because this workspace
has no `cargo`. Full CI must pass before merge. The first CI run passed
typecheck, build, and all unit-test shards. Its browser failure expected
the old inline upload label. The assertion now uses the thumbnail upload
status.
- The prior browser review used the production components with simulated
upload and submit calls. Desktop, mobile, and dark-theme captures were
accepted before this PR. Browser checks confirmed equal-size rounded
previews above the editor, no inline image nodes, no horizontal
overflow, and removal that preserves text. These checks do not prove
live backend persistence.
- Earlier repository typecheck and build attempts also stopped without
`cargo`. An earlier full test run was killed with a recorded
out-of-memory event during a server integration shard. It had no
full-suite verdict. One document-recovery test timed out during that
concurrent run. Its isolated rerun and later complete focused runs
passed; the initial timeout cause was not established.
- An initial catalog command in this workspace ran before dependency
installation finished. It could not load Storybook. The command passed
after installation. The first UI typecheck could not find plugin SDK
declarations while that package was still building. The UI typecheck
passed after `pnpm --filter @paperclipai/plugin-sdk build`.
To inspect the layout, open `composer-new-task--images`,
`composer-new-task--mobile-images`, `composer-add-menu--images`, and
`composer-add-menu--mobile-images` in Storybook. Select images with
different aspect ratios. Check removal, mixed files, failed upload and
retry, and draft restoration.
- Greptile reports 5/5 for commit
`9b9e93beeed80371f667ad2e1a9573e82332c05c`. There are no open review
threads.
[CI](https://github.com/paperclipai/paperclip/actions/runs/41544180330)
passed on this commit. All 58 checks finished: 54 passed, one review is
neutral, and three optional checks were skipped. The legacy Snyk status
passed. Paperclip also reports 5/5. No review threads are open.
## Risks
- Open tabs share the account and company draft. Atomic file writes keep
changes from other tabs. A reload can restore those saved files.
- Attachment state now controls when image references enter a thread
message. Tests cover pending uploads, failures, retry, removed images,
and retained upload IDs.
- New-task images use the existing staged-file upload flow after task
creation. A failed upload follows that flow's existing error behavior.
Browser storage can be unavailable or full. The composer keeps the files
in memory and shows a recovery message.
- Legacy inline-image drafts retain their original text. No migration is
required.
## Model Used
OpenAI GPT-6 through Codex, with reasoning, tool use, and shell
execution. The exact runtime snapshot ID and context-window size are not
exposed in this session. The earlier implementation's model snapshot is
not recorded in the handoff.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details available in this session)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub references)
- [x] My remote branch name describes the change and contains no
internal Paperclip ticket ID
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip
---
doc/DEVELOPING.md | 5 +
maps/feature-map/tasks.md | 8 +
tests/e2e/board-attachment-receipts.spec.ts | 104 +++++++++-
ui/src/components/MarkdownEditor.tsx | 8 +-
ui/src/components/NewIssueDialog.test.tsx | 62 +++++-
ui/src/components/NewIssueDialog.tsx | 39 ++--
.../task-chat/ComposerImageAttachments.tsx | 93 +++++++++
.../task-chat/TaskChatComposer.test.tsx | 180 +++++++++---------
.../components/task-chat/TaskChatComposer.tsx | 111 +++++------
ui/src/hooks/useStagedIssueFiles.test.tsx | 79 ++++++++
ui/src/hooks/useStagedIssueFiles.ts | 60 ++++++
ui/src/lib/composer-draft.ts | 2 +
ui/src/lib/staged-issue-files.ts | 55 ++++++
.../tasks/composer-add-menu.stories.tsx | 35 +++-
.../tasks/new-task-composer.stories.tsx | 33 ++--
ui/storybook/support/composerImageFiles.ts | 11 ++
16 files changed, 688 insertions(+), 197 deletions(-)
create mode 100644 ui/src/components/task-chat/ComposerImageAttachments.tsx
create mode 100644 ui/src/hooks/useStagedIssueFiles.test.tsx
create mode 100644 ui/src/hooks/useStagedIssueFiles.ts
create mode 100644 ui/src/lib/staged-issue-files.ts
create mode 100644 ui/storybook/support/composerImageFiles.ts
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index 106e8412cf1..96426bf35b9 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -4024,6 +4024,11 @@ under its original key; it is never relabelled as a provider refusal. Legacy
unowned form drafts remain in browser storage but are not restored into another
account. Storybook fixtures seed the same account-specific keys.
+New-task staged file bytes are stored in IndexedDB for the account and company.
+Writes merge the selected files with the current saved list in one read/write
+transaction. Removal and successful creation delete only the files that the
+mounted draft removed. Other open tabs keep their saved files across reloads.
+
Successful pending-record writes have the same readable size range as browser
storage. In particular, a large task description cannot silently drop its
creation key on reload. Reselected text documents recover their original
diff --git a/maps/feature-map/tasks.md b/maps/feature-map/tasks.md
index 66fa4b4b99a..fa735bb3d07 100644
--- a/maps/feature-map/tasks.md
+++ b/maps/feature-map/tasks.md
@@ -53,6 +53,14 @@ the personal workspace preference. Verify explicit history expansion afterward.
### `new-task`
Use New task from the global launcher, task list, or project task view.
+Images selected, pasted, or dropped into either the new-task or thread composer
+appear as equal-size rounded thumbnails above the text. Check mixed image/file
+selections, removal, thread upload failure/retry, and restored thread drafts.
+New-task files persist in account- and company-scoped browser storage across
+reloads and are cleared after creation. Verify that restored image bytes reach
+the task and that older inline-image drafts keep the rich editor.
+The Storybook new-task and add-menu suites have desktop and mobile image examples;
+their upload and submit boundaries are fixtures.
### `task-list`
diff --git a/tests/e2e/board-attachment-receipts.spec.ts b/tests/e2e/board-attachment-receipts.spec.ts
index a26baf2acf6..c408aeb60b4 100644
--- a/tests/e2e/board-attachment-receipts.spec.ts
+++ b/tests/e2e/board-attachment-receipts.spec.ts
@@ -125,6 +125,108 @@ async function openAttachmentChooser(page: Page, composer: Locator) {
return chooser;
}
+test("new-task images survive reload, retain bytes, and clear after creation", async ({ page, request }) => {
+ const fixture = await setup(page, request, false);
+ await page.getByRole("button", { name: "New Task", exact: true }).first().click();
+ const dialog = page.getByRole("dialog", { name: "New task", exact: true });
+ const editor = dialog.getByRole("textbox", { name: "editable markdown", exact: true });
+ await editor.fill("Keep the caption and image after reload.");
+ const chooser = await openAttachmentChooser(page, dialog);
+ await chooser.setFiles(files[1]!);
+ await expect(dialog.getByRole("img", { name: "board-fresh.png", exact: true })).toBeVisible();
+ await expect.poll(() => page.evaluate(async () => {
+ const db = await new Promise((resolve, reject) => {
+ const request = indexedDB.open("paperclip:issue-draft-files", 1);
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ try {
+ return await new Promise((resolve, reject) => {
+ const tx = db.transaction("files", "readonly");
+ const request = tx.objectStore("files").getAll();
+ tx.oncomplete = () => resolve(request.result.flat().length);
+ tx.onerror = () => reject(tx.error);
+ });
+ } finally { db.close(); }
+ })).toBe(1);
+ await expect.poll(() => page.evaluate(() => Object.entries(localStorage)
+ .some(([key, value]) => key.startsWith("paperclip:issue-draft:") && value.includes("Keep the caption")))).toBe(true);
+ await page.reload();
+ await page.getByRole("button", { name: "New Task", exact: true }).first().click();
+ await expect(editor).toContainText("Keep the caption and image after reload.");
+ await expect(dialog.getByRole("img", { name: "board-fresh.png", exact: true })).toBeVisible();
+ const upload = page.waitForResponse((response) => response.request().method() === "POST"
+ && /\/issues\/[^/]+\/attachments$/.test(new URL(response.url()).pathname));
+ await dialog.getByRole("button", { name: "Create task", exact: true }).click();
+ const attachment = await body(await upload);
+ const content = await request.get(attachment.contentPath);
+ expect(content.ok()).toBe(true);
+ expect(await content.body()).toEqual(files[1]!.buffer);
+ await expect(dialog).toBeHidden();
+ await page.reload();
+ await page.getByRole("button", { name: "New Task", exact: true }).first().click();
+ await expect(dialog.getByRole("img")).toHaveCount(0);
+});
+
+test("an older image draft retains the rich editor", async ({ page, request }) => {
+ const fixture = await setup(page, request, false);
+ const attachment = await body(await request.post(`/api/companies/${fixture.company.id}/issues/${fixture.issue.id}/attachments`, {
+ multipart: { file: { name: files[1]!.name, mimeType: files[1]!.mimeType, buffer: files[1]!.buffer } },
+ }));
+ await page.addInitScript(({ issueId, imagePath }) => {
+ localStorage.setItem(`paperclip:issue-comment-draft:${issueId}`, `Keep this older caption.\n\n`);
+ }, { issueId: fixture.issue.id, imagePath: attachment.contentPath });
+ await page.reload();
+ await expect(fixture.editor).toBeVisible();
+ await expect(fixture.editor).toContainText("Keep this older caption.");
+ await expect(fixture.composer.getByRole("img", { name: "Older image", exact: true })).toBeVisible();
+ await expect(fixture.composer.locator("textarea")).toHaveCount(0);
+});
+
+test("two open tabs retain their staged images when either tab saves or creates a task", async ({ page, request, context }) => {
+ await setup(page, request, false);
+ const second = await context.newPage();
+ await second.goto(page.url());
+ const dialogs = [page, second].map((tab) => tab.getByRole("dialog", { name: "New task", exact: true }));
+ for (const [index, tab] of [page, second].entries()) {
+ await tab.getByRole("button", { name: "New Task", exact: true }).first().click();
+ await dialogs[index]!.getByRole("textbox", { name: "editable markdown", exact: true }).fill(`Keep tab ${index + 1}'s image.`);
+ await expect(dialogs[index]!.getByRole("button", { name: "Create task", exact: true })).toBeEnabled();
+ }
+ const savedNames = () => page.evaluate(async () => {
+ const db = await new Promise((resolve, reject) => {
+ const request = indexedDB.open("paperclip:issue-draft-files", 1);
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ try {
+ return await new Promise((resolve, reject) => {
+ const tx = db.transaction("files", "readonly");
+ const request = tx.objectStore("files").getAll();
+ tx.oncomplete = () => resolve(request.result.flat().map((item: { file: File }) => item.file.name).sort());
+ tx.onerror = () => reject(tx.error);
+ });
+ } finally { db.close(); }
+ });
+ for (const [index, tab] of [page, second].entries()) {
+ const chooser = await openAttachmentChooser(tab, dialogs[index]!);
+ await chooser.setFiles({ ...files[1]!, name: `tab-${index + 1}.png` });
+ await expect(dialogs[index]!.getByRole("img", { name: `tab-${index + 1}.png`, exact: true })).toBeVisible();
+ await expect.poll(savedNames).toEqual(index === 0 ? ["tab-1.png"] : ["tab-1.png", "tab-2.png"]);
+ }
+ await dialogs[0]!.getByRole("button", { name: "Create task", exact: true }).click();
+ await expect(dialogs[0]!).toBeHidden();
+ await expect.poll(savedNames).toEqual(["tab-2.png"]);
+ await second.reload();
+ await second.getByRole("button", { name: "New Task", exact: true }).first().click();
+ await expect(dialogs[1]!.getByRole("img", { name: "tab-2.png", exact: true })).toBeVisible();
+ await dialogs[1]!.getByRole("textbox", { name: "editable markdown", exact: true }).fill("Create the remaining tab's image.");
+ await dialogs[1]!.getByRole("button", { name: "Create task", exact: true }).click();
+ await expect(dialogs[1]!).toBeHidden();
+ await expect.poll(savedNames).toEqual([]);
+ await second.close();
+});
+
async function upload(
page: Page,
fixture: Awaited>,
@@ -410,7 +512,7 @@ for (const classic of [false, true])
try {
await expect(
fixture.composer.getByText(
- classic ? "Uploading to task" : "Uploading…",
+ classic ? "Uploading to task" : "Uploading board-fresh.png…",
{ exact: true },
),
).toBeVisible();
diff --git a/ui/src/components/MarkdownEditor.tsx b/ui/src/components/MarkdownEditor.tsx
index 39a0f3d9f6b..2d1521a3864 100644
--- a/ui/src/components/MarkdownEditor.tsx
+++ b/ui/src/components/MarkdownEditor.tsx
@@ -945,8 +945,6 @@ export const MarkdownEditor = forwardRef
};
}, [editorValue, placeholder, richEditorError]);
- // Whether the image plugin should be included (boolean is stable across renders
- // as long as the handler presence doesn't toggle)
const hasImageUpload = Boolean(imageUploadHandler);
const plugins = useMemo(() => {
@@ -1003,11 +1001,7 @@ export const MarkdownEditor = forwardRef
codeMirrorPlugin({ codeBlockLanguages: CODE_BLOCK_LANGUAGES }),
markdownShortcutPlugin(),
];
- if (imageHandler) {
- // The inline image chip keeps only its remove affordance — no settings
- // dialog, and the X glyph instead of MDXEditor's default trash can.
- all.push(imagePlugin({ imageUploadHandler: imageHandler, disableImageSettingsButton: true }));
- }
+ all.push(imagePlugin({ imageUploadHandler: imageHandler, disableImageSettingsButton: true }));
return all;
}, [hasImageUpload]);
diff --git a/ui/src/components/NewIssueDialog.test.tsx b/ui/src/components/NewIssueDialog.test.tsx
index b04fb244969..d5f9a259b63 100644
--- a/ui/src/components/NewIssueDialog.test.tsx
+++ b/ui/src/components/NewIssueDialog.test.tsx
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import type { ComponentProps, ReactNode } from "react";
+import { act as reactAct } from "react";
import { webcrypto } from "node:crypto";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
@@ -13,6 +14,13 @@ import { rememberComposerEffort } from "../lib/recent-composer-effort";
import { addStagedFilesToIssue, NewIssueDialog } from "./NewIssueDialog";
const primaryState = vi.hoisted(() => ({ primaryAgentId: null as string | null, loading: false }));
+const storedFiles = vi.hoisted(() => new Map());
+vi.mock("../lib/staged-issue-files", () => ({
+ readStagedIssueFiles: vi.fn(async (key: string) => storedFiles.get(key) ?? []),
+ writeStagedIssueFiles: vi.fn(async (key: string, files: import("../lib/staged-issue-files").StagedIssueFile[]) => {
+ storedFiles.set(key, files);
+ }),
+}));
vi.mock("./primary-agent/PrimaryAgentPresentation", () => ({ usePrimaryAgentPresentation: () => primaryState }));
const coordinatorState = vi.hoisted(() => ({ enabled: false }));
vi.mock("../hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => coordinatorState }));
@@ -291,7 +299,7 @@ function act(callback: () => void | Promise): void | Promise {
}
async function flush() {
- await act(async () => {
+ await reactAct(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
@@ -402,6 +410,7 @@ describe("NewIssueDialog", () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });
mockMissingUserSecretsBannerRender.mockReset();
localStorage.clear();
+ storedFiles.clear();
mockIssuesApi.create.mockResolvedValue({
id: "issue-2",
companyId: "company-1",
@@ -1840,6 +1849,57 @@ describe("NewIssueDialog", () => {
} finally { storage?.mockRestore(); act(() => root.unmount()); queryClient.clear(); }
});
+ it.each(["image/png", "", "application/octet-stream"])("shows staged images above text with MIME '%s' and uploads only retained files", async (type) => {
+ dialogState.newIssueDefaults = { title: "Review image references" };
+ mockIssuesApi.create.mockResolvedValue({ id: "image-task", identifier: "PAP-1", companyId: "company-1" });
+ mockIssuesApi.uploadAttachment.mockResolvedValue({});
+ const { root, queryClient } = renderDialog(container);
+ try {
+ await flush();
+ const editor = container.querySelector('textarea[aria-label="Describe a task…"]')!;
+ await typeTextareaValue(editor, "Keep this caption");
+ const retained = new File(["image"], "reference.png", { type });
+ const removed = new File(["other"], "removed.png", { type: "image/png" });
+ const input = container.querySelector('input[type="file"]')!;
+ Object.defineProperty(input, "files", { configurable: true, value: [retained, removed] });
+ await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); });
+ await flush();
+ const row = container.querySelector('[data-testid="task-chat-composer-images"]')!;
+ expect(row.querySelectorAll("img")).toHaveLength(2);
+ expect(row.compareDocumentPosition(editor) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(editor.value).toBe("Keep this caption");
+ await act(async () => { container.querySelector('[aria-label="Remove removed.png"]')!.click(); });
+ await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); });
+ await waitForAssertion(() => expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(1));
+ expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledWith("company-1", "image-task", retained);
+ expect(mockIssuesApi.create.mock.calls[0][1].description).toBe("Keep this caption");
+ expect(mockAssetsApi.uploadImage).not.toHaveBeenCalled();
+ } finally { act(() => root.unmount()); queryClient.clear(); }
+ });
+
+ it("restores staged image bytes after remount and clears them after creation", async () => {
+ dialogState.newIssueDefaults = { title: "Retain these images" };
+ const file = new File(["image bytes"], "reference.png", { type: "image/png", lastModified: 12 });
+ const first = renderDialog(container);
+ await flush();
+ await waitForAssertion(() => expect(container.querySelector('[aria-label="Create task"]')!.disabled).toBe(false));
+ const input = container.querySelector('input[type="file"]')!;
+ Object.defineProperty(input, "files", { configurable: true, value: [file] });
+ await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); });
+ await flush();
+ expect(storedFiles.get(JSON.stringify(["user-1", "company-1"]))?.[0].file).toBe(file);
+ act(() => first.root.unmount());
+ first.queryClient.clear();
+ const second = renderDialog(container);
+ try {
+ await flush();
+ await waitForAssertion(() => expect(container.querySelector('img[alt="reference.png"]')).not.toBeNull());
+ await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); });
+ await waitForAssertion(() => expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledWith("company-1", "issue-2", file));
+ await waitForAssertion(() => expect(storedFiles.get(JSON.stringify(["user-1", "company-1"])) ?? []).toEqual([]));
+ } finally { act(() => second.root.unmount()); second.queryClient.clear(); }
+ });
+
it.each(["create", "upload"] as const)("stops old staged work after an account change during %s", async (during) => {
dialogState.newIssueDefaults = { title: "Account A in-flight task" };
let finish!: (value: unknown) => void;
diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx
index d38ff1b7f30..434c704ccd0 100644
--- a/ui/src/components/NewIssueDialog.tsx
+++ b/ui/src/components/NewIssueDialog.tsx
@@ -13,7 +13,6 @@ import { projectsApi } from "../api/projects";
import { agentsApi } from "../api/agents";
import { accessApi } from "../api/access";
import { authApi } from "../api/auth";
-import { assetsApi } from "../api/assets";
import { buildCompanyUserInlineOptions, buildMarkdownMentionOptions, isAgentTaskTarget } from "../lib/company-members";
import { queryKeys } from "../lib/queryKeys";
import { useNavigate } from "../lib/router";
@@ -51,14 +50,17 @@ import { clearPendingSend, pendingSendKeyFor, readPendingSend, writePendingSend,
import { useDraftOwner, useDraftOwnerReader } from "../hooks/useDraftOwner";
import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector";
import { getTrustPreset } from "../lib/trust-policy-ui";
+import { useStagedIssueFiles } from "../hooks/useStagedIssueFiles";
+import type { StagedIssueFile } from "../lib/staged-issue-files";
+import { isImageAttachment } from "./task-chat/task-chat-attachments";
const DRAFT_KEY = "paperclip:issue-draft";
/** A create that is waiting to resend: its request body and idempotency key. */
const PENDING_CREATE_KEY = "paperclip:issue-draft:pending-create";
/**
- * The create request. Staged files cannot be stored, so they ride in memory and
- * only their names are saved: a create restored after reload knows it needs them.
+ * The create request keeps file names for reconciliation. File bytes are stored
+ * separately in the account- and company-scoped browser draft.
*/
type PendingCreate = { fingerprint: string; data: Record; stagedFileNames?: string[] };
@@ -203,14 +205,6 @@ interface IssueDraft {
composerSettings?: ComposerRunSettings | null;
}
-type StagedIssueFile = {
- id: string;
- file: File;
- kind: "document" | "attachment";
- documentKey?: string;
- title?: string | null;
-};
-
/**
* Files a keyed create has already added to its task. A replayed create (same
* key, after a reload mid-upload) gets the existing task back from the
@@ -491,7 +485,6 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
const [isPrivate, setIsPrivate] = useState(false);
const { isMobile } = useSidebar();
const [composerSettings, setComposerSettings] = useState(null);
- const [stagedFiles, setStagedFiles] = useState([]);
const [isFileDragOver, setIsFileDragOver] = useState(false);
const draftTimer = useRef | null>(null);
const executionWorkspaceDefaultProjectId = useRef(null);
@@ -502,6 +495,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
// sent or cancelled, whatever the files and fields look like when resubmitted.
const createRequestRef = useRef<{ fingerprint: string; idempotencyKey: string; recovering?: boolean; payload?: PendingCreate } | null>(null);
const draftOwner = useDraftOwner();
+ const { files: stagedFiles, setFiles: setStagedFiles, restoring: filesRestoring, error: filesStorageError } = useStagedIssueFiles(draftOwner, effectiveCompanyId);
const [restoredLaunch, setRestoredLaunch] = useState<{ owner: string | undefined; parentId?: string; goalId?: string } | null>(null);
const savedLaunch = restoredLaunch?.owner === draftOwner ? restoredLaunch : null;
const parentId = savedLaunch ? savedLaunch.parentId : newIssueDefaults.parentId;
@@ -1063,7 +1057,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
async function handleSubmit(body: string, mode: IssueWorkMode, settings: ComposerRunSettings | null) {
const currentTitle = titleRef.current.trim();
const currentDescription = body.trim();
- if (!effectiveCompanyId || (!currentTitle && !currentDescription) || createIssue.isPending || durableCreate.pending || worktreeSelectionIncomplete || parentPrivacyUnresolved) return;
+ if (!effectiveCompanyId || filesRestoring || (!currentTitle && !currentDescription) || createIssue.isPending || durableCreate.pending || worktreeSelectionIncomplete || parentPrivacyUnresolved) return;
const inheritedOverrides = buildAssigneeAdapterOverrides({
adapterType: assigneeAdapterType,
lane: assigneeChrome ? "custom" : assigneeModelLane,
@@ -1200,7 +1194,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
}
function stageFiles(files: File[]) {
- if (files.length === 0 || createIssue.isPending || durableCreate.pending) return;
+ if (files.length === 0 || filesRestoring || createIssue.isPending || durableCreate.pending) return;
setStagedFiles((current) => {
const next = [...current];
for (const file of files) {
@@ -1329,7 +1323,8 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
[orderedProjects],
);
const stagedDocuments = stagedFiles.filter((file) => file.kind === "document");
- const stagedAttachments = stagedFiles.filter((file) => file.kind === "attachment");
+ const isStagedImage = (item: StagedIssueFile) => isImageAttachment({ name: item.file.name, url: "", contentType: item.file.type });
+ const stagedAttachments = stagedFiles.filter((file) => file.kind === "attachment" && !isStagedImage(file));
const handleProjectChange = useCallback(
(nextProjectId: string) => {
@@ -1459,6 +1454,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
onDragLeave={handleFileDragLeave}
onDrop={handleFileDrop}
>
+ {filesStorageError ?
{filesStorageError}
: null}
{
- if (!effectiveCompanyId) throw new Error("No organization selected");
- const asset = await assetsApi.uploadImage(effectiveCompanyId, file, "issues/drafts");
- return asset.contentPath;
- }}
companyId={effectiveCompanyId}
enableReassign
reassignOptions={assigneeOptions}
@@ -1512,6 +1503,8 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
submitLabel: isSubIssueMode ? "Create sub-task" : "Create task",
canSubmitWithoutBody: Boolean(title.trim()),
onSelectFiles: stageFiles,
+ images: stagedFiles.filter(isStagedImage).map(item => ({ id: item.id, name: item.file.name, file: item.file })),
+ onRemoveImage: removeStagedFile,
runSettings: composerSettings,
onRunSettingsChange: setComposerSettings,
header:
@@ -1591,7 +1584,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
: "The selected worktree is no longer available. Choose another worktree or start a new one."}