diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index 2523f6b862..b73c255eb2 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -5,8 +5,16 @@ import { json } from 'svelte-highlight/languages' import DbtRunResult from '$lib/components/dbt/DbtRunResult.svelte' import { parseDbtRun } from '$lib/components/dbt/parseDbtRun' - import { copyToClipboard, parseS3Object, roughSizeOfObject } from '$lib/utils' + import { + copyToClipboard, + isS3ImageKey, + parseS3Object, + roughSizeOfObject, + s3ImagePreviewUrl + } from '$lib/utils' import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte' + import { getImageOpener } from '$lib/components/common/image/imageOpener' + import type { ImageResultFormat, ResultPath } from '$lib/components/sessions/previewRouter' import { downloadBlob, downloadViaClient, @@ -132,6 +140,9 @@ * run from the next, or a second one continues the first one's fold. */ runKey?: string | undefined + /** Where `result` sits inside the job's result, for a nested render; null when it + * cannot be addressed from the job (an agent's structured output). */ + resultPath?: ResultPath | null workspaceId?: string | undefined hideAsJson?: boolean noControls?: boolean @@ -158,6 +169,7 @@ disableExpand = false, jobId = undefined, runKey = undefined, + resultPath = [], workspaceId = undefined, hideAsJson = false, noControls = false, @@ -193,15 +205,12 @@ // the provenance-gated `apps_u/download_s3_file/{appPath}` endpoint; otherwise // (editor/preview) it uses the viewer-scoped `job_helpers/load_image_preview`. function s3DisplayUrl(s3object: { s3: string; storage?: string; presigned?: string }): string { - const endpoint = appPath - ? `apps_u/download_s3_file/${appPath}` - : 'job_helpers/load_image_preview' - const keyParam = appPath ? 's3' : 'file_key' - let url = `/api/w/${workspaceId}/${endpoint}?${keyParam}=${encodeURIComponent(s3object.s3)}` + if (!appPath) return s3ImagePreviewUrl(workspaceId ?? '', s3object) + let url = `/api/w/${workspaceId}/apps_u/download_s3_file/${appPath}?s3=${encodeURIComponent(s3object.s3)}` if (s3object.storage) { url += `&storage=${s3object.storage}` } - if (appPath && s3object.presigned) { + if (s3object.presigned) { url += `&${s3object.presigned}` } return url @@ -535,6 +544,44 @@ return false } + const imageOpener = getImageOpener() + + /** In a session, an image result opens in the preview panel. Only a result whose job is + * known: the tab refetches it from there, and a result shown without one (a replay, a + * value an app computed) keeps expanding in place. */ + function openResultImage(format: ImageResultFormat): (() => void) | undefined { + if (!imageOpener || !jobId || !workspaceId || !resultPath) return undefined + const opener = imageOpener + const job = jobId + const workspace = workspaceId + const node = nodeId + const path = resultPath + const at = path.length ? ` #${path.filter((k) => typeof k === 'number').join('.')}` : '' + return () => + opener( + { + kind: 'result', + workspace, + jobId: job, + format, + ...(node ? { nodeId: node } : {}), + ...(path.length ? { path } : {}) + }, + (node ? `${node} result` : `Result ${job.slice(-8)}`) + at + ) + } + + function openS3Image(s3object: { + s3: string + storage?: string + presigned?: string + }): (() => void) | undefined { + if (!imageOpener) return undefined + const opener = imageOpener + const url = s3DisplayUrl(s3object) + return () => opener({ kind: 'url', url }, s3object.s3.split('/').pop() || s3object.s3) + } + function contentOrRootString(obj: string | { filename: string; content: string } | undefined) { if (obj == undefined || obj == null) { return '' @@ -849,10 +896,11 @@ {/if}
- {#each result['render_all'] as res} + {#each result['render_all'] as res, i}
@@ -988,6 +1037,7 @@ @@ -1017,6 +1067,7 @@ @@ -1242,13 +1293,14 @@ presigned={s3object?.presigned} /> {/key} - {:else if s3object?.s3?.endsWith('.png') || s3object?.s3?.endsWith('.jpeg') || s3object?.s3?.endsWith('.jpg') || s3object?.s3?.endsWith('.webp')} + {:else if isS3ImageKey(s3object?.s3 ?? '')}
{:else if s3object?.s3?.endsWith('.pdf')} @@ -1311,7 +1363,7 @@ >open table preview {/if} - {:else if s3object?.s3?.endsWith('.png') || s3object?.s3?.endsWith('.jpeg') || s3object?.s3?.endsWith('.jpg') || s3object?.s3?.endsWith('.webp')} + {:else if isS3ImageKey(s3object?.s3 ?? '')} {#if seeS3PreviewFileFromList == s3object?.s3}
{:else} @@ -1351,6 +1404,7 @@ noControls hideAsJson result={output} + resultPath={null} {markupTrust} {filename} {disableExpand} @@ -1500,6 +1554,7 @@ void } - let { src, alt = '', title, class: className = '' }: Props = $props() + let { src, alt = '', title, class: className = '', onOpen }: Props = $props() let isOpen = $state(false) @@ -69,4 +72,4 @@ }} /> - + diff --git a/frontend/src/lib/components/common/image/ImagePanelViewer.svelte b/frontend/src/lib/components/common/image/ImagePanelViewer.svelte new file mode 100644 index 0000000000..de4097d183 --- /dev/null +++ b/frontend/src/lib/components/common/image/ImagePanelViewer.svelte @@ -0,0 +1,151 @@ + + +
+ +
+ + {#if view.natural} + {view.natural.w} × {view.natural.h}{bytes !== undefined ? ` · ${humanSize(bytes)}` : ''} + {/if} + +
+ + +
+
+ + + +
{ + if (view.handleKey(e)) e.preventDefault() + }} + > + {#if failed} +
+ + This file could not be displayed as an image. + +
+ {:else} + {name} (failedSrc = src)} + class={view.imageClass} + style={view.imageStyle} + /> + {/if} +
+
diff --git a/frontend/src/lib/components/common/image/ImageViewer.svelte b/frontend/src/lib/components/common/image/ImageViewer.svelte index c50254a073..8c6595c0de 100644 --- a/frontend/src/lib/components/common/image/ImageViewer.svelte +++ b/frontend/src/lib/components/common/image/ImageViewer.svelte @@ -1,8 +1,9 @@ + +
+ {#if draft !== undefined} +
+ +
+ {:else} + + {/if} +
diff --git a/frontend/src/lib/components/common/image/imageOpener.ts b/frontend/src/lib/components/common/image/imageOpener.ts new file mode 100644 index 0000000000..62264703c1 --- /dev/null +++ b/frontend/src/lib/components/common/image/imageOpener.ts @@ -0,0 +1,17 @@ +import { getContext, setContext } from 'svelte' +import type { ImageSource } from '$lib/components/sessions/previewRouter' + +/** Opens an image in a viewer beside the current surface: a session's preview panel. */ +export type ImageOpener = (source: ImageSource, label: string) => void + +const KEY = 'imageOpener' + +/** Provided by a session for everything it renders, the chat and the preview tabs. */ +export function setImageOpener(opener: ImageOpener): void { + setContext(KEY, opener) +} + +/** Undefined outside a session: an image then expands in place. */ +export function getImageOpener(): ImageOpener | undefined { + return getContext(KEY) +} diff --git a/frontend/src/lib/components/common/image/zoomPan.svelte.ts b/frontend/src/lib/components/common/image/zoomPan.svelte.ts new file mode 100644 index 0000000000..38e138bd40 --- /dev/null +++ b/frontend/src/lib/components/common/image/zoomPan.svelte.ts @@ -0,0 +1,244 @@ +import { on } from 'svelte/events' + +/** The scales the zoom buttons and keys step between; the wheel zooms continuously. */ +const ZOOM_STEPS = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32] +const MAX_SCALE = 32 +// From this scale up, pixels are drawn as hard squares: smoothing an upscaled +// screenshot or icon blurs exactly the detail the user zoomed in to look at. +const PIXELATED_FROM = 2 + +type Point = { x: number; y: number } + +/** + * Zoom and pan of one image inside a surface: fit, zoom around a point, step, wheel, + * drag, double-click and the `+` `-` `0` `1` keys. Attach `surface` to the element that + * clips the image and `image` to the ``, which `imageStyle` positions at the + * surface's centre. + */ +export function useZoomPan(opts: { + /** Room kept around a fitted image, in total per axis. */ + margin: Point + /** A click that did not drag; `onImage` tells whether it landed on the image. */ + onTap?: (onImage: boolean) => void +}) { + let natural = $state<{ w: number; h: number } | undefined>(undefined) + let viewW = $state(0) + let viewH = $state(0) + /** `fit` follows the surface as it resizes; a number is a fixed scale of the natural size. */ + let zoom = $state('fit') + let pan = $state({ x: 0, y: 0 }) + /** Eases button and keyboard zooms; wheel and drag must track the pointer without lag. */ + let animate = $state(false) + let panning = $state(false) + let surfaceEl: HTMLElement | undefined + let imageEl: HTMLImageElement | undefined + + // Fit never enlarges: a small image is shown at its real size rather than blown up. + const fitScale = $derived( + natural && viewW > 0 && viewH > 0 + ? Math.min( + 1, + Math.max(viewW - opts.margin.x, 1) / natural.w, + Math.max(viewH - opts.margin.y, 1) / natural.h + ) + : 1 + ) + const scale = $derived(zoom === 'fit' ? fitScale : zoom) + const minScale = $derived(Math.min(fitScale, ZOOM_STEPS[0])) + const pannable = $derived( + !!natural && (natural.w * scale > viewW + 1 || natural.h * scale > viewH + 1) + ) + + function clampPan(p: Point, s: number): Point { + if (!natural) return { x: 0, y: 0 } + const maxX = Math.max(0, (natural.w * s - viewW) / 2) + const maxY = Math.max(0, (natural.h * s - viewH) / 2) + return { + x: Math.min(maxX, Math.max(-maxX, p.x)), + y: Math.min(maxY, Math.max(-maxY, p.y)) + } + } + + /** `at` is relative to the surface's centre; the image point there stays put. */ + function zoomTo(next: number, at: Point = { x: 0, y: 0 }) { + const s = Math.min(MAX_SCALE, Math.max(minScale, next)) + const k = s / scale + pan = clampPan({ x: at.x - (at.x - pan.x) * k, y: at.y - (at.y - pan.y) * k }, s) + zoom = s + } + + function fit() { + animate = true + zoom = 'fit' + pan = { x: 0, y: 0 } + } + + function zoomIn() { + animate = true + zoomTo(ZOOM_STEPS.find((z) => z > scale * 1.01) ?? MAX_SCALE) + } + + function zoomOut() { + animate = true + zoomTo(ZOOM_STEPS.findLast((z) => z < scale / 1.01) ?? minScale) + } + + function actualSize() { + animate = true + zoomTo(1) + } + + function surfacePoint(e: { clientX: number; clientY: number }): Point { + const r = surfaceEl!.getBoundingClientRect() + return { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 } + } + + let drag: { x: number; y: number; pan: Point; moved: boolean; onImage: boolean } | undefined + + function endDrag() { + drag = undefined + panning = false + } + + function surface(node: HTMLElement) { + surfaceEl = node + const resize = new ResizeObserver(() => { + viewW = node.clientWidth + viewH = node.clientHeight + }) + resize.observe(node) + const offs = [ + // Not passive: the page must not scroll under a wheel zoom. + on( + node, + 'wheel', + (e: WheelEvent) => { + if (!natural) return + e.preventDefault() + animate = false + const lines = e.deltaMode === 1 ? 33 : 1 + // Pinch on a trackpad arrives as ctrl+wheel with small deltas. + const speed = e.ctrlKey ? 0.01 : 0.0015 + zoomTo(scale * Math.exp(-e.deltaY * lines * speed), surfacePoint(e)) + }, + { passive: false } + ), + on(node, 'pointerdown', (e: PointerEvent) => { + if (e.button !== 0) return + drag = { x: e.clientX, y: e.clientY, pan, moved: false, onImage: e.target === imageEl } + node.setPointerCapture(e.pointerId) + }), + on(node, 'pointermove', (e: PointerEvent) => { + if (!drag) return + const dx = e.clientX - drag.x + const dy = e.clientY - drag.y + if (!drag.moved && Math.hypot(dx, dy) < 4) return + drag.moved = true + if (pannable) { + panning = true + animate = false + pan = clampPan({ x: drag.pan.x + dx, y: drag.pan.y + dy }, scale) + } + }), + on(node, 'pointerup', () => { + if (drag && !drag.moved) opts.onTap?.(drag.onImage) + endDrag() + }), + on(node, 'pointercancel', endDrag), + on(node, 'dblclick', (e: MouseEvent) => { + if (!natural) return + animate = true + if (zoom === 'fit' || Math.abs(scale - fitScale) < 0.001) { + zoomTo(fitScale < 1 ? 1 : 2, surfacePoint(e)) + } else { + fit() + } + }) + ] + return () => { + resize.disconnect() + offs.forEach((off) => off()) + surfaceEl = undefined + } + } + + function image(node: HTMLImageElement) { + imageEl = node + const measure = () => { + // An SVG without width/height has no intrinsic size. + natural = { w: node.naturalWidth || 1024, h: node.naturalHeight || 768 } + } + if (node.complete && node.naturalWidth) measure() + const off = on(node, 'load', measure) + return () => { + off() + imageEl = undefined + } + } + + return { + get natural() { + return natural + }, + get scale() { + return scale + }, + get minScale() { + return minScale + }, + maxScale: MAX_SCALE, + get zoom() { + return zoom + }, + get pannable() { + return pannable + }, + get panning() { + return panning + }, + /** Positions the image: its natural size, centred, then panned and scaled. */ + get imageStyle() { + return `width: ${natural?.w ?? 0}px; height: ${natural?.h ?? 0}px; transform: translate(-50%, -50%) translate(${pan.x}px, ${pan.y}px) scale(${scale});` + }, + get imageClass() { + return [ + 'absolute left-1/2 top-1/2 max-w-none', + natural ? '' : 'opacity-0', + animate ? 'transition-transform duration-150 ease-out' : '', + scale >= PIXELATED_FROM ? '[image-rendering:pixelated]' : '' + ].join(' ') + }, + surface, + image, + fit, + zoomIn, + zoomOut, + actualSize, + /** Eased, for a zoom the user typed or picked. */ + zoomToAnimated(next: number) { + animate = true + zoomTo(next) + }, + /** Back to fit with no easing, for a viewer shown afresh. */ + reset() { + zoom = 'fit' + pan = { x: 0, y: 0 } + animate = false + }, + /** Handles a zoom key; returns whether it did, so the caller can prevent its default. */ + handleKey(e: KeyboardEvent): boolean { + if (e.metaKey || e.ctrlKey || e.altKey) return false + const action = { + '+': zoomIn, + '=': zoomIn, + '-': zoomOut, + _: zoomOut, + '0': fit, + '1': actualSize + }[e.key] + if (!action) return false + action() + return true + } + } +} diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index fa6d809aa4..697b42f01b 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -523,7 +523,7 @@ return } // Otherwise (folders / multi-select): summarize to avoid a flood of toasts. The only - // per-file rejection left is non-text content (binary files are skipped). + // per-file rejection left is binary content other than images. const lead = added.length ? `Attached ${added.length}, skipped ${rejected.length}` : `Skipped ${rejected.length} file${rejected.length === 1 ? '' : 's'}` @@ -663,10 +663,9 @@ const entries = await readDroppedEntries(Array.from(dt.items ?? [])) const source: FileToAttach[] = entries.length > 0 ? entries : flatFiles // Top-level files attach to the message (images were already reserved - // from dt.files before the walk). Folder children keep riding the - // session store as a snapshot — including nested images, which are - // deliberately NOT attached (the FSA path never extracts folder - // contents either); they are summarized as skipped there. + // from dt.files before the walk). Folder children ride the session store + // as a snapshot, nested images included: they become image rows the + // preview can show, never message attachments, as on the FSA path. const topLevelText: File[] = [] const folderEntries: FileToAttach[] = [] for (const entry of source) { diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index a86d8e30e4..b80f37fc61 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -215,7 +215,7 @@ import { scopedKey, onUserChange, migrateLegacyLocalStorage } from '$lib/userSco import { getLocalSetting, storeLocalSetting } from '$lib/utils' import { AttachedFilesStore } from './files/attachedFiles.svelte' import { SessionArtifactsStore } from './artifacts/artifactsState.svelte' -import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRouter' +import type { ArtifactVersionTarget, ImageSource } from '$lib/components/sessions/previewRouter' import { appendAttachedFilesRoster } from './files/fileTools' import { ENTER_PLAN_MODE_TOOL, EXIT_PLAN_MODE_TOOL } from './planMode' import { PlanModeController, type PlanModeHost } from './planModeController.svelte' @@ -688,6 +688,8 @@ export class AIChatManager implements ChatViewHost { * mounts of it each reorder the schema SchemaForm edits in place. */ isRunFormTabOpen?: (toolCallId: string) => boolean openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void + /** Show an image in the session's preview panel. Set by a session runtime only. */ + openImage?: (source: ImageSource, label: string) => void closeArtifact?: (artifactId: string) => void #loading = $state(false) get loading(): boolean { @@ -3196,7 +3198,8 @@ export class AIChatManager implements ChatViewHost { artifacts: this.artifacts, access: this.#toolAccess, getChatId: () => this.historyManager.getCurrentChatId(), - openArtifact: this.openArtifact + openArtifact: this.openArtifact, + openImage: this.openImage } : {}), testActiveFlow: async (storagePath: string, args?: Record, memoryId?: string) => diff --git a/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte b/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte index f521fcce1d..c0344ec8f4 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte @@ -13,6 +13,7 @@ import { messageDraft, segments } from './chatDraft' import { lineCountLabel } from './pasteTokens' import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte' + import { imageContentKey } from './files/imageFiles' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -178,6 +179,13 @@ src={image.dataUrl} alt={image.name ?? 'attached image'} class="max-h-40 max-w-[min(20rem,100%)] rounded-lg border border-border-light" + onOpen={chatHost.openImage + ? () => + chatHost.openImage?.( + { kind: 'message', hash: imageContentKey(image.dataUrl) }, + image.name ?? 'Image' + ) + : undefined} /> {/each} diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 63ef5d1ef8..4bc7a2f6e9 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -12,6 +12,7 @@ ExternalLink, BookOpen } from 'lucide-svelte' + import { imageContentKey } from './files/imageFiles' import { truncateRev } from '$lib/utils' import { EXIT_PLAN_MODE_TOOL, @@ -39,6 +40,13 @@ type ToolDisplayMessage } from './shared' import SecretRequestCard from './SecretRequestCard.svelte' + + // Only a loaded image: a reloaded chat holds a reference until its bytes come back. + function toolImageOpener(url: string): (() => void) | undefined { + const open = chatHost.openImage + if (!open || !url.startsWith('data:')) return undefined + return () => open({ kind: 'message', hash: imageContentKey(url) }, 'Screenshot') + } import ChatCollapsibleCard from './ChatCollapsibleCard.svelte' import { twMerge } from 'tailwind-merge' import { slide } from 'svelte/transition' @@ -405,6 +413,7 @@ src={message.imageUrl} alt="Image returned by the tool" class="max-h-48 max-w-full rounded border border-border-light" + onOpen={toolImageOpener(message.imageUrl)} /> {/if} diff --git a/frontend/src/lib/components/copilot/chat/chatViewHost.ts b/frontend/src/lib/components/copilot/chat/chatViewHost.ts index f23a2ab1d8..1d1d613940 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -14,7 +14,7 @@ import type { ScopeDecision } from './workingScope' import type { GroupingTools } from './toolGroups' import type { AttachedFilesStore } from './files/attachedFiles.svelte' import type { SessionArtifactsStore } from './artifacts/artifactsState.svelte' -import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRouter' +import type { ArtifactVersionTarget, ImageSource } from '$lib/components/sessions/previewRouter' import type { FlowAIChatHelpers } from './flow/core' import type { AppAIChatHelpers } from './app/core' import type AIChatInput from './AIChatInput.svelte' @@ -202,6 +202,9 @@ export interface ChatViewHost { attachedFiles: AttachedFilesStore artifacts: SessionArtifactsStore openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void + /** Opens an image in a preview panel beside the chat. Undefined where there is none, and + * a message image then expands in place. */ + openImage?: (source: ImageSource, label: string) => void flowAiChatHelpers?: FlowAIChatHelpers appAiChatHelpers?: AppAIChatHelpers } diff --git a/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte b/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte index ec52c90ab9..31fb2db9db 100644 --- a/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte +++ b/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte @@ -36,7 +36,17 @@ {#snippet chip(card: Card)} {#if card.kind === 'folder'} - removeCard(card)} /> + removeCard(card)} + onOpenImage={aiChatManager.openImage + ? (f) => + aiChatManager.openImage?.( + { kind: 'file', name: f.name }, + f.name.split('/').pop() || f.name + ) + : undefined} + /> {:else} removeCard(card)} /> {/if} diff --git a/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte b/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte index 068447a878..c13150a206 100644 --- a/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte +++ b/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte @@ -1,28 +1,52 @@
(showDelete = true)} onmouseleave={() => (showDelete = false)} role="listitem" - title={hoverList} > - {folder.name} + {#if canList} + + {#snippet trigger()} + {folder.name} + {/snippet} + {#snippet content()} +
+
+ {folder.name}/ + · {folder.files.length} + {folder.files.length === 1 ? 'file' : 'files'}{imageCount > 0 + ? ` · ${imageCount} ${imageCount === 1 ? 'image' : 'images'}` + : ''} +
+
    + {#each sorted.slice(0, MAX_LISTED) as f (f.name)} + {@const icon = getFileIcon(f.name)} + {@const Icon = icon.icon} +
  • + {#if onOpenImage && isOpenable(f)} + + {:else} +
    + + {innerPath(f)} +
    + {/if} +
  • + {:else} +
  • No files linked from this folder.
  • + {/each} + {#if sorted.length > MAX_LISTED} +
  • + … {sorted.length - MAX_LISTED} more +
  • + {/if} +
+
+ {/snippet} +
+ {:else} + {folder.name} + {/if}
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() + +function fnv1a(dataUrl: string): string { + let h = 0x811c9dc5 + for (let i = 0; i < dataUrl.length; i++) { + h ^= dataUrl.charCodeAt(i) + h = Math.imul(h, 0x01000193) + } + return `${(h >>> 0).toString(16)}-${dataUrl.length.toString(36)}` +} diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index c618e8b9b4..53ff9adf6c 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -20,7 +20,11 @@ import { WorkspaceService } from '$lib/gen' import { deepEqual } from 'fast-equals' -import { promptSafe, type ArtifactVersionTarget } from '$lib/components/sessions/previewRouter' +import { + promptSafe, + type ArtifactVersionTarget, + type ImageSource +} from '$lib/components/sessions/previewRouter' import { canDraftItem, roleCanDraft } from '$lib/editRights' import { renderPromptTemplate } from './promptTemplate' import { $ScriptLang } from '$lib/gen/schemas.gen' @@ -4879,7 +4883,8 @@ export const SESSION_PREVIEW_TOOL_NAMES = new Set([ 'update_artifact', 'list_artifacts', 'read_artifact', - 'list_artifact_versions' + 'list_artifact_versions', + 'show_image' ]) /** @@ -4952,6 +4957,7 @@ export type GlobalToolHelpers = SessionToolHelpers & { artifacts?: SessionArtifactsStore getChatId?: () => string | undefined openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void + openImage?: (source: ImageSource, label: string) => void } function sessionIdFromCtx(ctx: { helpers?: unknown }): string | undefined { diff --git a/frontend/src/lib/components/sessions/ImagePreviewSlot.svelte b/frontend/src/lib/components/sessions/ImagePreviewSlot.svelte new file mode 100644 index 0000000000..a63c853972 --- /dev/null +++ b/frontend/src/lib/components/sessions/ImagePreviewSlot.svelte @@ -0,0 +1,149 @@ + + +{#if src} + +{:else if folderLocked} +
+ Your browser needs permission again to read this folder. + +
+{:else if source.kind === 'result'} +
+ {resultImage.loading + ? 'Loading the result…' + : resultImage.error + ? 'The result of this run could not be loaded.' + : 'This run’s result no longer holds an image.'} +
+{:else if file && file.status !== 'ready'} +
+ {file.status === 'indexing' ? 'Loading…' : 'This image is no longer available.'} +
+{:else} +
+ {source.kind === 'file' + ? 'This image is no longer linked to the session.' + : source.kind === 'message' + ? 'This image is not in the current chat.' + : 'This image could not be loaded.'} +
+{/if} diff --git a/frontend/src/lib/components/sessions/PreviewTabHost.svelte b/frontend/src/lib/components/sessions/PreviewTabHost.svelte index ef3a3bfbfb..9d3d3d47bd 100644 --- a/frontend/src/lib/components/sessions/PreviewTabHost.svelte +++ b/frontend/src/lib/components/sessions/PreviewTabHost.svelte @@ -15,13 +15,16 @@ resolvePreviewTab, parsePreviewItemRoute, parsePreviewSelectedId, + parseImageRoute, showsView } from './previewRouter' import { withMenuHidden } from './sessionMode.svelte' import { useSessionPermissions } from './sessionPermissions.svelte' import ArtifactViewer from '../copilot/chat/artifacts/ArtifactViewer.svelte' import RunFormPreviewSlot from './RunFormPreviewSlot.svelte' + import ImagePreviewSlot from './ImagePreviewSlot.svelte' import { setOverlayHost } from '../common/overlayHost.svelte' + import { setImageOpener } from '../common/image/imageOpener' import { setReadOnlyWorkspace } from '../operatingWorkspace.svelte' let { @@ -82,6 +85,8 @@ () => runtime?.manager ) setReadOnlyWorkspace((ws) => !!ws && ws === workspaceId && permissions.readOnly) + // An image inside a tab (a run's result, a test result in an editor) opens in a tab beside it. + setImageOpener((source, label) => runtime?.manager.openImage?.(source, label)) // Every route into an editor ends here, the breadcrumb and the chat's openers included, so // this is where an editor the user cannot save is turned into the deployed page. const mode = $derived( @@ -505,6 +510,20 @@
This artifact is no longer available.
{/if} +{:else if slot.kind === 'image' && mounted} +
+ {#if runtime} + + {/if} +
{:else if slot.kind === 'runform' && mounted}
import { setContext, untrack } from 'svelte' + import { setImageOpener } from '$lib/components/common/image/imageOpener' import { Pane, Splitpanes } from 'svelte-splitpanes' import type AIChat from '$lib/components/copilot/chat/AIChat.svelte' import ComposerPlaceholder from '$lib/components/copilot/chat/ComposerPlaceholder.svelte' @@ -111,6 +112,7 @@ if (runtime) { setContext('aiChatManager', runtime.manager) + setImageOpener((source, label) => runtime.manager.openImage?.(source, label)) } // Reactive session reference (mutations to summary/target propagate via the $state proxy). diff --git a/frontend/src/lib/components/sessions/previewRouter.test.ts b/frontend/src/lib/components/sessions/previewRouter.test.ts index 18d287769e..4040215227 100644 --- a/frontend/src/lib/components/sessions/previewRouter.test.ts +++ b/frontend/src/lib/components/sessions/previewRouter.test.ts @@ -4,6 +4,8 @@ import { describeLocation, draftFriendlyLeaf, drawerAnchorFor, + imageUrl, + parseImageRoute, showsView, itemDisplayName, matchReusablePage, @@ -532,3 +534,26 @@ describe('run form route', () => { expect(parseRunFormRoute('artifact:abc#Plan')).toBeNull() }) }) + +describe('image routes', () => { + it('round-trips every image source, slashes in a name or URL included', () => { + const sources = [ + { kind: 'file', name: 'screens/icons/logo.png' }, + { kind: 'message', hash: '36976501-1qvb' }, + { kind: 'result', workspace: 'admins', jobId: '01a2', format: 'png' }, + { kind: 'result', workspace: 'admins', jobId: '01a2', format: 'jpeg', nodeId: 'a' }, + { + kind: 'result', + workspace: 'admins', + jobId: '01a2', + format: 'png', + path: ['render_all', 1] + }, + { kind: 'url', url: '/api/w/admins/job_helpers/load_image_preview?file_key=out/x.png' } + ] as const + for (const source of sources) { + expect(parseImageRoute(imageUrl(source, 'My image'))).toEqual({ source, label: 'My image' }) + } + expect(parseImageRoute('image:result/admins/01a2/bmp')).toBeNull() + }) +}) diff --git a/frontend/src/lib/components/sessions/previewRouter.ts b/frontend/src/lib/components/sessions/previewRouter.ts index 5cbaa542ba..d4d730fc35 100644 --- a/frontend/src/lib/components/sessions/previewRouter.ts +++ b/frontend/src/lib/components/sessions/previewRouter.ts @@ -105,6 +105,31 @@ export type PreviewTarget = | { type: 'artifact'; id: string; name: string; version?: ArtifactVersionTarget } | { type: 'runform'; toolCallId: string; label: string } | { type: 'pageitem'; ref: PageItemRef } + | { type: 'image'; source: ImageSource; label: string } + +/** Where an image tab's bytes come from: a file the session linked (addressed by its + * name in the attached-files store), an image the user sent in a chat message (by a hash + * of its data URL, since message images carry no id), a job's inline image result (by the + * job, refetched rather than carried: the tab url is persisted and the bytes run to + * megabytes), or an image the API serves at a URL (an S3 result's preview). */ +export type ImageSource = + | { kind: 'file'; name: string } + | { kind: 'message'; hash: string } + | { + kind: 'result' + workspace: string + jobId: string + nodeId?: string + format: ImageResultFormat + /** Where the image sits inside the result, when it is not the result itself + * (a `render_all` child). */ + path?: ResultPath + } + | { kind: 'url'; url: string } + +export type ImageResultFormat = 'png' | 'jpeg' | 'gif' +export type ResultPath = (string | number)[] +const IMAGE_RESULT_FORMATS: readonly string[] = ['png', 'jpeg', 'gif'] /** * Which side of an item to open when the opener is showing the reader something @@ -214,7 +239,13 @@ const INJECTED_PARAMS = ['nomenubar', 'workspace'] as const export function canonicalizeObservedLoc(loc: string): string { // An artifact or a run form is a scheme, not a path — `new URL` would happily parse it // and hand back a pathname with the scheme gone. - if (parseArtifactRoute(loc) || parseRunFormRoute(loc) || parsePageItemRoute(loc)) return loc + if ( + parseArtifactRoute(loc) || + parseRunFormRoute(loc) || + parsePageItemRoute(loc) || + parseImageRoute(loc) + ) + return loc try { const u = new URL(loc, 'http://_') for (const p of INJECTED_PARAMS) u.searchParams.delete(p) @@ -294,6 +325,9 @@ export function describeLocation(loc: string): PreviewLocation { // Identity is the call, never the label: that carries the script's summary, so folding it // in would open a second tab for the same form whenever the summary differed. if (runForm) return { identity: `runform:${runForm.toolCallId}`, view: '', anchor: '' } + // Identity is the source, never the label. + const image = parseImageRoute(loc) + if (image) return { identity: imageUrl(image.source, ''), view: '', anchor: '' } const pageItem = parsePageItemRoute(loc) if (pageItem) return { identity: pageItemUrl(pageItem), view: '', anchor: '' } // Keyed by its hash: as a bare path it would claim the live editor's tab on the same script. @@ -479,6 +513,8 @@ export function previewLocationLabel(url: string): string { if (artifact) return artifact.name || 'Artifact' const runForm = parseRunFormRoute(url) if (runForm) return runForm.label || 'Run form' + const image = parseImageRoute(url) + if (image) return image.label || 'Image' const pageItem = parsePageItemRoute(url) if (pageItem) return pageItem.path.split('/').pop() || pageItem.path const page = matchReusablePage(url) @@ -607,6 +643,79 @@ export function parseRunRoute( } } +// An image tab: `image:file/` or `image:msg/`, the label in the hash. A scheme for +// the same reason as artifacts — the tab mounts a viewer, there is no page to frame. +export function parseImageRoute(url: string): { source: ImageSource; label: string } | null { + const m = url.match(/^image:(file|msg|result|url)\/([^?#]+)(?:#(.*))?$/) + if (!m) return null + let parts: string[] + let label = '' + try { + parts = m[2].split('/').map(decodeURIComponent) + label = m[3] ? decodeURIComponent(m[3]) : '' + } catch { + return null + } + const source = imageSourceOf(m[1], parts) + return source ? { source, label } : null +} + +function imageSourceOf(kind: string, parts: string[]): ImageSource | undefined { + if (kind === 'file' && parts.length === 1) return { kind: 'file', name: parts[0] } + if (kind === 'msg' && parts.length === 1) return { kind: 'message', hash: parts[0] } + if (kind === 'url' && parts.length === 1) return { kind: 'url', url: parts[0] } + if (kind === 'result' && parts.length >= 3 && parts.length <= 5) { + const [workspace, jobId, format, nodeId, pathJson] = parts + if (!IMAGE_RESULT_FORMATS.includes(format)) return undefined + const path = pathJson ? parseResultPath(pathJson) : undefined + if (pathJson && !path) return undefined + return { + kind: 'result', + workspace, + jobId, + format: format as ImageResultFormat, + ...(nodeId ? { nodeId } : {}), + ...(path ? { path } : {}) + } + } + return undefined +} + +function parseResultPath(json: string): ResultPath | undefined { + try { + const path: unknown = JSON.parse(json) + return Array.isArray(path) && + path.length > 0 && + path.every((k) => typeof k === 'string' || typeof k === 'number') + ? path + : undefined + } catch { + return undefined + } +} + +// Every segment is encoded on its own, so a `/` inside a file name or URL stays one segment. +export function imageUrl(source: ImageSource, label: string): string { + const segments = + source.kind === 'file' + ? ['file', source.name] + : source.kind === 'message' + ? ['msg', source.hash] + : source.kind === 'url' + ? ['url', source.url] + : [ + 'result', + source.workspace, + source.jobId, + source.format, + // The node segment is kept, empty, when a path follows it. + ...(source.nodeId || source.path?.length ? [source.nodeId ?? ''] : []), + ...(source.path?.length ? [JSON.stringify(source.path)] : []) + ] + const [kind, ...rest] = segments + return `image:${kind}/${rest.map(encodeURIComponent).join('/')}${label ? `#${encodeURIComponent(label)}` : ''}` +} + export function runFormUrl(toolCallId: string, label: string): string { return `runform:${encodeURIComponent(toolCallId)}#${encodeURIComponent(label)}` } @@ -640,6 +749,7 @@ export type PreviewSlot = | { kind: 'viewer'; viewerKind: SessionTargetKind | 'agent'; path: string } | { kind: 'artifact'; id: string; version?: number } | { kind: 'runform'; toolCallId: string } + | { kind: 'image'; source: ImageSource } | { kind: 'pageitem'; ref: PageItemRef } | { kind: 'pagelist'; path: string } | { kind: 'run'; jobId: string; workspace?: string } @@ -662,6 +772,8 @@ export function resolvePreviewTab(url: string): PreviewSlot { if (artifact) return { kind: 'artifact', id: artifact.id, version: artifact.version } const runForm = parseRunFormRoute(url) if (runForm) return { kind: 'runform', toolCallId: runForm.toolCallId } + const image = parseImageRoute(url) + if (image) return { kind: 'image', source: image.source } const pageItem = parsePageItemRoute(url) if (pageItem) return { kind: 'pageitem', ref: pageItem } const route = barePath(url) @@ -702,6 +814,7 @@ export function workspacePageHref(location: string): string | undefined { switch (slot.kind) { case 'artifact': case 'runform': + case 'image': return undefined case 'pageitem': return pageItemPageHref(slot.ref) diff --git a/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts b/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts index 368da68421..b844c4767a 100644 --- a/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts @@ -16,6 +16,8 @@ import { promptSafe, parsePreviewItemRoute, parseRunFormRoute, + parseImageRoute, + imageUrl, previewLocationLabel, resolvePreviewTab, runFormUrl, @@ -109,6 +111,7 @@ function targetUrl(target: PreviewTarget, onto?: SessionPreviewTab): string { return artifactUrl(target.id, target.name, keptVersion(target, onto)) } if (target.type === 'runform') return runFormUrl(target.toolCallId, target.label) + if (target.type === 'image') return imageUrl(target.source, target.label) // A re-point with no mode keeps the side the tab is already on, so an AI write to // an item the user left on View does not yank them back to the editor. const mode = target.mode ?? (onto ? (parsePreviewItemRoute(onto.url)?.mode ?? 'edit') : 'edit') @@ -848,6 +851,7 @@ export function describePreview( const lines = tabs.map((t) => { const where = whereIs(t) const artifact = parseArtifactRoute(where) + const image = parseImageRoute(where) const pageItem = parsePageItemRoute(where) const page = matchPreviewPage(where) const pipelineFolder = parsePipelineRoute(where) @@ -856,17 +860,25 @@ export function describePreview( ? // A pinned tab is not showing what the assistant last wrote, and nothing else in this // summary would tell it so. `artifact "${artifact.name || 'Artifact'}"${artifact.version ? ` (pinned to v${artifact.version})` : ''}` - : pageItem - ? `${pageItemKindLabel(pageItem).toLowerCase()} "${pageItem.path}"` - : page - ? `page "${page.label}"${previewLocationDetail(where)}` - : pipelineFolder - ? `pipeline "${pipelineFolder}"` - : route - ? `${route.raw_app ? 'raw_app' : route.kind} "${route.itemPath}"` - : // Trigger list pages land here (they're outside PREVIEW_PAGES), and - // their `#` is the trigger the drawer has open. - `${barePath(where)}${previewLocationDetail(where)}` + : image + ? image.source.kind === 'file' + ? `image file "${image.source.name}"` + : image.source.kind === 'message' + ? `image "${image.label || 'Image'}" from a chat message` + : image.source.kind === 'result' + ? `image result of job ${image.source.jobId}${image.source.nodeId ? ` (step ${image.source.nodeId})` : ''}` + : `image "${image.label || 'Image'}"` + : pageItem + ? `${pageItemKindLabel(pageItem).toLowerCase()} "${pageItem.path}"` + : page + ? `page "${page.label}"${previewLocationDetail(where)}` + : pipelineFolder + ? `pipeline "${pipelineFolder}"` + : route + ? `${route.raw_app ? 'raw_app' : route.kind} "${route.itemPath}"` + : // Trigger list pages land here (they're outside PREVIEW_PAGES), and + // their `#` is the trigger the drawer has open. + `${barePath(where)}${previewLocationDetail(where)}` const slotKind = resolvePreviewTab(t.url).kind const live = slotKind === 'editor' || slotKind === 'pageitem' diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index b6e819ce84..c78e77a3ed 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -227,6 +227,7 @@ function tabUsageKey(slot: PreviewSlot): string { if (slot.kind === 'editor') return slot.editorKind if (slot.kind === 'viewer') return `view_${slot.viewerKind}` if (slot.kind === 'artifact') return 'artifact' + if (slot.kind === 'image') return 'image' return slot.kind === 'runform' ? 'run_form' : 'page' } @@ -754,6 +755,9 @@ function createRuntime(session: Session): SessionRuntime { previewTabs.open({ type: 'artifact', id, name, version }) } manager.closeArtifact = (id) => previewTabs.closeArtifact(id) + manager.openImage = (source, label) => { + previewTabs.open({ type: 'image', source, label }) + } // Key the store before any configureGlobalMode runs, so a new session's first create shows at once. void manager.artifacts.setSession(session.id) diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 1229bfdc2d..2beaa4312a 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -1943,6 +1943,23 @@ export function parseS3Object(s3Object: S3Object): { s3: string; storage?: strin return { storage: match?.[1] || undefined, s3: match?.[2] ?? '' } } +const S3_IMAGE_EXTENSIONS = ['.png', '.jpeg', '.jpg', '.webp'] + +/** Whether a result's S3 object renders as an image. */ +export function isS3ImageKey(key: string): boolean { + return S3_IMAGE_EXTENSIONS.some((ext) => key.endsWith(ext)) +} + +/** The workspace's preview URL for an S3 image a job returned. */ +export function s3ImagePreviewUrl( + workspace: string, + s3object: { s3: string; storage?: string } +): string { + let url = `/api/w/${workspace}/job_helpers/load_image_preview?file_key=${encodeURIComponent(s3object.s3)}` + if (s3object.storage) url += `&storage=${s3object.storage}` + return url +} + export function formatS3Object(s3Object: S3Object): S3Uri { if (typeof s3Object === 'object') return `s3://${s3Object.storage ?? ''}/${s3Object.s3}` return s3Object