diff --git a/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts b/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts
index 6a4b93ee94..4dc0acdef8 100644
--- a/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts
+++ b/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts
@@ -26,6 +26,7 @@ import {
} from './attachedFilesDB'
import { sanitizeAttachmentName } from '../textFileUtils'
import { enumerateDir, isIgnoredPath, queryReadPermission, requestReadPermission } from './fsAccess'
+import { isRasterImageName } from './imageFiles'
export type AttachedFileStatus = 'indexing' | 'ready' | 'error' | 'locked' | 'unavailable'
@@ -59,6 +60,9 @@ export interface AttachedFile extends FileEntry {
* sanitize identically are different files even with equal stats. Falls back
* to `name` for rows persisted before provenance existed. */
sourceName?: string
+ /** A binary image (png, jpeg, …): kept so the session's preview can show it, but
+ * never line-indexed and never handed to the text tools. */
+ image?: boolean
}
/** A linked folder as a first-class object — consumers read this instead of re-grouping rows. */
@@ -128,8 +132,9 @@ export class AttachedFilesStore {
return undefined
}
readyFiles(): AttachedFile[] {
- // Folder-root placeholders aren't real files — never expose them to the read/search tools.
- return this.files.filter((f) => f.status === 'ready' && !f.isFolderRoot)
+ // Folder-root placeholders aren't real files and images have no lines — never expose
+ // either to the read/search tools.
+ return this.files.filter((f) => f.status === 'ready' && !f.isFolderRoot && !f.image)
}
get count(): number {
return this.files.length
@@ -259,7 +264,7 @@ export class AttachedFilesStore {
continue // silent no-op on re-link
}
- const reason = await this.#preflight(file)
+ const reason = await this.#preflight(file, rawPath)
if (reason) {
result.rejected.push({ name: sanitizeAttachmentName(rawPath), reason })
continue
@@ -315,7 +320,7 @@ export class AttachedFilesStore {
const files = await enumerateDir(dirHandle)
const sourceId = createLongHash()
for (const { file, path } of files) {
- if (!(await this.#sniffText(file))) {
+ if (!(await this.#admissible(file, path))) {
result.rejected.push({ name: path, reason: 'Not a text file' })
continue
}
@@ -497,11 +502,16 @@ export class AttachedFilesStore {
}
/** Returns a rejection reason, or undefined if the file may be linked. */
- async #preflight(file: File): Promise {
- if (!(await this.#sniffText(file))) return 'Not a text file'
+ async #preflight(file: File, rawPath: string): Promise {
+ if (!(await this.#admissible(file, rawPath))) return 'Not a text file'
return undefined
}
+ /** A file the store links: text, or a binary image by its name. */
+ async #admissible(file: Blob, path: string): Promise {
+ return isRasterImageName(path) || (await this.#sniffText(file))
+ }
+
async #sniffText(file: Blob): Promise {
try {
return await isTextFile(file)
@@ -521,6 +531,9 @@ export class AttachedFilesStore {
messageScoped?: boolean
id?: string
}): void {
+ // Message rows are decoded text by construction; every other row is judged by
+ // the name it had on disk.
+ const image = !p.messageScoped && isRasterImageName(p.sourceName ?? p.name)
this.files = [
...this.files,
{
@@ -530,7 +543,8 @@ export class AttachedFilesStore {
size: p.file.size,
lineIndex: [],
lineCount: 0,
- status: 'indexing',
+ status: image ? 'ready' : 'indexing',
+ image: image || undefined,
folder: p.folder,
sourceId: p.sourceId,
handle: p.handle,
@@ -539,7 +553,7 @@ export class AttachedFilesStore {
id: p.id
}
]
- void this.#indexFile(p.name, p.file)
+ if (!image) void this.#indexFile(p.name, p.file)
}
#pushPlaceholder(
@@ -576,7 +590,7 @@ export class AttachedFilesStore {
const folder = dirHandle.name
const children = await enumerateDir(dirHandle)
for (const { file, path } of children) {
- if (!(await this.#sniffText(file))) continue
+ if (!(await this.#admissible(file, path))) continue
const name = this.#claimName(path)
this.#pushIndexing({
name,
@@ -632,7 +646,7 @@ export class AttachedFilesStore {
const cur = existing.get(path)
if (!cur) {
// newly added on disk
- if (!(await this.#sniffText(file))) continue
+ if (!(await this.#admissible(file, path))) continue
const name = this.#claimName(path)
this.#pushIndexing({
name,
@@ -649,9 +663,11 @@ export class AttachedFilesStore {
// content changed → re-read + re-index. Patch by row identity — a
// message attachment may share the display name.
this.files = this.files.map((f) =>
- f === cur ? { ...f, file, size: file.size, status: 'indexing' } : f
+ f === cur
+ ? { ...f, file, size: file.size, status: cur.image ? 'ready' : 'indexing' }
+ : f
)
- void this.#indexFile(cur.name, file)
+ if (!cur.image) void this.#indexFile(cur.name, file)
}
}
}
diff --git a/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts b/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts
index 4376314c5f..dc8c27f2ba 100644
--- a/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts
+++ b/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts
@@ -93,6 +93,20 @@ describe('AttachedFilesStore', () => {
expect(store.get('proj/app.ts')?.folder).toBe('proj')
})
+ it('links a folder image as a ready image row, kept out of the text files', async () => {
+ const png = new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0])], 'logo.png', {
+ type: 'image/png'
+ })
+ enumerateDirMock.mockResolvedValue([
+ { file: file('app.ts', 'x\n'), path: 'proj/app.ts' },
+ { file: png, path: 'proj/logo.png' }
+ ])
+ await store.addFolder(dir)
+ await settle(store)
+ expect(store.get('proj/logo.png')).toMatchObject({ status: 'ready', image: true })
+ expect(store.readyFiles().map((f) => f.name)).toEqual(['proj/app.ts'])
+ })
+
it('refreshFolders detects rename, add, edit, and delete', async () => {
enumerateDirMock.mockResolvedValue([
{ file: file('app.ts', 'x\n', 1), path: 'proj/app.ts' },
diff --git a/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts b/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts
index bb61f95c8c..1cb687842d 100644
--- a/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts
+++ b/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts
@@ -6,7 +6,7 @@ vi.mock('../shared', () => ({
createToolDef: (_schema: unknown, name: string, description: string) => ({ name, description })
}))
-import { searchFilesTool } from './fileTools'
+import { imagesAtPath, resultImages, searchFilesTool } from './fileTools'
import type { AttachedFile, AttachedFilesStore } from './attachedFiles.svelte'
/** Minimal store stub mirroring the real lookup contract (id first, then
@@ -58,6 +58,23 @@ describe('search_files — attachments present but nothing readable', () => {
expect(msg).toMatch(/re-link/i)
})
+ it('reports an image row by its status until it is ready', async () => {
+ const gone = await runSearch(
+ fakeStore([{ name: 'a.png', status: 'unavailable', image: true }]),
+ {
+ pattern: 'x',
+ file: 'a.png'
+ }
+ )
+ expect(gone).toMatch(/re-link/i)
+ const ready = await runSearch(fakeStore([{ name: 'a.png', status: 'ready', image: true }]), {
+ pattern: 'x',
+ file: 'a.png'
+ })
+ expect(ready).toMatch(/is an image/i)
+ expect(ready).not.toMatch(/show_image/)
+ })
+
it('still reports indexing while a file is genuinely indexing', async () => {
const msg = await runSearch(fakeStore([{ name: 'a.txt', status: 'indexing' }]))
expect(msg).toMatch(/still being indexed/i)
@@ -122,3 +139,54 @@ describe('search_files — colliding display names', () => {
expect(out).not.toContain('alpha target')
})
})
+
+describe('resultImages', () => {
+ it('finds the image a result holds and each render_all item, by its path', () => {
+ expect(resultImages({ png: 'AAA' })).toEqual([{ format: 'png', path: [] }])
+ expect(resultImages({ jpeg: { content: 'AAA' } })).toEqual([{ format: 'jpeg', path: [] }])
+ expect(
+ resultImages({ render_all: [{ markdown: '# a' }, { png: 'AAA' }, { gif: 'BBB' }] })
+ ).toEqual([
+ { format: 'png', path: ['render_all', 1] },
+ { format: 'gif', path: ['render_all', 2] }
+ ])
+ expect(resultImages({ s3: 'charts/a.png' })).toEqual([{ s3: { s3: 'charts/a.png' } }])
+ expect(resultImages('s3://secondary/b.jpg')).toEqual([
+ { s3: { s3: 'b.jpg', storage: 'secondary' } }
+ ])
+ expect(resultImages([{ s3: 'a.png' }, { s3: 'b.webp' }])).toHaveLength(2)
+ expect(resultImages([{ s3: 'plot.png' }, { s3: 'data.csv' }])).toEqual([
+ { s3: { s3: 'plot.png' } }
+ ])
+ expect(resultImages([{ s3: 'plot.png' }, 'other'])).toEqual([])
+ expect(resultImages({ s3: 'data.parquet' })).toEqual([])
+ expect(resultImages({ png: 42 })).toEqual([])
+ expect(resultImages('png')).toEqual([])
+ })
+})
+
+describe('imagesAtPath', () => {
+ // A list of inline images, which resultImages alone does not open.
+ const result = { charts: [{ png: 'AAA' }, { jpeg: { content: 'BBB' } }], files: ['s3://x/c.png'] }
+
+ it('opens the image a path points at, by its object or its base64 field', () => {
+ expect(imagesAtPath(result, ['charts', 1])).toEqual([{ format: 'jpeg', path: ['charts', 1] }])
+ expect(imagesAtPath(result, ['charts', 0, 'png'])).toEqual([
+ { format: 'png', path: ['charts', 0] }
+ ])
+ expect(imagesAtPath(result, ['files', 0])).toEqual([{ s3: { s3: 'c.png', storage: 'x' } }])
+ })
+
+ it('opens the format a path names when the object holds several', () => {
+ expect(imagesAtPath({ png: 'AAA', jpeg: 'BBB' }, ['jpeg'])).toEqual([
+ { format: 'jpeg', path: [] }
+ ])
+ expect(imagesAtPath({ png: 'AAA' }, ['jpeg'])).toEqual([])
+ })
+
+ it('finds nothing where the path leads off the result', () => {
+ expect(imagesAtPath(result, ['charts', 5])).toEqual([])
+ expect(imagesAtPath(result, ['charts', 0, 'png', 'deeper'])).toEqual([])
+ expect(imagesAtPath('text', [0])).toEqual([])
+ })
+})
diff --git a/frontend/src/lib/components/copilot/chat/files/fileTools.ts b/frontend/src/lib/components/copilot/chat/files/fileTools.ts
index d9b1f89e44..897661047b 100644
--- a/frontend/src/lib/components/copilot/chat/files/fileTools.ts
+++ b/frontend/src/lib/components/copilot/chat/files/fileTools.ts
@@ -19,10 +19,24 @@ import {
} from './fileEngine'
import type { AttachedFile, AttachedFilesStore } from './attachedFiles.svelte'
import { sanitizeAttachmentName } from '../textFileUtils'
+import { isViewableImageName } from './imageFiles'
+import type {
+ ImageResultFormat,
+ ImageSource,
+ ResultPath
+} from '$lib/components/sessions/previewRouter'
+import { JobService } from '$lib/gen'
+import { workspaceStore } from '$lib/stores'
+import { get } from 'svelte/store'
+import { isS3ImageKey, parseS3Object, s3ImagePreviewUrl } from '$lib/utils'
/** Slice of the GLOBAL tool helpers that exposes the attached-files store. */
export interface AttachedFilesHelper {
attachedFiles?: AttachedFilesStore
+ /** Session chats only: shows an image in the side-panel preview. */
+ openImage?: (source: ImageSource, label: string) => void
+ /** The session's own (possibly forked) workspace, where its jobs run. */
+ operatingWorkspace?: string
}
function storeFrom(helpers: unknown): AttachedFilesStore | undefined {
@@ -35,9 +49,19 @@ function storeFrom(helpers: unknown): AttachedFilesStore | undefined {
* or undefined when it's `ready`. Shared by read_file and search_files so both report the
* same accurate status instead of search_files claiming a non-ready file isn't attached.
*/
-function notReadyMessage(store: AttachedFilesStore, file: string): string | undefined {
+function notReadyMessage(
+ store: AttachedFilesStore,
+ file: string,
+ helpers: unknown
+): string | undefined {
const entry = store.resolve(file)
- if (entry?.status === 'ready') return undefined
+ if (entry?.status === 'ready') {
+ if (!entry.image) return undefined
+ // show_image exists only where an image can open: a session's preview panel.
+ return (helpers as AttachedFilesHelper | undefined)?.openImage
+ ? `"${file}" is an image, which has no text to read or search. Show it to the user with show_image.`
+ : `"${file}" is an image, which has no text to read or search.`
+ }
if (entry?.status === 'indexing')
return `File "${file}" is still being indexed. Try again shortly.`
if (entry?.status === 'locked')
@@ -110,7 +134,7 @@ export const searchFilesTool: SessionTool<{}> = {
// Validate a specifically requested file against the full store first, so a non-ready
// target reports its real status (indexing/locked/…) instead of "not attached".
if (parsed.file) {
- const notReady = notReadyMessage(store, parsed.file)
+ const notReady = notReadyMessage(store, parsed.file, helpers)
if (notReady) return notReady
}
// Restrict to the resolved row itself, not a name filter: display names may
@@ -178,7 +202,7 @@ export const readFileTool: SessionTool<{}> = {
return 'No files are attached to this conversation.'
}
const parsed = readFileSchema.parse(args)
- const notReady = notReadyMessage(store, parsed.file)
+ const notReady = notReadyMessage(store, parsed.file, helpers)
if (notReady) return notReady
const entry = store.resolve(parsed.file)!
toolCallbacks.setToolStatus(toolId, { content: `Reading "${entry.name}"...` })
@@ -198,7 +222,205 @@ export const readFileTool: SessionTool<{}> = {
}
}
-export const fileTools: SessionTool<{}>[] = [searchFilesTool, readFileTool]
+const showImageSchema = z.object({
+ file: z
+ .string()
+ .optional()
+ .describe('Exact filename of an attached image, as the roster lists it.'),
+ job_id: z
+ .string()
+ .optional()
+ .describe('A completed job whose result holds images (a run, a flow).'),
+ step_id: z
+ .string()
+ .optional()
+ .describe('With job_id on a flow: the step whose result holds the image, by its id.'),
+ path: z
+ .array(z.union([z.string(), z.number()]))
+ .optional()
+ .describe(
+ 'With job_id: keys and list indexes from the root of the result (of the step, with step_id) to the image, e.g. [2] or ["charts", 0, "png"]. Without it, every image the result holds is shown.'
+ ),
+ s3: z
+ .object({
+ s3: z.string().describe('The object key, e.g. "charts/plot.png".'),
+ storage: z
+ .string()
+ .optional()
+ .describe('The secondary storage holding it, when not the workspace default.')
+ })
+ .optional()
+ .describe('An S3 image object, as a result holds it: `{ s3, storage? }`.')
+})
+
+const showImageToolDef = createToolDef(
+ showImageSchema,
+ 'show_image',
+ 'Show an image to the user in the side-panel preview next to the chat, where they can zoom and pan it. Pass exactly one of: `file` for an image the user attached (png, jpeg, gif, webp, avif, bmp, ico or svg); `job_id` (and `step_id` for a flow step) for a job result, showing every image it holds (inline png, jpeg or gif, S3 image objects, each `render_all` item), or with `path` only the image at that place in the result, read with get_run first; or `s3` for an S3 image object. Call it again to show more images. You cannot see the image yourself: this only displays it to the user.'
+)
+
+const RESULT_IMAGE_FORMATS: ImageResultFormat[] = ['png', 'jpeg', 'gif']
+
+export type ResultImage =
+ | { format: ImageResultFormat; path: ResultPath }
+ | { s3: { s3: string; storage?: string } }
+
+function s3Image(value: unknown): ResultImage | undefined {
+ if (typeof value === 'string') {
+ if (!/^s3:\/\/[^/]*\/.+/.test(value)) return undefined
+ } else if (typeof (value as { s3?: unknown } | undefined)?.s3 !== 'string') return undefined
+ const s3 = parseS3Object(value as Parameters[0])
+ return isS3ImageKey(s3.s3) ? { s3: { s3: s3.s3, storage: s3.storage } } : undefined
+}
+
+/** The images a result holds, where DisplayResult renders them: the result's own
+ * `png`/`jpeg`/`gif` key (a base64 string or `{ content }`), an S3 image object, the images
+ * among a list of S3 objects (DisplayResult lists any mix of file types), and each
+ * `render_all` item. */
+export function resultImages(value: unknown, path: ResultPath = []): ResultImage[] {
+ const s3 = s3Image(value)
+ if (s3) return [s3]
+ if (Array.isArray(value)) {
+ const isS3List = value.every((i) => typeof (i as { s3?: unknown } | null)?.s3 === 'string')
+ return isS3List ? value.flatMap((i) => s3Image(i) ?? []) : []
+ }
+ if (!value || typeof value !== 'object') return []
+ const obj = value as Record
+ if (Array.isArray(obj.render_all)) {
+ return obj.render_all.flatMap((child, i) => resultImages(child, [...path, 'render_all', i]))
+ }
+ const format = RESULT_IMAGE_FORMATS.find((f) => {
+ const v = obj[f]
+ return typeof v === 'string' || typeof (v as { content?: unknown })?.content === 'string'
+ })
+ return format ? [{ format, path }] : []
+}
+
+/** The images at `path` inside a result. A path may end on the image's base64 field
+ * (`[0, "png"]`), which names the same image as the object holding it. */
+export function imagesAtPath(result: unknown, path: ResultPath): ResultImage[] {
+ const last = path.at(-1)
+ const format = RESULT_IMAGE_FORMATS.find((f) => f === last)
+ const at = format ? path.slice(0, -1) : path
+ let value = result
+ for (const key of at) {
+ if (!value || typeof value !== 'object') return []
+ value = (value as Record)[key]
+ }
+ if (format) {
+ // The named field, not the first image field of the object holding it.
+ const v = (value as Record | undefined)?.[format]
+ const isImage =
+ typeof v === 'string' || typeof (v as { content?: unknown })?.content === 'string'
+ return isImage ? [{ format, path: at }] : []
+ }
+ return resultImages(value, at)
+}
+
+async function showResultImages(
+ openImage: (source: ImageSource, label: string) => void,
+ workspace: string,
+ jobId: string,
+ stepId: string | undefined,
+ path: ResultPath | undefined
+): Promise {
+ const what = `job ${jobId}${stepId ? ` step ${stepId}` : ''}`
+ let result: unknown
+ try {
+ result = stepId
+ ? await JobService.resultById({ workspace, flowJobId: jobId, nodeId: stepId })
+ : await JobService.getCompletedJobResult({ workspace, id: jobId })
+ } catch (e) {
+ return `Could not load the result of ${what}: ${e instanceof Error ? e.message : String(e)}`
+ }
+ const images = path?.length ? imagesAtPath(result, path) : resultImages(result)
+ if (images.length === 0) {
+ return path?.length
+ ? `Nothing at ${JSON.stringify(path)} in the result of ${what} is an image. Read the result with get_run to find the image's path.`
+ : `The result of ${what} holds no image.`
+ }
+ const base = stepId ? `${stepId} result` : `Result ${jobId.slice(-8)}`
+ for (const image of images) {
+ if ('s3' in image) {
+ openImage(
+ { kind: 'url', url: s3ImagePreviewUrl(workspace, image.s3) },
+ image.s3.s3.split('/').pop() || image.s3.s3
+ )
+ continue
+ }
+ const { format, path } = image
+ const at = path.length ? ` #${path.filter((k) => typeof k === 'number').join('.')}` : ''
+ openImage(
+ {
+ kind: 'result',
+ workspace,
+ jobId,
+ format,
+ ...(stepId ? { nodeId: stepId } : {}),
+ ...(path.length ? { path } : {})
+ },
+ base + at
+ )
+ }
+ return images.length === 1
+ ? 'Showing the result image in the preview panel.'
+ : `Showing the ${images.length} result images in the preview panel, one tab each.`
+}
+
+export const showImageTool: SessionTool<{}> = {
+ requires: NONE,
+ def: showImageToolDef,
+ planModeSafe: true,
+ fn: async ({ args, helpers }) => {
+ const h = helpers as AttachedFilesHelper | undefined
+ const openImage = h?.openImage
+ if (!openImage) return 'Images can only be shown inside an AI session.'
+ const parsed = showImageSchema.parse(args)
+ const given = [parsed.file, parsed.job_id, parsed.s3].filter((v) => v !== undefined).length
+ if (given !== 1) {
+ return 'Pass exactly one of `file` (an attached image), `job_id` (a job result) or `s3` (an S3 image object).'
+ }
+ if (!parsed.job_id && (parsed.step_id || parsed.path)) {
+ return '`step_id` and `path` locate an image in a job result: pass them with `job_id`.'
+ }
+ if (parsed.job_id || parsed.s3) {
+ const workspace = h?.operatingWorkspace ?? get(workspaceStore)
+ if (!workspace) return 'No workspace to load the image from.'
+ if (parsed.job_id) {
+ return showResultImages(openImage, workspace, parsed.job_id, parsed.step_id, parsed.path)
+ }
+ const s3 = parsed.s3!
+ if (!isS3ImageKey(s3.s3)) {
+ return `"${s3.s3}" is not an image the viewer can show (png, jpeg or webp).`
+ }
+ openImage(
+ { kind: 'url', url: s3ImagePreviewUrl(workspace, s3) },
+ s3.s3.split('/').pop() || s3.s3
+ )
+ return `Showing "${s3.s3}" in the preview panel.`
+ }
+ if (!parsed.file) return 'Pass `file` for an attached image or `job_id` for a job result.'
+ const store = storeFrom(helpers)
+ if (!store) return 'No files are attached to this chat.'
+ const entry = store.resolve(parsed.file)
+ if (!entry || entry.messageScoped || entry.isFolderRoot) {
+ return (
+ notReadyMessage(store, parsed.file, helpers) ??
+ `No attached file matching "${parsed.file}".`
+ )
+ }
+ if (!isViewableImageName(entry.sourceName ?? entry.name)) {
+ return `"${entry.name}" is not an image. Read it with read_file instead.`
+ }
+ if (entry.status !== 'ready') {
+ return notReadyMessage(store, parsed.file, helpers) ?? `"${entry.name}" is not available.`
+ }
+ openImage({ kind: 'file', name: entry.name }, entry.name.split('/').pop() || entry.name)
+ return `Showing "${entry.name}" in the preview panel.`
+ }
+}
+
+export const fileTools: SessionTool<{}>[] = [searchFilesTool, readFileTool, showImageTool]
function rosterLine(f: AttachedFile): string {
// Message rows are addressed by their stable id (names may collide); session
@@ -211,6 +433,7 @@ function rosterLine(f: AttachedFile): string {
if (f.status === 'locked') return `- ${ref} (locked — needs the user to restore access)`
if (f.status === 'unavailable') return `- ${ref} (unavailable)`
if (f.status === 'error') return `- ${ref} (failed to load)`
+ if (f.image) return `- ${ref} — image, ${humanSize(f.size)}`
return `- ${ref} — ${f.lineCount} lines, ${humanSize(f.size)}`
}
@@ -253,6 +476,9 @@ export function buildAttachedFilesRoster(
'## Attached files',
'The user has attached the following files to this conversation. Their contents are NOT included here.',
'Use the `search_files` tool to find content with a regex, and `read_file` to read a bounded window of lines.',
+ ...([...store.folders.flatMap((d) => d.files), ...store.standalone].some((f) => f.image)
+ ? ['Images have no text: `show_image` displays one to the user, where it is available.']
+ : []),
'Reference a file by its file id when one is shown, otherwise by its filename.',
'',
lines.join('\n')
diff --git a/frontend/src/lib/components/copilot/chat/files/imageFiles.ts b/frontend/src/lib/components/copilot/chat/files/imageFiles.ts
new file mode 100644
index 0000000000..1d8b832116
--- /dev/null
+++ b/frontend/src/lib/components/copilot/chat/files/imageFiles.ts
@@ -0,0 +1,72 @@
+/**
+ * Which linked files the session's image viewer can show. Decided by extension: a
+ * folder's files come off disk through the File System Access API, which leaves
+ * `File.type` empty for many of them, and a snapshot Blob restored from IndexedDB
+ * keeps whatever type it had at link time.
+ */
+
+/** Binary image formats: linked as image rows, never line-indexed or read as text. */
+const RASTER_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'bmp', 'ico'])
+
+function extensionOf(name: string): string {
+ const dot = name.lastIndexOf('.')
+ return dot >= 0 ? name.slice(dot + 1).toLowerCase() : ''
+}
+
+/** A binary image the store keeps as an image row instead of rejecting it as non-text. */
+export function isRasterImageName(name: string): boolean {
+ return RASTER_EXTENSIONS.has(extensionOf(name))
+}
+
+/** Whether the image viewer can show the file. SVG is text, so it stays readable by the
+ * file tools as well. */
+export function isViewableImageName(name: string): boolean {
+ return isRasterImageName(name) || extensionOf(name) === 'svg'
+}
+
+const MIME_BY_EXTENSION: Record = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ gif: 'image/gif',
+ webp: 'image/webp',
+ avif: 'image/avif',
+ bmp: 'image/bmp',
+ ico: 'image/x-icon',
+ svg: 'image/svg+xml'
+}
+
+/** The bytes as a Blob the browser decodes as an image. An SVG served without
+ * `image/svg+xml` does not render in an ``, and a folder file often has no type. */
+export function asImageBlob(file: Blob, name: string): Blob {
+ const type = MIME_BY_EXTENSION[extensionOf(name)]
+ if (!type || file.type === type) return file
+ return new Blob([file], { type })
+}
+
+/**
+ * Stable short key for an image sent in a chat message, which has no id of its own:
+ * FNV-1a over the data URL, plus its length. A tab persists this key and finds the
+ * image again by recomputing it over the transcript's images.
+ */
+export function imageContentKey(dataUrl: string, owner?: object): string {
+ // An image tab re-resolves on every transcript change, so it passes the message or
+ // image object as `owner`: the hash is then computed once per image and released with it.
+ if (!owner) return fnv1a(dataUrl)
+ const hit = keyByOwner.get(owner)
+ if (hit?.dataUrl === dataUrl) return hit.key
+ const key = fnv1a(dataUrl)
+ keyByOwner.set(owner, { dataUrl, key })
+ return key
+}
+
+const keyByOwner = new WeakMap