From d5f0a4466c5bb7be027c265a41eba581c3ea6868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Thu, 13 Aug 2026 12:44:08 +0100 Subject: [PATCH] fix(web): render queued attachment previews (#2622) --- .../internal/backendapp/orchestrator.go | 3 + .../task/service/attachment_service.go | 28 +++- .../attachment_service_lifecycle_test.go | 34 +++++ .../task/chat/queued-attachment-row.tsx | 73 +++++++++++ .../task/chat/queued-ghost-message.test.tsx | 53 ++++++++ .../task/chat/queued-ghost-message.tsx | 49 +------ apps/web/lib/state/slices/session/types.ts | 4 +- .../queued-message-attachment-preview/plan.md | 124 ++++++++++++++++++ .../task-01-queue-attachment-rendering.md | 80 +++++++++++ docs/specs/tasks/prompt-attachments.md | 9 ++ 10 files changed, 408 insertions(+), 49 deletions(-) create mode 100644 apps/web/components/task/chat/queued-attachment-row.tsx create mode 100644 docs/plans/queued-message-attachment-preview/plan.md create mode 100644 docs/plans/queued-message-attachment-preview/task-01-queue-attachment-rendering.md diff --git a/apps/backend/internal/backendapp/orchestrator.go b/apps/backend/internal/backendapp/orchestrator.go index 954f182482..7323217842 100644 --- a/apps/backend/internal/backendapp/orchestrator.go +++ b/apps/backend/internal/backendapp/orchestrator.go @@ -117,6 +117,9 @@ func provideOrchestrator( } taskSvc.SetAttachmentService(attachmentSvc) } + if attachmentSvc := taskSvc.AttachmentService(); attachmentSvc != nil { + attachmentSvc.SetTaskAuthorizer(taskSvc.AuthorizeTaskAccess) + } orchestratorSvc := orchestrator.NewService(serviceCfg, eventBus, agentManagerClient, taskRepoAdapter, taskRepo, userSvc, secretStore, msgQueue, log) if gitCredentialBroker != nil { diff --git a/apps/backend/internal/task/service/attachment_service.go b/apps/backend/internal/task/service/attachment_service.go index 428f97a5b3..29523b9d35 100644 --- a/apps/backend/internal/task/service/attachment_service.go +++ b/apps/backend/internal/task/service/attachment_service.go @@ -58,6 +58,7 @@ type AttachmentService struct { repo repository.AttachmentRepository root string authorizeWorkspace func(context.Context, string) error + authorizeTask func(context.Context, string) error log *logger.Logger } @@ -78,6 +79,13 @@ func (s *AttachmentService) ensureRoot() error { return os.MkdirAll(s.root, 0o700) } +// SetTaskAuthorizer wires the per-user task visibility check used to serve +// claimed attachments to transcript readers. Staged attachments remain +// owner-only; claimed attachments are authorized through their owning task. +func (s *AttachmentService) SetTaskAuthorizer(authorizer func(context.Context, string) error) { + s.authorizeTask = authorizer +} + // Stage writes one raw file to a temporary file, validates its exact byte // count, atomically renames it, then commits the descriptor row. Any failure // removes both the temporary and committed file so callers never observe a @@ -187,10 +195,28 @@ func (s *AttachmentService) Get(ctx context.Context, ownerID, id string) (*model } func (s *AttachmentService) Open(ctx context.Context, ownerID, id string) (*models.TaskMessageAttachment, *os.File, error) { - attachment, err := s.Get(ctx, ownerID, id) + attachment, err := s.repo.GetMessageAttachment(ctx, id) if err != nil { return nil, nil, err } + if attachment == nil { + return nil, nil, ErrAttachmentForbidden + } + switch attachment.State { + case models.AttachmentStateStaged: + if attachment.OwnerID != ownerID { + return nil, nil, ErrAttachmentForbidden + } + case models.AttachmentStateClaimed: + if attachment.TaskID == "" || s.authorizeTask == nil { + return nil, nil, ErrAttachmentForbidden + } + if err := s.authorizeTask(ctx, attachment.TaskID); err != nil { + return nil, nil, ErrAttachmentForbidden + } + default: + return nil, nil, ErrAttachmentForbidden + } if filepath.Base(attachment.StorageKey) != attachment.StorageKey || attachment.StorageKey == "" { return nil, nil, ErrAttachmentInvalid } diff --git a/apps/backend/internal/task/service/attachment_service_lifecycle_test.go b/apps/backend/internal/task/service/attachment_service_lifecycle_test.go index 8d85085bf5..47e0e35074 100644 --- a/apps/backend/internal/task/service/attachment_service_lifecycle_test.go +++ b/apps/backend/internal/task/service/attachment_service_lifecycle_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/kandev/kandev/internal/auth/authn" "github.com/kandev/kandev/internal/task/models" "github.com/kandev/kandev/internal/task/repository" sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite" @@ -398,6 +399,39 @@ func TestAttachmentOpenClaimedAuthorizesByBinding(t *testing.T) { } } +func TestAttachmentOpenClaimedAllowsAuthorizedTaskReader(t *testing.T) { + svc, _, _, _ := newAttachmentTestService(t) + ctx := context.Background() + attachment := stageTestAttachment(t, svc, "user-a", "shared.png", "payload") + if err := svc.Claim(ctx, "user-a", "ws-att", "task-1", "sess-1", []string{attachment.ID}); err != nil { + t.Fatalf("Claim: %v", err) + } + + svc.SetTaskAuthorizer(func(ctx context.Context, taskID string) error { + identity, ok := authn.IdentityFromContext(ctx) + if !ok || identity.UserID != "user-b" || taskID != "task-1" { + return ErrAttachmentForbidden + } + return nil + }) + _, reader, err := svc.Open(ctxAs("user-b"), "user-b", attachment.ID) + if err != nil { + t.Fatalf("authorized transcript reader Open: %v", err) + } + defer func() { _ = reader.Close() }() + content, err := io.ReadAll(reader) + if err != nil { + t.Fatalf("read claimed attachment: %v", err) + } + if string(content) != "payload" { + t.Fatalf("content = %q, want payload", content) + } + + if _, _, err := svc.Open(ctxAs("user-c"), "user-c", attachment.ID); !errors.Is(err, ErrAttachmentForbidden) { + t.Fatalf("unauthorized transcript reader Open = %v, want ErrAttachmentForbidden", err) + } +} + func TestAttachmentDeleteOnlyRemovesStagedRows(t *testing.T) { svc, repo, root, _ := newAttachmentTestService(t) ctx := context.Background() diff --git a/apps/web/components/task/chat/queued-attachment-row.tsx b/apps/web/components/task/chat/queued-attachment-row.tsx new file mode 100644 index 0000000000..48b21fa47d --- /dev/null +++ b/apps/web/components/task/chat/queued-attachment-row.tsx @@ -0,0 +1,73 @@ +"use client"; + +import { IconFile } from "@tabler/icons-react"; +import { useTranslation } from "react-i18next"; +import { cn } from "@/lib/utils"; +import { attachmentContentUrl } from "@/lib/api/domains/attachment-api"; +import { ImagePreviewDialog } from "@/components/task/chat/image-preview-dialog"; +import type { QueuedMessage } from "@/lib/state/slices/session/types"; + +export type QueuedAttachment = NonNullable[number]; + +type AttachmentRowProps = { + attachments: QueuedAttachment[]; + interactive: boolean; +}; + +function queuedAttachmentSource(attachment: QueuedAttachment): string | null { + if (attachment.attachment_id) return attachmentContentUrl(attachment.attachment_id); + if (attachment.data) return `data:${attachment.mime_type};base64,${attachment.data}`; + return null; +} + +/** + * Renders queued-message attachments as compact thumbnails (images) and chips + * (other resources). Used in both display and edit views; `interactive=false` + * disables the click-to-open behavior so it stays a passive context cue while + * editing the message text. + */ +export function AttachmentRow({ attachments, interactive }: AttachmentRowProps) { + const { t } = useTranslation(); + if (attachments.length === 0) return null; + const images = attachments.filter((a) => a.type === "image"); + const files = attachments.filter((a) => a.type !== "image"); + return ( +
+ {images.map((att, i) => { + const src = queuedAttachmentSource(att); + if (!src) { + return ( + + + {att.name || t("task:attachment")} + + ); + } + return ( + + ); + })} + {files.map((att, i) => ( + + + {att.name || t("task:attachment")} + + ))} +
+ ); +} diff --git a/apps/web/components/task/chat/queued-ghost-message.test.tsx b/apps/web/components/task/chat/queued-ghost-message.test.tsx index 6b96e02076..7fbde6a217 100644 --- a/apps/web/components/task/chat/queued-ghost-message.test.tsx +++ b/apps/web/components/task/chat/queued-ghost-message.test.tsx @@ -218,7 +218,60 @@ describe("QueuedGhostMessage attachment thumbnails", () => { expect(img.src).toBe(`data:image/png;base64,${PNG_BASE64}`); expect(trigger.className).toContain("cursor-pointer"); }); +}); +describe("QueuedGhostMessage queued attachment sources", () => { + it("renders staged image descriptors through the authenticated content URL", () => { + render( + {}} + onRemove={() => {}} + />, + ); + + fireEvent.click(screen.getByRole("button", { name: OPEN_ATTACHMENT_1_LABEL })); + + expect(screen.getByAltText(FULL_SIZE_ATTACHMENT_1_ALT).getAttribute("src")).toContain( + "/api/v1/attachments/attachment-staged-1/content", + ); + }); + + it("does not render a broken image when an image has no source", () => { + render( + {}} + onRemove={() => {}} + />, + ); + + expect(screen.queryByRole("button", { name: OPEN_ATTACHMENT_1_LABEL })).toBeNull(); + expect(screen.getByText("missing.png")).toBeTruthy(); + }); +}); + +describe("QueuedGhostMessage attachment thumbnails", () => { it("renders a file chip for non-image (resource) attachments", () => { render( [number]; - -type AttachmentRowProps = { - attachments: QueuedAttachment[]; - interactive: boolean; -}; - -/** - * Renders queued-message attachments as compact thumbnails (images) and chips - * (other resources). Used in both display and edit views; `interactive=false` - * disables the click-to-open behavior so it stays a passive context cue while - * editing the message text. - */ -function AttachmentRow({ attachments, interactive }: AttachmentRowProps) { - const { t } = useTranslation(); - if (attachments.length === 0) return null; - const images = attachments.filter((a) => a.type === "image"); - const files = attachments.filter((a) => a.type !== "image"); - return ( -
- {images.map((att, i) => ( - - ))} - {files.map((_, i) => ( - - - {t("task:attachment")} - - ))} -
- ); -} - /** Imperative handle for the ghost row, used by chat input "edit last queued" affordance. */ export type QueuedGhostMessageHandle = { startEdit: () => void; diff --git a/apps/web/lib/state/slices/session/types.ts b/apps/web/lib/state/slices/session/types.ts index aa48fd4076..d62e8d955e 100644 --- a/apps/web/lib/state/slices/session/types.ts +++ b/apps/web/lib/state/slices/session/types.ts @@ -123,9 +123,11 @@ export type QueuedMessage = { plan_mode: boolean; attachments?: Array<{ type: string; - data: string; + data?: string; + attachment_id?: string; mime_type: string; name?: string; + size_bytes?: number; delivery_mode?: "prompt" | "path"; }>; metadata?: QueuedMessageMetadata; diff --git a/docs/plans/queued-message-attachment-preview/plan.md b/docs/plans/queued-message-attachment-preview/plan.md new file mode 100644 index 0000000000..4f31162bf2 --- /dev/null +++ b/docs/plans/queued-message-attachment-preview/plan.md @@ -0,0 +1,124 @@ +--- +spec: docs/specs/tasks/prompt-attachments.md +created: 2026-08-13 +status: completed +--- + +# Implementation Plan: Queued message attachment previews + +## Overview + +Repair the queue panel's image preview contract after file-backed prompt +attachments were introduced. The frontend queue DTO and renderer will accept +both descriptor-backed attachments and legacy inline data, using the same +authorized content URL fallback already used by persisted chat messages. The +content endpoint must also authorize claimed attachments through the owning task +so transcript readers can load queued previews after claim. + +Confirmed root cause: `use-chat-input-state.ts` submits ready uploads as +`attachment_id`, while `QueuedMessage` still requires `data` and the queue row +always constructs a base64 data URL from it. The existing queue tests only +exercise inline data fixtures. The existing content handler also checks only +the staging owner, so claimed previews need the owning-task access callback. + +--- + +## Frontend + +### Queue attachment contract + +- Extend `apps/web/lib/state/slices/session/types.ts` so queued attachment + descriptors allow optional `data` and `attachment_id`, matching the queue + API and backend `MessageAttachment` JSON shape. +- Update `apps/web/components/task/chat/queued-attachment-row.tsx` to resolve + `attachment_id` with `attachmentContentUrl()` before falling back to an + inline MIME-qualified data URL. Do not render an invalid image URL when both + sources are absent. +- Update `apps/web/components/task/chat/queued-ghost-message.tsx` to consume + the shared queued attachment row renderer. +- Preserve the existing compact 40x40 thumbnail and dialog/edit interaction; + thumbnail geometry and crop policy are out of scope. + +### Mobile parity + +- **Outcome and entry:** desktop and phone queue panels show the same image + preview content for a queued attachment; the existing queue chip/panel entry + remains unchanged. +- **Nearest exemplar:** reuse the persisted chat message resolver in + `apps/web/components/task/chat/messages/chat-message.tsx`; the existing + `mobile-message-queue-management.spec.ts` remains the closest mobile queue + surface. +- **Hierarchy and action:** no action or navigation changes. The existing + thumbnail remains the preview trigger on both pointer types. +- **Presentation and scroll:** no new overlay or layout is introduced; the + current queue panel remains the scroll owner and the 40x40 thumbnail remains + within the row. +- **Shared logic:** descriptor resolution and inline fallback are shared by + the queue display and edit preview through the existing component path. + +### Claimed attachment authorization + +- Keep staged attachment reads owner-only. +- Authorize claimed attachment reads through the owning task's + `AuthorizeTaskAccess` callback, preserving the existing 404 response for + unauthorized or unknown attachments. +- Cover an authorized second-user transcript reader and an unauthorized reader + in the attachment service regression tests. + +--- + +## Tests + +- **What:** a queued image with `attachment_id` and no inline data uses the + authorized content URL, and a legacy inline image still uses its data URL. + **File:** `apps/web/components/task/chat/queued-ghost-message.test.tsx`. + **How:** focused React Testing Library regression tests using the existing + queue fixture and preview dialog behavior. +- **What:** an attachment with neither source does not create a broken image + element. **File:** the same test file. **How:** focused rendered fallback + assertion if the implementation exposes this defensive case. +- **What:** a claimed attachment can be opened by an authorized task reader, + but not by an unrelated user. **File:** + `apps/backend/internal/task/service/attachment_service_lifecycle_test.go`. + **How:** claim a staged attachment, authorize a second user through the task + callback, and verify both content and denial behavior. + +## E2E Tests + +No new permanent Playwright test is planned. This repair only normalizes the +image source inside the already-shipped queue row and does not change mobile +composition, touch targets, scrolling, or navigation. A disposable managed +capture covered the affected desktop and mobile views for the PR; it was removed +after capture. The deterministic staged-descriptor regression belongs in the +component test, and the existing desktop and mobile queue-management scenarios +continue to cover row mounting and interaction. + +--- + +## Verification Results + +- `rtk pnpm --filter @kandev/web test -- --run + components/task/chat/queued-ghost-message.test.tsx` from `apps`: passed, + 44 tests. +- `rtk pnpm run typecheck` from `apps/web`: passed. +- `rtk git diff --check`: passed. +- `rtk go test -v ./internal/task/service -run + 'TestAttachment(OpenClaimedAllowsAuthorizedTaskReader|OpenClaimedAuthorizesByBinding|OpenReturnsBytesAndScopes)' -count=1`: + passed, 3 tests. +- Changed-file web ESLint and backendapp wiring test passed during PR fixup. +- No new mobile Playwright test was added because the repair does not change + composition, touch targets, scrolling, navigation, or viewport behavior. + +--- + +## Implementation Waves And Parallel Candidates + +Wave 1: + +- [x] [task-01-queue-attachment-rendering](task-01-queue-attachment-rendering.md) — completed; sequential + +Execution remains sequential in the primary conversation. + +## Open Questions + +None. diff --git a/docs/plans/queued-message-attachment-preview/task-01-queue-attachment-rendering.md b/docs/plans/queued-message-attachment-preview/task-01-queue-attachment-rendering.md new file mode 100644 index 0000000000..d1950ad96e --- /dev/null +++ b/docs/plans/queued-message-attachment-preview/task-01-queue-attachment-rendering.md @@ -0,0 +1,80 @@ +--- +id: "01-queue-attachment-rendering" +title: "Render queued attachment IDs" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +spec: "../../specs/tasks/prompt-attachments.md" +--- + +# Task 01: Render queued attachment IDs + +## Acceptance + +1. A queued image descriptor with `attachment_id` and no inline `data` renders + from `/api/v1/attachments//content` in both thumbnail and full-size + preview contexts for callers authorized to read the owning task. +2. Legacy inline image descriptors continue to render from their MIME-qualified + data URL, and missing image sources do not produce a broken `` URL. +3. Existing queue thumbnail dimensions, dialog behavior, edit-mode read-only + behavior, and desktop/mobile row interaction remain unchanged. + +## Verification + +```bash +cd apps && pnpm --filter @kandev/web test -- --run components/task/chat/queued-ghost-message.test.tsx +cd apps/web && pnpm run typecheck +``` + +## Files likely touched + +- `apps/web/lib/state/slices/session/types.ts` +- `apps/web/components/task/chat/queued-attachment-row.tsx` +- `apps/web/components/task/chat/queued-ghost-message.tsx` +- `apps/web/components/task/chat/queued-ghost-message.test.tsx` +- `apps/backend/internal/task/service/attachment_service.go` +- `apps/backend/internal/task/service/attachment_service_lifecycle_test.go` +- `apps/backend/internal/backendapp/orchestrator.go` + +## Dependencies + +None. + +## Parallelism + +Sequential. The type, renderer, and regression test form one shared frontend +contract. + +## Inputs + +- `docs/specs/tasks/prompt-attachments.md`, queued preview scenario +- `docs/plans/queued-message-attachment-preview/plan.md` +- Existing source resolution in + `apps/web/components/task/chat/messages/chat-message.tsx` + +## Output contract + +Report the final source-resolution behavior, files changed, exact test and +typecheck results, any mobile verification limitation, and synchronized task +and plan status. + +## Results + +- RED: `rtk pnpm exec vitest run components/task/chat/queued-ghost-message.test.tsx` + from `apps/web` failed as expected with 2 failures: staged descriptors became + `data:image/png;base64,undefined`, and source-less images rendered a preview + trigger. +- GREEN: `rtk pnpm --filter @kandev/web test -- --run + components/task/chat/queued-ghost-message.test.tsx` from `apps` passed with + 44 tests. +- Typecheck: `rtk pnpm run typecheck` from `apps/web` passed. +- Backend authorization regression: `rtk go test -v ./internal/task/service -run + 'TestAttachment(OpenClaimedAllowsAuthorizedTaskReader|OpenClaimedAuthorizesByBinding|OpenReturnsBytesAndScopes)' -count=1` + passed, 3 tests. +- Formatting: `rtk git diff --check` passed. +- Mobile verification: no new Playwright test was needed because the repair + only changes attachment source resolution inside the existing row; the + existing `mobile-message-queue-management.spec.ts` remains the relevant + mobile surface. +- Cleanup: no temporary diagnostic or capture artifacts were created. diff --git a/docs/specs/tasks/prompt-attachments.md b/docs/specs/tasks/prompt-attachments.md index acc3d26f2e..ffc9b54005 100644 --- a/docs/specs/tasks/prompt-attachments.md +++ b/docs/specs/tasks/prompt-attachments.md @@ -37,6 +37,10 @@ move files into a workspace manually or strip useful evidence. - Submitted user messages and queue entries retain attachment name, MIME type, raw size, kind, and delivery mode for transcript display and later authorized download. They do not retain base64 data or expose host filesystem paths. +- Queued image previews resolve file-backed attachment IDs through the + authorized content endpoint and retain the legacy inline-data fallback. The + queue UI does not construct an image data URL when an attachment has no + inline bytes. - Path-delivered files are materialized in the active execution beneath the session's `.kandev/attachments//` directory before the agent is prompted. Existing native-prompt and path delivery choices remain available. @@ -167,6 +171,10 @@ request paths never determine ownership. - **GIVEN** a message with a ready attachment is queued while an agent is busy, **WHEN** the queue entry drains, **THEN** the same file is attached to the persisted message and delivered once without re-upload. +- **GIVEN** a queued image has an `attachment_id` and no inline `data`, **WHEN** + the queue panel renders it, **THEN** the thumbnail and full-size preview load + from the authorized attachment content endpoint; a legacy inline image still + loads from its MIME-qualified data URL. - **GIVEN** a phone viewport, **WHEN** an upload fails or exceeds the limit, **THEN** the existing composer shows reachable retry/remove actions and a contained localized error with the 100 MiB limit. @@ -178,3 +186,4 @@ request paths never determine ownership. - Per-user or per-workspace configurable attachment limits. - External object storage or direct browser-to-executor uploads. - Changing the separate 10 MiB task-document attachment contract. +- Changing the queue's existing compact thumbnail dimensions or crop policy.