Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): persist staged upload references and render file chips

Steven Enamakel8835c13149bc
diff --git a/app/src/features/conversations/Conversations.processSourceCommand.test.tsx b/app/src/features/conversations/Conversations.processSourceCommand.test.tsx
index 5a9d6f0996..0e9383c35a 100644
--- a/app/src/features/conversations/Conversations.processSourceCommand.test.tsx
+++ b/app/src/features/conversations/Conversations.processSourceCommand.test.tsx
@@ -9,20 +9,23 @@
* swapped, so the overlays (and the command) are live in both modes.
*/
import { combineReducers, configureStore } from '@reduxjs/toolkit';
-import { act, cleanup, render } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { SidebarSlotOutlet, SidebarSlotProvider } from '../../components/layout/shell/SidebarSlot';
import { registry } from '../../lib/commands/registry';
+import { threadApi } from '../../services/api/threadApi';
+import { chatSend } from '../../services/chatService';
import chatRuntimeReducer from '../../store/chatRuntimeSlice';
import layoutReducer from '../../store/layoutSlice';
+import queueReducer from '../../store/queueSlice';
import runModeReducer from '../../store/runModeSlice';
import socketReducer from '../../store/socketSlice';
import themeReducer from '../../store/themeSlice';
import threadGoalReducer from '../../store/threadGoalSlice';
-import threadReducer from '../../store/threadSlice';
+import threadReducer, { markThreadInferenceActive } from '../../store/threadSlice';
import threadTodosReducer from '../../store/threadTodosSlice';
import type { Thread } from '../../types/thread';
import Conversations from './Conversations';
@@ -125,6 +128,7 @@ function buildStore(preload: Record<string, unknown>) {
layout: layoutReducer,
socket: socketReducer,
chatRuntime: chatRuntimeReducer,
+ queue: queueReducer,
theme: themeReducer,
threadTodos: threadTodosReducer,
threadGoal: threadGoalReducer,
@@ -172,6 +176,7 @@ async function renderChat(composer?: 'text' | 'mic-cloud', withProcessData = fal
</Provider>
);
});
+ return store;
}
// The predicate's other half (`selectedThreadId !== null`) is deliberately not
@@ -184,6 +189,63 @@ describe('the agent-process-source command follows the panel that hosts it', ()
registry.reset();
});
+ it('persists raw uploads once and sends the core returned durable reference', async () => {
+ const staged =
+ '[ATTACHMENT:%7B%22path%22%3A%22uploads%2Ft%2Fa%2Fphoto.png%22%2C%22name%22%3A%22photo.png%22%2C%22mime%22%3A%22image%2Fpng%22%2C%22size_bytes%22%3A3%7D]';
+ vi.mocked(threadApi.appendMessage).mockImplementationOnce(async (_id, message) => ({
+ ...message,
+ content: staged,
+ }));
+ await renderChat('text');
+ const picker = document.querySelector('input[type="file"]');
+ expect(picker).not.toBeNull();
+ fireEvent.change(picker!, {
+ target: { files: [new File([Uint8Array.of(1, 2, 3)], 'photo.png', { type: 'image/png' })] },
+ });
+ await waitFor(() => expect(screen.getByText('photo.png')).toBeInTheDocument());
+ fireEvent.click(screen.getByTestId('send-message-button'));
+ await waitFor(() => expect(chatSend).toHaveBeenCalled());
+ const uploaded = vi.mocked(threadApi.appendMessage).mock.calls.at(-1)![1];
+ expect(uploaded.content).toContain('[IMAGE:data:image/png;name=photo.png;base64,AQID]');
+ expect(JSON.stringify(uploaded.extraMetadata)).not.toContain('base64');
+ expect(uploaded.extraMetadata).not.toHaveProperty('attachmentDataUris');
+ expect(chatSend).toHaveBeenLastCalledWith(
+ expect.objectContaining({ threadId: THREAD_ID, message: staged })
+ );
+ });
+
+ it('keeps queued raw upload content only in memory until the core append flush', async () => {
+ vi.mocked(threadApi.appendMessage).mockClear();
+ vi.mocked(chatSend).mockClear();
+ const store = await renderChat('text');
+ fireEvent.change(document.querySelector('input[type="file"]')!, {
+ target: {
+ files: [new File([Uint8Array.of(1, 2, 3)], 'archive.zip', { type: 'application/zip' })],
+ },
+ });
+ await waitFor(() => expect(screen.getByText('archive.zip')).toBeInTheDocument());
+ await act(async () => {
+ store.dispatch(markThreadInferenceActive(THREAD_ID));
+ });
+ fireEvent.click(screen.getByTestId('send-message-button'));
+ await waitFor(() => expect(chatSend).toHaveBeenCalled());
+ expect(chatSend).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ queueMode: 'followup',
+ message: '[FILE:data:application/zip;name=archive.zip;base64,AQID]',
+ })
+ );
+ expect(threadApi.appendMessage).not.toHaveBeenCalled();
+ const pending = store.getState().queue.pendingFollowupsByThread[THREAD_ID][0].message;
+ expect(pending.content).toBe('[FILE:data:application/zip;name=archive.zip;base64,AQID]');
+ expect(pending.extraMetadata).toEqual({
+ attachmentCount: 1,
+ attachmentNames: ['archive.zip'],
+ attachmentKinds: ['file'],
+ attachmentCompressed: [false],
+ });
+ });
+
it('is disabled when the assistant-ui surface has no process data to show', async () => {
await renderChat('text');
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index 94367f5b58..50429e28cf 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -50,6 +50,7 @@ import {
type Attachment,
ATTACHMENT_MAX_FILES,
ATTACHMENT_MAX_IMAGES,
+ attachmentMetadata,
buildMessageWithAttachments,
imageMarkerCost,
parseMessageImages,
@@ -1152,34 +1153,22 @@ const Conversations = ({
addPendingSendingThread(sendingThreadId);
const pendingAttachments = attachments.slice();
const modelOverride = composerModelOverride ?? CHAT_MODEL_HINT;
- const messageText = buildMessageWithAttachments(trimmed, pendingAttachments);
+ let messageText = buildMessageWithAttachments(trimmed, pendingAttachments);
const userMessage: ThreadMessage = {
id: `msg_${globalThis.crypto.randomUUID()}`,
- content: trimmed,
+ content: messageText,
type: 'text',
- extraMetadata:
- pendingAttachments.length > 0
- ? {
- attachmentCount: pendingAttachments.length,
- attachmentNames: pendingAttachments.map(a => a.file.name),
- attachmentKinds: pendingAttachments.map(a => a.kind),
- attachmentDataUris: pendingAttachments
- .filter(a => a.kind === 'image')
- .map(a => a.previewUri ?? a.dataUri),
- // Poster (first frame) per attachment, index-aligned with
- // attachmentKinds — only video entries carry one; others null.
- attachmentPosters: pendingAttachments.map(a =>
- a.kind === 'video' ? (a.previewUri ?? null) : null
- ),
- attachmentCompressed: pendingAttachments.map(a => a.compressed),
- }
- : {},
+ extraMetadata: attachmentMetadata(pendingAttachments),
sender: 'user',
createdAt: new Date().toISOString(),
};
try {
- await dispatch(addMessageLocal({ threadId: sendingThreadId, message: userMessage })).unwrap();
+ const persisted = await dispatch(
+ addMessageLocal({ threadId: sendingThreadId, message: userMessage })
+ ).unwrap();
+ // The core saved the originals before returning this durable reference.
+ messageText = persisted.message.content;
} catch (error) {
// RTK's unwrap() re-throws the rejectWithValue payload directly (a plain
// string, not an Error). Check for the stale-thread sentinel before
@@ -1294,25 +1283,9 @@ const Conversations = ({
}`;
const followupMessage: ThreadMessage = {
id: messageId,
- content: normalized,
+ content: messageText,
type: 'text',
- extraMetadata:
- pendingAttachments.length > 0
- ? {
- attachmentCount: pendingAttachments.length,
- attachmentNames: pendingAttachments.map(a => a.file.name),
- attachmentKinds: pendingAttachments.map(a => a.kind),
- attachmentDataUris: pendingAttachments
- .filter(a => a.kind === 'image')
- .map(a => a.previewUri ?? a.dataUri),
- // Poster (first frame) per attachment, index-aligned with
- // attachmentKinds — only video entries carry one; others null.
- attachmentPosters: pendingAttachments.map(a =>
- a.kind === 'video' ? (a.previewUri ?? null) : null
- ),
- attachmentCompressed: pendingAttachments.map(a => a.compressed),
- }
- : {},
+ extraMetadata: attachmentMetadata(pendingAttachments),
sender: 'user',
createdAt: new Date().toISOString(),
};
diff --git a/app/src/lib/attachments.ts b/app/src/lib/attachments.ts
index a324f1fcb5..ff7890485f 100644
--- a/app/src/lib/attachments.ts
+++ b/app/src/lib/attachments.ts
@@ -199,9 +199,8 @@ function seekVideo(video: HTMLVideoElement, time: number): Promise<void> {
/**
* Sample `count` still frames from a video file as JPEG data URIs by decoding it
* in a detached `<video>` element and painting each seek point onto a `<canvas>`.
- * The full clip is never uploaded — only these frames ride the `[IMAGE:]` vision
- * path. Throws if the browser can't decode the file (the caller maps that to a
- * `read_failed` error). Requires a real codec-capable runtime (CEF/Chromium);
+ * This optional preview helper does not affect original upload acceptance.
+ * Throws if the browser cannot decode the file. Requires a codec-capable browser;
* jsdom can't decode video, so unit tests stub {@link videoFrameExtractor}.
*/
async function extractVideoFramesImpl(
@@ -321,6 +320,69 @@ export function buildMessageWithAttachments(text: string, attachments: Attachmen
return text.trim() ? `${text.trim()} ${markers}` : markers;
}
+/** Workspace references returned by the core after it has saved originals. */
+export interface AttachmentReference {
+ path: string;
+ name: string;
+ mime: string;
+ size_bytes: number;
+}
+
+/** Decode durable references without exposing raw JSON in message bubbles. */
+export function parseAttachmentReferences(content: string): {
+ text: string;
+ attachments: AttachmentReference[];
+} {
+ const attachments: AttachmentReference[] = [];
+ const text = content
+ .replace(/\[ATTACHMENT:([^\]]+)\]/g, (marker, encoded: string) => {
+ try {
+ const decoded = new URLSearchParams(`value=${encoded}`).get('value');
+ const value: unknown = JSON.parse(decoded ?? '');
+ if (!value || typeof value !== 'object') return marker;
+ const file = value as Partial<AttachmentReference>;
+ if (
+ typeof file.path !== 'string' ||
+ typeof file.name !== 'string' ||
+ typeof file.mime !== 'string' ||
+ typeof file.size_bytes !== 'number' ||
+ !Number.isSafeInteger(file.size_bytes) ||
+ file.size_bytes < 0
+ )
+ return marker;
+ // These are workspace references, never URLs or absolute browser targets.
+ const components = file.path.split('/');
+ if (
+ !file.path ||
+ file.path.includes('\\') ||
+ file.path.includes(':') ||
+ file.path.includes('\0') ||
+ components.some(part => part === '' || part === '.' || part === '..')
+ )
+ return marker;
+ attachments.push(file as AttachmentReference);
+ return '';
+ } catch {
+ return marker;
+ }
+ })
+ .replace(/ {2,}/g, ' ')
+ .trim();
+ return { text, attachments };
+}
+
+/** Display metadata excludes payload bytes; originals travel only in upload markers. */
+export function attachmentMetadata(attachments: Attachment[]): Record<string, unknown> {
+ return attachments.length === 0
+ ? {}
+ : {
+ attachmentCount: attachments.length,
+ attachmentNames: attachments.map(file => file.file.name),
+ attachmentKinds: attachments.map(file => file.kind),
+ attachmentCompressed: attachments.map(file => file.compressed),
+ };
+}
+
/**
* Parse `[IMAGE:<data-uri>]` and `[FILE:<data-uri>]` markers out of a stored message string.
* Returns the clean text (markers removed) and the list of image data URIs found.
@@ -328,8 +390,8 @@ export function buildMessageWithAttachments(text: string, attachments: Attachmen
*/
export function parseMessageImages(content: string): { text: string; dataUris: string[] } {
const dataUris: string[] = [];
- const text = content
- .replace(/\[IMAGE:([^\]]+)\]/g, (_match, uri: string) => {
+ const text = parseAttachmentReferences(content)
+ .text.replace(/\[IMAGE:([^\]]+)\]/g, (_match, uri: string) => {
dataUris.push(uri);
return '';
})
diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsx
index 704576890c..d15888e312 100644
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@ -609,8 +609,8 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
// Persist sequentially so the queued prompts land in the append-log in the
// order the user queued them (concurrent dispatches would race), and
// surface failures instead of dropping them silently. The stored message
- // carries the original content + attachment metadata, so the follow-up
- // persists identically to an interactive send.
+ // carries the original upload markers in memory. The append boundary
+ // saves originals and returns durable references before writing history.
for (const item of queued) {
try {
await dispatch(addMessageLocal({ threadId, message: item.message })).unwrap();
diff --git a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
index be74f10436..9328cf4e6c 100644
--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
@@ -859,6 +859,52 @@ describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invaria
expect(store.getState().chatRuntime.pendingPlanReviewByThread['t-plan']).toBeUndefined();
});
+ it('flushes queued upload originals through core staging and caches only returned references', async () => {
+ const listeners = renderProvider();
+ const raw = '[FILE:data:application/zip;name=archive.zip;base64,AQID]';
+ const durable =
+ '[ATTACHMENT:%7B%22path%22%3A%22uploads%2Ft%2Fa%2Farchive.zip%22%2C%22name%22%3A%22archive.zip%22%2C%22mime%22%3A%22application%2Fzip%22%2C%22size_bytes%22%3A3%7D]';
+ vi.mocked(threadApi.appendMessage).mockImplementation(async (_tid, message) =>
+ message.sender === 'user' ? { ...message, content: durable } : message
+ );
+ store.dispatch(
+ pendingFollowupAdded({
+ threadId: 't-upload',
+ message: {
+ id: 'queued-upload',
+ content: raw,
+ type: 'text',
+ extraMetadata: { attachmentNames: ['archive.zip'], attachmentKinds: ['file'] },
+ sender: 'user',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ },
+ text: raw,
+ })
+ );
+ await act(async () => {
+ listeners.onDone?.({
+ thread_id: 't-upload',
+ request_id: 'r-upload',
+ full_response: 'done',
+ rounds_used: 1,
+ total_input_tokens: 1,
+ total_output_tokens: 1,
+ });
+ });
+ await waitFor(() =>
+ expect(threadApi.appendMessage).toHaveBeenCalledWith(
+ 't-upload',
+ expect.objectContaining({ content: raw, sender: 'user' })
+ )
+ );
+ const row = store
+ .getState()
+ .thread.messagesByThreadId['t-upload'].find(message => message.id === 'queued-upload');
+ expect(row?.content).toBe(durable);
+ expect(JSON.stringify(row?.extraMetadata)).not.toContain('base64');
+ expect(store.getState().queue.pendingFollowupsByThread['t-upload']).toBeUndefined();
+ });
+
it('flushes queued follow-ups into the transcript when a turn ends', async () => {
const listeners = renderProvider();
store.dispatch(
diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.ts
index 5f0e3a15de..24c786a92c 100644
--- a/app/src/providers/__tests__/assistantUiMessages.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts
@@ -32,6 +32,47 @@ function tool(over: Partial<ToolTimelineEntry> = {}): ToolTimelineEntry {
}
describe('toThreadMessageLike', () => {
+ it('renders durable uploads as file chips without raw reference JSON or inline bytes', () => {
+ const references = [
+ { path: 'uploads/t/id/scan.png', name: 'scan.png', mime: 'image/png', size_bytes: 3 },
+ {
+ path: 'uploads/t/id/archive.zip',
+ name: 'archive.zip',
+ mime: 'application/zip',
+ size_bytes: 8,
+ },
+ ]
+ .map(file => `[ATTACHMENT:${encodeURIComponent(JSON.stringify(file))}]`)
+ .join(' ');
+ expect(toThreadMessageLike(msg({ content: `inspect ${references}` })).content).toEqual([
+ { type: 'text', text: 'inspect' },
+ { type: 'file', filename: 'scan.png', data: '', mimeType: 'image/png' },
+ { type: 'file', filename: 'archive.zip', data: '', mimeType: 'application/zip' },
+ ]);
+ });
+
+ it('keeps malformed or unsafe durable markers as ordinary text', () => {
+ for (const path of ['../escape', '/etc/passwd', 'C:\\secret', 'uploads/../secret']) {
+ const content = `[ATTACHMENT:${encodeURIComponent(JSON.stringify({ path, name: 'file', mime: 'image/png', size_bytes: 1 }))}]`;
+ expect(toThreadMessageLike(msg({ content })).content).toEqual([
+ { type: 'text', text: content },
+ ]);
+ }
+ const content = '[ATTACHMENT:%invalid]';
+ expect(toThreadMessageLike(msg({ content })).content).toEqual([
+ { type: 'text', text: content },
+ ]);
+ });
+
+ it('continues to render legacy inline image previews', () => {
+ expect(
+ toThreadMessageLike(msg({ content: 'photo [IMAGE:data:image/png;base64,old]' })).content
+ ).toEqual([
+ { type: 'text', text: 'photo' },
+ { type: 'image', image: 'data:image/png;base64,old', filename: undefined },
+ ]);
+ });
+
it('maps sender to role', () => {
expect(toThreadMessageLike(msg({ id: 'u' })).role).toBe('user');
expect(toThreadMessageLike(msg({ id: 'a', sender: 'agent' })).role).toBe('assistant');
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index b210ec7f22..5b90829b06 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -9,7 +9,7 @@ import {
} from '@assistant-ui/react';
import { parseBubbleSegments } from '../features/conversations/utils/format';
-import { parseMessageImages } from '../lib/attachments';
+import { parseAttachmentReferences, parseMessageImages } from '../lib/attachments';
import { unwrapToolCallEnvelope } from '../lib/chat/toolCallEnvelope';
import type { ChatCitation } from '../services/chatService';
import {
@@ -780,7 +780,8 @@ function mimeTypeFromDataUri(dataUri: string): string {
}
function userParts(msg: ThreadMessage): ThreadUserMessagePart[] {
- const parsed = parseMessageImages(msg.content ?? '');
+ const references = parseAttachmentReferences(msg.content ?? '');
+ const parsed = parseMessageImages(references.text);
const metadata = msg.extraMetadata ?? {};
const kinds = stringArray(metadata.attachmentKinds);
const names = stringArray(metadata.attachmentNames);
@@ -791,6 +792,16 @@ function userParts(msg: ThreadMessage): ThreadUserMessagePart[] {
if (parsed.text.length > 0) parts.push({ type: 'text', text: parsed.text });
+ if (references.attachments.length > 0) {
+ // Workspace paths cannot be loaded as browser images. A file chip restores
+ // the attachment's identity without storing preview bytes in the message log.
+ for (const file of references.attachments) {
+ parts.push({ type: 'file', filename: file.name, data: '', mimeType: file.mime });
+ }
+ for (const image of parsed.dataUris) parts.push({ type: 'image', image });
+ return parts;
+ }
+
if (kinds.length === 0) {
for (const [index, image] of dataUris.entries()) {
parts.push({ type: 'image', image, filename: names[index] });