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): let Vibey's reply linger 10s on screen after its turn ends (#2855)
Max6a12459f1c4c
diff --git a/docs/plans/2026-10-12-desktop-mini-main-agent.md b/docs/plans/2026-10-12-desktop-mini-main-agent.mdindex 766604b79..df7505764 100644--- a/docs/plans/2026-10-12-desktop-mini-main-agent.md+++ b/docs/plans/2026-10-12-desktop-mini-main-agent.md@@ -169,17 +169,65 @@ slot above the avatar: thinking, delegated-to (only when provenance is known),then the latest reply. The bubble names Vibey in its existing localized spelling.It remains available with either the collapsed or expanded stack.-**When it shows.** Only while Vibey's conversation is active: the turn is-running or thinking, or a send is pending; Vibey needs the user (a pending-Vault handoff, a failure notice, an uncertain-send notice, or a queued-notice); or the history is open. Composing and dictating take the slot as-before (§5.2). The moment none of these holds, the turn's result arriving-included, the bubble hides with the speech slot's transition (instant under-reduced motion), taking no space and no clicks: there is no linger. Unread-replies only light Vibey's badge, and quick replies stay in the history; to-read a reply, click Vibey (§5.1). On first load an old, finished exchange-starts hidden. A new running turn, a new needs-you state or a Vibey click-that opens the history shows it at once.+**When it shows.** While Vibey's conversation is active: the turn is running+or thinking, or a send is pending; Vibey needs the user (a pending Vault+handoff, a failure notice, an uncertain-send notice, or a queued notice); or+the history is open. Composing and dictating take the slot as before (§5.2).+Then, when Vibey's turn ends, the bubble shows the reply summary for+**10 seconds of on-screen time** before it hides with the speech slot's+transition (instant under reduced motion), taking no space and no clicks.++- **The reply of a turn this epoch watched end.** One thing lingers: that+ reply, pinned by its id, and everything about the linger is derived from it+ while rendering. The turn end is the main session's server turn state going+ from running to done while the current epoch (binding and authorization)+ watches; the local send grace (which shows "thinking" before the server+ registers a turn) is not part of it. The reply is the newest non-empty agent+ result after the input of that turn that is not a background run's detached+ completion; nothing before that input counts, so a promoted answer to an+ earlier input (#2815) keeps the badge but does not linger. A stopped+ turn (which ends with an empty result) or a turn with no reply does not+ linger; a reply that lands after its turn end lingers once it arrives. The+ summary shows the pinned reply for as long as it lingers, even if a later+ result (a background completion) arrives. The render that ends the turn is+ the render that starts the linger, so the bubble never closes in between;+ the only state is which replies have expired or been seen, per epoch. A turn+ already over when the epoch first looks is history, so on first load an old,+ finished exchange starts hidden. A reply that appears without a watched turn+ end (a background or detached result, a turn that starts and ends while+ authorization is still resolving, or a turn so quick the pet never saw the+ server report it running) does not linger; Vibey's badge still marks it, and+ a Vibey click opens it. A turn that ends in failure keeps the bubble shown+ through its failure notice (needs-you).+- **On-screen time.** The 10s count only while the reply itself is on+ screen: the document is visible, the slot is drawing this bubble (not the+ input, the dictation marquee, or the loading and unavailable notices), its+ summary row is the reply (not "thinking" while the turn still reads as+ running, nor a failure notice), and the pointer is not over the bubble.+ The pointer reading counts only while the bubble is drawn; when the input or+ the marquee replaces it, or it hides, the reading is dropped, since no leave+ event may come.+ Typing or dictating pauses it, and the rest plays when the bubble is back.+ Leaving the bubble with the pointer leaves at least 3s. One timer, rescheduled+ whenever these change.+- **Keyboard focus** is read when the time runs out, not tracked: focus on a+ focus-visible control inside the bubble keeps the reply and is looked at+ again a second later. A pointer click never pins it. If the bubble goes+ while focus is inside, whether it folds away or is replaced (by the input,+ the dictation marquee, or a loading notice), focus moves to Vibey's button.+- **Looked at means done.** A reply present while the history is open (its+ expansion confirmed by the shell) counts as seen and does not linger after,+ whether the history was opened from the lingering reply (a Vibey click or its+ toggle row) or the reply arrived while it was already open; closing the+ history hides the bubble. A reply that arrives only after the history has+ closed was not seen there, so it lingers. A history the user asked for that+ the shell has not confirmed yet holds the bubble and pauses the linger; if+ the shell refuses, the request is dropped and the linger resumes. A new running turn holds the bubble again, and its+ own result lingers anew.++Unread replies only light Vibey's badge and never hold the bubble; quick+replies stay in the history. A new running turn, a new needs-you state or a+Vibey click that opens the history shows the bubble at once.Click the bubble to expand recent turns from the loaded tail. Preserve allprevious main detail behavior:diff --git a/ui/e2e/pet-mini/layout.spec.ts b/ui/e2e/pet-mini/layout.spec.tsindex e1edd723e..41116ce37 100644--- a/ui/e2e/pet-mini/layout.spec.ts+++ b/ui/e2e/pet-mini/layout.spec.ts@@ -976,15 +976,126 @@ test('an old, finished exchange starts with the bubble hidden, and takes no spacawait expect.poll(() => bubbleIsRegion(page)).toBe(false);});-test('a running turn shows the bubble, and it hides as soon as the result arrives', async ({ page }) => {+// The reply lingers for 10s of on-screen time after the turn ends (spec §4.2).+// It waits until the running turn and its conversation are on screen, so the+// turn's end is one this page watched happen.+const finishTurn = async (page: import('@playwright/test').Page, text = '做完了。') => {+ await expect(page.locator('.pet-mini-reply-bubble')).toContainText('检查桌宠 mini 的交互');+ await page.evaluate((text) =>+ window.petFixtureFinishTurn({ id: 'live_reply', author: 'agent', type: 'result', text, read_at: null }), text);+};+// Tab (Option+Tab in WebKit, whose Tab skips buttons) until the toggle row has+// keyboard focus; with no cards it is the first stop.+const tabToToggle = async (page: import('@playwright/test').Page, browserName: string) => {+ const toggle = page.locator('.pet-mini-reply-toggle');+ for (let step = 0; step < 6 && !(await toggle.evaluate((node) => node === document.activeElement)); step += 1) {+ await page.keyboard.press(browserName === 'webkit' ? 'Alt+Tab' : 'Tab');+ }+ await expect(toggle).toBeFocused();+ expect(await toggle.evaluate((node) => node.matches(':focus-visible'))).toBe(true);+ return toggle;+};++for (const theme of ['light', 'dark']) {+ test(`a running turn shows thinking, then its reply for 10s on screen (${theme})`, async ({ page }) => {+ await page.clock.install();+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&running=1&asr=1');+ await page.evaluate((theme) => { document.documentElement.dataset.theme = theme; }, theme);+ await page.clock.runFor(500);+ await expect(bubbleShown(page)).toBeVisible();+ await expect(page.locator('.pet-mini-reply-toggle')).toContainText('思考中');+ await finishTurn(page);+ await page.clock.runFor(100);+ await expect(bubbleShown(page)).toBeVisible();+ await expect(page.locator('.pet-mini-reply-toggle')).toContainText('已回复:做完了。');+ await page.clock.runFor(9_500);+ await expect(bubbleShown(page)).toBeVisible();+ await page.clock.runFor(1_000);+ await expect(bubbleShown(page)).toHaveCount(0);+ await settleMotion(page);+ await page.clock.runFor(100);+ await expect.poll(() => bubbleIsRegion(page)).toBe(false);+ });+}++test('a background completion arriving during the linger does not take over its summary', async ({ page }) => {+ await page.clock.install();await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&running=1');+ await page.clock.runFor(500);+ await finishTurn(page);+ await page.clock.runFor(1_000);+ await expect(page.locator('.pet-mini-reply-toggle')).toContainText('已回复:做完了。');+ await page.evaluate(() => window.petFixtureMessage({+ id: 'background', author: 'agent', type: 'result', text: '后台任务也完成了。', read_at: null, metadata: { detached: true },+ }));+ await page.clock.runFor(500);+ await expect(page.locator('.pet-mini-reply-toggle')).toContainText('已回复:做完了。');+ await expect(page.locator('.pet-mini-reply-toggle')).not.toContainText('后台任务');+});++test('the pointer over the lingering reply holds it, and leaving leaves at least 3s', async ({ page }) => {+ await page.clock.install();+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&running=1');+ await page.clock.runFor(500);+ await finishTurn(page);+ await page.clock.runFor(9_000);+ await page.locator('.pet-mini-reply-toggle').hover();+ await page.clock.runFor(60_000);await expect(bubbleShown(page)).toBeVisible();- await expect.poll(() => bubbleIsRegion(page)).toBe(true);- // The turn ends with its result, announced the way the event stream does.- await page.evaluate(() => window.petFixtureFinishTurn({ id: 'live_reply', author: 'agent', type: 'result', text: '做完了。', read_at: null }));- await expect(page.locator('.pet-mini-reply-bubble')).toContainText('做完了。');+ await page.mouse.move(2, 2);+ await page.clock.runFor(2_800);+ await expect(bubbleShown(page)).toBeVisible();+ await page.clock.runFor(400);await expect(bubbleShown(page)).toHaveCount(0);- await expect.poll(() => bubbleIsRegion(page)).toBe(false);+});++test('keyboard focus in the lingering reply keeps it until focus moves on', async ({ page, browserName }) => {+ await page.clock.install();+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&running=1&activities=0');+ await page.clock.runFor(500);+ await finishTurn(page);+ await page.clock.runFor(100);+ await tabToToggle(page, browserName);+ await page.clock.runFor(30_000);+ await expect(bubbleShown(page)).toBeVisible();+ // Focus moves on: the next look finds nothing holding it, and it goes.+ await page.locator('.pet-mini-avatar-button').focus();+ await page.clock.runFor(1_500);+ await expect(bubbleShown(page)).toHaveCount(0);+});++test('a Vibey click on the lingering reply opens its history, which does not linger after', async ({ page }) => {+ await page.clock.install();+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&running=1');+ await page.clock.runFor(500);+ await finishTurn(page);+ await page.clock.runFor(2_000);+ const avatar = page.locator('.pet-mini-avatar-button');+ await avatar.click();+ await page.clock.runFor(300);+ await expect(page.locator('.pet-mini-reply-bubble .pet-mini-detail')).toHaveClass(/is-open/);+ await expect.poll(() => page.locator('.pet-mini-bubble-history').evaluate((node) => Math.abs(node.scrollHeight - node.clientHeight - node.scrollTop))).toBeLessThanOrEqual(1);+ await avatar.click();+ await page.clock.runFor(300);+ await expect(bubbleShown(page)).toHaveCount(0);+});++test('the lingering reply\'s toggle row opens its history; closing it hides the bubble and hands focus to Vibey', async ({ page, browserName }) => {+ await page.clock.install();+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&running=1&activities=0');+ await page.clock.runFor(500);+ await finishTurn(page);+ await page.clock.runFor(1_000);+ // From the keyboard, so focus is inside the bubble as it goes (WebKit does+ // not focus a button on a mouse click).+ await tabToToggle(page, browserName);+ await page.keyboard.press('Enter');+ await page.clock.runFor(300);+ await expect(page.locator('.pet-mini-reply-bubble .pet-mini-detail')).toHaveClass(/is-open/);+ await page.keyboard.press('Enter');+ await page.clock.runFor(300);+ await expect(bubbleShown(page)).toHaveCount(0);+ await expect(page.locator('.pet-mini-avatar-button')).toBeFocused();});for (const [name, query] of [['a running turn', 'running=1'], ['a pending Vault handoff', 'history=actions']] as const) {diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsxindex 5888924e5..eb48090a8 100644--- a/ui/src/pet/PetPage.test.tsx+++ b/ui/src/pet/PetPage.test.tsx@@ -18,6 +18,7 @@ import type {import { ApiError } from '@/context/ApiContext';import { PET_BOUND_EVENT, PET_HOVER_EVENT, PET_SUMMON_EVENT } from './petBridge';+import { SEND_GRACE_MS } from './usePetSession';vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),@@ -2453,7 +2454,8 @@ describe('PetPage IME composition', () => {});describe('Vibey bubble visibility (spec §4.2)', () => {- const bubbleOpen = () => document.querySelector('.pet-mini-reply-bubble')?.closest('.pet-mini-slot')?.classList.contains('is-open') ?? false;+ // Vibey's own bubble (its toggle row), not the loading notice that shares the slot.+ const bubbleOpen = () => document.querySelector('.pet-mini-reply-toggle')?.closest('.pet-mini-slot')?.classList.contains('is-open') ?? false;it('starts hidden for an old, finished exchange, quick replies and unread included', async () => {tails.S = [@@ -2466,29 +2468,381 @@ describe('Vibey bubble visibility (spec §4.2)', () => {expect(bubbleOpen()).toBe(false);});- it('shows while Vibey works, and hides as soon as the result arrives', async () => {+ // A turn that is running, then ends with `text` as its result; returns the+ // slot's class at every commit after the result lands.+ const runToResult = async (text = 'All done') => {+ // Fake time that still moves on its own, so waitFor keeps polling while the+ // linger's own timer is under the test's control from the start.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'], shouldAdvanceTime: true });tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' })];let running = true;api.getTurnState.mockImplementation(async () => (running ? { ...idleTurn, in_flight: true, foreground: 'running' as const } : idleTurn));+ mainSession('S');+ render(<PetPage />);+ await waitFor(() => expect(bubbleOpen()).toBe(true));+ const slot = document.querySelector('.pet-mini-reply-toggle')!.closest('.pet-mini-slot')!;+ const classes: string[] = [];+ const observer = new MutationObserver(() => classes.push(slot.className));+ observer.observe(slot, { attributes: true, attributeFilter: ['class'] });+ const result = message('r', 'S', { text, read_at: null });+ tails.S = [...tails.S, result];+ running = false;+ await emit((h) => {+ h.onMessageNew?.(result);+ h.onTurnEnd?.({ session_id: 'S' });+ });+ await waitFor(() => expect(api.getTurnState).toHaveBeenCalled());+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));+ observer.disconnect();+ return classes;+ };+ const bubbleWrap = () => document.querySelector('.pet-mini-reply-bubble')!.parentElement!;+ afterEach(() => {+ vi.useRealTimers();+ api.getTurnState.mockImplementation(async () => idleTurn);+ });++ it('keeps the bubble open from running to its result, then shows the reply for 10s', async () => {+ const classes = await runToResult();+ // No closed frame between the running bubble and the reply.+ expect(classes.every((value) => value.includes('is-open'))).toBe(true);+ expect(bubbleOpen()).toBe(true);+ expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('All done');+ act(() => { vi.advanceTimersByTime(9_900); });+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(200); });+ expect(bubbleOpen()).toBe(false);+ });++ it('spends nothing while the turn still reads as running, so a late turn end still gets the full 10s', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'], shouldAdvanceTime: true });+ tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' })];+ let running = true;+ api.getTurnState.mockImplementation(async () => (running ? { ...idleTurn, in_flight: true, foreground: 'running' as const } : idleTurn));+ mainSession('S');+ render(<PetPage />);+ await waitFor(() => expect(bubbleOpen()).toBe(true));+ // The result lands, but its turn end is late: the summary still says thinking.+ const result = message('r', 'S', { text: 'Late end', read_at: null });+ tails.S = [...tails.S, result];+ await emit((h) => h.onMessageNew?.(result));+ act(() => { vi.advanceTimersByTime(30_000); });+ expect(bubbleOpen()).toBe(true);+ running = false;+ await emit((h) => h.onTurnEnd?.({ session_id: 'S' }));+ await waitFor(() => expect(document.querySelector('.pet-mini-reply-toggle .pet-mini-running-dot')).toBeNull());+ act(() => { vi.advanceTimersByTime(9_800); });+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(400); });+ expect(bubbleOpen()).toBe(false);+ });++ it('does not linger an old reply again when it is edited', async () => {+ const old = message('r', 'S', { text: 'Old reply', metadata: { promoted_from: 'output' } });+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), old];+ mainSession('S');+ render(<PetPage />);+ await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));+ await emit((h) => h.onMessageUpdated?.({ ...old, text: 'Old reply, edited' }));+ await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('edited'));+ expect(bubbleOpen()).toBe(false);+ });++ it('hands keyboard focus to Vibey when a loading notice replaces the bubble', async () => {+ await runToResult();+ const toggle = document.querySelector<HTMLButtonElement>('.pet-mini-reply-toggle')!;+ act(() => { toggle.focus(); });+ expect(document.activeElement).toBe(toggle);+ // A new authorization resolves slowly: the loading notice takes the slot.+ const pending = deferred<WorkbenchSessionReadResult>();+ api.getMainSession.mockReturnValueOnce(pending.promise);+ await emit((h) => h.onAuthorizationChanged?.({}));+ expect(document.querySelector('.pet-mini-reply-toggle')).toBeNull();+ expect(document.activeElement).toBe(screen.getByLabelText('pet.recentTurns'));+ await act(async () => pending.resolve({ status: 200, session: session('S'), capabilities: { can_chat: true } }));+ });++ it('hands keyboard focus to Vibey when dictation replaces the bubble', async () => {+ class Dictation { done = new Promise<string>(() => {}); start = async () => {}; finish = () => {}; abort = () => {}; }+ vi.doMock('@/lib/showPageVoiceDictation', () => ({ ShowPageVoiceDictation: Dictation }));+ const locks = Object.getOwnPropertyDescriptor(navigator, 'locks');+ const media = Object.getOwnPropertyDescriptor(navigator, 'mediaDevices');try {- mainSession('S');- render(<PetPage />);- await waitFor(() => expect(bubbleOpen()).toBe(true));- // The turn ends with its result: the server tail now holds it.- const result = message('r', 'S', { text: 'All done', read_at: null });- tails.S = [...tails.S, result];- running = false;+ Object.defineProperty(navigator, 'locks', { configurable: true, value: {} });+ Object.defineProperty(navigator, 'mediaDevices', { configurable: true, value: { getUserMedia: vi.fn() } });+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ available: true }) })));+ vi.resetModules();+ ({ PetPage } = await import('./PetPage'));+ await runToResult();+ await waitFor(() => expect(screen.getByLabelText('pet.voice.open')).toBeTruthy());+ const toggle = document.querySelector<HTMLButtonElement>('.pet-mini-reply-toggle')!;+ act(() => { toggle.focus(); });+ // Holding the summon hotkey starts dictation: the marquee takes the slot.+ summon('listen');+ await waitFor(() => expect(document.querySelector('.pet-mini-reply-toggle')).toBeNull());+ expect(document.activeElement).toBe(screen.getByLabelText('pet.recentTurns'));+ } finally {+ vi.doUnmock('@/lib/showPageVoiceDictation');+ vi.unstubAllGlobals();+ if (locks) Object.defineProperty(navigator, 'locks', locks);+ else Reflect.deleteProperty(navigator, 'locks');+ if (media) Object.defineProperty(navigator, 'mediaDevices', media);+ else Reflect.deleteProperty(navigator, 'mediaDevices');+ vi.resetModules();+ ({ PetPage } = await import('./PetPage'));+ }+ });++ // Running, then the turn ends; the test supplies what the end delivers.+ const runThenEnd = async (deliver: (finish: () => void) => Promise<void>) => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'], shouldAdvanceTime: true });+ tails.S = [message('r0', 'S', { text: 'Earlier reply' }), message('u', 'S', { author: 'user', type: 'user', text: 'hello' })];+ let running = true;+ api.getTurnState.mockImplementation(async () => (running ? { ...idleTurn, in_flight: true, foreground: 'running' as const } : idleTurn));+ mainSession('S');+ render(<PetPage />);+ await waitFor(() => expect(bubbleOpen()).toBe(true));+ await deliver(() => { running = false; });+ };++ it('does not linger after a stopped turn, whose result is empty', async () => {+ await runThenEnd(async (finish) => {+ const silent = message('stop', 'S', { text: '', read_at: null });+ tails.S = [...tails.S, silent];+ finish();await emit((h) => {- h.onMessageNew?.(result);+ h.onMessageNew?.(silent);h.onTurnEnd?.({ session_id: 'S' });});- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('All done'));- await waitFor(() => expect(bubbleOpen()).toBe(false));+ });+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ });++ it('does not take a background completion for the ended turn\'s reply', async () => {+ await runThenEnd(async (finish) => {+ const detached = message('bg', 'S', { text: 'Background run done', read_at: null, metadata: { detached: true } });+ const silent = message('stop', 'S', { text: '', read_at: null });+ tails.S = [...tails.S, detached, silent];+ finish();+ await emit((h) => {+ h.onMessageNew?.(detached);+ h.onMessageNew?.(silent);+ h.onTurnEnd?.({ session_id: 'S' });+ });+ });+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ });++ it('counts a turn that ends while the history is open as already seen', async () => {+ await runThenEnd(async (finish) => {+ // The history is open (expansion confirmed) when the turn ends with its reply.+ await userEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).not.toBeNull());+ const reply = message('r1', 'S', { text: 'Answered while open', read_at: null });+ tails.S = [...tails.S, reply];+ finish();+ await emit((h) => {+ h.onMessageNew?.(reply);+ h.onTurnEnd?.({ session_id: 'S' });+ });+ await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Answered while open'));+ });+ await userEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ });++ it('lingers a reply that lands after its turn end, once the history it was not in has closed', async () => {+ await runThenEnd(async (finish) => {+ // History open, then the turn ends before its result.+ await userEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).not.toBeNull());+ finish();+ await emit((h) => h.onTurnEnd?.({ session_id: 'S' }));+ await waitFor(() => expect(api.getTurnState).toHaveBeenCalled());+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));+ });+ // Closed before the reply came: it was never seen there.+ await userEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ const late = message('late', 'S', { text: 'Late reply', read_at: null });+ tails.S = [...tails.S, late];+ await emit((h) => h.onMessageNew?.(late));+ await waitFor(() => expect(bubbleOpen()).toBe(true));+ act(() => { vi.advanceTimersByTime(9_800); });+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(400); });+ expect(bubbleOpen()).toBe(false);+ });++ it('lingers once the reply arrives when the turn end came first', async () => {+ await runThenEnd(async (finish) => {+ finish();+ await emit((h) => h.onTurnEnd?.({ session_id: 'S' }));+ });+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ const late = message('late', 'S', { text: 'Late reply', read_at: null });+ tails.S = [...tails.S, late];+ await emit((h) => h.onMessageNew?.(late));+ await waitFor(() => expect(bubbleOpen()).toBe(true));+ act(() => { vi.advanceTimersByTime(9_800); });+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(400); });+ expect(bubbleOpen()).toBe(false);+ });++ it('keeps the lingering reply while a history request waits on the shell, and after it is refused', async () => {+ const expand = deferred<unknown>();+ const invoke = vi.fn((command: string, args?: { expanded?: boolean }) => {+ if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });+ if (command === 'pet_set_expanded' && args?.expanded) return expand.promise;+ return Promise.resolve({ panel_side: 'left', panel_edge: 'bottom' });+ });+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });+ try {+ await runToResult();+ const toggle = document.querySelector<HTMLButtonElement>('.pet-mini-reply-toggle')!;+ act(() => { toggle.focus(); });+ fireEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));+ // Not yet confirmed: the reply still holds the bubble, and focus stays put.+ expect(bubbleOpen()).toBe(true);+ expect(document.activeElement).toBe(toggle);+ await act(async () => expand.reject(new Error('no monitor')));+ // Refused: the history never opened, so the reply plays out its time.+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(10_200); });+ expect(bubbleOpen()).toBe(false);} finally {- api.getTurnState.mockImplementation(async () => idleTurn);+ Reflect.deleteProperty(window, '__AVIBE_DESKTOP_SHELL__');+ Reflect.deleteProperty(window, '__TAURI_INTERNALS__');}});+ it('holds a lingering reply while the shell is slower to confirm the history than its time left', async () => {+ const expand = deferred<unknown>();+ const invoke = vi.fn((command: string, args?: { expanded?: boolean }) => {+ if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });+ if (command === 'pet_set_expanded' && args?.expanded) return expand.promise;+ return Promise.resolve({ panel_side: 'left', panel_edge: 'bottom' });+ });+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });+ try {+ await runToResult();+ act(() => { vi.advanceTimersByTime(9_000); });+ fireEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));+ // Far longer than the second left: the request holds the bubble.+ act(() => { vi.advanceTimersByTime(5_000); });+ expect(bubbleOpen()).toBe(true);+ await act(async () => expand.resolve({ panel_side: 'left', panel_edge: 'bottom' }));+ await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).not.toBeNull());+ expect(bubbleOpen()).toBe(true);+ } finally {+ Reflect.deleteProperty(window, '__AVIBE_DESKTOP_SHELL__');+ Reflect.deleteProperty(window, '__TAURI_INTERNALS__');+ }+ });++ it('does not take an earlier input\'s promoted answer for a later turn that ends without a reply', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'], shouldAdvanceTime: true });+ tails.S = [+ message('u1', 'S', { author: 'user', type: 'user', text: 'first' }),+ message('p1', 'S', { text: 'Promoted answer', metadata: { promoted_from: 'output' } }),+ message('u2', 'S', { author: 'user', type: 'user', text: 'second' }),+ ];+ let running = true;+ api.getTurnState.mockImplementation(async () => (running ? { ...idleTurn, in_flight: true, foreground: 'running' as const } : idleTurn));+ mainSession('S');+ render(<PetPage />);+ await waitFor(() => expect(bubbleOpen()).toBe(true));+ // The later turn is stopped: it reaches idle before its empty row lands.+ running = false;+ await emit((h) => h.onTurnEnd?.({ session_id: 'S' }));+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ });++ it('does not linger when a send grace runs out with no turn registered', async () => {+ tails.S = [message('u0', 'S', { author: 'user', type: 'user', text: 'earlier' }), message('r0', 'S', { text: 'Earlier reply' })];+ // The send is accepted and echoed back, so nothing local still holds the bubble.+ api.sendSessionMessage.mockImplementationOnce(async () => message('sent', 'S', { author: 'user', type: 'user', text: 'quick' }));+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'], shouldAdvanceTime: true });+ mainSession('S');+ render(<PetPage />);+ summon('listen');+ const input = await screen.findByLabelText('pet.inputPlaceholder');+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('S'));+ await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));+ await userEvent.type(input, 'quick{Enter}');+ await waitFor(() => expect(pose()).toBe('running'));+ // The server never registers the turn: the local grace simply runs out.+ act(() => { vi.advanceTimersByTime(SEND_GRACE_MS + 100); });+ await waitFor(() => expect(pose()).not.toBe('running'));+ act(() => { vi.advanceTimersByTime(500); });+ expect(bubbleOpen()).toBe(false);+ });++ it('drops a lingering reply when the epoch changes', async () => {+ await runToResult();+ expect(bubbleOpen()).toBe(true);+ // A new authorization is a new epoch: its first read is the baseline.+ await resolveMainAs('S');+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ });++ it('pauses while typing takes the slot, then plays the rest', async () => {+ await runToResult();+ act(() => { vi.advanceTimersByTime(4_000); });+ summon('listen');+ await screen.findByLabelText('pet.inputPlaceholder');+ act(() => { vi.advanceTimersByTime(60_000); });+ act(() => { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); });+ expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(5_900); });+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(200); });+ expect(bubbleOpen()).toBe(false);+ });++ it('holds while the pointer is over it, and leaves at least 3s after', async () => {+ await runToResult();+ act(() => { vi.advanceTimersByTime(9_000); });+ fireEvent.pointerEnter(bubbleWrap());+ act(() => { vi.advanceTimersByTime(60_000); });+ expect(bubbleOpen()).toBe(true);+ fireEvent.pointerLeave(bubbleWrap());+ act(() => { vi.advanceTimersByTime(2_900); });+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(200); });+ expect(bubbleOpen()).toBe(false);+ });++ it('drops the pointer hold when the input replaces the bubble under a still pointer', async () => {+ await runToResult();+ act(() => { vi.advanceTimersByTime(4_000); });+ fireEvent.pointerEnter(bubbleWrap());+ // The summon opens the input in the bubble's place; no pointer leave comes.+ summon('listen');+ await screen.findByLabelText('pet.inputPlaceholder');+ act(() => { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); });+ expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(5_900); });+ expect(bubbleOpen()).toBe(true);+ act(() => { vi.advanceTimersByTime(200); });+ expect(bubbleOpen()).toBe(false);+ });++ it('does not linger again once its history has been opened and closed', async () => {+ await runToResult();+ await userEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).not.toBeNull());+ await userEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(bubbleOpen()).toBe(false));+ });+it('stays shown while a failure needs the user', async () => {tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' }),diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsxindex 1e9a8231f..a10a91b79 100644--- a/ui/src/pet/PetPage.tsx+++ b/ui/src/pet/PetPage.tsx@@ -10,7 +10,8 @@ import { Button } from '@/components/ui/button';import { Markdown } from '@/components/ui/markdown';import { QuickReplies } from '@/components/workbench/QuickReplies';import { isComposingKey } from '@/lib/imeComposition';-import { usePageActive } from '@/lib/pageActivity';+import { useDocumentVisible, usePageActive } from '@/lib/pageActivity';+import { isDetachedCompletionMessage } from '@/lib/chatMessageTypes';import { usePendingVaultRequests } from '@/lib/usePendingVaultRequests';import { useVaultRequestRefresh } from '@/lib/useVaultRequestRefresh';import { vaultRequestType } from '@/lib/vaultRequestPlacement';@@ -20,8 +21,9 @@ import { VoiceTranscriptionError } from '@/lib/voiceTranscription';import { PetAvatar, type PetPose } from './PetAvatar';import { PetOpenButton } from './PetOpenButton';+import { REPLY_LINGER_RESUME_MS, useReplyLinger } from './useReplyLinger';import { onPetHover, petBridge, sessionLink, vaultRequestLink } from './petBridge';-import { usePetPanel } from './petPanel';+import { petPanel, usePetPanel } from './petPanel';import { petComposer, usePetComposer } from './petComposer';import { petShell, useOnSummon, usePetBinding, usePetDismissed } from './petShell';import { derivePetPose, derivePetState, latestExchange, latestFailureNotice, openQuickReplies } from './petState';@@ -45,6 +47,7 @@ const STACK_HEIGHT = 304; // 292px scroll box + 6px panel padding on each side.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 NO_REPLIES: ReadonlySet<string> = new Set();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;@@ -276,8 +279,7 @@ const PetSurface: React.FC = () => {// Typing and dictation keep the speech slot, and the draft, as they are.if (composing || voice.listening) return;if (!binding || resolvingMain || (data.messages.length === 0 && !optimisticTitle)) return;- setDetailOpen(true);- void setPanel(true);+ openHistory();};const [composing, setComposing] = useState(false);const [presentations, setPresentations] = useState<Record<string, CardPresentation>>({});@@ -648,20 +650,115 @@ const PetSurface: React.FC = () => {&& (historyOpen || data.running || optimisticTitle || exchange.user || exchange.results.length > 0 || failure || uncertain|| queued || vaultRequests.length > 0 || quickReplies),);- // Whether it is drawn (spec §4.2): only while the main session is active —- // Vibey is working, a send is pending, Vibey needs the user, or the history- // is open — and hidden the moment none holds, the turn's result included.- // Unread replies only light Vibey's badge; a Vibey click opens the history.- // Every input is the current epoch's own state, so nothing carries a bubble- // over from a previous session.+ // Whether it is drawn (spec §4.2): while the main session is active — Vibey+ // is working, a send is pending, Vibey needs the user, or the history is+ // open — and then for a short on-screen linger of a fresh reply. Unread+ // replies only light Vibey's badge. Every input is the current epoch's own+ // state, so nothing carries a bubble over from a previous session.const needsYou = Boolean((!data.running && failure) || uncertain || queued || vaultRequests.length > 0);- const showReplyBubble = hasBubbleContent && Boolean(data.running || optimisticTitle || needsYou || historyOpen);- const toggleHistory = () => { setDetailOpen(!detailOpen); void setPanel(!detailOpen); };+ // A history the user asked for but the shell has not confirmed yet holds the+ // bubble too: it neither folds nor spends the linger while it waits.+ const historyPending = detailOpen && !expanded;+ const held = Boolean(data.running || optimisticTitle || needsYou || historyOpen || historyPending);+ // A turn that ends while this epoch watches is what lingers: the moment the+ // server's turn state goes from running to done, derived during render from+ // the last value seen, so the render that ends the turn is the render that+ // starts the linger and the bubble never closes in between. The server's+ // state alone: the local send grace running out is not a turn that ended.+ // A turn already over when the epoch first looks is history.+ // One thing lingers: the reply of a turn this epoch watched end, pinned by+ // its id. Everything about the linger is derived from that reply during+ // render — whether there is one, what the summary shows, whether it was seen.+ //+ // `endedFor` is the latest input when the server's turn state was last seen+ // going from running to done (the local send grace is not a turn ending).+ // That turn's reply is the newest non-empty agent result after that input+ // that is not a background run's detached completion (an exchange can hold+ // an earlier answer from before this turn ran). Nothing before the input+ // counts, a promoted answer to an earlier input (#2815) included: it keeps+ // the badge but does not linger. A stopped turn ends with an empty result+ // and has none; a reply that lands after its turn end lingers then.+ // `seen` holds the replies shown while the history was open (expansion+ // confirmed by the shell); those do not linger again.+ const inputId = exchange.user?.id ?? '';+ const [turnWatch, setTurnWatch] = useState(() => ({ epoch, running: data.serverRunning, endedFor: null as string | null, seen: NO_REPLIES }));+ let watched = turnWatch;+ if (watched.epoch !== epoch) watched = { epoch, running: data.serverRunning, endedFor: null, seen: NO_REPLIES };+ else if (watched.running !== data.serverRunning) {+ watched = { ...watched, running: data.serverRunning, endedFor: data.serverRunning ? watched.endedFor : inputId };+ }+ const isTurnReply = (row: WorkbenchMessage) => row.author === 'agent' && row.type === 'result'+ && !isDetachedCompletionMessage(row) && Boolean(row.text?.trim());+ const inputAt = exchange.user ? data.messages.findIndex((row) => row.id === exchange.user!.id) : -1;+ const turnReply = watched.endedFor === inputId+ ? data.messages.slice(inputAt + 1).reverse().find(isTurnReply)+ : null;+ if (historyOpen && turnReply && !watched.seen.has(turnReply.id)) {+ watched = { ...watched, seen: new Set([...watched.seen, turnReply.id]) };+ }+ if (watched !== turnWatch) setTurnWatch(watched);+ const lingerReply = turnReply && !watched.seen.has(turnReply.id) ? turnReply : null;+ // The bubble is drawn: the speech slot shows it rather than the input or the+ // dictation marquee. Every input to the linger (time, pointer) means+ // something only while this holds.+ const bubbleDrawn = hasBubbleContent && Boolean(binding) && !voice.listening && !(composing && canChat && !uncertain);+ // The reply is on screen: the bubble is drawn and its summary row is the+ // reply (not "thinking" while the turn still runs, nor a failure notice).+ // Only then does the linger spend its time.+ const replyOnScreen = bubbleDrawn && !data.running && !failure;+ const documentVisible = useDocumentVisible();+ const [pointerOverBubble, setPointerOverBubble] = useState(false);+ const bubbleRef = useRef<HTMLDivElement | null>(null);+ const avatarRef = useRef<HTMLButtonElement>(null);+ // Focus inside a bubble that is replaced (by the input, the dictation+ // marquee, or a loading notice) moves to Vibey rather than to nowhere. The+ // node is checked as it detaches, while it still holds the focus.+ const attachBubble = useCallback((node: HTMLDivElement | null) => {+ bubbleRef.current = node;+ if (!node) return undefined;+ return () => {+ if (bubbleRef.current === node) bubbleRef.current = null;+ if (node.contains(document.activeElement)) avatarRef.current?.focus();+ };+ }, []);+ const { lingeringId, keepAtLeast } = useReplyLinger({+ scope: epoch,+ candidateId: lingerReply?.id ?? null,+ counting: documentVisible && replyOnScreen && !pointerOverBubble && !historyPending,+ keyboardHeld: () => {+ const node = bubbleRef.current;+ const active = document.activeElement;+ return Boolean(node && active && node.contains(active) && active.matches(':focus-visible'));+ },+ });+ const showReplyBubble = hasBubbleContent && (held || lingeringId !== null);+ // A bubble that is not drawn, or is hidden, cannot be under the pointer, and+ // its leave event may never come (the input replaced it under a still+ // pointer); a stale reading would pause the reply for good.+ if ((!bubbleDrawn || !showReplyBubble) && pointerOverBubble) setPointerOverBubble(false);+ // Looking at the history is looking at the reply (`seen` above): once it+ // closes, the reply does not linger again.+ function openHistory() {+ setDetailOpen(true);+ // A refused expansion leaves no history to wait for: drop the request so+ // the pending hold ends and the linger resumes.+ void setPanel(true).then(() => { if (epoch.isCurrent() && !petPanel.current()) setDetailOpen(false); });+ }+ const toggleHistory = () => {+ if (detailOpen) { setDetailOpen(false); void setPanel(false); } else openHistory();+ };+ useLayoutEffect(() => {+ // Focus inside a bubble that folds away (still mounted) moves to Vibey too.+ if (showReplyBubble) return;+ const node = bubbleRef.current;+ if (node && document.activeElement && node.contains(document.activeElement)) avatarRef.current?.focus();+ }, [showReplyBubble]);const avatar = (<div className={clsx('pet-mini-avatar-wrap', voice.listening && 'is-listening', hovered && 'is-hovered')} data-pet-hover>{voice.listening && <span className="pet-mini-listen-ring" aria-hidden />}<button+ ref={avatarRef}type="button"className="pet-mini-avatar-button"// A click opens or closes Vibey's recent turns (§5.1).@@ -791,9 +888,22 @@ const PetSurface: React.FC = () => {</>) : hasBubbleContent && binding ? (// Still drawn while the slot closes, so it fades out rather than vanishing.+ <div+ // Its own identity, so a notice drawn in the same place replaces+ // it (and runs the focus handoff) instead of reusing this node.+ key="vibey-bubble"+ ref={attachBubble}+ onPointerEnter={() => setPointerOverBubble(true)}+ onPointerLeave={() => {+ // Leaving gives the reader a moment before it goes.+ keepAtLeast(REPLY_LINGER_RESUME_MS);+ setPointerOverBubble(false);+ }}+ ><MainReplyBubbleopen={historyOpen}onToggle={toggleHistory}+ pinnedReply={lingeringId !== null ? lingerReply : null}epoch={epoch}voiceNeedsCloud={voice.cloudRequired}canChat={canChat}@@ -811,6 +921,7 @@ const PetSurface: React.FC = () => {uncertain={uncertain}onInspect={() => { void petBridge.open(sessionLink(binding)).then(() => { if (epoch.isCurrent()) setUncertain(binding, false); }).catch(() => undefined); }}/>+ </div>) : resolvingMain || !binding ? (<div className="pet-mini-reply-bubble pet-mini-detail-inner" data-pet-hit role="status"><p className="pet-mini-detail-muted">{t(data.canChat === null ? 'common.loading' : 'pet.vibeyUnavailable')}</p>@@ -1150,9 +1261,11 @@ const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, optype MainDetailProps = { epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; canChat: boolean; visible: boolean; binding: string; exchange: ReturnType<typeof latestExchange>; messages: WorkbenchMessage[]; failure: WorkbenchMessage | null; running: boolean; queued: boolean; markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>; onRead: () => void; vaultRequestIds: string[]; quickReplies: ReturnType<typeof openQuickReplies>; onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>; uncertain: boolean; onInspect: () => void };-const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boolean; onToggle: () => void }> = ({ open, onToggle, ...props }) => {+const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boolean; onToggle: () => void; pinnedReply?: WorkbenchMessage | null }> = ({ open, onToggle, pinnedReply, ...props }) => {const { t } = useTranslation();- const last = props.exchange.results.at(-1);+ // A lingering reply keeps its summary even if a later result (a background+ // completion) arrives while it lingers.+ const last = pinnedReply ?? props.exchange.results.at(-1);const summary = props.running ? t('pet.thinking'): props.failure ? `${t('pet.failedPrefix')} ${props.failure.text.trim()}`: last?.text?.trim() ? t('pet.repliedPrefix', { text: last.text.trim() })diff --git a/ui/src/pet/usePetSession.ts b/ui/src/pet/usePetSession.tsindex 2feb42e88..857fa1c3f 100644--- a/ui/src/pet/usePetSession.ts+++ b/ui/src/pet/usePetSession.ts@@ -42,6 +42,9 @@ export type PetSessionData = {turn: SessionRuntimeState | null;/** Running per the server, or a local send inside the registration grace. */running: boolean;+ /** Running per the server's turn state alone, without the local send grace:+ * its end is a turn that really finished, not a grace that ran out. */+ serverRunning: boolean;/** Merge a row the pet itself just sent. */noteSent: (message: WorkbenchMessage | null) => void;/** Re-read the tail from the server. */@@ -300,6 +303,7 @@ export function usePetSession(sessionId: string | null): PetSessionData {hasOlder: tail.hasOlder || !tail.loaded,turn,running: working,+ serverRunning,noteSent,refreshTail,};diff --git a/ui/src/pet/useReplyLinger.ts b/ui/src/pet/useReplyLinger.tsnew file mode 100644index 000000000..7ab8ed81c--- /dev/null+++ b/ui/src/pet/useReplyLinger.ts@@ -0,0 +1,76 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import { useLatestRef } from '@/lib/useLatestRef';++/** How long a reply stays on screen after its turn ends, once nothing else holds the bubble. */+export const REPLY_LINGER_MS = 10_000;+/** The least time left when the pointer leaves a paused reply. */+export const REPLY_LINGER_RESUME_MS = 3_000;+/** How soon to look again while keyboard focus holds an otherwise spent reply. */+const KEYBOARD_RECHECK_MS = 1_000;++const NONE: ReadonlySet<string> = new Set();++/**+ * The on-screen linger of Vibey's reply after a turn ends (spec §4.2).+ *+ * Nothing here opens anything. `candidateId` names the ended turn whose reply+ * may linger, derived by the caller during render, and it lingers until it is+ * expired. Expiry is the only state: a set of ended-turn ids, scoped to+ * `scope` (the session epoch), so a new epoch starts with nothing expired and+ * nothing carried over. One timer spends the budget while `counting` holds and+ * is rescheduled whenever that changes; time paused is kept, not spent.+ *+ * Keyboard focus is read when the budget runs out, not tracked: if it sits on+ * a focus-visible control inside the bubble, the reply is kept a little longer+ * and looked at again; a pointer click never leaves anything pinned.+ */+export function useReplyLinger({ scope, candidateId, counting, keyboardHeld }: {+ scope: unknown;+ candidateId: string | null;+ counting: boolean;+ keyboardHeld: () => boolean;+}) {+ const [state, setState] = useState<{ scope: unknown; expired: ReadonlySet<string> }>(() => ({ scope, expired: NONE }));+ const expired = state.scope === scope ? state.expired : NONE;+ const lingeringId = candidateId !== null && !expired.has(candidateId) ? candidateId : null;+ const budget = useRef<{ scope: unknown; id: string | null; remaining: number }>({ scope: null, id: null, remaining: 0 });+ const keyboardHeldRef = useLatestRef(keyboardHeld);++ const expire = useCallback((id: string) => {+ setState((current) => ({ scope, expired: new Set([...(current.scope === scope ? current.expired : NONE), id]) }));+ }, [scope]);++ useEffect(() => {+ if (lingeringId === null || !counting) return undefined;+ if (budget.current.scope !== scope || budget.current.id !== lingeringId) {+ budget.current = { scope, id: lingeringId, remaining: REPLY_LINGER_MS };+ }+ let started = Date.now();+ let timer = 0;+ const decide = () => {+ if (keyboardHeldRef.current()) {+ budget.current.remaining = KEYBOARD_RECHECK_MS;+ started = Date.now();+ timer = window.setTimeout(decide, KEYBOARD_RECHECK_MS);+ return;+ }+ budget.current.remaining = 0;+ expire(lingeringId);+ };+ timer = window.setTimeout(decide, budget.current.remaining);+ return () => {+ window.clearTimeout(timer);+ budget.current.remaining = Math.max(0, budget.current.remaining - (Date.now() - started));+ };+ }, [lingeringId, counting, scope, expire, keyboardHeldRef]);++ /** Leave at least `ms` on the lingering reply, as when the pointer leaves it. */+ const keepAtLeast = useCallback((ms: number) => {+ if (budget.current.scope === scope && budget.current.id === lingeringId) {+ budget.current.remaining = Math.max(budget.current.remaining, ms);+ }+ }, [scope, lingeringId]);++ return { lingeringId, expire, keepAtLeast };+}