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.

feat(pet): optimize desktop mini card display (#3057)

Max83c8a6f094d1
diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs
index a61b6587d..b0d798a2d 100644
--- a/desktop/src-tauri/build.rs
+++ b/desktop/src-tauri/build.rs
@@ -25,6 +25,7 @@ fn main() {
"pet_set_voice_mode",
"pet_reset_voice_shortcut",
"pet_ready",
+ "pet_context_menu",
"pet_set_expanded",
"pet_drag",
"pet_settle",
diff --git a/desktop/src-tauri/capabilities/pet.json b/desktop/src-tauri/capabilities/pet.json
index 7f992b461..30ffcd2ca 100644
--- a/desktop/src-tauri/capabilities/pet.json
+++ b/desktop/src-tauri/capabilities/pet.json
@@ -9,6 +9,7 @@
},
"permissions": [
"allow-pet-ready",
+ "allow-pet-context-menu",
"allow-pet-set-expanded",
"allow-pet-drag",
"allow-pet-settle",
diff --git a/desktop/src-tauri/permissions/autogenerated/pet_context_menu.toml b/desktop/src-tauri/permissions/autogenerated/pet_context_menu.toml
new file mode 100644
index 000000000..24d9087a3
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/pet_context_menu.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-pet-context-menu"
+description = "Enables the pet_context_menu command without any pre-configured scope."
+commands.allow = ["pet_context_menu"]
+
+[[permission]]
+identifier = "deny-pet-context-menu"
+description = "Denies the pet_context_menu command without any pre-configured scope."
+commands.deny = ["pet_context_menu"]
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 3c16448e6..aaacaa171 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -2209,6 +2209,7 @@ pub fn run() {
}
pet::MENU_ID => pet::toggle(app),
pet::SHORTCUT_SETTINGS_MENU_ID => open_workbench_shortcut_settings(app),
+ pet::HIDE_MENU_ID => pet::toggle(app),
#[cfg(target_os = "macos")]
COMPUTER_USE_MENU_ID => {
app.state::<computer_use::Controller>().toggle();
@@ -2337,6 +2338,7 @@ pub fn run() {
pet::pet_reset_shortcuts,
pet::pet_set_voice_mode,
pet::pet_ready,
+ pet::pet_context_menu,
pet::pet_set_expanded,
pet::pet_drag,
pet::pet_settle,
diff --git a/desktop/src-tauri/src/pet.rs b/desktop/src-tauri/src/pet.rs
index 8a77e2f90..aa35805e4 100644
--- a/desktop/src-tauri/src/pet.rs
+++ b/desktop/src-tauri/src/pet.rs
@@ -23,7 +23,7 @@ use avibe_runtime_host::pet::{
};
use avibe_runtime_host::LoopbackOrigin;
use serde::{Deserialize, Serialize};
-use tauri::menu::{CheckMenuItem, MenuItem};
+use tauri::menu::{CheckMenuItem, Menu, MenuItem};
use tauri::{
AppHandle, Manager, Monitor, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindow, WebviewWindowBuilder,
};
@@ -36,6 +36,7 @@ use crate::{native_catalog_for_locales, Shell, DESKTOP_SHELL_MARKER, MAIN_WINDOW
pub const PET_WINDOW: &str = "pet";
pub const MENU_ID: &str = "show-pet";
pub const SHORTCUT_SETTINGS_MENU_ID: &str = "pet-shortcut-settings";
+pub const HIDE_MENU_ID: &str = "hide-pet";
const PET_PATH: &str = "/pet";
const SUMMON_EVENT: &str = "avibe:pet-summon";
const BOUND_EVENT: &str = "avibe:pet-bound";
@@ -71,12 +72,17 @@ pub const DESKTOP_PET_SETTINGS_MARKER: &str =
pub struct NativePetCatalog {
toggle: String,
shortcut_settings: String,
+ hide: String,
}
fn native_pet_catalog() -> NativePetCatalog {
native_catalog_for_locales(sys_locale::get_locales()).pet
}
+fn native_pet_menu_accelerator(store: &PetStore) -> &str {
+ store.toggle_shortcut()
+}
+
#[derive(Clone, Copy)]
struct Frame {
expanded: bool,
@@ -446,6 +452,28 @@ pub fn toggle(app: &AppHandle) {
}
}
+/// Shows the pet's native context menu. The menu action calls [`toggle`]
+/// through the same event path as the tray switch, so both surfaces persist
+/// the same `enabled` preference and reconcile the same window.
+#[tauri::command]
+pub fn pet_context_menu(window: WebviewWindow) -> Result<(), String> {
+ ensure_pet_page(&window)?;
+ let app = window.app_handle();
+ let pet = app.state::<Pet>();
+ if !pet.enabled() {
+ return Ok(());
+ }
+ let catalog = native_pet_catalog();
+ let shortcut = {
+ let store = pet.store();
+ native_pet_menu_accelerator(&store).to_owned()
+ };
+ let hide = MenuItem::with_id(app, HIDE_MENU_ID, &catalog.hide, true, Some(shortcut.as_str()))
+ .map_err(|error| error.to_string())?;
+ let menu = Menu::with_items(app, &[&hide]).map_err(|error| error.to_string())?;
+ window.popup_menu(&menu).map_err(|error| error.to_string())
+}
+
#[derive(Debug, PartialEq, Eq)]
enum ShortcutAction {
Toggle,
@@ -1539,6 +1567,7 @@ pub fn pet_open(window: WebviewWindow, link: String) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::*;
+ use avibe_runtime_host::pet::shortcut_label;
use avibe_runtime_host::pet::{settle_frame, DRAG_HEIGHT, WINDOW_HEIGHT};
use std::cell::RefCell;
@@ -1751,9 +1780,26 @@ mod tests {
let catalog = native_catalog_for_locales([locale.to_owned()]).pet;
assert!(!catalog.toggle.is_empty());
assert!(!catalog.shortcut_settings.is_empty());
+ assert!(!catalog.hide.is_empty());
}
}
+ #[test]
+ fn context_menu_uses_raw_toggle_shortcut_as_native_accelerator() {
+ let directory = TestPetDirectory::new();
+ let pet = Pet::new(directory.file());
+ let store = pet.store();
+ let accelerator = native_pet_menu_accelerator(&store);
+
+ assert_eq!(accelerator, DEFAULT_TOGGLE_SHORTCUT);
+ assert!(parse_shortcut(accelerator).is_ok());
+ assert_ne!(
+ accelerator,
+ shortcut_label(accelerator, cfg!(target_os = "macos")),
+ "native menus receive the accelerator syntax, not the display label"
+ );
+ }
+
fn origin(raw: &str) -> LoopbackOrigin {
LoopbackOrigin::parse(raw).unwrap()
}
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index 1efe3d3da..4e65e4b62 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -456,6 +456,7 @@ fn every_shell_command_is_declared_so_its_permission_exists() {
"pet_set_voice_mode",
"pet_reset_voice_shortcut",
"pet_ready",
+ "pet_context_menu",
"pet_set_expanded",
"pet_drag",
"pet_settle",
@@ -1242,6 +1243,7 @@ fn the_pet_and_the_workbench_get_only_their_pet_commands_on_loopback_pages() {
pet["permissions"],
serde_json::json!([
"allow-pet-ready",
+ "allow-pet-context-menu",
"allow-pet-set-expanded",
"allow-pet-drag",
"allow-pet-settle",
diff --git a/ui/e2e/pet-mini/layout.spec.ts b/ui/e2e/pet-mini/layout.spec.ts
index ffe10983d..520a5d3d1 100644
--- a/ui/e2e/pet-mini/layout.spec.ts
+++ b/ui/e2e/pet-mini/layout.spec.ts
@@ -17,7 +17,8 @@ for (const theme of ['light', 'dark']) {
- document.querySelector('.pet-mini-collapsed')!.getBoundingClientRect().bottom);
expect(gap).toBeGreaterThanOrEqual(13);
expect(gap).toBeLessThanOrEqual(15);
- await expect(page.locator('.pet-mini-reply-toggle')).toContainText(lang === 'zh' ? /已回复:\S/ : /Replied: \S/);
+ await expect(page.locator('.pet-mini-reply-toggle')).not.toContainText(/已回复:|Replied:/);
+ await expect(page.locator('.pet-mini-reply-toggle')).toContainText('我会帮你');
await page.locator('.pet-mini-collapsed').click();
const stop = page.locator('.pet-mini-stop').first();
await expect(stop).toHaveAttribute('aria-label', lang === 'zh' ? /^停止:.+/ : /^Stop: .+/);
@@ -986,11 +987,11 @@ test('an old, finished exchange starts with the bubble hidden, and takes no spac
await expect.poll(() => bubbleIsRegion(page)).toBe(false);
});
-// The reply lingers for 10s of on-screen time after the turn ends (spec §4.2).
+// The reply lingers for 20s 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 expect(page.locator('.pet-mini-reply-toggle')).toContainText('思考中');
await page.evaluate((text) =>
window.petFixtureFinishTurn({ id: 'live_reply', author: 'agent', type: 'result', text, read_at: null }), text);
};
@@ -1007,7 +1008,7 @@ const tabToToggle = async (page: import('@playwright/test').Page, browserName: s
};
for (const theme of ['light', 'dark']) {
- test(`a running turn shows thinking, then its reply for 10s on screen (${theme})`, async ({ page }) => {
+ test(`a running turn shows thinking, then its reply for 20s 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);
@@ -1017,8 +1018,8 @@ for (const theme of ['light', 'dark']) {
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(page.locator('.pet-mini-reply-toggle')).toContainText('做完了。');
+ await page.clock.runFor(19_500);
await expect(bubbleShown(page)).toBeVisible();
await page.clock.runFor(1_000);
await expect(bubbleShown(page)).toHaveCount(0);
@@ -1034,12 +1035,12 @@ test('a background completion arriving during the linger does not take over its
await page.clock.runFor(500);
await finishTurn(page);
await page.clock.runFor(1_000);
- await expect(page.locator('.pet-mini-reply-toggle')).toContainText('已回复:做完了。');
+ 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')).toContainText('做完了。');
await expect(page.locator('.pet-mini-reply-toggle')).not.toContainText('后台任务');
});
@@ -1375,7 +1376,7 @@ for (const reduced of [false, true]) {
}
return seen;
});
- await expect(page.locator('.pet-mini-reply-toggle')).toContainText('已回复');
+ await expect(page.locator('.pet-mini-reply-toggle')).toContainText('做完了');
for (const frame of frames) expect(Math.abs(frame.centre - centre)).toBeLessThanOrEqual(1);
const widths = frames.map((frame) => frame.width);
for (let i = 1; i < widths.length; i += 1) expect(widths[i]).toBeGreaterThanOrEqual(widths[i - 1] - 0.5);
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 71749a0f9..1578527e1 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -582,7 +582,6 @@
},
"src/pet/PetPage.tsx": {
"avibe/localized-user-text": 3,
- "react-hooks/preserve-manual-memoization": 2,
"react-hooks/set-state-in-effect": 6
}
},
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 8730a248b..b0d3ad0c3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -99,6 +99,7 @@
},
"pet": {
"toggle": "Show Pet",
+ "hide": "Hide Desktop Mini",
"shortcutSettings": "Shortcut settings…"
},
"uninstall": {
@@ -6277,7 +6278,7 @@
"mainAgentTitle": "Vibey",
"thinking": "Thinking",
"waiting": "Waiting",
- "repliedPrefix": "Replied: {{text}}",
+ "fileAttachment": "File",
"untitledTask": "Untitled task",
"dismiss": "Dismiss task",
"voiceContinue": "Continue voice input",
@@ -6333,7 +6334,6 @@
"unknownProject": "Conversation",
"unknownAgent": "Agent",
"needsAuthorization": "Needs your approval",
- "replied": "Replied",
"referenceSession": "Reference session: {{title}}",
"authorize": "Review",
"recentTurns": "Recent turns",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index f3d20af49..e8abfd6a7 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -99,6 +99,7 @@
},
"pet": {
"toggle": "显示桌宠",
+ "hide": "隐藏桌宠",
"shortcutSettings": "快捷键设置…"
},
"uninstall": {
@@ -6277,7 +6278,7 @@
"mainAgentTitle": "歪比",
"thinking": "思考中",
"waiting": "等待中",
- "repliedPrefix": "已回复:{{text}}",
+ "fileAttachment": "文件",
"untitledTask": "未命名任务",
"dismiss": "移除任务",
"voiceContinue": "继续语音输入",
@@ -6333,7 +6334,6 @@
"unknownProject": "会话",
"unknownAgent": "Agent",
"needsAuthorization": "需要你授权",
- "replied": "已回复",
"referenceSession": "引用会话:{{title}}",
"authorize": "授权",
"recentTurns": "最近几轮",
diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsx
index ff84909d8..500da948e 100644
--- a/ui/src/pet/PetPage.test.tsx
+++ b/ui/src/pet/PetPage.test.tsx
@@ -207,7 +207,13 @@ const showCards = async () => {
const showDetail = async () => {
await showCards();
const main = document.querySelector('.pet-mini-reply-toggle');
- if (main && !document.querySelector('.pet-mini-detail.is-open')) fireEvent.click(main);
+ if (document.querySelector('.pet-mini-detail.is-open')) return;
+ if (main) {
+ fireEvent.click(main);
+ return;
+ }
+ const avatar = screen.queryByLabelText('pet.recentTurns');
+ if (avatar) fireEvent.click(avatar);
};
const pose = () => document.querySelector('.pet-avatar')?.getAttribute('data-pose');
@@ -398,7 +404,7 @@ describe('main-only resolution', () => {
await emit((h) => h.onAuthorizationChanged?.({}));
await showDetail();
await emit((h) => h.onMessageNew?.(message('new-authorized', 'S', { text: 'New authorized reply' })));
- expect(await screen.findByText('New authorized reply')).toBeTruthy();
+ expect((await screen.findAllByText('New authorized reply')).length).toBeGreaterThan(0);
});
it('keeps a draft through a transient resolution failure and fences a late transcript after access is lost', async () => {
@@ -479,7 +485,7 @@ describe('PetPage state', () => {
await waitFor(() => expect(api.getTurnState.mock.calls.length).toBeGreaterThan(before));
});
- it('marks read through the last rendered unread result only when all unread rows are loaded', async () => {
+ it('keeps omitted unread results unread when the card renders only the latest one', async () => {
tails.S = [
message('r1', 'S'),
message('u', 'S', { author: 'user', type: 'user' }),
@@ -491,20 +497,26 @@ describe('PetPage state', () => {
render(<PetPage />);
await waitFor(() => expect(pose()).toBe('ready'));
await showDetail();
- await screen.findByText('reply r3');
- await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r3'));
+ await screen.findAllByText('reply r3');
+ expect(markRead).not.toHaveBeenCalled();
});
it('does not mark read when unread rows may reach past the loaded tail', async () => {
tails.S = [message('r2', 'S', { read_at: null })];
- api.listSessionMessages.mockImplementationOnce(async (id: string) => ({
+ const incompleteTail = async (id: string) => ({
messages: tails[id] ?? [], next_after_id: null, next_before_id: 'older',
- }));
+ });
+ api.listSessionMessages
+ .mockImplementationOnce(incompleteTail)
+ .mockImplementationOnce(incompleteTail)
+ .mockImplementationOnce(incompleteTail)
+ .mockImplementationOnce(incompleteTail)
+ .mockImplementationOnce(incompleteTail);
unreadBySession = { S: 5 };
mainSession('S');
render(<PetPage />);
await showDetail();
- expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
+ expect(document.querySelector('.pet-mini-detail.is-open')).toBeTruthy();
expect(markRead).not.toHaveBeenCalled();
});
});
@@ -597,7 +609,7 @@ describe('PetPage review fixes', () => {
mainSession('S');
render(<PetPage />);
await showDetail();
- await screen.findByText('reply r1');
+ await screen.findAllByText('reply r1');
await waitFor(() => expect(markRead).toHaveBeenCalled());
await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
expect(markRead).toHaveBeenCalledTimes(1);
@@ -696,7 +708,7 @@ describe('PetPage review fixes, round 3', () => {
mainSession('S');
render(<PetPage />);
await showDetail();
- await screen.findByText('reply r1');
+ await screen.findAllByText('reply r1');
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
expect(markRead).not.toHaveBeenCalled();
visibility = 'visible';
@@ -754,12 +766,15 @@ describe('PetPage independent sweep', () => {
});
it('does not mark read through rows trimmed from a long live tail', async () => {
- tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null })];
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S')];
unreadBySession = { S: 2 };
+ api.listSessionMessages.mockImplementationOnce(async (id: string) => ({
+ messages: tails[id] ?? [], next_after_id: null, next_before_id: 'older',
+ }));
mainSession('S');
render(<PetPage />);
- // The hidden history proves the initial read applied without marking it read.
- await screen.findByText('reply r1');
+ // The old reply stays hidden until the user opens the card.
+ await screen.findByLabelText('pet.recentTurns');
// A long turn: many transcript rows arrive live, pushing r1 out of the tail.
await emit((h) => {
for (let index = 0; index < 70; index += 1) {
@@ -768,7 +783,7 @@ describe('PetPage independent sweep', () => {
h.onMessageNew?.(message('r2', 'S', { read_at: null, text: 'reply r2' }));
});
await showDetail();
- expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
+ expect(document.querySelector('.pet-mini-detail.is-open')).toBeTruthy();
expect(markRead).not.toHaveBeenCalled();
});
});
@@ -823,8 +838,8 @@ describe('PetPage review fixes, round 7', () => {
// The live summon is newer than the pending one pet_ready still carries.
await shellBound('S', 1);
await showDetail();
- // The summon expanded the panel (Vibey's aria-expanded now speaks for the history).
- expect(screen.getByLabelText('pet.panel')).toBeTruthy();
+ // There is no reply yet, so the expanded surface contains only the input.
+ expect(screen.getByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeTruthy();
act(() => {
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
});
@@ -854,7 +869,7 @@ describe('PetPage review fixes, round 8', () => {
const r2 = message('r2', 'S', { read_at: null, text: 'second reply' });
tails.S = [...tails.S, r2];
await emit((h) => h.onMessageNew?.(r2));
- await screen.findByText('second reply');
+ await screen.findAllByText('second reply');
expect(screen.queryByText('first reply')).toBeNull();
});
@@ -920,7 +935,7 @@ describe('PetPage review fixes, round 10', () => {
mainSession('S');
render(<PetPage />);
await showDetail();
- await screen.findByText('unseen');
+ await screen.findAllByText('unseen');
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
expect(markRead).not.toHaveBeenCalled();
windowFocused = true;
@@ -999,7 +1014,7 @@ describe('PetPage review fixes, round 13', () => {
mainSession('S');
render(<PetPage />);
await showDetail();
- await screen.findByText('private reply');
+ await screen.findAllByText('private reply');
sessionReads.S = async () => ({ status: 403, session: null });
await emit((h) => h.onAuthorizationChanged?.({}));
await waitFor(() => expect(screen.queryByText('private reply')).toBeNull());
@@ -1019,9 +1034,8 @@ describe('PetPage async closure', () => {
mainSession('S');
render(<PetPage />);
await showDetail();
- await screen.findByLabelText('pet.panel');
await emit((h) => h.onMessageNew?.(message('live', 'S', { read_at: null })));
- await screen.findByText('reply live');
+ await screen.findAllByText('reply live');
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
expect(markRead).not.toHaveBeenCalled();
// The snapshot shows older unread rows past the tail: still not marked.
@@ -1638,7 +1652,7 @@ describe('desktop mini v2 interaction contract', () => {
class Dictation { done = new Promise<string>(() => {}); start = start; finish = () => {}; abort = () => {}; }
await withVoiceEnv(() => true, Dictation, async () => {
vi.stubGlobal('fetch', vi.fn(() => status.promise));
- mainSession('S'); render(<PetPage />); await screen.findByText('Session S');
+ mainSession('S'); render(<PetPage />); await screen.findByLabelText('pet.recentTurns');
const avatar = screen.getByLabelText('pet.recentTurns');
vi.useFakeTimers();
try {
@@ -1763,7 +1777,7 @@ describe('desktop mini v2 interaction contract', () => {
const report = vi.spyOn(petBridge, 'setHitRegions').mockResolvedValue(undefined);
try {
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
const oldFrames = [...frames];
expect(oldFrames.length).toBeGreaterThan(0);
await emit((h) => h.onAuthorizationChanged?.({}));
@@ -1925,6 +1939,7 @@ describe('desktop mini v2 interaction contract', () => {
});
it.each(['blur', 'open'])('suppresses the idle dock after %s until shell leave and re-enter', async (cause) => {
+ canChat = cause !== 'open';
mainSession('S'); render(<PetPage />);
const avatar = await screen.findByLabelText('pet.recentTurns');
const wrap = avatar.closest('.pet-mini-avatar-wrap')!;
@@ -1951,6 +1966,7 @@ describe('desktop mini v2 interaction contract', () => {
});
it.each(['blur', 'open'])('restores the idle dock on the first enter when already outside before %s', async (cause) => {
+ canChat = cause !== 'open';
mainSession('S'); render(<PetPage />);
const avatar = await screen.findByLabelText('pet.recentTurns');
const wrap = avatar.closest('.pet-mini-avatar-wrap')!;
@@ -2040,12 +2056,11 @@ describe('desktop mini v2 interaction contract', () => {
unreadBySession = { S: 1 };
mainSession('S');
render(<PetPage />);
- await screen.findByText('Question');
+ await screen.findByLabelText('pet.recentTurns');
expect(markRead).not.toHaveBeenCalled();
summon('show');
- await waitFor(() => expect(document.querySelector('.pet-mini-detail')).toBeTruthy());
- expect(markRead).not.toHaveBeenCalled();
- fireEvent.click(document.querySelector('.pet-mini-reply-toggle')!);
+ fireEvent.click(screen.getByLabelText('pet.recentTurns'));
+ await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).toBeTruthy());
await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r'));
fireEvent.click(screen.getByLabelText('pet.recentTurns'));
await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull());
@@ -2117,7 +2132,7 @@ describe('desktop mini v2 interaction contract', () => {
});
it('holds for exactly 320ms, cancels a departed press, and falls back to text without voice support', async () => {
- mainSession('S'); render(<PetPage />); await screen.findByText('Session S');
+ mainSession('S'); render(<PetPage />); await screen.findByLabelText('pet.recentTurns');
const avatar = screen.getByLabelText('pet.recentTurns');
vi.useFakeTimers();
fireEvent.pointerDown(avatar, { button: 0, pointerId: 1 });
@@ -2143,7 +2158,7 @@ describe('desktop mini v2 interaction contract', () => {
it('opens the history above the typed input, keeping its draft, focus and caret, and Escape closes the history first', async () => {
withHistory();
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
await userEvent.click(screen.getByLabelText('pet.keyboard.open'));
const input = await screen.findByRole('textbox') as HTMLTextAreaElement;
await userEvent.type(input, 'half a thought');
@@ -2155,6 +2170,7 @@ describe('desktop mini v2 interaction contract', () => {
expect(screen.getByRole('textbox')).toBe(input);
expect(input.value).toBe('half a thought');
expect(document.activeElement).toBe(input);
+ expect(screen.getByLabelText('pet.keyboard.close').getAttribute('aria-pressed')).toBe('true');
expect([input.selectionStart, input.selectionEnd]).toEqual([4, 4]);
// Drawn in the same slot, above the input.
const bubble = document.querySelector('.pet-mini-reply-bubble')!;
@@ -2181,10 +2197,9 @@ describe('desktop mini v2 interaction contract', () => {
it('keeps an open history when the input opens, and sends from the input below it', async () => {
withHistory();
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
await userEvent.click(screen.getByLabelText('pet.recentTurns'));
await waitFor(() => expect(historyIsOpen()).toBe(true));
- await userEvent.click(screen.getByLabelText('pet.keyboard.open'));
const input = await screen.findByRole('textbox');
expect(historyIsOpen()).toBe(true);
await userEvent.type(input, 'next{Enter}');
@@ -2218,133 +2233,112 @@ describe('desktop mini v2 interaction contract', () => {
});
});
- it.each([false, true])('a double-click opens once without ever toggling history (initially open=%s)', async (initiallyOpen) => {
+ it('handles a single pointer click immediately and keeps the draft when the card closes', async () => {
+ withHistory();
+ mainSession('S'); render(<PetPage />);
+ await screen.findByLabelText('pet.recentTurns');
+ const avatar = screen.getByLabelText('pet.recentTurns');
+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 1 });
+ fireEvent.pointerUp(avatar, { pointerId: 1 });
+ await waitFor(() => expect(historyIsOpen()).toBe(true));
+ const input = screen.getByRole('textbox') as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: 'keep this draft' } });
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 2 });
+ fireEvent.pointerUp(avatar, { pointerId: 2 });
+ await waitFor(() => expect(historyIsOpen()).toBe(false));
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('keep this draft');
+ });
+
+ it('opens the main session on a double-click and leaves the main card closed', async () => {
withHistory();
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
const { petBridge } = await import('./petBridge');
const opens = vi.spyOn(petBridge, 'open').mockResolvedValue();
const panel = vi.spyOn(petBridge, 'setExpanded');
const avatar = screen.getByLabelText('pet.recentTurns');
- if (initiallyOpen) {
- fireEvent.click(avatar);
- await waitFor(() => expect(historyIsOpen()).toBe(true));
- }
- panel.mockClear();
- vi.useFakeTimers({ shouldAdvanceTime: true });
- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
- await user.dblClick(avatar);
- expect(historyIsOpen()).toBe(initiallyOpen);
- expect(panel).not.toHaveBeenCalled();
+ await userEvent.dblClick(avatar);
+ expect(historyIsOpen()).toBe(false);
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(document.querySelector('.pet-mini-dock.is-active')).toBeNull();
expect(opens).toHaveBeenCalledExactlyOnceWith('avibe://session/S');
- // The main window taking key is part of the double-click, not a collapse.
- act(() => window.dispatchEvent(new Event('blur')));
- await act(async () => vi.advanceTimersByTime(1000));
- expect(historyIsOpen()).toBe(initiallyOpen);
- expect(panel).not.toHaveBeenCalled();
- expect(opens).toHaveBeenCalledTimes(1);
+ expect(panel).toHaveBeenCalledWith(true);
+ expect(panel).toHaveBeenCalledWith(false);
});
- it('confirms single pointer clicks after 450ms, while keyboard activation is immediate', async () => {
+ it('does not pair a completed hold with a later native double-click count', async () => {
withHistory();
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
const { petBridge } = await import('./petBridge');
const opens = vi.spyOn(petBridge, 'open').mockResolvedValue();
const avatar = screen.getByLabelText('pet.recentTurns');
vi.useFakeTimers();
- for (const next of [true, false]) {
- fireEvent.pointerDown(avatar, { button: 0 });
- fireEvent.pointerUp(avatar);
- expect(historyIsOpen()).toBe(!next);
- await act(async () => vi.advanceTimersByTime(449));
- expect(historyIsOpen()).toBe(!next);
- await act(async () => vi.advanceTimersByTime(1));
- expect(historyIsOpen()).toBe(next);
+ try {
+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 1 });
+ await act(async () => vi.advanceTimersByTime(320));
+ fireEvent.pointerUp(avatar, { pointerId: 1 });
+
+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 2, detail: 2 });
+ fireEvent.mouseDown(avatar, { detail: 2 });
+ fireEvent.pointerUp(avatar, { pointerId: 2 });
+
+ expect(opens).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
}
- await act(async () => fireEvent.click(avatar));
- expect(historyIsOpen()).toBe(true);
- await act(async () => fireEvent.click(avatar));
- expect(historyIsOpen()).toBe(false);
- expect(opens).not.toHaveBeenCalled();
});
- it.each([1, 2])('pairs a second press with click count %s before the first timer can fire', async (clicks) => {
+ it('keeps the dock suppressed after opening Avibe until a fresh pointer re-entry', async () => {
withHistory();
+ canChat = false;
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
const { petBridge } = await import('./petBridge');
const opens = vi.spyOn(petBridge, 'open').mockResolvedValue();
- const panel = vi.spyOn(petBridge, 'setExpanded');
const avatar = screen.getByLabelText('pet.recentTurns');
- vi.useFakeTimers();
- fireEvent.pointerDown(avatar, { button: 0 });
- fireEvent.mouseDown(avatar, { detail: 1 });
- fireEvent.pointerUp(avatar);
- await act(async () => vi.advanceTimersByTime(440));
- expect(historyIsOpen()).toBe(false);
- fireEvent.pointerDown(avatar, { button: 0 });
- fireEvent.mouseDown(avatar, { detail: clicks });
- await act(async () => vi.advanceTimersByTime(100));
- expect(panel).not.toHaveBeenCalled();
- fireEvent.pointerUp(avatar);
- fireEvent.doubleClick(avatar);
- await act(async () => vi.advanceTimersByTime(1000));
- expect(panel).not.toHaveBeenCalled();
- expect(opens).toHaveBeenCalledExactlyOnceWith('avibe://session/S');
+ const wrap = avatar.closest('.pet-mini-avatar-wrap')!;
+ act(() => window.dispatchEvent(new CustomEvent(PET_HOVER_EVENT, { detail: { hover: true } })));
+ await userEvent.dblClick(avatar);
+ act(() => window.dispatchEvent(new Event('blur')));
+ expect(opens).toHaveBeenCalledOnce();
+ expect(wrap.classList.contains('is-hover-suppressed')).toBe(true);
+ act(() => window.dispatchEvent(new CustomEvent(PET_HOVER_EVENT, { detail: { hover: false } })));
+ act(() => window.dispatchEvent(new CustomEvent(PET_HOVER_EVENT, { detail: { hover: true } })));
+ expect(wrap.classList.contains('is-hover-suppressed')).toBe(false);
});
- it.each(['hold', 'drag', 'cancel', 'leave'])('a %s cancels a pending click and cannot open the conversation', async (gesture) => {
+ it.each(['drag', 'cancel', 'leave'])('a %s is not counted as a click', async (gesture) => {
withHistory();
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
const { petBridge } = await import('./petBridge');
const opens = vi.spyOn(petBridge, 'open').mockResolvedValue();
const avatar = screen.getByLabelText('pet.recentTurns');
- vi.useFakeTimers();
- fireEvent.pointerDown(avatar, { button: 0 });
- fireEvent.pointerUp(avatar);
fireEvent.pointerDown(avatar, { button: 0, clientX: 0, clientY: 0 });
- fireEvent.mouseDown(avatar, { detail: 2 });
- if (gesture === 'hold') await act(async () => vi.advanceTimersByTime(320));
if (gesture === 'drag') fireEvent.pointerMove(avatar, { buttons: 1, clientX: 20, clientY: 0 });
if (gesture === 'cancel') fireEvent.pointerCancel(avatar);
if (gesture === 'leave') fireEvent.pointerLeave(avatar);
fireEvent.pointerUp(avatar);
- fireEvent.doubleClick(avatar);
- await act(async () => vi.advanceTimersByTime(1000));
expect(historyIsOpen()).toBe(false);
expect(opens).not.toHaveBeenCalled();
});
- it('a quick click after a hold is a single click, not a double-click', async () => {
- const invoke = vi.fn((command: string) => {
- if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
- return Promise.resolve(command === 'pet_open' ? null : { 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 });
+ it('opens the text input on a long press without opening the main session', async () => {
withHistory();
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
const avatar = screen.getByLabelText('pet.recentTurns');
- // A click, then a hold (which opens the input without voice), then a
- // press the platform counts as the second of a double-click.
- await userEvent.click(avatar);
- await waitFor(() => expect(historyIsOpen()).toBe(true));
+ vi.useFakeTimers();
fireEvent.pointerDown(avatar, { button: 0, pointerId: 7 });
- fireEvent.mouseDown(avatar, { detail: 2 });
- await act(async () => new Promise((resolve) => setTimeout(resolve, 400)));
+ await act(async () => vi.advanceTimersByTime(320));
+ expect(screen.getByRole('textbox')).toBeTruthy();
fireEvent.pointerUp(avatar, { pointerId: 7 });
- expect(await screen.findByRole('textbox')).toBeTruthy();
- fireEvent.pointerDown(avatar, { button: 0, pointerId: 8 });
- fireEvent.mouseDown(avatar, { detail: 2 });
- fireEvent.pointerUp(avatar, { pointerId: 8 });
- await waitFor(() => expect(historyIsOpen()).toBe(false));
- expect(invoke.mock.calls.filter(([command]) => command === 'pet_open')).toEqual([]);
+ expect(historyIsOpen()).toBe(false);
});
- it('a double-click never collapses the expanded card list, while a confirmed single click does', async () => {
+ it('collapses the other cards and opens the main card on a single click', async () => {
canUseAgents = true;
const row = workingIn('running').agents[0];
runningAgents = { ...workingIn('running'), agents: [
@@ -2356,24 +2350,11 @@ describe('desktop mini v2 interaction contract', () => {
await waitFor(() => expect(document.querySelector('.pet-mini-collapsed')).not.toBeNull());
await showCards();
await waitFor(() => expect(document.querySelector('.pet-mini-scroll')).not.toBeNull());
- const { petBridge } = await import('./petBridge');
- vi.spyOn(petBridge, 'open').mockResolvedValue();
- const panel = vi.spyOn(petBridge, 'setExpanded');
const avatar = screen.getByLabelText('pet.recentTurns');
- vi.useFakeTimers({ shouldAdvanceTime: true });
- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
- await user.dblClick(avatar);
- expect(document.querySelector('.pet-mini-scroll')).not.toBeNull();
- expect(panel).not.toHaveBeenCalled();
- await act(async () => vi.advanceTimersByTime(1000));
- expect(document.querySelector('.pet-mini-scroll')).not.toBeNull();
- expect(panel).not.toHaveBeenCalled();
- expect(historyIsOpen()).toBe(false);
- await user.click(avatar);
- expect(document.querySelector('.pet-mini-scroll')).not.toBeNull();
- await act(async () => vi.advanceTimersByTime(450));
+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 1 });
+ fireEvent.pointerUp(avatar, { pointerId: 1 });
expect(document.querySelector('.pet-mini-scroll')).toBeNull();
- expect(historyIsOpen()).toBe(false);
+ await waitFor(() => expect(historyIsOpen()).toBe(true));
});
});
@@ -2400,6 +2381,7 @@ describe('Personal Agent mini', () => {
await waitFor(() => expect(pose()).toBe('needs_input'));
expect(Array.from(document.querySelectorAll('.pet-mini-card'), (node) => node.getAttribute('data-session-id'))).toEqual(['approval', 'running', 'reply']);
expect(document.querySelector('.pet-mini-card.is-main')).toBeNull();
+ expect(document.querySelector('[data-session-id="reply"] .pet-mini-unread-dot')).not.toBeNull();
expect(api.getVaultRequests).not.toHaveBeenCalledWith(expect.objectContaining({ session: 'hidden' }), expect.anything());
api.getVaultRequests.mockResolvedValue({ requests: [] });
await emit((h) => h.onVaultsUpdated?.({}));
@@ -2409,11 +2391,12 @@ describe('Personal Agent mini', () => {
it('keeps unread Inbox replies after their process ends and rechecks visibility', async () => {
canUseAgents = true;
- inboxSessions = [{ session_id: 'reply', unread: true, project_name: 'Project' } as InboxSession];
+ inboxSessions = [{ session_id: 'reply', unread: true, project_name: 'Project', preview_text: '**Latest reply**' } as InboxSession];
unreadBySession = { reply: 1 };
mainSession('S'); render(<PetPage />); await showDetail();
await waitFor(() => expect(document.querySelector('[data-session-id="reply"]')).not.toBeNull());
- expect(screen.getByText('pet.replied')).toBeTruthy();
+ expect(screen.getByText('Latest reply')).toBeTruthy();
+ expect(screen.queryByText('pet.replied')).toBeNull();
expect(pose()).toBe('ready');
sessionReads.reply = async () => ({ status: 200, session: session('reply', { visibility: 'background' }) });
await emit((h) => h.onSessionActivity?.({ session_id: 'reply', scope_id: null, event: 'visibility', visibility: 'background' }));
@@ -2565,8 +2548,7 @@ describe('Personal Agent review: history and lifecycle', () => {
} finally { vi.useRealTimers(); }
});
- it('draws a promoted result after the input it answered and before a later input answered by silence', async () => {
- // Scenario: MESSAGE-DELIVERY-325.
+ it('shows only the latest assistant reply in the expanded card', async () => {
tails.S = [
message('ask', 'S', { author: 'user', type: 'user', text: 'Check CI' }),
message('report', 'S', { text: 'CI is green', read_at: null, metadata: { promoted_from: 'output' } }),
@@ -2574,12 +2556,13 @@ describe('Personal Agent review: history and lifecycle', () => {
];
render(<PetPage />); await showDetail();
const text = document.querySelector('.pet-mini-detail')?.textContent ?? '';
- expect(text.indexOf('Check CI')).toBeGreaterThanOrEqual(0);
- expect(text.indexOf('Check CI')).toBeLessThan(text.indexOf('CI is green'));
- expect(text.indexOf('CI is green')).toBeLessThan(text.indexOf('Also the docs'));
+ expect(text).toContain('CI is green');
+ expect(text).not.toContain('See #<result-ref>');
+ expect(text).not.toContain('Check CI');
+ expect(text).not.toContain('Also the docs');
});
- it('renders reference sidecars in current and historical Markdown', async () => {
+ it('renders reference sidecars for the latest reply', async () => {
const reference = (id: string, title: string) => ({ references: [{ kind: 'session', session_id: id, title }] });
tails.S = [
message('old-user', 'S', { author: 'user', type: 'user', text: 'Read #<older>', content: reference('older', '旧项目') }),
@@ -2589,7 +2572,10 @@ describe('Personal Agent review: history and lifecycle', () => {
];
render(<PetPage />); await showDetail();
const detail = within(document.querySelector('.pet-mini-detail') as HTMLElement);
- for (const title of ['#旧项目', '#Old result', '#当前项目', '#Latest result']) expect(detail.getByText(title)).toBeTruthy();
+ expect(detail.getByText('#Latest result')).toBeTruthy();
+ expect(detail.queryByText('#旧项目')).toBeNull();
+ expect(detail.queryByText('#Old result')).toBeNull();
+ expect(detail.queryByText('#当前项目')).toBeNull();
expect(document.querySelector('.pet-mini-detail')?.textContent).not.toMatch(/#</);
});
@@ -2896,7 +2882,7 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
];
mainSession('S');
render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Done already'));
+ await screen.findByLabelText('pet.recentTurns');
expect(bubbleOpen()).toBe(false);
});
@@ -2938,7 +2924,7 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
it('is content-sized while thinking, full width for the reply and whenever the history is open', async () => {
const compact = () => document.querySelector('.pet-mini-reply-bubble')!.classList.contains('is-compact');
tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' })];
- let running = true;
+ const running = true;
api.getTurnState.mockImplementation(async () => (running ? { ...idleTurn, in_flight: true, foreground: 'running' as const } : idleTurn));
mainSession('S');
render(<PetPage />);
@@ -2950,49 +2936,71 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
expect(compact()).toBe(false);
fireEvent.click(document.querySelector('.pet-mini-reply-toggle')!);
await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull());
- expect(compact()).toBe(true);
- const result = message('r', 'S', { text: 'All done', read_at: null });
- tails.S = [...tails.S, result];
- running = false;
- await emit((h) => {
- h.onMessageNew?.(result);
- h.onTurnEnd?.({ session_id: 'S' });
- });
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-toggle')?.textContent).toContain('pet.repliedPrefix'));
- expect(compact()).toBe(false);
- expect(bubbleOpen()).toBe(true);
+ expect(screen.getByLabelText('pet.inputPlaceholder')).toBeTruthy();
+ expect(document.querySelector('.pet-mini-reply-bubble')).toBeNull();
+ });
+
+ it('shows a plain text collapsed reply without the old prefix', async () => {
+ await runToResult('**Bold** and [a link](https://example.com)\nOpen `~/.avibe/config.json` and run `my_script.py`.\n2 < 3 && 5 > 4\n```ts\nconst answer = 1\n```');
+ const summary = document.querySelector('.pet-mini-reply-summary')!;
+ expect(summary.textContent).toContain('Bold and a link');
+ expect(summary.textContent).toContain('~/.avibe/config.json');
+ expect(summary.textContent).toContain('my_script.py');
+ expect(summary.textContent).toContain('2 < 3 && 5 > 4');
+ expect(summary.textContent).toContain('const answer = 1');
+ expect(summary.textContent).not.toContain('**');
+ expect(summary.textContent).not.toContain('```');
+ expect(summary.classList.contains('pet-mini-reply-summary')).toBe(true);
+ });
+
+ it('leaves an unread dot when an untouched reply times out, then clears it on expansion', async () => {
+ await runToResult();
+ await act(async () => { vi.advanceTimersByTime(20_100); });
+ await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')).toBeNull());
+ expect(document.querySelector('.pet-mini-avatar-unread-dot')).not.toBeNull();
+ fireEvent.click(screen.getByLabelText('pet.recentTurns'));
+ await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).not.toBeNull());
+ expect(document.querySelector('.pet-mini-avatar-unread-dot')).toBeNull();
+ });
+
+ it('clears the unread dot when another window marks the last reply read', async () => {
+ await runToResult();
+ await act(async () => { vi.advanceTimersByTime(20_100); });
+ await waitFor(() => expect(document.querySelector('.pet-mini-avatar-unread-dot')).not.toBeNull());
+
+ const read = message('r', 'S', { text: 'All done', read_at: '2026-10-04T00:00:02Z' });
+ tails.S = [
+ message('u', 'S', { author: 'user', type: 'user', text: 'hello' }),
+ read,
+ ];
+ await emit((h) => h.onMessageUpdated?.(read));
+
+ await waitFor(() => expect(document.querySelector('.pet-mini-avatar-unread-dot')).toBeNull());
});
it('a double-click leaves the lingering reply unseen and on its original timer', async () => {
await runToResult();
const { petBridge } = await import('./petBridge');
const opens = vi.spyOn(petBridge, 'open').mockResolvedValue();
- const panel = vi.spyOn(petBridge, 'setExpanded');
await userEvent.dblClick(screen.getByLabelText('pet.recentTurns'));
expect(opens).toHaveBeenCalledExactlyOnceWith('avibe://session/S');
- expect(panel).not.toHaveBeenCalled();
- expect(markRead).not.toHaveBeenCalled();
- expect(bubbleOpen()).toBe(true);
- await act(async () => vi.advanceTimersByTime(1000));
expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull();
- expect(bubbleOpen()).toBe(true);
- await act(async () => vi.advanceTimersByTime(9500));
expect(bubbleOpen()).toBe(false);
});
- it('keeps the bubble open from running to its result, then shows the reply for 10s', async () => {
+ it('keeps the bubble open from running to its result, then shows the reply for 20s', 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); });
+ act(() => { vi.advanceTimersByTime(19_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 () => {
+ it('spends nothing while the turn still reads as running, so a late turn end still gets the full 20s', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'], shouldAdvanceTime: true });
tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' })];
let running = true;
@@ -3009,7 +3017,7 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
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); });
+ act(() => { vi.advanceTimersByTime(19_800); });
expect(bubbleOpen()).toBe(true);
act(() => { vi.advanceTimersByTime(400); });
expect(bubbleOpen()).toBe(false);
@@ -3020,10 +3028,10 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
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 screen.findByLabelText('pet.recentTurns');
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);
+ expect(document.querySelector('.pet-mini-reply-bubble')).toBeNull();
});
it('hands keyboard focus to Vibey when a loading notice replaces the bubble', async () => {
@@ -3139,16 +3147,13 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
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'));
+ // Close the composer left by the first click. The reply was seen while
+ // the history was open, so it should not start a new linger.
+ await userEvent.keyboard('{Escape}');
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);
});
@@ -3162,7 +3167,7 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
tails.S = [...tails.S, late];
await emit((h) => h.onMessageNew?.(late));
await waitFor(() => expect(bubbleOpen()).toBe(true));
- act(() => { vi.advanceTimersByTime(9_800); });
+ act(() => { vi.advanceTimersByTime(19_800); });
expect(bubbleOpen()).toBe(true);
act(() => { vi.advanceTimersByTime(400); });
expect(bubbleOpen()).toBe(false);
@@ -3183,13 +3188,14 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
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.
+ // Not yet confirmed: the reply still holds the bubble. The expanded
+ // card also opens the keyboard composer, so focus moves into it.
expect(bubbleOpen()).toBe(true);
- expect(document.activeElement).toBe(toggle);
+ expect(document.activeElement).toBe(screen.getByLabelText('pet.inputPlaceholder'));
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); });
+ act(() => { vi.advanceTimersByTime(20_200); });
expect(bubbleOpen()).toBe(false);
} finally {
Reflect.deleteProperty(window, '__AVIBE_DESKTOP_SHELL__');
@@ -3275,10 +3281,12 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
summon('listen');
await screen.findByLabelText('pet.inputPlaceholder');
act(() => { vi.advanceTimersByTime(60_000); });
+ expect(screen.getByLabelText('pet.inputPlaceholder')).toBeTruthy();
+ expect(bubbleOpen()).toBe(false);
act(() => { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); });
expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
expect(bubbleOpen()).toBe(true);
- act(() => { vi.advanceTimersByTime(5_900); });
+ act(() => { vi.advanceTimersByTime(15_900); });
expect(bubbleOpen()).toBe(true);
act(() => { vi.advanceTimersByTime(200); });
expect(bubbleOpen()).toBe(false);
@@ -3291,7 +3299,7 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
act(() => { vi.advanceTimersByTime(60_000); });
expect(bubbleOpen()).toBe(true);
fireEvent.pointerLeave(bubbleWrap());
- act(() => { vi.advanceTimersByTime(2_900); });
+ act(() => { vi.advanceTimersByTime(10_900); });
expect(bubbleOpen()).toBe(true);
act(() => { vi.advanceTimersByTime(200); });
expect(bubbleOpen()).toBe(false);
@@ -3307,7 +3315,7 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
act(() => { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); });
expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
expect(bubbleOpen()).toBe(true);
- act(() => { vi.advanceTimersByTime(5_900); });
+ act(() => { vi.advanceTimersByTime(15_900); });
expect(bubbleOpen()).toBe(true);
act(() => { vi.advanceTimersByTime(200); });
expect(bubbleOpen()).toBe(false);
@@ -3354,7 +3362,7 @@ describe('Vibey bubble visibility (spec §4.2)', () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' }), message('r', 'S', { text: 'Old reply' })];
mainSession('S');
render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
expect(bubbleOpen()).toBe(false);
await userEvent.click(screen.getByLabelText('pet.recentTurns'));
await waitFor(() => expect(bubbleOpen()).toBe(true));
@@ -3402,7 +3410,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
const invoke = recording((command) => command === 'pet_ready' ? ready(top, 4) : { revision: 4, layout: top });
shell(invoke);
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
await waitFor(() => expect(edge()).toBe('top'));
await waitFor(() => expect(settles(invoke)).toContainEqual([4, 'top']));
expect(invoke).toHaveBeenCalledWith('pet_ready', { layouts: true });
@@ -3412,7 +3420,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
const readyAnswer = deferred<unknown>();
shell(vi.fn((command: string) => command === 'pet_ready' ? readyAnswer.promise : Promise.resolve({ revision: 2, layout: top })));
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
const pending = () => document.querySelector('.pet-mini-stage')?.hasAttribute('data-layout-pending');
expect(pending()).toBe(true);
await act(async () => readyAnswer.resolve(ready(top, 2)));
@@ -3447,7 +3455,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
});
shell(invoke);
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
const pending = () => document.querySelector('.pet-mini-stage')?.hasAttribute('data-layout-pending');
const called = (name: string) => invoke.mock.calls.filter(([command]) => command === name).length;
await waitFor(() => expect(pending()).toBe(false));
@@ -3466,7 +3474,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
const invoke = recording((command, args) => command === 'pet_ready' ? ready() : { revision: args?.revision ?? 1, layout: top });
shell(invoke);
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
await waitFor(() => expect(settles(invoke)).toContainEqual([1, 'bottom']));
await publish(3, top);
await waitFor(() => expect(settles(invoke)).toContainEqual([3, 'top']));
@@ -3482,7 +3490,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
const invoke = recording((command, args) => command === 'pet_ready' ? readyAnswer.promise : { revision: args?.revision ?? 3, layout: top });
shell(invoke);
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
// The shell published revision 3 while it still took this document for loading.
await publish(3, top);
await waitFor(() => expect(settles(invoke)).toEqual([[3, 'top']]));
@@ -3494,7 +3502,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
const invoke = recording((command) => command === 'pet_ready' ? ready() : { revision: 5, layout: top });
shell(invoke);
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
await waitFor(() => expect(settles(invoke)).toContainEqual([5, 'top']));
expect(edge()).toBe('top');
});
@@ -3508,7 +3516,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
});
shell(invoke);
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
const called = (name: string) => invoke.mock.calls.filter(([command]) => command === name).length;
// The shell does not yet know this page draws the top layout.
drag(screen.getByLabelText('pet.recentTurns'));
@@ -3530,7 +3538,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
: bottom);
shell(invoke, false);
mainSession('S'); render(<PetPage />);
- await screen.findByText('Session S');
+ await screen.findByLabelText('pet.recentTurns');
drag(screen.getByLabelText('pet.recentTurns'));
await waitFor(() => expect(invoke).toHaveBeenCalledWith('plugin:window|start_dragging'));
expect(invoke.mock.calls.some(([command]) => command === 'pet_drag' || command === 'pet_settle')).toBe(false);
@@ -3546,7 +3554,7 @@ describe('dragging the pet to the top of the display (spec §9.1)', () => {
shell(invoke);
tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' }), message('r', 'S', { text: 'Old reply' })];
mainSession('S'); render(<PetPage />);
- await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));
+ await screen.findByLabelText('pet.recentTurns');
await userEvent.click(screen.getByLabelText('pet.recentTurns'));
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsx
index 2666bd5f8..0aa9946c0 100644
--- a/ui/src/pet/PetPage.tsx
+++ b/ui/src/pet/PetPage.tsx
@@ -7,11 +7,14 @@ import { ApiError, useApi, type InboxSession, type RunningAgent, type VaultReque
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { useWorkbenchInbox } from '@/context/WorkbenchInboxContext';
import { Button } from '@/components/ui/button';
+import { ChatImage } from '@/components/ui/chat-image';
+import { FileCard } from '@/components/ui/file-card';
import { Markdown } from '@/components/ui/markdown';
import { QuickReplies } from '@/components/workbench/QuickReplies';
import { isComposingKey } from '@/lib/imeComposition';
import { useDocumentVisible, usePageActive } from '@/lib/pageActivity';
import { isDetachedCompletionMessage } from '@/lib/chatMessageTypes';
+import { readMessageAttachments } from '@/lib/messageAttachments';
import { usePendingVaultRequests } from '@/lib/usePendingVaultRequests';
import { useVaultRequestRefresh } from '@/lib/useVaultRequestRefresh';
import { vaultRequestType } from '@/lib/vaultRequestPlacement';
@@ -35,7 +38,7 @@ import { FencedSource } from './fencedSource';
import './pet-mini.css';
const HOLD_MS = 320;
-const DOUBLE_CLICK_MS = 450;
+const DOUBLE_CLICK_DETECTION_MS = 450;
const DISMISS_EXIT_MS = 500;
const STOP_CONFIRM_MS = 3000;
const STOP_LINGER_MS = 2500;
@@ -77,9 +80,41 @@ type CardPresentation = { phase?: StopPhase; leaving?: boolean; retained?: PetCa
const isRunning = (agent: RunningAgent) => agent.state === 'active';
+/** Make an agent reply readable when it is shown inside a compact card. */
+const collapseMarkdownToPlainText = (text: string): string => {
+ const code: string[] = [];
+ let nextCode = 0;
+ const protectCode = (): string => `@@PETCODE${nextCode++}@@`;
+ const plain = text
+ .replace(/```[^\n]*\n([\s\S]*?)\n?```|~~~[^\n]*\n([\s\S]*?)\n?~~~/g, (_match, fencedBacktick: string, fencedTilde: string) => {
+ const value = fencedBacktick ?? fencedTilde ?? '';
+ code.push(value);
+ return protectCode();
+ })
+ .replace(/`([^`\n]+)`/g, (_match, value: string) => {
+ code.push(value);
+ return protectCode();
+ })
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
+ .replace(/(^|\n)\s{0,3}(?:#{1,6}|>|[-*+]|\d+\.)[ \t]+/g, '$1')
+ .replace(/~~([^~\n]+)~~/g, '$1')
+ .replace(/\*\*\*([^*\n]+)\*\*\*/g, '$1')
+ .replace(/___([^_\n]+)___/g, '$1')
+ .replace(/\*\*([^*\n]+)\*\*/g, '$1')
+ .replace(/__([^_\n]+)__/g, '$1')
+ .replace(/(?<!\w)\*([^*\n]+)\*(?!\w)/g, '$1')
+ .replace(/(?<!\w)_([^_\n]+)_(?!\w)/g, '$1')
+ .replace(/<!--[\s\S]*?-->|<\/?[a-z][a-z0-9-]*(?:\s+[^<>]*?)?\/?>/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return plain.replace(/@@PETCODE(\d+)@@/g, (_match, index: string) => code[Number(index)] ?? '');
+};
+
function agentCard(
agent: RunningAgent,
unreadBySession: Record<string, number>,
+ previewBySession: Record<string, string>,
vaultRequests: VaultRequest[],
stoppable: string[],
fallback: string,
@@ -93,13 +128,14 @@ function agentCard(
const needsInput = vaultRequests.some((request) => request.session?.id === agent.session_id);
const hasUnread = (unreadBySession[agent.session_id] ?? 0) > 0;
const running = isRunning(agent);
+ const preview = collapseMarkdownToPlainText(previewBySession[agent.session_id] ?? '');
const status = needsInput
? t('pet.needsAuthorization')
: running
? t('pet.activityStatus.running')
: hasUnread
- ? t('pet.replied')
- : t('pet.activityStatus.waiting');
+ ? preview
+ : '';
return {
id: agent.session_id,
sessionId: agent.session_id,
@@ -249,6 +285,10 @@ const PetSurface: React.FC = () => {
const quickReplies = openQuickReplies(data.messages);
const runningAgents = useConversationAgentSnapshot(capabilities.can_use_agents === true);
const { rows: repliedAgents, pending: repliesPending } = usePetReplyActivities(capabilities.can_use_agents === true, epoch, inbox.inboxSessions ?? EMPTY_INBOX);
+ const previewBySession = useMemo(
+ () => Object.fromEntries((inbox.inboxSessions ?? []).map((row) => [row.session_id, row.preview_text ?? ''])),
+ [inbox.inboxSessions],
+ );
const activitySnapshotReady = inbox.unreadLoaded === true && !inbox.loading && runningAgents.ok && !repliesPending;
const visibleAgentRows = useMemo(() => (
[...(runningAgents.ok ? runningAgents.agents : []), ...repliedAgents].filter((agent) => (
@@ -270,16 +310,12 @@ const PetSurface: React.FC = () => {
const openCards = useCallback(() => {
setDetailOpen(false);
void setPanel(true);
- }, [setPanel]);
- // A Vibey click (§5.1) is about Vibey's own conversation: it collapses an
- // expanded card list, else closes an open history, else opens the history.
- // The collapsed stack is the only way to expand the cards (§3.3). Every
- // branch leaves the shell's panel state matching what is drawn. Typing and
- // dictation stay as they are: the history opens above the input.
+ }, [setDetailOpen, setPanel]);
+ // A Vibey click (§5.1) opens the main card immediately, closes it when it is
+ // already open, and folds the other cards as part of opening.
const toggleVibey = () => {
- if (cardsListed) { void setPanel(false); return; }
if (historyOpen) { setDetailOpen(false); void setPanel(false); return; }
- if (!binding || resolvingMain || (data.messages.length === 0 && !optimisticTitle)) return;
+ if (!binding || resolvingMain) return;
openHistory();
};
const [composing, setComposing] = useState(false);
@@ -301,9 +337,11 @@ const PetSurface: React.FC = () => {
const inputRef = useRef<HTMLTextAreaElement>(null);
const avatarRef = useRef<HTMLButtonElement>(null);
// Pair native mousedown click counts with time for webviews that always report 1.
- // No history/card side effects occur until a pointer single click is confirmed.
+ // A normal pointer click is handled on its pointer-up; this ref only decides
+ // whether that click is also the second half of a double-click.
const pressRef = useRef<{ held: boolean; dragged: boolean; clicks: number; double: boolean; x: number; y: number; timer: number } | null>(null);
- const pendingClickRef = useRef<{ at: number; timer: number } | null>(null);
+ const lastClickAtRef = useRef(0);
+ const composerBeforeClickRef = useRef(false);
const doubleOpenedRef = useRef(false);
const allowDoubleEventRef = useRef(false);
const dismissTimers = useRef<Record<string, number>>({});
@@ -350,11 +388,10 @@ const PetSurface: React.FC = () => {
Object.values(stopTimers.current).forEach(window.clearTimeout);
Object.values(dismissTimers.current).forEach(window.clearTimeout);
if (pressRef.current) window.clearTimeout(pressRef.current.timer);
- if (pendingClickRef.current) window.clearTimeout(pendingClickRef.current.timer);
stopTimers.current = {};
dismissTimers.current = {};
pressRef.current = null;
- pendingClickRef.current = null;
+ lastClickAtRef.current = 0;
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
};
@@ -381,13 +418,6 @@ const PetSurface: React.FC = () => {
setHovered(next);
}, []);
useEffect(() => onPetHover(handlePetHover), [handlePetHover]);
- const cancelPendingClick = useCallback(() => {
- const pending = pendingClickRef.current;
- if (!pending) return;
- window.clearTimeout(pending.timer);
- pendingClickRef.current = null;
- }, []);
-
useEffect(() => {
if (exchange.user?.text?.trim() === optimisticTitle) setOptimisticTitle('');
}, [exchange.user, optimisticTitle]);
@@ -402,6 +432,7 @@ const PetSurface: React.FC = () => {
return [...bySession.values()].map((agent) => agentCard(
agent,
inbox.unreadBySession,
+ previewBySession,
visibleVaultRequests,
stoppable,
t('pet.untitledTask'),
@@ -411,6 +442,7 @@ const PetSurface: React.FC = () => {
.map((card) => ({ ...card, id: `${card.sessionId}:${generations[card.sessionId] ?? 0}` }));
}, [
inbox.unreadBySession,
+ previewBySession,
t,
visibleAgentRows,
visibleVaultRequests,
@@ -489,14 +521,14 @@ const PetSurface: React.FC = () => {
const closeComposer = useCallback(() => {
setComposing(false);
setDraft('');
- }, [setDraft]);
+ }, [setComposing, setDraft]);
// An open history stays open: the input takes its place below it (§5.2).
const openComposer = useCallback((text = '', selected?: SessionReference[]) => {
if (!epoch.isCurrent()) return;
setDraft(text, selected);
setComposing(true);
window.setTimeout(() => { if (epoch.isCurrent()) inputRef.current?.focus(); }, 0);
- }, [setDraft, epoch]);
+ }, [epoch, setComposing, setDraft]);
const send = useCallback(async (text: string, metadata?: Record<string, unknown>) => {
if (!epoch.isCurrent() || !text.trim() || !binding || !canChat || data.session?.id !== binding) return false;
@@ -531,7 +563,7 @@ const PetSurface: React.FC = () => {
// Release this request's document-wide lock, not a new surface's state.
petComposer.setSending(false);
}
- }, [api, binding, canChat, data, setPanel, setUncertain, epoch, draftReferences]);
+ }, [api, binding, canChat, data, draftReferences, epoch, setComposing, setDetailOpen, setPanel, setUncertain]);
const submit = async () => {
const submitted = draft;
if (!(await send(submitted)) || !epoch.isCurrent()) return;
@@ -635,8 +667,8 @@ const PetSurface: React.FC = () => {
}, [listenPending, binding, canChat, expanded, voice.available, voice.start, openComposer, draft, uncertain, resetVoiceShortcut]);
const dockActiveRef = useRef(false);
useLayoutEffect(() => { dockActiveRef.current = voice.busy || composing; }, [voice.busy, composing]);
- const suppressDock = useCallback(() => {
- if (dockActiveRef.current) return;
+ const suppressDock = useCallback((force = false) => {
+ if (!force && dockActiveRef.current) return;
// The shell emits transitions only; an already-outside pointer can enter next.
hoverSuppressedRef.current = shellHoveredRef.current;
setHoverSuppressed(true);
@@ -645,8 +677,7 @@ const PetSurface: React.FC = () => {
}, []);
useEffect(() => {
const onBlur = () => {
- cancelPendingClick();
- suppressDock();
+ suppressDock(doubleOpenedRef.current && !composerBeforeClickRef.current && !draft.trim() && !voice.busy);
if (!voice.busy) resetVoiceShortcut();
// Opening Avibe must preserve the history/card list through its key change.
if (!doubleOpenedRef.current && !voice.busy && !draft.trim()) void setPanel(false);
@@ -658,7 +689,7 @@ const PetSurface: React.FC = () => {
window.removeEventListener('blur', onBlur);
window.removeEventListener('focus', onFocus);
};
- }, [cancelPendingClick, draft, setPanel, suppressDock, voice.busy, resetVoiceShortcut]);
+ }, [draft, setPanel, suppressDock, voice.busy, resetVoiceShortcut]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
// Escape also dismisses an IME candidate list; that one is not ours.
@@ -777,7 +808,15 @@ const PetSurface: React.FC = () => {
// The bubble is drawn: the speech slot shows it, alone or, while its history
// is open or asked for, above the input or the marquee (§5.2). Every input
// to the linger (time, pointer) means something only while this holds.
- const bubbleDrawn = hasBubbleContent && Boolean(binding) && (!inputShown || detailOpen);
+ const noReplyDetail = historyOpen
+ && !data.running
+ && !failure
+ && exchange.results.length === 0
+ && !uncertain
+ && !queued
+ && vaultRequests.length === 0
+ && !quickReplies;
+ const bubbleDrawn = hasBubbleContent && Boolean(binding) && (!inputShown || detailOpen) && !noReplyDetail;
// 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.
@@ -800,13 +839,26 @@ const PetSurface: React.FC = () => {
const { lingeringId, keepAtLeast } = useReplyLinger({
scope: epoch,
candidateId: lingerReply?.id ?? null,
- counting: documentVisible && replyOnScreen && !pointerOverBubble && !historyPending,
+ counting: documentVisible && replyOnScreen && !pointerOverBubble && !historyPending && !historyOpen && !inputShown,
keyboardHeld: () => {
const node = bubbleRef.current;
const active = document.activeElement;
return Boolean(node && active && node.contains(active) && active.matches(':focus-visible'));
},
});
+ const replyNeedsUnreadDot = Boolean(
+ turnReply
+ && turnReply.read_at === null
+ && !watched.seen.has(turnReply.id)
+ && lingeringId === null,
+ );
+ const [replyUnreadDotClearedFor, setReplyUnreadDotClearedFor] = useState<string | null>(null);
+ const replyUnreadDot = Boolean(
+ !historyOpen
+ && turnReply
+ && replyNeedsUnreadDot
+ && replyUnreadDotClearedFor !== turnReply.id,
+ );
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
@@ -815,10 +867,16 @@ const PetSurface: React.FC = () => {
// Looking at the history is looking at the reply (`seen` above): once it
// closes, the reply does not linger again.
function openHistory() {
+ if (turnReply) setReplyUnreadDotClearedFor(turnReply.id);
setDetailOpen(true);
+ if (canChat && !uncertain && !voice.busy) openComposer(draft);
// 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); });
+ void setPanel(true).then(() => {
+ if (!epoch.isCurrent() || petPanel.current()) return;
+ setDetailOpen(false);
+ if (!draft.trim()) setComposing(false);
+ });
}
const toggleHistory = () => {
if (detailOpen) { setDetailOpen(false); void setPanel(false); } else openHistory();
@@ -826,32 +884,23 @@ const PetSurface: React.FC = () => {
const openDoubleClick = () => {
if (doubleOpenedRef.current) return;
doubleOpenedRef.current = true;
- cancelPendingClick();
- if (!binding) return;
+ const preserveComposer = composerBeforeClickRef.current || Boolean(draft.trim()) || voice.busy;
+ if (!preserveComposer) setComposing(false);
+ if (turnReply) setReplyUnreadDotClearedFor(turnReply.id);
+ setDetailOpen(false);
+ void setPanel(false);
+ const lastUnread = exchange.results.at(-1);
+ if (binding && lastUnread?.read_at === null && exchange.unreadComplete) {
+ void inbox.markRead(binding, lastUnread.id);
+ }
+ if (!binding) {
+ suppressDock(!preserveComposer);
+ return;
+ }
void petBridge.open(sessionLink(binding)).then(() => {
- if (epoch.isCurrent()) suppressDock();
+ if (epoch.isCurrent()) suppressDock(!preserveComposer);
}, () => undefined);
};
- const beginDoubleClick = (clicks: number) => {
- const pending = pendingClickRef.current;
- // A native count alone cannot pair a click with a previous hold or drag.
- if (!pending || (clicks !== 2 && performance.now() - pending.at > DOUBLE_CLICK_MS)) return false;
- cancelPendingClick();
- return true;
- };
- const toggleVibeyRef = useRef(toggleVibey);
- useLayoutEffect(() => { toggleVibeyRef.current = toggleVibey; });
- const scheduleSingleClick = () => {
- cancelPendingClick();
- const at = performance.now();
- const timer = window.setTimeout(() => {
- if (pendingClickRef.current?.timer !== timer || !epoch.isCurrent()) return;
- pendingClickRef.current = null;
- allowDoubleEventRef.current = false;
- toggleVibeyRef.current();
- }, DOUBLE_CLICK_MS);
- pendingClickRef.current = { at, timer };
- };
useLayoutEffect(() => {
// Focus inside a bubble that folds away (still mounted) moves to Vibey too.
if (showReplyBubble) return;
@@ -877,7 +926,6 @@ const PetSurface: React.FC = () => {
data-pet-hit
onClick={(event) => {
if (event.detail !== 0) return;
- cancelPendingClick();
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
toggleVibey();
@@ -891,11 +939,16 @@ const PetSurface: React.FC = () => {
const pointerId = event.pointerId;
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
+ const now = performance.now();
+ const hasRecentEligibleClick = lastClickAtRef.current > 0
+ && now - lastClickAtRef.current <= DOUBLE_CLICK_DETECTION_MS;
+ const isSecondClick = hasRecentEligibleClick;
+ if (!isSecondClick) composerBeforeClickRef.current = composing || voice.busy || Boolean(draft.trim());
pressRef.current = {
held: false,
dragged: false,
clicks: event.detail || 1,
- double: beginDoubleClick(event.detail),
+ double: isSecondClick,
x: event.clientX,
y: event.clientY,
timer: window.setTimeout(() => {
@@ -903,7 +956,7 @@ const PetSurface: React.FC = () => {
const press = pressRef.current;
if (!press) return;
press.held = true;
- cancelPendingClick();
+ lastClickAtRef.current = 0;
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
target.setPointerCapture?.(pointerId);
@@ -918,7 +971,15 @@ const PetSurface: React.FC = () => {
const press = pressRef.current;
if (press) {
press.clicks = event.detail;
- if (!press.double && beginDoubleClick(event.detail)) press.double = true;
+ const now = performance.now();
+ if (
+ !press.double
+ && event.detail >= 2
+ && lastClickAtRef.current > 0
+ && now - lastClickAtRef.current <= DOUBLE_CLICK_DETECTION_MS
+ ) {
+ press.double = true;
+ }
}
// The input keeps its focus and caret: a Vibey click is not leaving it.
if (inputRef.current && document.activeElement === inputRef.current) event.preventDefault();
@@ -929,7 +990,7 @@ const PetSurface: React.FC = () => {
if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) return;
press.dragged = true;
window.clearTimeout(press.timer);
- cancelPendingClick();
+ lastClickAtRef.current = 0;
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
// The drop's layout arrives as the shell's snapshot (petShell).
@@ -939,7 +1000,7 @@ const PetSurface: React.FC = () => {
const press = pressRef.current;
pressRef.current = null;
if (press) window.clearTimeout(press.timer);
- cancelPendingClick();
+ lastClickAtRef.current = 0;
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
if (press?.held) voice.stop(true);
@@ -954,14 +1015,17 @@ const PetSurface: React.FC = () => {
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
} else if (press.dragged || press.clicks > 2) {
- cancelPendingClick();
+ lastClickAtRef.current = 0;
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
} else if (press.double) {
+ lastClickAtRef.current = 0;
allowDoubleEventRef.current = true;
+ toggleVibey();
openDoubleClick();
} else {
- scheduleSingleClick();
+ lastClickAtRef.current = performance.now();
+ toggleVibey();
}
}}
onPointerLeave={() => {
@@ -969,14 +1033,20 @@ const PetSurface: React.FC = () => {
if (press && !press.held) {
window.clearTimeout(press.timer);
pressRef.current = null;
- cancelPendingClick();
+ lastClickAtRef.current = 0;
doubleOpenedRef.current = false;
allowDoubleEventRef.current = false;
}
}}
- onContextMenu={(event) => event.preventDefault()}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ void petBridge.contextMenu().catch(() => undefined);
+ }}
>
<PetAvatar pose={voice.listening ? 'listening' : pose} badge={unreadCount + cardUnread} />
+ {replyUnreadDot && unreadCount + cardUnread === 0 && (
+ <span className="pet-mini-unread-dot pet-mini-avatar-unread-dot" aria-label={t('pet.unreadBadge', { count: 1 })} />
+ )}
</button>
<MiniDock
enabled={canChat && Boolean(binding)}
@@ -1020,7 +1090,7 @@ const PetSurface: React.FC = () => {
</div>
</div>
<SpeechSlot open={voice.busy || composing || showReplyBubble || resolvingMain || !binding}>
- {bubbleDrawn && binding ? (
+ {bubbleDrawn && showReplyBubble && 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
@@ -1044,7 +1114,6 @@ const PetSurface: React.FC = () => {
canChat={canChat}
binding={binding}
exchange={exchange}
- messages={data.messages}
failure={data.running ? null : failure}
running={data.running}
queued={(data.turn?.pending_input_count ?? 0) > 0}
@@ -1430,6 +1499,7 @@ const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, op
const subtitle = phase === 'stopping' ? t('pet.stop.stopping') : phase === 'stopped' ? t('pet.stop.stopped') : phase === 'failed' ? t('pet.stop.failed') : card.status;
const stopText = phase === 'confirm' ? t('pet.stop.confirmStop') : t('pet.stop.stop', { title: card.title });
const Reference = expanded ? 'button' : 'span';
+ const unread = card.hasUnread && !card.running && !card.needsInput;
return (
<article className={clsx('pet-mini-card', card.needsInput && 'is-needs-input')} title={card.title} data-session-id={card.sessionId} data-pet-hit>
{expanded && <button type="button" className="pet-mini-dismiss" data-pet-hit onClick={onDismiss} aria-label={t('pet.dismiss')}><svg viewBox="0 0 16 16" aria-hidden><path d="m4 4 8 8M12 4 4 12" /></svg></button>}
@@ -1442,7 +1512,8 @@ const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, op
<div className={clsx('pet-mini-subtitle', phase === 'stopped' && 'is-stopped')} title={subtitle}>
{running && <span className="pet-mini-running-dot" aria-hidden />}
{phase === 'stopped' && <span className="pet-mini-stopped-dot" aria-hidden />}
- <span>{subtitle}</span>
+ {unread && <span className="pet-mini-unread-dot" aria-hidden />}
+ {subtitle && <span>{subtitle}</span>}
</div>
</Reference>
{expanded && (
@@ -1461,7 +1532,33 @@ const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, op
);
};
-type 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 };
+type MainDetailProps = { epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; canChat: boolean; visible: boolean; binding: string; exchange: ReturnType<typeof latestExchange>; 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 MessageContent: React.FC<{ message: WorkbenchMessage }> = ({ message }) => {
+ const { t } = useTranslation();
+ const attachments = readMessageAttachments(message.content);
+ return (
+ <>
+ <Markdown
+ content={message.text}
+ references={(message.content as { references?: MentionReference[] })?.references}
+ softBreaks
+ />
+ {attachments.length > 0 && (
+ <div className="pet-mini-message-attachments">
+ {attachments.map((attachment, index) => {
+ if (!attachment.url) return null;
+ return attachment.image ? (
+ <ChatImage key={index} src={attachment.url} alt={attachment.name} width={attachment.width} height={attachment.height} />
+ ) : (
+ <FileCard key={index} href={attachment.url}>{attachment.name || t('pet.fileAttachment')}</FileCard>
+ );
+ })}
+ </div>
+ )}
+ </>
+ );
+};
/**
* Animates a box between two widths CSS cannot interpolate (its content's width
@@ -1522,7 +1619,7 @@ const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boole
const reply = last?.text?.trim() ?? '';
const summary = props.running ? t('pet.thinking')
: props.failure ? `${t('pet.failedPrefix')} ${props.failure.text.trim()}`
- : reply ? t('pet.repliedPrefix', { text: reply })
+ : reply ? collapseMarkdownToPlainText(reply)
: t('pet.waiting');
// A status word alone ("thinking", "waiting") sizes the bubble to its
// content (§4.2); a reply, a failure or the open history take the column.
@@ -1553,15 +1650,14 @@ const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boole
const MainDetail: React.FC<MainDetailProps> = (props) => {
const { t } = useTranslation();
- const lastResultRef = useRef<HTMLDivElement>(null);
const innerRef = useRef<HTMLDivElement>(null);
+ const lastResultRef = 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.
+ // who has scrolled up where they are.
useLayoutEffect(() => {
if (!props.visible) return undefined;
const inner = innerRef.current;
@@ -1587,11 +1683,10 @@ const MainDetail: React.FC<MainDetailProps> = (props) => {
history.removeEventListener('scroll', onScroll);
observer?.disconnect();
};
- }, [props.visible, props.exchange.user?.id]);
+ }, [props.visible, props.exchange.results.at(-1)?.id]);
useEffect(() => {
const node = lastResultRef.current;
- if (!props.visible || !node) return;
- if (typeof IntersectionObserver === 'undefined') return;
+ if (!props.visible || !node || typeof IntersectionObserver === 'undefined') return undefined;
const observer = new IntersectionObserver(([entry]) => {
if (props.epoch.isCurrent()) setSeenResult(entry.isIntersecting ? { epoch: props.epoch, key: resultKey } : null);
}, {
@@ -1600,24 +1695,20 @@ const MainDetail: React.FC<MainDetailProps> = (props) => {
observer.observe(node);
return () => observer.disconnect();
}, [props.visible, resultKey, props.epoch]);
- usePetMarkRead(props.epoch, props.binding, props.exchange, props.markRead, props.onRead, props.visible && (typeof IntersectionObserver === 'undefined' || (seenResult?.epoch === props.epoch && seenResult.key === resultKey)));
- const firstCurrent = props.messages.findIndex((message) => message.id === props.exchange.user?.id || props.exchange.results.some((result) => result.id === message.id));
- const history = props.messages.slice(0, Math.max(0, firstCurrent))
- .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>;
+ const resultVisible = props.visible && (typeof IntersectionObserver === 'undefined'
+ || (seenResult?.epoch === props.epoch && seenResult.key === resultKey));
+ usePetMarkRead(props.epoch, props.binding, props.exchange, props.markRead, props.onRead, resultVisible);
+ const lastResult = props.exchange.results.at(-1);
return (
<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>)}
- {props.exchange.answersEarlierInput && currentUser}
+ {props.running && <p className="pet-mini-detail-muted">{t('pet.thinking')}</p>}
+ {lastResult && <div ref={lastResultRef} className="pet-mini-detail-result"><MessageContent message={lastResult} /></div>}
{props.failure && (
<div className="pet-mini-detail-notice" role="status">
<p>{props.failure.text}</p>
{props.failure.metadata?.failure_next_step === 'models' && <Button variant="link" size="sm" className="px-0" onClick={() => void petBridge.open(sessionLink(props.binding))}>{t('pet.fixInAvibe')}</Button>}
</div>
)}
- {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>}
{/* The pinned Open in Avibe button is where the rest of the tail lives. */}
@@ -1636,7 +1727,7 @@ function usePetMarkRead(epoch: PetSurfaceEpoch, binding: string, exchange: Retur
const marker = useRef<string | null>(null);
useEffect(() => { marker.current = null; }, [epoch]);
useEffect(() => {
- if (!epoch.isCurrent() || !unreadId || !exchange.unreadComplete || !active || !visible) return;
+ if (!epoch.isCurrent() || !unreadId || exchange.results.length !== 1 || !exchange.unreadComplete || !active || !visible) return;
const key = `${binding}\u0000${unreadId}`;
if (marker.current === key) return;
marker.current = key;
@@ -1644,5 +1735,5 @@ function usePetMarkRead(epoch: PetSurfaceEpoch, binding: string, exchange: Retur
if (!epoch.isCurrent()) return;
if (applied) onRead(); else marker.current = null;
}, () => { if (epoch.isCurrent()) marker.current = null; });
- }, [active, binding, exchange.unreadComplete, markRead, onRead, unreadId, visible, epoch]);
+ }, [active, binding, exchange.results.length, exchange.unreadComplete, markRead, onRead, unreadId, visible, epoch]);
}
diff --git a/ui/src/pet/pet-mini.css b/ui/src/pet/pet-mini.css
index 64518100c..889d3a563 100644
--- a/ui/src/pet/pet-mini.css
+++ b/ui/src/pet/pet-mini.css
@@ -120,6 +120,21 @@
animation:pet-mini-pulse 2s cubic-bezier(.4,0,.6,1) infinite}
.pet-mini-stopped-dot {
background:color-mix(in srgb,var(--pet-ink) 40%,transparent)}
+.pet-mini-unread-dot {
+ width:5px;
+ height:5px;
+ flex:none;
+ border-radius:999px;
+ background:#34d399}
+.pet-mini-avatar-unread-dot {
+ position:absolute;
+ top:14px;
+ right:14px;
+ z-index:2;
+ width:8px;
+ height:8px;
+ border:2px solid var(--pet-card);
+ box-sizing:content-box}
@keyframes pet-mini-pulse {
50% {
@@ -864,15 +879,21 @@ to {
gap:6px;
margin-top:3px;
overflow:hidden;
- text-overflow:ellipsis;
- white-space:nowrap;
font-size:13px;
line-height:20px}
.pet-mini-reply-summary {
min-width:0;
overflow:hidden;
- text-overflow:ellipsis;
- white-space:nowrap}
+ display:-webkit-box;
+ -webkit-box-orient:vertical;
+ -webkit-line-clamp:3;
+ overflow:hidden;
+ word-break:break-word}
+.pet-mini-message-attachments {
+ display:flex;
+ flex-direction:column;
+ gap:8px;
+ margin-top:8px}
.pet-mini-bubble-history {
position:relative;
z-index:1;
diff --git a/ui/src/pet/petBridge.ts b/ui/src/pet/petBridge.ts
index 5b3615153..c67b21929 100644
--- a/ui/src/pet/petBridge.ts
+++ b/ui/src/pet/petBridge.ts
@@ -152,6 +152,13 @@ export const petBridge = {
await invoke('pet_reset_voice_shortcut');
},
+ /** Opens the native pet context menu inside the desktop shell. */
+ contextMenu: async (): Promise<void> => {
+ const invoke = shellInvoke();
+ if (!invoke) return;
+ await invoke('pet_context_menu');
+ },
+
/** Normalize the legacy binding; callers cannot choose another session. */
bindMain: async (): Promise<PetBinding> => {
const invoke = shellInvoke();
diff --git a/ui/src/pet/useReplyLinger.test.ts b/ui/src/pet/useReplyLinger.test.ts
new file mode 100644
index 000000000..0091107c6
--- /dev/null
+++ b/ui/src/pet/useReplyLinger.test.ts
@@ -0,0 +1,53 @@
+/* @vitest-environment jsdom */
+
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { REPLY_LINGER_MS, REPLY_LINGER_RESUME_MS, useReplyLinger } from './useReplyLinger';
+
+describe('useReplyLinger', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('keeps an untouched reply for 20 seconds', () => {
+ vi.useFakeTimers();
+ const scope = {};
+ const { result } = renderHook(() => useReplyLinger({
+ scope,
+ candidateId: 'reply-1',
+ counting: true,
+ keyboardHeld: () => false,
+ }));
+
+ act(() => { vi.advanceTimersByTime(REPLY_LINGER_MS - 1); });
+ expect(result.current.lingeringId).toBe('reply-1');
+ act(() => { vi.advanceTimersByTime(1); });
+ expect(result.current.lingeringId).toBeNull();
+ });
+
+ it('pauses the budget and restores at least three seconds after pointer leave', () => {
+ vi.useFakeTimers();
+ const scope = {};
+ let counting = true;
+ const { result, rerender } = renderHook(() => useReplyLinger({
+ scope,
+ candidateId: 'reply-1',
+ counting,
+ keyboardHeld: () => false,
+ }));
+
+ act(() => { vi.advanceTimersByTime(REPLY_LINGER_MS - 1_000); });
+ counting = false;
+ rerender();
+ act(() => { vi.advanceTimersByTime(REPLY_LINGER_MS); });
+ expect(result.current.lingeringId).toBe('reply-1');
+ act(() => { result.current.keepAtLeast(REPLY_LINGER_RESUME_MS); });
+ counting = true;
+ rerender();
+ act(() => { vi.advanceTimersByTime(REPLY_LINGER_RESUME_MS - 1); });
+ expect(result.current.lingeringId).toBe('reply-1');
+ act(() => { vi.advanceTimersByTime(1); });
+ expect(result.current.lingeringId).toBeNull();
+ });
+});
diff --git a/ui/src/pet/useReplyLinger.ts b/ui/src/pet/useReplyLinger.ts
index 7ab8ed81c..27564f942 100644
--- a/ui/src/pet/useReplyLinger.ts
+++ b/ui/src/pet/useReplyLinger.ts
@@ -3,7 +3,7 @@ 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;
+export const REPLY_LINGER_MS = 20_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. */