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): move personal agent interaction into mini speech bubble (#2678)

Max7423de3a8ee6
diff --git a/docs/plans/2026-10-12-desktop-mini-main-agent.md b/docs/plans/2026-10-12-desktop-mini-main-agent.md
index ba3542d61..878b95f65 100644
--- a/docs/plans/2026-10-12-desktop-mini-main-agent.md
+++ b/docs/plans/2026-10-12-desktop-mini-main-agent.md
@@ -16,6 +16,12 @@ Status: ready for implementation, v2 (2026-10-12). Supersedes v1 of this file.
#2408) stays the base for binding, IPC, the shortcut, `pet.json`, poses and
mark-read. This spec changes the layout and interaction on top of it.
+> P1 amendment (2026-10-15): §§4.2, 4.3, 5.2, 8 and 10 supersede the v2 main-card
+> and background-card descriptions elsewhere in this document. Layout, shell,
+> voice, dock, motion and timing remain v2. References to main-card detail now
+> mean the reply bubble's expandable detail. §10 now uses the shipped owner-only
+> main endpoint; the binding switcher and Workbench binding action are removed.
+
## 1. What changes, in one walk-through
1. Vibey (歪比) sits at the bottom of the mini. Above it is a **collapsed
@@ -74,6 +80,14 @@ the main agent; there is no Follow up on cards.
### 3.2 Expanded box
+- **Shared expansion (owner decision, 2026-10-15).** The card list and Vibey's
+ recent-turn history share the expanded space; they never expand together.
+ History retains the collapsed stack above it and uses up to the list's 292px
+ height, bounded by the measured stack, bubble header and fixed window. On the
+ 460×600 frame this leaves about 240px with four cards. Only overflowing history
+ scrolls; ordinary replies and their Open in Avibe/approval/quick-reply actions
+ fit without scrolling. Vibey and the dock keep their fixed anchors.
+
- **No backing panel on the desktop (owner decision, 2026-10-12).** The
expanded list sits in a transparent wrapper with 6px padding (kept so the
widths in §3.1 hold). Cards float directly over the desktop, separated by
@@ -133,64 +147,67 @@ the main agent; there is no Follow up on cards.
- There is **no reply/return button** and **no Follow up** (owner decisions).
- **Icons are SVG**, never Unicode glyphs. iOS renders `↩` as a blue emoji.
-### 4.2 Main agent card
-
-- **Position:** always the first card, collapsed or expanded. It cannot be
- dismissed and has no stop button in this version.
-- **Eyebrow:** the agent's name above the title, 2px gap: "Vibey" / "歪比"
- as written, no forced uppercase (owner decision, 2026-10-14). The fallback
- title and the input placeholder ("Message Vibey…" / "和歪比说…") name
- Vibey the same way; "main agent" is never shown to the user.
- - 11px, semibold, normal case and tracking.
- - Light green at 80%: map to the theme's mint token; the prototype used
- `emerald-300`.
- - It names the card type, not the speaker.
-- **Title:** the user's last message to the main agent. No avatar or icon:
- these are the user's own words, so nothing may suggest Vibey said them.
-- **Subtitle:**
- - while the turn runs, the current step ("Thinking", "Reading file", "Ran
- command", "Delegating", …) with the running dot;
- - after the turn, the start of the reply, "已回复:…", with no dot.
-- **Distinct but quiet:**
- - background `#34343b`, one step lighter than sub-task cards;
- - border light green at 45% (the same mint token);
- - 16px of row spacing after it.
-- **Click to open the conversation detail.** Clicking the main agent card in
- the expanded list opens an inline detail region inside the card. This keeps
- everything today's pet panel does, so nothing regresses (decided in review):
- - the latest exchange: the last user message and the unread results (or the
- last result), rendered with the existing Markdown renderer. Mark-read
- follows the existing rule: what is rendered and seen is marked read; when
- unread rows reach past the loaded tail, show "More in Avibe";
- - quick replies for the latest result, clickable, using the existing
- `QuickReplies` path (they never change Vibey's pose, #2408);
- - pending vault requests, one "需要授权,在 Avibe 中打开" button each;
- - the uncertain-send notice and the queued notice from the existing panel;
- - an "在 Avibe 中打开" link.
-
- The detail opens and closes with the `grid-template-rows 0fr ↔ 1fr`
- technique: 280ms settle for the rows, opacity 200ms ease. It grows inside
- the fixed scroll box: the box and Vibey do not move. It closes when the
- stack collapses, and clicking the card again also closes it.
-- **Before the first send,** the card shows the main session's last exchange.
- If there is none, it is absent.
-- **Pose:** Vibey takes the running pose while this card's turn runs.
-
-### 4.3 Sub-task cards
-
-- **Source:** the main session's turn state, `background_activities`. It
- already unions delegated runs (`item_kind: agent_run`), watches (`watch`)
- and scheduled tasks (`task`); this was verified live.
-- **Title:** the item's `label`, falling back to `description`.
-- **Subtitle:** "{kind} · {status}". Map the kind and raw status to readable,
- localized text: 委派运行 / 监控 / 定时任务; Running, 排队中, 等待中…
- Never show raw values such as `enabled`.
-- **Running** means `status` is `running` or `processing`; it shows the
- running dot and the stop button.
-- **Order:** the main agent card first, then running sub-tasks, then the rest.
- A sub-task the current turn just created goes directly below the main agent
- card. Live data must not reshuffle rows under the pointer while the list is
- expanded; apply reorders on collapse.
+### 4.2 Personal Agent reply bubble
+
+There is no main-agent card. Vibey's own progress and reply occupy the speech
+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.
+
+Click the bubble to expand recent turns from the loaded tail. Preserve all
+previous main detail behavior:
+
+- Markdown for the latest exchange and recent user/result rows;
+- mark-read only for the current, fully loaded unread exchange when its result
+ is visible and the page has focus; incomplete unread tails keep More in Avibe;
+- latest quick replies, pending Vault authorization handoffs, queued and
+ uncertain-send notices, and Open in Avibe;
+- the document-wide send lock and authorization/session epoch fencing.
+
+Detail retains the 280ms grid / 200ms opacity transition and closes on stack
+collapse. Its own scroll region fits the existing window; opening it never
+resizes the avatar or the 292px activity scroll box. Input and dictation hide
+this detail according to §5.2, including quick replies.
+
+### 4.3 Visible activity cards
+
+Use `api.getRunningAgents()` as the activity source, shared by the card and
+team-pose derivation. Exclude the bound main session, `ses_main`, missing session
+identities, and rows without explicit foreground visibility and chat access.
+Deduplicate by session; an active row wins over an idle row. A process going
+idle or disappearing is not evidence of a completed reply.
+
+The existing Inbox supplies unread evidence. Foreground unread sessions in its
+loaded feed remain eligible after their process disappears, with visibility
+revalidated by `getSessionResult`. No separate unread counter is created.
+The card says Replied while it has unread evidence and no running process.
+Callbacks to the main session are reported in Vibey's bubble.
+
+- Heading: project · agent; for IM, platform · project · agent.
+- Title: session title, with the existing localized fallback.
+- Priority: needs authorization, running, then replied. Preserve relative order
+ within a priority group while expanded; a newly actionable card moves first.
+- Clicking the card body appends the Web marker `#<session-id>` to the main
+ draft. It appears as a removable title chip; sending uses the main binding and
+ the existing session-reference sidecar. Cards never send replies directly.
+- Actions: dismiss, authorization handoff, Open in Avibe, and supported stop.
+ A foreground Web session exposes stop only after its live turn-state confirms
+ an in-flight dispatch turn. Use `cancelSession`, with §6's two presses, 3s
+ confirmation, 2.5s success linger and §7's exit. Runtime teardown is not stop.
+ Agent runs and IM rows without this cancellation evidence hide the control.
+ A process snapshot does not identify a Watch/Task definition; never infer a
+ definition ID or pause a schedule from a runtime identifier.
+
+Known data limitations for P1:
+
+- `trigger_source` defaults to human and does not prove caller lineage. Omit
+ the delegated badge and delegated-to summary until a reliable read-only
+ relation exists; do not fabricate attribution or suppress a visible result.
+- Background/system/unknown visibility is excluded. Ordinary questions lack a
+ reliable attention field; only pending Vault requests supply this signal.
+- Replied fallback is bounded by the existing loaded Inbox feed, which covers
+ Web Inbox data. A process-free session absent from that feed cannot be
+ discovered here, including a Vault-only session with no unread Inbox row.
### 4.4 Empty
@@ -241,7 +258,14 @@ the main agent; there is no Follow up on cards.
- **One slot** sits at the bottom of the column, between the cards and
Vibey. By priority it holds the marquee while dictating, otherwise the
- input bubble when it is open, otherwise nothing.
+ input bubble when it is open, otherwise Vibey's reply bubble when it has
+ progress, history, a notice, quick replies or a pending authorization.
+ Only the highest-priority content is interactive or eligible for mark-read.
+- **Mutually exclusive expansion.** Opening "Recent turns" collapses the cards
+ into their layered stack. Opening the card stack or clicking Vibey expands
+ the cards and closes history. Closing history returns to the collapsed mini.
+ Both transitions reuse the v2 height/content motion (§7.1, §7.4); reduced
+ motion switches directly. There is no separate 48–120px history cap.
- **No margin of its own.** The last card's row spacing plus the panel's 6px
padding separate it from the cards (about 14px).
- **Motion:**
@@ -361,7 +385,8 @@ Two beats, so the exit reads before the reflow:
- The leaving row ignores the pointer.
- A second click on the same × is a no-op.
-- A dismissed card does **not** come back on a refresh (§9.3).
+- A dismissed card stays closed through activity refreshes in the same document.
+ Reloading or reopening the mini starts fresh (§11.3).
### 7.4 No reflow jumps
@@ -395,19 +420,24 @@ With `prefers-reduced-motion: reduce`, every transition and animation in this
spec is off. States switch instantly, a dismissed card disappears at once, and
the marquee text still updates.
-## 8. Busy rule (pose)
+## 8. Pose priority
+
+Use the first matching condition, following the approved prototype's `POSES`:
-Vibey shows the running pose when **any** agent is working in a conversation
-the user can see: the main session, built-in role sessions, or ordinary user
-sessions.
+1. Listening: active dictation.
+2. Needs input: pending authorization in the main session or any eligible card.
+3. Blocked: the main session failed.
+4. Running: the main session is running.
+5. Ready: main unread results or a nondismissed replied card.
+6. Team working: an eligible activity is active.
+7. Idle; sleeping after five idle minutes.
-- This keeps #2401: an `active` foreground session in the running-agents
- snapshot.
-- It **adds the main session's own running sub-tasks**: running items in its
- turn state's `background_activities`. They run in background sessions, which
- #2401 excludes.
-- The main session's own needs-input, blocked and ready states still win over
- busy (existing priority).
+Cards and team activity use the same filtered snapshot. Background definitions
+alone do not create cards or a busy pose. Quick-reply suggestions do not count
+as needs input. Keep the current static images (team uses the existing running
+image); layered pose animation is deferred. Preserve reduced-motion behavior.
+The lower-left green activity-count badge is removed; the stack and team pose
+already communicate activity. Keep the upper-right red unread badge.
## 9. Shell (Tauri) work
@@ -464,78 +494,70 @@ sessions.
the pet page only, like the other pet commands, and must recheck its
caller.
-## 10. Main agent session (dependency; owned by another lane)
-
-- **Model:**
- - sessions get a built-in type (`main`, `memory`, `ops`, …);
- - each user has their **own** `main`;
- - `main` is a writable session with **normal visibility** (the pet's
- validity rule accepts it);
- - it is **built in at install** (upgrades must create it too);
- - it **cannot be archived or deleted**;
- - its **id is stable** across context rotation.
-- **Lookup API — not built yet; mock it.** Proposed contract:
-
- ```
- GET /api/sessions/main
- 200 { "session": WorkbenchSession, "capabilities": { "can_chat": bool } }
- ```
-
- - The pet reads the main session only through one client function,
- `api.getMainSession()`.
- - Until the endpoint exists, the function returns the session the pet is
- bound to today (the user-picked binding from `pet_ready()`), in the same
- shape. Under this mock, keep a way to pick the session (for example in
- the main card's detail header).
- - When the endpoint lands: call it on start, on reconnect and after
- authorization changes. Then remove the switcher, "在桌宠中显示" and the
- binding writes. Older `pet.json` files that contain `binding` must still
- load; ignore the field (persisted-shape rule).
-
-### 10.1 Interim: the mini talks to Vibey (owner decision, 2026-10-13)
-
-Until the `main` type exists, the mini's main agent is a Vibey conversation
-(the built-in Agent, `backend: vibey`).
-
-- **One per person, created on first use.** `POST /api/desktop-mini/session`
- (Editor) returns the caller's conversation, creating it the first time in
- their most recently active Project they can chat in. A session needs a
- Project so it has a Workbench sidebar home and "在 Avibe 中打开" lands on it.
- It is an ordinary foreground session, so the Workbench shows and manages it
- like any other. Which session belongs to whom is recorded server-side in
- `state_meta` (`desktop_mini_session:<principal>`, principal `local` or
- `remote:<sub>`), never in session metadata a client can write or a fork can
- copy.
-- **Who the caller is.** The principal comes from the request's authorization
- context, never from a second lookup that could fall back: a remote context
- without a subject owns nothing and is refused.
-- **Reuse.** The same session is returned while it is still what creation
- would produce: active, foreground, a Project the caller can chat in, still on
- the built-in Agent (a Workbench route change makes it an ordinary chat), which
- the caller may use. Title, model and effort are the user's to change. An archived session, an archived Project or lost
- access gets a new one. With no chat Project at all the answer is
- `409 no_chat_project`, and the mini asks the user to create a Project.
-- **Binding.** The mini binds that session whenever nothing is bound. An
- existing binding is kept; the switcher offers "和歪比对话" to move to it.
-- **Switcher navigation.** The switcher opens only from "切换会话", or by
- itself when nothing is bound. While a session is bound it has a "返回"
- control that goes back to the cards, and collapsing the panel leaves it. A
- bound session with nothing to show (no exchange, no sub-tasks) expands to the
- "切换会话" control alone, never to the switcher, so picking such a session
- does not reopen the list.
- A session the mini already bound and then cleared as invalid is not
- re-bound automatically, so a bad answer cannot loop.
-- **A turn Vibey cannot run is shown.** When the latest exchange ended in a
- backend failure notice (for example no model source), the main card's
- subtitle reads "没跑起来:<notice>" (the exchange ends at its foreground
- terminal row, by the transcript's own rule, so detached completions and
- replayed failures never decide it), and the detail shows the notice as plain
- text with "在 Avibe 中处理" when it names a next step. That opens the session,
- where the Workbench draws "Open Models" for those who manage the instance.
-- **Not in this change.** A live step label ("Ran command", …) for the main
- card still waits on §11.1; the server already computes `status_label` for
- the IM status bubble and can expose it later.
-- When `main` lands, this endpoint is replaced by `GET /api/sessions/main`.
+## 10. Main agent session (implemented; main-only)
+
+`GET /api/sessions/main` shipped in #2637. The mini uses this endpoint through
+`api.getMainSession()` as its only conversation selector:
+
+```
+GET /api/sessions/main
+200 { "session": WorkbenchSession, "capabilities": { "can_chat": true } }
+```
+
+- **Owner-only in this release.** The instance owner uses the stable `ses_main`
+ session. Non-owner 403 is an accepted unavailable state; per-member main
+ sessions and permission expansion are outside P1.
+- **Lifecycle and recovery.** Resolve main on startup, reconnect and authorization
+ change, and retry on page reactivation after transient failures. Use the existing
+ authorization epoch and `FencedSource` request ordering. No new polling loop.
+ Transcript/runtime reads wait for main's explicit chat grant. Authorization
+ changes immediately invalidate pending reads and action callbacks before resolving
+ again. Retain the user's draft and document send ledger across transient failures.
+- **No switcher.** The bubble's switch button, the entire recent-session picker,
+ its "Talk to Vibey" option and the Workbench "Show in pet" action are removed.
+ The only allowed binding write is `pet_bind("ses_main")` after successful main
+ resolution, to normalize the legacy binding. No caller writes another
+ session or invokes `pet_unbind`. Summons still open/listen
+ through the existing shell flow and wait for a usable main.
+- **Persisted compatibility.** Existing `pet.json` shapes still load unchanged.
+ Legacy `binding` values and bound events never select a conversation, including
+ when they arrive after main has resolved. The existing native IPC normalizes empty or other persisted bindings to
+ `ses_main`; the file format and native code remain unchanged.
+- **Unavailable.** A 403, `409 main_session_invalid`, `409 main_session_archived`,
+ `builtin_agent_unavailable`, or a transport failure shows the existing localized
+ unavailable message and "Open in Avibe". No arbitrary-session fallback. Pending
+ resolution shows the existing loading copy; reconnect/reactivation can recover.
+- **Main-only binding normalization.** After main resolves successfully, compare the legacy
+ binding from `pet_ready` with `ses_main`. If different, make at most one
+ `pet_bind("ses_main")` attempt per surface epoch. An already-main file
+ needs no binding write. A failed normalization does not retry in a loop;
+ a later epoch may try again. This does not synchronize dismissals.
+- **Document-only dismissal.** Manual × closes a card for the current document.
+ The last successfully resolved main owns these closes, including new closes
+ made during a temporary main lookup failure. Do not read or write native
+ `dismissed_ids`; `pet_ready` and binding normalization cannot restore, clear,
+ or delay document closes. Reloading or reopening starts with no closed cards.
+ Forget an id on an explicit new turn, or after it disappears from eligible
+ activities and has no unread Inbox reply. Absence-based forgetting and local
+ reappearance detection require an applied whole-account Inbox unread snapshot,
+ no initial Inbox feed load in progress, a successful running-agents snapshot,
+ and no pending reply-activity validation. Retain validated reply rows during
+ revalidation; only the latest read may replace them. A failed read stays
+ non-authoritative until a later event retries. No new polling loop or shared
+ activity-source lifecycle is introduced.
+- **Turn-scoped card presentation.** Confirmation, cancellation, stopped/failed
+ notices, exits, leaving animation and retained cards use `sessionId:generation`
+ keys. Increment the local generation on `turn.start` or healthy activity
+ disappearance followed by reappearance. Retire that key's timers together;
+ every timer/cancel callback checks its captured key and authorization epoch.
+ Old callbacks cannot alter a new turn. Stop exits never add manual dismissals.
+- **Standalone stop eligibility.** A foreground, chat-openable human activity
+ with `platform = null` is a Web candidate, as is `platform = avibe`. Both still
+ require an explicitly in-flight turn-state read; actual IM platforms stay excluded.
+- **Turn failures remain visible.** A foreground terminal failure notice is shown
+ in the reply bubble/detail, with "Fix in Avibe" when it names a next step. Detached
+ completions and replayed failures do not replace the current exchange. Live step
+ labels still wait on §11.1; the mini shows "Thinking" meanwhile.
## 11. Backend gaps (not in this delivery; degrade gracefully)
@@ -547,10 +569,12 @@ Until the `main` type exists, the mini's main agent is a Vibey conversation
- **Do not guess from tool names in the client.**
2. **No HTTP cancel for agent runs.** Hide stop on agent runs until it exists
(§6).
-3. **Dismiss persistence.** There is no server state for dismissed cards.
- Keep the dismissed ids in `pet.json`, so a dismissed card stays gone across
- restarts. Forget an id once its item disappears from the turn state. This
- adds an optional field, so older files keep loading.
+3. **No dismissal persistence in this delivery.** A manual × lasts only for the
+ current mini document. Refreshing the page or restarting the mini lets the
+ activity sources populate cards again. Existing `pet.json` files still load,
+ but their `dismissed_ids` are ignored and no dismissal IPC writes are made.
+ Forgetting within the document follows §10. Cross-restart memory and a unified
+ readiness model for the three activity sources are deferred.
## 12. Prototype-only (do not copy)
diff --git a/ui/e2e/pet-mini/fixture.tsx b/ui/e2e/pet-mini/fixture.tsx
index 866cf9d8d..517fd9ba2 100644
--- a/ui/e2e/pet-mini/fixture.tsx
+++ b/ui/e2e/pet-mini/fixture.tsx
@@ -10,68 +10,128 @@ import { OWNER_INSTANCE_CAPABILITIES } from '../../src/lib/sessionInfo';
import i18n from '../../src/i18n';
import '../../src/index.css';
-await i18n.changeLanguage('en');
+const params = new URLSearchParams(location.search);
+await i18n.changeLanguage(params.get('lang') ?? 'en');
declare global {
interface Window {
petLayoutHitRegions: Parameters<typeof petBridge.setHitRegions>[0];
setPetLayoutVisible: (visible: boolean) => void;
+ petFixtureSends: { sessionId: string; payload: unknown }[];
+ petFixtureOpens: string[];
+ petFixtureStops: unknown[];
+ petFixtureMainReads: number;
+ setPetMainAvailable: (available: boolean) => void;
+ petFixtureConnection: (connected: boolean) => void;
}
}
window.petLayoutHitRegions = [];
petBridge.setHitRegions = async (rects) => { window.petLayoutHitRegions = rects; };
-const params = new URLSearchParams(location.search);
+window.petFixtureSends = [];
+window.petFixtureOpens = [];
+window.petFixtureStops = [];
+petBridge.open = async (link) => { window.petFixtureOpens.push(link); };
const hasMain = params.get('main') !== 'false';
const layers = Number(params.get('layers') ?? 3);
-const sessionCount = Number(params.get('sessions') ?? 1);
-const title = 'A long unbroken title '.repeat(40);
+const personal = params.get('scenario') === 'personal';
+const historyActions = params.get('history') === 'actions';
+const title = personal ? '检查桌宠 mini 的交互' : 'A long unbroken title '.repeat(40);
const session = {
- id: 'pet-layout', scope_id: 'fixture', title, agent_backend: 'codex',
+ id: 'ses_main', scope_id: 'fixture', title, agent_backend: 'codex',
+ capabilities: { can_chat: true },
status: 'active', visibility: 'foreground', agent_status: 'idle', metadata: {},
};
const messages = hasMain ? [{
id: 'user', session_id: session.id, scope_id: session.scope_id,
author: 'user', type: 'user', text: title, metadata: {}, content: {},
created_at: '2026-10-12T00:00:00Z', updated_at: '2026-10-12T00:00:00Z',
+}, {
+ id: 'result', session_id: session.id, scope_id: session.scope_id,
+ author: 'agent', type: 'result',
+ text: personal ? '我会帮你跟进各个项目。需要授权的事已经排在前面。' : 'Ready to help with your next task.',
+ metadata: {}, content: historyActions ? { quick_replies: ['继续', '稍后'] } : {}, read_at: '2026-10-12T00:00:01Z',
+ created_at: '2026-10-12T00:00:01Z', updated_at: '2026-10-12T00:00:01Z',
}] : [];
-const activities = Array.from({ length: layers + (hasMain ? 0 : 1) }, (_, i) => ({
- id: `watch:fixture-${i}`, item_kind: 'watch', status: 'enabled', label: title,
- description: title, backend: 'codex', runtime_key: `fixture-${i}`,
- session_id: session.id, kind: 'watch', started_at: '2026-10-12T00:00:00Z',
+const agents = Array.from({ length: Number(params.get('activities') ?? layers + 1) }, (_, i) => ({
+ backend: i === 1 ? 'claude' : 'codex', state: personal && i === 2 ? 'idle' : 'active',
+ session_id: `ses_fixture_${i}`, base_session_id: `native_${i}`, composite_key: null,
+ pid: null, pid_shared: false, workdir: null, native_session_id: null, model: null, elapsed_seconds: 10,
+ title: personal ? ['修复桌宠语音输入', '整理团队本周进展', '梳理 Personal Agent 交互', '检查项目文档'][i % 4] : title,
+ scope_display_name: personal && i === 1 ? '产品频道' : i === 2 ? 'avibe-docs' : 'avibe-app',
+ agent_name: i === 1 ? 'claude' : 'codex', platform: personal && i === 1 ? 'feishu' : 'avibe',
+ scope_type: 'project', visibility: 'foreground', trigger_source: 'human', openable_in_chat: true,
}));
-const switcherSessions = [session, ...Array.from({ length: sessionCount - 1 }, (_, i) => ({ ...session, id: `fixture-session-${i}`, title: `Session ${i + 1} ${title}` }))];
-localStorage.setItem('avibe.pet.devBinding', JSON.stringify({ binding: session.id, revision: 1 }));
+const requests = personal ? [{
+ id: 'vr_fixture', request_type: 'access', status: 'pending', card: { request_type: 'access' },
+ session: { id: 'ses_fixture_0' }, expires_at: null,
+}] : [];
+if (historyActions) requests.push({
+ id: 'vr_main_fixture', request_type: 'access', status: 'pending', card: { request_type: 'access' },
+ session: { id: 'ses_main' }, expires_at: null,
+});
+const unread = personal ? { ses_fixture_2: 1 } : {};
+// A legacy file must not steer reads or sends away from main.
+localStorage.setItem('avibe.pet.devBinding', JSON.stringify({ binding: 'legacy-session', revision: 1 }));
+let mainAvailable = params.get('offline') !== 'true';
+window.petFixtureMainReads = 0;
+window.setPetMainAvailable = (available) => { mainAvailable = available; };
// Every API read is fixture-owned. Unexpected calls fail rather than reaching a
// user's runtime; the Vite proxy also points at an unused local port.
-window.fetch = async (input) => {
- const path = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, location.origin).pathname;
+window.fetch = async (input, init) => {
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, location.origin);
+ const path = url.pathname;
+ const json = (value: unknown) => new Response(JSON.stringify(value), { headers: { 'Content-Type': 'application/json' } });
+ if (path === '/api/sessions/main') {
+ window.petFixtureMainReads += 1;
+ if (!mainAvailable) return new Response(JSON.stringify({ error: 'temporarily_unavailable' }), { status: 503, headers: { 'Content-Type': 'application/json' } });
+ return json({ session, capabilities: { can_chat: true } });
+ }
+ if (init?.method === 'POST' && path.endsWith('/messages')) {
+ const payload = JSON.parse(String(init.body));
+ window.petFixtureSends.push({ sessionId: path.split('/')[3], payload });
+ return json({ ...messages[0], id: 'sent', text: payload.text });
+ }
+ if (init?.method === 'POST' && path.endsWith('/cancel')) {
+ window.petFixtureStops.push(path.split('/')[3]);
+ return json({ ok: true });
+ }
+ if (path.endsWith('/turn-state') && !path.includes('ses_main')) return json({ in_flight: true, foreground: 'running' });
+ if (path.endsWith('/mark-read')) return json({ updated: 1, unread_by_session: unread });
const payloads: Record<string, unknown> = {
+ '/api/csrf-token': { csrf_token: 'fixture-only-token' },
'/api/config': { mode: 'self_host', setup_state: { needs_setup: false } },
'/api/session': { remote: false, instance_kind: 'personal', capabilities: OWNER_INSTANCE_CAPABILITIES },
- '/api/sessions/pet-layout': session,
- '/api/sessions/pet-layout/messages': { messages, next_after_id: null, next_before_id: null },
- '/api/sessions/pet-layout/turn-state': {
+ '/api/sessions/ses_main': session,
+ '/api/sessions/ses_main/messages': { messages, next_after_id: null, next_before_id: null },
+ '/api/sessions/ses_main/turn-state': {
foreground: 'idle', in_flight: false, native_turn_started: false, pending_input_count: 0,
- background_activities: activities, pending_activity_output_count: 0, connection: 'connected',
+ background_activities: [], pending_activity_output_count: 0, connection: 'connected',
},
- '/api/vault/requests': { ok: true, requests: [] },
+ '/api/vault/requests': { ok: true, requests: requests.filter((request) => !url.searchParams.get('session') || request.session.id === url.searchParams.get('session')) },
'/api/asr/status': { available: false },
- '/api/running-agents': { ok: true, agents: [], counts: { total: 0, active: 0, idle: 0, orphan: 0, by_backend: {} } },
- '/api/sessions': { sessions: switcherSessions, next_before_id: null },
- '/api/inbox': { ok: true, sessions: [], unread_by_session: {}, total_unread: 0, next_before_id: null },
+ '/api/running-agents': { ok: true, agents, counts: { total: agents.length, active: agents.length, idle: 0, orphan: 0, by_backend: {} } },
+ '/api/sessions': { sessions: [session], next_before_id: null },
+ '/api/inbox': { ok: true, sessions: [], unread_by_session: unread, total_unread: Object.values(unread).reduce((a, b) => a + b, 0), next_before_id: null },
};
if (!(path in payloads)) throw new Error(`Unexpected pet fixture request: ${path}`);
- return new Response(JSON.stringify(payloads[path]), { headers: { 'Content-Type': 'application/json' } });
+ return json(payloads[path]);
};
-// A disconnected event stream is sufficient for this fixed layout fixture.
-class FixtureEvents {
+// Fixture-owned real EventTarget: exercise the provider's reconnect path.
+const streams = new Set<FixtureEvents>();
+class FixtureEvents extends EventTarget {
static OPEN = 1;
readyState = 1;
- addEventListener() {}
- removeEventListener() {}
- close() {}
+ constructor() { super(); streams.add(this); }
+ close() { streams.delete(this); }
}
window.EventSource = FixtureEvents as unknown as typeof EventSource;
+window.petFixtureConnection = (connected) => {
+ for (const stream of streams) {
+ stream.dispatchEvent(new MessageEvent('workbench.events.bridge.status', {
+ data: JSON.stringify({ type: 'workbench.events.bridge.status', data: { connected } }),
+ }));
+ }
+};
const root = createRoot(document.getElementById('root')!);
window.setPetLayoutVisible = (visible) => root.render(
diff --git a/ui/e2e/pet-mini/layout.spec.ts b/ui/e2e/pet-mini/layout.spec.ts
index 4b59245eb..a70fb605f 100644
--- a/ui/e2e/pet-mini/layout.spec.ts
+++ b/ui/e2e/pet-mini/layout.spec.ts
@@ -1,5 +1,33 @@
import { expect, test } from '@playwright/test';
+for (const theme of ['light', 'dark']) {
+ for (const lang of ['en', 'zh']) {
+ test(`collapsed bubble spacing and action copy (${theme}, ${lang})`, async ({ page }) => {
+ await page.goto(`/e2e/pet-mini/fixture.html?scenario=personal&lang=${lang}`);
+ await page.evaluate((theme) => { document.documentElement.dataset.theme = theme; }, theme);
+ await expect(page.locator('.pet-mini-collapsed')).toBeVisible();
+ await expect(page.locator('.pet-mini-stage')).toHaveCSS('color', theme === 'dark' ? 'rgb(255, 255, 255)' : 'rgb(23, 23, 28)');
+ await page.evaluate(async () => {
+ await Promise.all(document.getAnimations()
+ .filter((animation) => animation.effect?.getTiming().iterations !== Infinity)
+ .map((animation) => animation.finished.catch(() => {})));
+ });
+ const gap = await page.evaluate(() =>
+ document.querySelector('.pet-mini-reply-bubble')!.getBoundingClientRect().top
+ - 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 page.locator('.pet-mini-collapsed').click();
+ const stop = page.locator('.pet-mini-stop').first();
+ await expect(stop).toHaveAttribute('aria-label', lang === 'zh' ? /^停止:.+/ : /^Stop: .+/);
+ await stop.click();
+ await expect(stop).toHaveAttribute('aria-label', lang === 'zh' ? '停止?' : 'Stop?');
+ expect(await page.evaluate(() => window.petFixtureStops)).toEqual([]);
+ });
+ }
+}
+
test('an unmounted surface releases desktop input and a remount reports fresh regions', async ({ page }) => {
await page.goto('/e2e/pet-mini/fixture.html');
await expect(page.locator('.pet-mini-collapsed')).toBeVisible();
@@ -66,7 +94,6 @@ for (const main of [true, false]) {
const x = (first.left + first.right) / 2;
return { card: covers(x, (first.top + first.bottom) / 2), gap: covers(x, (first.bottom + second.top) / 2) };
})).toEqual({ card: true, gap: false });
- if (main) await page.locator('.pet-mini-card[role=button]').click();
// A long nowrap title and long detail must remain inside the fixed list.
const widths = await page.locator('.pet-mini-scroll').evaluate((scroll) => ({
client: scroll.clientWidth, content: scroll.scrollWidth,
@@ -74,30 +101,13 @@ for (const main of [true, false]) {
}));
expect(widths.content).toBe(widths.client);
expect(widths.cards.every((width) => width <= widths.client)).toBe(true);
+ if (main) await page.locator('.pet-mini-reply-toggle').click();
expect(await page.locator('.pet-mini-avatar-button').boundingBox()).toEqual(avatar);
expect(errors).toEqual([]);
});
}
}
-test('the session picker keeps every row at its text height and scrolls', async ({ page }) => {
- await page.goto('/e2e/pet-mini/fixture.html?main=true&layers=0&sessions=14');
- await page.locator('.pet-mini-collapsed').click();
- await page.locator('.pet-mini-card[role=button]').click();
- const toggle = page.getByRole('button', { name: 'Switch session' });
- await expect(toggle).toBeVisible();
- // The switcher is a real button, not a text link.
- expect(await toggle.evaluate((node) => getComputedStyle(node).borderTopStyle)).toBe('solid');
- await toggle.click();
- const options = page.locator('.pet-mini-session-option');
- await expect(options).toHaveCount(15);
- // A shrunk flex column squeezes overflow-hidden rows below their text height.
- const rows = await options.evaluateAll((nodes) => nodes.map((node) => ({ client: node.clientHeight, content: node.scrollHeight })));
- expect(rows.every((row) => row.client >= 36 && row.client >= row.content)).toBe(true);
- const scroll = await page.locator('.pet-mini-scroll').evaluate((node) => ({ client: node.clientHeight, content: node.scrollHeight }));
- expect(scroll.content).toBeGreaterThan(scroll.client);
-});
-
test('no mini surface casts a shadow the transparent window would clip', async ({ page }) => {
await page.goto('/e2e/pet-mini/fixture.html?main=true&layers=2&sessions=4');
await expect(page.locator('.pet-mini-collapsed')).toBeVisible();
@@ -123,25 +133,11 @@ test('no mini surface casts a shadow the transparent window would clip', async (
.map((node) => node.className.toString()));
expect(await shadowed()).toEqual([]);
await page.locator('.pet-mini-collapsed').click();
- await page.locator('.pet-mini-card[role=button]').click();
- await page.getByRole('button', { name: 'Switch session' }).click();
- await expect(page.locator('.pet-mini-session-option')).toHaveCount(5);
+ await page.locator('.pet-mini-reply-toggle').click();
+ await expect(page.getByRole('button', { name: 'Switch session' })).toHaveCount(0);
expect(await shadowed()).toEqual([]);
});
-test('the switcher goes back to the cards', async ({ page }) => {
- await page.goto('/e2e/pet-mini/fixture.html?main=true&layers=0&sessions=3');
- await page.locator('.pet-mini-collapsed').click();
- await page.locator('.pet-mini-card[role=button]').click();
- await page.getByRole('button', { name: 'Switch session' }).click();
- await expect(page.locator('.pet-mini-session-option')).toHaveCount(4);
- const back = page.getByRole('button', { name: 'Back' });
- expect(await back.evaluate((node) => getComputedStyle(node).borderTopStyle)).toBe('solid');
- await back.click();
- await expect(page.locator('.pet-mini-session-option')).toHaveCount(0);
- await expect(page.locator('.pet-mini-card.is-main')).toBeVisible();
-});
-
test('Vibey and its dock are reported as the hover zone, and a shell hover shows the dock', async ({ page }) => {
await page.goto('/e2e/pet-mini/fixture.html?main=true&layers=0');
const dock = page.locator('.pet-mini-dock');
@@ -167,10 +163,160 @@ test('Vibey and its dock are reported as the hover zone, and a shell hover shows
await expect(dock).toHaveCSS('opacity', '0');
});
-test('the main card names Vibey as written', async ({ page }) => {
+test('the reply bubble names Vibey as written', async ({ page }) => {
await page.goto('/e2e/pet-mini/fixture.html?main=true&layers=0');
- const eyebrow = page.locator('.pet-mini-collapsed .pet-mini-eyebrow');
+ const eyebrow = page.locator('.pet-mini-bubble-speaker');
await expect(eyebrow).toBeVisible();
// innerText applies text-transform, so this is what the user reads.
- expect(await eyebrow.evaluate((node) => node.innerText)).toBe('Vibey');
+ expect(await eyebrow.evaluate((node) => node.innerText)).toContain('Vibey');
+});
+
+
+test('attention leads the list and referencing sends only through the main composer', async ({ page }) => {
+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal');
+ await page.locator('.pet-mini-collapsed').click();
+ const first = page.locator('.pet-mini-card').first();
+ await expect(first).toHaveAttribute('data-session-id', 'ses_fixture_0');
+ await expect(first).toHaveClass(/is-needs-input/);
+ await first.getByRole('button', { name: 'Open in Avibe', exact: true }).click();
+ await expect(page.getByRole('textbox')).toHaveCount(0);
+ await first.locator('.pet-mini-card-reference').click();
+ await expect(page.locator('.pet-mini-reference-chip')).toHaveCount(1);
+ await expect(page.locator('.pet-mini-reply-bubble')).toHaveCount(0);
+ await page.getByRole('textbox').fill('请总结进展');
+ await page.getByRole('textbox').press('Enter');
+ await expect.poll(() => page.evaluate(() => window.petFixtureSends)).toEqual([{
+ sessionId: 'ses_main', payload: { text: '#<ses_fixture_0> 请总结进展', content: { references: [{ kind: 'session', session_id: 'ses_fixture_0', title: '修复桌宠语音输入' }] } },
+ }]);
+ await expect(page.locator('.pet-mini-reply-bubble')).toBeVisible();
+});
+
+test('reply history and input remain within the fixed window with reduced motion', async ({ page }) => {
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal');
+ await page.locator('.pet-mini-collapsed').click();
+ const avatar = await page.locator('.pet-mini-avatar-button').boundingBox();
+ await page.locator('.pet-mini-reply-toggle').click();
+ await expect(page.locator('.pet-mini-detail')).toHaveClass(/is-open/);
+ const history = await page.locator('.pet-mini-bubble-history').boundingBox();
+ expect(history!.y).toBeGreaterThanOrEqual(0);
+ expect(history!.y + history!.height).toBeLessThanOrEqual(600);
+ expect(await page.locator('.pet-mini-avatar-button').boundingBox()).toEqual(avatar);
+ expect(await page.locator('.pet-mini-detail').evaluate((node) => parseFloat(getComputedStyle(node).transitionDuration))).toBeLessThan(0.01);
+});
+
+for (const theme of ['light', 'dark']) {
+ for (const reduced of [false, true]) {
+ test(`history and cards share expansion with reachable actions (${theme}, reduced=${reduced})`, async ({ page }) => {
+ await page.emulateMedia({ reducedMotion: reduced ? 'reduce' : 'no-preference' });
+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=actions');
+ await page.evaluate((theme) => { document.documentElement.dataset.theme = theme; }, theme);
+ const avatar = page.locator('.pet-mini-avatar-button');
+ await expect(avatar).toBeVisible();
+ const anchor = await avatar.boundingBox();
+ await page.locator('.pet-mini-collapsed').click();
+ await expect(page.locator('.pet-mini-scroll')).toBeVisible();
+ await page.locator('.pet-mini-reply-toggle').click();
+ await expect(page.locator('.pet-mini-collapsed')).toBeVisible();
+ await expect(page.locator('.pet-mini-scroll')).toHaveCount(0);
+ await expect(page.locator('.pet-mini-detail')).toHaveClass(/is-open/);
+ await page.evaluate(async () => {
+ await Promise.all(document.getAnimations()
+ .filter((animation) => animation.effect?.getTiming().iterations !== Infinity)
+ .map((animation) => animation.finished.catch(() => {})));
+ });
+ const history = page.locator('.pet-mini-bubble-history');
+ for (const name of ['在 Avibe 中打开', '需要授权,在 Avibe 中打开', '继续']) {
+ const button = history.getByRole('button', { name, exact: true });
+ await expect(button).toBeVisible();
+ const bounds = await button.boundingBox(), box = await history.boundingBox();
+ expect(bounds!.y).toBeGreaterThanOrEqual(box!.y);
+ expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(box!.y + box!.height + 1);
+ }
+ expect(await history.evaluate((node) => node.scrollHeight <= node.clientHeight + 1)).toBe(true);
+ expect((await page.locator('.pet-mini-collapsed').boundingBox())!.y).toBeGreaterThanOrEqual(0);
+ expect(await avatar.boundingBox()).toEqual(anchor);
+ await page.locator('.pet-mini-collapsed').click();
+ await expect(page.locator('.pet-mini-scroll')).toBeVisible();
+ await expect(page.locator('.pet-mini-detail')).not.toHaveClass(/is-open/);
+ await page.locator('.pet-mini-reply-toggle').click();
+ await expect(page.locator('.pet-mini-collapsed')).toBeVisible();
+ await avatar.click();
+ await expect(page.locator('.pet-mini-scroll')).toBeVisible();
+ await expect(page.locator('.pet-mini-detail')).not.toHaveClass(/is-open/);
+ expect(await avatar.boundingBox()).toEqual(anchor);
+ });
+ }
+}
+
+
+test('an empty activity stack takes no space while history remains usable without a switcher', async ({ page }) => {
+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&activities=0');
+ await page.locator('.pet-mini-reply-toggle').waitFor();
+ const avatar = await page.locator('.pet-mini-avatar-button').boundingBox();
+ await page.locator('.pet-mini-avatar-button').click();
+ await expect(page.locator('.pet-mini-cards')).toHaveCSS('height', '0px');
+ await expect(page.locator('.pet-mini-panel')).toHaveCount(0);
+ await page.locator('.pet-mini-reply-toggle').click();
+ await expect(page.getByRole('button', { name: 'Switch session' })).toHaveCount(0);
+ await expect(page.locator('.pet-mini-session-option')).toHaveCount(0);
+ await expect(page.locator('.pet-mini-detail')).toHaveClass(/is-open/);
+ await expect(page.locator('.pet-mini-cards')).toHaveCSS('height', '0px');
+ expect(await page.locator('.pet-mini-avatar-button').boundingBox()).toEqual(avatar);
});
+
+test('a close during a main outage lasts until the mini document reopens', async ({ page }) => {
+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal');
+ await page.locator('.pet-mini-collapsed').click();
+ const card = page.locator('.pet-mini-card[data-session-id="ses_fixture_0"]');
+ await expect(card).toBeVisible();
+ await page.evaluate(() => {
+ window.petFixtureConnection(false);
+ window.setPetMainAvailable(false);
+ window.petFixtureConnection(true);
+ });
+ await expect(page.getByText("Couldn't open the conversation with Vibey. Try again in a moment.")).toBeVisible();
+ await card.locator('.pet-mini-dismiss').click();
+ await expect(card).toHaveCount(0);
+ await page.evaluate(() => {
+ window.petFixtureConnection(false);
+ window.setPetMainAvailable(true);
+ window.petFixtureConnection(true);
+ });
+ await expect(page.locator('.pet-mini-reply-toggle')).toBeVisible();
+ await expect(card).toHaveCount(0);
+ await page.reload();
+ await page.locator('.pet-mini-collapsed').click();
+ await expect(card).toBeVisible();
+});
+
+for (const trigger of ['reconnect', 'reactivation']) {
+ test(`main resolves automatically after service recovery on ${trigger}`, async ({ page }) => {
+ await page.goto('/e2e/pet-mini/fixture.html?offline=true&activities=0');
+ await expect(page.getByText("Couldn't open the conversation with Vibey. Try again in a moment.")).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Open in Avibe', exact: true })).toBeVisible();
+ await expect(page.getByRole('textbox')).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Switch session' })).toHaveCount(0);
+ if (trigger === 'reconnect') {
+ await page.evaluate(() => {
+ window.petFixtureConnection(false);
+ window.setPetMainAvailable(true);
+ window.petFixtureConnection(true);
+ });
+ } else {
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'hasFocus', { configurable: true, value: () => false });
+ window.dispatchEvent(new Event('blur'));
+ window.setPetMainAvailable(true);
+ Object.defineProperty(document, 'hasFocus', { configurable: true, value: () => true });
+ window.dispatchEvent(new Event('focus'));
+ });
+ }
+ await expect(page.locator('.pet-mini-reply-bubble')).toContainText('Ready to help');
+ await page.evaluate(() => window.dispatchEvent(new CustomEvent('avibe:pet-summon', { detail: { intent: 'listen' } })));
+ await page.getByRole('textbox').fill('recovered');
+ await page.getByRole('textbox').press('Enter');
+ await expect.poll(() => page.evaluate(() => window.petFixtureSends)).toEqual([{ sessionId: 'ses_main', payload: { text: 'recovered' } }]);
+ expect(await page.evaluate(() => JSON.parse(localStorage.getItem('avibe.pet.devBinding')!).binding)).toBe('ses_main');
+ });
+}
diff --git a/ui/src/components/workbench/useSessionActions.test.tsx b/ui/src/components/workbench/useSessionActions.test.tsx
index bc17e4fed..f573c5c6e 100644
--- a/ui/src/components/workbench/useSessionActions.test.tsx
+++ b/ui/src/components/workbench/useSessionActions.test.tsx
@@ -18,8 +18,6 @@ const mocks = vi.hoisted(() => ({
setSessionVisibility: vi.fn(),
showToast: vi.fn(),
authorizeRouteAction: vi.fn<() => UnsavedChangesActionAuthorization | null>(),
- canShowInDesktopPet: vi.fn(() => false),
- showInPet: vi.fn<(sessionId: string) => Promise<{ shown: boolean }>>(),
}));
vi.mock('../../context/ApiContext', () => ({
@@ -37,8 +35,6 @@ vi.mock('../../context/WorkbenchProjectsContext', () => ({
vi.mock('../../context/useUnsavedChangesActionGuard', () => ({
useUnsavedChangesActionGuard: () => mocks.authorizeRouteAction,
}));
-vi.mock('../../lib/desktopShell', () => ({ canShowInDesktopPet: mocks.canShowInDesktopPet }));
-vi.mock('../../pet/petBridge', () => ({ petBridge: { showInPet: mocks.showInPet } }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
const session = (over: Partial<WorkbenchSession> = {}): WorkbenchSession =>
@@ -110,8 +106,6 @@ beforeEach(() => {
mocks.setSessionPinned.mockResolvedValue(undefined);
mocks.archiveSession.mockResolvedValue(undefined);
mocks.authorizeRouteAction.mockImplementation(grantedAuthorization);
- mocks.canShowInDesktopPet.mockReturnValue(false);
- mocks.showInPet.mockResolvedValue({ shown: true });
});
describe('surface-specific actions', () => {
@@ -275,37 +269,6 @@ describe('a metadata-only session', () => {
});
});
-// "Show in pet": the Workbench hands one session to the pet.
-describe('show in pet', () => {
- it('is offered only by a desktop shell that has a pet', () => {
- expect(mount(options()).actions.map((action) => action.id)).not.toContain('pet');
-
- mocks.canShowInDesktopPet.mockReturnValue(true);
- const ids = mount(options()).actions.map((action) => action.id);
- expect(ids).toEqual(['pin', 'rename', 'fork', 'pet', 'hide', 'archive']);
- // Read-only sessions still offer nothing.
- expect(mount(options({ session: session({ status: 'archived' }) })).actions).toEqual([]);
- });
-
- it('binds the session and stays quiet when the pet shows it', async () => {
- mocks.canShowInDesktopPet.mockReturnValue(true);
- select(mount(options()), 'pet');
-
- expect(mocks.showInPet).toHaveBeenCalledWith('ses_standalone');
- await flush();
- expect(mocks.showToast).not.toHaveBeenCalled();
- });
-
- it('says how to turn the pet on when it is off, and reports a failure', async () => {
- mocks.canShowInDesktopPet.mockReturnValue(true);
- mocks.showInPet.mockResolvedValueOnce({ shown: false });
- select(mount(options()), 'pet');
- await flush();
- expect(mocks.showToast).toHaveBeenCalledWith('pet.showInPetOff', 'warning');
-
- mocks.showInPet.mockRejectedValueOnce(new Error('denied'));
- select(mount(options()), 'pet');
- await flush();
- expect(mocks.showToast).toHaveBeenLastCalledWith('pet.showInPetFailed', 'error');
- });
+it('never offers session binding to the main-only pet', () => {
+ expect(mount(options()).actions.map((action) => action.id)).toEqual(['pin', 'rename', 'fork', 'hide', 'archive']);
});
diff --git a/ui/src/components/workbench/useSessionActions.tsx b/ui/src/components/workbench/useSessionActions.tsx
index 47f8a8ee3..6e613e6d7 100644
--- a/ui/src/components/workbench/useSessionActions.tsx
+++ b/ui/src/components/workbench/useSessionActions.tsx
@@ -1,7 +1,7 @@
import type * as React from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Archive, EyeOff, GitFork, Hash, PawPrint, Pencil, Pin, PinOff } from 'lucide-react';
+import { Archive, EyeOff, GitFork, Hash, Pencil, Pin, PinOff } from 'lucide-react';
import { useApi } from '../../context/ApiContext';
import type { WorkbenchSession } from '../../context/ApiContext';
@@ -9,9 +9,7 @@ import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';
import { useWorkbenchProjectsActions } from '../../context/WorkbenchProjectsContext';
import { useToast } from '../../context/ToastContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
-import { canShowInDesktopPet } from '../../lib/desktopShell';
import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';
-import { petBridge } from '../../pet/petBridge';
import { archiveRequestIsLive, isSessionReadOnly } from './sessionArchived';
import { ArchiveSessionDialog } from './ArchiveSessionDialog';
import type { SessionActionDescriptor } from './sessionActions';
@@ -173,16 +171,6 @@ export const useSessionActions = ({
});
}, [target, api.setSessionVisibility, showToast, t]);
- const showInPet = useCallback(() => {
- if (!target) return;
- petBridge.showInPet(target.id).then(
- ({ shown }) => {
- if (!shown) showToast(t('pet.showInPetOff'), 'warning');
- },
- () => showToast(t('pet.showInPetFailed'), 'error'),
- );
- }, [target, showToast, t]);
-
const actions = useMemo<SessionActionDescriptor[]>(() => {
if (!target) return [];
const canFork = Boolean(target.native_session_id);
@@ -234,17 +222,6 @@ export const useSessionActions = ({
onSelect: () => void fork(),
});
}
- // Only a desktop shell with a pet can take the session; a browser tab or
- // an older shell never sees the row.
- if (canShowInDesktopPet()) {
- rows.push({
- id: 'pet',
- group: 'continue',
- icon: PawPrint,
- label: t('workbench.sessionShowInPet'),
- onSelect: showInPet,
- });
- }
rows.push({
id: 'hide',
group: 'continue',
@@ -273,7 +250,6 @@ export const useSessionActions = ({
togglePinned,
onRenameStart,
fork,
- showInPet,
hide,
requestArchive,
archiveHint,
diff --git a/ui/src/context/WorkbenchInboxContext.ts b/ui/src/context/WorkbenchInboxContext.ts
index 64f8eaad7..60a9c09c5 100644
--- a/ui/src/context/WorkbenchInboxContext.ts
+++ b/ui/src/context/WorkbenchInboxContext.ts
@@ -14,6 +14,8 @@ export interface InboxState {
* each session row from this (a session with unread may sit past the first
* inbox page, so the feed array alone isn't a complete source). */
unreadBySession: Record<string, number>;
+ /** A whole-account unread snapshot has applied. Missing means unknown. */
+ unreadLoaded?: boolean;
/** Sum of ``unreadBySession`` — the Inbox nav badge. */
totalUnread: number;
/** Number of sessions with ≥1 unread reply — the header "N unread" count. */
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 58b3dde60..b7836fabc 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -1002,6 +1002,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
() => ({
inboxSessions,
unreadBySession,
+ unreadLoaded,
totalUnread,
unreadSessions,
nextCursor,
@@ -1016,6 +1017,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
activateFeed,
inboxSessions,
unreadBySession,
+ unreadLoaded,
totalUnread,
unreadSessions,
nextCursor,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b34f45daa..091f7bea6 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3177,7 +3177,6 @@
"sessionReference": "Reference this session",
"sessionFork": "Fork session",
"sessionForkUnavailable": "This session has no native agent session to fork yet.",
- "sessionShowInPet": "Show in pet",
"sessionHideToBackground": "Hide to background",
"sessionHiddenToast": "Hidden to background · Find it in Agents → Runs",
"sessionArchive": "Archive session",
@@ -5926,14 +5925,10 @@
"unreadBadge_one": "{{count}} unread reply",
"unreadBadge_other": "{{count}} unread replies",
"setupPending": "Finish setting up in Avibe to talk to your agent here.",
- "showInPetOff": "The session is set for the pet. Turn on Show Pet in the Avibe tray menu to see it.",
- "showInPetFailed": "The pet could not show this session.",
"openAvibe": "Open Avibe",
"toggle": "Show or hide the pet panel",
"panel": "Pet panel",
"untitled": "Untitled session",
- "chooseSession": "Choose a session",
- "switchSession": "Switch session",
"openInAvibe": "Open in Avibe",
"inputPlaceholder": "Message Vibey…",
"send": "Send",
@@ -5941,12 +5936,11 @@
"moreInAvibe": "More replies in Avibe",
"empty": "No messages yet. Say something to get started.",
"vaultRequest": "Approval needed — open in Avibe",
- "noSessions": "No active sessions yet. Start one in Avibe.",
"mainAgent": "Vibey",
"mainAgentTitle": "Vibey",
"thinking": "Thinking",
"waiting": "Waiting",
- "repliedPrefix": "Replied:",
+ "repliedPrefix": "Replied: {{text}}",
"untitledTask": "Untitled task",
"dismiss": "Dismiss task",
"voiceContinue": "Continue voice input",
@@ -5982,7 +5976,7 @@
"unknown": "In progress"
},
"stop": {
- "stop": "Stop",
+ "stop": "Stop: {{title}}",
"pause": "Pause",
"confirmStop": "Stop?",
"confirmPause": "Pause?",
@@ -5994,8 +5988,24 @@
},
"failedPrefix": "Didn't run:",
"fixInAvibe": "Fix it in Avibe",
- "talkToVibey": "Talk to Vibey",
- "noChatProject": "Create a project in Avibe first, so Vibey has a place for this conversation.",
- "vibeyUnavailable": "Couldn't open the conversation with Vibey. Try again in a moment."
+ "vibeyUnavailable": "Couldn't open the conversation with Vibey. Try again in a moment.",
+ "unknownProject": "Conversation",
+ "unknownAgent": "Agent",
+ "needsAuthorization": "Needs your approval",
+ "replied": "Replied",
+ "referenceSession": "Reference session: {{title}}",
+ "authorize": "Review",
+ "recentTurns": "Recent turns",
+ "collapseHistory": "Hide history",
+ "platform": {
+ "slack": "Slack",
+ "discord": "Discord",
+ "telegram": "Telegram",
+ "feishu": "Feishu",
+ "lark": "Lark",
+ "wechat": "WeChat",
+ "unknown": "IM"
+ },
+ "removeReference": "Remove reference to {{title}}"
}
}
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c73f36529..4cc2ba613 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3177,7 +3177,6 @@
"sessionReference": "引用该会话",
"sessionFork": "复刻会话",
"sessionForkUnavailable": "此会话还没有可复刻的原生 Agent 会话。",
- "sessionShowInPet": "在桌宠中显示",
"sessionHideToBackground": "隐藏到后台",
"sessionHiddenToast": "已隐藏到后台 · 可在 Agents→Runs 找回",
"sessionArchive": "归档会话",
@@ -5926,14 +5925,10 @@
"unreadBadge_one": "{{count}} 条未读回复",
"unreadBadge_other": "{{count}} 条未读回复",
"setupPending": "先在 Avibe 里完成设置,就可以在这里和 agent 对话了。",
- "showInPetOff": "桌宠已切换到这个会话。在 Avibe 托盘菜单中打开“显示桌宠”即可看到。",
- "showInPetFailed": "桌宠无法显示这个会话。",
"openAvibe": "打开 Avibe",
"toggle": "展开或收起宠物面板",
"panel": "宠物面板",
"untitled": "未命名会话",
- "chooseSession": "选择一个会话",
- "switchSession": "切换会话",
"openInAvibe": "在 Avibe 中打开",
"inputPlaceholder": "和歪比说…",
"send": "发送",
@@ -5941,12 +5936,11 @@
"moreInAvibe": "更多回复请在 Avibe 中查看",
"empty": "还没有消息,说点什么开始吧。",
"vaultRequest": "需要授权,在 Avibe 中打开",
- "noSessions": "还没有进行中的会话,先在 Avibe 里新建一个。",
"mainAgent": "歪比",
"mainAgentTitle": "歪比",
"thinking": "思考中",
"waiting": "等待中",
- "repliedPrefix": "已回复:",
+ "repliedPrefix": "已回复:{{text}}",
"untitledTask": "未命名任务",
"dismiss": "移除任务",
"voiceContinue": "继续语音输入",
@@ -5982,7 +5976,7 @@
"unknown": "处理中"
},
"stop": {
- "stop": "停止",
+ "stop": "停止:{{title}}",
"pause": "暂停",
"confirmStop": "停止?",
"confirmPause": "暂停?",
@@ -5994,8 +5988,24 @@
},
"failedPrefix": "没跑起来:",
"fixInAvibe": "在 Avibe 中处理",
- "talkToVibey": "和歪比对话",
- "noChatProject": "先在 Avibe 里建一个项目,和歪比的对话需要放在项目里。",
- "vibeyUnavailable": "没能打开和歪比的对话,请稍后再试。"
+ "vibeyUnavailable": "没能打开和歪比的对话,请稍后再试。",
+ "unknownProject": "会话",
+ "unknownAgent": "Agent",
+ "needsAuthorization": "需要你授权",
+ "replied": "已回复",
+ "referenceSession": "引用会话:{{title}}",
+ "authorize": "授权",
+ "recentTurns": "最近几轮",
+ "collapseHistory": "收起记录",
+ "platform": {
+ "slack": "Slack",
+ "discord": "Discord",
+ "telegram": "Telegram",
+ "feishu": "飞书",
+ "lark": "Lark",
+ "wechat": "微信",
+ "unknown": "IM"
+ },
+ "removeReference": "移除对 {{title}} 的引用"
}
}
diff --git a/ui/src/lib/desktopShell.ts b/ui/src/lib/desktopShell.ts
index 26d91a285..a20c533a4 100644
--- a/ui/src/lib/desktopShell.ts
+++ b/ui/src/lib/desktopShell.ts
@@ -5,7 +5,7 @@ declare global {
readonly __AVIBE_DESKTOP_VERSION__?: string;
/** The macOS shell grants Tauri window dragging to this page. */
readonly __AVIBE_DESKTOP_DRAG__?: true;
- /** The shell has a desktop pet this page can bind a session to (`pet_bind`). */
+ /** The shell supports the desktop pet IPC. Conversation selection is main-only. */
readonly __AVIBE_DESKTOP_PET__?: true;
}
}
@@ -38,9 +38,8 @@ export function desktopDragRegion(): '' | undefined {
}
/**
- * True when this Workbench runs in a desktop shell that can show a session in
- * its pet. An older shell has no pet, so the page offers "Show in pet" only on
- * this marker, never on the shell marker alone.
+ * Retained capability probe for the native shell's frontend contract.
+ * Main-only mini no longer exposes a Workbench "Show in pet" action.
*/
export function canShowInDesktopPet(): boolean {
return isDesktopShell() && window.__AVIBE_DESKTOP_PET__ === true;
diff --git a/ui/src/pet/PetAvatar.tsx b/ui/src/pet/PetAvatar.tsx
index 13b402dd9..af0b6e247 100644
--- a/ui/src/pet/PetAvatar.tsx
+++ b/ui/src/pet/PetAvatar.tsx
@@ -30,16 +30,10 @@ const POSES: Record<PetPose, string> = {
// nothing; any other pose keeps breathing while the window is visible.
const BREATHING_SETTLE_MS = 30 * 1000;
-/**
- * `badge`: unread replies (top right). `activities`: background work for the
- * session (delegated runs, watches, tasks), shown as a small count at the
- * bottom left so it is visible while the pet is collapsed; it never changes
- * the pose, which reflects only the agent itself.
- */
-export const PetAvatar: React.FC<{ pose: PetPose; badge?: number; activities?: number }> = ({
+/** The caller derives the pose from eligible activities; badge counts unread replies. */
+export const PetAvatar: React.FC<{ pose: PetPose; badge?: number }> = ({
pose,
badge = 0,
- activities = 0,
}) => {
const { t } = useTranslation();
return (
@@ -55,14 +49,6 @@ export const PetAvatar: React.FC<{ pose: PetPose; badge?: number; activities?: n
{badge > 99 ? '99+' : badge}
</span>
)}
- {activities > 0 && (
- <span
- className="absolute bottom-1 left-1 flex h-5 min-w-5 items-center justify-center rounded-full border border-mint/40 bg-mint-soft px-1.5 text-[11px] font-semibold leading-none text-mint-ink"
- aria-label={t('chat.activities.running', { count: activities })}
- >
- {activities > 99 ? '99+' : activities}
- </span>
- )}
</div>
);
};
diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsx
index d3dca7b46..f3edcf737 100644
--- a/ui/src/pet/PetPage.test.tsx
+++ b/ui/src/pet/PetPage.test.tsx
@@ -7,6 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type {
RunningAgentsResult,
+ InboxSession,
+ VaultRequest,
WorkbenchEventHandlers,
WorkbenchMessage,
WorkbenchSession,
@@ -94,7 +96,10 @@ const idleTurn = {
let setupDone = true;
let sessionReads: Record<string, () => Promise<WorkbenchSessionReadResult>> = {};
let tails: Record<string, WorkbenchMessage[]> = {};
-let switcherSessions: WorkbenchSession[] = [];
+let mainId: string | null = 'S';
+let inboxSessions: InboxSession[] = [];
+let unreadLoaded = true;
+let inboxLoading = false;
let unreadBySession: Record<string, number> = {};
let runningAgents: RunningAgentsResult = { ok: true, agents: [], counts: { total: 0, active: 0, idle: 0, orphan: 0, by_backend: {} } };
const workingIn = (sessionId: string): RunningAgentsResult => ({
@@ -118,14 +123,10 @@ const markRead = vi.fn(async (): Promise<boolean> => {
});
const api = {
+ cancelSession: vi.fn(async (_payload: unknown) => ({ ok: true })),
setHarnessWatchEnabled: vi.fn(async () => ({ ok: true })),
setHarnessTaskEnabled: vi.fn(async () => ({ ok: true })),
- getMainSession: vi.fn(() => {
- const binding = (window as unknown as { __AVIBE_PET_BINDING__?: unknown }).__AVIBE_PET_BINDING__;
- return typeof binding === 'string' && binding
- ? api.getSessionResult(binding)
- : Promise.resolve({ status: 404, session: null });
- }),
+ getMainSession: vi.fn((): Promise<WorkbenchSessionReadResult> => mainId ? api.getSessionResult(mainId) : Promise.resolve({ status: 403, session: null })),
getConfig: vi.fn(async () => (setupDone
? { mode: 'self_host', setup_state: { needs_setup: false } }
: { mode: 'self_host', setup_state: { needs_setup: true } })),
@@ -133,9 +134,9 @@ const api = {
? sessionReads[id]()
: Promise.resolve({ status: 200, session: session(id), capabilities: { can_chat: true } }))),
listSessionMessages: vi.fn(async (id: string) => ({ messages: tails[id] ?? [], next_after_id: null, next_before_id: null })),
- getTurnState: vi.fn(async () => idleTurn),
- listSessions: vi.fn(async () => ({ sessions: switcherSessions, next_before_id: null })),
- getVaultRequests: vi.fn(async () => ({ requests: [] })),
+ getTurnState: vi.fn(async (_id?: string, _options?: unknown) => idleTurn),
+ listSessions: vi.fn(async () => ({ sessions: [], next_before_id: null })),
+ getVaultRequests: vi.fn(async (_filter?: { session?: string }, _options?: unknown): Promise<{ requests: VaultRequest[] }> => ({ requests: [] })),
getRunningAgents: vi.fn(async (): Promise<RunningAgentsResult> => runningAgents),
sendSessionMessage: vi.fn(async () => message('sent', 'S', { author: 'user', type: 'user' })),
connectWorkbenchEvents: (h: WorkbenchEventHandlers) => {
@@ -161,7 +162,7 @@ vi.mock('@/context/WorkbenchInboxContext', async () => {
inboxListeners.add(listener);
return () => inboxListeners.delete(listener);
}, () => inboxVersion);
- return { unreadBySession: { ...unreadBySession }, markRead };
+ return { unreadBySession: { ...unreadBySession }, inboxSessions, unreadLoaded, loading: inboxLoading, markRead };
},
};
});
@@ -184,34 +185,27 @@ Object.defineProperty(window, 'localStorage', { value: memoryStorage(), configur
let windowFocused = true;
Object.defineProperty(document, 'hasFocus', { value: () => windowFocused, configurable: true });
-// The dev bridge's stand-in for the shell: the binding and its revision.
-const DEV_BINDING_KEY = 'avibe.pet.devBinding';
-const devBinding = (): { binding: string | null; revision: number } => {
- const stored = window.localStorage.getItem(DEV_BINDING_KEY);
- return stored ? JSON.parse(stored) : { binding: null, revision: 0 };
+// Configure the authoritative endpoint independently from legacy shell state.
+const mainSession = (sessionId: string | null) => { mainId = sessionId; };
+const resolveMainAs = (sessionId: string | null) => {
+ mainId = sessionId;
+ return emit((h) => h.onAuthorizationChanged?.({}));
};
-const devBind = (sessionId: string | null) => {
- const next = { binding: sessionId, revision: devBinding().revision + 1 };
- window.localStorage.setItem(DEV_BINDING_KEY, JSON.stringify(next));
- return next;
-};
-// A change made elsewhere (the main window's "Show in pet"), reported by event.
-const bound = (sessionId: string | null) => act(() => {
- const next = devBind(sessionId);
- window.dispatchEvent(new CustomEvent(PET_BOUND_EVENT, { detail: { session_id: sessionId, revision: next.revision } }));
-});
const shellBound = (sessionId: string | null, revision: number) => act(() => {
window.dispatchEvent(new CustomEvent(PET_BOUND_EVENT, { detail: { session_id: sessionId, revision } }));
});
const summon = (intent: 'listen' | 'show' | 'release') => act(() => {
window.dispatchEvent(new CustomEvent(PET_SUMMON_EVENT, { detail: { intent } }));
});
-// v2 puts the exchange behind the main card. Tests of the exchange explicitly
+// The speech bubble holds the exchange. Tests of the exchange explicitly
// open it; raw summon remains available for collapsed/detail visibility tests.
-const showDetail = async () => {
+const showCards = async () => {
summon('show');
await act(async () => new Promise((resolve) => setTimeout(resolve, 15)));
- const main = document.querySelector('.pet-mini-card[role="button"]');
+};
+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);
};
const pose = () => document.querySelector('.pet-avatar')?.getAttribute('data-pose');
@@ -231,19 +225,19 @@ beforeEach(async () => {
api.getRunningAgents.mockClear();
sessionReads = {};
tails = Object.fromEntries(['S', 'A', 'B', 'C'].map((id) => [id, [message(`u-${id}`, id, { author: 'user', type: 'user', text: `Session ${id}` })]]));
- switcherSessions = [];
+ mainId = 'S';
+ inboxSessions = [];
+ unreadLoaded = true;
+ inboxLoading = false;
unreadBySession = {};
+ api.getVaultRequests.mockReset().mockResolvedValue({ requests: [] });
markRead.mockClear();
inboxVersion = 0;
api.getSessionResult.mockClear();
+ api.listSessionMessages.mockClear();
api.listSessions.mockClear();
api.getMainSession.mockReset();
- api.getMainSession.mockImplementation(() => {
- const binding = (window as unknown as { __AVIBE_PET_BINDING__?: unknown }).__AVIBE_PET_BINDING__;
- return typeof binding === 'string' && binding
- ? api.getSessionResult(binding)
- : Promise.resolve({ status: 404, session: null });
- });
+ api.getMainSession.mockImplementation(() => mainId ? api.getSessionResult(mainId) : Promise.resolve({ status: 403, session: null }));
window.localStorage.clear();
});
@@ -285,107 +279,149 @@ describe('PetPage setup', () => {
});
});
-describe('PetPage binding', () => {
- it('keeps B bound when a late 404 for A arrives after switching', async () => {
- const lateA = deferred<WorkbenchSessionReadResult>();
- sessionReads.A = () => lateA.promise;
- devBind('A');
+
+describe('main-only resolution', () => {
+ const mainResult = (): WorkbenchSessionReadResult => ({ status: 200, session: session('S'), capabilities: { can_chat: true } });
+
+ it('ignores legacy ready/bound state and never selects another session', async () => {
+ const legacy = JSON.stringify({ binding: 'legacy', revision: 9 });
+ localStorage.setItem('avibe.pet.devBinding', legacy);
+ const invoke = vi.fn(async (command: string) => command === 'pet_ready'
+ ? { binding: 'legacy', revision: 9, dismissed_ids: ['unrelated'], summon_pending: { intent: 'listen' } }
+ : { 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 });
render(<PetPage />);
- await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('A'));
- await bound('B');
- summon('listen');
- await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('B'));
- await act(async () => lateA.resolve({ status: 404, session: null }));
+ await userEvent.type(await screen.findByRole('textbox'), 'main only{Enter}');
+ await shellBound('another-session', 10);
+ expect(api.sendSessionMessage).toHaveBeenCalledWith('S', { text: 'main only' });
+ expect(api.getSessionResult).not.toHaveBeenCalledWith('legacy');
+ expect(api.getSessionResult).not.toHaveBeenCalledWith('another-session');
+ expect(invoke.mock.calls.some(([command]) => command === 'pet_bind' || command === 'pet_unbind')).toBe(false);
+ expect(localStorage.getItem('avibe.pet.devBinding')).toBe(legacy);
await showDetail();
- expect(await screen.findAllByText('Session B')).toBeTruthy();
- expect(devBinding().binding).toBe('B');
+ expect(screen.queryByText('pet.switchSession')).toBeNull();
+ expect(api.listSessions).not.toHaveBeenCalled();
+ const { petShell } = await import('./petShell');
+ expect(petShell.dismissed()).not.toContain('unrelated');
});
- it('clears a persisted binding to a Runtime-owned session and opens the switcher', async () => {
- sessionReads['ses-workspace-notices'] = async () => ({
- status: 200,
- session: session('ses-workspace-notices', { visibility: 'system' }),
+ it.each([null, 'legacy-session', 'ses_main'])('normalizes persisted binding %s to main while keeping closes document-local', async (persisted) => {
+ mainSession('ses_main');
+ canUseAgents = true;
+ runningAgents = workingIn('T');
+ const invoke = vi.fn(async (command: string) => {
+ if (command === 'pet_ready') return { binding: persisted, revision: 4, dismissed_ids: [], summon_pending: null };
+ if (command === 'pet_bind') return { binding: 'ses_main', revision: 5 };
+ return { panel_side: 'left', panel_edge: 'bottom' };
});
- switcherSessions = [session('fresh', { title: 'Brand new' })];
- devBind('ses-workspace-notices');
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ render(<PetPage />); summon('show');
+ const close = await screen.findByLabelText('pet.dismiss');
+ if (persisted !== 'ses_main') await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'ses_main' }));
+ await userEvent.click(close);
+ const { petShell } = await import('./petShell');
+ await waitFor(() => expect(petShell.dismissed()).toEqual(['T']));
+ expect(invoke.mock.calls.some(([command]) => command === 'pet_set_dismissed')).toBe(false);
+ await emit((h) => h.onConnected?.());
+ expect(invoke.mock.calls.filter(([command]) => command === 'pet_bind')).toHaveLength(persisted === 'ses_main' ? 0 : 1);
+ expect(invoke.mock.calls.some(([command]) => command === 'pet_unbind')).toBe(false);
+ });
+
+ it('does not retry failed main normalization until the authorization epoch changes', async () => {
+ mainSession('ses_main');
+ const invoke = vi.fn(async (command: string) => {
+ if (command === 'pet_ready') return { binding: 'legacy-session', revision: 4, dismissed_ids: [], summon_pending: null };
+ if (command === 'pet_bind') throw new Error('disk unavailable');
+ return { 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 });
render(<PetPage />);
- await waitFor(() => expect(devBinding().binding).toBeNull());
- summon('listen');
- expect(await screen.findByText('Brand new')).toBeTruthy();
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'ses_main' }));
+ await emit((h) => h.onConnected?.());
+ await emit((h) => h.onConnected?.());
+ expect(invoke.mock.calls.filter(([command]) => command === 'pet_bind')).toHaveLength(1);
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ await waitFor(() => expect(invoke.mock.calls.filter(([command]) => command === 'pet_bind')).toHaveLength(2));
});
- it('lists new sessions in the switcher and leaves out read-only ones', async () => {
- switcherSessions = [
- session('new', { title: 'No reply yet' }),
- session('old', { title: 'Archived', status: 'archived' }),
- ];
+ it.each(['reconnect', 'reactivation'])('recovers a failed main lookup on %s without a polling loop', async (trigger) => {
+ api.getMainSession.mockRejectedValueOnce(new Error('offline')).mockResolvedValue(mainResult());
render(<PetPage />);
+ await screen.findByText('pet.vibeyUnavailable');
+ expect(api.listSessionMessages).not.toHaveBeenCalled();
+ expect(api.getMainSession).toHaveBeenCalledTimes(1);
+ if (trigger === 'reconnect') await emit((h) => h.onConnected?.());
+ else {
+ act(() => { windowFocused = false; window.dispatchEvent(new Event('blur')); });
+ act(() => { windowFocused = true; window.dispatchEvent(new Event('focus')); });
+ }
summon('listen');
- expect(await screen.findByText('No reply yet')).toBeTruthy();
- expect(screen.queryByText('Archived')).toBeNull();
- await userEvent.click(screen.getByText('No reply yet'));
- expect(devBinding().binding).toBe('new');
- });
-});
-
-describe('PetPage Vibey conversation', () => {
- const mainResult = (id = 'V'): WorkbenchSessionReadResult => ({
- status: 200,
- session: session(id, { agent_name: 'vibey', agent_backend: 'vibey' }),
- capabilities: { can_chat: true },
- });
-
- it('binds the stable main session when nothing is bound', async () => {
- api.getMainSession.mockResolvedValue(mainResult());
- render(<PetPage />);
- await waitFor(() => expect(devBinding().binding).toBe('V'));
- expect(api.getMainSession).toHaveBeenCalled();
- });
-
- it('leaves an existing binding alone', async () => {
- devBind('S');
- render(<PetPage />);
- await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('S'));
+ await userEvent.type(await screen.findByRole('textbox'), 'recovered{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledWith('S', { text: 'recovered' });
+ expect(api.getMainSession).toHaveBeenCalledTimes(2);
});
- it('never re-binds a conversation that was cleared as invalid', async () => {
- api.getMainSession.mockResolvedValueOnce(mainResult());
- sessionReads.V = async () => ({ status: 404, session: null });
+ it.each([
+ [403, 'owner_only'], [409, 'main_session_invalid'], [409, 'main_session_archived'], [409, 'builtin_agent_unavailable'],
+ ])('keeps main unavailable for %s %s and offers Avibe', async (status) => {
+ api.getMainSession.mockResolvedValue({ status: Number(status), session: null });
render(<PetPage />);
- await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('V'));
- await waitFor(() => expect(devBinding().binding).toBeNull());
- await act(async () => new Promise((resolve) => setTimeout(resolve, 30)));
- expect(devBinding().binding).toBeNull();
+ await screen.findByText('pet.vibeyUnavailable');
+ expect(screen.getByRole('button', { name: 'pet.openInAvibe' })).toBeTruthy();
+ summon('listen');
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(api.listSessionMessages).not.toHaveBeenCalled();
+ expect(api.listSessions).not.toHaveBeenCalled();
});
- it('offers the stable main session in the switcher without requiring a project', async () => {
- switcherSessions = [session('B', { title: 'Another session' })];
- api.getMainSession.mockResolvedValueOnce({ status: 404, session: null });
- api.getMainSession.mockResolvedValue(mainResult());
+ it('discards main and transcript reads from the prior authorization before resolving again', async () => {
+ const oldMain = deferred<WorkbenchSessionReadResult>();
+ const freshMain = deferred<WorkbenchSessionReadResult>();
+ api.getMainSession.mockReturnValueOnce(oldMain.promise).mockReturnValueOnce(freshMain.promise);
render(<PetPage />);
- summon('show');
- await userEvent.click(await screen.findByText('pet.talkToVibey'));
- await waitFor(() => expect(devBinding().binding).toBe('V'));
+ await waitFor(() => expect(api.getMainSession).toHaveBeenCalledTimes(1));
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ await waitFor(() => expect(api.getMainSession).toHaveBeenCalledTimes(2));
+ await act(async () => oldMain.resolve(mainResult()));
+ expect(api.listSessionMessages).not.toHaveBeenCalled();
+ await act(async () => freshMain.resolve({ status: 403, session: null }));
+ await screen.findByText('pet.vibeyUnavailable');
+ expect(api.listSessionMessages).not.toHaveBeenCalled();
});
- it('shows an error when the main-session endpoint resolves without a session', async () => {
- api.getMainSession.mockResolvedValue({ status: 409, session: null });
- render(<PetPage />);
- summon('show');
- await userEvent.click(await screen.findByText('pet.talkToVibey'));
- expect(await screen.findByText('pet.vibeyUnavailable')).toBeTruthy();
+ it('keeps live updates working after main is reauthorized with the same id', async () => {
+ render(<PetPage />); await showDetail();
+ 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();
});
- it('does not offer Vibey to someone who cannot chat', async () => {
- canChat = false;
- switcherSessions = [session('B', { title: 'Another session' })];
- render(<PetPage />);
- summon('show');
- expect(await screen.findByText('Another session')).toBeTruthy();
- expect(screen.queryByText('pet.talkToVibey')).toBeNull();
- expect(api.getMainSession).not.toHaveBeenCalled();
+ it('keeps a draft through a transient resolution failure and fences a late transcript after access is lost', async () => {
+ render(<PetPage />); summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'keep my words');
+ api.getMainSession.mockRejectedValueOnce(new Error('offline'));
+ await emit((h) => h.onConnected?.());
+ await screen.findByText('pet.vibeyUnavailable');
+ await emit((h) => h.onConnected?.());
+ summon('listen');
+ expect((await screen.findByRole('textbox') as HTMLTextAreaElement).value).toBe('keep my words');
+ const oldTail = deferred<{ messages: WorkbenchMessage[]; next_after_id: null; next_before_id: null }>();
+ api.listSessionMessages.mockReturnValueOnce(oldTail.promise);
+ await emit((h) => h.onConnected?.());
+ api.getMainSession.mockResolvedValue({ status: 403, session: null });
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ await act(async () => oldTail.resolve({ messages: [message('old-secret', 'S', { text: 'private stale text' })], next_after_id: null, next_before_id: null }));
+ await screen.findByText('pet.vibeyUnavailable');
+ expect(screen.queryByText('private stale text')).toBeNull();
+ expect(screen.queryByRole('textbox')).toBeNull();
});
+});
+describe('PetPage Vibey conversation', () => {
it('shows a turn the agent could not run, with the way to fix it', async () => {
tails.S = [
message('u', 'S', { author: 'user', type: 'user', text: 'hello' }),
@@ -395,7 +431,7 @@ describe('PetPage Vibey conversation', () => {
metadata: { event: 'backend_failure', failure_id: 'f', turn_id: 't', failure_next_step: 'models' },
}),
];
- devBind('S');
+ mainSession('S');
render(<PetPage />);
expect(await screen.findByText('pet.failedPrefix No model source yet.')).toBeTruthy();
await showDetail();
@@ -408,7 +444,7 @@ describe('PetPage state', () => {
it('offers an open quick-reply group in the panel without asking for attention', async () => {
const asking = message('q', 'S', { content: { quick_replies: ['Yes', 'No'] } });
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), asking];
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
expect(await screen.findByText('Yes')).toBeTruthy();
@@ -418,7 +454,7 @@ describe('PetPage state', () => {
it('asks for attention only for a pending vault request', async () => {
api.getVaultRequests.mockImplementation(async () => ({ requests: [{ id: 'v1', request_type: 'access' }] } as never));
try {
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(pose()).toBe('needs_input'));
} finally {
@@ -427,14 +463,14 @@ describe('PetPage state', () => {
});
it('derives Blocked from the first session read, with no provider row', async () => {
- sessionReads.S = async () => ({ status: 200, session: session('S', { agent_status: 'failed' }) });
- devBind('S');
+ sessionReads.S = async () => ({ status: 200, session: session('S', { agent_status: 'failed' }), capabilities: { can_chat: true } });
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(pose()).toBe('blocked'));
});
it('re-reads turn state on any runs.updated, even for another executor session', async () => {
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(api.getTurnState).toHaveBeenCalled());
const before = api.getTurnState.mock.calls.length;
@@ -450,7 +486,7 @@ describe('PetPage state', () => {
message('r3', 'S', { read_at: null }),
];
unreadBySession = { S: 2 };
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(pose()).toBe('ready'));
await showDetail();
@@ -464,7 +500,7 @@ describe('PetPage state', () => {
messages: tails[id] ?? [], next_after_id: null, next_before_id: 'older',
}));
unreadBySession = { S: 5 };
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
@@ -478,7 +514,7 @@ describe('PetPage other conversations', () => {
it('looks busy while another conversation\'s agent works, and the bound session stays idle', async () => {
canUseAgents = true;
runningAgents = workingIn('T');
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(pose()).toBe('running'));
expect(dataState()).toBe('idle');
@@ -489,7 +525,7 @@ describe('PetPage other conversations', () => {
it('keeps re-reading a started turn until the backend registers it', async () => {
canUseAgents = true;
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(api.getRunningAgents).toHaveBeenCalled());
// turn.start lands before the agent is active in the snapshot.
@@ -506,7 +542,7 @@ describe('PetPage other conversations', () => {
it('keeps re-reading a started turn after a failed read', async () => {
canUseAgents = true;
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(api.getRunningAgents).toHaveBeenCalled());
const before = api.getRunningAgents.mock.calls.length;
@@ -522,7 +558,7 @@ describe('PetPage other conversations', () => {
const { REFRESH_TRIGGERS } = await import('./useConversationAgentWorking');
canUseAgents = true;
runningAgents = workingIn('T');
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(pose()).toBe('running'));
for (const trigger of REFRESH_TRIGGERS) {
@@ -545,7 +581,7 @@ describe('PetPage other conversations', () => {
it('never reads other conversations without the agents permission', async () => {
runningAgents = workingIn('T');
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await waitFor(() => expect(api.getTurnState).toHaveBeenCalled());
expect(pose()).toBe('idle');
@@ -557,7 +593,7 @@ describe('PetPage review fixes', () => {
it('marks a rendered row read once, however often the inbox state changes', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null })];
unreadBySession = { S: 1 };
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await screen.findByText('reply r1');
@@ -570,14 +606,15 @@ describe('PetPage review fixes', () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
tails.B = [message('b1', 'B', { text: 'B only' })];
- devBind('A');
+ mainSession('A');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder');
await userEvent.type(input, 'hello{Enter}');
- await bound('B');
+ await resolveMainAs('B');
summon('listen');
- await screen.findByText('B only');
+ await screen.findByRole('textbox');
+ await waitFor(() => expect(api.listSessionMessages).toHaveBeenCalledWith('B', expect.anything()));
await act(async () => pending.resolve(message('a-sent', 'A', { author: 'user', type: 'user', text: 'sent to A' })));
// B neither shows A's row nor enters A's post-send Running grace.
expect(screen.queryByText('sent to A')).toBeNull();
@@ -585,7 +622,7 @@ describe('PetPage review fixes', () => {
expect(pose()).toBe('idle');
});
- it('acts on the binding pet_ready returns together with a pending summon', async () => {
+ it('acts on a pending summon while ignoring the legacy binding from pet_ready', async () => {
const ready = deferred<unknown>();
const invoke = vi.fn((command: string) => (command === 'pet_ready'
? ready.promise
@@ -595,30 +632,14 @@ describe('PetPage review fixes', () => {
render(<PetPage />);
// The surface is mounted and subscribed before the shell answers.
await screen.findByLabelText('pet.toggle');
- await act(async () => ready.resolve({ binding: 'S', revision: 1, summon_pending: { intent: 'listen' } }));
- // The summon opens the bound session's input, not the switcher.
+ await act(async () => ready.resolve({ binding: 'legacy', revision: 1, summon_pending: { intent: 'listen' } }));
+ // The summon opens the resolved main's input.
expect(await screen.findByLabelText('pet.inputPlaceholder')).toBeTruthy();
expect(api.listSessions).not.toHaveBeenCalled();
});
});
describe('PetPage review fixes, round 2', () => {
- it('does not mark replies read while the switcher hides them', async () => {
- tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null })];
- unreadBySession = { S: 1 };
- switcherSessions = [session('S'), session('T')];
- devBind('S');
- render(<PetPage />);
- await showDetail();
- await screen.findByText('reply r1');
- await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
- // A newer reply arrives while the user is looking at the switcher.
- await userEvent.click(screen.getByLabelText('pet.switchSession'));
- await screen.findAllByText('Session T');
- await emit((h) => h.onMessageNew?.(message('r2', 'S', { read_at: null })));
- await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
- expect(markRead).toHaveBeenCalledTimes(1);
- });
it('retries a failed mark-read the next time the reply is shown', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null })];
@@ -626,7 +647,7 @@ describe('PetPage review fixes, round 2', () => {
markRead.mockImplementationOnce(async (): Promise<boolean> => {
throw new Error('offline');
});
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
@@ -641,7 +662,7 @@ describe('PetPage review fixes, round 2', () => {
it('keeps a draft typed after submitting when the send completes', async () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
@@ -656,7 +677,7 @@ describe('PetPage review fixes, round 3', () => {
it('sends a draft once however often Enter is pressed while the POST is pending', async () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder');
@@ -671,7 +692,7 @@ describe('PetPage review fixes, round 3', () => {
let visibility: DocumentVisibilityState = 'hidden';
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
try {
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await screen.findByText('reply r1');
@@ -687,21 +708,6 @@ describe('PetPage review fixes, round 3', () => {
}
});
- it('keeps a bind that lands while pet_ready is still answering', async () => {
- const ready = deferred<unknown>();
- const invoke = vi.fn((command: string) => (command === 'pet_ready'
- ? ready.promise
- : 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 });
- render(<PetPage />);
- await screen.findByLabelText('pet.toggle');
- // The shell moved to B (revision 2) after answering pet_ready at revision 1.
- await shellBound('B', 2);
- await act(async () => ready.resolve({ binding: 'A', revision: 1, summon_pending: null }));
- await showDetail();
- expect(await screen.findAllByText('Session B')).toBeTruthy();
- });
});
describe('PetPage independent sweep', () => {
@@ -712,7 +718,7 @@ describe('PetPage independent sweep', () => {
let visibility: DocumentVisibilityState = 'visible';
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
try {
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
@@ -731,28 +737,16 @@ describe('PetPage independent sweep', () => {
}
});
- it('lands a bound summon on the session even if the switcher was left open', async () => {
- switcherSessions = [session('S')];
- render(<PetPage />);
- await showDetail();
- expect(await screen.findAllByText('Session S')).toBeTruthy();
- act(() => {
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
- });
- await bound('S');
- summon('listen');
- expect(await screen.findByLabelText('pet.inputPlaceholder')).toBeTruthy();
- });
it('clears sent text even when the session changed while it was sending', async () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('A');
+ mainSession('A');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(input, 'deploy{Enter}');
- await bound('B');
+ await resolveMainAs('B');
summon('listen');
await act(async () => pending.resolve(message('a-sent', 'A', { author: 'user', type: 'user' })));
expect((screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement).value).toBe('');
@@ -761,9 +755,10 @@ 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 })];
unreadBySession = { S: 2 };
- devBind('S');
+ mainSession('S');
render(<PetPage />);
- await waitFor(() => expect(api.listSessionMessages).toHaveBeenCalled());
+ // The hidden history proves the initial read applied without marking it read.
+ await screen.findByText('reply r1');
// 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) {
@@ -777,54 +772,13 @@ describe('PetPage independent sweep', () => {
});
});
-describe('PetPage review fixes, round 4', () => {
- it('goes back to the binding the shell still holds when a pick cannot be persisted', async () => {
- const invoke = vi.fn((command: string) => {
- if (command === 'pet_ready') return Promise.resolve({ binding: 'A', revision: 1, summon_pending: null });
- if (command === 'pet_bind') return Promise.reject(new Error('disk full'));
- 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 });
- switcherSessions = [session('A'), session('B')];
- render(<PetPage />);
- await showDetail();
- expect(await screen.findAllByText('Session A')).toBeTruthy();
- await userEvent.click(screen.getByLabelText('pet.switchSession'));
- await userEvent.click(await screen.findByText('Session B'));
- await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'B' }));
- // The header shows the session the shell still holds.
- await waitFor(() => expect(api.getSessionResult).toHaveBeenLastCalledWith('A'));
- });
-});
-describe('PetPage review fixes, round 5', () => {
- it('stays unbound, without a validation loop, when the shell cannot persist a clear', async () => {
- sessionReads.A = async () => ({ status: 404, session: null });
- const invoke = vi.fn((command: string) => {
- if (command === 'pet_ready') return Promise.resolve({ binding: 'A', revision: 1, summon_pending: null });
- if (command === 'pet_unbind') return Promise.reject(new Error('disk full'));
- 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 });
- switcherSessions = [session('B')];
- render(<PetPage />);
- await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_unbind', { sessionId: 'A' }));
- await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
- await showDetail();
- // The invalid session is never offered as usable: the switcher shows.
- expect(await screen.findAllByText('Session B')).toBeTruthy();
- expect(api.getSessionResult.mock.calls.filter(([id]) => id === 'A')).toHaveLength(1);
- expect(invoke.mock.calls.filter(([command]) => command === 'pet_unbind')).toHaveLength(1);
- });
-});
describe('PetPage review fixes, round 6', () => {
it('accepts no input for a binding whose session has not been validated yet', async () => {
const validation = deferred<WorkbenchSessionReadResult>();
sessionReads.S = () => validation.promise;
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
await screen.findByLabelText('pet.panel');
@@ -841,37 +795,17 @@ describe('PetPage review fixes, round 6', () => {
});
it('starts an empty draft when the binding changes', async () => {
- devBind('A');
+ mainSession('A');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(input, 'meant for A');
- await bound('B');
+ await resolveMainAs('B');
summon('listen');
- await screen.findAllByText('Session B');
+ await screen.findByRole('textbox');
expect((screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement).value).toBe('');
});
- it('keeps a pick made before pet_ready answers over the older answer', async () => {
- const ready = deferred<unknown>();
- const invoke = vi.fn((command: string) => {
- if (command === 'pet_ready') return ready.promise;
- if (command === 'pet_bind') return Promise.resolve({ binding: 'B', revision: 2, shown: false });
- 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 });
- switcherSessions = [session('B')];
- render(<PetPage />);
- await userEvent.click(await screen.findByLabelText('pet.toggle'));
- await userEvent.click(await screen.findByText('Session B'));
- await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'B' }));
- // The shell answered pet_ready at revision 1, before it applied the pick.
- await act(async () => ready.resolve({ binding: 'A', revision: 1, summon_pending: null }));
- await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
- expect(api.getSessionResult).not.toHaveBeenCalledWith('A');
- expect(api.getSessionResult).toHaveBeenLastCalledWith('B');
- });
});
describe('PetPage review fixes, round 7', () => {
@@ -908,7 +842,7 @@ describe('PetPage review fixes, round 8', () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { text: 'first reply' })];
return true;
});
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r1'));
@@ -925,12 +859,12 @@ describe('PetPage review fixes, round 8', () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q', 'S', { content: { quick_replies: ['Yes', 'No'] } })];
- devBind('S');
+ mainSession('S');
render(<PetPage />);
- summon('listen');
- const input = await screen.findByLabelText('pet.inputPlaceholder');
await showDetail();
await userEvent.click(await screen.findByText('Yes'));
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
await userEvent.type(input, 'also this{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
await act(async () => pending.resolve(message('sent', 'S', { author: 'user', type: 'user' })));
@@ -939,14 +873,14 @@ describe('PetPage review fixes, round 8', () => {
it('does not clear a draft typed in another session by an older send', async () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('A');
+ mainSession('A');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(input, 'continue{Enter}');
- await bound('B');
+ await resolveMainAs('B');
summon('listen');
- await screen.findAllByText('Session B');
+ await screen.findByRole('textbox');
const inputB = screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(inputB, 'continue');
await act(async () => pending.resolve(message('a-sent', 'A', { author: 'user', type: 'user' })));
@@ -955,7 +889,7 @@ describe('PetPage review fixes, round 8', () => {
});
describe('PetPage review fixes, round 9', () => {
- it('counts own running sub-tasks in the collapsed busy pose', async () => {
+ it('does not turn background definitions into visible team activity', async () => {
api.getTurnState.mockImplementation(async () => ({
...idleTurn,
background_activities: [
@@ -964,11 +898,11 @@ describe('PetPage review fixes, round 9', () => {
],
}) as never);
try {
- devBind('S');
+ mainSession('S');
render(<PetPage />);
- expect(await screen.findByLabelText('chat.activities.running')).toBeTruthy();
- expect(screen.getByLabelText('chat.activities.running').textContent).toBe('2');
- expect(pose()).toBe('running');
+ await screen.findByLabelText('pet.toggle');
+ await act(async () => {});
+ expect(pose()).toBe('idle');
} finally {
api.getTurnState.mockImplementation(async () => idleTurn);
}
@@ -980,7 +914,7 @@ describe('PetPage review fixes, round 10', () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null, text: 'unseen' })];
unreadBySession = { S: 1 };
windowFocused = false;
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await screen.findByText('unseen');
@@ -993,28 +927,6 @@ describe('PetPage review fixes, round 10', () => {
await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r1'));
});
- it('reverts a failed pick to the binding the shell confirmed, not an earlier pick', async () => {
- const binds: Record<string, ReturnType<typeof deferred<unknown>>> = { B: deferred(), C: deferred() };
- const invoke = vi.fn((command: string, args?: { sessionId?: string }) => {
- if (command === 'pet_ready') return Promise.resolve({ binding: 'A', revision: 1, summon_pending: null });
- if (command === 'pet_bind') return binds[args?.sessionId ?? ''].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 });
- switcherSessions = [session('A'), session('B'), session('C')];
- render(<PetPage />);
- await showDetail();
- await screen.findAllByText('Session A');
- await userEvent.click(screen.getByLabelText('pet.switchSession'));
- await userEvent.click(await screen.findByText('Session B'));
- await showDetail();
- await userEvent.click(await screen.findByLabelText('pet.switchSession'));
- await userEvent.click(await screen.findByText('Session C'));
- await act(async () => binds.B.reject(new Error('disk full')));
- await act(async () => binds.C.reject(new Error('disk full')));
- await waitFor(() => expect(api.getSessionResult).toHaveBeenLastCalledWith('A'));
- });
});
describe('PetPage review fixes, round 12', () => {
@@ -1038,7 +950,7 @@ describe('PetPage review fixes, round 13', () => {
it('offers no composer or quick replies without the chat capability', async () => {
canChat = false;
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q', 'S', { content: { quick_replies: ['Yes'] } })];
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
await screen.findByLabelText('pet.panel');
@@ -1055,7 +967,7 @@ describe('PetPage review fixes, round 13', () => {
capabilities: { can_chat: false },
});
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q', 'S', { content: { quick_replies: ['Yes'] } })];
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
await screen.findByLabelText('pet.panel');
@@ -1067,7 +979,7 @@ describe('PetPage review fixes, round 13', () => {
});
it('ends the post-send Running grace on an authoritative turn.end', async () => {
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder');
@@ -1081,69 +993,27 @@ describe('PetPage review fixes, round 13', () => {
it('drops what it read and unbinds when authorization to the session is lost', async () => {
tails.S = [message('r1', 'S', { text: 'private reply' })];
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await screen.findByText('private reply');
sessionReads.S = async () => ({ status: 403, session: null });
await emit((h) => h.onAuthorizationChanged?.({}));
await waitFor(() => expect(screen.queryByText('private reply')).toBeNull());
- await waitFor(() => expect(devBinding().binding).toBeNull());
+ await screen.findByText('pet.vibeyUnavailable');
});
});
describe('PetPage async closure', () => {
- // Binding order: the shell's revision decides, and picks reach it in order.
- it('sends picks one at a time and ignores a report older than the newest answer', async () => {
- const binds: Record<string, Deferred<unknown>> = { B: deferred(), C: deferred() };
- const invoke = vi.fn((command: string, args?: { sessionId?: string }) => {
- if (command === 'pet_ready') return Promise.resolve({ binding: 'A', revision: 1, summon_pending: null });
- if (command === 'pet_bind') return binds[args?.sessionId ?? ''].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 });
- switcherSessions = [session('A'), session('B'), session('C')];
- render(<PetPage />);
- await showDetail();
- await screen.findAllByText('Session A');
- await userEvent.click(screen.getByLabelText('pet.switchSession'));
- await userEvent.click(await screen.findByText('Session B'));
- await showDetail();
- await userEvent.click(await screen.findByLabelText('pet.switchSession'));
- await userEvent.click(await screen.findByText('Session C'));
- // C waits for B's answer, so the shell sees the picks in the user's order.
- expect(invoke.mock.calls.filter(([command]) => command === 'pet_bind')).toEqual([['pet_bind', { sessionId: 'B' }]]);
- await act(async () => binds.B.resolve({ binding: 'B', revision: 2, shown: false }));
- await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'C' }));
- await act(async () => binds.C.resolve({ binding: 'C', revision: 3, shown: false }));
- // B's own pet:bound arrives late, after the answer for C.
- await shellBound('B', 2);
- await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
- expect(api.getSessionResult).toHaveBeenLastCalledWith('C');
- expect(await screen.findAllByText('Session C')).toBeTruthy();
- });
// Read freshness: what was read under the old authorization goes at once.
- it('drops switcher rows at once when authorization changes, then re-reads', async () => {
- switcherSessions = [session('X', { title: 'Revoked project' })];
- render(<PetPage />);
- await showDetail();
- await screen.findByText('Revoked project');
- const reread = deferred<{ sessions: WorkbenchSession[]; next_before_id: null }>();
- api.listSessions.mockImplementationOnce(() => reread.promise);
- await emit((h) => h.onAuthorizationChanged?.({}));
- expect(screen.queryByText('Revoked project')).toBeNull();
- await act(async () => reread.resolve({ sessions: [session('Y', { title: 'Still allowed' })], next_before_id: null }));
- expect(await screen.findByText('Still allowed')).toBeTruthy();
- });
// Unknown outcomes are not treated as answers.
it('does not mark read from live rows that land before the first tail read', async () => {
const tail = deferred<{ messages: WorkbenchMessage[]; next_after_id: null; next_before_id: string | null }>();
api.listSessionMessages.mockImplementationOnce(() => tail.promise);
unreadBySession = { S: 3 };
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await screen.findByLabelText('pet.panel');
@@ -1164,7 +1034,7 @@ describe('PetPage async closure', () => {
it('keeps the draft and closes input when a send may have been admitted', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q', 'S', { content: { quick_replies: ['Yes'] } })];
api.sendSessionMessage.mockRejectedValueOnce(new ApiError('dispatch pending', 504, null));
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
@@ -1187,7 +1057,7 @@ describe('PetPage async closure', () => {
it('keeps input open when the server refused the send', async () => {
api.sendSessionMessage.mockRejectedValueOnce(new ApiError('conflict', 409, null));
- devBind('S');
+ mainSession('S');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder');
@@ -1252,7 +1122,7 @@ describe('PetPage live convergence', () => {
api.sendSessionMessage
.mockRejectedValueOnce(new ApiError('dispatch pending', 504, null))
.mockRejectedValueOnce(new ApiError('dispatch pending', 504, null));
- devBind('A');
+ mainSession('A');
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
@@ -1260,7 +1130,7 @@ describe('PetPage live convergence', () => {
await userEvent.type(input, 'to A{Enter}');
expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
- await bound('B');
+ await resolveMainAs('B');
summon('listen');
await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('B'));
const inputB = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
@@ -1269,7 +1139,7 @@ describe('PetPage live convergence', () => {
await userEvent.type(inputB, 'to B{Enter}');
expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
- await bound('A');
+ await resolveMainAs('A');
await settle();
expect(screen.getByText('newSession.sendUncertain')).toBeTruthy();
expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
@@ -1293,12 +1163,12 @@ describe('PetPage live convergence', () => {
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
render(<PetPage />);
- await showDetail();
+ summon('show');
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
await act(async () => first.resolve({ panel_side: 'left', panel_edge: 'bottom' }));
await screen.findByLabelText('pet.panel');
- await showDetail();
+ await showCards();
await waitFor(() => expect(invoke.mock.calls.filter(([c]) => c === 'pet_set_expanded')).toHaveLength(2));
await act(async () => second.reject(new Error('already expanded')));
await settle();
@@ -1317,7 +1187,7 @@ describe('PetPage live convergence', () => {
Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
render(<PetPage />);
- await showDetail();
+ summon('show');
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
await settle();
expect(screen.queryByLabelText('pet.panel')).toBeNull();
@@ -1329,11 +1199,11 @@ describe('PetPage live convergence', () => {
expect(markRead).not.toHaveBeenCalled();
});
- it('reads the session on a status event when no read has supplied it yet', async () => {
+ it('resolves main on reconnect when the initial read failed', async () => {
sessionReads.S = vi.fn()
.mockResolvedValueOnce({ status: 500, session: null })
.mockResolvedValue({ status: 200, session: session('S'), capabilities: { can_chat: true } });
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
await screen.findByLabelText('pet.panel');
@@ -1341,7 +1211,7 @@ describe('PetPage live convergence', () => {
expect(sessionReads.S).toHaveBeenCalledTimes(1);
expect(screen.getByLabelText('pet.keyboard.open').hasAttribute('disabled')).toBe(true);
- await emit((h) => h.onSessionStatus?.({ session_id: 'S', agent_status: 'idle' }));
+ await emit((h) => h.onConnected?.());
await waitFor(() => expect(sessionReads.S).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.getByLabelText('pet.keyboard.open').hasAttribute('disabled')).toBe(false));
summon('listen');
@@ -1351,9 +1221,9 @@ describe('PetPage live convergence', () => {
it('reads the tail on a live row when no tail read has landed yet', async () => {
api.listSessionMessages.mockRejectedValueOnce(new Error('network'));
- devBind('S');
+ mainSession('S');
render(<PetPage />);
- await showDetail();
+ await showCards();
await screen.findByLabelText('pet.panel');
await settle();
const reads = api.listSessionMessages.mock.calls.filter(([id]) => id === 'S').length;
@@ -1364,9 +1234,9 @@ describe('PetPage live convergence', () => {
});
it('re-reads the tail when the session is marked read in another window', async () => {
- devBind('S');
+ mainSession('S');
render(<PetPage />);
- await showDetail();
+ await showCards();
await screen.findByLabelText('pet.panel');
await settle();
const reads = api.listSessionMessages.mock.calls.filter(([id]) => id === 'S').length;
@@ -1384,7 +1254,7 @@ describe('PetPage review fixes, round 14', () => {
api.listSessionMessages.mockImplementationOnce(async (id: string) => ({
messages: tails[id] ?? [], next_after_id: null, next_before_id: 'older',
}));
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await showDetail();
expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
@@ -1394,7 +1264,7 @@ describe('PetPage review fixes, round 14', () => {
it('keeps an in-flight send locked across a page remount', async () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('S');
+ mainSession('S');
const first = render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder');
@@ -1411,7 +1281,7 @@ describe('PetPage review fixes, round 14', () => {
it('keeps an uncertain send locked across a page recheck', async () => {
api.sendSessionMessage.mockRejectedValueOnce(new ApiError('dispatch pending', 504, null));
- devBind('S');
+ mainSession('S');
const first = render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder');
@@ -1442,7 +1312,7 @@ describe('PetPage review fixes, round 14', () => {
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
render(<PetPage />);
- await showDetail();
+ summon('show');
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
expect(order).toEqual([true]);
// Collapse while expand is still in flight: Esc is not listening yet
@@ -1479,18 +1349,26 @@ describe('PetPage review fixes, round 14', () => {
describe('desktop mini v2 interaction contract', () => {
- // Match derive_session_harness_activities(): definitions carry durable
- // enabled/scheduled states, while delegated executions carry running.
- const activity = (id: string, item_kind: 'watch' | 'task' | 'agent_run', status = { watch: 'enabled', task: 'scheduled', agent_run: 'running' }[item_kind]) => ({
+ // Visible process rows replace background definitions; stopping keeps v2 timing.
+ const activity = (id: string, item_kind: 'watch' | 'task' | 'agent_run', status = 'running') => ({
id, item_kind, status, label: id, description: id, backend: 'codex',
runtime_key: id, session_id: 'S', kind: item_kind, started_at: '', updated_at: '',
});
const turn = (items: ReturnType<typeof activity>[]) => {
- api.getTurnState.mockResolvedValue({ ...idleTurn, background_activities: items } as never);
+ canUseAgents = true;
+ api.getTurnState.mockImplementation(async (id: string) => ({ ...idleTurn, in_flight: items.some((item) => item.id === id && item.status === 'running') }));
+ runningAgents = {
+ ok: true,
+ agents: items.map((item) => ({
+ ...workingIn(item.id).agents[0], backend: 'codex', title: item.label,
+ state: item.status === 'running' ? 'active' : 'idle',
+ trigger_source: item.item_kind === 'agent_run' ? 'agent' : 'human',
+ })),
+ counts: { total: items.length, active: items.length, idle: 0, orphan: 0, by_backend: {} },
+ };
};
beforeEach(() => {
- api.setHarnessWatchEnabled.mockReset().mockResolvedValue({ ok: true });
- api.setHarnessTaskEnabled.mockReset().mockResolvedValue({ ok: true });
+ api.cancelSession.mockReset().mockResolvedValue({ ok: true });
});
afterEach(() => {
vi.useRealTimers();
@@ -1503,22 +1381,22 @@ describe('desktop mini v2 interaction contract', () => {
const id = `${kind}:private`;
turn([activity(id, kind)]);
const pending = deferred<{ ok: boolean }>();
- const pause = kind === 'watch' ? api.setHarnessWatchEnabled : api.setHarnessTaskEnabled;
+ const pause = api.cancelSession;
pause.mockImplementationOnce(() => pending.promise);
- devBind('S'); render(<PetPage />); await showDetail();
- const stop = await screen.findByLabelText('pet.stop.confirmPause');
+ mainSession('S'); render(<PetPage />); await showCards();
+ const stop = await screen.findByLabelText('pet.stop.stop');
vi.useFakeTimers();
fireEvent.click(stop); fireEvent.click(stop);
- expect(screen.getByText('pet.stop.pausing')).toBeTruthy();
+ expect(screen.getByText('pet.stop.stopping')).toBeTruthy();
turn([]);
await emit((h) => h.onAuthorizationChanged?.({}));
expect(screen.queryByText(id)).toBeNull();
- expect(screen.queryByText('pet.stop.pausing')).toBeNull();
+ expect(screen.queryByText('pet.stop.stopping')).toBeNull();
// An authorized new version with the same id must not inherit old phases.
turn([{ ...activity(id, kind), label: 'Allowed replacement' }]);
- await emit((h) => h.onDefinitionsUpdated?.({}));
+ await emit((h) => h.onRunsUpdated?.({}));
expect(screen.getByText('Allowed replacement')).toBeTruthy();
- const freshStop = screen.getByLabelText('pet.stop.confirmPause');
+ const freshStop = screen.getByLabelText('pet.stop.stop');
expect(freshStop.hasAttribute('disabled')).toBe(false);
fireEvent.click(freshStop);
expect(freshStop.classList.contains('is-confirm')).toBe(true);
@@ -1527,7 +1405,7 @@ describe('desktop mini v2 interaction contract', () => {
else pending.reject(new Error('old pause failed'));
});
expect(freshStop.classList.contains('is-confirm')).toBe(true);
- expect(screen.queryByText('pet.stop.paused')).toBeNull();
+ expect(screen.queryByText('pet.stop.stopped')).toBeNull();
expect(screen.queryByText('pet.stop.failed')).toBeNull();
await act(async () => vi.advanceTimersByTime(4000));
expect(screen.getByText('Allowed replacement')).toBeTruthy();
@@ -1538,7 +1416,7 @@ describe('desktop mini v2 interaction contract', () => {
it('drops an exiting card on authorization change and ignores its already-queued removal', async () => {
const id = 'watch:private';
turn([activity(id, 'watch')]);
- devBind('S'); render(<PetPage />); await showDetail();
+ mainSession('S'); render(<PetPage />); await showCards();
vi.useFakeTimers();
const timeouts = vi.spyOn(window, 'setTimeout');
fireEvent.click(screen.getByLabelText('pet.dismiss'));
@@ -1551,7 +1429,7 @@ describe('desktop mini v2 interaction contract', () => {
expect(screen.queryByText(id)).toBeNull();
expect(document.querySelector('.is-leaving')).toBeNull();
turn([{ ...activity(id, 'watch'), label: 'New authorized card' }]);
- await emit((h) => h.onDefinitionsUpdated?.({}));
+ await emit((h) => h.onRunsUpdated?.({}));
await act(async () => { (remove as () => void)(); });
await act(async () => vi.advanceTimersByTime(500));
expect(screen.getByText('New authorized card')).toBeTruthy();
@@ -1563,26 +1441,28 @@ describe('desktop mini v2 interaction contract', () => {
const id = 'watch:private';
turn([activity(id, 'watch')]);
const pending = deferred<{ ok: boolean }>();
- api.setHarnessWatchEnabled.mockImplementationOnce(() => pending.promise);
- devBind('S'); render(<PetPage />); await showDetail();
- const stop = await screen.findByLabelText('pet.stop.confirmPause');
+ api.cancelSession.mockImplementationOnce(() => pending.promise);
+ mainSession('S'); render(<PetPage />); await showCards();
+ const stop = await screen.findByLabelText('pet.stop.stop');
fireEvent.click(stop); fireEvent.click(stop);
turn([]);
- await bound('B');
+ await resolveMainAs('B');
+ await emit((h) => h.onRunsUpdated?.({}));
expect(screen.queryByText(id)).toBeNull();
turn([{ ...activity(id, 'watch'), label: 'Fresh S card' }]);
- await bound('S');
- await showDetail();
+ await emit((h) => h.onRunsUpdated?.({}));
+ await resolveMainAs('S');
+ await showCards();
expect(await screen.findByText('Fresh S card')).toBeTruthy();
await act(async () => pending.resolve({ ok: true }));
- expect(screen.queryByText('pet.stop.paused')).toBeNull();
- expect(screen.getByLabelText('pet.stop.confirmPause').hasAttribute('disabled')).toBe(false);
+ expect(screen.queryByText('pet.stop.stopped')).toBeNull();
+ expect(screen.getByLabelText('pet.stop.stop').hasAttribute('disabled')).toBe(false);
});
it.each(['success', 'uncertain'])('preserves user text while fencing a late send %s after authorization changes', async (outcome) => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('S'); render(<PetPage />); summon('listen');
+ mainSession('S'); render(<PetPage />); summon('listen');
const input = await screen.findByRole('textbox');
await userEvent.type(input, 'my own words{Enter}');
await emit((h) => h.onAuthorizationChanged?.({}));
@@ -1599,14 +1479,14 @@ describe('desktop mini v2 interaction contract', () => {
expect(screen.queryByText('Old authorized response')).toBeNull();
// The async completion cannot clear the user's draft or open old detail.
if (outcome === 'success') expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('my own words');
- else expect(document.querySelector('.pet-mini-title')?.textContent).toBe('my own words');
+ else expect(petComposer.isUncertain('S')).toBe(true);
expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull();
});
it('keeps the document send ledger locked when an old page fails after remount', async () => {
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('S');
+ mainSession('S');
const first = render(<PetPage />);
summon('listen');
await userEvent.type(await screen.findByRole('textbox'), 'preserve this{Enter}');
@@ -1621,36 +1501,11 @@ describe('desktop mini v2 interaction contract', () => {
expect(petComposer.isUncertain('S')).toBe(true);
expect(petComposer.isSending()).toBe(false);
expect(screen.queryByRole('textbox')).toBeNull();
- expect(document.querySelector('.pet-mini-title')?.textContent).toBe('preserve this');
+ expect(petComposer.isUncertain('S')).toBe(true);
await userEvent.keyboard('{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
});
- it('discards an unauthorized queued pick while mirroring the already-sent native binding', async () => {
- const pending = deferred<unknown>();
- const invoke = vi.fn((command: string) => {
- if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
- if (command === 'pet_bind') return pending.promise;
- return Promise.resolve(null);
- });
- Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
- Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
- switcherSessions = [session('A'), session('B')];
- render(<PetPage />); await showDetail();
- await userEvent.click(screen.getByLabelText('pet.switchSession'));
- await userEvent.click(await screen.findByRole('button', { name: 'Session A' }));
- await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'A' }));
- await showDetail();
- await userEvent.click(screen.getByLabelText('pet.switchSession'));
- await userEvent.click(await screen.findByRole('button', { name: 'Session B' }));
- await emit((h) => h.onAuthorizationChanged?.({}));
- await act(async () => pending.resolve({ binding: 'A', revision: 2 }));
- expect(invoke.mock.calls.filter(([command]) => command === 'pet_bind')).toEqual([['pet_bind', { sessionId: 'A' }]]);
- const { petShell } = await import('./petShell');
- expect(petShell.currentBinding()).toBe('A');
- expect(await screen.findAllByText('Session A')).toHaveLength(2);
- expect(screen.queryByText('Session B')).toBeNull();
- });
// A tapped (not held) hotkey opens the text input once voice status is known.
const tapHotkey = () => { summon('listen'); summon('release'); };
@@ -1691,7 +1546,7 @@ describe('desktop mini v2 interaction contract', () => {
}
await withVoiceEnv(() => true, Dictation, async () => {
({ VoiceTranscriptionError: TranscriptionError } = await import('@/lib/voiceTranscription'));
- devBind('S'); render(<PetPage />); tapHotkey();
+ mainSession('S'); render(<PetPage />); tapHotkey();
const input = await screen.findByRole('textbox');
await userEvent.type(input, 'typed before voice');
await userEvent.click(await screen.findByLabelText('pet.voice.open'));
@@ -1712,7 +1567,7 @@ describe('desktop mini v2 interaction contract', () => {
asrCalls += 1;
return asrCalls === 1 ? Promise.resolve({ ok: true, json: async () => ({ available: true }) }) : status.promise;
}));
- devBind('S'); render(<PetPage />); tapHotkey();
+ mainSession('S'); render(<PetPage />); tapHotkey();
expect(await screen.findByLabelText('pet.voice.open')).toBeTruthy();
await emit((h) => h.onAuthorizationChanged?.({}));
await waitFor(() => expect(screen.queryByLabelText('pet.voice.open')).toBeNull());
@@ -1728,7 +1583,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));
- devBind('S'); render(<PetPage />); summon('listen');
+ mainSession('S'); render(<PetPage />); summon('listen');
expect(await screen.findByRole('textbox')).toBeTruthy();
expect(pose()).not.toBe('listening');
await act(async () => status.resolve({ ok: true, json: async () => ({ available: true }) }));
@@ -1744,7 +1599,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));
- devBind('S'); render(<PetPage />); await screen.findByText('Session S');
+ mainSession('S'); render(<PetPage />); await screen.findByText('Session S');
const avatar = screen.getByLabelText('pet.toggle');
vi.useFakeTimers();
try {
@@ -1783,7 +1638,7 @@ describe('desktop mini v2 interaction contract', () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ available: true }) })));
vi.resetModules();
({ PetPage } = await import('./PetPage'));
- devBind('S'); render(<PetPage />); tapHotkey();
+ mainSession('S'); render(<PetPage />); tapHotkey();
const input = await screen.findByRole('textbox');
await userEvent.type(input, 'typed before voice');
await userEvent.click(await screen.findByLabelText('pet.voice.open'));
@@ -1812,7 +1667,7 @@ describe('desktop mini v2 interaction contract', () => {
const { petBridge } = await import('./petBridge');
const report = vi.spyOn(petBridge, 'setHitRegions').mockResolvedValue(undefined);
try {
- devBind('S'); render(<PetPage />);
+ mainSession('S'); render(<PetPage />);
await screen.findByText('Session S');
const oldFrames = [...frames];
expect(oldFrames.length).toBeGreaterThan(0);
@@ -1845,7 +1700,7 @@ describe('desktop mini v2 interaction contract', () => {
try {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('result', 'S', { read_at: null })];
unreadBySession = { S: 1 };
- devBind('S'); render(<PetPage />); await showDetail();
+ mainSession('S'); render(<PetPage />); await showDetail();
const oldIntersection = intersections.at(-1)!;
await act(async () => oldIntersection([{ isIntersecting: true }]));
expect(markRead).toHaveBeenCalledTimes(1);
@@ -1871,9 +1726,10 @@ describe('desktop mini v2 interaction contract', () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q', 'S', { content: { quick_replies: ['Yes'] } })];
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('S'); render(<PetPage />); await showDetail(); summon('listen');
- await userEvent.type(await screen.findByRole('textbox'), 'my draft');
+ mainSession('S'); render(<PetPage />); await showDetail();
await userEvent.click(screen.getByText('Yes'));
+ summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'my draft');
await emit((h) => h.onAuthorizationChanged?.({}));
await userEvent.keyboard('{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', { text: 'Yes', metadata: { quick_reply_for: 'q' } });
@@ -1888,10 +1744,10 @@ describe('desktop mini v2 interaction contract', () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), asking];
const pending = deferred<WorkbenchMessage>();
api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
- devBind('S'); render(<PetPage />); await showDetail();
+ mainSession('S'); render(<PetPage />); await showDetail();
+ await userEvent.click(await screen.findByText('Yes'));
summon('listen');
const input = await screen.findByRole('textbox');
- await userEvent.click(await screen.findByText('Yes'));
const chosen = { ...asking, content: { ...asking.content, quick_reply_chosen: 'Yes' } };
const update = () => {
tails.S = tails.S.map((row) => row.id === chosen.id ? chosen : row);
@@ -1917,6 +1773,8 @@ describe('desktop mini v2 interaction contract', () => {
expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', { text: 'Yes', metadata: { quick_reply_for: 'q1' } });
expect(screen.queryByRole('button', { name: 'Yes', exact: true })).toBeNull();
expect(screen.queryByRole('button', { name: 'No', exact: true })).toBeNull();
+ await userEvent.keyboard('{Escape}');
+ await showDetail();
// An older update must never reclaim a newer result's quick-reply group.
await emit((h) => h.onMessageNew?.(message('q2', 'S', { content: { quick_replies: ['Continue', 'Wait'] } })));
expect(await screen.findByRole('button', { name: 'Continue', exact: true })).toBeTruthy();
@@ -1928,7 +1786,7 @@ describe('desktop mini v2 interaction contract', () => {
it('keeps quick replies behind the same uncertain-send lock as typed input', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q1', 'S', { content: { quick_replies: ['Yes', 'No'] } })];
api.sendSessionMessage.mockRejectedValueOnce(new Error('connection lost'));
- devBind('S'); render(<PetPage />); await showDetail();
+ mainSession('S'); render(<PetPage />); await showDetail();
await userEvent.click(await screen.findByText('Yes'));
expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
summon('listen');
@@ -1941,87 +1799,23 @@ describe('desktop mini v2 interaction contract', () => {
expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', { text: 'Yes', metadata: { quick_reply_for: 'q1' } });
});
- it('keeps waiting definitions pausable without marking them as executing', async () => {
- turn([activity('watch:w1', 'watch'), activity('task:t1', 'task')]);
- devBind('S'); render(<PetPage />); await showDetail();
- expect(screen.getAllByLabelText('pet.stop.confirmPause')).toHaveLength(2);
- expect(screen.getByText('pet.activityKind.watch · pet.activityStatus.waiting')).toBeTruthy();
- expect(screen.getByText('pet.activityKind.task · pet.activityStatus.waiting')).toBeTruthy();
- expect(document.querySelector('.pet-mini-running-dot')).toBeNull();
+ it('does not label idle processes as working or completed, and hides unsupported run stops', async () => {
+ turn([activity('watch:w1', 'watch', 'idle'), activity('task:t1', 'task', 'idle')]);
+ mainSession('S'); render(<PetPage />); await showDetail();
+ expect(document.querySelectorAll('.pet-mini-card')).toHaveLength(0);
expect(pose()).toBe('idle');
- expect(document.querySelector('[data-busy]')?.getAttribute('data-busy')).toBe('false');
- turn([activity('watch:w1', 'watch'), activity('task:t1', 'task'), activity('agent_run:r1', 'agent_run')]);
+ turn([activity('run:r1', 'agent_run')]);
await emit((h) => h.onRunsUpdated?.({}));
await waitFor(() => expect(pose()).toBe('running'));
- expect(document.querySelectorAll('.pet-mini-running-dot')).toHaveLength(1);
- expect(screen.getAllByLabelText('pet.stop.confirmPause')).toHaveLength(2);
- expect(screen.queryByLabelText('pet.stop.confirmStop')).toBeNull();
+ expect(screen.queryByLabelText('pet.stop.stop')).toBeNull();
});
- it.each([false, true])('keeps switching reachable without a main exchange (background work: %s)', async (hasBackgroundWork) => {
- tails.S = [];
- turn(hasBackgroundWork ? [activity('watch:w1', 'watch')] : []);
- switcherSessions = [session('B', { title: 'Another session' })];
- devBind('S'); render(<PetPage />);
- await waitFor(() => expect(api.listSessionMessages).toHaveBeenCalledWith('S', expect.anything()));
- summon('show');
- if (hasBackgroundWork) expect(await screen.findByText('watch:w1')).toBeTruthy();
- // An empty bound session is not the picker: it shows the switch control.
- expect(screen.queryByText('Another session')).toBeNull();
- fireEvent.click(await screen.findByText('pet.switchSession'));
- fireEvent.click(await screen.findByText('Another session'));
- await waitFor(() => expect(devBinding().binding).toBe('B'));
- expect(await screen.findAllByText('Session B')).toHaveLength(2);
- });
-
- it('picking a session with nothing to show leaves the switcher instead of reopening it', async () => {
- tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r', 'S')];
- tails.B = [];
- switcherSessions = [session('B', { title: 'Another session' })];
- devBind('S'); render(<PetPage />);
- await showDetail();
- fireEvent.click(await screen.findByText('pet.switchSession'));
- fireEvent.click(await screen.findByText('Another session'));
- await waitFor(() => expect(devBinding().binding).toBe('B'));
- await waitFor(() => expect(api.listSessionMessages).toHaveBeenCalledWith('B', expect.anything()));
- await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
- expect(screen.queryByText('Another session')).toBeNull();
- expect(screen.getByText('pet.switchSession')).toBeTruthy();
- });
- it('goes back from the switcher with the back control, and a collapse leaves it', async () => {
- tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r', 'S')];
- switcherSessions = [session('B', { title: 'Another session' })];
- devBind('S'); render(<PetPage />);
- await showDetail();
- fireEvent.click(await screen.findByText('pet.switchSession'));
- expect(await screen.findByText('Another session')).toBeTruthy();
- fireEvent.click(screen.getByText('common.back'));
- await waitFor(() => expect(screen.queryByText('Another session')).toBeNull());
- expect(document.querySelector('.pet-mini-card.is-main')).toBeTruthy();
- expect(devBinding().binding).toBe('S');
-
- fireEvent.click(screen.getByText('pet.switchSession'));
- expect(await screen.findByText('Another session')).toBeTruthy();
- fireEvent.click(screen.getByLabelText('pet.toggle'));
- await waitFor(() => expect(screen.getByLabelText('pet.toggle').getAttribute('aria-expanded')).toBe('false'));
- fireEvent.click(screen.getByLabelText('pet.toggle'));
- await waitFor(() => expect(screen.getByLabelText('pet.toggle').getAttribute('aria-expanded')).toBe('true'));
- expect(screen.queryByText('Another session')).toBeNull();
- expect(document.querySelector('.pet-mini-card.is-main')).toBeTruthy();
- });
- it('offers no back control when nothing is bound', async () => {
- canChat = false;
- switcherSessions = [session('B', { title: 'Another session' })];
- render(<PetPage />);
- summon('show');
- expect(await screen.findByText('Another session')).toBeTruthy();
- expect(screen.queryByText('common.back')).toBeNull();
- });
+
it('shows the dock while the shell reports hover over Vibey, and reports that zone', async () => {
- devBind('S'); render(<PetPage />);
+ mainSession('S'); render(<PetPage />);
const wrap = (await screen.findByLabelText('pet.toggle')).closest('.pet-mini-avatar-wrap')!;
expect(wrap.hasAttribute('data-pet-hover')).toBe(true);
expect(wrap.classList.contains('is-hovered')).toBe(false);
@@ -2034,7 +1828,7 @@ describe('desktop mini v2 interaction contract', () => {
it('keeps the unread count visible until the inbox confirms the result was read', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r', 'S', { read_at: null })];
unreadBySession = { S: 1 };
- devBind('S'); render(<PetPage />);
+ mainSession('S'); render(<PetPage />);
expect((await screen.findByLabelText('pet.unreadBadge')).textContent).toBe('1');
summon('show');
expect(screen.getByLabelText('pet.unreadBadge').textContent).toBe('1');
@@ -2052,17 +1846,17 @@ describe('desktop mini v2 interaction contract', () => {
it('does not mark the collapsed card read; detail is explicitly opened and closes on collapse', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'Question' }), message('r', 'S', { read_at: null })];
unreadBySession = { S: 1 };
- devBind('S');
+ mainSession('S');
render(<PetPage />);
await screen.findByText('Question');
expect(markRead).not.toHaveBeenCalled();
- fireEvent.click(screen.getByLabelText('pet.stack.expand'));
+ summon('show');
await waitFor(() => expect(document.querySelector('.pet-mini-detail')).toBeTruthy());
expect(markRead).not.toHaveBeenCalled();
- fireEvent.click(document.querySelector('.pet-mini-card[role=button]')!);
+ fireEvent.click(document.querySelector('.pet-mini-reply-toggle')!);
await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r'));
fireEvent.click(screen.getByLabelText('pet.toggle'));
- await waitFor(() => expect(document.querySelector('.pet-mini-detail')).toBeNull());
+ await waitFor(() => expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull());
});
it('marks detail read only after its result intersects the fixed scroll viewport', async () => {
@@ -2075,7 +1869,7 @@ describe('desktop mini v2 interaction contract', () => {
try {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('unseen', 'S', { read_at: null })];
unreadBySession = { S: 1 };
- devBind('S'); render(<PetPage />); await showDetail();
+ mainSession('S'); render(<PetPage />); await showDetail();
expect(intersect).toBeDefined();
expect(markRead).not.toHaveBeenCalled();
await act(async () => intersect!([{ isIntersecting: true }]));
@@ -2087,19 +1881,19 @@ describe('desktop mini v2 interaction contract', () => {
it('requires a second press, uses the native watch id, and retains the stopped row through linger and both exit beats', async () => {
turn([activity('watch:w1', 'watch'), activity('run:r1', 'agent_run')]);
- devBind('S'); render(<PetPage />); await showDetail();
- const stop = await screen.findByLabelText('pet.stop.confirmPause');
- expect(screen.queryByLabelText('pet.stop.confirmStop')).toBeNull();
+ mainSession('S'); render(<PetPage />); await showCards();
+ const stop = await screen.findByLabelText('pet.stop.stop');
+ expect(screen.getAllByLabelText('pet.stop.stop')).toHaveLength(1);
const pending = deferred<{ ok: boolean }>();
- api.setHarnessWatchEnabled.mockImplementationOnce(() => pending.promise);
+ api.cancelSession.mockImplementationOnce(() => pending.promise);
vi.useFakeTimers();
fireEvent.click(stop);
- expect(api.setHarnessWatchEnabled).not.toHaveBeenCalled();
+ expect(api.cancelSession).not.toHaveBeenCalled();
fireEvent.click(stop);
- expect(api.setHarnessWatchEnabled).toHaveBeenCalledExactlyOnceWith('w1', false);
+ expect(api.cancelSession).toHaveBeenCalledExactlyOnceWith('watch:w1');
expect(stop.hasAttribute('disabled')).toBe(true);
await act(async () => pending.resolve({ ok: true }));
- expect(screen.getByText('pet.stop.paused')).toBeTruthy();
+ expect(screen.getByText('pet.stop.stopped')).toBeTruthy();
turn([]);
// Server removal during the linger cannot cut off the local exit.
await act(async () => { handlers.forEach((h) => h.onRunsUpdated?.({})); });
@@ -2115,23 +1909,23 @@ describe('desktop mini v2 interaction contract', () => {
});
it('expires confirmation at 3s and lets a failed pause be retried', async () => {
- turn([activity('task:t1', 'task')]); devBind('S'); render(<PetPage />); await showDetail();
- const stop = await screen.findByLabelText('pet.stop.confirmPause');
+ turn([activity('task:t1', 'task')]); mainSession('S'); render(<PetPage />); await showCards();
+ const stop = await screen.findByLabelText('pet.stop.stop');
vi.useFakeTimers(); fireEvent.click(stop);
await act(async () => vi.advanceTimersByTime(3000));
expect(stop.classList.contains('is-confirm')).toBe(false);
- api.setHarnessTaskEnabled.mockRejectedValueOnce(new Error('offline'));
+ api.cancelSession.mockRejectedValueOnce(new Error('offline'));
fireEvent.click(stop); fireEvent.click(stop);
await act(async () => {});
expect(screen.getByText('pet.stop.failed')).toBeTruthy();
fireEvent.click(stop); fireEvent.click(stop);
await act(async () => {});
- expect(api.setHarnessTaskEnabled).toHaveBeenNthCalledWith(2, 't1', false);
- expect(screen.getByText('pet.stop.paused')).toBeTruthy();
+ expect(api.cancelSession).toHaveBeenNthCalledWith(2, 'task:t1');
+ expect(screen.getByText('pet.stop.stopped')).toBeTruthy();
});
it('holds for exactly 320ms, cancels a departed press, and falls back to text without voice support', async () => {
- devBind('S'); render(<PetPage />); await screen.findByText('Session S');
+ mainSession('S'); render(<PetPage />); await screen.findByText('Session S');
const avatar = screen.getByLabelText('pet.toggle');
vi.useFakeTimers();
fireEvent.pointerDown(avatar, { button: 0, pointerId: 1 });
@@ -2148,3 +1942,458 @@ describe('desktop mini v2 interaction contract', () => {
expect(api.sendSessionMessage).not.toHaveBeenCalled();
});
});
+
+
+describe('Personal Agent mini', () => {
+ it('uses the same visible sessions for cards and attention, excluding the main and unknown visibility', async () => {
+ canUseAgents = true;
+ const row = workingIn('running').agents[0];
+ runningAgents = { ...workingIn('running'), agents: [
+ { ...row, session_id: 'S' },
+ { ...row, session_id: 'ses_main' },
+ { ...row, session_id: 'hidden', visibility: 'background' },
+ { ...row, session_id: 'system', visibility: 'system' },
+ { ...row, session_id: 'unknown', visibility: null },
+ { ...row, session_id: 'closed', openable_in_chat: false },
+ { ...row, session_id: 'reply', state: 'idle' },
+ { ...row, session_id: 'running', state: 'idle' },
+ row,
+ { ...row, session_id: 'approval', state: 'idle' },
+ ] };
+ unreadBySession = { reply: 1 };
+ api.getVaultRequests.mockImplementation(async (filter) => ({ requests: filter?.session === 'approval' ? [{ id: 'request', request_type: 'access', session: { id: 'approval' } } as VaultRequest] : [] }));
+ mainSession('S'); render(<PetPage />); await showCards();
+ 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(api.getVaultRequests).not.toHaveBeenCalledWith(expect.objectContaining({ session: 'hidden' }), expect.anything());
+ api.getVaultRequests.mockResolvedValue({ requests: [] });
+ await emit((h) => h.onVaultsUpdated?.({}));
+ await waitFor(() => expect(pose()).toBe('ready'));
+ expect(Array.from(document.querySelectorAll('.pet-mini-card'), (node) => node.getAttribute('data-session-id'))).toEqual(['running', 'reply']);
+ });
+
+ 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];
+ 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(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' }));
+ await waitFor(() => expect(document.querySelector('[data-session-id="reply"]')).toBeNull());
+ expect(pose()).toBe('idle');
+ });
+
+ it('appends a removable reference to the draft and sends it only to the main binding', async () => {
+ canUseAgents = true;
+ runningAgents = workingIn('other');
+ api.sendSessionMessage.mockResolvedValueOnce(message('sent-ref', 'S', { author: 'user', type: 'user' }));
+ mainSession('S'); render(<PetPage />); summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'Check this');
+ await userEvent.click(await screen.findByRole('button', { name: 'pet.referenceSession' }));
+ expect(screen.getByRole('textbox').getAttribute('placeholder')).toBe('pet.inputPlaceholder');
+ expect(api.sendSessionMessage).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole('button', { name: 'pet.send' }));
+ expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', {
+ text: 'Check this #<other>', content: { references: [{ kind: 'session', session_id: 'other', title: 'pet.untitledTask' }] },
+ });
+ });
+});
+
+
+describe('Personal Agent review invariants', () => {
+ it.each(['ended', 'hidden', 'unreachable', 'remount'])('keeps selected reference metadata when the activity is %s', async (reason) => {
+ canUseAgents = true;
+ runningAgents = workingIn('other');
+ api.sendSessionMessage.mockResolvedValueOnce(message('sent-ref', 'S', { author: 'user', type: 'user' }));
+ mainSession('S'); const view = render(<PetPage />); summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'Check this');
+ await userEvent.click(await screen.findByRole('button', { name: 'pet.referenceSession' }));
+ runningAgents = reason === 'hidden'
+ ? { ...workingIn('other'), agents: workingIn('other').agents.map((row) => ({ ...row, visibility: 'background' })) }
+ : { ok: false, unreachable: true, agents: [], counts: {} };
+ if (reason === 'ended' || reason === 'remount') runningAgents = { ...workingIn('other'), agents: [] };
+ await emit((h) => h.onRunsUpdated?.({}));
+ if (reason === 'remount') {
+ view.unmount(); render(<PetPage />); summon('listen');
+ }
+ const input = await screen.findByRole('textbox');
+ expect((input as HTMLTextAreaElement).value).toBe('Check this ');
+ expect(screen.getByRole('button', { name: 'pet.removeReference' })).toBeTruthy();
+ await userEvent.click(screen.getByRole('button', { name: 'pet.send' }));
+ expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', {
+ text: 'Check this #<other>', content: { references: [{ kind: 'session', session_id: 'other', title: 'pet.untitledTask' }] },
+ });
+ summon('listen');
+ await screen.findByRole('textbox');
+ expect(screen.queryByRole('button', { name: 'pet.removeReference' })).toBeNull();
+ });
+
+ it.each(['remove', 'escape', 'binding'])('clears draft references on %s', async (action) => {
+ canUseAgents = true; runningAgents = workingIn('other');
+ mainSession('S'); render(<PetPage />); summon('show');
+ await userEvent.click(await screen.findByRole('button', { name: 'pet.referenceSession' }));
+ if (action === 'remove') await userEvent.click(screen.getByRole('button', { name: 'pet.removeReference' }));
+ else if (action === 'escape') await userEvent.keyboard('{Escape}');
+ else await resolveMainAs('B');
+ summon('listen');
+ expect((await screen.findByRole('textbox') as HTMLTextAreaElement).value).toBe('');
+ expect(screen.queryByRole('button', { name: 'pet.removeReference' })).toBeNull();
+ });
+
+ it('sleeps despite unread sessions excluded from the visible activity model', async () => {
+ vi.useFakeTimers();
+ try {
+ canUseAgents = true;
+ const row = workingIn('hidden').agents[0];
+ runningAgents = { ...workingIn('hidden'), agents: [
+ { ...row, session_id: 'hidden', visibility: 'background' },
+ { ...row, session_id: 'system', visibility: 'system' },
+ { ...row, session_id: 'unknown', visibility: null },
+ { ...row, session_id: 'closed', openable_in_chat: false },
+ ] };
+ unreadBySession = { hidden: 1, system: 1, unknown: 1, closed: 1 };
+ mainSession('S'); render(<PetPage />);
+ await act(async () => {});
+ expect(pose()).toBe('idle');
+ await act(async () => vi.advanceTimersByTimeAsync(5 * 60 * 1000 + 1));
+ expect(pose()).toBe('sleeping');
+ runningAgents = workingIn('visible');
+ await emit((h) => h.onRunsUpdated?.({}));
+ expect(pose()).toBe('running');
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('reads each activity action source once on mount and when IDs change with a healthy bridge', async () => {
+ canUseAgents = true; runningAgents = workingIn('other');
+ api.getTurnState.mockClear();
+ mainSession('S'); render(<PetPage />); await showDetail();
+ await waitFor(() => expect(api.getTurnState).toHaveBeenCalledWith('other', expect.anything()));
+ expect(api.getVaultRequests.mock.calls.filter(([filter]) => filter?.session === 'other')).toHaveLength(1);
+ expect(api.getTurnState.mock.calls.filter(([id]) => id === 'other')).toHaveLength(1);
+ await emit((h) => h.onEventBridgeStatus?.({ connected: true }));
+ runningAgents = { ...workingIn('other'), agents: [...workingIn('other').agents, ...workingIn('new').agents] };
+ await emit((h) => h.onRunsUpdated?.({}));
+ await waitFor(() => expect(api.getTurnState).toHaveBeenCalledWith('new', expect.anything()));
+ expect(api.getVaultRequests.mock.calls.filter(([filter]) => filter?.session === 'other')).toHaveLength(2);
+ expect(api.getVaultRequests.mock.calls.filter(([filter]) => filter?.session === 'new')).toHaveLength(1);
+ expect(api.getTurnState.mock.calls.filter(([id]) => id === 'new')).toHaveLength(1);
+ });
+});
+
+describe('Personal Agent review: history and lifecycle', () => {
+ it.each(['disappeared', 'new-turn', 'new-turn-during-outage'])('forgets a manual dismissal when %s', async (reason) => {
+ mainSession('ses_main'); canUseAgents = true; runningAgents = workingIn('T');
+ const invoke = vi.fn(async (command: string) => command === 'pet_ready'
+ ? { binding: 'ses_main', revision: 1, dismissed_ids: [], summon_pending: 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 });
+ render(<PetPage />); summon('show');
+ await userEvent.click(await screen.findByLabelText('pet.dismiss'));
+ const { petShell } = await import('./petShell');
+ await waitFor(() => expect(petShell.dismissed()).toEqual(['T']));
+ if (reason === 'disappeared') {
+ runningAgents = { ...runningAgents, agents: [] };
+ await emit((h) => h.onRunsUpdated?.({}));
+ } else {
+ if (reason === 'new-turn-during-outage') {
+ api.getMainSession.mockRejectedValueOnce(new Error('offline'));
+ await emit((h) => h.onConnected?.());
+ await screen.findByText('pet.vibeyUnavailable');
+ }
+ await emit((h) => h.onTurnStart?.({ session_id: 'T' }));
+ }
+ await waitFor(() => expect(petShell.dismissed()).toEqual([]));
+ expect(invoke.mock.calls.some(([command]) => command === 'pet_set_dismissed')).toBe(false);
+ runningAgents = workingIn('T');
+ await emit((h) => h.onConnected?.());
+ await waitFor(() => expect(document.querySelector('[data-session-id="T"]')).toBeTruthy());
+ });
+
+ it('cancels an old manual exit when the next turn starts before its animation ends', async () => {
+ canUseAgents = true; runningAgents = workingIn('T');
+ render(<PetPage />); summon('show');
+ const close = await screen.findByLabelText('pet.dismiss');
+ vi.useFakeTimers();
+ try {
+ fireEvent.click(close);
+ expect(document.querySelector('.is-leaving')).toBeTruthy();
+ await emit((h) => h.onTurnStart?.({ session_id: 'T' }));
+ await act(async () => vi.advanceTimersByTime(500));
+ const { petShell } = await import('./petShell');
+ expect(petShell.dismissed()).toEqual([]);
+ expect(document.querySelector('[data-session-id="T"]')).toBeTruthy();
+ expect(document.querySelector('.is-leaving')).toBeNull();
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('renders reference sidecars in current and historical Markdown', 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', '旧项目') }),
+ message('old-result', 'S', { text: 'Done #<old-result-ref>', content: reference('old-result-ref', 'Old result') }),
+ message('current-user', 'S', { author: 'user', type: 'user', text: 'Summarize #<current>', content: reference('current', '当前项目') }),
+ message('current-result', 'S', { text: 'See #<result-ref>', content: reference('result-ref', 'Latest result') }),
+ ];
+ 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(document.querySelector('.pet-mini-detail')?.textContent).not.toMatch(/#</);
+ });
+
+ it.each([false, true])('preserves document dismissals across an outage (native bind succeeds: %s)', async (persistable) => {
+ mainSession('ses_main'); canUseAgents = true; runningAgents = workingIn('T');
+ const invoke = vi.fn(async (command: string) => {
+ if (command === 'pet_ready') return { binding: null, revision: 0, dismissed_ids: [], summon_pending: null };
+ if (command === 'pet_bind') {
+ if (!persistable) throw new Error('storage unavailable');
+ return { binding: 'ses_main', revision: 1 };
+ }
+ return { 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 });
+ render(<PetPage />); summon('show');
+ await userEvent.click(await screen.findByLabelText('pet.dismiss'));
+ const { petShell } = await import('./petShell');
+ await waitFor(() => expect(petShell.dismissed()).toEqual(['T']));
+ api.getMainSession.mockRejectedValueOnce(new Error('offline'));
+ await emit((h) => h.onConnected?.());
+ await screen.findByText('pet.vibeyUnavailable');
+ expect(petShell.dismissed()).toEqual(['T']);
+ await emit((h) => h.onConnected?.());
+ await waitFor(() => expect(petShell.currentBinding()).toBe('ses_main'));
+ expect(petShell.dismissed()).toEqual(['T']);
+ expect(document.querySelector('[data-session-id="T"]')).toBeNull();
+ });
+
+ it('shows loading during slow reauthorization while preserving the draft', async () => {
+ render(<PetPage />); summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'unsent draft');
+ const pending = deferred<WorkbenchSessionReadResult>();
+ api.getMainSession.mockReturnValueOnce(pending.promise);
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ expect(screen.getByRole('status').textContent).toContain('common.loading');
+ expect(screen.getByRole('button', { name: 'pet.openInAvibe' })).toBeTruthy();
+ expect(screen.queryByRole('textbox')).toBeNull();
+ await act(async () => pending.resolve({ status: 200, session: session('S'), capabilities: { can_chat: true } }));
+ expect((await screen.findByRole('textbox') as HTMLTextAreaElement).value).toBe('unsent draft');
+ expect(screen.queryByText('common.loading')).toBeNull();
+ });
+
+ it.each(['idle-then-running', 'new-turn', 'unread'])('does not turn a stop exit into a manual dismissal before %s', async (next) => {
+ canUseAgents = true; runningAgents = workingIn('T');
+ api.getTurnState.mockImplementation(async (id) => ({ ...idleTurn, in_flight: id === 'T' }));
+ api.cancelSession.mockResolvedValue({ ok: true });
+ render(<PetPage />); summon('show');
+ const stop = await screen.findByLabelText('pet.stop.stop');
+ vi.useFakeTimers();
+ try {
+ fireEvent.click(stop); fireEvent.click(stop);
+ await act(async () => {});
+ await act(async () => vi.advanceTimersByTime(2500));
+ await act(async () => vi.advanceTimersByTime(500));
+ expect(document.querySelector('[data-session-id="T"]')).toBeNull();
+ const { petShell } = await import('./petShell');
+ expect(petShell.dismissed()).not.toContain('T');
+ if (next === 'idle-then-running') {
+ runningAgents = { ...runningAgents, agents: runningAgents.agents.map((row) => ({ ...row, state: 'idle' })) };
+ await emit((h) => h.onRunsUpdated?.({}));
+ runningAgents = workingIn('T');
+ await emit((h) => h.onRunsUpdated?.({}));
+ } else if (next === 'new-turn') {
+ await emit((h) => h.onTurnStart?.({ session_id: 'T' }));
+ } else {
+ runningAgents = { ...runningAgents, agents: runningAgents.agents.map((row) => ({ ...row, state: 'idle' })) };
+ act(() => {
+ unreadBySession = { T: 1 }; inboxVersion += 1; inboxListeners.forEach((listener) => listener());
+ });
+ await emit((h) => h.onRunsUpdated?.({}));
+ }
+ expect(document.querySelector('[data-session-id="T"]')).toBeTruthy();
+ expect(petShell.dismissed()).not.toContain('T');
+ } finally { vi.useRealTimers(); }
+ });
+});
+
+describe('Personal Agent breaker: readiness and turn generations', () => {
+ it('keeps closes only in this document and ignores legacy dismissals even after slow ready', async () => {
+ mainSession('ses_main'); canUseAgents = true; runningAgents = workingIn('T');
+ const ready = deferred<unknown>();
+ const legacy = { binding: 'ses_main', revision: 5, dismissed_ids: ['T'], summon_pending: null };
+ const invoke = vi.fn((command: string) => command === 'pet_ready' ? ready.promise : 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 });
+ const view = render(<PetPage />); await showCards();
+ await userEvent.click(await screen.findByLabelText('pet.dismiss'));
+ const { petShell } = await import('./petShell');
+ await waitFor(() => expect(petShell.dismissed()).toEqual(['T']));
+ await act(async () => ready.resolve(legacy));
+ expect(petShell.dismissed()).toEqual(['T']);
+ expect(document.querySelector('[data-session-id="T"]')).toBeNull();
+ expect(invoke.mock.calls.some(([command]) => command === 'pet_set_dismissed')).toBe(false);
+ view.unmount();
+ // A new module graph represents reopening the document, with the same file.
+ vi.resetModules();
+ const { PetPage: ReopenedPet } = await import('./PetPage');
+ render(<ReopenedPet />); await showCards();
+ await waitFor(() => expect(document.querySelector('[data-session-id="T"]')).toBeTruthy());
+ expect(invoke.mock.calls.some(([command]) => command === 'pet_set_dismissed')).toBe(false);
+ });
+
+ it.each(['unread', 'feed', 'running'])('does not forget a close while the %s source is unready', async (source) => {
+ mainSession('ses_main'); canUseAgents = true;
+ unreadLoaded = source !== 'unread'; inboxLoading = source === 'feed';
+ if (source === 'running') runningAgents = { ok: false, agents: [], counts: {} };
+ const { petShell } = await import('./petShell');
+ petShell.addDismissed('reply');
+ render(<PetPage />); await showCards();
+ await waitFor(() => expect(petShell.currentBinding()).toBe('ses_main'));
+ await waitFor(() => expect(api.getRunningAgents).toHaveBeenCalled());
+ expect(petShell.dismissed()).toEqual(['reply']);
+ act(() => {
+ inboxSessions = [{ session_id: 'reply', unread: true } as InboxSession];
+ unreadBySession = { reply: 1 }; unreadLoaded = true; inboxLoading = false;
+ inboxVersion += 1; inboxListeners.forEach((listener) => listener());
+ });
+ runningAgents = { ok: true, agents: [], counts: {} };
+ await emit((h) => h.onRunsUpdated?.({}));
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('reply'));
+ expect(petShell.dismissed()).toEqual(['reply']);
+ expect(document.querySelector('[data-session-id="reply"]')).toBeNull();
+ // A loaded empty snapshot can now forget it.
+ act(() => {
+ inboxSessions = []; unreadBySession = {};
+ inboxVersion += 1; inboxListeners.forEach((listener) => listener());
+ });
+ await waitFor(() => expect(petShell.dismissed()).toEqual([]));
+ });
+
+ it.each([false, true])('retains reply cards and their generation during revalidation (dismissed: %s)', async (dismissed) => {
+ mainSession('ses_main'); canUseAgents = true;
+ inboxSessions = [{ session_id: 'reply', unread: true } as InboxSession];
+ unreadBySession = { reply: 1 };
+ render(<PetPage />); await showCards();
+ await waitFor(() => expect(document.querySelector('[data-session-id="reply"]')).toBeTruthy());
+ const { petShell } = await import('./petShell');
+ if (dismissed) {
+ await userEvent.click(await screen.findByLabelText('pet.dismiss'));
+ await waitFor(() => expect(petShell.dismissed()).toEqual(['reply']));
+ }
+ const first = deferred<WorkbenchSessionReadResult>();
+ const latest = deferred<WorkbenchSessionReadResult>();
+ sessionReads.reply = () => first.promise;
+ await emit((h) => h.onConnected?.());
+ const assertStable = () => {
+ expect(petShell.dismissed()).toEqual(dismissed ? ['reply'] : []);
+ expect(Boolean(document.querySelector('[data-session-id="reply"]'))).toBe(!dismissed);
+ if (!dismissed) expect(pose()).toBe('ready');
+ };
+ assertStable();
+ sessionReads.reply = () => latest.promise;
+ await emit((h) => h.onSessionActivity?.({ session_id: 'unrelated', scope_id: null, event: 'updated' }));
+ assertStable();
+ await act(async () => latest.resolve({ status: 200, session: session('reply') }));
+ assertStable();
+ // The older read must not remove the newer validated row.
+ await act(async () => first.resolve({ status: 404, session: null }));
+ assertStable();
+ sessionReads.reply = () => Promise.reject(new Error('offline'));
+ await emit((h) => h.onConnected?.());
+ assertStable();
+ });
+
+ it('records a new close against the retained main during a lookup outage', async () => {
+ mainSession('ses_main'); canUseAgents = true; runningAgents = workingIn('T');
+ render(<PetPage />); await showCards();
+ await screen.findByLabelText('pet.dismiss');
+ api.getMainSession.mockRejectedValueOnce(new Error('offline'));
+ await emit((h) => h.onConnected?.());
+ await screen.findByText('pet.vibeyUnavailable');
+ await userEvent.click(await screen.findByLabelText('pet.dismiss'));
+ const { petShell } = await import('./petShell');
+ await waitFor(() => expect(petShell.dismissed()).toEqual(['T']));
+ expect(document.querySelector('[data-session-id="T"]')).toBeNull();
+ await emit((h) => h.onConnected?.());
+ await waitFor(() => expect(petShell.currentBinding()).toBe('ses_main'));
+ expect(petShell.dismissed()).toEqual(['T']);
+ expect(document.querySelector('[data-session-id="T"]')).toBeNull();
+ });
+
+ it('requires two fresh stop presses after confirmation, manual exit and a new turn', async () => {
+ canUseAgents = true; runningAgents = workingIn('T');
+ api.getTurnState.mockImplementation(async (id) => ({ ...idleTurn, in_flight: id === 'T' }));
+ api.cancelSession.mockReset().mockResolvedValue({ ok: true });
+ render(<PetPage />); await showCards();
+ const stop = await screen.findByLabelText('pet.stop.stop');
+ vi.useFakeTimers();
+ try {
+ fireEvent.click(stop);
+ fireEvent.click(screen.getByLabelText('pet.dismiss'));
+ await act(async () => vi.advanceTimersByTime(500));
+ expect(document.querySelector('[data-session-id="T"]')).toBeNull();
+ await emit((h) => h.onTurnStart?.({ session_id: 'T' }));
+ const nextStop = screen.getByLabelText('pet.stop.stop');
+ fireEvent.click(nextStop);
+ expect(nextStop.getAttribute('aria-label')).toBe('pet.stop.confirmStop');
+ expect(api.cancelSession).not.toHaveBeenCalled();
+ // The old confirmation timer must not clear the new turn's confirmation.
+ await act(async () => vi.advanceTimersByTime(2500));
+ expect(nextStop.getAttribute('aria-label')).toBe('pet.stop.confirmStop');
+ fireEvent.click(nextStop);
+ expect(api.cancelSession).toHaveBeenCalledExactlyOnceWith('T');
+ await act(async () => {});
+ } finally { vi.useRealTimers(); }
+ });
+
+ it.each([
+ ['event', 'success'], ['event', 'failure'], ['reappearance', 'success'], ['reappearance', 'failure'],
+ ] as const)('fences a pending cancel across %s before late %s', async (boundary, outcome) => {
+ canUseAgents = true; runningAgents = workingIn('T');
+ api.getTurnState.mockImplementation(async (id) => ({ ...idleTurn, in_flight: id === 'T' }));
+ const pending = deferred<{ ok: boolean }>();
+ api.cancelSession.mockReset().mockImplementationOnce(() => pending.promise);
+ render(<PetPage />); await showCards();
+ const stop = await screen.findByLabelText('pet.stop.stop');
+ fireEvent.click(stop); fireEvent.click(stop);
+ expect(screen.getByText('pet.stop.stopping')).toBeTruthy();
+ if (boundary === 'event') await emit((h) => h.onTurnStart?.({ session_id: 'T' }));
+ else {
+ runningAgents = { ...runningAgents, agents: [] };
+ await emit((h) => h.onRunsUpdated?.({}));
+ runningAgents = workingIn('T');
+ await emit((h) => h.onRunsUpdated?.({}));
+ }
+ const nextStop = await screen.findByLabelText('pet.stop.stop');
+ expect(nextStop.hasAttribute('disabled')).toBe(false);
+ fireEvent.click(nextStop);
+ await act(async () => {
+ if (outcome === 'success') pending.resolve({ ok: true });
+ else pending.reject(new Error('old cancellation failed'));
+ });
+ expect(nextStop.getAttribute('aria-label')).toBe('pet.stop.confirmStop');
+ expect(screen.queryByText('pet.stop.stopped')).toBeNull();
+ expect(screen.queryByText('pet.stop.failed')).toBeNull();
+ expect(document.querySelector('.is-leaving')).toBeNull();
+ expect(api.cancelSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('offers stop for a scope-less Web turn but excludes IM and non-running turns', async () => {
+ canUseAgents = true;
+ runningAgents = { ...workingIn('web'), agents: [
+ { ...workingIn('web').agents[0], platform: null, scope_type: null },
+ { ...workingIn('idleweb').agents[0], platform: null, scope_type: null },
+ { ...workingIn('im').agents[0], platform: 'feishu' },
+ ] };
+ api.getTurnState.mockReset().mockImplementation(async (id) => ({ ...idleTurn, in_flight: id === 'web' || id === 'im' }));
+ render(<PetPage />); await showCards();
+ await waitFor(() => expect(document.querySelector('[data-session-id="web"] .pet-mini-stop')).toBeTruthy());
+ expect(document.querySelector('[data-session-id="idleweb"] .pet-mini-stop')).toBeNull();
+ expect(document.querySelector('[data-session-id="im"] .pet-mini-stop')).toBeNull();
+ expect(api.getTurnState).not.toHaveBeenCalledWith('im', expect.anything());
+ });
+});
diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsx
index 4e0946884..e0eaed3a7 100644
--- a/ui/src/pet/PetPage.tsx
+++ b/ui/src/pet/PetPage.tsx
@@ -1,17 +1,19 @@
-import { useCallback, useEffect, useMemo, useRef, useState, useLayoutEffect, type ReactNode } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, useLayoutEffect, type CSSProperties, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
-import { ArrowLeft, ArrowLeftRight, ExternalLink, KeyRound } from 'lucide-react';
+import { ChevronRight, ExternalLink, KeyRound, X } from 'lucide-react';
-import { ApiError, useApi, type SessionActivityState, type WorkbenchMessage } from '@/context/ApiContext';
+import { ApiError, useApi, type InboxSession, type RunningAgent, type VaultRequest, type WorkbenchMessage } from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { useWorkbenchInbox } from '@/context/WorkbenchInboxContext';
import { Button } from '@/components/ui/button';
import { Markdown } from '@/components/ui/markdown';
import { QuickReplies } from '@/components/workbench/QuickReplies';
-import { harnessItemNativeId } from '@/lib/backgroundActivity';
import { usePageActive } from '@/lib/pageActivity';
import { usePendingVaultRequests } from '@/lib/usePendingVaultRequests';
+import { useVaultRequestRefresh } from '@/lib/useVaultRequestRefresh';
+import { vaultRequestType } from '@/lib/vaultRequestPlacement';
+import { referenceToMarker, type MentionReference, type SessionReference } from '@/lib/mentions';
import { ShowPageVoiceDictation } from '@/lib/showPageVoiceDictation';
import { VoiceTranscriptionError } from '@/lib/voiceTranscription';
@@ -21,10 +23,11 @@ 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';
-import { useConversationAgentWorking } from './useConversationAgentWorking';
+import { useConversationAgentSnapshot } from './useConversationAgentWorking';
import { usePetSession, type PetSurfaceEpoch } from './usePetSession';
import { usePetSetup } from './usePetSetup';
-import { useSessionSwitcher } from './useSessionSwitcher';
+import { usePetReplyActivities } from './usePetReplyActivities';
+import { FencedSource } from './fencedSource';
import './pet-mini.css';
const HOLD_MS = 320;
@@ -32,57 +35,67 @@ const DISMISS_EXIT_MS = 500;
const STOP_CONFIRM_MS = 3000;
const STOP_LINGER_MS = 2500;
const STACK_HEIGHT = 304; // 292px scroll box + 6px panel padding on each side.
-const EMPTY_ACTIVITIES: SessionActivityState[] = [];
const FADE_PX = 32;
+const EMPTY_INBOX: InboxSession[] = [];
const REFUSED_SEND_STATUSES = new Set([400, 403, 404, 409, 422]);
const sendRefused = (error: unknown) => error instanceof ApiError && REFUSED_SEND_STATUSES.has(error.status);
-type CardKind = 'watch' | 'task' | 'agent_run' | 'backend_activity';
-type StopPhase = 'confirm' | 'stopping' | 'stopped' | 'failed';
+type StopPhase = 'confirm' | 'stopping' | 'stopped' | 'exited' | 'failed';
type PetCard = {
id: string;
+ sessionId: string;
title: string;
- kind: CardKind;
+ eyebrow: string;
status: string;
running: boolean;
- canPause: boolean;
- main?: boolean;
+ needsInput: boolean;
+ hasUnread: boolean;
+ canStop: boolean;
+ canOpen: boolean;
+ vaultRequestIds: string[];
};
-const isRunning = (activity: SessionActivityState) => activity.status === 'running' || activity.status === 'processing';
-const isPausable = (card: PetCard) => card.kind === 'watch' || card.kind === 'task';
+type CardPresentation = { phase?: StopPhase; leaving?: boolean; retained?: PetCard };
-const activityTitle = (activity: SessionActivityState, fallback: string) => (
- (activity.label || activity.description || fallback).trim()
-);
+const isRunning = (agent: RunningAgent) => agent.state === 'active';
-const activityStatusKey = (status: string): string => ({
- running: 'pet.activityStatus.running',
- processing: 'pet.activityStatus.running',
- queued: 'pet.activityStatus.queued',
- pending: 'pet.activityStatus.waiting',
- waiting: 'pet.activityStatus.waiting',
- enabled: 'pet.activityStatus.waiting',
- scheduled: 'pet.activityStatus.waiting',
- disabled: 'pet.activityStatus.stopped',
- completed: 'pet.activityStatus.completed',
- succeeded: 'pet.activityStatus.completed',
- failed: 'pet.activityStatus.failed',
- error: 'pet.activityStatus.failed',
-}[status] ?? 'pet.activityStatus.unknown');
-
-function activityCard(activity: SessionActivityState, fallback: string, t: (key: string) => string): PetCard {
- const kindKey = `pet.activityKind.${activity.item_kind ?? 'backend_activity'}`;
+function agentCard(
+ agent: RunningAgent,
+ unreadBySession: Record<string, number>,
+ vaultRequests: VaultRequest[],
+ stoppable: string[],
+ fallback: string,
+ t: (key: string, options?: Record<string, unknown>) => string,
+): PetCard | null {
+ if (!agent.session_id) return null;
+ const project = agent.scope_display_name?.trim() || t('pet.unknownProject');
+ const name = agent.agent_name?.trim() || agent.backend.trim() || t('pet.unknownAgent');
+ const platform = agent.platform && agent.platform !== 'avibe'
+ ? t(`pet.platform.${['slack', 'discord', 'telegram', 'feishu', 'lark', 'wechat'].includes(agent.platform) ? agent.platform : 'unknown'}`) : '';
+ const needsInput = vaultRequests.some((request) => request.session?.id === agent.session_id);
+ const hasUnread = (unreadBySession[agent.session_id] ?? 0) > 0;
+ const running = isRunning(agent);
+ const status = needsInput
+ ? t('pet.needsAuthorization')
+ : running
+ ? t('pet.activityStatus.running')
+ : hasUnread
+ ? t('pet.replied')
+ : t('pet.activityStatus.waiting');
return {
- id: activity.id,
- title: activityTitle(activity, fallback),
- kind: activity.item_kind ?? 'backend_activity',
- status: `${t(kindKey)} · ${t(activityStatusKey(activity.status))}`,
- running: isRunning(activity),
- // Durable definitions are pausable while waiting for their next execution.
- // They do not make Vibey busy or receive the actively-running indicator.
- canPause: (activity.item_kind === 'watch' && (activity.status === 'enabled' || isRunning(activity)))
- || (activity.item_kind === 'task' && (activity.status === 'scheduled' || isRunning(activity))),
+ id: agent.session_id,
+ sessionId: agent.session_id,
+ title: agent.title?.trim() || fallback,
+ eyebrow: [platform, project, name].filter(Boolean).join(' · '),
+ status,
+ running,
+ needsInput,
+ hasUnread,
+ // This snapshot defaults trigger_source to human; it carries no caller
+ // lineage. Never infer a delegation to or from the personal agent.
+ canStop: running && stoppable.includes(agent.session_id),
+ canOpen: agent.openable_in_chat,
+ vaultRequestIds: vaultRequests.filter((request) => request.session?.id === agent.session_id).map((request) => request.id),
};
}
@@ -136,40 +149,75 @@ const PetSetupPending: React.FC<{ recheck: () => void }> = ({ recheck }) => {
);
};
+function useVisibleActivityActions(enabled: boolean, epoch: PetSurfaceEpoch, sessionIds: string, cancellableIds: string) {
+ const api = useApi();
+ const [value, setValue] = useState<{ epoch: PetSurfaceEpoch; sessionIds: string; cancellableIds: string; requests: VaultRequest[]; stoppable: string[] } | null>(null);
+ const source = useMemo(() => new FencedSource<PetSurfaceEpoch, { requests: VaultRequest[]; stoppable: string[] }>({
+ read: async () => {
+ const ids: string[] = JSON.parse(sessionIds);
+ const groups = await Promise.all(ids.map(async (id) => {
+ const result = await api.getVaultRequests({ status: 'pending', session: id }, { handleError: false }).catch(() => ({ requests: [] }));
+ return (result.requests ?? []).map((request) => ({
+ ...request,
+ session: request.session ?? { id, title: null, label: null, platform: null, scope_kind: null, is_workbench: false },
+ }));
+ }));
+ const candidates: string[] = JSON.parse(cancellableIds);
+ const stoppable = await Promise.all(candidates.map(async (id) => {
+ try {
+ const turn = await api.getTurnState(id, { handleError: false });
+ return turn.in_flight === true ? id : null;
+ } catch { return null; }
+ }));
+ return { requests: groups.flat(), stoppable: stoppable.filter((id): id is string => id !== null) };
+ },
+ apply: (key, { requests, stoppable }) => {
+ if (key.isCurrent()) setValue({ epoch: key, sessionIds, cancellableIds, stoppable, requests: requests.filter((request) => vaultRequestType(request) !== 'other') });
+ },
+ fail: (key) => { if (key.isCurrent()) setValue(null); },
+ }), [api, sessionIds, cancellableIds]);
+ const initiallyRead = useRef(false);
+ useEffect(() => {
+ initiallyRead.current = false;
+ source.setKey(enabled ? epoch : null);
+ return () => source.setKey(null);
+ }, [source, enabled, epoch]);
+ const refresh = useCallback(() => {
+ if (!enabled || !epoch.isCurrent()) return;
+ initiallyRead.current = true;
+ source.refresh();
+ }, [source, enabled, epoch]);
+ useVaultRequestRefresh(refresh);
+ // The fallback hook performs the first visible read. When the bridge is
+ // already healthy it does not poll, so a new source/epoch still needs one.
+ useEffect(() => {
+ if (!initiallyRead.current) refresh();
+ }, [refresh]);
+ const requests = enabled && value?.epoch === epoch && value.sessionIds === sessionIds ? value.requests : [];
+ useEffect(() => {
+ const nextExpiry = Math.min(...requests.map((request) => Date.parse(request.expires_at ?? '')).filter((time) => time > Date.now()));
+ if (!Number.isFinite(nextExpiry)) return;
+ const timer = window.setTimeout(refresh, Math.min(nextExpiry - Date.now() + 250, 2_000_000_000));
+ return () => window.clearTimeout(timer);
+ }, [requests, refresh]);
+ return { requests, ready: !enabled || (value?.epoch === epoch && value.sessionIds === sessionIds), stoppable: enabled && value?.epoch === epoch && value.sessionIds === sessionIds && value.cancellableIds === cancellableIds ? value.stoppable : [] };
+}
+
const PetSurface: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
- const rawBinding = usePetBinding();
- const binding = rawBinding ?? null;
+ const binding = usePetBinding();
const { capabilities } = useInstanceAuthorization();
- const inbox = useWorkbenchInbox({ feed: false });
+ const inbox = useWorkbenchInbox();
const { expanded, setPanel } = usePetPanel();
- const { draft, uncertain, sending, listenPending, setDraft, setUncertain } = usePetComposer(binding);
- const data = usePetSession(binding, petShell.unbind);
+ const { draft, references: draftReferences, uncertain, sending, listenPending, setDraft, setUncertain } = usePetComposer(binding);
+ const data = usePetSession(binding);
const epoch = data.epoch;
const canChat = capabilities.can_chat && data.canChat === true;
- // Bind the stable main session when the shell has no current session. A session
- // it already handed out is never re-bound once it was cleared as invalid, so a
- // bad answer cannot turn into a bind/clear loop.
- const ensured = useRef<{ generation: number; ids: Set<string>; inFlight: boolean }>({ generation: -1, ids: new Set(), inFlight: false });
useEffect(() => {
- if (rawBinding !== null || !capabilities.can_chat) return;
- const state = ensured.current;
- if (state.generation !== epoch.authorizationGeneration) {
- ensured.current = { generation: epoch.authorizationGeneration, ids: new Set(), inFlight: false };
- }
- if (ensured.current.inFlight) return;
- const current = ensured.current;
- current.inFlight = true;
- void api.getMainSession().then((result) => {
- const session = result.session;
- if (!session || result.capabilities?.can_chat === false) return;
- if (!epoch.isCurrent() || current.ids.has(session.id)) return;
- current.ids.add(session.id);
- petShell.pick(session.id, epoch.isAuthorizationCurrent);
- }, () => undefined).finally(() => { current.inFlight = false; });
- }, [rawBinding, capabilities.can_chat, api, epoch]);
- const { requests: vaultRequests } = usePendingVaultRequests(binding ?? '');
+ if (canChat) petShell.normalizeMain(epoch);
+ }, [canChat, epoch]);
+ const { requests: vaultRequests } = usePendingVaultRequests(data.canChat === true ? binding ?? '' : '');
const unreadCount = binding ? inbox.unreadBySession[binding] ?? 0 : 0;
const state = derivePetState({
session: data.session,
@@ -180,50 +228,92 @@ const PetSurface: React.FC = () => {
const exchange = useMemo(() => latestExchange(data.messages, data.hasOlder, unreadCount), [data.messages, data.hasOlder, unreadCount]);
const failure = useMemo(() => latestFailureNotice(data.messages), [data.messages]);
const quickReplies = openQuickReplies(data.messages);
- const activeActivities = data.turn?.background_activities ?? EMPTY_ACTIVITIES;
- const activeSubtasks = activeActivities.filter(isRunning);
- const othersWorking = useConversationAgentWorking(capabilities.can_use_agents === true);
- const busy = data.running || activeSubtasks.length > 0 || othersWorking;
+ 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 activitySnapshotReady = inbox.unreadLoaded === true && !inbox.loading && runningAgents.ok && !repliesPending;
+ const visibleAgentRows = useMemo(() => (
+ [...(runningAgents.ok ? runningAgents.agents : []), ...repliedAgents].filter((agent) => (
+ agent.session_id
+ && agent.session_id !== binding
+ && agent.session_id !== 'ses_main'
+ && agent.visibility === 'foreground'
+ && agent.openable_in_chat
+ ))
+ ), [binding, runningAgents, repliedAgents]);
+ const activitySessionIds = JSON.stringify([...new Set(visibleAgentRows.map((row) => row.session_id!))].sort());
+ const cancellableIds = JSON.stringify(visibleAgentRows.filter((row) => (row.platform === 'avibe' || row.platform == null) && row.trigger_source === 'human' && row.state === 'active').map((row) => row.session_id).sort());
+ const { requests: visibleVaultRequests, stoppable, ready: activityActionsReady } = useVisibleActivityActions(capabilities.can_use_agents === true, epoch, activitySessionIds, cancellableIds);
+ const othersWorking = visibleAgentRows.some(isRunning);
+ const busy = data.running || othersWorking;
const [asleep, setAsleep] = useState(false);
- useEffect(() => {
- setAsleep(false);
- if (state !== 'idle' || busy) return;
- const timer = window.setTimeout(() => { if (epoch.isCurrent()) setAsleep(true); }, 5 * 60 * 1000);
- return () => window.clearTimeout(timer);
- }, [state, busy, epoch]);
- const pose: PetPose = derivePetPose(state, { othersWorking: othersWorking || activeSubtasks.length > 0, asleep });
const [detailOpen, setDetailOpen] = useState(false);
+ const cardsExpanded = expanded && !detailOpen;
+ const openCards = useCallback(() => {
+ setDetailOpen(false);
+ void setPanel(true);
+ }, [setPanel]);
+ const togglePanel = () => {
+ if (detailOpen) openCards();
+ else void setPanel(!petPanel.want());
+ };
const [composing, setComposing] = useState(false);
- const [stops, setStops] = useState<Record<string, StopPhase>>({});
+ const [presentations, setPresentations] = useState<Record<string, CardPresentation>>({});
+ const presentationNow = useRef<Record<string, CardPresentation>>({});
+ const [generations, setGenerations] = useState<Record<string, number>>({});
+ const generationNow = useRef<Record<string, number>>({});
+ const activityPresence = useRef(new Map<string, boolean>());
+ const stops = useMemo(() => Object.fromEntries(Object.entries(presentations)
+ .filter(([, value]) => value.phase).map(([key, value]) => [key, value.phase!])), [presentations]);
+ const leaving = useMemo(() => Object.keys(presentations).filter((key) => presentations[key].leaving), [presentations]);
+ const retainedCards = useMemo(() => Object.fromEntries(Object.entries(presentations)
+ .filter(([, value]) => value.retained).map(([key, value]) => [key, value.retained!])), [presentations]);
const dismissed = usePetDismissed();
- const [switcherOpen, setSwitcherOpen] = useState(false);
const [optimisticTitle, setOptimisticTitle] = useState('');
const reducedMotion = useReducedMotion();
- const [leaving, setLeaving] = useState<string[]>([]);
const [orderedIds, setOrderedIds] = useState<string[]>([]);
- const [retainedCards, setRetainedCards] = useState<Record<string, PetCard>>({});
const stopTimers = useRef<Record<string, number>>({});
const inputRef = useRef<HTMLTextAreaElement>(null);
const pressRef = useRef<{ held: boolean; dragged: boolean; x: number; y: number; timer: number } | null>(null);
const dismissTimers = useRef<Record<string, number>>({});
- const stopPhases = useRef<Record<string, StopPhase>>({});
- const leavingIds = useRef(new Set<string>());
+ const updatePresentation = useCallback((key: string, patch: CardPresentation | null) => {
+ const next = { ...presentationNow.current };
+ if (patch) next[key] = { ...next[key], ...patch };
+ else delete next[key];
+ presentationNow.current = next;
+ setPresentations(next);
+ }, []);
+ const retireCard = useCallback((key: string) => {
+ window.clearTimeout(stopTimers.current[key]);
+ window.clearTimeout(dismissTimers.current[key]);
+ delete stopTimers.current[key];
+ delete dismissTimers.current[key];
+ updatePresentation(key, null);
+ }, [updatePresentation]);
+ const isCurrentCard = useCallback((card: PetCard) => epoch.isCurrent()
+ && card.id === `${card.sessionId}:${generationNow.current[card.sessionId] ?? 0}`, [epoch]);
+ const advanceTurn = useCallback((sessionId: string) => {
+ if (!epoch.isCurrent()) return;
+ const previous = generationNow.current[sessionId] ?? 0;
+ generationNow.current = { ...generationNow.current, [sessionId]: previous + 1 };
+ retireCard(`${sessionId}:${previous}`);
+ setGenerations(generationNow.current);
+ petShell.forgetDismissed(sessionId);
+ }, [epoch, retireCard]);
const previousBinding = useRef(binding);
useLayoutEffect(() => {
setDetailOpen(false);
- setSwitcherOpen(false);
// Authorization changes remove authorized presentation, not the user's text.
if (previousBinding.current !== binding) {
setComposing(false);
setOptimisticTitle('');
previousBinding.current = binding;
}
- setStops({});
- setLeaving([]);
+ presentationNow.current = {};
+ setPresentations({});
+ generationNow.current = {};
+ setGenerations({});
+ activityPresence.current.clear();
setOrderedIds([]);
- setRetainedCards({});
- stopPhases.current = {};
- leavingIds.current.clear();
return () => {
Object.values(stopTimers.current).forEach(window.clearTimeout);
Object.values(dismissTimers.current).forEach(window.clearTimeout);
@@ -235,34 +325,55 @@ const PetSurface: React.FC = () => {
}, [binding, epoch]);
useEffect(() => {
if (expanded) return;
- // Collapsing leaves the switcher too, so the next expand shows the cards.
setDetailOpen(false);
- setSwitcherOpen(false);
}, [expanded]);
// The shell reports hover over Vibey and the dock: macOS gives a webview no
// hover while its window is not key, and the pet never takes focus itself.
const [hovered, setHovered] = useState(false);
useEffect(() => onPetHover(setHovered), []);
- const mainCard = useMemo<PetCard | null>(() => {
- const user = exchange.user;
- const latest = exchange.results.at(-1);
- if (!user && !latest && !failure && !optimisticTitle && !(uncertain && draft.trim())) return null;
- const title = optimisticTitle || (uncertain ? draft.trim() : '') || user?.text?.trim() || t('pet.mainAgentTitle');
- const subtitle = data.running
- ? t('pet.thinking')
- : failure
- ? `${t('pet.failedPrefix')} ${failure.text.trim()}`
- : latest?.text?.trim()
- ? `${t('pet.repliedPrefix')} ${latest.text.trim()}`
- : t('pet.waiting');
- return { id: 'main-agent', title, kind: 'backend_activity', status: subtitle, running: data.running, canPause: false, main: true };
- }, [data.running, exchange.results, exchange.user, failure, optimisticTitle, uncertain, draft, t]);
useEffect(() => {
if (exchange.user?.text?.trim() === optimisticTitle) setOptimisticTitle('');
}, [exchange.user, optimisticTitle]);
- const liveCards = useMemo(() => activeActivities.map((activity) => activityCard(activity, t('pet.untitledTask'), (key) => String(t(key as never)))), [activeActivities, t]);
+ const liveCards = useMemo(() => {
+ const bySession = new Map<string, RunningAgent>();
+ for (const agent of visibleAgentRows) {
+ if (!agent.session_id) continue;
+ const previous = bySession.get(agent.session_id);
+ if (!previous || (agent.state === 'active' && previous.state !== 'active')) bySession.set(agent.session_id, agent);
+ }
+ return [...bySession.values()].map((agent) => agentCard(
+ agent,
+ inbox.unreadBySession,
+ visibleVaultRequests,
+ stoppable,
+ t('pet.untitledTask'),
+ (key, options) => String(t(key as never, options as never)),
+ ))
+ .filter((card): card is PetCard => Boolean(card && (card.running || card.hasUnread || card.needsInput)))
+ .map((card) => ({ ...card, id: `${card.sessionId}:${generations[card.sessionId] ?? 0}` }));
+ }, [
+ inbox.unreadBySession,
+ t,
+ visibleAgentRows,
+ visibleVaultRequests,
+ stoppable,
+ generations,
+ ]);
+ // A healthy disappearance followed by reappearance is also a new local turn,
+ // including when its turn.start event was missed during a connection gap.
+ useLayoutEffect(() => {
+ if (!activitySnapshotReady || !activityActionsReady || !epoch.isCurrent()) return;
+ const present = new Set(liveCards.map((card) => card.sessionId));
+ for (const id of present) {
+ if (activityPresence.current.get(id) === false) advanceTurn(id);
+ activityPresence.current.set(id, true);
+ }
+ for (const id of activityPresence.current.keys()) {
+ if (!present.has(id)) activityPresence.current.set(id, false);
+ }
+ }, [liveCards, activitySnapshotReady, activityActionsReady, advanceTurn, epoch]);
const activities = useMemo(() => [
...liveCards.map((card) => retainedCards[card.id] ?? card),
...Object.values(retainedCards).filter((card) => !liveCards.some((live) => live.id === card.id)),
@@ -270,20 +381,20 @@ const PetSurface: React.FC = () => {
useEffect(() => {
setOrderedIds((current) => {
const live = new Set(activities.map((card) => card.id));
- const fresh = activities.filter((card) => !current.includes(card.id)).map((card) => card.id);
- const next = expanded && current.length > 0
- ? [...fresh, ...current.filter((id) => live.has(id))]
- : [...activities].sort((a, b) => Number(b.running) - Number(a.running)).map((card) => card.id);
+ const priority = (card: PetCard) => Number(card.needsInput) * 2 + Number(card.running);
+ const fresh = activities.filter((card) => !current.includes(card.id)).sort((a, b) => priority(b) - priority(a)).map((card) => card.id);
+ const byId = new Map(activities.map((card) => [card.id, card]));
+ const next = cardsExpanded && current.length > 0
+ ? [...current.filter((id) => live.has(id)), ...fresh].sort((a, b) => priority(byId.get(b)!) - priority(byId.get(a)!))
+ : [...activities].sort((a, b) => priority(b) - priority(a)).map((card) => card.id);
return next.length === current.length && next.every((id, i) => id === current[i]) ? current : next;
});
- }, [activities, expanded]);
+ }, [activities, cardsExpanded]);
useEffect(() => {
- // A missing initial read or an authorization recheck is not an empty turn.
- if (!data.turn || !binding) return;
- const liveIds = new Set(liveCards.map((card) => card.id));
- const next = dismissed.filter((id) => liveIds.has(id));
- if (next.length !== dismissed.length) petShell.setDismissed(binding, next);
- }, [liveCards, binding, data.turn, dismissed]);
+ if (!activitySnapshotReady) return;
+ const liveIds = new Set([...visibleAgentRows.map((row) => row.session_id), ...Object.keys(inbox.unreadBySession).filter((id) => inbox.unreadBySession[id] > 0)]);
+ for (const id of dismissed) if (!liveIds.has(id)) petShell.forgetDismissed(id);
+ }, [visibleAgentRows, inbox.unreadBySession, dismissed, activitySnapshotReady]);
const sortedActivities = useMemo(() => {
const byId = new Map(activities.map((card) => [card.id, card]));
@@ -291,18 +402,42 @@ const PetSurface: React.FC = () => {
const fresh = activities.filter((card) => !orderedIds.includes(card.id));
return [...fresh, ...ordered];
}, [activities, orderedIds]);
- const visibleCards = useMemo(() => [
- ...(mainCard ? [mainCard] : []),
- ...sortedActivities.filter((card) => !dismissed.includes(card.id)),
- ], [dismissed, mainCard, sortedActivities]);
+ const visibleCards = useMemo(
+ () => sortedActivities.filter((card) => !dismissed.includes(card.sessionId) && stops[card.id] !== 'exited'),
+ [dismissed, sortedActivities, stops],
+ );
+ // A result or authorization arriving after a stopped turn still deserves
+ // a card. This releases only that key; new turns use a new key altogether.
+ useEffect(() => {
+ if (!runningAgents.ok || !activityActionsReady) return;
+ for (const [key, presentation] of Object.entries(presentations)) {
+ const card = liveCards.find((item) => item.id === key);
+ if (presentation.phase === 'exited' && (!card?.running || card.hasUnread || card.needsInput)) retireCard(key);
+ }
+ }, [presentations, liveCards, runningAgents.ok, activityActionsReady, retireCard]);
+ useEffect(() => api.connectWorkbenchEvents({
+ onTurnStart: ({ session_id }) => advanceTurn(session_id),
+ }), [api, advanceTurn]);
+ const cardNeedsInput = liveCards.some((card) => card.needsInput);
+ const cardUnread = visibleCards.reduce((total, card) => total + (inbox.unreadBySession[card.sessionId] ?? 0), 0);
+ useEffect(() => {
+ setAsleep(false);
+ if (state !== 'idle' || busy || cardNeedsInput || cardUnread > 0) return;
+ const timer = window.setTimeout(() => { if (epoch.isCurrent()) setAsleep(true); }, 5 * 60 * 1000);
+ return () => window.clearTimeout(timer);
+ }, [state, busy, epoch, cardNeedsInput, cardUnread]);
+ const pose: PetPose = cardNeedsInput ? 'needs_input'
+ : state === 'idle' && cardUnread > 0 ? 'ready'
+ : derivePetPose(state, { othersWorking: liveCards.some((card) => card.running), asleep });
const closeComposer = useCallback(() => {
setComposing(false);
setDraft('');
}, [setDraft]);
- const openComposer = useCallback((text = '') => {
+ const openComposer = useCallback((text = '', selected?: SessionReference[]) => {
if (!epoch.isCurrent()) return;
- setDraft(text);
+ setDetailOpen(false);
+ setDraft(text, selected);
setComposing(true);
window.setTimeout(() => { if (epoch.isCurrent()) inputRef.current?.focus(); }, 0);
}, [setDraft, epoch]);
@@ -312,7 +447,12 @@ const PetSurface: React.FC = () => {
if (petComposer.isSending() || petComposer.isUncertain(binding)) return false;
petComposer.setSending(true);
try {
- const row = await api.sendSessionMessage(binding, { text: text.trim(), ...(metadata ? { metadata } : {}) });
+ const references = draftReferences.filter((reference) => text.includes(referenceToMarker(reference)));
+ const row = await api.sendSessionMessage(binding, {
+ text: text.trim(),
+ ...(references.length ? { content: { references } } : {}),
+ ...(metadata ? { metadata } : {}),
+ });
if (epoch.isCurrent()) {
data.noteSent(row && typeof row === 'object' && 'id' in row ? row : null);
setOptimisticTitle(text.trim());
@@ -335,42 +475,42 @@ 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]);
+ }, [api, binding, canChat, data, setPanel, setUncertain, epoch, draftReferences]);
const submit = async () => {
const submitted = draft;
if (!(await send(submitted)) || !epoch.isCurrent()) return;
if (petComposer.clearDraftIf(submitted)) setComposing(false);
};
const choose = (message: WorkbenchMessage, choice: string) => send(choice, { quick_reply_for: message.id });
+ const referenceCard = useCallback((card: PetCard) => {
+ if (!canChat || uncertain) return;
+ const marker = referenceToMarker({ kind: 'session', session_id: card.sessionId });
+ const next = draft.includes(marker) ? draft : [draft.trim(), marker].filter(Boolean).join(' ');
+ const selected = draftReferences.some((reference) => reference.session_id === card.sessionId)
+ ? draftReferences : [...draftReferences, { kind: 'session' as const, session_id: card.sessionId, title: card.title }];
+ openComposer(next, selected);
+ }, [draft, draftReferences, openComposer, canChat, uncertain]);
+ const draftMarkers = draftReferences.map(referenceToMarker);
+ const inputDraft = draftMarkers.length ? draftMarkers.reduce((text, marker) => text.replaceAll(marker, ''), draft).trimStart() : draft;
- const dismiss = useCallback((id: string) => {
- if (!epoch.isCurrent() || leavingIds.current.has(id) || id === 'main-agent') return;
- leavingIds.current.add(id);
- const card = visibleCards.find((item) => item.id === id);
- if (card) setRetainedCards((current) => ({ ...current, [id]: card }));
- setLeaving((current) => [...current, id]);
+ const dismiss = useCallback((card: PetCard, manual = true) => {
+ if (!isCurrentCard(card) || presentationNow.current[card.id]?.leaving) return;
+ updatePresentation(card.id, { leaving: true, retained: card });
const remove = () => {
- if (!epoch.isCurrent()) return;
- if (binding) {
- petShell.setDismissed(binding, [...new Set([...petShell.dismissed(), id])]);
- setLeaving((current) => current.filter((item) => item !== id));
- }
- leavingIds.current.delete(id);
- setRetainedCards((current) => { const next = { ...current }; delete next[id]; return next; });
+ if (!isCurrentCard(card)) return;
+ if (manual) petShell.addDismissed(card.sessionId);
+ updatePresentation(card.id, { leaving: false, retained: undefined, ...(!manual ? { phase: 'exited' as const } : {}) });
};
if (reducedMotion) remove();
- else dismissTimers.current[id] = window.setTimeout(remove, DISMISS_EXIT_MS);
- }, [binding, reducedMotion, visibleCards, epoch]);
+ else dismissTimers.current[card.id] = window.setTimeout(remove, DISMISS_EXIT_MS);
+ }, [reducedMotion, isCurrentCard, updatePresentation]);
const setStop = useCallback((card: PetCard) => {
- if (!epoch.isCurrent() || !card.canPause || card.main) return;
+ if (!isCurrentCard(card) || !card.canStop) return;
const updatePhase = (phase?: StopPhase) => {
- if (!epoch.isCurrent()) return;
- if (phase) stopPhases.current[card.id] = phase;
- else delete stopPhases.current[card.id];
- setStops({ ...stopPhases.current });
+ if (isCurrentCard(card)) updatePresentation(card.id, { phase });
};
- const phase = stopPhases.current[card.id];
+ const phase = presentationNow.current[card.id]?.phase;
if (!phase || phase === 'failed') {
updatePhase('confirm');
window.clearTimeout(stopTimers.current[card.id]);
@@ -379,20 +519,17 @@ const PetSurface: React.FC = () => {
}
if (phase !== 'confirm') return;
window.clearTimeout(stopTimers.current[card.id]);
- updatePhase('stopping');
- setRetainedCards((current) => ({ ...current, [card.id]: card }));
- const update = card.kind === 'watch' ? api.setHarnessWatchEnabled(harnessItemNativeId(card), false) : api.setHarnessTaskEnabled(harnessItemNativeId(card), false);
- void update.then((result) => {
- if (!epoch.isCurrent()) return;
+ updatePresentation(card.id, { phase: 'stopping', retained: card });
+ void api.cancelSession(card.sessionId).then((result) => {
+ if (!isCurrentCard(card)) return;
if (!result.ok) throw new Error('stop failed');
updatePhase('stopped');
- stopTimers.current[card.id] = window.setTimeout(() => dismiss(card.id), STOP_LINGER_MS);
+ stopTimers.current[card.id] = window.setTimeout(() => dismiss(card, false), STOP_LINGER_MS);
}).catch(() => {
- if (!epoch.isCurrent()) return;
- updatePhase('failed');
- setRetainedCards((current) => { const next = { ...current }; delete next[card.id]; return next; });
+ if (!isCurrentCard(card)) return;
+ updatePresentation(card.id, { phase: 'failed', retained: undefined });
});
- }, [api, dismiss, epoch]);
+ }, [api, dismiss, isCurrentCard, updatePresentation]);
const voice = usePetVoice({
enabled: canChat && Boolean(binding) && !uncertain,
@@ -417,13 +554,13 @@ const PetSurface: React.FC = () => {
}
return;
}
- void setPanel(true);
- setSwitcherOpen(false);
+ if (intent === 'show') openCards();
+ else void setPanel(true);
if (intent === 'listen') {
hotkeyHeld.current = true;
petComposer.requestListen();
}
- }, [setPanel, voice.stop, voice.listening, composing]);
+ }, [setPanel, openCards, voice.stop, voice.listening, composing]);
useOnSummon(onSummon);
useEffect(() => {
if (!listenPending || !binding || !canChat || !expanded) return;
@@ -442,12 +579,12 @@ const PetSurface: React.FC = () => {
if (event.key !== 'Escape') return;
if (voice.listening) voice.cancel();
else if (composing) closeComposer();
- else if (switcherOpen) setSwitcherOpen(false);
+ else if (detailOpen) { setDetailOpen(false); void setPanel(false); }
else void setPanel(false);
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
- }, [closeComposer, composing, setPanel, switcherOpen, voice]);
+ }, [closeComposer, composing, detailOpen, setPanel, voice]);
useEffect(() => {
const node = inputRef.current;
@@ -462,13 +599,23 @@ const PetSurface: React.FC = () => {
const [collapsedHeight, setCollapsedHeight] = useState(0);
useLayoutEffect(() => {
const node = collapsedRef.current;
- if (!node || expanded) return;
- const measure = () => setCollapsedHeight(node.getBoundingClientRect().height);
+ if (!node || cardsExpanded) return;
+ // The entrance scales this wrapper; layout height must include its spacing
+ // without capturing that transient transform.
+ const measure = () => setCollapsedHeight(node.offsetHeight);
measure();
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure);
observer?.observe(node);
return () => observer?.disconnect();
- }, [expanded, visibleCards.length]);
+ }, [cardsExpanded, visibleCards.length]);
+
+ const queued = (data.turn?.pending_input_count ?? 0) > 0;
+ const resolvingMain = data.canChat === null;
+ const showReplyBubble = Boolean(
+ binding && !resolvingMain
+ && (data.running || optimisticTitle || exchange.user || exchange.results.length > 0 || failure || uncertain
+ || queued || vaultRequests.length > 0 || quickReplies),
+ );
const avatar = (
<div className={clsx('pet-mini-avatar-wrap', voice.listening && 'is-listening', hovered && 'is-hovered')} data-pet-hover>
@@ -479,7 +626,7 @@ const PetSurface: React.FC = () => {
aria-label={t('pet.toggle')}
aria-expanded={expanded}
data-pet-hit
- onClick={(event) => { if (event.detail === 0) void setPanel(!petPanel.want()); }}
+ onClick={(event) => { if (event.detail === 0) togglePanel(); }}
onPointerDown={(event) => {
if (event.button !== 0) return;
const target = event.currentTarget;
@@ -516,7 +663,7 @@ const PetSurface: React.FC = () => {
if (!press) return;
window.clearTimeout(press.timer);
if (press.held) voice.stop(true);
- else if (!press.dragged) void setPanel(!petPanel.want());
+ else if (!press.dragged) togglePanel();
}}
onPointerLeave={() => {
const press = pressRef.current;
@@ -527,7 +674,7 @@ const PetSurface: React.FC = () => {
}}
onContextMenu={(event) => event.preventDefault()}
>
- <PetAvatar pose={voice.listening ? 'listening' : pose} badge={state === 'ready' ? unreadCount : 0} activities={activeSubtasks.length} />
+ <PetAvatar pose={voice.listening ? 'listening' : pose} badge={unreadCount + cardUnread} />
</button>
<MiniDock
enabled={canChat && Boolean(binding)}
@@ -548,45 +695,43 @@ const PetSurface: React.FC = () => {
return (
<div ref={rootRef} className="pet-mini-stage" data-pet-root data-busy={busy} data-state={state}>
- <div className={clsx('pet-mini-column', voice.listening && 'is-voice-active')}>
- <div className={clsx('pet-mini-cards', voice.listening && 'is-hidden')} inert={voice.listening || undefined} aria-label={expanded ? t('pet.panel') : undefined} style={{ height: expanded ? STACK_HEIGHT : collapsedHeight }}>
- <div ref={collapsedRef} key={expanded ? 'expanded' : 'collapsed'} className="pet-mini-swap is-switching" onAnimationEnd={(event) => { if (event.target === event.currentTarget) event.currentTarget.classList.remove('is-switching'); }}>
- {expanded && (!binding || switcherOpen) ? (
- <SessionPicker canStartVibey={capabilities.can_chat} onBack={binding ? () => setSwitcherOpen(false) : undefined} onPick={(sessionId) => {
- if (!epoch.isCurrent()) return;
- petShell.pick(sessionId, epoch.isAuthorizationCurrent);
- setSwitcherOpen(false);
- }} />
- ) : (expanded || visibleCards.length > 0) && (
- expanded ? (
+ <div className={clsx('pet-mini-column', voice.listening && 'is-voice-active')} style={{ '--pet-collapsed-height': `${collapsedHeight}px` } as CSSProperties}>
+ <div className={clsx('pet-mini-cards', voice.listening && 'is-hidden')} inert={voice.listening || undefined} aria-label={cardsExpanded ? t('pet.panel') : undefined} style={{ height: cardsExpanded ? (visibleCards.length > 0 ? STACK_HEIGHT : 'auto') : collapsedHeight }}>
+ <div ref={collapsedRef} key={cardsExpanded ? 'expanded' : 'collapsed'} className="pet-mini-swap is-switching" onAnimationEnd={(event) => { if (event.target === event.currentTarget) event.currentTarget.classList.remove('is-switching'); }}>
+ {visibleCards.length > 0 && (
+ cardsExpanded ? (
<ExpandedCards
cards={visibleCards}
leaving={leaving}
- detailOpen={detailOpen}
- onMain={() => setDetailOpen((open) => !open)}
- onSwitch={mainCard ? undefined : () => setSwitcherOpen(true)}
+ onReference={referenceCard}
onDismiss={dismiss}
stops={stops}
onStop={setStop}
t={(key, options) => String(t(key as never, options as never))}
- detail={binding ? <MainDetail epoch={epoch} voiceNeedsCloud={voice.cloudRequired} canChat={canChat} visible={detailOpen && !voice.listening} onSwitch={() => setSwitcherOpen(true)} binding={binding} exchange={exchange} failure={data.running ? null : failure} running={data.running} queued={(data.turn?.pending_input_count ?? 0) > 0} markRead={inbox.markRead} onRead={data.refreshTail} vaultRequestIds={vaultRequests.map((request) => request.id)} quickReplies={quickReplies} onChoose={choose} uncertain={uncertain} onInspect={() => { void petBridge.open(sessionLink(binding)).then(() => { if (epoch.isCurrent()) setUncertain(binding, false); }).catch(() => undefined); }} /> : null}
/>
) : (
- <CollapsedCards cards={visibleCards} onOpen={() => void setPanel(true)} t={(key) => String(t(key as never))} />
+ <CollapsedCards cards={visibleCards} onOpen={openCards} t={(key) => String(t(key as never))} />
)
)}
</div>
</div>
- <SpeechSlot open={voice.listening || composing}>
- {voice.listening ? <Marquee text={voice.preview} listeningLabel={t('pet.voice.listening')} /> : canChat && !uncertain ? (
+ <SpeechSlot open={voice.listening || composing || showReplyBubble || resolvingMain || !binding}>
+ {voice.listening ? <Marquee text={voice.preview} listeningLabel={t('pet.voice.listening')} /> : composing && canChat && !uncertain ? (
<>
{voice.error && <p className="pet-mini-input-note" role="status">{t(`pet.voice.${voice.error}`)}</p>}
<form className="pet-mini-input" data-pet-hit onSubmit={(event) => { event.preventDefault(); void submit(); }}>
+ {draftReferences.length > 0 && <div className="pet-mini-references">
+ {draftReferences.map((reference) => <span key={reference.session_id} className="pet-mini-reference-chip">
+ <span title={reference.title ?? reference.session_id}># {reference.title ?? reference.session_id}</span>
+ <button type="button" aria-label={t('pet.removeReference', { title: reference.title ?? reference.session_id })} onClick={() => setDraft(draft.replaceAll(referenceToMarker(reference), '').trim())}><X size={12} /></button>
+ </span>)}
+ </div>}
+ <div className="pet-mini-input-row">
<textarea
ref={inputRef}
rows={1}
- value={draft}
- onChange={(event) => setDraft(event.target.value)}
+ value={inputDraft}
+ onChange={(event) => setDraft([...draftMarkers, event.target.value].join(' '))}
onKeyDown={(event) => {
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
event.preventDefault();
@@ -598,8 +743,35 @@ const PetSurface: React.FC = () => {
/>
{voice.available && <button type="button" className="pet-mini-input-button" onClick={() => voice.start()} aria-label={t('pet.voiceContinue')}><MicIcon /></button>}
<button type="submit" className="pet-mini-send" disabled={!draft.trim() || sending || uncertain} aria-label={t('pet.send')}><SendIcon /></button>
+ </div>
</form>
</>
+ ) : showReplyBubble && binding ? (
+ <MainReplyBubble
+ open={detailOpen && expanded}
+ onToggle={() => { setDetailOpen(!detailOpen); void setPanel(!detailOpen); }}
+ epoch={epoch}
+ voiceNeedsCloud={voice.cloudRequired}
+ 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}
+ markRead={inbox.markRead}
+ onRead={data.refreshTail}
+ vaultRequestIds={vaultRequests.map((request) => request.id)}
+ quickReplies={quickReplies}
+ onChoose={choose}
+ uncertain={uncertain}
+ onInspect={() => { void petBridge.open(sessionLink(binding)).then(() => { if (epoch.isCurrent()) setUncertain(binding, false); }).catch(() => undefined); }}
+ />
+ ) : 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>
+ <Button variant="link" size="sm" className="px-0" onClick={() => void petBridge.open('avibe://settings')}>{t('pet.openInAvibe')}</Button>
+ </div>
) : null}
</SpeechSlot>
</div>
@@ -608,57 +780,6 @@ const PetSurface: React.FC = () => {
);
};
-const SwitchSessionButton: React.FC<{ onClick: () => void; label: string }> = ({ onClick, label }) => (
- <button type="button" className="pet-mini-chip" data-pet-hit aria-label={label} onClick={onClick}><ArrowLeftRight aria-hidden />{label}</button>
-);
-
-const SessionPicker: React.FC<{ onPick: (sessionId: string) => void; onBack?: () => void; canStartVibey: boolean }> = ({ onPick, onBack, canStartVibey }) => {
- const { t } = useTranslation();
- const api = useApi();
- const { sessions, loading } = useSessionSwitcher(true);
- const [vibeyError, setVibeyError] = useState<string | null>(null);
- const [vibeyPending, setVibeyPending] = useState(false);
- const mounted = useRef(true);
- useEffect(() => {
- mounted.current = true;
- return () => { mounted.current = false; };
- }, []);
- const pickVibey = () => {
- if (vibeyPending) return;
- setVibeyPending(true);
- setVibeyError(null);
- api.getMainSession().then((result) => {
- if (!result.session) {
- if (mounted.current) setVibeyError(t('pet.vibeyUnavailable'));
- return;
- }
- if (mounted.current) onPick(result.session.id);
- }, (error: unknown) => {
- if (mounted.current) setVibeyError(error instanceof ApiError && error.code === 'no_chat_project' ? t('pet.noChatProject') : t('pet.vibeyUnavailable'));
- }).finally(() => { if (mounted.current) setVibeyPending(false); });
- };
- return (
- <div className="pet-mini-panel" aria-label={t('pet.chooseSession')}>
- <div className="pet-mini-scroll">
- {onBack && (
- <div className="pet-mini-action-row">
- <button type="button" className="pet-mini-chip" data-pet-hit onClick={onBack}><ArrowLeft aria-hidden />{t('common.back')}</button>
- </div>
- )}
- <div className="pet-mini-session-picker" data-pet-hit>
- {canStartVibey && <button type="button" onClick={pickVibey} disabled={vibeyPending} className="pet-mini-session-option is-vibey">{t('pet.talkToVibey')}</button>}
- {vibeyError && <p className="pet-mini-detail-muted">{vibeyError}</p>}
- {sessions.length === 0 && <p className="pet-mini-detail-muted">{loading ? t('common.loading') : t('pet.noSessions')}</p>}
- {sessions.map((session) => (
- <button key={session.id} type="button" onClick={() => onPick(session.id)} className="pet-mini-session-option">
- {session.title || t('pet.untitled')}
- </button>
- ))}
- </div>
- </div>
- </div>
- );
-};
function useReducedMotion() {
const [reduced, setReduced] = useState(() => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false);
@@ -875,7 +996,7 @@ const CollapsedCards: React.FC<{ cards: PetCard[]; onOpen: () => void; t: (key:
);
};
-const ExpandedCards: React.FC<{ cards: PetCard[]; leaving: string[]; detailOpen: boolean; onMain: () => void; onSwitch?: () => void; onDismiss: (id: string) => void; stops: Record<string, StopPhase>; onStop: (card: PetCard) => void; t: (key: string, options?: Record<string, unknown>) => string; detail: ReactNode }> = ({ cards, leaving, detailOpen, onMain, onSwitch, onDismiss, stops, onStop, t, detail }) => {
+const ExpandedCards: React.FC<{ cards: PetCard[]; leaving: string[]; onReference: (card: PetCard) => void; onDismiss: (card: PetCard) => void; stops: Record<string, StopPhase>; onStop: (card: PetCard) => void; t: (key: string, options?: Record<string, unknown>) => string }> = ({ cards, leaving, onReference, onDismiss, stops, onStop, t }) => {
const scrollRef = useRef<HTMLDivElement>(null);
const [edges, setEdges] = useState({ top: 0, bottom: 0 });
const measure = useCallback(() => {
@@ -893,21 +1014,19 @@ const ExpandedCards: React.FC<{ cards: PetCard[]; leaving: string[]; detailOpen:
const list = node.querySelector('.pet-mini-list');
if (list) observer.observe(list);
return () => observer.disconnect();
- }, [measure, cards.length, detailOpen]);
+ }, [measure, cards.length]);
const mask = `linear-gradient(to bottom, transparent 0, #000 ${edges.top}px, #000 calc(100% - ${edges.bottom}px), transparent 100%)`;
return (
<div className="pet-mini-panel">
<div ref={scrollRef} onScroll={measure} className="pet-mini-scroll" style={{ maskImage: mask, WebkitMaskImage: mask }}>
- {onSwitch && <div className="pet-mini-action-row"><SwitchSessionButton onClick={onSwitch} label={t('pet.switchSession')} /></div>}
<ul className="pet-mini-list">
{cards.map((card) => {
const phase = stops[card.id];
return (
<li key={card.id} className={clsx('pet-mini-row', leaving.includes(card.id) && 'is-leaving')}>
- <div className="pet-mini-row-inner"><div className={clsx('pet-mini-row-body', card.main && 'is-main')}>
- <div className={clsx('pet-mini-card-wrap', card.main && 'is-main')} data-pet-hit>
- <CardBody card={card} expanded t={t} phase={phase} onDismiss={() => onDismiss(card.id)} onStop={() => onStop(card)} onClick={card.main ? onMain : undefined} />
- {card.main && <div className={clsx('pet-mini-detail', detailOpen && 'is-open')}><div className="pet-mini-detail-clip" inert={!detailOpen || undefined}>{detail}</div></div>}
+ <div className="pet-mini-row-inner"><div className="pet-mini-row-body">
+ <div className="pet-mini-card-wrap" data-pet-hit>
+ <CardBody card={card} expanded t={t} phase={phase} onDismiss={() => onDismiss(card)} onStop={() => onStop(card)} onClick={() => onReference(card)} />
</div>
</div></div>
</li>
@@ -921,34 +1040,72 @@ const ExpandedCards: React.FC<{ cards: PetCard[]; leaving: string[]; detailOpen:
const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, options?: Record<string, unknown>) => string; phase?: StopPhase; onDismiss?: () => void; onStop?: () => void; onClick?: () => void }> = ({ card, expanded, t, phase, onDismiss, onStop, onClick }) => {
const running = card.running && phase !== 'stopped' && phase !== 'stopping';
- const subtitle = phase === 'stopping' ? t(isPausable(card) ? 'pet.stop.pausing' : 'pet.stop.stopping') : phase === 'stopped' ? t(isPausable(card) ? 'pet.stop.paused' : 'pet.stop.stopped') : phase === 'failed' ? t('pet.stop.failed') : card.status;
- const stopText = isPausable(card) ? t('pet.stop.confirmPause') : t('pet.stop.confirmStop');
+ 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';
return (
- <article className={clsx('pet-mini-card', card.main && 'is-main')} title={card.title} data-pet-hit onClick={onClick} role={onClick ? 'button' : undefined} tabIndex={onClick ? 0 : undefined} onKeyDown={onClick ? (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); onClick(); } } : undefined}>
- {expanded && !card.main && <button type="button" className="pet-mini-dismiss" data-pet-hit onClick={(event) => { event.stopPropagation(); 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>}
- <div className="pet-mini-card-content">
- {card.main && <div className="pet-mini-eyebrow">{t('pet.mainAgent')}</div>}
+ <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>}
+ <Reference className="pet-mini-card-content pet-mini-card-reference" onClick={onClick} {...(expanded ? { type: 'button' as const, 'aria-label': t('pet.referenceSession', { title: card.title }) } : {})}>
+ <div className="pet-mini-eyebrow"><span title={card.eyebrow}>{card.eyebrow}</span></div>
<div className="pet-mini-title">{card.title}</div>
<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>
</div>
- </div>
- {expanded && card.canPause && !card.main && phase !== 'stopped' && (
- <button type="button" className={clsx('pet-mini-stop', phase === 'confirm' && 'is-confirm')} onClick={(event) => { event.stopPropagation(); onStop?.(); }} disabled={phase === 'stopping'} aria-label={stopText}>
- {phase === 'confirm' ? stopText : phase === 'stopping' ? <span className="pet-mini-spinner" aria-hidden /> : <StopIcon />}
- </button>
+ </Reference>
+ {expanded && (
+ <div className="pet-mini-card-actions">
+ {card.needsInput && card.vaultRequestIds[0] ? (
+ <button type="button" className="pet-mini-authorize" onClick={() => void petBridge.open(vaultRequestLink(card.vaultRequestIds[0]))}><KeyRound className="size-3.5" />{t('pet.authorize')}</button>
+ ) : card.canStop && phase !== 'stopped' ? (
+ <button type="button" className={clsx('pet-mini-stop', phase === 'confirm' && 'is-confirm')} onClick={onStop} disabled={phase === 'stopping'} aria-label={stopText}>
+ {phase === 'confirm' ? stopText : phase === 'stopping' ? <span className="pet-mini-spinner" aria-hidden /> : <StopIcon />}
+ </button>
+ ) : null}
+ {card.canOpen && <button type="button" className="pet-mini-open" onClick={() => void petBridge.open(sessionLink(card.sessionId))} aria-label={t('pet.openInAvibe')} title={t('pet.openInAvibe')}><ExternalLink className="size-3.5" /></button>}
+ </div>
)}
</article>
);
};
-const MainDetail: React.FC<{ epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; canChat: boolean; visible: boolean; onSwitch: () => void; 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 }> = (props) => {
+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 };
+
+const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boolean; onToggle: () => void }> = ({ open, onToggle, ...props }) => {
+ const { t } = useTranslation();
+ const last = 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() })
+ : t('pet.waiting');
+ return (
+ <div className="pet-mini-reply-bubble" data-pet-hit>
+ <button type="button" className="pet-mini-reply-toggle" onClick={onToggle} aria-expanded={open}>
+ <span className="pet-mini-bubble-speaker">{t('pet.mainAgent')}<span>{t(open ? 'pet.collapseHistory' : 'pet.recentTurns')}<ChevronRight size={11} /></span></span>
+ <p title={summary}>{props.running && <span className="pet-mini-running-dot" aria-hidden />}<span className="pet-mini-reply-summary">{summary}</span></p>
+ </button>
+ <div className={clsx('pet-mini-detail', open && 'is-open')}>
+ <div className="pet-mini-detail-clip" inert={!open || undefined}>
+ <div className="pet-mini-bubble-history"><MainDetail {...props} visible={open} /></div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+const MainDetail: React.FC<MainDetailProps> = (props) => {
const { t } = useTranslation();
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);
+ useLayoutEffect(() => {
+ if (!props.visible) return;
+ const result = lastResultRef.current;
+ const history = result?.closest<HTMLElement>('.pet-mini-bubble-history');
+ if (result && history) history.scrollTop = result.offsetTop + result.offsetHeight - history.clientHeight;
+ }, [props.visible, resultKey]);
useEffect(() => {
const node = lastResultRef.current;
if (!props.visible || !node) return;
@@ -956,17 +1113,20 @@ const MainDetail: React.FC<{ epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; c
const observer = new IntersectionObserver(([entry]) => {
if (props.epoch.isCurrent()) setSeenResult(entry.isIntersecting ? { epoch: props.epoch, key: resultKey } : null);
}, {
- root: node.closest('.pet-mini-scroll'),
+ root: node.closest('.pet-mini-bubble-history'),
});
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);
return (
<div className="pet-mini-detail-inner">
- <div className="pet-mini-action-row"><SwitchSessionButton onClick={props.onSwitch} label={t('pet.switchSession')} /></div>
- {props.exchange.user && <div className="pet-mini-detail-user"><Markdown content={props.exchange.user.text} softBreaks /></div>}
- {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} softBreaks /></div>)}
+ {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.user && <div className="pet-mini-detail-user"><Markdown content={props.exchange.user.text} references={(props.exchange.user.content as { references?: MentionReference[] })?.references} softBreaks /></div>}
+ {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.failure && (
<div className="pet-mini-detail-notice" role="status">
<p>{props.failure.text}</p>
diff --git a/ui/src/pet/fencedSource.ts b/ui/src/pet/fencedSource.ts
index 7819d7fdf..1ee860a53 100644
--- a/ui/src/pet/fencedSource.ts
+++ b/ui/src/pet/fencedSource.ts
@@ -2,9 +2,8 @@
* One input of the pet, read from an authoritative API and kept fresh by live
* events. Every read is fenced twice:
*
- * - by key: a result applies only while its key (the bound session, or the
- * switcher's constant key while it is open) is still current, so switching
- * from A to B never shows A's state;
+ * - by key: a result applies only while its session or authorization key
+ * is still current, so an old context never supplies a new context's state;
* - by order: starting a read and merging a live event both advance the
* generation, and a result applies only if nothing newer happened on this
* source since it started. A merge that overtakes an in-flight read schedules
diff --git a/ui/src/pet/pet-mini.css b/ui/src/pet/pet-mini.css
index c57854184..bc66a6ffc 100644
--- a/ui/src/pet/pet-mini.css
+++ b/ui/src/pet/pet-mini.css
@@ -67,10 +67,6 @@
text-align:left;
pointer-events:auto}
-.pet-mini-card.is-main {
- background:var(--pet-main);
- border-color:color-mix(in srgb,var(--mint) 45%,transparent)}
-
.pet-mini-card-content {
min-width:0;
flex:1}
@@ -173,9 +169,6 @@ to {
min-width:0;
perspective:900px;
padding-bottom:8px}
-.pet-mini-row-body.is-main {
- padding-bottom:16px}
-
.pet-mini-row.is-leaving {
grid-template-rows:0fr;
pointer-events:none}
@@ -375,10 +368,40 @@ to {
color:color-mix(in srgb,var(--pet-ink) 45%,transparent)}
.pet-mini-input {
- align-items:flex-end;
+ flex-direction:column;
+ align-items:stretch;
gap:6px;
border:1px solid color-mix(in srgb,var(--pet-ink) 10%,transparent);
padding:6px 6px 6px 14px}
+.pet-mini-input-row {
+ display:flex;
+ align-items:flex-end;
+ gap:6px;
+ min-width:0}
+.pet-mini-references {
+ display:flex;
+ flex-wrap:wrap;
+ gap:4px;
+ padding-top:4px}
+.pet-mini-reference-chip {
+ display:inline-flex;
+ max-width:100%;
+ min-width:0;
+ align-items:center;
+ gap:6px;
+ padding:2px 6px;
+ border-radius:6px;
+ background:var(--mint-soft);
+ color:var(--mint-ink);
+ font-size:11px}
+.pet-mini-reference-chip > span {
+ min-width:0;
+ overflow:hidden;
+ text-overflow:ellipsis;
+ white-space:nowrap}
+.pet-mini-reference-chip button {
+ flex:none;
+ cursor:pointer}
.pet-mini-input textarea {
min-width:0;
max-height:96px;
@@ -415,91 +438,6 @@ to {
color:color-mix(in srgb,var(--pet-ink) 30%,transparent);
cursor:default}
-/* The picker is a card like the others (no backing panel, §3.2), bottom-aligned
- next to Vibey. `flex:none` keeps the scroll box from shrinking it to 292px: a
- shrunk column squeezes its overflow-hidden rows below their text height. */
-.pet-mini-session-picker {
- display:flex;
- flex:none;
- flex-direction:column;
- gap:2px;
- min-width:0;
- margin-top:auto;
- border:1px solid color-mix(in srgb,var(--pet-ink) 8%,transparent);
- border-radius:28px;
- padding:8px;
- background:var(--pet-card);
- pointer-events:auto}
-.pet-mini-session-picker > .pet-mini-detail-muted {
- padding:9px 12px;
- font-size:13px}
-.pet-mini-session-option {
- flex:none;
- min-width:0;
- border:0;
- border-radius:12px;
- background:transparent;
- padding:9px 12px;
- color:var(--pet-ink);
- text-align:left;
- font-size:13px;
- line-height:19.5px;
- overflow:hidden;
- text-overflow:ellipsis;
- white-space:nowrap;
- cursor:pointer}
-.pet-mini-session-option:hover {
- background:color-mix(in srgb,var(--pet-ink) 8%,transparent)}
-.pet-mini-session-option:disabled {
- cursor:default;
- opacity:.5}
-.pet-mini-session-option.is-vibey {
- color:color-mix(in srgb,var(--mint) 90%,transparent);
- font-weight:600}
-
-/* Small pill action on the dark mini surface ("Switch session"). */
-.pet-mini-action-row {
- display:flex;
- justify-content:flex-end;
- min-width:0}
-.pet-mini-detail-inner > .pet-mini-action-row {
- margin-bottom:10px}
-/* Without a main card the row sits directly above the bottom-aligned list. */
-.pet-mini-scroll > .pet-mini-action-row {
- flex:none;
- margin-top:auto;
- padding-top:10px}
-.pet-mini-scroll > .pet-mini-action-row + .pet-mini-list {
- margin-top:0}
-.pet-mini-scroll > .pet-mini-action-row + .pet-mini-session-picker {
- margin-top:8px}
-.pet-mini-chip {
- display:inline-flex;
- align-items:center;
- gap:6px;
- height:28px;
- border:1px solid color-mix(in srgb,var(--pet-ink) 10%,transparent);
- border-radius:999px;
- padding:0 12px;
- background:color-mix(in srgb,var(--pet-ink) 8%,transparent);
- color:color-mix(in srgb,var(--pet-ink) 82%,transparent);
- font-size:12px;
- font-weight:500;
- white-space:nowrap;
- cursor:pointer;
- pointer-events:auto;
- transition:background 150ms ease,color 150ms ease}
-.pet-mini-chip:hover {
- background:color-mix(in srgb,var(--pet-ink) 14%,transparent);
- color:var(--pet-ink)}
-.pet-mini-chip:focus-visible {
- outline:2px solid color-mix(in srgb,var(--mint) 70%,transparent);
- outline-offset:2px}
-.pet-mini-chip svg {
- width:14px;
- height:14px;
- flex:none}
-
.pet-mini-avatar-wrap {
position:absolute;
left:50%;
@@ -643,17 +581,6 @@ to {
white-space: nowrap;
}
-.pet-mini-card-wrap.is-main {
- border: 1px solid color-mix(in srgb,var(--mint) 45%,transparent);
- border-radius: 28px;
- background: var(--pet-main);
- }
-
-.pet-mini-card-wrap.is-main > .pet-mini-card {
- border: 0;
- background: transparent;
- }
-
.pet-mini-card[role=button] {
cursor: pointer;
}
@@ -745,3 +672,133 @@ to {
color:color-mix(in srgb,var(--pet-ink) 70%,transparent);
font-size:12px;
line-height:16px}
+
+/* Personal-agent speech and activities share the v2 fixed mini column. */
+.pet-mini-card-reference {
+ display:block;
+ border:0;
+ background:transparent;
+ padding:0;
+ color:inherit;
+ text-align:left;
+ cursor:pointer}
+.pet-mini-card-reference .pet-mini-eyebrow {
+ display:flex;
+ align-items:center;
+ gap:6px;
+ line-height:16px;
+ color:color-mix(in srgb,var(--pet-ink) 65%,transparent)}
+.pet-mini-eyebrow > span {
+ min-width:0;
+ overflow:hidden;
+ text-overflow:ellipsis;
+ white-space:nowrap}
+.pet-mini-card.is-needs-input {
+ border-color:var(--gold);
+ background:color-mix(in srgb,var(--gold) 8%,var(--pet-card))}
+.pet-mini-card.is-needs-input .pet-mini-subtitle {
+ color:var(--gold)}
+.pet-mini-card.is-needs-input .pet-mini-running-dot {
+ background:var(--gold)}
+.pet-mini-card-actions {
+ display:flex;
+ align-items:center;
+ flex:none;
+ gap:6px;
+ padding-top:2px;
+ margin-right:-4px;
+ margin-left:12px}
+.pet-mini-card-actions .pet-mini-stop {
+ margin:0}
+.pet-mini-open,.pet-mini-authorize {
+ display:inline-flex;
+ align-items:center;
+ justify-content:center;
+ gap:4px;
+ height:32px;
+ border:0;
+ border-radius:999px;
+ color:color-mix(in srgb,var(--pet-ink) 75%,transparent);
+ background:color-mix(in srgb,var(--pet-ink) 8%,transparent);
+ cursor:pointer}
+.pet-mini-open { width:32px }
+.pet-mini-authorize {
+ padding:0 10px;
+ color:var(--gold);
+ font-size:12px}
+.pet-mini-open:hover,.pet-mini-authorize:hover {
+ background:color-mix(in srgb,var(--pet-ink) 14%,transparent)}
+.pet-mini-card-reference:focus-visible,.pet-mini-reply-toggle:focus-visible {
+ outline:2px solid var(--mint);
+ outline-offset:2px;
+ border-radius:8px}
+.pet-mini-reply-bubble {
+ position:relative;
+ width:100%;
+ min-width:0;
+ border:1px solid color-mix(in srgb,var(--pet-ink) 10%,transparent);
+ border-radius:22px;
+ background:var(--pet-card)}
+.pet-mini-reply-bubble:after {
+ position:absolute;
+ bottom:-6px;
+ left:calc(50% - 7px);
+ width:14px;
+ height:14px;
+ border-right:1px solid color-mix(in srgb,var(--pet-ink) 10%,transparent);
+ border-bottom:1px solid color-mix(in srgb,var(--pet-ink) 10%,transparent);
+ border-radius:0 0 3px 0;
+ background:inherit;
+ content:"";
+ transform:rotate(45deg);
+ pointer-events:none}
+.pet-mini-reply-toggle {
+ display:block;
+ width:100%;
+ padding:10px 14px;
+ color:inherit;
+ text-align:left;
+ cursor:pointer}
+.pet-mini-bubble-speaker {
+ display:flex;
+ align-items:center;
+ justify-content:space-between;
+ color:var(--mint-ink);
+ font-size:11px;
+ line-height:16px;
+ font-weight:600}
+.pet-mini-bubble-speaker > span {
+ display:flex;
+ align-items:center;
+ gap:4px;
+ color:color-mix(in srgb,var(--pet-ink) 60%,transparent);
+ font-size:10px;
+ font-weight:400}
+.pet-mini-reply-toggle[aria-expanded=true] svg { transform:rotate(90deg) }
+.pet-mini-reply-toggle p {
+ display:flex;
+ align-items:center;
+ 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}
+.pet-mini-bubble-history {
+ position:relative;
+ z-index:1;
+ /* Share the list's 292px box, bounded by the fixed avatar/dock reservation
+ (147px), bubble header (62px), top inset (16px), and measured stack. */
+ max-height:min(292px,max(0px,calc(100dvh - 225px - var(--pet-collapsed-height,0px))));
+ overflow:auto;
+ overscroll-behavior:contain;
+ border-top:1px solid color-mix(in srgb,var(--pet-ink) 8%,transparent);
+ scrollbar-width:thin}
+.pet-mini-bubble-history .pet-mini-detail-inner { padding:8px 14px }
+.pet-mini-swap:has(.pet-mini-collapsed) { padding-bottom:14px }
diff --git a/ui/src/pet/petBridge.ts b/ui/src/pet/petBridge.ts
index af3701549..a9e94edfa 100644
--- a/ui/src/pet/petBridge.ts
+++ b/ui/src/pet/petBridge.ts
@@ -1,42 +1,9 @@
import { isDesktopShell } from '@/lib/desktopShell';
import { openLinkInNewContext } from '@/lib/pwaNavigation';
-/**
- * The desktop pet's channel to the native shell. This file is the contract the
- * shell implements (docs/plans/2026-10-01-desktop-pet.md, "Shell ↔ pet IPC"):
- *
- * Page → shell, Tauri commands granted only to the `pet` window:
- * pet_ready() -> PetBinding & { summon_pending: { intent } | null }
- * pet_set_expanded({ expanded }) -> PetLayout
- * pet_bind({ sessionId }) -> PetBinding & { shown: boolean }
- * pet_unbind({ sessionId }) -> PetBinding compare-and-clear
- * pet_open({ link }) any link the deep-link parser accepts
- * plugin:window|start_dragging the `start-dragging` permission
- *
- * Workbench → shell, granted only to the `main` window ("Show in pet"):
- * pet_bind({ sessionId }) -> PetBinding & { shown: boolean }
- * also brings the pet forward; `shown`
- * is false while the pet is turned off
- *
- * Shell → page, DOM events dispatched on `window` by a shell-evaluated script
- * (the same channel as the Settings… menu, so no event permission is needed):
- * avibe:pet-summon detail { intent } only after pet_ready(); earlier summons
- * are returned by pet_ready() instead
- * avibe:pet-bound detail { session_id: string | null, revision }
- * avibe:pet-hover detail { hover: boolean } the cursor entered or left
- * the hit rects reported with `hover`;
- * a webview in a window that is not
- * key gets no hover of its own on macOS
- *
- * `revision` is the shell's binding revision: it grows by one on every change
- * to the binding, and every answer and event carries the revision it reflects.
- * Answers and events travel on different channels and may arrive out of
- * order, so the page applies only a revision newer than the last it applied.
- *
- * Outside the shell (a browser tab during development) the bridge keeps the
- * binding in localStorage with the same fixed mini layout, so the route
- * stays usable without the native window.
- */
+/** Native window/layout transport. pet_ready still parses legacy persisted
+ * bindings for backwards compatibility; only GET /api/sessions/main selects
+ * the conversation. The only binding write normalizes native storage to main. */
export type PetIntent = 'listen' | 'show' | 'release';
@@ -53,7 +20,6 @@ export type PetBinding = {
export type PetReady = PetBinding & {
summon_pending: { intent: PetIntent } | null;
- dismissed_ids: string[];
};
export const PET_SUMMON_EVENT = 'avibe:pet-summon';
@@ -102,31 +68,18 @@ const readDevBinding = (): PetBinding => {
return devMemory;
};
-const writeDevBinding = (sessionId: string | null): PetBinding => {
- devMemory = { binding: sessionId, revision: readDevBinding().revision + 1 };
- try {
- window.localStorage.setItem(DEV_BINDING_KEY, JSON.stringify(devMemory));
- } catch {
- /* storage unavailable: the binding lasts for this page only */
- }
- return devMemory;
-};
-
export const petBridge = {
/** True inside the native pet window. */
native: (): boolean => shellInvoke() !== null,
ready: async (): Promise<PetReady> => {
const invoke = shellInvoke();
- if (!invoke) return { ...readDevBinding(), summon_pending: null, dismissed_ids: [] };
+ if (!invoke) return { ...readDevBinding(), summon_pending: null };
const result = (await invoke('pet_ready')) as { summon_pending?: { intent?: unknown } | null } | null;
const pending = result?.summon_pending;
return {
...parseBinding(result),
summon_pending: pending && isIntent(pending.intent) ? { intent: pending.intent } : null,
- dismissed_ids: Array.isArray((result as { dismissed_ids?: unknown } | null)?.dismissed_ids)
- ? (result as { dismissed_ids: unknown[] }).dismissed_ids.filter((id): id is string => typeof id === 'string')
- : [],
};
},
@@ -146,39 +99,17 @@ export const petBridge = {
await invoke('pet_hit_regions', { rects });
},
- setDismissedIds: async (sessionId: string, ids: string[]): Promise<void> => {
- const invoke = shellInvoke();
- if (!invoke) return;
- await invoke('pet_set_dismissed', { sessionId, ids });
- },
-
- bind: async (sessionId: string): Promise<PetBinding> => {
- const invoke = shellInvoke();
- if (!invoke) return writeDevBinding(sessionId);
- return parseBinding(await invoke('pet_bind', { sessionId }));
- },
-
- /** Clears the binding only if it is still `sessionId`. */
- unbind: async (sessionId: string): Promise<PetBinding> => {
+ /** Normalize the legacy binding; callers cannot choose another session. */
+ bindMain: async (): Promise<PetBinding> => {
const invoke = shellInvoke();
- if (!invoke) {
- const current = readDevBinding();
- return current.binding === sessionId ? writeDevBinding(null) : current;
+ if (invoke) return parseBinding(await invoke('pet_bind', { sessionId: 'ses_main' }));
+ devMemory = { binding: 'ses_main', revision: readDevBinding().revision + 1 };
+ try {
+ window.localStorage.setItem(DEV_BINDING_KEY, JSON.stringify(devMemory));
+ } catch {
+ // Browser preview without storage keeps the normalized state in memory.
}
- return parseBinding(await invoke('pet_unbind', { sessionId }));
- },
-
- /**
- * The Workbench's "Show in pet": binds the pet to `sessionId` and brings it
- * forward. `shown` is false while the pet is turned off; the binding is kept
- * for when it is turned on.
- */
- showInPet: async (sessionId: string): Promise<{ shown: boolean }> => {
- const invoke = shellInvoke();
- if (!invoke) throw new Error('the desktop pet is only available in the Avibe desktop app');
- const result = (await invoke('pet_bind', { sessionId })) as { shown?: unknown } | null;
- parseBinding(result);
- return { shown: result?.shown === true };
+ return devMemory;
},
/** Moves the native window with the pointer (`start-dragging`). */
@@ -220,26 +151,13 @@ export const onPetHover = (handler: (hover: boolean) => void): (() => void) => {
/** Subscribe to shell events; returns the unsubscribe function. */
export const onPetEvents = (handlers: {
summon?: (intent: PetIntent) => void;
- bound?: (binding: PetBinding) => void;
}): (() => void) => {
const summon = (event: Event) => {
const intent = (event as CustomEvent<{ intent?: unknown }>).detail?.intent;
handlers.summon?.(isIntent(intent) ? intent : 'show');
};
- const bound = (event: Event) => {
- const detail = (event as CustomEvent<{ session_id?: unknown; revision?: unknown }>).detail;
- let binding: PetBinding;
- try {
- binding = parseBinding({ binding: detail?.session_id, revision: detail?.revision });
- } catch {
- return; // Without a revision the event cannot be ordered, so it is not applied.
- }
- handlers.bound?.(binding);
- };
window.addEventListener(PET_SUMMON_EVENT, summon);
- window.addEventListener(PET_BOUND_EVENT, bound);
return () => {
window.removeEventListener(PET_SUMMON_EVENT, summon);
- window.removeEventListener(PET_BOUND_EVENT, bound);
};
};
diff --git a/ui/src/pet/petComposer.ts b/ui/src/pet/petComposer.ts
index 07b2dff2b..3e5cc5205 100644
--- a/ui/src/pet/petComposer.ts
+++ b/ui/src/pet/petComposer.ts
@@ -1,5 +1,7 @@
import { useEffect, useSyncExternalStore } from 'react';
+import { referenceToMarker, type SessionReference } from '@/lib/mentions';
+
/**
* Draft, in-flight send, per-session uncertainty, and a pending listen-focus
* for the pet window. Held once per document outside React so an AuthGuard
@@ -8,6 +10,8 @@ import { useEffect, useSyncExternalStore } from 'react';
* the composer to mount.
*/
let draft = '';
+let references: SessionReference[] = [];
+const NO_REFERENCES: SessionReference[] = [];
let draftSession: string | null | undefined;
const uncertainSessions = new Set<string>();
let sending = false;
@@ -42,22 +46,27 @@ export const petComposer = {
sending = value;
notify();
},
- setDraft(value: string, sessionId: string | null) {
+ setDraft(value: string, sessionId: string | null, selected?: SessionReference[]) {
const sessionChanged = draftSession !== sessionId;
- if (!sessionChanged && draft === value) return;
+ const candidates = selected ?? (sessionChanged ? NO_REFERENCES : references);
+ const next = candidates.filter((reference) => value.includes(referenceToMarker(reference)));
+ if (!sessionChanged && draft === value && next.length === references.length && next.every((reference, index) => reference === references[index])) return;
draftSession = sessionId;
draft = value;
+ references = next;
notify();
},
bind(sessionId: string | null) {
if (draftSession === sessionId) return;
draftSession = sessionId;
draft = '';
+ references = [];
notify();
},
clearDraftIf(value: string) {
if (draft !== value) return false;
draft = '';
+ references = [];
notify();
return true;
},
@@ -76,24 +85,26 @@ export const petComposer = {
export function usePetComposer(binding: string | null): {
draft: string;
+ references: SessionReference[];
uncertain: boolean;
sending: boolean;
listenPending: boolean;
- setDraft: (value: string) => void;
+ setDraft: (value: string, selected?: SessionReference[]) => void;
setUncertain: (sessionId: string, value: boolean) => void;
} {
useSyncExternalStore(subscribe, () => version);
useEffect(() => {
- petComposer.bind(binding);
+ if (binding) petComposer.bind(binding);
}, [binding]);
return {
// A draft belongs to the session it was typed for. Until bind lands,
// hide text that still belongs to the previous binding.
draft: draftSession === binding ? draft : '',
+ references: draftSession === binding ? references : NO_REFERENCES,
uncertain: petComposer.isUncertain(binding),
sending,
listenPending: pendingListen,
- setDraft: (value: string) => petComposer.setDraft(value, binding),
+ setDraft: (value: string, selected?: SessionReference[]) => petComposer.setDraft(value, binding, selected),
setUncertain: petComposer.setUncertain,
};
}
diff --git a/ui/src/pet/petShell.ts b/ui/src/pet/petShell.ts
index d534a4581..8eb62d3c1 100644
--- a/ui/src/pet/petShell.ts
+++ b/ui/src/pet/petShell.ts
@@ -1,81 +1,40 @@
import { useEffect, useSyncExternalStore } from 'react';
import { onPetEvents, petBridge, type PetBinding, type PetIntent } from './petBridge';
+import type { PetSurfaceEpoch } from './usePetSession';
-/**
- * The pet window's shell state, held once per document outside React so the
- * setup-pending view and the pet surface share it across their remounts:
- *
- * - `binding`: the bound session (undefined until the shell has told us);
- * - the latest summon not yet acted on. A summon that arrives while setup is
- * pending, or before the surface has mounted, waits here, so the user's
- * hotkey is never lost to the page's own loading order.
- *
- * The shell owns the binding and orders every change to it by revision. The
- * page applies whatever the shell reports (`pet_ready()`, `pet:bound`, and the
- * answers to its own picks and clears) only when it is newer than what it
- * already applied, so no answer or event can be overtaken by an older one.
- * The page's own changes are sent one at a time, in the order the user made
- * them, and shown at once; when none is outstanding, the page shows exactly
- * what the shell last reported.
- *
- * Listeners are installed before `pet_ready()` is called, so nothing the shell
- * sends after it can be missed; anything it sent earlier is returned by it.
- */
-let binding: string | null | undefined;
-let reported: PetBinding | null = null;
-// The page's own changes not yet answered by the shell, and the latest one.
-let outstanding = 0;
-let latestChange: string | null = null;
-let changes: Promise<void> = Promise.resolve();
+/** Document-local main resolution and pending summons. Legacy shell bindings
+ * remain readable for compatibility, but never select the conversation. */
+let binding: string | null = null;
+let legacyBinding: PetBinding | null = null;
let pendingSummon: PetIntent | null = null;
+let dismissedSession: string | null = null;
let dismissedIds: string[] = [];
+let readyLoaded = false;
+let changes: Promise<void> = Promise.resolve();
+let readyPromise: Promise<void> = Promise.resolve();
+const normalizationAttempts = new WeakSet<PetSurfaceEpoch>();
let started = false;
-// Bumped by every live summon, so a summon `pet_ready()` returns is used only
-// if no live one has arrived since it was asked.
let liveSummons = 0;
const storeListeners = new Set<() => void>();
const summonListeners = new Set<() => void>();
-const show = () => {
- const next = outstanding > 0 ? latestChange : reported?.binding;
- if (next === binding) return;
+const setMain = (next: string | null) => {
+ if (binding === next) return;
binding = next;
- dismissedIds = [];
- (window as unknown as { __AVIBE_PET_BINDING__?: string | null }).__AVIBE_PET_BINDING__ = next;
+ // A failed lookup withdraws the conversation, not the user's preferences.
+ if (next && next !== dismissedSession) {
+ if (dismissedSession) dismissedIds = [];
+ dismissedSession = next;
+ }
storeListeners.forEach((listener) => listener());
};
-const report = (next: PetBinding) => {
- if (reported && next.revision <= reported.revision) return;
- reported = next;
- show();
-};
-
const noteSummon = (intent: PetIntent) => {
pendingSummon = intent;
summonListeners.forEach((listener) => listener());
};
-/** A change made by this page: shown now, sent after the ones before it. */
-const change = (next: string | null, send: () => Promise<PetBinding>, failed: () => void, maySend?: () => boolean) => {
- outstanding += 1;
- latestChange = next;
- show();
- changes = changes
- .then(() => maySend?.() === false ? null : send())
- .then((confirmed) => {
- // An IPC already sent changes the shell's authoritative binding. Keep
- // mirroring its revision even if authorization changed meanwhile; the
- // surface must validate that binding afresh before displaying any data.
- if (confirmed) report(confirmed);
- }, failed)
- .finally(() => {
- outstanding -= 1;
- show();
- });
-};
-
const start = () => {
if (started) return;
started = true;
@@ -84,40 +43,36 @@ const start = () => {
liveSummons += 1;
noteSummon(intent);
},
- bound: report,
});
const liveSummonsAtRequest = liveSummons;
- void petBridge.ready().then((ready) => {
- const applies = !reported || ready.revision >= reported.revision;
- report(ready);
- if (applies && binding === ready.binding) {
- dismissedIds = ready.dismissed_ids ?? [];
- storeListeners.forEach((listener) => listener());
- }
+ readyPromise = petBridge.ready().then((ready) => {
+ legacyBinding = ready;
+ readyLoaded = true;
if (ready.summon_pending && liveSummons === liveSummonsAtRequest) noteSummon(ready.summon_pending.intent);
- }).catch(() => {
- // Without an answer the pet starts unbound; the shell's next report wins.
- if (!reported) report({ binding: null, revision: 0 });
- });
+ }).catch(() => undefined);
+};
+
+const setDismissed = (ids: string[]) => {
+ dismissedIds = ids;
+ storeListeners.forEach((listener) => listener());
};
export const petShell = {
- /** Bind `sessionId`. If the shell cannot, the pet shows what it holds. */
- pick: (sessionId: string, isAuthorizationCurrent?: () => boolean) => change(sessionId, () => petBridge.bind(sessionId), () => undefined, isAuthorizationCurrent),
+ setMain,
- /**
- * Clear an invalid binding (compare-and-clear). Unlike a failed pick, a
- * failed clear is not undone: the session is archived, missing or read-only,
- * so showing it again would only re-run validation and clear it again, in a
- * loop. The page treats it as cleared until the shell reports a newer
- * binding; if the shell keeps it durably, the next load validates it the
- * same way before the pet uses it, so it is never sent to.
- */
- unbind: (sessionId: string) => {
- if (binding !== sessionId) return;
- change(null, () => petBridge.unbind(sessionId), () => {
- if (reported?.binding === sessionId) reported = { binding: null, revision: reported.revision };
- });
+ /** One main-only binding normalization attempt per authorized epoch. */
+ normalizeMain: (epoch: PetSurfaceEpoch) => {
+ if (epoch.binding !== 'ses_main' || normalizationAttempts.has(epoch)) return;
+ normalizationAttempts.add(epoch);
+ start();
+ changes = changes.then(async () => {
+ await readyPromise;
+ if (!readyLoaded || !epoch.isCurrent() || legacyBinding?.binding === 'ses_main') return;
+ const confirmed = await petBridge.bindMain();
+ // An IPC already sent may finish after authorization changes. It only
+ // writes main; mirror the native storage owner without selecting a session.
+ legacyBinding = confirmed;
+ }).catch(() => undefined); // A later epoch may retry; never loop in this one.
},
/** Take the waiting summon, if any. */
@@ -128,18 +83,19 @@ export const petShell = {
},
/** The binding now, for callbacks that must not read a stale render. */
- currentBinding: (): string | null | undefined => binding,
+ currentBinding: (): string | null => binding,
dismissed: (): string[] => dismissedIds,
- setDismissed: (sessionId: string, ids: string[]) => {
- if (sessionId !== binding) return;
- dismissedIds = ids;
- storeListeners.forEach((listener) => listener());
- // Persist writes in order, so an older dismiss cannot resurrect a later one.
- changes = changes.then(() => petBridge.setDismissedIds(sessionId, ids)).catch(() => undefined);
+ // Document-local preferences stay with the last resolved main through an
+ // outage. They never wait for pet_ready and never reach native storage.
+ addDismissed: (id: string) => {
+ if (!dismissedIds.includes(id)) setDismissed([...dismissedIds, id]);
+ },
+ forgetDismissed: (id: string) => {
+ if (dismissedIds.includes(id)) setDismissed(dismissedIds.filter((entry) => entry !== id));
},
};
-export function usePetBinding(): string | null | undefined {
+export function usePetBinding(): string | null {
useEffect(start, []);
return useSyncExternalStore(
(listener) => {
diff --git a/ui/src/pet/useConversationAgentWorking.ts b/ui/src/pet/useConversationAgentWorking.ts
index 38f581f2b..839f9999e 100644
--- a/ui/src/pet/useConversationAgentWorking.ts
+++ b/ui/src/pet/useConversationAgentWorking.ts
@@ -51,15 +51,15 @@ class ConversationWorkingSource {
private readonly awaiting = new Map<string, number>();
private retry: number | undefined;
- constructor(read: () => Promise<RunningAgentsResult>, onWorking: (working: boolean) => void) {
+ constructor(read: () => Promise<RunningAgentsResult>, onResult: (result: RunningAgentsResult) => void) {
this.fenced = new FencedSource({
read,
apply: (_key, result) => {
- onWorking(conversationAgentWorking(result));
+ onResult(result);
this.settle(activeSessions(result));
},
fail: () => {
- onWorking(false);
+ onResult({ ok: false, unreachable: true, agents: [], counts: {} });
// A failed read registers nothing: keep waiting on every started turn
// until its cap, as `turn.start` is not replayed.
this.settle(new Set());
@@ -101,18 +101,24 @@ class ConversationWorkingSource {
}
}
+const UNREACHABLE: RunningAgentsResult = { ok: false, unreachable: true, agents: [], counts: {} };
+
/**
- * Whether an agent is working in any conversation the user can see, from the
- * running-agents snapshot the Agents page reads. `enabled` is the caller's
- * permission to read it; without it the answer is always false.
+ * The running-agents snapshot used by both the pose and the desktop mini
+ * activity cards. The source is fenced so an old response cannot replace a
+ * newer authorization/session snapshot.
*/
-export function useConversationAgentWorking(enabled: boolean): boolean {
+export function useConversationAgentSnapshot(enabled: boolean): RunningAgentsResult {
const api = useApi();
- const [working, setWorking] = useState(false);
- const source = useMemo(() => new ConversationWorkingSource(() => api.getRunningAgents(), setWorking), [api]);
+ const [result, setResult] = useState<RunningAgentsResult>(UNREACHABLE);
+ const [displayedEnabled, setDisplayedEnabled] = useState(enabled);
+ if (displayedEnabled !== enabled) {
+ setDisplayedEnabled(enabled);
+ setResult(UNREACHABLE);
+ }
+ const source = useMemo(() => new ConversationWorkingSource(() => api.getRunningAgents(), setResult), [api]);
useEffect(() => {
- // Disabled, the return value below ignores whatever was last read.
source.setEnabled(enabled);
if (!enabled) return undefined;
const refresh = () => source.refresh();
@@ -122,6 +128,12 @@ export function useConversationAgentWorking(enabled: boolean): boolean {
onTurnEnd: ({ session_id }) => source.turnEnded(session_id),
};
for (const trigger of REFRESH_TRIGGERS) handlers[trigger] = refresh;
+ handlers.onAuthorizationChanged = () => {
+ setResult(UNREACHABLE);
+ source.setEnabled(false);
+ source.setEnabled(true);
+ refresh();
+ };
const disconnect = api.connectWorkbenchEvents(handlers);
const stopReactivation = onPageReactivated(refresh);
const interval = window.setInterval(() => {
@@ -135,5 +147,15 @@ export function useConversationAgentWorking(enabled: boolean): boolean {
};
}, [api, enabled, source]);
- return enabled && working;
+ return enabled ? result : UNREACHABLE;
+}
+
+/**
+ * Whether an agent is working in any conversation the user can see, from the
+ * running-agents snapshot the Agents page reads. `enabled` is the caller's
+ * permission to read it; without it the answer is always false.
+ */
+export function useConversationAgentWorking(enabled: boolean): boolean {
+ const snapshot = useConversationAgentSnapshot(enabled);
+ return enabled && conversationAgentWorking(snapshot);
}
diff --git a/ui/src/pet/usePetReplyActivities.ts b/ui/src/pet/usePetReplyActivities.ts
new file mode 100644
index 000000000..46c6f796c
--- /dev/null
+++ b/ui/src/pet/usePetReplyActivities.ts
@@ -0,0 +1,59 @@
+import { useEffect, useState } from 'react';
+
+import { useApi, type InboxSession, type RunningAgent } from '@/context/ApiContext';
+import type { PetSurfaceEpoch } from './usePetSession';
+
+/**
+ * A replied session can have no live process. The existing Inbox supplies
+ * unread evidence, and a fresh session read supplies visibility and identity;
+ * never keep a disappeared process and invent a successful completion.
+ */
+export function usePetReplyActivities(
+ enabled: boolean,
+ epoch: PetSurfaceEpoch,
+ inbox: InboxSession[],
+): { rows: RunningAgent[]; pending: boolean } {
+ const api = useApi();
+ const [value, setValue] = useState<{ epoch: PetSurfaceEpoch; inbox: InboxSession[]; rows: RunningAgent[]; pending: boolean } | null>(null);
+ useEffect(() => {
+ if (!enabled) return;
+ let current = true;
+ let generation = 0;
+ const refresh = () => {
+ const read = ++generation;
+ setValue((previous) => ({
+ epoch, inbox, pending: true,
+ rows: previous?.epoch === epoch ? previous.rows : [],
+ }));
+ void Promise.all(inbox.filter((item) => item.unread && item.session_id !== epoch.binding).map(async (item): Promise<RunningAgent | null> => {
+ const { session, status } = await api.getSessionResult(item.session_id);
+ if (status >= 500) throw new Error('Reply visibility read unavailable');
+ if (status !== 200 || !session || session.visibility !== 'foreground' || session.status !== 'active') return null;
+ return {
+ backend: session.agent_backend ?? '', state: 'idle',
+ session_id: session.id, title: session.title, agent_name: session.agent_name,
+ scope_display_name: item.project_name, platform: 'avibe', scope_type: 'project',
+ visibility: session.visibility, openable_in_chat: true, trigger_source: null,
+ base_session_id: null, composite_key: null, pid: null, pid_shared: false,
+ workdir: null, native_session_id: null, model: null, elapsed_seconds: null,
+ };
+ })).then((rows) => {
+ if (current && read === generation && epoch.isCurrent()) setValue({ epoch, inbox, pending: false, rows: rows.filter((row): row is RunningAgent => row !== null) });
+ }).catch(() => {
+ // A failed read is not evidence of absence. Keep validated rows and
+ // pending until the next event retries, without a new polling loop.
+ });
+ };
+ refresh();
+ // A hidden/archived session must leave even when its unread count did not change.
+ const disconnect = api.connectWorkbenchEvents({
+ onSessionActivity: refresh,
+ onConnected: refresh,
+ });
+ return () => { current = false; disconnect(); };
+ }, [api, enabled, epoch, inbox]);
+ return {
+ rows: enabled && value?.epoch === epoch ? value.rows : [],
+ pending: enabled && (value?.epoch !== epoch || value.inbox !== inbox || value.pending),
+ };
+}
diff --git a/ui/src/pet/usePetSession.ts b/ui/src/pet/usePetSession.ts
index 7c3f4e183..2feb42e88 100644
--- a/ui/src/pet/usePetSession.ts
+++ b/ui/src/pet/usePetSession.ts
@@ -19,8 +19,6 @@ export type PetSurfaceEpoch = {
binding: string | null;
authorizationGeneration: number;
isCurrent: () => boolean;
- /** A pick intentionally changes binding; its queued IPC still needs this gate. */
- isAuthorizationCurrent: () => boolean;
};
export const PET_TAIL_LIMIT = 30;
@@ -78,10 +76,9 @@ const mergeRow = (tail: Tail, row: WorkbenchMessage): Tail => {
* contract in docs/plans/2026-10-01-desktop-pet.md: an initial read, live
* triggers, and gap fallbacks, with every read fenced by binding and order.
*
- * `onInvalid(S)` fires when `S` turns out to be read-only or missing, so the
- * caller can clear the binding (compare-and-clear) and show the switcher.
+ * Main is resolved through the owner-only endpoint; native bindings are ignored.
*/
-export function usePetSession(sessionId: string | null, onInvalid: (sessionId: string) => void): PetSessionData {
+export function usePetSession(sessionId: string | null): PetSessionData {
const api = useApi();
const [authorizationGeneration, setAuthorizationGeneration] = useState(0);
const authorizationNow = useRef(0);
@@ -96,7 +93,6 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
const isAuthorizationCurrent = () => mounted.current && authorizationNow.current === identity.authorizationGeneration;
return {
...identity,
- isAuthorizationCurrent,
isCurrent: () => isAuthorizationCurrent() && currentIdentity.current === identity
&& (petShell.currentBinding() ?? null) === identity.binding,
};
@@ -106,8 +102,6 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
const [canChat, setCanChat] = useState<boolean | null>(null);
const [tail, setTail] = useState<Tail>(EMPTY_TAIL);
const [turn, setTurn] = useState<SessionRuntimeState | null>(null);
- // The session a fresh read found missing or read-only.
- const [invalid, setInvalid] = useState<string | null>(null);
// A local send stays Running for the registration grace.
const [inGrace, setInGrace] = useState(false);
const [sendCount, setSendCount] = useState(0);
@@ -116,31 +110,25 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
const [displayed, setDisplayed] = useState(sessionId);
if (displayed !== sessionId) {
setDisplayed(sessionId);
- setSession(null);
- setCanChat(null);
setTail(EMPTY_TAIL);
setTurn(null);
setInGrace(false);
- setInvalid(null);
}
const sources = useMemo(() => ({
- session: new FencedSource<string, WorkbenchSessionReadResult>({
- read: (key) => api.getSessionResult(key),
- apply: (key, { status, session: row, capabilities }) => {
- // A binding is valid only while S is writable: missing, archived and
- // Runtime-owned sessions all clear it.
- // 403: this principal lost access to the session (or its project).
- if (status === 404 || status === 403 || (row && isSessionReadOnly(row))) {
- setInvalid(key);
- setCanChat(false);
- return;
- }
- // Unknown or missing: deny. The composer waits on an explicit true.
- setCanChat(capabilities?.can_chat === true);
- if (row) setSession(row);
+ session: new FencedSource<number, WorkbenchSessionReadResult>({
+ read: () => api.getMainSession(),
+ apply: (_key, { status, session: row, capabilities }) => {
+ const valid = status === 200 && row && !isSessionReadOnly(row) && capabilities?.can_chat === true;
+ setSession(valid ? row : null);
+ setCanChat(Boolean(valid));
+ petShell.setMain(valid ? row.id : null);
+ },
+ fail: () => {
+ setSession(null);
+ setCanChat(false);
+ petShell.setMain(null);
},
- fail: () => setCanChat(false),
}),
tail: new FencedSource<string, { messages: WorkbenchMessage[]; next_before_id?: string | null }>({
read: (key) => api.listSessionMessages(key, { tail: true, cache: false, limit: PET_TAIL_LIMIT }),
@@ -168,27 +156,27 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
sources.turn.refresh();
}, [sources]);
- // Initial read on every binding change.
+ // One fenced main lookup per mount, then event-driven recovery. No polling.
useEffect(() => {
- sources.session.setKey(sessionId);
- sources.tail.setKey(sessionId);
- sources.turn.setKey(sessionId);
- if (sessionId) refreshAll();
- return () => {
- sources.session.setKey(null);
- sources.tail.setKey(null);
- sources.turn.setKey(null);
- };
- }, [sessionId, sources, refreshAll]);
+ sources.session.setKey(authorizationNow.current);
+ sources.session.refresh();
+ return () => sources.session.setKey(null);
+ }, [sources]);
- // Report an invalid binding once, and only while it is still the binding.
+ // No transcript or runtime reads before the main endpoint grants access.
+ const resolved = session?.id === sessionId && canChat === true;
useEffect(() => {
- if (epoch.isCurrent() && invalid && invalid === sessionId) onInvalid(invalid);
- }, [invalid, sessionId, onInvalid, epoch]);
+ const key = resolved ? sessionId : null;
+ sources.tail.setKey(key);
+ sources.turn.setKey(key);
+ if (key) { sources.tail.refresh(); sources.turn.refresh(); }
+ return () => { sources.tail.setKey(null); sources.turn.setKey(null); };
+ }, [sessionId, resolved, authorizationGeneration, sources]);
// Live triggers and the reconnect gap fallback.
useEffect(() => {
- const mine = (id: string | null | undefined) => Boolean(sessionId && id === sessionId);
+ const generation = authorizationNow.current;
+ const mine = (id: string | null | undefined) => Boolean(generation === authorizationNow.current && resolved && sessionId && id === sessionId);
return api.connectWorkbenchEvents({
onConnected: refreshAll,
onMessageNew: (row) => {
@@ -234,8 +222,8 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
sources.turn.refresh();
},
// Access changed: drop everything read under the old authorization at
- // once, then re-read (a refresh also drops any read in flight); a lost
- // session reads 403 and clears the binding.
+ // once, then resolve main again. Its owner-only grant must land before any
+ // transcript/runtime reads under the new authorization.
onAuthorizationChanged: () => {
// Invalidate callbacks synchronously, before React commits the reset.
authorizationNow.current += 1;
@@ -245,8 +233,10 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
setTail(EMPTY_TAIL);
setTurn(null);
setInGrace(false);
- setInvalid(null);
- refreshAll();
+ sources.tail.setKey(null);
+ sources.turn.setKey(null);
+ sources.session.setKey(authorizationNow.current);
+ sources.session.refresh();
},
onQueueUpdated: ({ session_id }) => {
if (mine(session_id)) sources.turn.refresh();
@@ -256,11 +246,10 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
onRunsUpdated: () => sources.turn.refresh(),
onDefinitionsUpdated: () => sources.turn.refresh(),
});
- }, [api, sessionId, sources, refreshAll, sessionRef, tailLoadedRef]);
+ }, [api, sessionId, resolved, authorizationGeneration, sources, refreshAll, sessionRef, tailLoadedRef]);
// The window coming back is a gap too.
useEffect(() => {
- if (!sessionId) return undefined;
return onPageReactivated(refreshAll);
}, [sessionId, refreshAll]);
diff --git a/ui/src/pet/useSessionSwitcher.ts b/ui/src/pet/useSessionSwitcher.ts
deleted file mode 100644
index 44917f324..000000000
--- a/ui/src/pet/useSessionSwitcher.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useEffect, useMemo, useState } from 'react';
-
-import { useApi, type WorkbenchSession } from '@/context/ApiContext';
-import { isSessionReadOnly } from '@/components/workbench/sessionArchived';
-
-import { FencedSource } from './fencedSource';
-
-const SWITCHER_KEY = 'switcher';
-export const SWITCHER_LIMIT = 20;
-
-/**
- * Recent writable sessions for the pet's switcher: the global active list,
- * newest first, so a new session with no reply yet is listed. Read when the
- * switcher opens and re-read on session activity, reconnects and
- * authorization changes while open, fenced so an older response never
- * overwrites a newer refresh.
- */
-export function useSessionSwitcher(open: boolean): { sessions: WorkbenchSession[]; loading: boolean } {
- const api = useApi();
- const [sessions, setSessions] = useState<WorkbenchSession[]>([]);
- const [loading, setLoading] = useState(open);
- // Opening starts a load; adjusted during render, React's pattern for state
- // that follows a prop.
- const [wasOpen, setWasOpen] = useState(open);
- if (wasOpen !== open) {
- setWasOpen(open);
- if (open) setLoading(true);
- }
-
- const source = useMemo(() => new FencedSource<string, WorkbenchSession[]>({
- read: async () => {
- const page = await api.listSessions({ status: 'active', limit: SWITCHER_LIMIT, cache: false });
- return page.sessions.filter((session) => !isSessionReadOnly(session));
- },
- apply: (_key, value) => {
- setSessions(value);
- setLoading(false);
- },
- fail: () => setLoading(false),
- }), [api]);
-
- useEffect(() => {
- source.setKey(open ? SWITCHER_KEY : null);
- if (!open) return undefined;
- source.refresh();
- return api.connectWorkbenchEvents({
- onConnected: () => source.refresh(),
- onSessionActivity: () => source.refresh(),
- // Access changed: rows from a project the user lost must not stay
- // listed or pickable, so they go at once and the list is re-read.
- onAuthorizationChanged: () => {
- setSessions([]);
- setLoading(true);
- source.refresh();
- },
- });
- }, [api, open, source]);
-
- return { sessions, loading };
-}