feat: open images in the session preview panel (#12602)

* feat: open images in the session preview panel

* fix: address review findings on the image preview

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the result path in the expanded result and report non-ready images by status

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the tool screenshot thumbnail as it was

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show job and S3 images in the preview, shared zoom control

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: show the images in an S3 result list that also holds other files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: share zoom and pan between the full-screen and panel image viewers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: drop the blob url revoke effect from the image preview tab

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: let show_image take a path into a job result or an s3 object

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: open the format a show_image path names

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem
2026-11-27 18:38:05 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 8ec6beed3a
commit 0c63dfe18c
28 changed files with 1549 additions and 272 deletions
@@ -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 @@
</div>
{/if}
<div class="flex flex-col w-full gap-10">
{#each result['render_all'] as res}
{#each result['render_all'] as res, i}
<DisplayResult
{noControls}
result={res}
resultPath={resultPath ? [...resultPath, 'render_all', i] : null}
{markupTrust}
{filename}
{disableExpand}
@@ -980,6 +1028,7 @@
<ExpandableImage
alt="png rendered"
class="w-auto h-full"
onOpen={openResultImage('png')}
src="data:image/png;base64,{contentOrRootString(result.png)}"
/>
</div>
@@ -988,6 +1037,7 @@
<ExpandableImage
alt="jpeg rendered"
class="w-auto h-full"
onOpen={openResultImage('jpeg')}
src="data:image/jpeg;base64,{contentOrRootString(result.jpeg)}"
/>
</div>
@@ -1017,6 +1067,7 @@
<ExpandableImage
alt="gif rendered"
class="w-auto h-full"
onOpen={openResultImage('gif')}
src="data:image/gif;base64,{contentOrRootString(result.gif)}"
/>
</div>
@@ -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 ?? '')}
<div class="h-full mt-2">
<ExpandableImage
alt="preview rendered"
title={s3object?.s3}
class="w-auto h-full"
src={s3DisplayUrl(s3object)}
onOpen={openS3Image(s3object)}
/>
</div>
{:else if s3object?.s3?.endsWith('.pdf')}
@@ -1311,7 +1363,7 @@
>open table preview <ArrowDownFromLine />
</button>
{/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}
<div class="h-full mt-2">
<ExpandableImage
@@ -1319,6 +1371,7 @@
title={s3object?.s3}
class="w-auto h-full"
src={s3DisplayUrl(s3object)}
onOpen={openS3Image(s3object)}
/>
</div>
{:else}
@@ -1351,6 +1404,7 @@
noControls
hideAsJson
result={output}
resultPath={null}
{markupTrust}
{filename}
{disableExpand}
@@ -1500,6 +1554,7 @@
<DisplayResult
{noControls}
{result}
{resultPath}
{markupTrust}
{filename}
{jobId}
@@ -25,9 +25,12 @@
title?: string
/** Classes for the inline thumbnail — sizing, border, radius. */
class?: string
/** Opens the image in a viewer elsewhere (a session's preview panel), offered as a
* button in the expanded view. */
onOpen?: () => 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 @@
}}
/>
<ImageViewer bind:isOpen {src} {alt} {title} />
<ImageViewer bind:isOpen {src} {alt} {title} onOpenInPreview={onOpen} />
@@ -0,0 +1,151 @@
<script lang="ts">
import { Download, Grid2x2, Maximize, Moon, Sun } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import ZoomControl from './ZoomControl.svelte'
import { useZoomPan } from './zoomPan.svelte'
import { twMerge } from 'tailwind-merge'
import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte'
interface Props {
src: string
/** Shown in the header and used as the download's file name. */
name: string
/** Byte size, shown beside the dimensions when known. */
bytes?: number
}
let { src, name, bytes }: Props = $props()
type Backdrop = 'checker' | 'light' | 'dark'
const BACKDROPS = {
light: { label: 'Light', icon: Sun },
dark: { label: 'Dark', icon: Moon },
checker: { label: 'Checkerboard', icon: Grid2x2 }
} as const
// Room kept around a fitted image so its edges stay visible against the backdrop.
const view = useZoomPan({ margin: { x: 32, y: 32 } })
// The source that failed, not a flag: a new `src` (the file fixed and re-read) must mount
// the image again, and only the image's own load event could clear a flag.
let failedSrc = $state<string>()
const failed = $derived(failedSrc === src)
// Until the viewer picks one, the backdrop is Windmill's own theme, and follows it.
const isDark = useIsDarkMode()
let chosenBackdrop = $state<Backdrop | undefined>(undefined)
const backdrop = $derived<Backdrop>(chosenBackdrop ?? (isDark.val ? 'dark' : 'light'))
// The cycle starts at the theme's own backdrop, so the first click swaps light and dark.
const backdropCycle = $derived<Backdrop[]>(
isDark.val ? ['dark', 'light', 'checker'] : ['light', 'dark', 'checker']
)
const nextBackdrop = $derived(
backdropCycle[(backdropCycle.indexOf(backdrop) + 1) % backdropCycle.length]
)
function humanSize(n: number): string {
if (n < 1024) return `${n} B`
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
return `${(n / (1024 * 1024)).toFixed(1)} MB`
}
// A 16px checkerboard, the usual stand-in for "transparent".
const CHECKER_STYLE =
'background-color:#ffffff;background-image:linear-gradient(45deg,#e5e7eb 25%,transparent 25%,transparent 75%,#e5e7eb 75%),linear-gradient(45deg,#e5e7eb 25%,transparent 25%,transparent 75%,#e5e7eb 75%);background-size:16px 16px;background-position:0 0,8px 8px'
</script>
<div class="flex flex-col h-full min-h-0 bg-surface">
<!-- The file name is the tab's label already; this bar carries what the tab cannot. -->
<div
class="flex flex-wrap items-center justify-between gap-x-2 gap-y-1 px-4 py-2 border-b border-border-light"
>
<span class="text-xs text-secondary whitespace-nowrap tabular-nums" title={name}>
{#if view.natural}
{view.natural.w} × {view.natural.h}{bytes !== undefined ? ` · ${humanSize(bytes)}` : ''}
{/if}
</span>
<div class="flex flex-wrap items-center gap-1">
<ZoomControl
scale={view.natural ? view.scale : undefined}
min={view.minScale}
max={view.maxScale}
onZoomOut={view.zoomOut}
onZoomIn={view.zoomIn}
onZoomTo={view.zoomToAnimated}
/>
<Button
unifiedSize="sm"
variant="subtle"
iconOnly
startIcon={{ icon: Maximize }}
title="Fit to panel (0)"
disabled={!view.natural}
onClick={view.fit}
/>
<Button
unifiedSize="sm"
variant={view.zoom === 1 ? 'default' : 'subtle'}
title="Actual size (1)"
disabled={!view.natural}
onClick={view.actualSize}
>
1:1
</Button>
<Button
unifiedSize="sm"
variant="subtle"
iconOnly
startIcon={{ icon: BACKDROPS[backdrop].icon }}
title={`${BACKDROPS[backdrop].label} background, click for ${BACKDROPS[nextBackdrop].label.toLowerCase()}`}
onClick={() => (chosenBackdrop = nextBackdrop)}
/>
<Button
unifiedSize="sm"
variant="subtle"
iconOnly
startIcon={{ icon: Download }}
title="Download"
href={src}
download={name}
/>
</div>
</div>
<!-- The viewport takes keys and the wheel itself: zoom follows the cursor, so it has to
be the element under it. ARIA's `application` role is the one for a surface that
handles its own pointer and keys, but Svelte does not count it as interactive. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
<div
class={twMerge(
'relative flex-1 min-h-0 overflow-hidden outline-none select-none touch-none',
backdrop === 'light' && 'bg-white',
// The dark theme's surface-secondary in either theme: the light theme holds it as `-inverse`.
backdrop === 'dark' && (isDark.val ? 'bg-surface-secondary' : 'bg-surface-secondary-inverse'),
view.pannable ? (view.panning ? 'cursor-grabbing' : 'cursor-grab') : 'cursor-default'
)}
style={backdrop === 'checker' ? CHECKER_STYLE : undefined}
{@attach view.surface}
tabindex="0"
role="application"
aria-roledescription="image viewer"
aria-label={`${name}. Plus and minus zoom, 0 fits, 1 shows actual size.`}
onkeydown={(e) => {
if (view.handleKey(e)) e.preventDefault()
}}
>
{#if failed}
<div class="absolute inset-0 flex items-center justify-center p-4">
<span class="rounded-md bg-surface px-3 py-2 text-xs text-secondary shadow-sm">
This file could not be displayed as an image.
</span>
</div>
{:else}
<img
{@attach view.image}
{src}
alt={name}
draggable="false"
onerror={() => (failedSrc = src)}
class={view.imageClass}
style={view.imageStyle}
/>
{/if}
</div>
</div>
@@ -1,8 +1,9 @@
<script lang="ts">
import Portal from '$lib/components/Portal.svelte'
import { Copy, Download, ExternalLink, X, ZoomIn, ZoomOut } from 'lucide-svelte'
import { Copy, Download, ExternalLink, Maximize, PanelRight, X } from 'lucide-svelte'
import ZoomControl from './ZoomControl.svelte'
import { useZoomPan } from './zoomPan.svelte'
import { fade } from 'svelte/transition'
import { on } from 'svelte/events'
import { sendUserToast } from '$lib/toast'
import Button from '../button/Button.svelte'
import Disposable from '../drawer/Disposable.svelte'
@@ -15,41 +16,23 @@
* ends in an extension (an S3 key, an attachment's file name). */
title?: string
isOpen: boolean
/** Shows the image in a viewer elsewhere (a session's preview panel), closing this one. */
onOpenInPreview?: () => void
}
let { src, alt = '', title, isOpen = $bindable() }: Props = $props()
let { src, alt = '', title, isOpen = $bindable(), onOpenInPreview }: Props = $props()
const caption = $derived(title || alt || 'Image')
const ZOOM_STEPS = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8]
const MAX_SCALE = 8
// Room kept around a fitted image: the top bar overlays the stage, so the image clears it.
const FIT_MARGIN_X = 48
const FIT_MARGIN_Y = 128
/** A plain click beside the image dismisses; one that ends a pan does not. */
let dismissOnClick = false
const view = useZoomPan({
// The top bar overlays the stage, so a fitted image keeps clear of it.
margin: { x: 48, y: 128 },
onTap: (onImage) => (dismissOnClick = !onImage)
})
let natural = $state<{ w: number; h: number } | undefined>(undefined)
let stageW = $state(0)
let stageH = $state(0)
let stage: HTMLDivElement | undefined = $state(undefined)
let imgEl: HTMLImageElement | undefined = $state(undefined)
/** `fit` follows the viewport as it resizes; a number is a fixed scale of the natural size. */
let zoom: number | 'fit' = $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)
const fitScale = $derived(
natural && stageW && stageH
? Math.min(1, (stageW - FIT_MARGIN_X) / natural.w, (stageH - FIT_MARGIN_Y) / 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 > stageW + 1 || natural.h * scale > stageH + 1)
)
let disposable: Disposable | undefined = $state(undefined)
const hostActive = overlayHostActive()
const shown = overlayShown()
@@ -59,123 +42,13 @@
// A bound `open` alone does not put the viewer on the disposable stack, and the stack
// lifts it above the drawer or dialog it was opened from and gives Escape to the topmost.
disposable?.openDrawer()
zoom = 'fit'
pan = { x: 0, y: 0 }
animate = false
view.reset()
}
function close() {
isOpen = false
}
function clampPan(p: { x: number; y: number }, s: number) {
if (!natural) return { x: 0, y: 0 }
const maxX = Math.max(0, (natural.w * s - stageW) / 2)
const maxY = Math.max(0, (natural.h * s - stageH) / 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 stage centre; that point stays under the pointer while zooming. */
function zoomTo(next: number, at = { 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 stagePoint(e: { clientX: number; clientY: number }) {
const r = stage!.getBoundingClientRect()
return { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 }
}
function toggleZoom(e: MouseEvent) {
// The stage captures the pointer, so the double click targets the stage, not the image.
const r = imgEl?.getBoundingClientRect()
if (
!r ||
e.clientX < r.left ||
e.clientX > r.right ||
e.clientY < r.top ||
e.clientY > r.bottom
)
return
animate = true
if (zoom === 'fit' || Math.abs(scale - fitScale) < 0.001) {
zoomTo(fitScale < 1 ? 1 : 2, stagePoint(e))
} else {
fit()
}
}
function wheelZoom(node: HTMLElement) {
// Registered by hand: the default must be prevented, so the listener cannot be passive.
return on(
node,
'wheel',
(e: WheelEvent) => {
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), stagePoint(e))
},
{ passive: false }
)
}
let panning = $state(false)
let drag:
| { x: number; y: number; pan: { x: number; y: number }; moved: boolean; onImage: boolean }
| undefined
function onPointerDown(e: PointerEvent) {
if (e.button !== 0) return
drag = { x: e.clientX, y: e.clientY, pan, moved: false, onImage: e.target === imgEl }
stage?.setPointerCapture(e.pointerId)
}
function onPointerMove(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)
}
}
/** A plain click beside the image dismisses; one that ends a pan does not. */
let dismissOnClick = false
function onPointerUp() {
dismissOnClick = !!drag && !drag.moved && !drag.onImage
drag = undefined
panning = false
}
function onStageClick() {
// Closed on `click`, not `pointerup`: outside-click guards elsewhere (the chat composer)
// listen for this click and must still see the viewer open when it arrives.
@@ -185,20 +58,7 @@
function onKeyDown(e: KeyboardEvent) {
if (!isOpen || !hostActive() || !(disposable?.isTopmost() ?? true)) return
if (e.metaKey || e.ctrlKey || e.altKey) return
const action = {
'+': zoomIn,
'=': zoomIn,
'-': zoomOut,
'0': fit,
'1': () => {
animate = true
zoomTo(1)
}
}[e.key]
if (!action) return
e.preventDefault()
action()
if (view.handleKey(e)) e.preventDefault()
}
const MIME_EXT: Record<string, string> = {
@@ -313,39 +173,21 @@
transition:fade|local={{ duration: 150 }}
>
<div
bind:this={stage}
bind:clientWidth={stageW}
bind:clientHeight={stageH}
{@attach wheelZoom}
{@attach view.surface}
class="absolute inset-0 overflow-hidden touch-none select-none"
class:cursor-grab={pannable && !panning}
class:cursor-grabbing={panning}
class:cursor-grab={view.pannable && !view.panning}
class:cursor-grabbing={view.panning}
role="presentation"
onpointerdown={onPointerDown}
onpointermove={onPointerMove}
onpointerup={onPointerUp}
onclick={onStageClick}
onpointercancel={() => {
drag = undefined
panning = false
}}
ondblclick={toggleZoom}
>
<img
bind:this={imgEl}
{@attach view.image}
{src}
{alt}
draggable="false"
class="absolute left-1/2 top-1/2 max-w-none {natural ? '' : 'opacity-0'} {animate
? 'transition-transform duration-150 ease-out'
: ''}"
style="width: {natural?.w ?? 0}px; height: {natural?.h ??
0}px; transform: translate(-50%, -50%) translate({pan.x}px, {pan.y}px) scale({scale});"
onload={(e) => {
const el = e.currentTarget as HTMLImageElement
// An SVG without width/height has no intrinsic size.
natural = { w: el.naturalWidth || 1024, h: el.naturalHeight || 768 }
}}
class={view.imageClass}
style={view.imageStyle}
/>
</div>
@@ -353,44 +195,35 @@
class="absolute inset-x-0 top-0 flex items-center justify-between gap-3 p-3 pointer-events-none"
>
<div
class="flex items-baseline gap-2 min-w-0 h-9 px-3 leading-9 rounded-md bg-surface-tertiary shadow-lg pointer-events-auto"
class="flex items-baseline gap-2 min-w-0 h-9 px-1 leading-9 drop-shadow pointer-events-auto"
>
<span class="truncate text-xs font-semibold text-emphasis">{caption}</span>
{#if natural}
<span class="shrink-0 text-2xs text-secondary tabular-nums">
{natural.w} × {natural.h}
<!-- The overlay is black in both themes, and a zoomed image can pass under the
caption, hence fixed white text with a shadow rather than theme tokens. -->
<span class="truncate text-xs font-medium text-white/90">{caption}</span>
{#if view.natural}
<span class="shrink-0 text-2xs text-white/60 tabular-nums">
{view.natural.w} × {view.natural.h}
</span>
{/if}
</div>
<div
class="flex shrink-0 items-center gap-0.5 h-9 px-1 rounded-md bg-surface-tertiary shadow-lg pointer-events-auto"
>
<Button
variant="subtle"
unifiedSize="sm"
iconOnly
startIcon={{ icon: ZoomOut }}
title="Zoom out (−)"
disabled={scale <= minScale + 0.001}
onclick={zoomOut}
<ZoomControl
scale={view.scale}
min={view.minScale}
max={view.maxScale}
onZoomOut={view.zoomOut}
onZoomIn={view.zoomIn}
onZoomTo={view.zoomToAnimated}
/>
<Button
variant="subtle"
unifiedSize="sm"
btnClasses="w-14 justify-center tabular-nums"
title="Fit to screen (0)"
onclick={fit}
>
{Math.round(scale * 100)}%
</Button>
<Button
variant="subtle"
unifiedSize="sm"
iconOnly
startIcon={{ icon: ZoomIn }}
title="Zoom in (+)"
disabled={scale >= MAX_SCALE - 0.001}
onclick={zoomIn}
startIcon={{ icon: Maximize }}
title="Fit to screen (0)"
onclick={view.fit}
/>
<div class="w-px h-4 mx-1 bg-border-light"></div>
<Button
@@ -417,6 +250,19 @@
title="Open in new tab"
onclick={openInNewTab}
/>
{#if onOpenInPreview}
<Button
variant="subtle"
unifiedSize="sm"
iconOnly
startIcon={{ icon: PanelRight }}
title="Open in preview"
onclick={() => {
close()
onOpenInPreview?.()
}}
/>
{/if}
<div class="w-px h-4 mx-1 bg-border-light"></div>
<Button
variant="subtle"
@@ -0,0 +1,97 @@
<script lang="ts">
import { Minus, Plus } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import TextInput from '$lib/components/text_input/TextInput.svelte'
interface Props {
/** Current scale, 1 is actual size; undefined while there is no image. */
scale: number | undefined
min: number
max: number
onZoomOut: () => void
onZoomIn: () => void
/** A scale typed by the user, already clamped to `min`..`max`. */
onZoomTo: (scale: number) => void
}
let { scale, min, max, onZoomOut, onZoomIn, onZoomTo }: Props = $props()
const percent = $derived(scale === undefined ? '' : `${Math.round(scale * 100)}%`)
let draft = $state<string | undefined>(undefined)
function edit() {
if (scale !== undefined) draft = String(Math.round(scale * 100))
}
function commit() {
if (draft === undefined) return
const typed = parseFloat(draft.replace('%', '').trim())
draft = undefined
if (Number.isFinite(typed) && typed > 0) {
onZoomTo(Math.min(max, Math.max(min, typed / 100)))
}
}
function onKeyDown(e: KeyboardEvent) {
// The viewers bind +, -, 0 and 1 as zoom shortcuts; typed digits must not reach them.
e.stopPropagation()
if (e.key === 'Enter') commit()
else if (e.key === 'Escape') {
e.preventDefault()
draft = undefined
}
}
function focusAndSelect(node: HTMLElement) {
const input = node.querySelector('input')
input?.focus()
input?.select()
}
</script>
<div class="flex items-center gap-0.5">
{#if draft !== undefined}
<div class="w-14" {@attach focusAndSelect}>
<TextInput
size="sm"
bind:value={draft}
class="text-center tabular-nums"
inputProps={{
'aria-label': 'Zoom level in percent',
inputmode: 'decimal',
onkeydown: onKeyDown,
onblur: commit
}}
/>
</div>
{:else}
<Button
unifiedSize="sm"
variant="subtle"
btnClasses="w-14 justify-center tabular-nums"
title="Set zoom level"
disabled={scale === undefined}
onClick={edit}
>
{percent}
</Button>
{/if}
<Button
unifiedSize="sm"
variant="subtle"
iconOnly
startIcon={{ icon: Minus }}
title="Zoom out (-)"
disabled={scale === undefined || scale <= min + 1e-3}
onClick={onZoomOut}
/>
<Button
unifiedSize="sm"
variant="subtle"
iconOnly
startIcon={{ icon: Plus }}
title="Zoom in (+)"
disabled={scale === undefined || scale >= max - 1e-3}
onClick={onZoomIn}
/>
</div>
@@ -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<ImageOpener | undefined>(KEY)
}
@@ -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 `<img>`, 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<number | 'fit'>('fit')
let pan = $state<Point>({ 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
}
}
}
@@ -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) {
@@ -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<boolean>(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<string, any>, memoryId?: string) =>
@@ -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}
</div>
@@ -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)}
/>
</div>
{/if}
@@ -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
}
@@ -36,7 +36,17 @@
{#snippet chip(card: Card)}
{#if card.kind === 'folder'}
<AttachedFolderChip folder={card.folder} onRemove={() => removeCard(card)} />
<AttachedFolderChip
folder={card.folder}
onRemove={() => removeCard(card)}
onOpenImage={aiChatManager.openImage
? (f) =>
aiChatManager.openImage?.(
{ kind: 'file', name: f.name },
f.name.split('/').pop() || f.name
)
: undefined}
/>
{:else}
<AttachedFileChip file={card.file} onRemove={() => removeCard(card)} />
{/if}
@@ -1,28 +1,52 @@
<script lang="ts">
import { Folder, X, Loader2, AlertTriangle, Lock } from 'lucide-svelte'
import type { AttachedFolder } from './attachedFiles.svelte'
import Popover from '$lib/components/meltComponents/Popover.svelte'
import { Button } from '$lib/components/common'
import { getFileIcon } from '$lib/components/icons/fileIcon'
import type { AttachedFile, AttachedFolder } from './attachedFiles.svelte'
import { isViewableImageName } from './imageFiles'
let { folder, onRemove }: { folder: AttachedFolder; onRemove: () => void } = $props()
let {
folder,
onRemove,
onOpenImage
}: {
folder: AttachedFolder
onRemove: () => void
/** Shows an image of the folder beside the chat; without it images are listed only. */
onOpenImage?: (file: AttachedFile) => void
} = $props()
let showDelete = $state(false)
let popover: Popover | undefined = $state(undefined)
// Native tooltip listing the contained files (capped).
let hoverList = $derived.by(() => {
if (folder.status === 'locked') return `${folder.name}/ — locked, click send to restore`
if (folder.status === 'unavailable') return `${folder.name}/ — unavailable`
const max = 20
const shown = folder.files.slice(0, max).map((f) => f.name)
if (folder.files.length > max) shown.push(`… +${folder.files.length - max} more`)
return `${folder.name}/\n${shown.join('\n')}`
})
// The list renders every row; past this a folder is a build output, not something to browse.
const MAX_LISTED = 300
const sorted = $derived(
[...folder.files].sort((a, b) => (a.relPath ?? a.name).localeCompare(b.relPath ?? b.name))
)
const imageCount = $derived(folder.files.filter((f) => isOpenable(f)).length)
function isOpenable(f: AttachedFile): boolean {
return f.status === 'ready' && isViewableImageName(f.sourceName ?? f.name)
}
/** Path inside the folder: the folder's own name is the chip's label already. */
function innerPath(f: AttachedFile): string {
const path = f.relPath ?? f.name
const prefix = `${folder.name}/`
return path.startsWith(prefix) ? path.slice(prefix.length) : path
}
const canList = $derived(folder.status !== 'locked' && folder.status !== 'unavailable')
</script>
<div
class="border rounded-md px-1 py-0.5 flex flex-row items-center gap-1 text-primary text-xs font-normal cursor-default hover:bg-surface-hover hover:cursor-pointer max-w-48 bg-surface"
class="border rounded-md px-1 py-0.5 flex flex-row items-center gap-1 text-primary text-xs font-normal cursor-default hover:bg-surface-hover max-w-48 bg-surface"
onmouseenter={() => (showDelete = true)}
onmouseleave={() => (showDelete = false)}
role="listitem"
title={hoverList}
>
<button
class="shrink-0"
@@ -44,5 +68,70 @@
<Folder size={16} class="text-tertiary" />
{/if}
</button>
<span class="truncate" title={folder.name}>{folder.name}</span>
{#if canList}
<Popover bind:this={popover} placement="top-start" class="min-w-0" contentClasses="p-0">
{#snippet trigger()}
<span class="block truncate cursor-pointer" title={`Show the files in ${folder.name}`}
>{folder.name}</span
>
{/snippet}
{#snippet content()}
<div class="flex flex-col w-72 max-w-[80vw]">
<div class="px-3 py-2 border-b border-border-light text-2xs text-secondary">
<span class="font-semibold text-emphasis">{folder.name}/</span>
· {folder.files.length}
{folder.files.length === 1 ? 'file' : 'files'}{imageCount > 0
? ` · ${imageCount} ${imageCount === 1 ? 'image' : 'images'}`
: ''}
</div>
<ul class="max-h-72 overflow-y-auto py-1" aria-label={`Files in ${folder.name}`}>
{#each sorted.slice(0, MAX_LISTED) as f (f.name)}
{@const icon = getFileIcon(f.name)}
{@const Icon = icon.icon}
<li>
{#if onOpenImage && isOpenable(f)}
<Button
variant="subtle"
unifiedSize="sm"
wrapperClasses="w-full"
btnClasses="w-full !justify-start rounded-none font-normal"
title={`Open ${innerPath(f)} in the preview`}
onClick={() => {
onOpenImage(f)
popover?.close()
}}
>
<Icon size={14} class="shrink-0 {icon.className ?? ''}" />
<span class="truncate">{innerPath(f)}</span>
</Button>
{:else}
<div
class="flex items-center gap-2 px-3 py-1 text-xs text-secondary"
title={innerPath(f)}
>
<Icon size={14} class="shrink-0 {icon.className ?? ''}" />
<span class="truncate">{innerPath(f)}</span>
</div>
{/if}
</li>
{:else}
<li class="px-3 py-1 text-xs text-tertiary">No files linked from this folder.</li>
{/each}
{#if sorted.length > MAX_LISTED}
<li class="px-3 py-1 text-2xs text-tertiary">
… {sorted.length - MAX_LISTED} more
</li>
{/if}
</ul>
</div>
{/snippet}
</Popover>
{:else}
<span
class="truncate"
title={folder.status === 'locked'
? `${folder.name}/ — locked, click send to restore`
: `${folder.name}/ — unavailable`}>{folder.name}</span
>
{/if}
</div>
@@ -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<string | undefined> {
if (!(await this.#sniffText(file))) return 'Not a text file'
async #preflight(file: File, rawPath: string): Promise<string | undefined> {
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<boolean> {
return isRasterImageName(path) || (await this.#sniffText(file))
}
async #sniffText(file: Blob): Promise<boolean> {
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)
}
}
}
@@ -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' },
@@ -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([])
})
})
@@ -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<typeof parseS3Object>[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<string, unknown>
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<string | number, unknown>)[key]
}
if (format) {
// The named field, not the first image field of the object holding it.
const v = (value as Record<string, unknown> | 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<string> {
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')
@@ -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<string, string> = {
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 `<img>`, 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<object, { dataUrl: string; key: string }>()
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)}`
}
@@ -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 {
@@ -0,0 +1,149 @@
<script lang="ts">
import { Button } from '$lib/components/common'
import ImagePanelViewer from '$lib/components/common/image/ImagePanelViewer.svelte'
import type { AIChatManager } from '../copilot/chat/AIChatManager.svelte'
import { asImageBlob, imageContentKey } from '../copilot/chat/files/imageFiles'
import type { ImageSource } from './previewRouter'
import { resource } from 'runed'
import { onDestroy } from 'svelte'
import { JobService } from '$lib/gen'
interface Props {
manager: AIChatManager
source: ImageSource
label: string
}
let { manager, source, label }: Props = $props()
// A session link, never a message attachment: those share the namespace only by name.
const file = $derived(
source.kind === 'file'
? manager.attachedFiles.files.find(
(f) => f.name === source.name && !f.messageScoped && !f.isFolderRoot
)
: undefined
)
// A folder whose permission lapsed after a reload keeps only its placeholder row.
const folderLocked = $derived(
source.kind === 'file' &&
!file &&
manager.attachedFiles.folders.some(
(f) => f.status === 'locked' && source.name.startsWith(`${f.name}/`)
)
)
const messageImage = $derived.by(() => {
if (source.kind !== 'message') return undefined
// A user's attachment, or an image a tool produced (a screenshot).
for (const m of manager.displayMessages) {
if (m.role === 'user') {
for (const image of m.images ?? []) {
if (imageContentKey(image.dataUrl, image) === source.hash) return image
}
} else if (m.role === 'tool' && m.imageUrl?.startsWith('data:')) {
if (imageContentKey(m.imageUrl, m) === source.hash)
return { dataUrl: m.imageUrl, name: undefined }
}
}
return undefined
})
const blob = $derived(
file && file.status === 'ready'
? asImageBlob(file.file, file.sourceName ?? file.name)
: undefined
)
// A live object URL keeps its blob's backing data (an unlinked file's IndexedDB copy
// included) until revoked, so each one is released when the next replaces it and on unmount.
let lastUrl: string | undefined
const blobUrl = $derived.by(() => {
if (lastUrl) URL.revokeObjectURL(lastUrl)
lastUrl = blob ? URL.createObjectURL(blob) : undefined
return lastUrl
})
onDestroy(() => {
if (lastUrl) URL.revokeObjectURL(lastUrl)
})
// An inline result is fetched again from its job: the tab keeps only the job's address.
const resultImage = resource(
() => (source.kind === 'result' ? source : undefined),
async (s) => {
if (!s) return undefined
const full: unknown = s.nodeId
? await JobService.resultById({
workspace: s.workspace,
flowJobId: s.jobId,
nodeId: s.nodeId
})
: await JobService.getCompletedJobResult({ workspace: s.workspace, id: s.jobId })
let result = full
for (const key of s.path ?? []) result = (result as Record<string | number, unknown>)?.[key]
// DisplayResult takes either the base64 string or `{ content }`.
const value = (result as Record<string, unknown> | undefined)?.[s.format]
const b64 =
typeof value === 'string'
? value
: typeof (value as { content?: unknown })?.content === 'string'
? (value as { content: string }).content
: undefined
return b64 ? `data:image/${s.format};base64,${b64}` : null
}
)
const src = $derived(
source.kind === 'message'
? messageImage?.dataUrl
: source.kind === 'result'
? (resultImage.current ?? undefined)
: source.kind === 'url'
? source.url
: blobUrl
)
const name = $derived(
source.kind === 'file'
? source.name.split('/').pop() || source.name
: source.kind === 'message'
? messageImage?.name || label || 'Image'
: source.kind === 'result'
? `${label || 'result'}.${source.format === 'jpeg' ? 'jpg' : source.format}`
: label || 'Image'
)
</script>
{#if src}
<ImagePanelViewer {src} {name} bytes={file?.size} />
{:else if folderLocked}
<div class="flex flex-col items-start gap-2 p-4 text-xs text-secondary">
<span>Your browser needs permission again to read this folder.</span>
<Button
unifiedSize="sm"
variant="default"
onClick={() => void manager.attachedFiles.regrantLocked()}
>
Restore access
</Button>
</div>
{:else if source.kind === 'result'}
<div class="p-4 text-xs text-secondary">
{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.'}
</div>
{:else if file && file.status !== 'ready'}
<div class="p-4 text-xs text-secondary">
{file.status === 'indexing' ? 'Loading…' : 'This image is no longer available.'}
</div>
{:else}
<div class="p-4 text-xs text-secondary">
{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.'}
</div>
{/if}
@@ -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 @@
<div class="p-4 text-sm text-tertiary">This artifact is no longer available.</div>
{/if}
</div>
{:else if slot.kind === 'image' && mounted}
<div
class="absolute inset-0 flex flex-col min-h-0 bg-surface {visibility}"
aria-hidden={!active}
{inert}
>
{#if runtime}
<ImagePreviewSlot
manager={runtime.manager}
source={slot.source}
label={parseImageRoute(tab.url)?.label ?? ''}
/>
{/if}
</div>
{:else if slot.kind === 'runform' && mounted}
<div
bind:this={overlayHostEl}
@@ -10,6 +10,7 @@
<script lang="ts">
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>('aiChatManager', runtime.manager)
setImageOpener((source, label) => runtime.manager.openImage?.(source, label))
}
// Reactive session reference (mutations to summary/target propagate via the $state proxy).
@@ -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()
})
})
@@ -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/<name>` or `image:msg/<hash>`, 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)
@@ -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 `#<path>` 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 `#<path>` is the trigger the drawer has open.
`${barePath(where)}${previewLocationDetail(where)}`
const slotKind = resolvePreviewTab(t.url).kind
const live =
slotKind === 'editor' || slotKind === 'pageitem'
@@ -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)
+17
View File
@@ -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