Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): stable, shift-free chat scrolling with images (#430)

Call White7c5a3f71efa2
diff --git a/core/workbench_media.py b/core/workbench_media.py
index 5f9f4851a..ed699c012 100644
--- a/core/workbench_media.py
+++ b/core/workbench_media.py
@@ -74,7 +74,19 @@ def rewrite_agent_media(conn: Connection, *, scope_id: str, session_id: str, tex
except Exception:
logger.exception("workbench_media: failed to register media for %s", safe_path)
return match.group(0)
- return f"{bang}[{label}](/api/media/{token})"
+ url = f"/api/media/{token}"
+ # For an image, carry its pixel dimensions on the URL (``?w=&h=``) so the
+ # browser reserves the box before it loads — the transcript never shifts on
+ # scroll. The proxy ignores the query and serves by token. Best-effort.
+ if bang == "!":
+ try:
+ row = media_service.get_by_token(conn, token)
+ w, h = (row or {}).get("width_px"), (row or {}).get("height_px")
+ if w and h:
+ url = f"{url}?w={w}&h={h}"
+ except Exception:
+ logger.debug("workbench_media: no dimensions for %s", safe_path, exc_info=True)
+ return f"{bang}[{label}]({url})"
return _FILE_LINK_RE.sub(_replace, text)
diff --git a/pyproject.toml b/pyproject.toml
index 2c3ae14e5..be4c434ac 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -66,6 +66,7 @@ dependencies = [
"psutil>=5.9.0",
"packaging>=23.0",
"uvicorn[standard]>=0.27",
+ "imagesize>=1.4.1",
]
[project.urls]
diff --git a/storage/alembic/versions/20260604_0015_media_dimensions.py b/storage/alembic/versions/20260604_0015_media_dimensions.py
new file mode 100644
index 000000000..e60c088f1
--- /dev/null
+++ b/storage/alembic/versions/20260604_0015_media_dimensions.py
@@ -0,0 +1,41 @@
+"""media_objects.width_px / height_px for zero-shift image rendering
+
+``storage.media_service.register`` now reads an image's pixel dimensions (header
+only, via ``imagesize``) when minting a media row and stores them here. The web
+Chat uses them to reserve an image's box before it loads, so a late-loading image
+never shifts the transcript while the user scrolls. Both columns are nullable:
+non-images and any file whose dimensions could not be read stay NULL, and the UI
+falls back to measuring the image once in the browser.
+
+Revision ID: 20260604_0015
+Revises: 20260603_0014
+Create Date: 2026-06-04
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260604_0015"
+down_revision = "20260603_0014"
+branch_labels = None
+depends_on = None
+
+
+def _columns(table: str) -> set[str]:
+ bind = op.get_bind()
+ return {row[1] for row in bind.exec_driver_sql(f"PRAGMA table_info({table})")}
+
+
+def upgrade() -> None:
+ existing = _columns("media_objects")
+ if "width_px" not in existing:
+ op.add_column("media_objects", sa.Column("width_px", sa.Integer(), nullable=True))
+ if "height_px" not in existing:
+ op.add_column("media_objects", sa.Column("height_px", sa.Integer(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("media_objects", "height_px")
+ op.drop_column("media_objects", "width_px")
diff --git a/storage/media_service.py b/storage/media_service.py
index 9a48090ae..0e3dd851f 100644
--- a/storage/media_service.py
+++ b/storage/media_service.py
@@ -9,6 +9,7 @@ and the UI file card have one shape to read.
from __future__ import annotations
+import logging
import mimetypes
import secrets
from datetime import datetime, timezone
@@ -20,6 +21,8 @@ from sqlalchemy.engine import Connection
from storage.models import media_objects
+logger = logging.getLogger(__name__)
+
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -30,6 +33,32 @@ def _new_token() -> str:
return secrets.token_urlsafe(16)
+def _probe_image_dimensions(
+ kind: str, content_type: Optional[str], local_path: str
+) -> tuple[Optional[int], Optional[int]]:
+ """Read an image's pixel ``(width, height)`` from its file header, or
+ ``(None, None)``.
+
+ Header-only (``imagesize``, no full decode, no pixel buffer) so it's cheap and
+ safe to run inline on the upload / register path. Only attempted for images;
+ any failure (unsupported format, unreadable file, library missing) degrades to
+ ``(None, None)`` — the UI then falls back to measuring the image once in the
+ browser, so dimensions are an optimization, never a hard dependency.
+ """
+ is_image = kind == "image" or (content_type or "").lower().startswith("image/")
+ if not is_image:
+ return None, None
+ try:
+ import imagesize
+
+ width, height = imagesize.get(local_path)
+ if width and height and width > 0 and height > 0:
+ return int(width), int(height)
+ except Exception:
+ logger.debug("media_service: could not read image dimensions for %s", local_path, exc_info=True)
+ return None, None
+
+
def register(
conn: Connection,
*,
@@ -84,6 +113,10 @@ def register(
if existing:
return existing
+ # Read image dimensions only for a freshly-minted row (a dedup hit above
+ # already carries them) so the UI can reserve the image's box before it loads.
+ width_px, height_px = _probe_image_dimensions(kind, ctype, str(local_path))
+
token = _new_token()
conn.execute(
media_objects.insert().values(
@@ -99,6 +132,8 @@ def register(
file_ext=ext,
size_bytes=size,
mtime_ns=mtime_ns,
+ width_px=width_px,
+ height_px=height_px,
created_at=_utc_now_iso(),
expires_at=None,
revoked_at=None,
diff --git a/storage/models.py b/storage/models.py
index d6afc5e24..629d66648 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -347,6 +347,11 @@ media_objects = Table(
Column("file_ext", String, nullable=True),
Column("size_bytes", Integer, nullable=True),
Column("mtime_ns", Integer, nullable=True),
+ # Image pixel dimensions, read at registration when the file is a decodable
+ # image (NULL for non-images / unknown). The UI uses them to reserve an
+ # image's box before it loads so the transcript never shifts on scroll.
+ Column("width_px", Integer, nullable=True),
+ Column("height_px", Integer, nullable=True),
Column("created_at", String, nullable=False),
Column("expires_at", String, nullable=True),
Column("revoked_at", String, nullable=True),
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index e1fa2e71e..ceed4ba0e 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -16,7 +16,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260603_0014"
+HEAD_REVISION = "20260604_0015"
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
@@ -45,6 +45,8 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
row[1] for row in conn.execute("pragma table_info(media_objects)")
}
assert "mtime_ns" in media_columns # 20260603_0014: dedup fingerprint
+ assert "width_px" in media_columns # 20260604_0015: zero-shift image box
+ assert "height_px" in media_columns
background_columns = {
row[1]
for row in conn.execute(
diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.py
index be9fcff8c..62227c4ba 100644
--- a/tests/test_workbench_media.py
+++ b/tests/test_workbench_media.py
@@ -8,6 +8,8 @@ SQLite migrated to head, so it never touches real ``~/.vibe_remote`` state.
from __future__ import annotations
+import struct
+import zlib
from datetime import datetime, timezone
from sqlalchemy import select
@@ -23,6 +25,23 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+def _png_bytes(width: int, height: int) -> bytes:
+ """A genuinely valid PNG of the given pixel size (stdlib only), so the
+ dimension probe reads the real header instead of a hand-faked one."""
+
+ def _chunk(typ: bytes, data: bytes) -> bytes:
+ return struct.pack(">I", len(data)) + typ + data + struct.pack(">I", zlib.crc32(typ + data) & 0xFFFFFFFF)
+
+ ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) # 8-bit RGB
+ scanlines = (b"\x00" + b"\x00\x00\x00" * width) * height # one filter byte + RGB per row
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + _chunk(b"IHDR", ihdr)
+ + _chunk(b"IDAT", zlib.compress(scanlines))
+ + _chunk(b"IEND", b"")
+ )
+
+
def _seed_scope_and_session(conn) -> str:
scope_id = settings_service.upsert_scope(
conn,
@@ -255,3 +274,78 @@ def test_register_dedups_same_fingerprint(tmp_path):
with engine.connect() as conn:
rows = conn.execute(select(media_objects)).mappings().all()
assert len(rows) == 2 # original (reused once) + the changed file
+
+
+def test_register_reads_image_dimensions(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ img = tmp_path / "wide.png"
+ img.write_bytes(_png_bytes(120, 48))
+ doc = tmp_path / "report.pdf"
+ doc.write_bytes(b"%PDF-1.4 hello")
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ img_token = media_service.register(
+ conn, scope_id=scope_id, session_id="sess_x", kind="image",
+ source="user_upload", local_path=str(img), file_name="wide.png",
+ )
+ doc_token = media_service.register(
+ conn, scope_id=scope_id, session_id="sess_x", kind="file",
+ source="user_upload", local_path=str(doc), file_name="report.pdf",
+ )
+
+ with engine.connect() as conn:
+ img_row = media_service.get_by_token(conn, img_token)
+ doc_row = media_service.get_by_token(conn, doc_token)
+
+ # The image's real header dimensions are captured…
+ assert (img_row["width_px"], img_row["height_px"]) == (120, 48)
+ # …while a non-image (and any file the probe can't read) stays NULL.
+ assert doc_row["width_px"] is None and doc_row["height_px"] is None
+
+
+def test_register_image_dimensions_unreadable_is_null(tmp_path):
+ # A file flagged as an image but not actually decodable must not break
+ # registration — dimensions degrade to NULL (UI measures it in the browser).
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ bogus = tmp_path / "broken.png"
+ bogus.write_bytes(b"not a real png")
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ token = media_service.register(
+ conn, scope_id=scope_id, session_id="sess_x", kind="image",
+ source="user_upload", local_path=str(bogus), file_name="broken.png",
+ )
+
+ with engine.connect() as conn:
+ row = media_service.get_by_token(conn, token)
+ assert row["width_px"] is None and row["height_px"] is None
+
+
+def test_rewrite_appends_image_dimensions(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ img = tmp_path / "chart.png"
+ img.write_bytes(_png_bytes(64, 32))
+ doc = tmp_path / "notes.pdf"
+ doc.write_bytes(b"%PDF-1.4")
+
+ text = f"![chart](file://{img}) and [notes](file://{doc})"
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)
+
+ # Image proxy URL carries the pixel size so the browser reserves the box…
+ assert "?w=64&h=32)" in out
+ # …and a non-image link gets no dimension query.
+ assert "/api/media/" in out.split(" and ")[1]
+ assert "?w=" not in out.split(" and ")[1]
diff --git a/ui/src/components/ui/chat-image.tsx b/ui/src/components/ui/chat-image.tsx
index 384e7bd1a..926cb5226 100644
--- a/ui/src/components/ui/chat-image.tsx
+++ b/ui/src/components/ui/chat-image.tsx
@@ -4,7 +4,7 @@ import { Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useImageViewer } from '@/components/ui/image-viewer';
-import { handleMediaDownloadClick } from '@/lib/downloadMedia';
+import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';
import { cn } from '@/lib/utils';
// When a markdown image is wrapped in a link (``[![](media)](href)``),
@@ -18,37 +18,122 @@ export const LinkedImageProvider: React.FC<{ children: React.ReactNode }> = ({ c
<LinkedImageContext.Provider value={true}>{children}</LinkedImageContext.Provider>
);
-// The width cap is an inline style so it beats the ``.vr-markdown img {
-// max-width: 100% }`` descendant rule.
+// Preview caps (mirror the design): an image renders at its natural size, scaled
+// down to fit a max width of 22rem and a max height of 15rem, never upscaled.
+const MAX_W_PX = 22 * 16; // 352
+const MAX_H_PX = 15 * 16; // 240
+// The unknown-dimensions box: inline ``max-*`` so it beats the
+// ``.vr-markdown img { max-width: 100% }`` descendant rule.
const IMG_BOX: React.CSSProperties = { maxWidth: 'min(22rem, 100%)', maxHeight: '15rem' };
const IMG_CLASS = 'block h-auto w-auto rounded-lg border border-border object-contain';
+// When the box is reserved by the parent, the image just fills it.
+const IMG_FILL_CLASS = 'block size-full rounded-lg border border-border object-contain';
+
+// Process-lifetime cache of natural pixel dimensions keyed by src, so an image
+// seen once (its ``load`` measured below) reserves its exact box on every later
+// render — scrolling back to it, switching chats and returning — with zero shift.
+// Media-proxy URLs are content-fingerprinted (the token changes when the file
+// does), so a cached size never goes stale. Best-effort mirrored to sessionStorage
+// so a reload stays shift-free too.
+const DIMS_CACHE_KEY = 'vr-img-dims';
+const dimsCache = new Map<string, { w: number; h: number }>();
+try {
+ const raw = sessionStorage.getItem(DIMS_CACHE_KEY);
+ if (raw) {
+ for (const [k, v] of Object.entries(JSON.parse(raw) as Record<string, { w: number; h: number }>)) {
+ if (v && v.w > 0 && v.h > 0) dimsCache.set(k, v);
+ }
+ }
+} catch {
+ /* no sessionStorage (private mode / SSR) — the in-memory Map still works */
+}
+function rememberDims(src: string, w: number, h: number): void {
+ if (!(w > 0 && h > 0) || dimsCache.has(src)) return;
+ dimsCache.set(src, { w, h });
+ try {
+ sessionStorage.setItem(DIMS_CACHE_KEY, JSON.stringify(Object.fromEntries(dimsCache)));
+ } catch {
+ /* quota / unavailable — keep the in-memory cache */
+ }
+}
+
+// Reserve the exact rendered box from known pixel dimensions: the widest the image
+// will ever draw (its natural width, clamped so neither cap is exceeded) plus an
+// ``aspect-ratio`` so the height is held before a single byte loads. ``maxWidth:
+// 100%`` keeps it responsive on a narrow phone (it shrinks, height tracking the
+// ratio). Returns ``undefined`` when dimensions are unknown.
+function reservedStyle(w?: number, h?: number): React.CSSProperties | undefined {
+ if (!w || !h || w <= 0 || h <= 0) return undefined;
+ const displayW = Math.min(w, MAX_W_PX, Math.round((MAX_H_PX * w) / h));
+ return { width: `${displayW}px`, maxWidth: '100%', aspectRatio: `${w} / ${h}` };
+}
// One inline chat image — used by both the Markdown renderer (agent replies) and
// the user-attachment renderer (ChatPage). Capped to a preview width and shown
// at its natural aspect (never stretched / full-width); click to open the
// lightbox; hover reveals a download button.
-export const ChatImage: React.FC<{ src: string; alt?: string; className?: string }> = ({ src, alt, className }) => {
+//
+// ``width`` / ``height`` are the source pixel dimensions when the server knows
+// them (user uploads carry them on the attachment; agent images on the proxy
+// URL). With them — or with a size measured on a prior load — the box is reserved
+// up front so loading shifts NOTHING; without them the image still renders and its
+// natural size is measured once for next time.
+export const ChatImage: React.FC<{
+ src: string;
+ alt?: string;
+ className?: string;
+ width?: number;
+ height?: number;
+}> = ({ src, alt, className, width, height }) => {
const { t } = useTranslation();
const viewer = useImageViewer();
const linked = React.useContext(LinkedImageContext);
+ const [measured, setMeasured] = React.useState<{ w: number; h: number } | null>(null);
+
+ // Source priority: server-provided > measured-this-mount > cached-from-before.
+ const cached = dimsCache.get(src);
+ const w = width ?? measured?.w ?? cached?.w;
+ const h = height ?? measured?.h ?? cached?.h;
+ const box = reservedStyle(w, h);
+
+ // Only measure while the box is still unknown; once reserved there's nothing to
+ // learn. Measuring re-renders this instance to apply the box (same size it
+ // already is → no shift) and seeds the cache for future mounts.
+ const onLoad = box
+ ? undefined
+ : (e: React.SyntheticEvent<HTMLImageElement>) => {
+ const img = e.currentTarget;
+ if (img.naturalWidth > 0 && img.naturalHeight > 0) {
+ rememberDims(src, img.naturalWidth, img.naturalHeight);
+ setMeasured({ w: img.naturalWidth, h: img.naturalHeight });
+ }
+ };
// Inside a markdown link: a bare capped image — no nested download anchor and
// no lightbox click stealing the link.
if (linked) {
return (
- <img src={src} alt={alt || ''} loading="lazy" style={IMG_BOX} className={cn('my-1 align-bottom', IMG_CLASS, className)} />
+ <img
+ src={src}
+ alt={alt || ''}
+ loading="lazy"
+ onLoad={onLoad}
+ style={box ?? IMG_BOX}
+ className={cn('my-1 align-bottom', box ? IMG_FILL_CLASS : IMG_CLASS, className)}
+ />
);
}
return (
- <span className={cn('group relative my-1 inline-block max-w-full align-bottom', className)}>
+ <span className={cn('group relative my-1 inline-block max-w-full align-bottom', className)} style={box}>
<img
src={src}
alt={alt || ''}
loading="lazy"
+ onLoad={onLoad}
onClick={() => viewer?.open(src)}
- style={IMG_BOX}
- className={cn(IMG_CLASS, viewer ? 'cursor-zoom-in' : '')}
+ style={box ? undefined : IMG_BOX}
+ className={cn(box ? IMG_FILL_CLASS : IMG_CLASS, viewer ? 'cursor-zoom-in' : '')}
/>
<Button
asChild
@@ -61,7 +146,7 @@ export const ChatImage: React.FC<{ src: string; alt?: string; className?: string
className="absolute right-2 top-2 size-7 rounded-md bg-black/55 text-white opacity-0 backdrop-blur-sm transition hover:bg-black/70 hover:text-white group-hover:opacity-100"
>
<a
- href={`${src}?download=1`}
+ href={mediaDownloadHref(src)}
download
onClick={(e) => {
e.stopPropagation();
diff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsx
index 989c790e0..717cd73fb 100644
--- a/ui/src/components/ui/file-card.tsx
+++ b/ui/src/components/ui/file-card.tsx
@@ -6,7 +6,7 @@ import type { LucideIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/apiFetch';
import { isProxyMediaUrl } from '@/lib/mediaProxy';
-import { handleMediaDownloadClick } from '@/lib/downloadMedia';
+import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';
import { useFileViewer } from '@/components/ui/file-viewer';
import { previewKind, formatBytes } from '@/lib/filePreview';
import { cn } from '@/lib/utils';
@@ -106,7 +106,7 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> =
))}
<Button asChild variant="ghost" size="icon" className="size-8 text-mint" aria-label={t('chat.media.download')}>
<a
- href={`${href}?download=1`}
+ href={mediaDownloadHref(href)}
download
onClick={(e) => handleMediaDownloadClick(e, href, meta?.name || label)}
>
diff --git a/ui/src/components/ui/image-viewer.tsx b/ui/src/components/ui/image-viewer.tsx
index a4ec9e6ce..ec7417d1d 100644
--- a/ui/src/components/ui/image-viewer.tsx
+++ b/ui/src/components/ui/image-viewer.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { ChevronLeft, ChevronRight, Download, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
-import { handleMediaDownloadClick } from '@/lib/downloadMedia';
+import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';
// A session-scoped image lightbox. ChatPage computes the ordered list of media-
// proxy image URLs in the transcript and wraps the page in a provider; any chat
@@ -96,7 +96,7 @@ export const ImageViewerProvider: React.FC<{ images: string[]; children: React.R
className={OVERLAY_BTN}
>
<a
- href={`${src}?download=1`}
+ href={mediaDownloadHref(src)}
download
onClick={(e) => {
e.stopPropagation();
diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsx
index 9244e4575..4406fb29d 100644
--- a/ui/src/components/ui/markdown.tsx
+++ b/ui/src/components/ui/markdown.tsx
@@ -4,7 +4,7 @@ import remarkGfm from 'remark-gfm';
import { ChatImage, LinkedImageProvider } from '@/components/ui/chat-image';
import { FileCard } from '@/components/ui/file-card';
-import { isProxyMediaUrl } from '@/lib/mediaProxy';
+import { isProxyMediaUrl, readMediaDims } from '@/lib/mediaProxy';
import { cn } from '@/lib/utils';
// Shared markdown renderer. react-markdown + remark-gfm (tables, strikethrough,
@@ -38,7 +38,10 @@ export const Markdown: React.FC<{ content: string; className?: string; interacti
if (!src) return null;
const url = String(src);
if (interactive && isProxyMediaUrl(url)) {
- return <ChatImage src={url} alt={alt || ''} />;
+ // Pixel dimensions ride on the proxy URL (``?w=&h=``) so the image's
+ // box is reserved before it loads — no scroll shift on the transcript.
+ const { width, height } = readMediaDims(url);
+ return <ChatImage src={url} alt={alt || ''} width={width} height={height} />;
}
const label = `🖼 ${alt || url}`;
return interactive ? (
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index f740ff5f4..a31695c3a 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -477,6 +477,10 @@ export const ChatPage: React.FC = () => {
size: a.size,
kind: a.kind,
url: a.url,
+ // Persist image pixel size when known so the box is reserved on
+ // reload (undefined keys drop out of the JSON).
+ width: a.width,
+ height: a.height,
})),
},
}
@@ -964,10 +968,16 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, onQ
const { t } = useTranslation();
const scrollRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
- // ``true`` while the viewport is pinned to (or near) the bottom — drives both
- // the auto-follow of new content and the jump button. A ref, not state, so the
- // scroll handler and ResizeObserver read it without stale closures or renders.
- const atBottomRef = useRef(true);
+ // ``true`` while the viewport is FOLLOWING the bottom (at/near it) — drives the
+ // auto-follow of new content and hides the jump button. A ref, not state, so the
+ // scroll handler + ResizeObserver read it without stale closures or extra renders.
+ const pinnedRef = useRef(true);
+ // While the user has scrolled UP to read history (not pinned), remember the
+ // topmost row still in view and how far its top sits below the viewport top, so
+ // any later content resize can put that exact row back where it was. This is a
+ // manual scroll-anchor: iOS Safari still ships no CSS ``overflow-anchor``, so a
+ // late-loading image would otherwise shift the page out from under the reader.
+ const anchorRef = useRef<{ el: HTMLElement; top: number } | null>(null);
const lastSessionRef = useRef<string | null>(null);
const [showJump, setShowJump] = useState(false);
@@ -982,16 +992,35 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, onQ
const showThinking = working && !lastIsAgentResult;
const empty = messages.length === 0 && !working;
- // Instant, not smooth: a smooth animation emits intermediate scroll events
- // that flip ``atBottomRef`` back off mid-flight (re-showing the button), and
- // if content grows during the glide the pin is skipped so it lands short of
- // the true bottom. A direct jump matches the ResizeObserver pin below and is
- // the conventional "jump to latest" behavior.
+ // Capture the topmost (partly) visible row as the restore anchor. Viewport-
+ // relative rects keep this correct regardless of the scroll container's padding;
+ // it breaks at the first visible row, so the common case (reading near the top of
+ // the loaded window) is a couple of reads. Called from the scroll handler while
+ // the user is reading history, so the anchor is always fresh when a resize lands.
+ const captureAnchor = useCallback(() => {
+ const el = scrollRef.current;
+ const content = contentRef.current;
+ if (!el || !content) return;
+ const containerTop = el.getBoundingClientRect().top;
+ for (const child of Array.from(content.children) as HTMLElement[]) {
+ const rect = child.getBoundingClientRect();
+ if (rect.bottom > containerTop) {
+ anchorRef.current = { el: child, top: rect.top - containerTop };
+ return;
+ }
+ }
+ anchorRef.current = null;
+ }, []);
+
+ // Jump to the exact bottom and resume following. Instant, not smooth: a smooth
+ // glide emits intermediate scroll events that would flip the pin off mid-flight
+ // and, if content grows during the glide, land short of the true bottom.
const scrollToBottom = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
el.scrollTop = el.scrollHeight;
- atBottomRef.current = true;
+ pinnedRef.current = true;
+ anchorRef.current = null;
setShowJump(false);
}, []);
@@ -999,10 +1028,15 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, onQ
const el = scrollRef.current;
if (!el) return;
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
- // Small tolerance keeps us "stuck" through sub-pixel rounding; the jump
+ // Small tolerance keeps us "following" through sub-pixel rounding; the jump
// button only appears once the user has scrolled up a clear distance.
- atBottomRef.current = distance < 80;
+ const pinned = distance < 80;
+ pinnedRef.current = pinned;
setShowJump(distance > 240);
+ // Only track an anchor while reading history; following needs none (the bottom
+ // is free to grow). Re-capturing here keeps it current as the user scrolls.
+ if (pinned) anchorRef.current = null;
+ else captureAnchor();
};
// Open each session pinned to the latest message (instant, no animation) —
@@ -1010,25 +1044,45 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, onQ
useEffect(() => {
if (lastSessionRef.current === session.id) return;
lastSessionRef.current = session.id;
- atBottomRef.current = true;
+ pinnedRef.current = true;
+ anchorRef.current = null;
setShowJump(false);
const id = requestAnimationFrame(() => scrollToBottom());
return () => cancelAnimationFrame(id);
}, [session.id, scrollToBottom]);
- // While the user is at the bottom, follow content growth (new messages, the
- // thinking bubble, late-loading images) so the latest stays in view; if they
- // scrolled up to read history, leave their position alone. Instant pin avoids
- // animating on rapid growth — and on image loads that would otherwise shift
- // the bottom out from under a just-opened transcript. ``empty`` is in the deps
- // so the observer (re)attaches when the scroll container mounts after an empty
- // state; ResizeObserver fires once on observe, pinning the freshly shown list.
+ // The one place scroll position reacts to content size changes — two modes,
+ // never conflated. (Conflating them WAS the bug: any resize while "at bottom"
+ // forced scrollTop=scrollHeight, and the snap's own scroll event re-armed the
+ // "at bottom" flag, so a history image loading as the user scrolled up kept
+ // yanking them back to the latest message.)
+ // • following → stay pinned to the exact bottom as content grows (new message,
+ // thinking bubble, the latest message's own image finishing to load).
+ // • reading history → restore the saved anchor so the row under the reader's
+ // eyes stays fixed wherever the growth happened: an image above expands and
+ // the anchor moves down with it (scrollTop tracks it), while growth below the
+ // anchor leaves it alone.
+ // ``[overflow-anchor:none]`` on the container hands anchoring entirely to us, so
+ // behavior is identical on every browser instead of fighting Chrome/Firefox's
+ // native anchoring; ResizeObserver delivers before paint, so the restore is
+ // flicker-free. ``empty`` is in the deps so the observer (re)attaches when the
+ // scroll container mounts after the empty state.
useEffect(() => {
const el = scrollRef.current;
const content = contentRef.current;
if (!el || !content) return;
const ro = new ResizeObserver(() => {
- if (atBottomRef.current) el.scrollTop = el.scrollHeight;
+ if (pinnedRef.current) {
+ el.scrollTop = el.scrollHeight;
+ return;
+ }
+ const anchor = anchorRef.current;
+ if (!anchor || !anchor.el.isConnected) return;
+ const currentTop = anchor.el.getBoundingClientRect().top - el.getBoundingClientRect().top;
+ const delta = currentTop - anchor.top;
+ // Sub-pixel rect noise would otherwise write scrollTop on every fire; only
+ // correct a real (≥0.5px) drift so reading history stays perfectly still.
+ if (Math.abs(delta) >= 0.5) el.scrollTop += delta;
});
ro.observe(content);
return () => ro.disconnect();
@@ -1044,7 +1098,7 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, onQ
}
return (
<div className="relative flex min-h-0 flex-1 flex-col">
- <div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 md:px-8">
+ <div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8">
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
{messages.map((message) => (
<MessageRow key={message.id} message={message} session={session} onQuickReply={onQuickReply} />
@@ -1161,8 +1215,12 @@ const MessageRow: React.FC<{
// remote host.
const isImage =
(att?.kind === 'image' || String(att?.mime || '').startsWith('image/')) && isProxyMediaUrl(url);
+ // Server-supplied pixel size (added at upload time) reserves the box so a
+ // freshly-loaded attachment never shifts the transcript.
+ const w = typeof att?.width === 'number' ? att.width : undefined;
+ const h = typeof att?.height === 'number' ? att.height : undefined;
return isImage ? (
- <ChatImage key={i} src={url} alt={typeof att?.name === 'string' ? att.name : ''} />
+ <ChatImage key={i} src={url} alt={typeof att?.name === 'string' ? att.name : ''} width={w} height={h} />
) : (
<FileCard key={i} href={url}>
{typeof att?.name === 'string' ? att.name : 'file'}
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 0b677b63e..1c2a34e9f 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -16,6 +16,11 @@ export type ComposerAttachment = {
size: number;
kind: 'image' | 'file';
url: string;
+ // Source pixel size for images, returned by the upload endpoint when it could
+ // read them — carried through to the persisted attachment so the renderer
+ // reserves the image box and loading never shifts the transcript.
+ width?: number;
+ height?: number;
status: 'uploading' | 'ready' | 'error';
};
@@ -190,7 +195,17 @@ export const Composer: React.FC<ComposerProps> = ({
setAttachments((cur) =>
cur.map((a) =>
a.localId === localId
- ? { ...a, token: json.token, url: json.url, mime: json.mime || a.mime, size: json.size ?? a.size, kind: json.kind || a.kind, status: 'ready' }
+ ? {
+ ...a,
+ token: json.token,
+ url: json.url,
+ mime: json.mime || a.mime,
+ size: json.size ?? a.size,
+ kind: json.kind || a.kind,
+ width: typeof json.width === 'number' ? json.width : undefined,
+ height: typeof json.height === 'number' ? json.height : undefined,
+ status: 'ready',
+ }
: a,
),
);
diff --git a/ui/src/lib/downloadMedia.ts b/ui/src/lib/downloadMedia.ts
index 5934fb162..495cf6ed2 100644
--- a/ui/src/lib/downloadMedia.ts
+++ b/ui/src/lib/downloadMedia.ts
@@ -22,6 +22,14 @@ import { isIosDevice, isStandalonePwa } from '@/lib/platform';
// can't run we do nothing (a rare no-op the user can just tap again — the
// refetch is cache-warm and instant) rather than navigate into the trap.
+// Build the ``<a href>`` for a media download. Appends ``download=1`` with the
+// right separator so it survives a URL that already carries a query (agent-reply
+// images keep their ``?w=&h=`` pixel-dimension hints) instead of producing an
+// invalid double ``?``.
+export function mediaDownloadHref(url: string): string {
+ return `${url}${url.includes('?') ? '&' : '?'}download=1`;
+}
+
const MIME_EXT: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
diff --git a/ui/src/lib/mediaProxy.ts b/ui/src/lib/mediaProxy.ts
index a5e877928..bfc01084b 100644
--- a/ui/src/lib/mediaProxy.ts
+++ b/ui/src/lib/mediaProxy.ts
@@ -9,3 +9,20 @@ const MEDIA_PROXY_RE = /^\/api\/media\/[^/?#]+/;
export function isProxyMediaUrl(url: string | null | undefined): boolean {
return !!url && MEDIA_PROXY_RE.test(url);
}
+
+// Agent-reply images carry their pixel dimensions as ``?w=&h=`` on the proxy URL
+// (the rewrite step appends them when known; the proxy ignores the query and serves
+// by token). The renderer reads them to reserve the image's box BEFORE it loads, so
+// a late-loading image causes zero layout shift. Returns ``{}`` when absent/invalid.
+export function readMediaDims(url: string | null | undefined): { width?: number; height?: number } {
+ if (!url) return {};
+ const q = url.indexOf('?');
+ if (q < 0) return {};
+ const params = new URLSearchParams(url.slice(q + 1));
+ const w = Number(params.get('w'));
+ const h = Number(params.get('h'));
+ return {
+ width: Number.isFinite(w) && w > 0 ? w : undefined,
+ height: Number.isFinite(h) && h > 0 ? h : undefined,
+ };
+}
diff --git a/uv.lock b/uv.lock
index 3d7bc4965..dd019c1ae 100644
--- a/uv.lock
+++ b/uv.lock
@@ -909,6 +909,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },
]
+[[package]]
+name = "imagesize"
+version = "2.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/6c/e6/7bf14eeb8f8b7251141944835abd42eb20a658d89084b7e1f3e5fe394090/imagesize-2.0.0.tar.gz", hash = "sha256:8e8358c4a05c304f1fccf7ff96f036e7243a189e9e42e90851993c558cfe9ee3", size = 1773045, upload-time = "2026-03-03T14:18:29.941Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5f/53/fb7122b71361a0d121b669dcf3d31244ef75badbbb724af388948de543e2/imagesize-2.0.0-py2.py3-none-any.whl", hash = "sha256:5667c5bbb57ab3f1fa4bc366f4fbc971db3d5ed011fd2715fd8001f782718d96", size = 9441, upload-time = "2026-03-03T14:18:27.892Z" },
+]
+
[[package]]
name = "iniconfig"
version = "2.3.0"
@@ -2206,6 +2215,7 @@ dependencies = [
{ name = "discord-py" },
{ name = "fastapi" },
{ name = "httpx", extra = ["socks"] },
+ { name = "imagesize" },
{ name = "lark-oapi" },
{ name = "markdown-to-mrkdwn" },
{ name = "packaging" },
@@ -2239,6 +2249,7 @@ requires-dist = [
{ name = "discord-py", specifier = ">=2.4.0" },
{ name = "fastapi", specifier = ">=0.110" },
{ name = "httpx", extras = ["socks"], specifier = ">=0.27" },
+ { name = "imagesize", specifier = ">=1.4.1" },
{ name = "lark-oapi", specifier = ">=1.4.0" },
{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },
{ name = "packaging", specifier = ">=23.0" },
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index aed6a17a4..9fd1ac26d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3402,6 +3402,8 @@ def media_meta(token: str):
"content_type": row.get("content_type"),
"ext": row.get("file_ext"),
"size": row.get("size_bytes"),
+ "width": row.get("width_px"),
+ "height": row.get("height_px"),
}
)
@@ -3462,6 +3464,10 @@ def sessions_attachments_create(session_id: str):
file_name=name,
content_type=mime,
)
+ # Read back the pixel dimensions register() captured (NULL for non-images
+ # / unreadable) so the client can reserve the image box and never shift the
+ # transcript when the upload renders.
+ row = media_service.get_by_token(conn, token)
return (
jsonify(
{
@@ -3471,6 +3477,8 @@ def sessions_attachments_create(session_id: str):
"size": len(raw),
"kind": kind,
"url": f"/api/media/{token}",
+ "width": row.get("width_px") if row else None,
+ "height": row.get("height_px") if row else None,
}
),
201,