Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(desktop-app): image attachment previews, dismissible new-chat nudge, resend with attachments
Md47251f485a4
diff --git a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx b/desktop-app/ui/src/components/GfsImagePreview/Body.tsxindex d8ebab419..73c57a095 100644--- a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/Body.tsx@@ -17,6 +17,7 @@ export function GfsImagePreviewBody({byteLength,fileName,gfsUri,+ dataBase64,mimeType,onDownloadError,titleId,@@ -44,15 +45,34 @@ export function GfsImagePreviewBody({const loadPreview = async () => {try {+ // Exactly one source is allowed (see GfsImagePreviewSource); enforce it+ // here so a mis-wired caller fails visibly instead of fetching a bogus+ // `undefined` URI.+ if (dataBase64 === undefined && gfsUri === undefined) {+ throw new Error('Image preview received no source')+ }// The listed size is a skip HINT (fail fast without a round-trip); the// download itself is independently bounded so a wrong listed size cannot// materialize an oversized payload.assertGfsImagePreviewSize(byteLength)- const { bytes } = await window.clerum.gfs.downloadPreview(- gfsUri,- GFS_IMAGE_PREVIEW_MAX_BYTES- )- assertGfsImagePreviewSize(bytes.byteLength)+ let bytes: ArrayBuffer+ if (dataBase64 !== undefined) {+ // Inline source (chat image attachments): the bytes already sit on+ // the attachment, so decode locally instead of a GFS round-trip.+ // Still guard the DECODED length — a lying `byteLength` hint must+ // not materialize an oversized blob.+ bytes = decodeBase64ToArrayBuffer(dataBase64)+ assertGfsImagePreviewSize(bytes.byteLength)+ } else {+ const downloaded = await window.clerum.gfs.downloadPreview(+ // Non-null by the source guard above (dataBase64 is absent → gfsUri+ // is present).+ gfsUri!,+ GFS_IMAGE_PREVIEW_MAX_BYTES+ )+ bytes = downloaded.bytes+ assertGfsImagePreviewSize(bytes.byteLength)+ }if (!active) returnconst blob = new Blob([bytes], { type: mimeType })setSourceBlob(blob)@@ -82,7 +102,7 @@ export function GfsImagePreviewBody({active = falseif (objectUrl) URL.revokeObjectURL(objectUrl)}- }, [byteLength, gfsUri, mimeType])+ }, [byteLength, gfsUri, dataBase64, mimeType])useEffect(() => {mountedRef.current = true@@ -177,6 +197,15 @@ export function GfsImagePreviewBody({)}+function decodeBase64ToArrayBuffer(dataBase64: string): ArrayBuffer {+ const binary = window.atob(dataBase64)+ const bytes = new Uint8Array(binary.length)+ for (let index = 0; index < binary.length; index += 1) {+ bytes[index] = binary.charCodeAt(index)+ }+ return bytes.buffer+}+async function convertBlobToPng(blob: Blob): Promise<Blob | null> {if (typeof createImageBitmap === 'undefined') return nulltry {diff --git a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsxindex 11300b94a..d3e557e32 100644--- a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx@@ -52,6 +52,29 @@ describe('GfsImagePreviewBody', () => {expect(screen.queryByRole('presentation')).toBeNull()})+ it('renders an inline base64 source without a GFS download (chat attachments)', async () => {+ // BUG-176: chat image attachments already carry their bytes — the body must+ // decode them locally instead of reaching for `gfs.downloadPreview`.+ const downloadPreview = vi.fn(async () => ({ bytes: new Uint8Array([9]).buffer }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { gfs: { downloadPreview } },+ })++ render(+ <GfsImagePreviewBody+ byteLength={3}+ fileName="Screenshot 2026-09-21 at 13.32.30.png"+ dataBase64="AQID"+ mimeType="image/png"+ />+ )++ const img = await screen.findByAltText('Preview of Screenshot 2026-09-21 at 13.32.30.png')+ expect(img.getAttribute('src')).toBe('blob:gfs-image-preview')+ expect(downloadPreview).not.toHaveBeenCalled()+ })+it('renders the heading at the requested level (a page uses h2)', async () => {stubDownload(new Uint8Array([1, 2, 3]).buffer)render(diff --git a/desktop-app/ui/src/components/GfsImagePreview/index.tsx b/desktop-app/ui/src/components/GfsImagePreview/index.tsxindex 610b1446c..1ec8faa80 100644--- a/desktop-app/ui/src/components/GfsImagePreview/index.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/index.tsx@@ -16,6 +16,7 @@ export function GfsImagePreview({byteLength,fileName,gfsUri,+ dataBase64,mimeType,onClose,onDownloadError,@@ -52,6 +53,7 @@ export function GfsImagePreview({byteLength={byteLength}fileName={fileName}gfsUri={gfsUri}+ dataBase64={dataBase64}mimeType={mimeType}onDownloadError={onDownloadError}titleId={titleId}@@ -76,4 +78,4 @@ export function GfsImagePreview({}export { GfsImagePreviewBody } from './Body'-export type { GfsImagePreviewProps } from './types'+export type { GfsImagePreviewProps, GfsImagePreviewSource } from './types'diff --git a/desktop-app/ui/src/components/GfsImagePreview/types.ts b/desktop-app/ui/src/components/GfsImagePreview/types.tsindex 03226508d..f6b7d9253 100644--- a/desktop-app/ui/src/components/GfsImagePreview/types.ts+++ b/desktop-app/ui/src/components/GfsImagePreview/types.ts@@ -1,13 +1,27 @@import type { ReactNode } from 'react'+/**+ * Where the preview bytes come from (exactly one):+ * - `gfsUri` — fetched from GFS by URI (Files/preview surfaces).+ * - `dataBase64` — supplied inline as base64 (chat image attachments already+ * carry their bytes; no GFS round-trip exists for them).+ *+ * Modeled as two optional props (not a discriminated union) so a caller can+ * destructure and forward them losslessly; `GfsImagePreviewBody` guards the+ * exactly-one contract at runtime.+ */+export type GfsImagePreviewSource = {+ gfsUri?: string+ dataBase64?: string+}+export type GfsImagePreviewProps = {byteLength: numberfileName: string- gfsUri: stringmimeType: stringonClose: () => voidonDownloadError?: (error: unknown) => void-}+} & GfsImagePreviewSource/*** The de-modalized image preview (spec 18 §3.B.2): the `<img>` + its fetch,@@ -19,10 +33,9 @@ export type GfsImagePreviewProps = {export type GfsImagePreviewBodyProps = {byteLength: numberfileName: string- gfsUri: stringmimeType: stringonDownloadError?: (error: unknown) => voidtitleId?: stringheaderActions?: ReactNodeheadingLevel?: 2 | 3-}+} & GfsImagePreviewSourcediff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsxindex c272bc721..87a796abc 100644--- a/desktop-app/ui/src/components/agents/ChatThread.tsx+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx@@ -16,6 +16,7 @@ import { useNotificationsContext } from '@contexts/NotificationsContext'import { Button, IconButton, MenuItem } from '@components/Common'import { ConfirmDialog } from '@components/ConfirmDialog'import { GfsFileIcon } from '@components/GfsFileIcon'+import { GfsImagePreview } from '@components/GfsImagePreview'import { MessageArtifactActions } from '@components/MessageArtifactActions'import { SecureHtmlPreview } from '@components/SecureHtmlPreview'import { IconConnectors, IconContexts, IconWorkflows } from '@components/SidebarNav/icons'@@ -32,6 +33,8 @@ import {getChatMessageAttachmentTypeLabel,parseChatMessageDisplay,} from '../../lib/chatMessageAttachments'+import { setComposerDraft } from '../../lib/composerDraftStore'+import { buildComposerResendDraft, findNearestPrecedingUserMessage } from '../../lib/composerResend'import {extractHtmlVisualization,formatChatTimestamp,@@ -146,6 +149,22 @@ function canDownloadResponseFileAttachment(attachment: ChatMessageAttachment): b)}+/**+ * BUG-176: a user-attached image whose bytes ride on the attachment+ * (inline base64, same contract as response_file) can reopen the shared+ * `GfsImagePreview` modal from the sent-message chip. Parsed legacy+ * `[Attached images]` chips carry labels only and stay inert.+ */+function canPreviewUploadedFileAttachment(attachment: ChatMessageAttachment): boolean {+ return (+ attachment.type === 'uploaded_file' &&+ attachment.encoding === 'base64' &&+ typeof attachment.dataBase64 === 'string' &&+ attachment.dataBase64.length > 0 &&+ (attachment.mimeType ?? '').startsWith('image/')+ )+}+function downloadResponseFileAttachment(attachment: ChatMessageAttachment): void {if (!canDownloadResponseFileAttachment(attachment)) returnconst binary = window.atob(attachment.dataBase64 ?? '')@@ -167,7 +186,13 @@ function downloadResponseFileAttachment(attachment: ChatMessageAttachment): void}function MessageAttachmentList({ attachments }: { attachments: ChatMessageAttachment[] }) {+ const [previewAttachmentId, setPreviewAttachmentId] = useState<string | null>(null)if (!attachments.length) return null+ const previewAttachment =+ attachments.find(+ attachment =>+ attachment.id === previewAttachmentId && canPreviewUploadedFileAttachment(attachment)+ ) ?? nullreturn (<span className="message-attachments-list" aria-label="Message attachments">{attachments.map(attachment => {@@ -176,12 +201,9 @@ function MessageAttachmentList({ attachments }: { attachments: ChatMessageAttachattachment.type === 'uploaded_file' ? 'uploaded-image' : attachment.typeconst downloadable = canDownloadResponseFileAttachment(attachment)const isResponseFile = attachment.type === 'response_file'- return (- <span- key={attachment.id}- className={`message-attachment-chip${isResponseFile ? ' message-attachment-chip--response-file' : ''}`}- title={typeLabel}- >+ const previewable = canPreviewUploadedFileAttachment(attachment)+ const chipBody = (+ <><spanclassName={`composer-reference-icon message-attachment-icon composer-reference-icon--${iconTypeClass}`}aria-hidden="true"@@ -192,6 +214,26 @@ function MessageAttachmentList({ attachments }: { attachments: ChatMessageAttach<span className="message-attachment-type-label">Generated file</span>) : null}<span className="message-attachment-label">{attachment.label}</span>+ </>+ )+ return (+ <span+ key={attachment.id}+ className={`message-attachment-chip${isResponseFile ? ' message-attachment-chip--response-file' : ''}`}+ title={typeLabel}+ >+ {previewable ? (+ <button+ type="button"+ className="message-attachment-preview-trigger"+ onClick={() => setPreviewAttachmentId(attachment.id)}+ title={typeLabel}+ >+ {chipBody}+ </button>+ ) : (+ chipBody+ )}{downloadable ? (<ButtonclassName="message-attachment-download-button"@@ -206,6 +248,15 @@ function MessageAttachmentList({ attachments }: { attachments: ChatMessageAttach</span>)})}+ {previewAttachment ? (+ <GfsImagePreview+ byteLength={previewAttachment.sizeBytes ?? previewAttachment.dataBase64!.length}+ fileName={previewAttachment.filename || previewAttachment.label}+ dataBase64={previewAttachment.dataBase64}+ mimeType={previewAttachment.mimeType || 'image/png'}+ onClose={() => setPreviewAttachmentId(null)}+ />+ ) : null}</span>)}@@ -240,6 +291,8 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: ChandleSelectChat: onSelectChat,handleRenameChat: onRenameChat,handleDeleteChat: onDeleteChat,+ handleAddComposerImageAttachments: onAddComposerImageAttachments,+ handleAddComposerReferenceAttachments: onAddComposerReferenceAttachments,} = useAgentChatActionsContext()const { cancelTask: onCancelTask } = useMcpRuntimeContext()@@ -433,6 +486,26 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C}}, [])+ // TASK-42: resend repopulates the composer from the ORIGINAL prompt — text in+ // the per-chat draft store, uploaded files re-attached (bytes ride the chip),+ // plugin/connector/file indicators re-applied as composer references. The+ // source is always a user message: resending a reply re-issues the prompt that+ // produced it (see `findNearestPrecedingUserMessage`).+ const handleResendMessage = useCallback(+ (source: Pick<RenderableChatMessage, 'content' | 'attachments'>) => {+ if (!activeChatId) return+ const draft = buildComposerResendDraft(source)+ setComposerDraft(activeChatId, draft.content)+ if (draft.imageAttachments.length) {+ onAddComposerImageAttachments(draft.imageAttachments)+ }+ if (draft.referenceAttachments.length) {+ onAddComposerReferenceAttachments(draft.referenceAttachments)+ }+ },+ [activeChatId, onAddComposerImageAttachments, onAddComposerReferenceAttachments]+ )+const renderProgressStepper = useCallback((message: RenderableChatMessage, filterStatus?: 'completed' | 'non-completed') => {if (progressByMessageId[message.id] == null) return null@@ -615,6 +688,13 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C/\b[a-zA-Z0-9][a-zA-Z0-9._-]*\.html?\b/i.test(displayContent)const showMetaRow = message.role === 'assistant' || message.role === 'user'const copyContent = message.role === 'user' ? displayContent : message.content+ // TASK-42: a user message resends itself; an assistant+ // message (including error bubbles) resends the user+ // prompt that produced it.+ const resendSource =+ message.role === 'user'+ ? message+ : findNearestPrecedingUserMessage(groupedWithKeys, groupIndex)const metaRowRoleClass =message.role === 'user'? 'chat-message-meta-row--user'@@ -744,6 +824,25 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C<MessageTokens tokens={message.tokens} />)}</div>+ {resendSource ? (+ <IconButton+ className="message-resend-button message-copy-button message-copy-button--inline"+ onClick={() => handleResendMessage(resendSource)}+ aria-label={+ message.role === 'user' ? 'Resend message' : 'Resend prompt'+ }+ label={+ message.role === 'user' ? 'Resend message' : 'Resend prompt'+ }+ size="xs"+ variant="ghost"+ >+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path fill="none" d="M0 0h24v24H0V0z" />+ <path d="M2.01 21 23 12 2.01 3 2 10l15 2-15 2z" />+ </svg>+ </IconButton>+ ) : null}<IconButtonclassName={`message-copy-button message-copy-button--inline${copiedMessageKey === message.messageKey ? ' copied' : ''diff --git a/desktop-app/ui/src/components/agents/NudgeArea.tsx b/desktop-app/ui/src/components/agents/NudgeArea.tsxindex ee4412225..e3725d6fb 100644--- a/desktop-app/ui/src/components/agents/NudgeArea.tsx+++ b/desktop-app/ui/src/components/agents/NudgeArea.tsx@@ -1,6 +1,7 @@-import { useEffect, useState } from 'react'+import { useCallback, useEffect, useState } from 'react'import { type TaskState, makeTaskKey, useAgentTaskTracker } from '@contexts/AgentTaskTrackerContext'-import { Button, StatusBanner } from '@components/Common'+import { Button, IconButton, StatusBanner } from '@components/Common'+import { IconClose } from '@components/SidebarNav/icons'import { useBrowserWindowState } from '@hooks/useBrowserWindowState'import { useTaskTier } from '@hooks/useTaskTier'import type { ProgressStep } from '../../uiTypes'@@ -40,11 +41,19 @@ function MiniSummary({ steps }: { steps: ProgressStep[] }) {* the misleading copy — this guard does. No replacement "waiting for your* approval" banner: the approval card rendered above is already that affordance,* and duplicating it would just add noise under it.+ *+ * TASK-228: every tier renders a dismiss (×) button. A dismissal is keyed by+ * task identity and suppresses all later tiers of that same task; a new task+ * (same chat or another) starts fresh. Tier timing/thresholds are untouched.*/export function NudgeArea({ agentRef, chatId, onStartNewChat, onRefreshState }: Props) {const tracker = useAgentTaskTracker()const key = makeTaskKey(agentRef, chatId)const [state, setState] = useState<TaskState | undefined>(() => tracker.get(key))+ // TASK-228: tasks the user explicitly dismissed. Keyed by task identity so a+ // dismissal hides every later tier of the SAME task (tracker updates keep+ // arriving) while a NEW task in the same chat starts fresh with its nudges.+ const [dismissedTaskIds, setDismissedTaskIds] = useState<ReadonlySet<string>>(() => new Set())const { isWindowVisible } = useBrowserWindowState()const tier = useTaskTier(state)@@ -57,6 +66,15 @@ export function NudgeArea({ agentRef, chatId, onStartNewChat, onRefreshState }:return tracker.subscribe(key, setState)}, [tracker, key])+ const dismissNudge = useCallback((taskIdentity: string) => {+ setDismissedTaskIds(previous => {+ if (previous.has(taskIdentity)) return previous+ const next = new Set(previous)+ next.add(taskIdentity)+ return next+ })+ }, [])+if (!state) return nullif (state.status === 'completed' || state.status === 'cancelled' || state.status === 'failed')return null@@ -67,23 +85,43 @@ export function NudgeArea({ agentRef, chatId, onStartNewChat, onRefreshState }:// window too.if (state.status === 'suspended' || state.pendingApproval) return nullif (tier === 'T1' || tier === 'T2') return null+ const taskIdentity = state.taskId || key+ if (dismissedTaskIds.has(taskIdentity)) return null++ const dismissButton = (+ <IconButton+ className="nudge-area__dismiss"+ aria-label="Dismiss this suggestion"+ label="Dismiss this suggestion"+ size="xs"+ variant="ghost"+ onClick={() => dismissNudge(taskIdentity)}+ >+ <IconClose width={14} height={14} />+ </IconButton>+ )if (tier === 'T3') {return (<div className="nudge-area" data-tier="T3">- <StatusBanner tone="info" compact>- This task is taking longer than usual. You can keep working in another chat — we'll let- you know here when it's done.- </StatusBanner>- <Button- className="nudge-area-action"- variant="soft"- color="primary"- size="sm"- onClick={onStartNewChat}- >- Start a new chat- </Button>+ <div className="nudge-area__header">+ <StatusBanner tone="info" compact>+ This task is taking longer than usual. You can keep working in another chat — we'll let+ you know here when it's done.+ </StatusBanner>+ {dismissButton}+ </div>+ <div className="nudge-area__footer">+ <Button+ className="nudge-area-action"+ variant="soft"+ color="primary"+ size="sm"+ onClick={onStartNewChat}+ >+ Start a new chat+ </Button>+ </div></div>)}@@ -94,10 +132,15 @@ export function NudgeArea({ agentRef, chatId, onStartNewChat, onRefreshState }:: 'Your agent is still working. Your system will notify you when it finishes.'return (<div className="nudge-area" data-tier="T4">- <StatusBanner tone="info" compact>- {text}- </StatusBanner>- <MiniSummary steps={state.steps} />+ <div className="nudge-area__header">+ <StatusBanner tone="info" compact>+ {text}+ </StatusBanner>+ {dismissButton}+ </div>+ <div className="nudge-area__footer">+ <MiniSummary steps={state.steps} />+ </div></div>)}@@ -105,19 +148,24 @@ export function NudgeArea({ agentRef, chatId, onStartNewChat, onRefreshState }:// T5return (<div className="nudge-area" data-tier="T5">- <StatusBanner tone="warn" compact>- Your agent is still working. If you think something might be stuck, you can refresh the- state.- </StatusBanner>- <MiniSummary steps={state.steps} />- <Button- className="nudge-area-action"- variant="soft"- size="sm"- onClick={() => void onRefreshState()}- >- Refresh state- </Button>+ <div className="nudge-area__header">+ <StatusBanner tone="warn" compact>+ Your agent is still working. If you think something might be stuck, you can refresh the+ state.+ </StatusBanner>+ {dismissButton}+ </div>+ <div className="nudge-area__footer">+ <MiniSummary steps={state.steps} />+ <Button+ className="nudge-area-action"+ variant="soft"+ size="sm"+ onClick={() => void onRefreshState()}+ >+ Refresh state+ </Button>+ </div></div>)}diff --git a/desktop-app/ui/src/components/agents/__tests__/ChatThread.resend.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ChatThread.resend.test.tsxnew file mode 100644index 000000000..3ad2df7e3--- /dev/null+++ b/desktop-app/ui/src/components/agents/__tests__/ChatThread.resend.test.tsx@@ -0,0 +1,221 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { getComposerDraft, resetComposerDraftStore } from '@lib/composerDraftStore'+import { buildLoadedChatSemanticModels } from '../../../lib/chatMessageSemantics'+import type { AgentChatMessage } from '../../../uiTypes'+import { ChatThread } from '../ChatThread'++const navigationValue = { selectedAgent: 'agent-x', handleSelectChatAgent: vi.fn() }+const notificationsValue = { decideApproval: vi.fn() }+const chatListValue = {+ chatList: [],+ chatListLoading: false,+ sessionStateByChatId: {},+}+const addComposerImageAttachments = vi.fn()+const addComposerReferenceAttachments = vi.fn()+const actionsValue = {+ chatEndRef: { current: null },+ handleSelectChat: vi.fn(),+ handleRenameChat: vi.fn(),+ handleDeleteChat: vi.fn(),+ handleAddComposerImageAttachments: addComposerImageAttachments,+ handleAddComposerReferenceAttachments: addComposerReferenceAttachments,+}+const runtimeValue = { cancelTask: vi.fn() }+let messages: AgentChatMessage[] = []+let groupedMessages: Array<{ role: 'user' | 'assistant' | 'system'; items: AgentChatMessage[] }> =+ []++vi.mock('@contexts/NavigationContext', () => ({+ useNavigationContext: () => navigationValue,+}))+vi.mock('@contexts/NotificationsContext', () => ({+ useNotificationsContext: () => notificationsValue,+}))+vi.mock('@contexts/ChatListContext', () => ({+ useChatListContext: () => chatListValue,+}))+vi.mock('@contexts/AgentChatActionsContext', () => ({+ useAgentChatActionsContext: () => actionsValue,+}))+vi.mock('@contexts/McpRuntimeContext', () => ({+ useMcpRuntimeContext: () => runtimeValue,+}))+vi.mock('@contexts/ChatThreadStateContext', () => ({+ useChatThreadStateContext: () => ({+ activeMessages: messages,+ groupedMessages,+ chatMessagesLoading: false,+ hasOlderMessages: false,+ olderMessagesLoading: false,+ handleLoadOlderMessages: vi.fn(),+ activeChatId: 'chat-1',+ activityByMessageId: {},+ progressByMessageId: {},+ localSearchQuery: '',+ localSearchCurrentMatch: null,+ semanticModelsByMessageId: new Map(+ buildLoadedChatSemanticModels(messages).map(model => [model.messageId, model])+ ),+ }),+}))+vi.mock('../InFlightAssistantPlaceholder', () => ({ InFlightAssistantPlaceholder: () => null }))+vi.mock('../NudgeArea', () => ({ NudgeArea: () => null }))+vi.mock('../ChatStateBadge', () => ({ ChatStateBadge: () => null }))+vi.mock('@components/MessageArtifactActions', () => ({ MessageArtifactActions: () => null }))++const PNG_BASE64 = 'aGVsbG8='++function userMessageWithAttachments(): AgentChatMessage {+ return {+ id: 'user-1',+ role: 'user',+ content: 'Summarize the chart with the plugin',+ timestamp: 1,+ attachments: [+ {+ id: 'img-1',+ type: 'uploaded_file',+ label: 'chart.png',+ addedOrder: 0,+ filename: 'chart.png',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: PNG_BASE64,+ sizeBytes: 5,+ },+ {+ id: 'chip-plugin',+ type: 'plugin',+ label: 'profits/revenue',+ addedOrder: 1,+ },+ ],+ }+}++afterEach(() => {+ cleanup()+ messages = []+ groupedMessages = []+ resetComposerDraftStore()+ vi.clearAllMocks()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++describe('ChatThread resend action (TASK-42)', () => {+ it('re-populates the composer draft and re-attaches files + plugin indicators from a user message', () => {+ const user = userMessageWithAttachments()+ messages = [user]+ groupedMessages = [{ role: 'user', items: [user] }]++ render(<ChatThread />)++ fireEvent.click(screen.getByRole('button', { name: 'Resend message' }))++ expect(getComposerDraft('chat-1')).toBe('Summarize the chart with the plugin')+ expect(addComposerImageAttachments).toHaveBeenCalledTimes(1)+ expect(addComposerImageAttachments.mock.calls[0]![0]).toEqual([+ expect.objectContaining({+ name: 'chart.png',+ mimeType: 'image/png',+ dataBase64: PNG_BASE64,+ sizeBytes: 5,+ previewDataUrl: `data:image/png;base64,${PNG_BASE64}`,+ }),+ ])+ expect(addComposerReferenceAttachments).toHaveBeenCalledTimes(1)+ expect(addComposerReferenceAttachments.mock.calls[0]![0]).toEqual([+ {+ id: 'plugin:profits:revenue',+ type: 'plugin',+ namespace: 'profits',+ name: 'revenue',+ label: 'revenue',+ },+ ])+ })++ it('resending from an assistant message re-issues the originating user prompt (text + attachments + indicators)', () => {+ const user = userMessageWithAttachments()+ const assistant: AgentChatMessage = {+ id: 'assistant-1',+ role: 'assistant',+ content: 'Here is the summary you asked for.',+ timestamp: 2,+ attachments: [+ {+ id: 'generated-1',+ type: 'response_file',+ label: 'summary.md',+ filename: 'summary.md',+ mimeType: 'text/markdown',+ encoding: 'base64',+ dataBase64: 'IyBzdW1tYXJ5',+ },+ ],+ }+ messages = [user, assistant]+ groupedMessages = [+ { role: 'user', items: [user] },+ { role: 'assistant', items: [assistant] },+ ]++ render(<ChatThread />)++ fireEvent.click(screen.getByRole('button', { name: 'Resend prompt' }))++ // The draft carries the USER prompt, not the assistant reply.+ expect(getComposerDraft('chat-1')).toBe('Summarize the chart with the plugin')+ expect(addComposerImageAttachments).toHaveBeenCalledTimes(1)+ expect(addComposerImageAttachments.mock.calls[0]![0]).toEqual([+ expect.objectContaining({ name: 'chart.png', dataBase64: PNG_BASE64 }),+ ])+ expect(addComposerReferenceAttachments).toHaveBeenCalledTimes(1)+ expect(addComposerReferenceAttachments.mock.calls[0]![0]).toEqual([+ expect.objectContaining({ type: 'plugin', namespace: 'profits', name: 'revenue' }),+ ])+ })++ it('hides the resend action on an assistant message with no preceding user prompt', () => {+ const assistant: AgentChatMessage = {+ id: 'assistant-only',+ role: 'assistant',+ content: 'A reply with no user turn before it.',+ timestamp: 1,+ }+ messages = [assistant]+ groupedMessages = [{ role: 'assistant', items: [assistant] }]++ render(<ChatThread />)++ expect(screen.queryByRole('button', { name: 'Resend prompt' })).toBeNull()+ expect(screen.queryByRole('button', { name: 'Resend message' })).toBeNull()+ })++ it('offers resend on an assistant error bubble (the most common retry case)', () => {+ const user = userMessageWithAttachments()+ const errorReply: AgentChatMessage = {+ id: 'assistant-error',+ role: 'assistant',+ content: 'LLM blew up',+ timestamp: 2,+ isError: true,+ errorCode: 'LLM_MODEL_OVERLOADED',+ }+ messages = [user, errorReply]+ groupedMessages = [+ { role: 'user', items: [user] },+ { role: 'assistant', items: [errorReply] },+ ]++ render(<ChatThread />)++ fireEvent.click(screen.getByRole('button', { name: 'Resend prompt' }))+ expect(getComposerDraft('chat-1')).toBe('Summarize the chart with the plugin')+ expect(addComposerImageAttachments).toHaveBeenCalledTimes(1)+ })+})diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.attachmentPreview.test.tsx b/desktop-app/ui/src/components/agents/__tests__/chatThread.attachmentPreview.test.tsxnew file mode 100644index 000000000..ded558c90--- /dev/null+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.attachmentPreview.test.tsx@@ -0,0 +1,181 @@+// @vitest-environment jsdom+/**+ * BUG-176 — a user-attached image in a SENT message must be viewable. The+ * inert chip (image icon + filename) gains a preview trigger that opens the+ * shared `GfsImagePreview` modal with the attachment's inline base64 bytes+ * (no GFS round-trip). Legacy parsed `[Attached images]` chips (labels only,+ * no bytes) stay inert.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { buildLoadedChatSemanticModels } from '../../../lib/chatMessageSemantics'+import type { AgentChatMessage, TaskProgress } from '../../../uiTypes'+// vi.mock calls are hoisted above this import, so ChatThread binds the mocks.+import { ChatThread } from '../ChatThread'++const navValue = { selectedAgent: 'agent-x', handleSelectChatAgent: vi.fn() }+const notificationsValue = { decideApproval: vi.fn() }+const chatListValue = { chatList: [], chatListLoading: false, sessionStateByChatId: {} }+const actionsValue = {+ chatEndRef: { current: null },+ handleSelectChat: vi.fn(),+ handleRenameChat: vi.fn(),+ handleDeleteChat: vi.fn(),+}+const mcpRuntimeValue = { cancelTask: vi.fn() }+let messages: AgentChatMessage[] = []++vi.mock('@contexts/NavigationContext', () => ({ useNavigationContext: () => navValue }))+vi.mock('@contexts/NotificationsContext', () => ({+ useNotificationsContext: () => notificationsValue,+}))+vi.mock('@contexts/ChatListContext', () => ({ useChatListContext: () => chatListValue }))+vi.mock('@contexts/AgentChatActionsContext', () => ({+ useAgentChatActionsContext: () => actionsValue,+}))+vi.mock('@contexts/McpRuntimeContext', () => ({ useMcpRuntimeContext: () => mcpRuntimeValue }))+vi.mock('@contexts/ChatThreadStateContext', () => ({+ useChatThreadStateContext: () => ({+ activeMessages: messages,+ groupedMessages: [{ role: 'user', items: messages }],+ chatMessagesLoading: false,+ hasOlderMessages: false,+ olderMessagesLoading: false,+ handleLoadOlderMessages: vi.fn(),+ activeChatId: 'chat-1',+ activityByMessageId: {},+ progressByMessageId: {} as Record<string, TaskProgress>,+ localSearchQuery: '',+ localSearchCurrentMatch: null,+ semanticModelsByMessageId: new Map(+ buildLoadedChatSemanticModels(messages).map(model => [model.messageId, model])+ ),+ }),+}))+vi.mock('../InFlightAssistantPlaceholder', () => ({ InFlightAssistantPlaceholder: () => null }))+vi.mock('../NudgeArea', () => ({ NudgeArea: () => null }))+vi.mock('../ChatStateBadge', () => ({ ChatStateBadge: () => null }))+vi.mock('@components/MessageArtifactActions', () => ({ MessageArtifactActions: () => null }))++const actEnvGlobal = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+actEnvGlobal.IS_REACT_ACT_ENVIRONMENT = true++/** base64 of bytes [1, 2, 3] — small enough to decode synchronously. */+const PNG_BASE64 = 'AQID'++beforeEach(() => {+ Object.defineProperty(URL, 'createObjectURL', {+ configurable: true,+ value: vi.fn(() => 'blob:attachment-preview'),+ })+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })+})++afterEach(() => {+ cleanup()+ messages = []+ vi.clearAllMocks()+ vi.restoreAllMocks()+})++describe('ChatThread uploaded-image attachment preview (BUG-176)', () => {+ it('opens the shared GfsImagePreview modal when the sent-image chip is clicked', async () => {+ messages = [+ {+ id: 'msg-1',+ role: 'user',+ content: 'What is in this screenshot?',+ timestamp: 1,+ attachments: [+ {+ id: 'image-1',+ type: 'uploaded_file',+ label: 'Screenshot 2026-09-21 at 13.32.30.png',+ tooltip: 'Uploaded File - 1 KB',+ filename: 'Screenshot 2026-09-21 at 13.32.30.png',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: PNG_BASE64,+ sizeBytes: 3,+ },+ ],+ },+ ]+ render(<ChatThread />)++ // The chip body is a real button (same trigger contract as the composer).+ const trigger = screen.getByRole('button', { name: /Screenshot 2026-09-21/i })+ expect(trigger.classList.contains('message-attachment-preview-trigger')).toBe(true)+ expect(screen.queryByRole('dialog')).toBeNull()++ fireEvent.click(trigger)++ const dialog = await screen.findByRole('dialog')+ expect(dialog.getAttribute('aria-modal')).toBe('true')+ const heading = screen.getByRole('heading', { name: /Screenshot 2026-09-21/i, level: 3 })+ expect(heading).toBeTruthy()+ const img = await screen.findByAltText(/Preview of Screenshot 2026-09-21/i)+ expect(img.getAttribute('src')).toBe('blob:attachment-preview')+ })++ it('closes the preview from the modal close button', async () => {+ messages = [+ {+ id: 'msg-2',+ role: 'user',+ content: 'and this one?',+ timestamp: 1,+ attachments: [+ {+ id: 'image-2',+ type: 'uploaded_file',+ label: 'photo.png',+ filename: 'photo.png',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: PNG_BASE64,+ sizeBytes: 3,+ },+ ],+ },+ ]+ render(<ChatThread />)+ fireEvent.click(screen.getByRole('button', { name: /photo\.png/i }))+ expect(await screen.findByRole('dialog')).toBeTruthy()++ fireEvent.click(screen.getByRole('button', { name: 'Close image preview' }))++ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('keeps chips inert when the attachment carries no image bytes (parsed history)', () => {+ messages = [+ {+ id: 'msg-3',+ role: 'user',+ content: 'legacy',+ timestamp: 1,+ attachments: [+ {+ id: 'parsed:uploaded_file:0:old-shot.png',+ type: 'uploaded_file',+ label: 'old-shot.png',+ },+ {+ id: 'pdf-1',+ type: 'uploaded_file',+ label: 'contract.pdf',+ mimeType: 'application/pdf',+ },+ ],+ },+ ]+ const { container } = render(<ChatThread />)++ expect(screen.getByText('old-shot.png')).toBeTruthy()+ expect(screen.getByText('contract.pdf')).toBeTruthy()+ // No trigger button and no preview modal for byte-less chips.+ expect(container.querySelector('.message-attachment-preview-trigger')).toBeNull()+ expect(screen.queryByRole('dialog')).toBeNull()+ })+})diff --git a/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsx b/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsxindex 5f4c936e9..d15f7eef2 100644--- a/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsx@@ -183,3 +183,119 @@ describe('NudgeArea (D.5b)', () => {expect(container.firstChild).toBeNull()})})++describe('NudgeArea dismissal (TASK-228)', () => {+ /** Live, key-aware fake: emits flow through `emit` so later tiers of a task+ * (and new tasks) reach an already-mounted NudgeArea. */+ function liveKeyedTracker(byKey: Map<string, TaskState>) {+ const listeners = new Map<string, (s: TaskState) => void>()+ const tracker = {+ get: (key: string) => byKey.get(key),+ subscribe: (key: string, fn: (s: TaskState) => void) => {+ listeners.set(key, fn)+ const s = byKey.get(key)+ if (s) fn(s)+ return () => {+ listeners.delete(key)+ }+ },+ start: vi.fn(),+ rejoinIfRunning: vi.fn(),+ ack: vi.fn(),+ cancel: vi.fn(async () => undefined),+ setCallbacks: vi.fn(),+ } as unknown as TaskTracker+ const emit = (key: string, next: TaskState) => {+ byKey.set(key, next)+ listeners.get(key)?.(next)+ }+ return { tracker, emit }+ }++ function nudgeElement(tracker: TaskTracker, chatId = 'c1') {+ return (+ <AgentTaskTrackerContext.Provider value={tracker}>+ <NudgeArea+ agentRef="agent-x"+ chatId={chatId}+ onStartNewChat={vi.fn()}+ onRefreshState={vi.fn()}+ />+ </AgentTaskTrackerContext.Provider>+ )+ }++ it('renders a dismiss control on every tier', () => {+ for (const ageMs of [150_000, 400_000, 1_000_000]) {+ const { unmount } = renderNudge(task(ageMs))+ expect(screen.getByRole('button', { name: /dismiss this suggestion/i })).toBeTruthy()+ unmount()+ }+ })++ it('removes the card on dismiss and keeps it hidden for later tiers of the same task', () => {+ const byKey = new Map<string, TaskState>([['agent-x::c1', task(150_000)]])+ const { tracker, emit } = liveKeyedTracker(byKey)+ const { container } = render(nudgeElement(tracker))+ expect(screen.getByText(/taking longer than usual/i)).toBeTruthy()++ act(() => {+ screen+ .getByRole('button', { name: /dismiss this suggestion/i })+ .dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })+ expect(container.firstChild).toBeNull()++ // Same task ages into T4 → the tracker keeps emitting, but the dismissal+ // is keyed to the task, so no later tier may re-show the card.+ act(() => {+ emit('agent-x::c1', task(400_000))+ })+ expect(container.firstChild).toBeNull()+ })++ it('shows the nudge again for a NEW task in the same chat', () => {+ const first = task(150_000)+ const byKey = new Map<string, TaskState>([['agent-x::c1', first]])+ const { tracker, emit } = liveKeyedTracker(byKey)+ const { container } = render(nudgeElement(tracker))++ act(() => {+ screen+ .getByRole('button', { name: /dismiss this suggestion/i })+ .dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })+ expect(container.firstChild).toBeNull()++ // A different task id → fresh nudges.+ act(() => {+ emit('agent-x::c1', task(150_000, { taskId: 't2', userMessageId: 'm2' }))+ })+ expect(screen.getByText(/taking longer than usual/i)).toBeTruthy()+ })++ it('keeps a dismissal across a chat switch away and back (same task)', () => {+ const byKey = new Map<string, TaskState>([['agent-x::c1', task(150_000)]])+ const { tracker } = liveKeyedTracker(byKey)+ const { container, rerender } = render(nudgeElement(tracker, 'c1'))+ expect(screen.getByText(/taking longer than usual/i)).toBeTruthy()++ act(() => {+ screen+ .getByRole('button', { name: /dismiss this suggestion/i })+ .dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })+ expect(container.firstChild).toBeNull()++ // Switch to c2 (no task) and back to c1 — the same task is still running+ // and must stay dismissed.+ act(() => {+ rerender(nudgeElement(tracker, 'c2'))+ })+ expect(container.firstChild).toBeNull()+ act(() => {+ rerender(nudgeElement(tracker, 'c1'))+ })+ expect(container.firstChild).toBeNull()+ })+})diff --git a/desktop-app/ui/src/lib/__tests__/chatMessageAttachments.test.ts b/desktop-app/ui/src/lib/__tests__/chatMessageAttachments.test.tsindex e00625002..b556874fa 100644--- a/desktop-app/ui/src/lib/__tests__/chatMessageAttachments.test.ts+++ b/desktop-app/ui/src/lib/__tests__/chatMessageAttachments.test.ts@@ -95,6 +95,29 @@ describe('chat message attachments', () => {).toEqual(['first', 'logo.png', 'second'])})+ it('keeps the image bytes on uploaded_file display attachments (BUG-176 chip preview)', () => {+ const images: ComposerImageAttachment[] = [+ {+ id: 'image:shot',+ name: 'shot.png',+ mimeType: 'image/png',+ dataBase64: 'AQID',+ sizeBytes: 3,+ previewDataUrl: 'blob:shot',+ },+ ]++ expect(buildChatMessageAttachments(images, [])[0]).toMatchObject({+ type: 'uploaded_file',+ label: 'shot.png',+ filename: 'shot.png',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: 'AQID',+ sizeBytes: 3,+ })+ })+it('builds downloadable generated-file attachments from task responses', () => {const attachments = buildResponseFileAttachments({attachments: [diff --git a/desktop-app/ui/src/lib/__tests__/composerResend.test.ts b/desktop-app/ui/src/lib/__tests__/composerResend.test.tsnew file mode 100644index 000000000..9116f5bea--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/composerResend.test.ts@@ -0,0 +1,285 @@+import { describe, expect, it } from 'vitest'+import type { ChatMessageAttachment } from '../../../../src/types'+import {+ buildComposerResendDraft,+ findNearestPrecedingUserMessage,+ parseStructuredResendReferences,+} from '../composerResend'++function uploadedFileChip(overrides: Partial<ChatMessageAttachment> = {}): ChatMessageAttachment {+ return {+ id: 'img-1',+ type: 'uploaded_file',+ label: 'chart.png',+ addedOrder: 0,+ filename: 'chart.png',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: 'aGVsbG8=',+ sizeBytes: 5,+ ...overrides,+ }+}++describe('parseStructuredResendReferences', () => {+ it('extracts full-identity references from a USER-ATTACHED CONTEXT block', () => {+ const content = [+ 'Analyze this.',+ '',+ 'USER-ATTACHED CONTEXT: The user selected these capabilities/files for this message.',+ 'Plugins: profits/revenue. Use workflow tools for these plugin names.',+ 'Connectors: github-x. Use MCP tools.',+ 'Agent Files: shared-fs/notes/todo.md. Inspect these paths.',+ 'Global Files: Report (gfs://drive-7/res-9). Resolve each gfs:// URI.',+ ].join('\n')++ const structured = parseStructuredResendReferences(content)++ expect(structured.plugin).toEqual([{ namespace: 'profits', name: 'revenue' }])+ expect(structured.connector).toEqual([{ name: 'github-x' }])+ expect(structured.agentFile).toEqual([{ filesystemName: 'shared-fs', path: 'notes/todo.md' }])+ expect(structured.globalFile).toEqual([+ { label: 'Report', drive: 'drive-7', resourceId: 'res-9', gfsUri: 'gfs://drive-7/res-9' },+ ])+ })++ it('returns empty collections when the content carries no context block', () => {+ const structured = parseStructuredResendReferences('Just a plain message')+ expect(structured).toEqual({ plugin: [], connector: [], agentFile: [], globalFile: [] })+ })+})++describe('buildComposerResendDraft', () => {+ it('re-attaches an uploaded file with its bytes and preserves the visible text', () => {+ const draft = buildComposerResendDraft({+ content: 'Summarize the chart',+ attachments: [uploadedFileChip()],+ })++ expect(draft.content).toBe('Summarize the chart')+ expect(draft.imageAttachments).toHaveLength(1)+ expect(draft.imageAttachments[0]).toMatchObject({+ name: 'chart.png',+ mimeType: 'image/png',+ dataBase64: 'aGVsbG8=',+ sizeBytes: 5,+ previewDataUrl: 'data:image/png;base64,aGVsbG8=',+ })+ expect(draft.referenceAttachments).toEqual([])+ expect(draft.unrestorable).toEqual([])+ })++ it('re-applies plugin indicators from the structured context block with full identity', () => {+ const content = [+ 'Run the analysis',+ 'USER-ATTACHED CONTEXT: The user selected these capabilities/files for this message.',+ 'Plugins: profits/revenue, ops/deploy. Use workflow tools.',+ 'Connectors: github-x. Use MCP tools.',+ 'Agent Files: shared-fs/notes/todo.md. Inspect these paths.',+ 'Global Files: Report (gfs://drive-7/res-9). Resolve each gfs:// URI.',+ ].join('\n')++ const draft = buildComposerResendDraft({ content, attachments: [] })++ expect(draft.content).toBe('Run the analysis')+ expect(draft.imageAttachments).toEqual([])+ expect(draft.referenceAttachments).toEqual([+ {+ id: 'plugin:profits:revenue',+ type: 'plugin',+ namespace: 'profits',+ name: 'revenue',+ label: 'revenue',+ },+ {+ id: 'plugin:ops:deploy',+ type: 'plugin',+ namespace: 'ops',+ name: 'deploy',+ label: 'deploy',+ },+ { id: 'connector:github-x', type: 'connector', name: 'github-x', label: 'github-x' },+ {+ id: 'agent-file:resend:shared-fs:notes/todo.md',+ type: 'agent_file',+ contextId: '',+ filesystemName: 'shared-fs',+ path: 'notes/todo.md',+ kind: 'file',+ label: 'todo.md',+ },+ {+ id: 'global-file:resend:gfs://drive-7/res-9',+ type: 'global_file',+ resourceId: 'res-9',+ drive: 'drive-7',+ gfsUri: 'gfs://drive-7/res-9',+ label: 'Report',+ },+ ])+ })++ it('keeps the structured plugin identity when the message also carries label chips', () => {+ // Locally optimistic messages store chips (label = recipe name only) while+ // the server-authoritative content embeds "Plugins: ns/name". Both present:+ // the structured identity must win over the bare chip label.+ const content = [+ 'Run it',+ 'USER-ATTACHED CONTEXT: The user selected these capabilities/files for this message.',+ 'Plugins: profits/revenue. Use workflow tools.',+ ].join('\n')+ const draft = buildComposerResendDraft({+ content,+ attachments: [{ id: 'chip-1', type: 'plugin', label: 'revenue', addedOrder: 0 }],+ })++ expect(draft.referenceAttachments).toEqual([+ {+ id: 'plugin:profits:revenue',+ type: 'plugin',+ namespace: 'profits',+ name: 'revenue',+ label: 'revenue',+ },+ ])+ })++ it('re-applies a plugin indicator from a chip-only message, splitting ns/name labels', () => {+ const draft = buildComposerResendDraft({+ content: 'Run it',+ attachments: [{ id: 'chip-1', type: 'plugin', label: 'profits/revenue', addedOrder: 0 }],+ })++ expect(draft.referenceAttachments).toEqual([+ {+ id: 'plugin:profits:revenue',+ type: 'plugin',+ namespace: 'profits',+ name: 'revenue',+ label: 'revenue',+ },+ ])+ })++ it('falls back to a name-only plugin reference when the chip label has no namespace', () => {+ const draft = buildComposerResendDraft({+ content: 'Run it',+ attachments: [{ id: 'chip-1', type: 'plugin', label: 'revenue', addedOrder: 0 }],+ })++ expect(draft.referenceAttachments).toEqual([+ {+ id: 'plugin:resend:revenue',+ type: 'plugin',+ namespace: '',+ name: 'revenue',+ label: 'revenue',+ },+ ])+ })++ it('reports legacy label-only uploaded files as unrestorable instead of dropping them silently', () => {+ const draft = buildComposerResendDraft({+ content: 'Analyze',+ attachments: [{ id: 'legacy-1', type: 'uploaded_file', label: 'photo.jpg', addedOrder: 0 }],+ })++ expect(draft.imageAttachments).toEqual([])+ expect(draft.unrestorable).toEqual([{ type: 'uploaded_file', label: 'photo.jpg' }])+ })++ it('never re-applies response_file artifacts (they belong to the old reply, not the prompt)', () => {+ const draft = buildComposerResendDraft({+ content: 'Build the report',+ attachments: [+ {+ id: 'gen-1',+ type: 'response_file',+ label: 'report.md',+ filename: 'report.md',+ mimeType: 'text/markdown',+ encoding: 'base64',+ dataBase64: 'IyByZXBvcnQ=',+ },+ ],+ })++ expect(draft.imageAttachments).toEqual([])+ expect(draft.referenceAttachments).toEqual([])+ expect(draft.unrestorable).toEqual([])+ })++ it('uses the parsed legacy markers when the message carries no attachments array', () => {+ const content = [+ 'Please analyze the attached image(s).',+ '[Attached images]',+ '- screenshot.png',+ ].join('\n')++ const draft = buildComposerResendDraft({ content, attachments: [] })++ expect(draft.content).toBe('Please analyze the attached image(s).')+ expect(draft.imageAttachments).toEqual([])+ expect(draft.unrestorable).toEqual([{ type: 'uploaded_file', label: 'screenshot.png' }])+ })++ it('rejects non-image uploaded files for the composer (picker accepts jpeg/png only)', () => {+ const draft = buildComposerResendDraft({+ content: 'Here',+ attachments: [+ uploadedFileChip({+ id: 'doc-1',+ label: 'notes.txt',+ filename: 'notes.txt',+ mimeType: 'text/plain',+ }),+ ],+ })++ expect(draft.imageAttachments).toEqual([])+ expect(draft.unrestorable).toEqual([{ type: 'uploaded_file', label: 'notes.txt' }])+ })+})++describe('findNearestPrecedingUserMessage', () => {+ type RoleItem = { role: 'user' | 'assistant' | 'system'; content: string; attachments: [] }+ const userA: RoleItem = { role: 'user', content: 'first prompt', attachments: [] }+ const assistantA: RoleItem = { role: 'assistant', content: 'first reply', attachments: [] }+ const userB: RoleItem = { role: 'user', content: 'second prompt', attachments: [] }+ const assistantB: RoleItem = { role: 'assistant', content: 'second reply', attachments: [] }+ const groups: Array<{ role: 'user' | 'assistant' | 'system'; items: RoleItem[] }> = [+ { role: 'user', items: [userA] },+ { role: 'assistant', items: [assistantA] },+ { role: 'user', items: [userB] },+ { role: 'assistant', items: [assistantB] },+ ]++ it('returns the last user message of the nearest preceding user group', () => {+ expect(findNearestPrecedingUserMessage(groups, 3)).toBe(userB)+ })++ it('skips consecutive assistant groups when walking back', () => {+ const followUp: RoleItem = { role: 'assistant', content: 'follow-up', attachments: [] }+ const multi: Array<{ role: 'user' | 'assistant' | 'system'; items: RoleItem[] }> = [+ { role: 'user', items: [userA] },+ { role: 'assistant', items: [assistantA] },+ { role: 'assistant', items: [followUp] },+ ]+ expect(findNearestPrecedingUserMessage(multi, 2)).toBe(userA)+ })++ it('returns the last item when a user group holds several messages', () => {+ const burstFirst: RoleItem = { role: 'user', content: 'part 1', attachments: [] }+ const burstLast: RoleItem = { role: 'user', content: 'part 2 (trigger)', attachments: [] }+ const withBurst: Array<{ role: 'user' | 'assistant' | 'system'; items: RoleItem[] }> = [+ { role: 'user', items: [burstFirst, burstLast] },+ { role: 'assistant', items: [assistantA] },+ ]+ expect(findNearestPrecedingUserMessage(withBurst, 1)).toBe(burstLast)+ })++ it('returns null when no user group precedes the assistant reply', () => {+ const assistantOnly = [{ role: 'assistant' as const, items: [assistantA] }]+ expect(findNearestPrecedingUserMessage(assistantOnly, 0)).toBeNull()+ })+})diff --git a/desktop-app/ui/src/lib/chatMessageAttachments.ts b/desktop-app/ui/src/lib/chatMessageAttachments.tsindex 295e9cb32..ebdd4294b 100644--- a/desktop-app/ui/src/lib/chatMessageAttachments.ts+++ b/desktop-app/ui/src/lib/chatMessageAttachments.ts@@ -100,6 +100,14 @@ export function buildChatMessageAttachments(label: attachment.name,tooltip: formatUploadedFileTooltip(attachment),addedOrder: attachmentOrder(attachment, fallbackIndex),+ // BUG-176: keep the image bytes on the display attachment so the+ // sent-message chip can reopen the shared image preview. Persisted with+ // the user message (same inline-base64 contract as response_file).+ filename: attachment.name,+ mimeType: attachment.mimeType,+ encoding: 'base64',+ dataBase64: attachment.dataBase64,+ sizeBytes: attachment.sizeBytes,}})return [...referenceItems, ...imageItems].sort(diff --git a/desktop-app/ui/src/lib/composerResend.ts b/desktop-app/ui/src/lib/composerResend.tsnew file mode 100644index 000000000..571f76d24--- /dev/null+++ b/desktop-app/ui/src/lib/composerResend.ts@@ -0,0 +1,324 @@+/**+ * TASK-42 — resend draft builder.+ *+ * Turns a sent USER message back into composer input: the visible text for the+ * draft, inline image bytes re-attached as composer image attachments, and+ * plugin/connector/agent-file/global-file indicators re-applied as composer+ * references.+ *+ * Fidelity ladder (a message can carry its inputs in two places):+ * 1. The raw content's `USER-ATTACHED CONTEXT:` block (server-authoritative+ * messages) — carries full identity (plugin `ns/name`, agent-file+ * `filesystem/path`, global-file `label (gfs://drive/resourceId)`).+ * 2. The persisted `attachments` chips (locally optimistic messages) —+ * uploaded files carry their base64 bytes, references carry labels only.+ * Labels that still encode the identity (`ns/name`) are split back into+ * structured fields; bare labels become best-effort references so the+ * indicator chip still re-appears (re-selecting from the + menu restores+ * the exact prompt coverage).+ *+ * `response_file` attachments are never re-applied: they are artifacts the+ * previous reply generated, not inputs of the resent prompt.+ */+import type { ChatMessageAttachment } from '../../../src/types'+import type {+ AgentChatMessage,+ ComposerImageAttachment,+ ComposerReferenceAttachment,+} from '../uiTypes'+import { parseChatMessageDisplay } from './chatMessageAttachments'++export type ComposerResendDraft = {+ /** Visible text for the composer draft (context block stripped). */+ content: string+ imageAttachments: ComposerImageAttachment[]+ referenceAttachments: ComposerReferenceAttachment[]+ /** Chips that could not be rebuilt (e.g. legacy label-only uploaded files). */+ unrestorable: Array<{ type: ChatMessageAttachment['type']; label: string }>+}++type StructuredPlugin = { namespace: string; name: string }+type StructuredConnector = { name: string }+type StructuredAgentFile = { filesystemName: string; path: string }+type StructuredGlobalFile = {+ label: string+ drive: string+ resourceId: string+ gfsUri: string+}++type StructuredReferences = {+ plugin: StructuredPlugin[]+ connector: StructuredConnector[]+ agentFile: StructuredAgentFile[]+ globalFile: StructuredGlobalFile[]+}++const USER_ATTACHED_CONTEXT_MARKER = 'USER-ATTACHED CONTEXT:'++/** Mirrors the legacy list format: first sentence, comma-separated items. */+function splitAttachmentItems(value: string): string[] {+ const segment = (value.split(/\.\s+/)[0] ?? '').replace(/\.\s*$/, '')+ return segment+ .split(',')+ .map(item => item.trim())+ .filter(Boolean)+}++function parseStructuredGlobalFile(item: string): StructuredGlobalFile {+ const labeled = item.match(/^(.*?)\s+\((gfs:\/\/[^)]+)\)$/i)+ if (labeled?.[1] && labeled[2]) {+ return parseGlobalFileFromUri(labeled[1].trim(), labeled[2])+ }+ if (/^gfs:\/\/[^/]+\//i.test(item)) {+ return parseGlobalFileFromUri('', item)+ }+ return { label: item, drive: '', resourceId: '', gfsUri: '' }+}++function parseGlobalFileFromUri(label: string, gfsUri: string): StructuredGlobalFile {+ const uri = gfsUri.match(/^gfs:\/\/([^/]+)\/(.+)$/i)+ if (!uri?.[1] || uri[2] === undefined) {+ return { label, drive: '', resourceId: '', gfsUri }+ }+ return { label, drive: uri[1], resourceId: uri[2], gfsUri }+}++function pathBasename(path: string): string {+ return path.split('/').filter(Boolean).pop() ?? path+}++/**+ * Extracts full-identity references from the `USER-ATTACHED CONTEXT:` block a+ * sent message embeds (the same block `parseChatMessageDisplay` strips for+ * display). Only this source carries plugin namespaces, agent-file filesystem+ * paths, and global-file URIs.+ */+export function parseStructuredResendReferences(content: string): StructuredReferences {+ const result: StructuredReferences = { plugin: [], connector: [], agentFile: [], globalFile: [] }+ const lines = content.split('\n')+ let markerIndex = lines.findIndex(line => line.trim().startsWith(USER_ATTACHED_CONTEXT_MARKER))+ if (markerIndex === -1) return result+ for (let index = markerIndex + 1; index < lines.length; index += 1) {+ const line = (lines[index] ?? '').trim()+ if (line.startsWith('Plugins:')) {+ for (const item of splitAttachmentItems(line.slice('Plugins:'.length))) {+ const qualified = item.match(/^([^/\s]+)\/([^/\s]+)$/)+ result.plugin.push(+ qualified?.[1] && qualified[2]+ ? { namespace: qualified[1], name: qualified[2] }+ : { namespace: '', name: item }+ )+ }+ } else if (line.startsWith('Connectors:')) {+ for (const item of splitAttachmentItems(line.slice('Connectors:'.length))) {+ result.connector.push({ name: item })+ }+ } else if (line.startsWith('Agent Files:')) {+ for (const item of splitAttachmentItems(line.slice('Agent Files:'.length))) {+ const slash = item.indexOf('/')+ result.agentFile.push(+ slash > 0+ ? { filesystemName: item.slice(0, slash), path: item.slice(slash + 1) }+ : { filesystemName: '', path: item }+ )+ }+ } else if (line.startsWith('Global Files:')) {+ for (const item of splitAttachmentItems(line.slice('Global Files:'.length))) {+ result.globalFile.push(parseStructuredGlobalFile(item))+ }+ }+ }+ return result+}++function buildResendImageAttachment(+ chip: ChatMessageAttachment,+ index: number+): ComposerImageAttachment | null {+ if (chip.type !== 'uploaded_file') return null+ if (chip.encoding !== 'base64') return null+ const dataBase64 = typeof chip.dataBase64 === 'string' ? chip.dataBase64 : ''+ if (!dataBase64) return null+ const mimeType =+ chip.mimeType === 'image/jpeg' || chip.mimeType === 'image/png' ? chip.mimeType : null+ if (!mimeType) return null+ return {+ id: `resend-image:${chip.id}:${index}`,+ ...(chip.addedOrder !== undefined ? { addedOrder: chip.addedOrder } : {}),+ name: chip.filename || chip.label,+ mimeType,+ dataBase64,+ sizeBytes: chip.sizeBytes ?? Math.floor((dataBase64.length * 3) / 4),+ previewDataUrl: `data:${mimeType};base64,${dataBase64}`,+ }+}++function buildPluginReference(+ label: string,+ structured: StructuredPlugin[]+): Extract<ComposerReferenceAttachment, { type: 'plugin' }> {+ const match =+ structured.find(entry => entry.namespace && `${entry.namespace}/${entry.name}` === label) ??+ structured.find(entry => entry.namespace && entry.name === label) ??+ null+ if (match) {+ return {+ id: `plugin:${match.namespace}:${match.name}`,+ type: 'plugin',+ namespace: match.namespace,+ name: match.name,+ label: match.name,+ }+ }+ const qualified = label.match(/^([^/\s]+)\/([^/\s]+)$/)+ if (qualified?.[1] && qualified[2]) {+ return {+ id: `plugin:${qualified[1]}:${qualified[2]}`,+ type: 'plugin',+ namespace: qualified[1],+ name: qualified[2],+ label: qualified[2],+ }+ }+ return { id: `plugin:resend:${label}`, type: 'plugin', namespace: '', name: label, label }+}++function buildConnectorReference(+ label: string,+ structured: StructuredConnector[]+): Extract<ComposerReferenceAttachment, { type: 'connector' }> {+ const name = structured.find(entry => entry.name === label)?.name ?? label+ return { id: `connector:${name}`, type: 'connector', name, label: name }+}++function buildAgentFileReference(+ label: string,+ structured: StructuredAgentFile[]+): Extract<ComposerReferenceAttachment, { type: 'agent_file' }> {+ const match =+ structured.find(+ entry =>+ entry.filesystemName &&+ `${entry.filesystemName}/${entry.path.replace(/^\/+/, '')}` === label+ ) ??+ structured.find(entry => entry.filesystemName && pathBasename(entry.path) === label) ??+ null+ if (match) {+ const normalizedPath = match.path.replace(/^\/+|\/+$/g, '')+ return {+ id: `agent-file:resend:${match.filesystemName}:${normalizedPath}`,+ type: 'agent_file',+ contextId: '',+ filesystemName: match.filesystemName,+ path: normalizedPath,+ kind: normalizedPath ? 'file' : 'directory',+ label: pathBasename(normalizedPath) || match.filesystemName,+ }+ }+ const normalizedLabel = label.replace(/^\/+|\/+$/g, '')+ return {+ id: `agent-file:resend:${normalizedLabel}`,+ type: 'agent_file',+ contextId: '',+ filesystemName: '',+ path: normalizedLabel,+ kind: 'file',+ label: pathBasename(normalizedLabel),+ }+}++function buildGlobalFileReference(+ label: string,+ structured: StructuredGlobalFile[]+): Extract<ComposerReferenceAttachment, { type: 'global_file' }> {+ const match =+ structured.find(entry => entry.gfsUri && entry.label === label) ??+ structured.find(entry => entry.gfsUri && pathBasename(entry.gfsUri) === label) ??+ null+ if (match) {+ return {+ id: `global-file:resend:${match.gfsUri}`,+ type: 'global_file',+ resourceId: match.resourceId,+ drive: match.drive,+ gfsUri: match.gfsUri,+ label: match.label || pathBasename(match.gfsUri),+ }+ }+ return {+ id: `global-file:resend:${label}`,+ type: 'global_file',+ resourceId: '',+ drive: '',+ gfsUri: '',+ label,+ }+}++/**+ * Builds the composer repopulation payload for a sent user message. Chip+ * resolution mirrors the thread's display precedence: the persisted+ * `attachments` array wins when present, otherwise the chips parsed from the+ * legacy/`USER-ATTACHED CONTEXT` content markers.+ */+export function buildComposerResendDraft(+ message: Pick<AgentChatMessage, 'content' | 'attachments'>+): ComposerResendDraft {+ const parsed = parseChatMessageDisplay(message.content)+ const chips = message.attachments?.length ? message.attachments : parsed.attachments+ const structured = parseStructuredResendReferences(message.content)+ const imageAttachments: ComposerImageAttachment[] = []+ const referenceAttachments: ComposerReferenceAttachment[] = []+ const unrestorable: ComposerResendDraft['unrestorable'] = []++ for (const [index, chip] of chips.entries()) {+ if (chip.type === 'uploaded_file') {+ const image = buildResendImageAttachment(chip, index)+ if (image) {+ imageAttachments.push(image)+ } else {+ unrestorable.push({ type: chip.type, label: chip.label })+ }+ continue+ }+ if (chip.type === 'response_file') continue+ if (chip.type === 'plugin') {+ referenceAttachments.push(buildPluginReference(chip.label, structured.plugin))+ continue+ }+ if (chip.type === 'connector') {+ referenceAttachments.push(buildConnectorReference(chip.label, structured.connector))+ continue+ }+ if (chip.type === 'agent_file') {+ referenceAttachments.push(buildAgentFileReference(chip.label, structured.agentFile))+ continue+ }+ if (chip.type === 'global_file') {+ referenceAttachments.push(buildGlobalFileReference(chip.label, structured.globalFile))+ }+ }++ return { content: parsed.content, imageAttachments, referenceAttachments, unrestorable }+}++/**+ * TASK-42 resend rule for ASSISTANT messages: "resending" a reply re-issues the+ * prompt that produced it. Walks the rendered groups backwards from `groupIndex`+ * to the nearest user group and returns its LAST message (the turn trigger);+ * `null` when the reply has no preceding user message to re-issue.+ */+export function findNearestPrecedingUserMessage<+ T extends Pick<AgentChatMessage, 'role' | 'content' | 'attachments'>,+>(+ groups: Array<{ role: 'user' | 'assistant' | 'system'; items: T[] }>,+ groupIndex: number+): T | null {+ for (let index = groupIndex - 1; index >= 0; index -= 1) {+ const group = groups[index]+ if (!group || group.role !== 'user') continue+ return group.items.at(-1) ?? null+ }+ return null+}diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.cssindex 661811eba..47b0ee36e 100644--- a/desktop-app/ui/src/styles.css+++ b/desktop-app/ui/src/styles.css@@ -7141,6 +7141,33 @@ h3 {padding-inline: var(--space-1);}+/* BUG-176: sent-message image chips open the shared GfsImagePreview modal.+ * Same trigger contract as the composer's chip (transparent inline-flex+ * button inside the chip frame, zoom-in cursor, keyboard focus ring). */+.message-attachment-preview-trigger {+ appearance: none;+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ min-width: 0;+ flex: 1 1 auto;+ height: 100%;+ border: none;+ background: transparent;+ color: inherit;+ padding: 0;+ cursor: zoom-in;+ font: inherit;+ line-height: 1;+ text-align: left;+}++.message-attachment-preview-trigger:focus-visible {+ outline: 2px solid rgba(var(--focus-rgb), 0.56);+ outline-offset: 2px;+ border-radius: var(--radius-sm);+}+.chat-bubble.assistant {padding: 0;border-color: transparent;@@ -14512,20 +14539,52 @@ pre {}/* D.5b — time-aware nudges (rendered below the in-flight progress) */+/* TASK-228: the nudge renders as one contained card — banner + dismiss (×) in+ * a header row, mini-summary and the tier action in a footer row — instead of+ * loosely stacked rows. */.nudge-area {display: flex;flex-direction: column;- gap: var(--space-1-5);+ gap: var(--space-2);margin-top: var(--space-2);/* Cap the width so the nudge reads as a contained card instead of stretching* full-width with the chat (and growing on larger windows). */max-width: 460px;+ padding: var(--space-2);+ border: 1px solid var(--control-border);+ border-radius: var(--radius-control);+ background: var(--panel);+}++.nudge-area__header {+ display: flex;+ align-items: flex-start;+ gap: var(--space-1-5);+ min-width: 0;+}++.nudge-area__header .status-banner {+ flex: 1 1 auto;+ min-width: 0;+}++.nudge-area__dismiss {+ flex: 0 0 auto;+ margin: calc(-1 * var(--space-0-5)) calc(-1 * var(--space-1)) 0 0;+}++.nudge-area__footer {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: var(--space-1-5) var(--space-2);+ min-width: 0;}-/* The nudge's call-to-action: a clear soft button anchored bottom-right of the- * capped card rather than a faint full-width row. */+/* The nudge's call-to-action: anchored bottom-right of the card, level with+ * the mini-summary when one is present (T5), alone otherwise (T3). */.nudge-area-action {- align-self: flex-end;+ margin-left: auto;}.nudge-mini-summary {