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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(pet): pin Open in Avibe to the history corner and deepen its fades (#2825)
Max7e3cd6533d30
diff --git a/docs/plans/2026-10-12-desktop-mini-main-agent.md b/docs/plans/2026-10-12-desktop-mini-main-agent.mdindex 2c2aff683..3f9bde595 100644--- a/docs/plans/2026-10-12-desktop-mini-main-agent.md+++ b/docs/plans/2026-10-12-desktop-mini-main-agent.md@@ -173,9 +173,31 @@ position in both states, so collapsing needs no mouse travel; the bubble'sbottom edge and tail never move. The toggle stays first in the DOM, so focusorder is unchanged; CSS places the detail above it, and the toggle's`aria-controls` names the detail. The divider sits between the history and the-toggle row. On open the history shows the newest result, which is closest to-the toggle row, with the §7.5 edge fades. Quick replies, Vault handoffs, notices and Open in-Avibe follow it at the end of the detail, right above the toggle row. Collapsed shows an up chevron and expanded a down chevron.+toggle row. On open the history scrolls to the very bottom, chat-style: the end+of the newest result and the quick replies, Vault handoffs and notices that+follow it sit right above the toggle row, with the §7.5 edge fades (no bottom+fade, since the end is reached). While it is open, new content keeps a reader+who is at the bottom (within 8px) pinned there and leaves one who has scrolled+up where they are. Mark-read needs any part of the latest result in view. Collapsed shows an up chevron and expanded a down chevron.++Open in Avibe is an icon-only button (the card's `ExternalLink` open button,+28px, on a solid surface) pinned to the top-right corner of the open history,+8px from the bubble's outer edge on both the top and the right, which centres+it on the 22px corner arc,+outside the scroll box: it stays put while the history scrolls, is never faded+by the edge mask, and exists only while the history is open. Its accessible name is+"Open in Avibe", and instead of a native `title` it shows a pet-styled tooltip+with that text: after about 350ms of hover, at once on keyboard focus, gone on+leave, blur or Escape (which it takes before the pet's own Escape). The tooltip+sits below the icon, right-aligned; the activity cards' open button uses the+same button and tooltip, placed to its left so the card scroll box cannot clip+it. Both are portalled to the pet stage. Hover only reaches the page while the+pet window receives hover (§5.1), which it does once opening the history or the+cards has made it key. The history's top padding reserves that corner,+so at the top of the scroll it covers no text. An incomplete unread tail keeps+its "More replies in Avibe" notice as plain text; the pinned button is the way+there. The history's scrollbar is hidden like the card list's (§3.2); the edge+fades show there is more.Detail retains the 280ms grid / 200ms opacity transition and closes on stackcollapse. Its own scroll region fits the existing window; opening it never@@ -413,9 +435,14 @@ Two beats, so the exit reads before the reflow:- Mask the scroll box: `linear-gradient(to bottom, transparent 0, #000{top}px, #000 calc(100% − {bottom}px), transparent 100%)`.- - `top = min(32, scrollTop)`: no fade at the top until the user scrolls.- - `bottom = min(32, scrollHeight − clientHeight − scrollTop)`: no fade once+ - `top = min(band, scrollTop)`: no fade at the top until the user scrolls.+ - `bottom = min(band, scrollHeight − clientHeight − scrollTop)`: no fade oncethe end is reached.+- The card list uses a 32px band with that linear ramp.+- The reply history (§4.2) uses a taller, darker 48px band. Its ramp fades the+ outer part of the band strongly: from the edge, `transparent 0`,+ `rgba(0,0,0,.12)` at 35% of the band, `rgba(0,0,0,.55)` at 70%, and `#000` at+ 100%, mirrored at the bottom.- Recompute on scroll, and whenever the box or its content resizes(ResizeObserver on both).diff --git a/ui/e2e/pet-mini/fixture.tsx b/ui/e2e/pet-mini/fixture.tsxindex 59f84566b..682a4b376 100644--- a/ui/e2e/pet-mini/fixture.tsx+++ b/ui/e2e/pet-mini/fixture.tsx@@ -38,6 +38,7 @@ declare global {petFixtureMainReads: number;setPetMainAvailable: (available: boolean) => void;petFixtureConnection: (connected: boolean) => void;+ petFixtureMessage: (message: Record<string, unknown>) => void;}}window.petLayoutHitRegions = [];@@ -51,8 +52,11 @@ const hasMain = params.get('main') !== 'false';const layers = Number(params.get('layers') ?? 3);const personal = params.get('scenario') === 'personal';const historyActions = params.get('history') === 'actions';-// Earlier turns that overflow the history box, with the latest reply unread.+// Earlier turns that overflow the history box, with the latest reply unread+// unless `unread=0`.const historyLong = params.get('history') === 'long';+// A latest reply too tall for the history box on its own.+const replyLong = params.get('reply') === 'long';const title = personal ? '检查桌宠 mini 的交互' : 'A long unbroken title '.repeat(40);const session = {id: 'ses_main', scope_id: 'fixture', title, agent_backend: 'codex',@@ -72,8 +76,8 @@ const messages = hasMain ? [...earlier, {}, {id: 'result', session_id: session.id, scope_id: session.scope_id,author: 'agent', type: 'result',- text: personal ? '我会帮你跟进各个项目。需要授权的事已经排在前面。' : 'Ready to help with your next task.',- metadata: {}, content: historyActions ? { quick_replies: ['继续', '稍后'] } : {}, read_at: historyLong ? null : '2026-10-12T00:00:01Z',+ text: replyLong ? '这是一条很长的回复。'.repeat(60) : personal ? '我会帮你跟进各个项目。需要授权的事已经排在前面。' : 'Ready to help with your next task.',+ metadata: {}, content: historyActions ? { quick_replies: ['继续', '稍后'] } : {}, read_at: historyLong && params.get('unread') !== '0' ? null : '2026-10-12T00:00:01Z',created_at: '2026-10-12T00:00:01Z', updated_at: '2026-10-12T00:00:01Z',}] : [];const agents = Array.from({ length: Number(params.get('activities') ?? layers + 1) }, (_, i) => ({@@ -160,6 +164,17 @@ window.petFixtureConnection = (connected) => {}));}};+// Deliver a live `message.new` for the main session, as the event stream would.+window.petFixtureMessage = (message) => {+ const data = {+ session_id: session.id, scope_id: session.scope_id, metadata: {}, content: {},+ created_at: '2026-10-12T00:00:02Z', updated_at: '2026-10-12T00:00:02Z', read_at: '2026-10-12T00:00:03Z',+ ...message,+ };+ for (const stream of streams) {+ stream.dispatchEvent(new MessageEvent('message.new', { data: JSON.stringify({ type: 'message.new', data }) }));+ }+};const root = createRoot(document.getElementById('root')!);window.setPetLayoutVisible = (visible) => root.render(diff --git a/ui/e2e/pet-mini/layout.spec.ts b/ui/e2e/pet-mini/layout.spec.tsindex f897c64fc..baafea9df 100644--- a/ui/e2e/pet-mini/layout.spec.ts+++ b/ui/e2e/pet-mini/layout.spec.ts@@ -364,7 +364,8 @@ for (const theme of ['light', 'dark']) {.map((animation) => animation.finished.catch(() => {})));});const history = page.locator('.pet-mini-bubble-history');- for (const name of ['在 Avibe 中打开', '需要授权,在 Avibe 中打开', '继续']) {+ // Open in Avibe is pinned outside the scroll box; see the history test below.+ for (const name of ['需要授权,在 Avibe 中打开', '继续']) {const button = history.getByRole('button', { name, exact: true });await expect(button).toBeVisible();const bounds = await button.boundingBox(), box = await history.boundingBox();@@ -372,6 +373,7 @@ for (const theme of ['light', 'dark']) {expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(box!.y + box!.height + 1);}expect(await history.evaluate((node) => node.scrollHeight <= node.clientHeight + 1)).toBe(true);+ expect(await history.evaluate((node) => Math.abs(node.scrollHeight - node.clientHeight - node.scrollTop))).toBeLessThanOrEqual(1);expect((await page.locator('.pet-mini-collapsed').boundingBox())!.y).toBeGreaterThanOrEqual(0);expect(await avatar.boundingBox()).toEqual(anchor);await page.locator('.pet-mini-collapsed').click();@@ -548,15 +550,13 @@ for (const theme of ['light', 'dark']) {expect(box.y).toBeGreaterThanOrEqual(0);// The newest result is shown on open, so the earlier turns sit scrolled// away under the top edge fade.- // It must also sit clear of both edge fades, not merely inside the box.+ // Chat-style: it opens at the very bottom, so there is no bottom fade and+ // the newest result is in view right above the toggle row.+ expect(await history.evaluate((node) => Math.abs(node.scrollHeight - node.clientHeight - node.scrollTop))).toBeLessThanOrEqual(1);+ expect(await history.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);const last = (await history.locator('.pet-mini-detail-result').last().boundingBox())!;- const fades = await history.evaluate((node) => ({- top: Math.min(32, node.scrollTop),- bottom: Math.min(32, node.scrollHeight - node.clientHeight - node.scrollTop),- }));- expect(fades.top).toBeGreaterThan(0);- expect(last.y).toBeGreaterThanOrEqual(box.y + fades.top - 1);- expect(last.y + last.height).toBeLessThanOrEqual(box.y + box.height - fades.bottom + 1);+ expect(last.y + last.height).toBeGreaterThan(box.y);+ expect(last.y).toBeLessThan(box.y + box.height);expect(await history.evaluate((node) => /#000 [1-9]\d*px|rgb\(0, 0, 0\) [1-9]\d*px/.test(node.style.maskImage || node.style.webkitMaskImage))).toBe(true);await expect(toggle.locator('svg')).not.toHaveCSS('transform', 'none');await expect.poll(() => page.evaluate(() => window.petFixtureMarkReads)).toEqual(['ses_main']);@@ -567,3 +567,217 @@ for (const theme of ['light', 'dark']) {near(await toggle.boundingBox(), collapsed);});}++for (const theme of ['light', 'dark']) {+ test(`Open in Avibe is an icon pinned to the open history's corner (${theme})`, async ({ page, browserName }) => {+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=long');+ await page.evaluate((theme) => { document.documentElement.dataset.theme = theme; }, theme);+ const settle = () => page.evaluate(async () => {+ await Promise.all(document.getAnimations()+ .filter((animation) => animation.effect?.getTiming().iterations !== Infinity)+ .map((animation) => animation.finished.catch(() => {})));+ });+ const toggle = page.locator('.pet-mini-reply-toggle');+ const history = page.locator('.pet-mini-bubble-history');+ const icon = page.locator('.pet-mini-reply-bubble').getByRole('button', { name: '在 Avibe 中打开', exact: true });+ await expect(toggle).toBeVisible();+ await expect(icon).toHaveCount(0);++ await toggle.click();+ await expect(page.locator('.pet-mini-reply-bubble .pet-mini-detail')).toHaveClass(/is-open/);+ await settle();+ await expect(icon).toBeVisible();+ expect(await icon.getAttribute('title')).toBe('');+ expect((await icon.innerText()).trim()).toBe('');+ // Only the pinned icon remains: no text link inside the scrolling history.+ await expect(history.getByRole('button', { name: '在 Avibe 中打开', exact: true })).toHaveCount(0);+ expect(await history.evaluate((node) => getComputedStyle(node).scrollbarWidth)).toBe('none');++ const pinned = (await icon.boundingBox())!;+ expect(pinned.width).toBeGreaterThanOrEqual(28);+ expect(pinned.height).toBeGreaterThanOrEqual(28);+ // Inset equally from the bubble's visible edge on the top and the right.+ const bubble = page.locator('.pet-mini-reply-bubble');+ const insets = async () => {+ const [outer, button] = [(await bubble.boundingBox())!, (await icon.boundingBox())!];+ return { top: button.y - outer.y, right: outer.x + outer.width - (button.x + button.width) };+ };++ // It stays put while the history scrolls, and at the top of the scroll it+ // covers none of the content.+ for (const top of ['top', 'middle', 'bottom'] as const) {+ await history.evaluate((node, top) => {+ node.scrollTop = top === 'top' ? 0 : top === 'bottom' ? node.scrollHeight : (node.scrollHeight - node.clientHeight) / 2;+ }, top);+ await expect.poll(() => icon.boundingBox()).toEqual(pinned);+ const { top: above, right } = await insets();+ expect(Math.abs(above - right)).toBeLessThanOrEqual(0.5);+ expect(above).toBeGreaterThanOrEqual(6);+ }+ await history.evaluate((node) => { node.scrollTop = 0; });+ const first = (await history.locator('.pet-mini-detail-inner > *').first().boundingBox())!;+ expect(first.y).toBeGreaterThanOrEqual(pinned.y + pinned.height);++ // Reachable with Tab from the toggle, with a visible focus ring.+ await toggle.focus();+ // WebKit on macOS only tabs to buttons with Option held (Full Keyboard Access).+ await page.keyboard.press(browserName === 'webkit' ? 'Alt+Tab' : 'Tab');+ await expect(icon).toBeFocused();+ await expect(icon).toHaveCSS('outline-style', 'solid');++ await icon.click();+ await expect.poll(() => page.evaluate(() => window.petFixtureOpens)).toEqual([expect.stringContaining('ses_main')]);++ await toggle.click();+ await expect(icon).toHaveCount(0);+ });+}++test('the history fades over a taller, darker band than the card list', async ({ page }) => {+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=long&activities=8');+ const mask = (selector: string) => page.locator(selector).evaluate((node) => (node as HTMLElement).style.maskImage || (node as HTMLElement).style.webkitMaskImage);+ const scrollTo = (selector: string, where: 'top' | 'middle') => page.locator(selector).evaluate((node, where) => {+ node.scrollTop = where === 'top' ? 0 : (node.scrollHeight - node.clientHeight) / 2;+ node.dispatchEvent(new Event('scroll'));+ return node.scrollHeight - node.clientHeight;+ }, where);++ await page.locator('.pet-mini-collapsed').click();+ expect(await scrollTo('.pet-mini-scroll', 'middle')).toBeGreaterThan(64);+ await expect.poll(() => mask('.pet-mini-scroll')).toContain('rgb(0, 0, 0) 32px');+ expect(await mask('.pet-mini-scroll')).toContain('calc(100% - 32px)');+ expect(await mask('.pet-mini-scroll')).not.toContain('rgba');++ await page.locator('.pet-mini-reply-toggle').click();+ await expect(page.locator('.pet-mini-reply-bubble .pet-mini-detail')).toHaveClass(/is-open/);+ expect(await scrollTo('.pet-mini-bubble-history', 'middle')).toBeGreaterThan(96);+ // A 48px band that is already well faded across its outer two thirds.+ await expect.poll(() => mask('.pet-mini-bubble-history')).toContain('rgb(0, 0, 0) 48px');+ const middle = await mask('.pet-mini-bubble-history');+ for (const stop of ['rgba(0, 0, 0, 0.12) 16.8px', 'rgba(0, 0, 0, 0.55) 33.6px', 'calc(100% - 48px)', 'rgba(0, 0, 0, 0.55) calc(100% - 33.6px)', 'rgba(0, 0, 0, 0.12) calc(100% - 16.8px)']) {+ expect(middle).toContain(stop);+ }+ // No top fade before the history is scrolled.+ await scrollTo('.pet-mini-bubble-history', 'top');+ await expect.poll(() => mask('.pet-mini-bubble-history')).toContain('rgb(0, 0, 0) 0px');+});++test('the history opens at the bottom and stays pinned there only while the reader is', async ({ page }) => {+ // Everything is read, so each live reply replaces the shown one and nothing+ // here is about mark-read; the open-once mark-read is covered above.+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=long&unread=0');+ const history = page.locator('.pet-mini-bubble-history');+ const gap = () => history.evaluate((node) => node.scrollHeight - node.clientHeight - node.scrollTop);+ const height = () => history.evaluate((node) => node.scrollHeight);+ await page.locator('.pet-mini-reply-toggle').click();+ await expect(page.locator('.pet-mini-reply-bubble .pet-mini-detail')).toHaveClass(/is-open/);+ await expect.poll(gap).toBeLessThanOrEqual(1);++ // Content arriving while the reader is at the bottom keeps them there.+ const before = await height();+ await page.evaluate(() => window.petFixtureMessage({ id: 'live_1', author: 'agent', type: 'result', text: '新的进展。'.repeat(30) }));+ await expect.poll(height).toBeGreaterThan(before);+ await expect.poll(gap).toBeLessThanOrEqual(1);++ // A reader who has scrolled up is left where they are.+ await history.evaluate((node) => { node.scrollTop = 0; });+ await expect.poll(() => history.evaluate((node) => node.scrollTop)).toBe(0);+ const grown = await height();+ await page.evaluate(() => window.petFixtureMessage({ id: 'live_2', author: 'agent', type: 'result', text: '又一条进展。'.repeat(60) }));+ await expect.poll(height).toBeGreaterThan(grown);+ expect(await history.evaluate((node) => node.scrollTop)).toBe(0);+ expect(await page.evaluate(() => window.petFixtureMarkReads)).toEqual([]);++ // A new latest input is a new place to read from: it re-opens at the end+ // even for a reader who had scrolled up.+ await page.evaluate(() => window.petFixtureMessage({ id: 'live_input', author: 'user', type: 'user', text: '再看看文档' }));+ await expect(history).toContainText('再看看文档');+ await expect.poll(gap).toBeLessThanOrEqual(1);+});++test('a latest reply taller than the history opens at its end', async ({ page }) => {+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&reply=long');+ const history = page.locator('.pet-mini-bubble-history');+ await page.locator('.pet-mini-reply-toggle').click();+ await expect(page.locator('.pet-mini-reply-bubble .pet-mini-detail')).toHaveClass(/is-open/);+ expect(await history.evaluate((node) => node.scrollHeight - node.clientHeight)).toBeGreaterThan(100);+ await expect.poll(() => history.evaluate((node) => Math.abs(node.scrollHeight - node.clientHeight - node.scrollTop))).toBeLessThanOrEqual(1);+ const last = (await history.locator('.pet-mini-detail-result').last().boundingBox())!;+ const box = (await history.boundingBox())!;+ expect(last.y + last.height).toBeGreaterThan(box.y);+});++for (const theme of ['light', 'dark']) {+ test(`the open buttons show a pet tooltip on hover and keyboard focus (${theme})`, async ({ page, browserName }) => {+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=long');+ await page.evaluate((theme) => { document.documentElement.dataset.theme = theme; }, theme);+ const tooltip = page.getByRole('tooltip');+ // Fully on screen and on top: nothing (clip, mask, scroll box) covers it.+ const unclipped = async () => {+ const box = (await tooltip.boundingBox())!;+ const viewport = page.viewportSize()!;+ expect(box.x).toBeGreaterThanOrEqual(0);+ expect(box.y).toBeGreaterThanOrEqual(0);+ expect(box.x + box.width).toBeLessThanOrEqual(viewport.width);+ expect(box.y + box.height).toBeLessThanOrEqual(viewport.height);+ expect(await tooltip.evaluate((node) => {+ const rect = node.getBoundingClientRect();+ // The tooltip ignores the pointer; let hit testing see it for the check.+ (node as HTMLElement).style.pointerEvents = 'auto';+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);+ (node as HTMLElement).style.pointerEvents = '';+ return hit === node;+ })).toBe(true);+ return box;+ };++ // History icon: below it, right-aligned.+ await page.locator('.pet-mini-reply-toggle').click();+ const icon = page.locator('.pet-mini-history-open');+ await expect(icon).toBeVisible();+ // No native tooltip applies: the nearest title on its ancestor chain, which+ // the browser would show, is its own empty one.+ expect(await icon.evaluate((node) => node.closest('[title]')?.getAttribute('title'))).toBe('');+ await expect(tooltip).toHaveCount(0);+ await icon.hover();+ await expect(tooltip).toHaveText('在 Avibe 中打开');+ await expect(icon).toHaveAttribute('aria-describedby', (await tooltip.getAttribute('id'))!);+ const below = await unclipped();+ const button = (await icon.boundingBox())!;+ expect(below.y).toBeGreaterThanOrEqual(button.y + button.height);+ expect(Math.abs(below.x + below.width - (button.x + button.width))).toBeLessThanOrEqual(1);+ await page.mouse.move(2, 2);+ await expect(tooltip).toHaveCount(0);+ await icon.hover();+ await expect(tooltip).toBeVisible();+ // Escape takes the tooltip first and leaves the history open.+ await page.keyboard.press('Escape');+ await expect(tooltip).toHaveCount(0);+ await expect(icon).toBeVisible();++ // Keyboard focus shows it at once, without the hover delay.+ await page.mouse.move(2, 2);+ await page.locator('.pet-mini-reply-toggle').focus();+ await page.keyboard.press(browserName === 'webkit' ? 'Alt+Tab' : 'Tab');+ await expect(icon).toBeFocused();+ await expect(tooltip).toBeVisible({ timeout: 150 });+ await page.keyboard.press('Escape');+ await expect(tooltip).toHaveCount(0);++ // Card open button: to its left, so the card scroll box cannot clip it.+ await page.locator('.pet-mini-collapsed').click();+ const cardOpen = page.locator('.pet-mini-card .pet-mini-open').first();+ await expect(cardOpen).toBeVisible();+ // The card carries its title, which a descendant inherits unless it sets+ // its own: an empty one suppresses that native tooltip.+ expect(await cardOpen.evaluate((node) => node.parentElement?.closest('[title]:not([title=""])') != null)).toBe(true);+ expect(await cardOpen.getAttribute('title')).toBe('');+ await cardOpen.hover();+ await expect(tooltip).toHaveText('在 Avibe 中打开');+ const left = await unclipped();+ const card = (await cardOpen.boundingBox())!;+ expect(left.x + left.width).toBeLessThanOrEqual(card.x);+ await page.mouse.move(2, 2);+ await expect(tooltip).toHaveCount(0);+ });+}diff --git a/ui/src/pet/PetOpenButton.tsx b/ui/src/pet/PetOpenButton.tsxnew file mode 100644index 000000000..f41c8d451--- /dev/null+++ b/ui/src/pet/PetOpenButton.tsx@@ -0,0 +1,111 @@+import { useCallback, useEffect, useId, useRef, useState, type CSSProperties } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';+import clsx from 'clsx';+import { ExternalLink } from 'lucide-react';++import { petBridge } from './petBridge';++const HOVER_DELAY_MS = 350;+const GAP_PX = 6;++/**+ * Where the tooltip sits relative to its button. `below-end` hangs under the+ * button, right-aligned with it; `start` sits to its left, vertically centred.+ */+export type PetTooltipPlacement = 'below-end' | 'start';++type Tip = { host: Element; style: CSSProperties };++/**+ * The pet's Open in Avibe icon button, with a pet-styled tooltip in place of+ * the native `title` (which waits for the system delay and draws in system+ * style). The tooltip is portalled to the pet stage and placed in viewport+ * coordinates, so no scroll box, clip or edge mask around the button can cut it.+ *+ * Hover only reaches the page while the pet window receives hover; on macOS+ * that is once the window is key (spec §5.1), which opening the history or the+ * card list makes it.+ */+export function PetOpenButton({ link, placement, className }: { link: string; placement: PetTooltipPlacement; className?: string }) {+ const { t } = useTranslation();+ const label = t('pet.openInAvibe');+ const tooltipId = useId();+ const buttonRef = useRef<HTMLButtonElement>(null);+ const timer = useRef<number | null>(null);+ const [tip, setTip] = useState<Tip | null>(null);++ const cancel = useCallback(() => {+ if (timer.current !== null) window.clearTimeout(timer.current);+ timer.current = null;+ }, []);+ const hide = useCallback(() => {+ cancel();+ setTip(null);+ }, [cancel]);+ const show = useCallback(() => {+ cancel();+ const button = buttonRef.current;+ if (!button) return;+ const rect = button.getBoundingClientRect();+ const right = document.documentElement.clientWidth - (placement === 'start' ? rect.left - GAP_PX : rect.right);+ const style: CSSProperties = placement === 'start'+ ? { top: rect.top + rect.height / 2, right, transform: 'translateY(-50%)' }+ : { top: rect.bottom + GAP_PX, right };+ setTip({ host: button.closest('.pet-mini-stage') ?? document.body, style });+ }, [cancel, placement]);++ useEffect(() => cancel, [cancel]);+ useEffect(() => {+ if (!tip) return undefined;+ // The tooltip is placed once, so anything that could move the button away+ // from it dismisses it instead.+ // Escape closes the innermost layer first: the tooltip takes this one, so+ // the pet's own Escape (which collapses the history or the panel) does not+ // also run. Captured on window, ahead of that bubbling listener.+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== 'Escape' || event.isComposing) return;+ event.stopImmediatePropagation();+ hide();+ };+ window.addEventListener('keydown', onKey, true);+ window.addEventListener('scroll', hide, true);+ window.addEventListener('resize', hide);+ return () => {+ window.removeEventListener('keydown', onKey, true);+ window.removeEventListener('scroll', hide, true);+ window.removeEventListener('resize', hide);+ };+ }, [tip, hide]);++ return (+ <>+ <button+ ref={buttonRef}+ type="button"+ className={clsx('pet-mini-open', className)}+ // An empty title stops the native tooltip of an ancestor's `title`+ // (an activity card's) from showing over the pet tooltip.+ title=""+ aria-label={label}+ aria-describedby={tip ? tooltipId : undefined}+ onClick={() => void petBridge.open(link)}+ onPointerEnter={(event) => {+ if (event.pointerType === 'touch') return;+ cancel();+ timer.current = window.setTimeout(show, HOVER_DELAY_MS);+ }}+ onPointerLeave={hide}+ onPointerDown={hide}+ onFocus={(event) => { if (event.currentTarget.matches(':focus-visible')) show(); }}+ onBlur={hide}+ >+ <ExternalLink className="size-3.5" />+ </button>+ {tip && createPortal(+ <span id={tooltipId} role="tooltip" className={clsx('pet-mini-tooltip', `is-${placement}`)} style={tip.style}>{label}</span>,+ tip.host,+ )}+ </>+ );+}diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsxindex e98c47c95..bb8fde13f 100644--- a/ui/src/pet/PetPage.tsx+++ b/ui/src/pet/PetPage.tsx@@ -1,7 +1,7 @@import { useCallback, useEffect, useId, useMemo, useRef, useState, useLayoutEffect, type CSSProperties, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';-import { ChevronUp, ExternalLink, KeyRound, X } from 'lucide-react';+import { ChevronUp, KeyRound, X } from 'lucide-react';import { ApiError, useApi, type InboxSession, type RunningAgent, type VaultRequest, type WorkbenchMessage } from '@/context/ApiContext';import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';@@ -19,6 +19,7 @@ import { ShowPageVoiceDictation } from '@/lib/showPageVoiceDictation';import { VoiceTranscriptionError } from '@/lib/voiceTranscription';import { PetAvatar, type PetPose } from './PetAvatar';+import { PetOpenButton } from './PetOpenButton';import { onPetHover, petBridge, sessionLink, vaultRequestLink } from './petBridge';import { petPanel, usePetPanel } from './petPanel';import { petComposer, usePetComposer } from './petComposer';@@ -36,7 +37,17 @@ const DISMISS_EXIT_MS = 500;const STOP_CONFIRM_MS = 3000;const STOP_LINGER_MS = 2500;const STACK_HEIGHT = 304; // 292px scroll box + 6px panel padding on each side.-const FADE_PX = 32;+/**+ * A scroll edge fade band (spec §7.5): its full height, and the mask's alpha+ * ramp across it as `[alpha, fraction of the band]` stops between transparent+ * at the edge and opaque at the band's inner end.+ */+type FadeProfile = { size: number; ramp: readonly (readonly [number, number])[] };+const CARD_FADE: FadeProfile = { size: 32, ramp: [] };+// The history is denser text, so its band is taller and darker at the edge.+const HISTORY_FADE: FadeProfile = { size: 48, ramp: [[0.12, 0.35], [0.55, 0.7]] };+// How close to the end of the history still counts as reading at the bottom.+const HISTORY_STICK_PX = 8;const MAX_COLLAPSED_LAYERS = 3;const MAX_COLLAPSED_COUNT = 99;const EMPTY_INBOX: InboxSession[] = [];@@ -1020,14 +1031,14 @@ const CollapsedCards: React.FC<{ cards: PetCard[]; onOpen: () => void; t: (key:* Scroll edge fades (spec §7.5): each edge fades only once there is content* past it. Recomputed on scroll and whenever the box or its content resizes.*/-function useScrollEdgeFade(contentKey: unknown) {+function useScrollEdgeFade(contentKey: unknown, profile: FadeProfile) {const ref = useRef<HTMLDivElement>(null);const [edges, setEdges] = useState({ top: 0, bottom: 0 });const measure = useCallback(() => {const node = ref.current;if (!node) return;- setEdges({ top: Math.min(FADE_PX, Math.max(0, node.scrollTop)), bottom: Math.min(FADE_PX, Math.max(0, node.scrollHeight - node.clientHeight - node.scrollTop)) });- }, []);+ setEdges({ top: Math.min(profile.size, Math.max(0, node.scrollTop)), bottom: Math.min(profile.size, Math.max(0, node.scrollHeight - node.clientHeight - node.scrollTop)) });+ }, [profile.size]);useEffect(() => {const node = ref.current;if (!node) return undefined;@@ -1038,12 +1049,16 @@ function useScrollEdgeFade(contentKey: unknown) {for (const child of node.children) observer.observe(child);return () => observer.disconnect();}, [measure, contentKey]);- const mask = `linear-gradient(to bottom, transparent 0, #000 ${edges.top}px, #000 calc(100% - ${edges.bottom}px), transparent 100%)`;+ // Each band is as tall as the content past that edge, up to the profile's+ // size, so there is no fade at the top before scrolling or at the end.+ const top = profile.ramp.map(([alpha, at]) => `rgba(0,0,0,${alpha}) ${edges.top * at}px`);+ const bottom = [...profile.ramp].reverse().map(([alpha, at]) => `rgba(0,0,0,${alpha}) calc(100% - ${edges.bottom * at}px)`);+ const mask = `linear-gradient(to bottom, ${['transparent 0', ...top, `#000 ${edges.top}px`, `#000 calc(100% - ${edges.bottom}px)`, ...bottom, 'transparent 100%'].join(', ')})`;return { ref, measure, style: { maskImage: mask, WebkitMaskImage: mask } satisfies CSSProperties };}const ExpandedCards: React.FC<{ cards: PetCard[]; leaving: string[]; onReference: (card: PetCard) => void; onDismiss: (card: PetCard) => void; stops: Record<string, StopPhase>; onStop: (card: PetCard) => void; t: (key: string, options?: Record<string, unknown>) => string }> = ({ cards, leaving, onReference, onDismiss, stops, onStop, t }) => {- const { ref: fadeRef, measure: measureFade, style: fadeStyle } = useScrollEdgeFade(cards.length);+ const { ref: fadeRef, measure: measureFade, style: fadeStyle } = useScrollEdgeFade(cards.length, CARD_FADE);return (<div className="pet-mini-panel"><div ref={fadeRef} onScroll={measureFade} className="pet-mini-scroll" style={fadeStyle}>@@ -1095,7 +1110,7 @@ const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, op{phase === 'confirm' ? stopText : phase === 'stopping' ? <span className="pet-mini-spinner" aria-hidden /> : <StopIcon />}</button>) : null}- {card.canOpen && <button type="button" className="pet-mini-open" onClick={() => void petBridge.open(sessionLink(card.sessionId))} aria-label={t('pet.openInAvibe')} title={t('pet.openInAvibe')}><ExternalLink className="size-3.5" /></button>}+ {card.canOpen && <PetOpenButton link={sessionLink(card.sessionId)} placement="start" />}</div>)}</article>@@ -1112,7 +1127,7 @@ const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boole: last?.text?.trim() ? t('pet.repliedPrefix', { text: last.text.trim() }): t('pet.waiting');const detailId = useId();- const { ref: fadeRef, measure: measureFade, style: fadeStyle } = useScrollEdgeFade(open);+ const { ref: fadeRef, measure: measureFade, style: fadeStyle } = useScrollEdgeFade(open, HISTORY_FADE);// The toggle stays first in the DOM, so focus order is unchanged, but the// bubble lays out bottom-up: the toggle keeps its place at the bottom and// the history opens above it, so expanding never moves what was clicked.@@ -1124,6 +1139,9 @@ const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boole</button><div id={detailId} className={clsx('pet-mini-detail', open && 'is-open')}><div className="pet-mini-detail-clip" inert={!open || undefined}>+ {/* Pinned outside the scroll box, so it stays put while the history+ scrolls and is not faded by its edge mask. */}+ {open && <PetOpenButton link={sessionLink(props.binding)} placement="below-end" className="pet-mini-history-open" />}<div ref={fadeRef} onScroll={measureFade} className="pet-mini-bubble-history" style={fadeStyle}><MainDetail {...props} visible={open} /></div></div></div>@@ -1134,19 +1152,32 @@ const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: booleconst MainDetail: React.FC<MainDetailProps> = (props) => {const { t } = useTranslation();const lastResultRef = useRef<HTMLDivElement>(null);+ const innerRef = useRef<HTMLDivElement>(null);const resultKey = `${props.binding}\u0000${props.exchange.results.at(-1)?.id ?? ''}`;const [seenResult, setSeenResult] = useState<{ epoch: PetSurfaceEpoch; key: string } | null>(null);+ // Chat-style: open at the very bottom, where the end of the newest reply,+ // its actions and notices sit right above the toggle row. While open, new+ // content keeps a reader who is at the bottom pinned there, and leaves one+ // who has scrolled up where they are. A different latest input, which may be+ // drawn after a promoted result (`answersEarlierInput`), re-opens at the end.useLayoutEffect(() => {- if (!props.visible) return;- const result = lastResultRef.current;- const history = result?.closest<HTMLElement>('.pet-mini-bubble-history');- // Open at the end, where the newest result sits right above its actions and- // the toggle row. If the result and its actions do not fit, start at the- // result instead, just past the top edge fade, so it is read from its first- // line rather than from under the fade. A later input drawn after a promoted- // result (`answersEarlierInput`) moves the end, so a new input re-scrolls.- if (result && history) history.scrollTop = Math.max(0, Math.min(history.scrollHeight - history.clientHeight, result.offsetTop - FADE_PX));- }, [props.visible, resultKey, props.exchange.user?.id]);+ if (!props.visible) return undefined;+ const inner = innerRef.current;+ const history = inner?.closest<HTMLElement>('.pet-mini-bubble-history');+ if (!inner || !history) return undefined;+ const toBottom = () => { history.scrollTop = history.scrollHeight - history.clientHeight; };+ let pinned = true;+ const onScroll = () => { pinned = history.scrollHeight - history.clientHeight - history.scrollTop <= HISTORY_STICK_PX; };+ toBottom();+ history.addEventListener('scroll', onScroll);+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => { if (pinned) toBottom(); });+ observer?.observe(inner);+ observer?.observe(history);+ return () => {+ history.removeEventListener('scroll', onScroll);+ observer?.disconnect();+ };+ }, [props.visible, props.exchange.user?.id]);useEffect(() => {const node = lastResultRef.current;if (!props.visible || !node) return;@@ -1165,7 +1196,7 @@ const MainDetail: React.FC<MainDetailProps> = (props) => {.filter((message) => message.type === 'user' || message.type === 'result').slice(-6);const currentUser = props.exchange.user && <div className="pet-mini-detail-user"><Markdown content={props.exchange.user.text} references={(props.exchange.user.content as { references?: MentionReference[] })?.references} softBreaks /></div>;return (- <div className="pet-mini-detail-inner">+ <div ref={innerRef} className="pet-mini-detail-inner">{history.map((message) => <div key={message.id} className={message.author === 'user' ? 'pet-mini-detail-user' : 'pet-mini-detail-result'}><Markdown content={message.text} references={(message.content as { references?: MentionReference[] })?.references} softBreaks /></div>)}{!props.exchange.answersEarlierInput && currentUser}{props.exchange.results.map((message, index) => <div ref={index === props.exchange.results.length - 1 ? lastResultRef : undefined} key={message.id} className="pet-mini-detail-result"><Markdown content={message.text} references={(message.content as { references?: MentionReference[] })?.references} softBreaks /></div>)}@@ -1179,11 +1210,11 @@ const MainDetail: React.FC<MainDetailProps> = (props) => {{props.running && <p className="pet-mini-detail-muted">{t('pet.thinking')}</p>}{props.voiceNeedsCloud && <p className="pet-mini-detail-muted">{t('pet.voice.cloudRequired')}</p>}{props.queued && <p className="pet-mini-detail-muted">{t('pet.queued')}</p>}- {!props.exchange.unreadComplete && <Button variant="link" size="sm" className="px-0" onClick={() => void petBridge.open(sessionLink(props.binding))}>{t('pet.moreInAvibe')}</Button>}+ {/* The pinned Open in Avibe button is where the rest of the tail lives. */}+ {!props.exchange.unreadComplete && <p className="pet-mini-detail-muted">{t('pet.moreInAvibe')}</p>}{props.vaultRequestIds.map((id) => <Button key={id} variant="outline" size="sm" className="justify-start gap-2" onClick={() => void petBridge.open(vaultRequestLink(id))}><KeyRound className="size-3.5" />{t('pet.vaultRequest')}</Button>)}{props.canChat && !props.uncertain && props.quickReplies && <QuickReplies key={props.quickReplies.message.id} options={props.quickReplies.options} chosen={null} onChoose={(choice) => props.onChoose(props.quickReplies!.message, choice)} />}{props.uncertain && <div className="pet-mini-detail-notice" role="status"><p>{t('newSession.sendUncertain')}</p><Button variant="link" size="sm" className="px-0" onClick={props.onInspect}>{t('pet.openInAvibe')}</Button></div>}- <Button variant="link" size="sm" className="px-0" onClick={() => void petBridge.open(sessionLink(props.binding))}><ExternalLink className="mr-1 size-3.5" />{t('pet.openInAvibe')}</Button></div>);};diff --git a/ui/src/pet/pet-mini.css b/ui/src/pet/pet-mini.cssindex a0d248efa..ee7d6d27a 100644--- a/ui/src/pet/pet-mini.css+++ b/ui/src/pet/pet-mini.css@@ -847,8 +847,56 @@ to {max-height:min(292px,max(0px,calc(100dvh - 225px - var(--pet-collapsed-height,0px))));overflow:auto;overscroll-behavior:contain;- scrollbar-width:thin}-/* The history's top edge is now the bubble's rounded top, so it gets more room- than the bottom edge, which meets the divider. */-.pet-mini-bubble-history .pet-mini-detail-inner { padding:12px 14px 8px }+ /* Hidden like the card list (§3.2); the edge fades show there is more. */+ scrollbar-width:none}+.pet-mini-bubble-history::-webkit-scrollbar {+ display:none}+/* The top padding reserves the corner for the pinned Open in Avibe button+ (8px inset + 28px + 4px), so at the top of the scroll it covers no text. */+.pet-mini-bubble-history .pet-mini-detail-inner { padding:40px 14px 8px }+/* Open in Avibe for the main history: the card open button's look on a solid+ surface, so it stays legible over the top fade and over scrolled text. */+.pet-mini-history-open {+ position:absolute;+ z-index:3;+ /* 8px from the bubble's outer edge on both sides (7px here, inside its 1px+ border). That centres the 28px circle on the 22px corner arc, so the gap+ to the border is the same 8px along the top, the side and the curve. */+ top:7px;+ right:7px;+ width:28px;+ height:28px;+ background:color-mix(in srgb,var(--pet-ink) 8%,var(--pet-card))}+.pet-mini-history-open:hover {+ background:color-mix(in srgb,var(--pet-ink) 14%,var(--pet-card))}+/* Pet-styled tooltip for the Open in Avibe buttons (PetOpenButton), placed in+ viewport coordinates by the component. No shadow: the transparent window+ would clip it (§3.2), so the ink border defines the edge. */+.pet-mini-tooltip {+ position:fixed;+ z-index:50;+ max-width:calc(100vw - 8px);+ overflow:hidden;+ padding:4px 8px;+ border:1px solid color-mix(in srgb,var(--pet-ink) 14%,transparent);+ border-radius:8px;+ color:var(--pet-ink);+ background:var(--pet-card);+ font-size:12px;+ line-height:16px;+ white-space:nowrap;+ text-overflow:ellipsis;+ pointer-events:none;+ animation:pet-mini-tooltip-in 120ms ease both}+@keyframes pet-mini-tooltip-in {+ from {+ opacity:0}+}+@media (prefers-reduced-motion: reduce) {+ .pet-mini-tooltip {+ animation:none}+}+.pet-mini-history-open:focus-visible {+ outline:2px solid var(--mint);+ outline-offset:2px}.pet-mini-swap:has(.pet-mini-collapsed) { padding-bottom:14px }