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): keep Show Page icons in memory so the Dock paints them at once (#2856)

Call White6bf63df90d26
diff --git a/ui/src/apps/showPageAvatarTile.test.tsx b/ui/src/apps/showPageAvatarTile.test.tsx
index 836023a9a..2ebf6468d 100644
--- a/ui/src/apps/showPageAvatarTile.test.tsx
+++ b/ui/src/apps/showPageAvatarTile.test.tsx
@@ -1,8 +1,30 @@
+/* @vitest-environment jsdom */
+
+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';
import { renderToStaticMarkup } from 'react-dom/server';
-import { describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ShowPageAvatarContent, ShowPageAvatarTile } from './showPageAvatarTile';
+// jsdom has no object URLs; mint distinct ones so a test can tell them apart.
+let minted = 0;
+const fetchMock = vi.fn<typeof fetch>();
+
+beforeEach(() => {
+ minted = 0;
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+ URL.createObjectURL = vi.fn(() => `blob:icon-${++minted}`);
+ URL.revokeObjectURL = vi.fn();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+const iconResponse = () => new Response('<svg/>', { headers: { 'Content-Type': 'image/svg+xml' } });
+
// Guards the Dock-drag invariant (§7.1h item 3): a Dock tile is a framer-motion
// Reorder.Item whose drag pan starts ONLY when the press lands on a non-interactive
// CHILD, never on the interactive <button> itself. So the avatar content must render
@@ -17,16 +39,59 @@ describe('ShowPageAvatarContent — Dock-drag press-target invariant', () => {
expect(html).not.toContain('pointer-events-none');
});
- it('renders the icon as a filling <img draggable="false"> with no pointer-events-none', () => {
- const html = renderToStaticMarkup(
- <ShowPageAvatarContent iconUrl="/api/show-pages/ses_1/icon?v=abc" letter="S" />,
+ it('fills the tile while the icon downloads and once it shows as <img draggable="false">', async () => {
+ fetchMock.mockResolvedValueOnce(iconResponse());
+ const { container } = render(
+ <ShowPageAvatarContent iconUrl="/api/show-pages/ses_drag/icon?v=abc" letter="S" />,
);
- expect(html).toContain('<img');
- expect(html).toContain('draggable="false"'); // native image DnD stays disabled (#906)
- expect(html).toContain('size-full'); // the img is the filling press target
+ const placeholder = container.firstElementChild!;
+ expect(placeholder.tagName).toBe('SPAN');
+ expect(placeholder.className).toContain('size-full');
+ expect(placeholder.className).not.toContain('pointer-events-none');
+
+ await waitFor(() => expect(container.querySelector('img')).not.toBeNull());
+ const img = container.querySelector('img')!;
+ expect(img.getAttribute('draggable')).toBe('false'); // native image DnD stays disabled (#906)
+ expect(img.className).toContain('size-full'); // the img is the filling press target
// The #907 pointer-events-none is reverted: it pushed the press back to the
// button and re-broke drag for icon tiles.
- expect(html).not.toContain('pointer-events-none');
+ expect(img.className).not.toContain('pointer-events-none');
+ });
+});
+
+describe('ShowPageAvatarContent — icon loading', () => {
+ // Remote icons are served `no-store`, so the browser re-downloads one for every
+ // freshly mounted <img>; the hover Dock remounts its tiles on every reveal.
+ it('paints a remounted icon on its first frame without downloading it again', async () => {
+ const url = '/api/show-pages/ses_remount/icon?v=abc';
+ fetchMock.mockResolvedValueOnce(iconResponse());
+ const first = render(<ShowPageAvatarContent iconUrl={url} letter="S" />);
+ await waitFor(() => expect(first.container.querySelector('img')).not.toBeNull());
+ first.unmount();
+
+ const second = render(<ShowPageAvatarContent iconUrl={url} letter="S" />);
+ expect(second.container.querySelector('img')?.getAttribute('src')).toBe('blob:icon-1');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to the letter after bounded retries of a failing icon', async () => {
+ const url = '/api/show-pages/ses_missing/icon?v=abc';
+ fetchMock.mockResolvedValue(new Response('', { status: 404 }));
+ const { container } = render(<ShowPageAvatarContent iconUrl={url} letter="S" />);
+ await waitFor(() => expect(container.textContent).toBe('S'));
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('downloads again when the held bytes cannot be decoded', async () => {
+ const url = '/api/show-pages/ses_corrupt/icon?v=abc';
+ fetchMock.mockImplementation(async () => iconResponse());
+ const { container } = render(<ShowPageAvatarContent iconUrl={url} letter="S" />);
+ await waitFor(() => expect(container.querySelector('img')?.getAttribute('src')).toBe('blob:icon-1'));
+
+ fireEvent.error(container.querySelector('img')!);
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:icon-1');
+ await waitFor(() => expect(container.querySelector('img')?.getAttribute('src')).toBe('blob:icon-2'));
+ expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
diff --git a/ui/src/apps/showPageAvatarTile.tsx b/ui/src/apps/showPageAvatarTile.tsx
index 7c0d32931..a2c6fef6f 100644
--- a/ui/src/apps/showPageAvatarTile.tsx
+++ b/ui/src/apps/showPageAvatarTile.tsx
@@ -1,26 +1,30 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import clsx from 'clsx';
import { showPageAvatar, showPageIconUrl } from './showPageAvatar';
+import { forgetShowPageIcon, loadShowPageIcon, peekShowPageIcon } from './showPageIconCache';
// The icon-or-letter CONTENT of a Show Page avatar, WITHOUT any tile wrapper:
// the page's own HTML icon (§7.1f) rendered as an <img>, falling back to the
-// letter avatar when there is no icon OR the image fails to load (onError).
+// letter avatar when there is no icon OR the icon fails to load.
// Shared by ShowPageAvatarTile and the Dock / mobile-drawer / window-title-bar
// tiles — each provides its own accent-box wrapper — so the icon + fallback rule
// lives in one place.
//
// Freshness needs no notifier/remount machinery: `iconUrl` is content-versioned
// (`?v=<token>` from the icon file's identity), so a changed icon changes the URL,
-// which is a new `src` the browser fetches on its own.
+// which is a new download on its own. The bytes come from showPageIconCache, so a
+// remounted tile (the hover Dock remounts on every reveal) paints its icon on the
+// first frame instead of waiting for another uncacheable remote download.
//
// A load failure is retried a bounded number of times before falling back to the
-// letter: `onError` remounts the <img> (a per-URL attempt count is the `key`, so it
-// re-fetches) and only latches to the letter after MAX_ICON_LOAD_ATTEMPTS. In the
-// versioned-URL model a permanently-absent icon arrives as a null `iconUrl` (letter,
-// no <img>, no onError) — so onError only ever signals a TRANSIENT failure (a brief
-// bytes-or-404 race window, a network blip), exactly the case worth retrying. The
-// count is keyed to the URL, so a new versioned URL retries with a fresh budget.
+// letter: a failed download or an undecodable image bumps a per-URL attempt count
+// that re-runs the download, and only latches to the letter after
+// MAX_ICON_LOAD_ATTEMPTS. In the versioned-URL model a permanently-absent icon
+// arrives as a null `iconUrl` (letter, no download) — so a failure only ever
+// signals a TRANSIENT problem (a brief bytes-or-404 race window, a network blip),
+// exactly the case worth retrying. The count is keyed to the URL, so a new
+// versioned URL retries with a fresh budget.
const MAX_ICON_LOAD_ATTEMPTS = 3;
// INVARIANT (proven by live CDP real-input on the regression env, §7.1h item 3): in
// the Dock a tile is a framer-motion Reorder.Item, and its drag pan does NOT start
@@ -29,25 +33,56 @@ const MAX_ICON_LOAD_ATTEMPTS = 3;
// direct press target: the avatar content MUST render as a FILLING child element —
// never a bare text node, and never `pointer-events-none` (which pushes the press
// back through to the button and re-breaks drag). Built-in tiles already render an
-// <svg> child; here both the icon <img> and the letter fill the tile as real children.
+// <svg> child; here the icon <img>, its download placeholder, and the letter all fill
+// the tile as real children.
export const ShowPageAvatarContent: React.FC<{ iconUrl: string | null; letter: string }> = ({ iconUrl, letter }) => {
const [failure, setFailure] = useState<{ url: string; attempts: number } | null>(null);
+ const [loaded, setLoaded] = useState<{ url: string; attempts: number; src: string } | null>(null);
const attempts = failure && failure.url === iconUrl ? failure.attempts : 0;
- if (iconUrl && attempts < MAX_ICON_LOAD_ATTEMPTS) {
+ const wanted = iconUrl && attempts < MAX_ICON_LOAD_ATTEMPTS ? iconUrl : null;
+ const src = wanted
+ ? (peekShowPageIcon(wanted) ?? (loaded?.url === wanted && loaded.attempts === attempts ? loaded.src : null))
+ : null;
+
+ useEffect(() => {
+ if (!wanted) return;
+ let live = true;
+ loadShowPageIcon(wanted).then(
+ (next) => {
+ if (live) setLoaded({ url: wanted, attempts, src: next });
+ },
+ () => {
+ if (live) setFailure({ url: wanted, attempts: attempts + 1 });
+ },
+ );
+ return () => {
+ live = false;
+ };
+ }, [wanted, attempts]);
+
+ if (wanted && src) {
return (
<img
- key={`${iconUrl}#${attempts}`}
- src={iconUrl}
+ key={`${wanted}#${attempts}`}
+ src={src}
alt=""
// `draggable={false}` disables native image DnD (#906's real concern). NO
// `pointer-events-none`: the filling <img> must itself BE the press target,
// or the Dock Reorder pan can't start (see invariant above).
draggable={false}
className="size-full select-none object-cover"
- onError={() => setFailure({ url: iconUrl, attempts: attempts + 1 })}
+ onError={() => {
+ forgetShowPageIcon(wanted);
+ setFailure({ url: wanted, attempts: attempts + 1 });
+ }}
/>
);
}
+ if (wanted) {
+ // First download in flight: the bare accent tint, as an unpainted <img> showed.
+ // Still a FILLING element so a press during the download starts a Dock drag.
+ return <span aria-hidden className="block size-full select-none" />;
+ }
// A FILLING element, never a bare text node: a raw string leaves the <button>
// itself as the press target and the Dock drag won't start (see invariant above).
return (
diff --git a/ui/src/apps/showPageIconCache.ts b/ui/src/apps/showPageIconCache.ts
new file mode 100644
index 000000000..babd59907
--- /dev/null
+++ b/ui/src/apps/showPageIconCache.ts
@@ -0,0 +1,70 @@
+// Show Page icon bytes held for the life of this document, keyed by their
+// content-versioned URL and handed to <img> as object URLs.
+//
+// Remote Workbench requests receive icons as `private, no-store` so the browser
+// HTTP cache never outlives the server's per-request ACL check. Once an
+// unmounted <img> is garbage-collected, its next mount downloads the icon
+// again. The hover Dock unmounts whenever it hides, so every reveal waited one
+// tunnel round trip per pinned icon before anything appeared.
+//
+// Reuse is safe here because the server enforces `?v=` against the bytes it
+// serves: one URL always names the same content. Lookups only come from URLs an
+// authorized inventory is rendering right now, and nothing outlives the page.
+// The budget bounds memory when a library holds many large icons; the least
+// recently used entries go first.
+const BUDGET_BYTES = 16 * 1024 * 1024;
+
+type Entry = { src: string; bytes: number };
+
+// Map iteration order is insertion order, so the first entry is the least
+// recently used one.
+const entries = new Map<string, Entry>();
+const pending = new Map<string, Promise<string>>();
+let totalBytes = 0;
+
+/** The object URL already held for an icon URL, or null. Pure: safe in render. */
+export function peekShowPageIcon(url: string): string | null {
+ return entries.get(url)?.src ?? null;
+}
+
+/** Resolve an icon URL to an object URL, downloading it at most once at a time.
+ * Rejects when the download fails so the caller can retry or fall back. */
+export function loadShowPageIcon(url: string): Promise<string> {
+ const hit = entries.get(url);
+ if (hit) {
+ entries.delete(url);
+ entries.set(url, hit);
+ return Promise.resolve(hit.src);
+ }
+ let request = pending.get(url);
+ if (!request) {
+ request = download(url).finally(() => pending.delete(url));
+ pending.set(url, request);
+ }
+ return request;
+}
+
+/** Drop a held icon whose bytes the browser could not decode. */
+export function forgetShowPageIcon(url: string): void {
+ const entry = entries.get(url);
+ if (!entry) return;
+ entries.delete(url);
+ totalBytes -= entry.bytes;
+ URL.revokeObjectURL(entry.src);
+}
+
+async function download(url: string): Promise<string> {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`Show Page icon request failed with ${response.status}`);
+ const blob = await response.blob();
+ const entry = { src: URL.createObjectURL(blob), bytes: blob.size };
+ entries.set(url, entry);
+ totalBytes += entry.bytes;
+ for (const [key, old] of entries) {
+ if (totalBytes <= BUDGET_BYTES || key === url) break;
+ entries.delete(key);
+ totalBytes -= old.bytes;
+ URL.revokeObjectURL(old.src);
+ }
+ return entry.src;
+}