Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop-app): enforce preview bounds and resend fidelity

Mc0d150784218
diff --git a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx b/desktop-app/ui/src/components/GfsImagePreview/Body.tsx
index 73c57a095..67cc4276f 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx
+++ b/desktop-app/ui/src/components/GfsImagePreview/Body.tsx
@@ -2,6 +2,7 @@ import { useEffect, useId, useRef, useState } from 'react'
import { Button, StatusBanner } from '@components/Common'
import { IconCopy } from '@components/SidebarNav/icons'
import { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'
+import { estimateBase64DecodedLength } from '@lib/base64Size'
import { describeGfsReadError } from '@lib/gfsGrantErrors'
import { assertGfsImagePreviewSize } from '@lib/gfsImagePreview'
import type { GfsImagePreviewBodyProps } from './types'
@@ -45,11 +46,10 @@ 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')
+ // Exactly one source is allowed (see GfsImagePreviewSource). Reject
+ // both missing and ambiguous sources before reading either one.
+ if ((dataBase64 === undefined) === (gfsUri === undefined)) {
+ throw new Error('Image preview requires exactly one 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
@@ -61,6 +61,7 @@ export function GfsImagePreviewBody({
// 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.
+ assertGfsImagePreviewSize(estimateBase64DecodedLength(dataBase64))
bytes = decodeBase64ToArrayBuffer(dataBase64)
assertGfsImagePreviewSize(bytes.byteLength)
} else {
diff --git a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx
index d3e557e32..41de06616 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx
+++ b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx
@@ -75,6 +75,40 @@ describe('GfsImagePreviewBody', () => {
expect(downloadPreview).not.toHaveBeenCalled()
})
+ it('rejects missing and ambiguous sources before decoding or downloading', async () => {
+ const downloadPreview = stubDownload(new Uint8Array([1]).buffer)
+ const atobSpy = vi.spyOn(window, 'atob')
+ render(<GfsImagePreviewBody byteLength={1} fileName="image.png" mimeType="image/png" />)
+ expect(await screen.findByText('Image preview requires exactly one source')).toBeTruthy()
+ cleanup()
+ render(
+ <GfsImagePreviewBody
+ byteLength={1}
+ fileName="image.png"
+ mimeType="image/png"
+ gfsUri="gfs://main/image-1"
+ dataBase64="AQ=="
+ />
+ )
+ expect(await screen.findByText('Image preview requires exactly one source')).toBeTruthy()
+ expect(downloadPreview).not.toHaveBeenCalled()
+ expect(atobSpy).not.toHaveBeenCalled()
+ })
+
+ it('rejects oversized inline base64 before calling atob even with a small size hint', async () => {
+ const atobSpy = vi.spyOn(window, 'atob')
+ render(
+ <GfsImagePreviewBody
+ byteLength={1}
+ fileName="image.png"
+ mimeType="image/png"
+ dataBase64={'A'.repeat(Math.ceil((GFS_IMAGE_PREVIEW_MAX_BYTES + 1) / 3) * 4)}
+ />
+ )
+ expect(await screen.findByText(/Image previews are limited to 10 MB/)).toBeTruthy()
+ expect(atobSpy).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/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index 292de723c..b3f08de7a 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -29,6 +29,7 @@ import {
} from '@constants/agents'
import { HTML_PREVIEW_INLINE_MAX_BYTES } from '@constants/htmlPreview'
import type { ChatMessageAttachment } from '../../../../src/types'
+import { estimateBase64DecodedLength } from '../../lib/base64Size'
import { chatMessageDomId } from '../../lib/chatLocalSearch'
import {
getChatMessageAttachmentTypeLabel,
@@ -256,7 +257,7 @@ function MessageAttachmentList({ attachments }: { attachments: ChatMessageAttach
// Base64 length overstates the decoded size by ~33%; the accurate
// 3/4 estimate keeps the 10 MB early-skip from refusing previews
// that are actually under the limit (PR #859 review).
- Math.floor(((previewAttachment.dataBase64 ?? '').length * 3) / 4)
+ estimateBase64DecodedLength(previewAttachment.dataBase64 ?? '')
}
fileName={previewAttachment.filename || previewAttachment.label}
dataBase64={previewAttachment.dataBase64}
diff --git a/desktop-app/ui/src/lib/__tests__/composerResend.test.ts b/desktop-app/ui/src/lib/__tests__/composerResend.test.ts
index 9116f5bea..4a899ca25 100644
--- a/desktop-app/ui/src/lib/__tests__/composerResend.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/composerResend.test.ts
@@ -161,20 +161,28 @@ describe('buildComposerResendDraft', () => {
])
})
- it('falls back to a name-only plugin reference when the chip label has no namespace', () => {
+ it('warns when a name-only plugin chip has no recoverable 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',
- },
+ expect(draft.referenceAttachments).toEqual([])
+ expect(draft.unrestorable).toEqual([{ type: 'plugin', label: 'revenue' }])
+ })
+
+ it('warns when file chips lack the path or URI needed to resend them', () => {
+ const draft = buildComposerResendDraft({
+ content: 'Read these',
+ attachments: [
+ { id: 'file', type: 'agent_file', label: 'todo.md' },
+ { id: 'global', type: 'global_file', label: 'Report' },
+ ],
+ })
+ expect(draft.referenceAttachments).toEqual([])
+ expect(draft.unrestorable).toEqual([
+ { type: 'agent_file', label: 'todo.md' },
+ { type: 'global_file', label: 'Report' },
])
})
diff --git a/desktop-app/ui/src/lib/base64Size.ts b/desktop-app/ui/src/lib/base64Size.ts
new file mode 100644
index 000000000..5092104f3
--- /dev/null
+++ b/desktop-app/ui/src/lib/base64Size.ts
@@ -0,0 +1,5 @@
+/** Upper bound for untrusted base64; padding makes the estimate exact for valid input. */
+export function estimateBase64DecodedLength(dataBase64: string): number {
+ const padding = dataBase64.endsWith('==') ? 2 : dataBase64.endsWith('=') ? 1 : 0
+ return Math.floor((dataBase64.length * 3) / 4) - padding
+}
diff --git a/desktop-app/ui/src/lib/composerResend.ts b/desktop-app/ui/src/lib/composerResend.ts
index 571f76d24..07deeb6c9 100644
--- a/desktop-app/ui/src/lib/composerResend.ts
+++ b/desktop-app/ui/src/lib/composerResend.ts
@@ -13,9 +13,8 @@
* 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).
+ * structured fields; bare labels without enough identity are reported as
+ * unrestorable so the composer never shows a chip that send will omit.
*
* `response_file` attachments are never re-applied: they are artifacts the
* previous reply generated, not inputs of the resent prompt.
@@ -26,6 +25,7 @@ import type {
ComposerImageAttachment,
ComposerReferenceAttachment,
} from '../uiTypes'
+import { estimateBase64DecodedLength } from './base64Size'
import { parseChatMessageDisplay } from './chatMessageAttachments'
export type ComposerResendDraft = {
@@ -149,7 +149,7 @@ function buildResendImageAttachment(
name: chip.filename || chip.label,
mimeType,
dataBase64,
- sizeBytes: chip.sizeBytes ?? Math.floor((dataBase64.length * 3) / 4),
+ sizeBytes: chip.sizeBytes ?? estimateBase64DecodedLength(dataBase64),
previewDataUrl: `data:${mimeType};base64,${dataBase64}`,
}
}
@@ -157,10 +157,11 @@ function buildResendImageAttachment(
function buildPluginReference(
label: string,
structured: StructuredPlugin[]
-): Extract<ComposerReferenceAttachment, { type: 'plugin' }> {
+): Extract<ComposerReferenceAttachment, { type: 'plugin' }> | null {
+ const nameMatches = structured.filter(entry => entry.namespace && entry.name === label)
const match =
structured.find(entry => entry.namespace && `${entry.namespace}/${entry.name}` === label) ??
- structured.find(entry => entry.namespace && entry.name === label) ??
+ (nameMatches.length === 1 ? nameMatches[0] : null) ??
null
if (match) {
return {
@@ -181,7 +182,7 @@ function buildPluginReference(
label: qualified[2],
}
}
- return { id: `plugin:resend:${label}`, type: 'plugin', namespace: '', name: label, label }
+ return null
}
function buildConnectorReference(
@@ -195,14 +196,17 @@ function buildConnectorReference(
function buildAgentFileReference(
label: string,
structured: StructuredAgentFile[]
-): Extract<ComposerReferenceAttachment, { type: 'agent_file' }> {
+): Extract<ComposerReferenceAttachment, { type: 'agent_file' }> | null {
+ const basenameMatches = structured.filter(
+ entry => entry.filesystemName && pathBasename(entry.path) === label
+ )
const match =
structured.find(
entry =>
entry.filesystemName &&
`${entry.filesystemName}/${entry.path.replace(/^\/+/, '')}` === label
) ??
- structured.find(entry => entry.filesystemName && pathBasename(entry.path) === label) ??
+ (basenameMatches.length === 1 ? basenameMatches[0] : null) ??
null
if (match) {
const normalizedPath = match.path.replace(/^\/+|\/+$/g, '')
@@ -216,22 +220,13 @@ function buildAgentFileReference(
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),
- }
+ return null
}
function buildGlobalFileReference(
label: string,
structured: StructuredGlobalFile[]
-): Extract<ComposerReferenceAttachment, { type: 'global_file' }> {
+): Extract<ComposerReferenceAttachment, { type: 'global_file' }> | null {
const match =
structured.find(entry => entry.gfsUri && entry.label === label) ??
structured.find(entry => entry.gfsUri && pathBasename(entry.gfsUri) === label) ??
@@ -246,14 +241,7 @@ function buildGlobalFileReference(
label: match.label || pathBasename(match.gfsUri),
}
}
- return {
- id: `global-file:resend:${label}`,
- type: 'global_file',
- resourceId: '',
- drive: '',
- gfsUri: '',
- label,
- }
+ return null
}
/**
@@ -284,7 +272,9 @@ export function buildComposerResendDraft(
}
if (chip.type === 'response_file') continue
if (chip.type === 'plugin') {
- referenceAttachments.push(buildPluginReference(chip.label, structured.plugin))
+ const reference = buildPluginReference(chip.label, structured.plugin)
+ if (reference) referenceAttachments.push(reference)
+ else unrestorable.push({ type: chip.type, label: chip.label })
continue
}
if (chip.type === 'connector') {
@@ -292,11 +282,15 @@ export function buildComposerResendDraft(
continue
}
if (chip.type === 'agent_file') {
- referenceAttachments.push(buildAgentFileReference(chip.label, structured.agentFile))
+ const reference = buildAgentFileReference(chip.label, structured.agentFile)
+ if (reference) referenceAttachments.push(reference)
+ else unrestorable.push({ type: chip.type, label: chip.label })
continue
}
if (chip.type === 'global_file') {
- referenceAttachments.push(buildGlobalFileReference(chip.label, structured.globalFile))
+ const reference = buildGlobalFileReference(chip.label, structured.globalFile)
+ if (reference) referenceAttachments.push(reference)
+ else unrestorable.push({ type: chip.type, label: chip.label })
}
}
diff --git a/desktop-app/ui/src/lib/imageHeaderDimensions.ts b/desktop-app/ui/src/lib/imageHeaderDimensions.ts
index a0ab258d2..0ae2284f2 100644
--- a/desktop-app/ui/src/lib/imageHeaderDimensions.ts
+++ b/desktop-app/ui/src/lib/imageHeaderDimensions.ts
@@ -56,6 +56,7 @@ function readJpegDimensions(bytes: Uint8Array): ImageHeaderDimensions | null {
while (pos < bytes.length && bytes[pos] === 0xff) pos += 1
if (pos >= bytes.length) return null
const marker = bytes[pos]
+ if (marker === undefined) return null
pos += 1
if (marker === 0x00) return null
if (marker === 0xd9) break