fix(web): render queued attachment previews (#2622)

This commit is contained in:
Carlos Florêncio
2026-08-13 12:44:08 +01:00
committed by GitHub
parent 9a7966a45e
commit d5f0a4466c
10 changed files with 408 additions and 49 deletions
@@ -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 {
@@ -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
}
@@ -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()
@@ -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<QueuedMessage["attachments"]>[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 (
<div className="flex flex-wrap items-center gap-1.5">
{images.map((att, i) => {
const src = queuedAttachmentSource(att);
if (!src) {
return (
<span
key={`img-${i}`}
className="inline-flex items-center gap-1.5 rounded-full bg-muted/60 px-2 py-0.5 text-xs text-muted-foreground"
>
<IconFile className="h-3 w-3" />
{att.name || t("task:attachment")}
</span>
);
}
return (
<ImagePreviewDialog
key={`img-${i}`}
src={src}
alt={t("task:attachmentIndexed", { index: i + 1 })}
interactive={interactive}
thumbnailClassName={cn(
"h-10 w-10 rounded-md border border-border object-cover",
interactive && "transition-opacity hover:opacity-90",
)}
/>
);
})}
{files.map((att, i) => (
<span
key={`file-${i}`}
className="inline-flex items-center gap-1.5 rounded-full bg-muted/60 px-2 py-0.5 text-xs text-muted-foreground"
>
<IconFile className="h-3 w-3" />
{att.name || t("task:attachment")}
</span>
))}
</div>
);
}
@@ -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(
<QueuedGhostMessage
entry={entry({
attachments: [
{
type: "image",
attachment_id: "attachment-staged-1",
mime_type: "image/png",
name: "diagram.png",
},
],
})}
canEdit
onSave={async () => {}}
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(
<QueuedGhostMessage
entry={entry({
content: "",
attachments: [
{
type: "image",
mime_type: "image/png",
name: "missing.png",
},
],
})}
canEdit
onSave={async () => {}}
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(
<QueuedGhostMessage
@@ -10,7 +10,7 @@ import {
useState,
} from "react";
import type { ReactNode } from "react";
import { IconCheck, IconFile, IconInfoCircle, IconRobot, IconUser } from "@tabler/icons-react";
import { IconCheck, IconInfoCircle, IconRobot, IconUser } from "@tabler/icons-react";
import ReactMarkdown from "react-markdown";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
@@ -22,7 +22,6 @@ import { Textarea } from "@kandev/ui/textarea";
import { cn } from "@/lib/utils";
import { QueueEntryNotFoundError } from "@/lib/api/domains/queue-api";
import { stripSystemTags } from "@/lib/utils/system-tags";
import { ImagePreviewDialog } from "@/components/task/chat/image-preview-dialog";
import {
SenderTaskBadge,
type SenderTaskInfo,
@@ -41,53 +40,9 @@ import {
} from "@/lib/entity-references/message-references";
import { buildEntityReferenceMarkdownComponents } from "@/components/task/chat/messages/entity-reference-chip";
import { QueuedGhostRowActions } from "@/components/task/chat/queued-ghost-row-actions";
import { AttachmentRow, type QueuedAttachment } from "@/components/task/chat/queued-attachment-row";
import { t } from "@/lib/i18n";
type QueuedAttachment = NonNullable<QueuedMessage["attachments"]>[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 (
<div className="flex flex-wrap items-center gap-1.5">
{images.map((att, i) => (
<ImagePreviewDialog
key={`img-${i}`}
src={`data:${att.mime_type};base64,${att.data}`}
alt={t("task:attachmentIndexed", { index: i + 1 })}
interactive={interactive}
thumbnailClassName={cn(
"h-10 w-10 rounded-md border border-border object-cover",
interactive && "transition-opacity hover:opacity-90",
)}
/>
))}
{files.map((_, i) => (
<span
key={`file-${i}`}
className="inline-flex items-center gap-1.5 rounded-full bg-muted/60 px-2 py-0.5 text-xs text-muted-foreground"
>
<IconFile className="h-3 w-3" />
{t("task:attachment")}
</span>
))}
</div>
);
}
/** Imperative handle for the ghost row, used by chat input "edit last queued" affordance. */
export type QueuedGhostMessageHandle = {
startEdit: () => void;
+3 -1
View File
@@ -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;
@@ -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.
@@ -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/<id>/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 `<img>` 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.
+9
View File
@@ -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/<session-id>/` 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.