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(desktop): add the desktop pet's /pet route (#2358)

Maxf473936e5a63
diff --git a/docs/plans/2026-10-01-desktop-pet.md b/docs/plans/2026-10-01-desktop-pet.md
index 0380cf1ab..2e2075a63 100644
--- a/docs/plans/2026-10-01-desktop-pet.md
+++ b/docs/plans/2026-10-01-desktop-pet.md
@@ -1,6 +1,7 @@
# Desktop Pet
-Status: proposed (2026-10-01)
+Status: in progress (2026-10-04). Delivery is split into three PRs; see
+"Implementation notes".
## Background
@@ -129,7 +130,7 @@ extra window:
The IPC surface is kept minimal. It is granted to window `pet` for the remote
loopback origin only, through a new capability file:
-- command `pet_ready() -> {binding, summon_pending: null | {intent}}`, which
+- command `pet_ready() -> {binding, revision, summon_pending: null | {intent}}`, which
the route calls once `/pet` has mounted and its listeners are installed. It
returns the current binding and consumes any summon that arrived before the
page was ready, so a summon that recreated the window is never lost;
@@ -143,12 +144,18 @@ loopback origin only, through a new capability file:
chose, `{panel_side: left | right, panel_edge: top | bottom, pet_offset}`,
and the route renders the pet and panel from that value. The native frame
and the DOM therefore share one placement decision;
-- command `pet_bind(session_id) -> {shown}` and event `pet:bound`, which set
- and carry the session binding (see Session binding). The pet uses
- `pet_bind` for its switcher; a call from `main` also wakes the pet;
-- command `pet_unbind(session_id)`, a compare-and-clear: it clears the binding
- only if it is still `session_id`, so a late result about an old session can
- never clear a newer one;
+- command `pet_bind(session_id) -> {binding, revision, shown}` and event
+ `pet:bound {session_id, revision}`, which set and carry the session binding
+ (see Session binding). The pet uses `pet_bind` for its switcher; a call from
+ `main` also wakes the pet;
+- command `pet_unbind(session_id) -> {binding, revision}`, a compare-and-clear:
+ it clears the binding only if it is still `session_id`, so a late result
+ about an old session can never clear a newer one;
+- every binding the shell reports carries `revision`, a counter it raises by
+ one on each change. The page applies a report only if its revision is newer
+ than the last one it applied, so a `pet:bound` and a command answer that
+ cross can never leave the older binding shown; a report without a revision
+ is rejected;
- command `pet_open(link)`, which takes any link the existing deep-link
parser (`desktop-deep-links.md`) accepts: session, Show Page, settings, and
vault request. It focuses `main` through the same path a clicked deep link
@@ -213,7 +220,13 @@ as it does for the Workbench.
`/pet` is a new route in the same SPA.
- It sits inside `AuthGuard` and the existing providers (Api, Inbox), but
- outside `AppShell`, so it has no sidebar or chrome.
+ outside `AppShell`, so it has no sidebar or chrome. The transparent
+ `pet-window` style is installed by a route shell around the guard, so a
+ loading or authorization recheck never paints an opaque body into the
+ native window. AuthGuard itself returns nothing, not its usual loading
+ surface, while `/pet` is waiting on a session. Draft, in-flight send, and
+ per-session send-uncertainty live in a document store so the same recheck
+ cannot drop a lock or the text that belongs to it.
- `/pet` is exempt from `AuthGuard`'s setup redirect. Before setup is
complete, it renders its own setup-pending state ("Finish setting up in
Avibe", which calls `pet_open("avibe://settings")`; `main`'s own guard then
@@ -309,7 +322,9 @@ when the user changes the UI port, so it cannot own anything durable.
re-read on `session.activity` and `onConnected` while it is open, so a new
session with no reply yet is listed.
- The shell writes `pet.json` and emits `pet:bound` to the pet. On load, the
- pet reads the binding from `pet_ready()`.
+ pet reads the binding from `pet_ready()`. Every report is ordered by its
+ revision, and the pet's own picks and clears are sent one at a time in the
+ order the user made them.
- **A binding is valid only while `S` is a writable session**, by the chat
page's own predicate: `getSession(S)` succeeds and
`isSessionReadOnly(session)` is false. That rejects archived sessions and
@@ -368,9 +383,10 @@ comes from an API the Workbench already uses:
Workbench together.
- A result that lands after rendering, for example from a queued turn,
stays unread and keeps the badge.
- - If the unread rows reach past the loaded tail, the panel does not mark
- read at all. It shows "More in Avibe" (`pet_open` with the session link)
- and leaves reading to the Workbench.
+ - If the unread rows reach past the loaded tail — including when the
+ inbox count is ahead of the unread results in that tail — the panel
+ does not mark read at all. It shows "More in Avibe" (`pet_open` with
+ the session link) and leaves reading to the Workbench.
**Only the latest agent result's quick replies mean Needs input.** This is a
deliberate difference from the Workbench, which keeps every unanswered group
@@ -418,7 +434,9 @@ Workbench. The pet shows "Queued" and offers no steering control in v1.
- **Hotkey tap with the pet collapsed or hidden** (`listen` intent). Show the
pet, expand it, focus it, and start listening. If voice is unavailable, focus the text input
- instead.
+ instead. Focus waits until the native frame has grown and the composer is
+ on screen (a cold load still waits on the session grant). The listen
+ request lives in the document store so an AuthGuard recheck cannot drop it.
- **No valid binding** (none chosen yet, or cleared after an archive). The
hotkey opens the panel on the session switcher and does not start listening
or accept input, so nothing is ever captured without a destination.
@@ -538,9 +556,15 @@ The microphone usage string and audio-input entitlement already ship (#2293).
lost recreates it through `pet_reconcile()`;
- the saved anchor is the pet image position whichever side the panel
opened on, and a restore onto a missing monitor is clamped on screen;
- - `pet_set_expanded` returns the layout it applied, near each screen edge;
+ - `pet_set_expanded` returns the layout it applied, near each screen edge,
+ and calls are applied in the order they were made, so a late collapse
+ cannot overtake a later expand. The page sends `pet_set_expanded` one
+ at a time in that same order, and still keeps only the answer to its
+ latest request;
- `pet_bind` persists to `pet.json` and emits `pet:bound`, and the binding
- survives a Runtime origin change;
+ survives a Runtime origin change; every change raises the revision by
+ one, and `pet_ready`, `pet_bind`, `pet_unbind` and `pet:bound` all carry
+ it;
- `main` gains only `pet_bind`, and `pet` is granted exactly `pet_ready`,
`pet_set_expanded`, `pet_bind`, `pet_unbind`, `pet_open`, the two events,
and `start-dragging`; `pet_unbind(A)` is a no-op when the binding is `B`;
@@ -632,6 +656,111 @@ The microphone usage string and audio-input entitlement already ship (#2293).
- **Focus.** Summoning focuses the pet so that typing works. Confirm that the
previously active app gets focus back when the panel collapses.
+## Implementation notes
+
+Decisions made while building, where the code is simpler than the text above.
+The code and its tests are the contract; this section records why.
+
+- **Three PRs instead of one for delivery 1.** (a) the Runtime
+ `message.updated` for quick-reply choices (#2357); (b) the `/pet` route,
+ state, panel, poses and i18n; (c) the shell: window, IPC, shortcut, tray,
+ `pet.json`, and "Show in pet". The pet stays invisible until (c) lands, so
+ (a) and (b) ship nothing a user can see.
+- **`/pet` sits inside `AuthGuard` with a setup-redirect exemption only.** It
+ keeps the login and authorization gates, and `SETUP_REDIRECT_EXEMPT_PATHS`
+ exempts it from the wizard redirect only. It is not a diagnostics-style
+ bypass (`SETUP_CHECK_BYPASS_PATHS`), so it never renders without a session:
+ if the first session probe fails, the guard keeps loading and checks again
+ each time the page comes back, and the pet always runs with its
+ authorization. Its own setup gate (`usePetSetup`)
+ applies the same rule through the shared `isSetupComplete` and shows
+ "finish setting up in Avibe" instead of a pet-sized wizard. The route stays
+ outside the Workbench chrome. The setup re-read bypasses the config cache
+ (`getConfig({ cache: false })`). Composing is shown only when both the
+ instance `can_chat` and the bound session's project `capabilities.can_chat`
+ are true. The session GET carries that flag with the same role rule as
+ bootstrap (`get_effective_session_role` + editor); unknown or failed reads
+ deny. The pet does not load bootstrap.
+- **Shell → page events are DOM events.** The shell dispatches
+ `avibe:pet-summon` and `avibe:pet-bound` on `window` through a
+ shell-evaluated script, the channel the Settings… menu already uses, so the
+ pet needs no Tauri event permission. Page → shell stays Tauri commands. The
+ contract lives in `ui/src/pet/petBridge.ts`.
+- **One summon store per document.** `petShell.ts` installs the listeners
+ from the first frame, before setup is known, and keeps the latest summon
+ until the pet surface takes it. A summon during setup-pending re-reads
+ setup and is then acted on, so a hotkey is never lost to loading order.
+- **`PetLayout` has no `pet_offset`.** The route places the pet and panel from
+ `panel_side` and `panel_edge` alone; the shell owns the offset.
+- **No `useSessionTurnState` extraction.** The chat page's turn logic is
+ interleaved with its Agent Activity buffer, so extracting it would be a
+ risky refactor of the chat page for a consumer that needs less. The pet
+ keeps the same rules in `usePetSession`: the authoritative
+ `GET /turn-state`, the same reconcile cadences, and the 4 s post-send grace.
+- **Generation fencing** is one class, `FencedSource`, used by every source
+ including the switcher list. A key change frees the in-flight slot at once,
+ so switching sessions never waits on the old session's read.
+- **The shell's revision orders bindings.** The page never infers order from
+ arrival: `pet_ready()`, `pet:bound`, and the answers to its own picks and
+ clears are applied only when newer than the last report it applied. Its own
+ changes are shown at once and queued, so a second pick is not sent before
+ the first is answered; when none is outstanding, it shows exactly what the
+ shell last reported. A failed pick shows the shell's binding again. A
+ failed clear is not undone, since re-showing an invalid session would only
+ fail validation and clear it again.
+- **An unknown send result is not a failure.** As in the chat composer
+ (`useNewSession`), a send counts as refused only for `400`, `403`, `404`,
+ `409` or `422`. Any other failure (a network error, a `5xx`, a
+ `dispatch_pending` `502`/`504`) may have been admitted, so the pet keeps the
+ draft, hides quick replies, closes input for that session and offers "Open
+ in Avibe"; opening the session there is how the user finds out, and lifts it.
+ Each session keeps its own lock, so inspecting B does not reopen A.
+ The lock lifts only after `pet_open` succeeds; a failed open leaves it.
+ Draft, in-flight send, those locks, and a pending listen-focus live
+ outside React so an AuthGuard recheck cannot drop them. A listen summon
+ focuses the input only after the panel has grown and the composer is on
+ screen.
+- **The panel opens after the shell grows the frame.** Closing hides it at
+ once; opening waits for `pet_set_expanded` to succeed, so replies are never
+ marked read while still clipped. Native resizes are sent one at a time in
+ the order they were asked, matching the shell's call-order contract, and
+ only the latest request updates React. A failed request restores the last
+ confirmed expansion, so a redundant expand of an already-open panel cannot
+ hide it. Expansion lives in `petPanel` so the setup-pending card grows the
+ native frame too; until it confirms, only the avatar is shown. The
+ setup-pending summon listener is stable, so a still-pending summon is not
+ replayed into an expand/recheck loop.
+- **Read-marking waits for a tail snapshot.** Live rows that arrive before the
+ first tail read lands say nothing about older unread rows, so the pet treats
+ the tail as having older rows until a read has landed. A live row or unread
+ change that arrives with no snapshot yet also starts that first read; a
+ mark-read in any window re-reads the bound session's tail so `read_at` is
+ not stale when the next result lands.
+- **Setup is monotonic.** One wake runs several setup reads (a summon also
+ focuses the window). Any read that sees setup complete wins; an incomplete
+ answer applies only from the latest read; a failure only settles the first
+ check and never turns a known state back.
+- **An authorization change drops what was read under the old one.** The
+ session, tail, turn state and switcher rows are cleared at once and re-read.
+ Pending vault requests do the same in the shared `usePendingVaultRequests`
+ (so the chat page gets it too), and the inbox has its own handler. A
+ `session.status` event that arrives with no session row starts a read
+ instead of patching nothing.
+- **Mark-read answers are ordered in the inbox provider.** A newer mark-read
+ or read-changing event for a session supersedes an older answer for it, and
+ the account-wide unread map in an answer is adopted only if no other write
+ or snapshot has committed since the write began; otherwise only that
+ session's count is merged.
+- **`design.pen` frames are deferred.** The panel reuses existing tokens and
+ primitives; frames follow once the shell PR makes the pet visible.
+- **Pet input uses the session GET's project grant.** Workbench Chat combines
+ instance `can_chat` with bootstrap `capabilities.can_chat`. The pet already
+ reads the session row, so GET `/api/sessions/<id>` now includes the same
+ `{capabilities:{can_chat}}` sibling (the session fields stay top-level; the
+ client strips `capabilities` before treating the rest as the row). An
+ instance editor who is a project viewer therefore sees state but no composer
+ or quick replies; POST remains rejected by project-role middleware.
+
## Follow-ups
- Bind to the main-agent session when the session type lands, and remove the
@@ -648,11 +777,12 @@ The microphone usage string and audio-input entitlement already ship (#2293).
- [x] Update G8 and G10 in `desktop-product-gaps.md` to point here.
- [ ] Pet window, lifecycle invariants, capability file, and IPC.
- [ ] Global shortcut, tray toggle and presets, `pet.json`.
-- [ ] `/pet` route, session binding, "Show in pet".
-- [ ] `derivePetState` with Vitest coverage.
-- [ ] Panel: latest exchange, activity strip, needs input, text send.
-- [ ] Input-freshness table for the pet route; extract `useSessionTurnState` from the chat page.
+- [x] `/pet` route and session binding ("Show in pet" ships with the shell PR).
+- [x] `derivePetState` with Vitest coverage.
+- [x] Panel: latest exchange, activity strip, needs input, text send.
+- [x] Input-freshness table for the pet route (`usePetSession`, `FencedSource`).
- [ ] Shared dictation hook; cross-window voice claim; pet listening flow.
-- [ ] Vibey pose assets, CSS motion, and panel design in `design.pen`; i18n strings.
+- [x] Vibey pose assets, CSS motion, i18n strings.
+- [ ] Panel frames in `design.pen`.
- [ ] Rust boundary tests; manual checks on macOS and Windows.
- [ ] User docs: `desktop/README.md` pet section.
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 05ccbb973..d7d91363c 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -486,4 +486,28 @@ scenarios:
- tests/test_model_hub_runtime.py::test_oauth_failure_detail_is_the_engine_reason_on_one_bounded_line
- ui/src/components/settings/models/serverCopy.test.ts
- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+ - id: AUTH-SETUP-128
+ name: The desktop pet leaves its setup-pending state once setup is finished in the main window
+ status: partial
+ kind: happy_path
+ layer: scenario
+ missing_layer: ui-e2e
+ backend: web
+ reason: >-
+ the rule is a browser rule across two windows with no new server boundary:
+ the pet route sits behind the login and authorization gates but is exempt
+ from the setup redirect, shows its own setup-pending state, and re-reads
+ the configuration past the config cache on every summon, focus and
+ visibility change, so finishing the wizard in the main window clears it
+ without a restart. The route tests drive the real setup gate, summon store
+ and config read against controlled responses; the packaged two-window
+ journey lands with the desktop shell PR that creates the pet window.
+ owning_layer: L4 integrated acceptance (packaged desktop shell against a live instance)
+ partial_evidence:
+ covers: the server half at the real boundary — the `/pet` shell document, authentication refusal of the config read, a signed-in pet read that reports setup pending with the fields the setup rule reads, completion from a second client through CSRF, and the pet's per-call re-read seeing it; the browser rules are the supporting tests below, against controlled responses
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_pet_window_reads_setup_finished_in_the_main_window_closed_loop
+ supporting_tests:
+ - ui/src/pet/PetPage.test.tsx
+ - ui/src/lib/remoteAuth.test.ts
+ - ui/src/App.remoteAuth.test.tsx
next_priority: []
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 1238bbe71..959420bb1 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -355,6 +355,88 @@ def test_authorized_config_envelope_and_completion_persistence_closed_loop(monke
SettingsStore.reset_instance()
+def test_pet_window_reads_setup_finished_in_the_main_window_closed_loop(monkeypatch, tmp_path):
+ """Scenarios: AUTH-SETUP-128 producer — the desktop pet leaves setup-pending once setup is
+ finished in the main window.
+
+ Two clients share one signed-in principal, as the pet and main windows share one
+ session. The `/pet` document is the non-sensitive SPA shell, served without a
+ session like every client route; what it shows is decided by `/api/config`, which
+ refuses an unauthenticated read and, for the signed-in pet, reports setup pending
+ with the `mode` and `setup_state` fields `isSetupComplete()` reads. The main window
+ then finishes setup through the same narrow CSRF-gated POSTs as the wizard, with no
+ message to the pet, and the pet's next read reports setup complete.
+
+ What this proves is the server half the pet relies on: its re-read is answered per
+ call, so a re-read after the main window's write sees it. When the pet re-reads
+ (summon, focus, visibility), its exemption from the setup redirect, and how it
+ orders overlapping reads are browser rules, asserted against controlled responses
+ in `ui/src/pet/PetPage.test.tsx` and `ui/src/lib/remoteAuth.test.ts`. Neither layer
+ runs the two real windows; that journey stays with the desktop shell PR.
+ """
+ from config.v2_settings import SettingsStore
+ from vibe import internal_client
+
+ config = _save_config(tmp_path, paired=True, instance_kind="personal")
+ ui_dist = tmp_path / "dist"
+ ui_dist.mkdir()
+ (ui_dist / "index.html").write_text("<html>avibe</html>", encoding="utf-8")
+ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)
+ monkeypatch.setattr(ui_server, "_ensure_remote_access_monitoring", lambda *_args: None)
+ monkeypatch.setattr(
+ internal_client, "reconcile_platforms",
+ AsyncMock(return_value={"status_code": 200, "body": {"ok": True}}),
+ )
+ # Finishing setup may not reach a real runtime action.
+ monkeypatch.setattr(remote_access, "reconcile", Mock(side_effect=AssertionError("pairing changed")))
+ monkeypatch.setattr(
+ ui_server, "_schedule_service_restart_for_config_fallback",
+ Mock(side_effect=AssertionError("unexpected restart")),
+ )
+ base_url = "https://alex.avibe.bot"
+ peer = {"REMOTE_ADDR": "203.0.113.44"}
+
+ def signed_in():
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(config, "[email protected]", "owner-1", role="owner", access_source="owner"),
+ domain="alex.avibe.bot",
+ )
+ return client
+
+ SettingsStore.reset_instance()
+ try:
+ anonymous = app.test_client()
+ shell = anonymous.get("/pet", base_url=base_url, environ_base=peer, headers={"Accept": "text/html"})
+ assert shell.status_code == 200
+ assert shell.headers["Cache-Control"] == "no-store, private"
+ refused = anonymous.get("/api/config", base_url=base_url, environ_base=peer)
+ assert refused.status_code == 401
+ assert refused.get_json()["error"] == "remote_access_login_required"
+
+ pet, main = signed_in(), signed_in()
+ pending = pet.get("/api/config", base_url=base_url, environ_base=peer)
+ assert pending.status_code == 200
+ assert pending.get_json()["mode"]
+ assert pending.get_json()["setup_state"]["needs_setup"] is True
+
+ headers = csrf_headers(main, base_url=base_url)
+ for payload in (
+ {"slack": {"bot_token": "xoxb-pet-fixture", "app_token": "xapp-pet-fixture"}},
+ {"setup_completed": True},
+ ):
+ response = main.post("/api/config", json=payload, headers=headers, base_url=base_url, environ_base=peer)
+ assert response.status_code == 200, response.get_json()
+
+ reread = pet.get("/api/config", base_url=base_url, environ_base=peer)
+ assert reread.status_code == 200
+ assert reread.get_json()["mode"]
+ assert reread.get_json()["setup_state"]["needs_setup"] is False
+ finally:
+ SettingsStore.reset_instance()
+
+
def test_limited_show_identity_closed_loop_installs_guest_lease(monkeypatch, tmp_path):
"""Scenario: AUTH-SETUP-404"""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index 0e1cd26bf..6a8493f0c 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -238,6 +238,7 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
session = _get(client, f"/api/sessions/{ids['session_a']}").get_json()
assert session["workdir"] == str((tmp_path / "project-a").resolve())
assert session["metadata"] == {"created_via": "workbench"}
+ assert session["capabilities"] == {"can_chat": True}
assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 200
assert _get(client, f"/api/sessions/{ids['session_b']}/messages").status_code == 404
assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 404
@@ -379,6 +380,11 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
assert viewer_project["folder_path"] == ""
assert viewer_project["metadata"] == {}
+ viewer_session = _get(client, f"/api/sessions/{ids['session_a']}")
+ assert viewer_session.status_code == 200
+ assert viewer_session.get_json()["capabilities"] == {"can_chat": False}
+ assert viewer_session.get_json()["id"] == ids["session_a"]
+
viewer_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")
assert viewer_bootstrap.status_code == 200
@@ -401,6 +407,10 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
},
)
+ editor_session = _get(client, f"/api/sessions/{ids['session_a']}")
+ assert editor_session.status_code == 200
+ assert editor_session.get_json()["capabilities"] == {"can_chat": True}
+
editor_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")
assert editor_bootstrap.status_code == 200
diff --git a/ui/e2e/inbox-return/fixture.tsx b/ui/e2e/inbox-return/fixture.tsx
index 7bd83eb15..2acfd3bdd 100644
--- a/ui/e2e/inbox-return/fixture.tsx
+++ b/ui/e2e/inbox-return/fixture.tsx
@@ -27,7 +27,7 @@ const history = Array.from({ length: 90 }, (_, index) => makeRow(index + 1));
const params = new URLSearchParams(window.location.search);
const delay = Number(params.get('delay') ?? 0);
-function Chat({ markRead, addActivity }: { markRead: (id: string) => Promise<void>; addActivity: () => void }) {
+function Chat({ markRead, addActivity }: { markRead: (id: string) => Promise<boolean>; addActivity: () => void }) {
const { sessionId } = useParams();
const navigate = useNavigate();
useEffect(() => {
@@ -55,6 +55,7 @@ export function Fixture() {
delete next[id];
return next;
});
+ return true;
}, []);
const addActivity = () => {
setSessions((prev) => prev.some((row) => row.session_id === 'session-100') ? prev : [makeRow(100), ...prev]);
diff --git a/ui/e2e/project-order/fixture.tsx b/ui/e2e/project-order/fixture.tsx
index c28cb64c0..2e7babdb6 100644
--- a/ui/e2e/project-order/fixture.tsx
+++ b/ui/e2e/project-order/fixture.tsx
@@ -73,7 +73,7 @@ export function Fixture() {
<WorkbenchProjectsProvider><WorkbenchInboxContext.Provider value={{
inboxSessions: [], unreadBySession: {}, totalUnread: 0, unreadSessions: 0, nextCursor: null,
loading: false, loadingMore: false, refresh: async () => {}, loadMore: async () => {},
- markRead: async () => {}, activateFeed: () => noop,
+ markRead: async () => true, activateFeed: () => noop,
}}><WindowManagerContext.Provider value={{ focusedId: null, focusCanvas: noop, openApp: noop } as unknown as WindowManagerValue}>
<div className="flex h-dvh overflow-hidden bg-background text-foreground">
<aside className="hidden h-full w-64 shrink-0 border-r border-border md:flex" data-testid="desktop-tree"><WorkbenchSidebar /></aside>
diff --git a/ui/e2e/session-dot/fixture.tsx b/ui/e2e/session-dot/fixture.tsx
index 5740fce1e..dddf5c52a 100644
--- a/ui/e2e/session-dot/fixture.tsx
+++ b/ui/e2e/session-dot/fixture.tsx
@@ -124,7 +124,7 @@ export function Fixture() {
<WorkbenchProjectsProvider><WorkbenchInboxContext.Provider value={{
inboxSessions: [], unreadBySession: {}, totalUnread: 0, unreadSessions: 0, nextCursor: null,
loading: false, loadingMore: false, refresh: async () => {}, loadMore: async () => {},
- markRead: async () => {}, activateFeed: () => noop,
+ markRead: async () => true, activateFeed: () => noop,
}}><WindowManagerContext.Provider value={{ focusedId: null, focusCanvas: noop, openApp: noop } as unknown as WindowManagerValue}>
<div className="flex h-dvh overflow-hidden bg-background text-foreground">
<aside className="hidden h-full w-64 shrink-0 border-r border-border md:flex" data-testid="desktop-tree"><WorkbenchSidebar /></aside>
diff --git a/ui/src/App.remoteAuth.test.tsx b/ui/src/App.remoteAuth.test.tsx
index e76c2f783..42b2ad563 100644
--- a/ui/src/App.remoteAuth.test.tsx
+++ b/ui/src/App.remoteAuth.test.tsx
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom';
import { AuthGuard } from './App';
+import { PetWindow } from './pet/PetWindow';
import { Summary } from './components/steps/Summary';
import { useInstanceAuthorization } from './context/InstanceAuthorizationContext';
import { DENIED_INSTANCE_CAPABILITIES, OWNER_INSTANCE_CAPABILITIES } from './lib/sessionInfo';
@@ -36,7 +37,8 @@ const api = vi.hoisted(() => ({
}));
const status = vi.hoisted(() => ({ control: vi.fn() }));
-vi.mock('./context/ApiContext', () => ({
+vi.mock('./context/ApiContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./context/ApiContext')>()),
useApi: () => api,
}));
vi.mock('./context/StatusContext', () => ({ useStatus: () => status }));
@@ -229,6 +231,87 @@ describe('AuthGuard setup-bypass authorization', () => {
});
});
+describe('AuthGuard on the desktop pet route', () => {
+ const localOwnerSession = {
+ remote: false as const,
+ instance_kind: 'personal' as const,
+ instance_role: 'owner' as const,
+ capabilities: OWNER_INSTANCE_CAPABILITIES,
+ };
+
+ it('renders the pet with its authorization while setup is pending, without the wizard', async () => {
+ api.getAuthSession.mockResolvedValue(localOwnerSession);
+ api.getConfig.mockResolvedValue({ mode: 'v2', setup_state: { needs_setup: true } });
+
+ render(
+ <MemoryRouter initialEntries={['/pet']}>
+ <AuthGuard>
+ <Routes>
+ <Route path="/pet" element={<CapabilityProbe />} />
+ <Route path="/setup" element={<div>setup-wizard</div>} />
+ </Routes>
+ </AuthGuard>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByText('owner-shell')).toBeTruthy();
+ expect(screen.queryByText('setup-wizard')).toBeNull();
+ });
+
+ it('keeps the transparent pet style while authorization is still loading', async () => {
+ api.getAuthSession.mockReturnValue(new Promise(() => undefined));
+
+ render(
+ <MemoryRouter initialEntries={['/pet']}>
+ <PetWindow>
+ <AuthGuard>
+ <CapabilityProbe />
+ </AuthGuard>
+ </PetWindow>
+ </MemoryRouter>,
+ );
+
+ expect(document.documentElement.classList.contains('pet-window')).toBe(true);
+ expect(screen.queryByText('common.loading')).toBeNull();
+ expect(document.querySelector('.bg-bg')).toBeNull();
+ });
+
+ it('does not render the pet without a session, and checks again when the page comes back', async () => {
+ let focused = true;
+ const hasFocus = vi.spyOn(document, 'hasFocus').mockImplementation(() => focused);
+ api.getAuthSession
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue(localOwnerSession);
+ api.getConfig.mockResolvedValue({ mode: 'v2', setup_state: { needs_setup: false } });
+
+ render(
+ <MemoryRouter initialEntries={['/pet']}>
+ <AuthGuard>
+ <CapabilityProbe />
+ </AuthGuard>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(api.getAuthSession).toHaveBeenCalledTimes(2));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));
+ expect(screen.queryByText('denied-shell')).toBeNull();
+ expect(screen.queryByText('owner-shell')).toBeNull();
+
+ act(() => {
+ focused = false;
+ window.dispatchEvent(new Event('blur'));
+ });
+ act(() => {
+ focused = true;
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ expect(await screen.findByText('owner-shell')).toBeTruthy();
+ hasFocus.mockRestore();
+ });
+});
+
describe('AuthGuard General Settings over setup', () => {
// AUTH-SETUP-125
it('opens the desktop Settings request over the wizard without leaving it', async () => {
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 151dbe9f9..2edf8f666 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -11,6 +11,7 @@ import {
import { Wizard } from './components/Wizard';
import { AppShell } from './components/AppShell';
import { ErrorBoundary } from './components/ui/error-boundary';
+import { PetWindow } from './pet/PetWindow';
import { Workbench } from './components/Workbench';
import { InboxPage } from './components/workbench/InboxPage';
import { SearchPage } from './components/workbench/SearchPage';
@@ -56,6 +57,7 @@ import type { ReactNode } from 'react';
import {
checkRemoteAuthForPath,
isSetupCheckBypassed,
+ isSetupRedirectExempt,
remoteLoginPath,
REMOTE_AUTH_REQUIRED_EVENT,
REMOTE_AUTH_STATE_EVENT,
@@ -78,6 +80,10 @@ const AppsTerminalPage = lazy(() =>
const AppsEditorPage = lazy(() =>
import('./components/workbench/AppsEditorPage').then((m) => ({ default: m.AppsEditorPage })),
);
+// The desktop pet window's page: its own small surface, outside the Workbench
+// shell. It sits behind AuthGuard's login and authorization gates, and is
+// exempt only from the setup redirect (docs/plans/2026-10-01-desktop-pet.md).
+const PetPage = lazy(() => import('./pet/PetPage').then((m) => ({ default: m.PetPage })));
const LibraryAppBody = lazy(() => import('./apps/LibraryApp').then((m) => ({ default: m.LibraryApp })));
// The mobile full-screen Show Page route body. Lazy so the iframe frame + session
// lookup load only when a pinned page is opened, not into the main entry.
@@ -93,7 +99,7 @@ const SettingsModelsPage = lazy(() =>
import { ModelHubCapabilityGate } from './components/settings/models/ModelHubCapabilityGate';
import { MODEL_HUB_SETTINGS_PATH } from './components/settings/models/modelHubRoutes';
import { settingsOverlayOriginFromState, SETUP_VISIT_SETTINGS_PATHS } from './lib/settingsOverlay';
-import { hasConfiguredPlatformCredentials } from './lib/platforms';
+import { isSetupComplete } from './lib/setupState';
import { isIosDevice, isStandalonePwa } from './lib/platform';
import {
readLastPwaPath,
@@ -299,6 +305,7 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
const [setupModelHubAllowed, setSetupModelHubAllowed] = useState(false);
const authorizationUnavailableRef = useRef(false);
const bypassSetupGuard = isSetupCheckBypassed(location.pathname);
+ const setupRedirectExempt = isSetupRedirectExempt(location.pathname);
// Re-validate only when crossing the setup boundary, not on every
// route change. The wizard completes by saving config and navigating
// off /setup; that pathname flip re-runs the effect so the stale
@@ -420,11 +427,7 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
// setup repair route. Unlike Diagnostics it is not a bypass.
setSetupModelHubAllowed(Boolean(config?.mode
&& 'capabilities' in session && session.capabilities?.can_manage_instance));
- const setupState = config?.setup_state;
- const setupReady = typeof setupState?.needs_setup === 'boolean'
- ? setupState.needs_setup === false
- : hasConfiguredPlatformCredentials(config);
- if (!config || !config.mode || !setupReady) {
+ if (!isSetupComplete(config)) {
setGuardStatus('needs-setup');
return;
}
@@ -485,10 +488,25 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
// completion clears the stale needs-setup status, while ordinary
// sidebar navigation never re-runs (which would re-mount the
// shell behind the Loading state).
- }, [authCheckVersion, bypassSetupGuard, isSetupRoute, getConfig, getAuthSession]);
+ }, [authCheckVersion, bypassSetupGuard, setupRedirectExempt, isSetupRoute, getConfig, getAuthSession]);
+
+ // A route exempt from the setup redirect still needs a session: without one
+ // its capabilities would read as denied. When the first probe found none
+ // (the Runtime was unreachable), check again each time the page comes back.
+ const awaitingExemptSession = setupRedirectExempt && guardStatus === 'needs-setup' && !authorizationSession;
+ useEffect(() => {
+ if (!awaitingExemptSession) return undefined;
+ return onPageReactivated(() => setAuthCheckVersion((version) => version + 1));
+ }, [awaitingExemptSession]);
+
+ // `/pet` is a transparent native window. An opaque loading surface would
+ // show as a solid square for the whole recheck; leave the frame empty.
+ const guardLoading = setupRedirectExempt
+ ? null
+ : <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
if (guardStatus === 'loading') {
- return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
+ return guardLoading;
}
if (guardStatus === 'remote-login-required') {
return <RemoteLoginGate target={guardTarget} />;
@@ -512,7 +530,7 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
if (guardStatus === 'access-blocked') {
return <AccessBlocked code={blockedCode} />;
}
- if (guardStatus === 'needs-setup' && !bypassSetupGuard) {
+ if (guardStatus === 'needs-setup' && !bypassSetupGuard && !setupRedirectExempt) {
// Model Hub keeps its own grant; General needs only the wizard beneath it.
if (authorizationSession && (location.pathname === '/setup'
|| (settingsOverSetup && location.pathname !== MODEL_HUB_SETTINGS_PATH)
@@ -531,7 +549,7 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
// (which owns the re-render) flips `guardStatus` to loading.
// eslint-disable-next-line react-hooks/refs -- Deliberate one-frame bridge; see above.
if (previousIsSetupRouteRef.current) {
- return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
+ return guardLoading;
}
return <Navigate to="/setup" replace />;
}
@@ -540,7 +558,7 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
// unfinished install can still inspect doctor output. Once the session
// lands, wrap it so AppShell does not treat the owner as denied.
if (bypassSetupGuard) return children;
- return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
+ return guardLoading;
}
return (
<>
@@ -816,11 +834,25 @@ function RouterRoot() {
const router = createBrowserRouter(
createRoutesFromElements(
+ <>
+ <Route
+ path="/pet"
+ element={(
+ <ErrorBoundary variant="page">
+ <PetWindow>
+ <AuthGuard>
+ <Suspense fallback={null}><PetPage /></Suspense>
+ </AuthGuard>
+ </PetWindow>
+ </ErrorBoundary>
+ )}
+ />
<Route element={<ErrorBoundary variant="page"><RouterRoot /></ErrorBoundary>}>
<Route element={<AuthGuard><AppShell /></AuthGuard>}>
<Route path="*" element={<WorkbenchRouteSurface />} />
</Route>
- </Route>,
+ </Route>
+ </>,
),
);
diff --git a/ui/src/assets/pet/vibey-celebrate.png b/ui/src/assets/pet/vibey-celebrate.png
new file mode 100644
index 000000000..2025fff49
Binary files /dev/null and b/ui/src/assets/pet/vibey-celebrate.png differ
diff --git a/ui/src/assets/pet/vibey-error.png b/ui/src/assets/pet/vibey-error.png
new file mode 100644
index 000000000..9ee37e5b8
Binary files /dev/null and b/ui/src/assets/pet/vibey-error.png differ
diff --git a/ui/src/assets/pet/vibey-focus.png b/ui/src/assets/pet/vibey-focus.png
new file mode 100644
index 000000000..d4942dd00
Binary files /dev/null and b/ui/src/assets/pet/vibey-focus.png differ
diff --git a/ui/src/assets/pet/vibey-message.png b/ui/src/assets/pet/vibey-message.png
new file mode 100644
index 000000000..620020f90
Binary files /dev/null and b/ui/src/assets/pet/vibey-message.png differ
diff --git a/ui/src/assets/pet/vibey-sleep.png b/ui/src/assets/pet/vibey-sleep.png
new file mode 100644
index 000000000..225330bcc
Binary files /dev/null and b/ui/src/assets/pet/vibey-sleep.png differ
diff --git a/ui/src/assets/pet/vibey-thinking.png b/ui/src/assets/pet/vibey-thinking.png
new file mode 100644
index 000000000..618009acb
Binary files /dev/null and b/ui/src/assets/pet/vibey-thinking.png differ
diff --git a/ui/src/assets/pet/vibey.png b/ui/src/assets/pet/vibey.png
new file mode 100644
index 000000000..db364e478
Binary files /dev/null and b/ui/src/assets/pet/vibey.png differ
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index cf2370295..ec52345c7 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -512,7 +512,9 @@ export type TunnelConnectivityDiagnostics = {
};
export type ApiContextType = {
- getConfig: () => Promise<any>;
+ /** `cache: false` reads past the 30-second config cache, for a surface (the
+ * desktop pet) that must see a setup another window just finished. */
+ getConfig: (options?: { cache?: boolean }) => Promise<any>;
getPlatformCatalog: () => Promise<any>;
mutateConfig: (mutations: readonly ConfigMutation[]) => Promise<any>;
waitForAgentActivityConfigMutations: () => Promise<void>;
@@ -964,8 +966,23 @@ export type WorkbenchSession = {
export type WorkbenchSessionReadResult = {
status: number;
session: WorkbenchSession | null;
+ /** Project-level chat grant; omitted when the payload has no usable flag. */
+ capabilities?: { can_chat: boolean };
};
+/** GET /api/sessions/:id carries capabilities as a sibling of the row fields. */
+function sessionCanChatFromPayload(payload: { capabilities?: { can_chat?: unknown } } | null): { can_chat: boolean } | undefined {
+ return payload?.capabilities && typeof payload.capabilities.can_chat === 'boolean'
+ ? { can_chat: payload.capabilities.can_chat }
+ : undefined;
+}
+
+function sessionRowFromPayload(payload: WorkbenchSession & { capabilities?: unknown }): WorkbenchSession {
+ if (!payload || typeof payload !== 'object') return payload;
+ const { capabilities: _capabilities, ...row } = payload;
+ return row;
+}
+
export type WorkbenchSessionCreate = {
project_id: string;
// Optional: when omitted the server resolves the current default Agent.
@@ -3359,7 +3376,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
// is correct (cached error messages would otherwise stay in the
// old language).
const value: ApiContextType = useMemo(() => ({
- getConfig: () => getCachedJson('/api/config', CONFIG_CACHE_TTL_MS),
+ getConfig: (options) => (options?.cache === false
+ ? getJson('/api/config')
+ : getCachedJson('/api/config', CONFIG_CACHE_TTL_MS)),
getPlatformCatalog: () => getJson('/api/platforms'),
mutateConfig: (mutations) => {
const save = async () => {
@@ -3700,16 +3719,22 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
createSession: (payload) => postJson('/api/sessions', payload),
forkSession: (sessionId) =>
postJson(`/api/sessions/${encodeURIComponent(sessionId)}/fork`, {}),
- getSession: (sessionId, params) =>
- params?.cache === false
- ? getJson(`/api/sessions/${encodeURIComponent(sessionId)}`, { handleError: params?.handleError })
- : getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`, undefined, { handleError: params?.handleError }),
+ getSession: async (sessionId, params) => {
+ const payload = params?.cache === false
+ ? await getJson(`/api/sessions/${encodeURIComponent(sessionId)}`, { handleError: params?.handleError })
+ : await getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`, undefined, { handleError: params?.handleError });
+ return sessionRowFromPayload(payload);
+ },
getSessionResult: async (sessionId) => {
const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`);
const payload = await res.json().catch(() => null);
+ if (!(res.ok && payload && typeof payload.id === 'string')) {
+ return { status: res.status, session: null };
+ }
return {
status: res.status,
- session: res.ok && payload && typeof payload.id === 'string' ? payload : null,
+ session: sessionRowFromPayload(payload),
+ capabilities: sessionCanChatFromPayload(payload),
};
},
getSessionBootstrap: async (sessionId) => {
diff --git a/ui/src/context/WorkbenchInboxContext.ts b/ui/src/context/WorkbenchInboxContext.ts
index cfcd2e11a..64f8eaad7 100644
--- a/ui/src/context/WorkbenchInboxContext.ts
+++ b/ui/src/context/WorkbenchInboxContext.ts
@@ -24,7 +24,9 @@ export interface InboxState {
loadingMore: boolean;
refresh: () => Promise<void>;
loadMore: () => Promise<void>;
- markRead: (sessionId: string, untilMessageId?: string) => Promise<void>;
+ /** Resolves true when the server applied the read, false when it did not
+ * (errors are not raised: clearing unread is best-effort). */
+ markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>;
/** Refcounted activation for the FEED (see ``useConsumerActivation``). The
* unread map is unconditional — it badges the favicon and the app icon on
* every route — but ``inboxSessions`` is only rendered by the sidebar and the
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 6ba3cf4c6..58b3dde60 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -452,15 +452,33 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// independent capabilities.
const operation = readOwnershipRef.current.beginRead(`inbox-mark-read:${sessionId}`);
const result = await api.markSessionRead(sessionId, untilMessageId, { handleError: false });
+ // With handleError off, a 4xx/5xx resolves with the error body rather
+ // than throwing; only the endpoint's success shape is an applied write.
+ const applied = typeof result?.updated === 'number' || Boolean(result?.unread_by_session);
+ // A later *started* write for this session (a second mark-read, or a
+ // read-changing event) supersedes this one. Completing an older write
+ // first must not fence a newer write that started after it: both share
+ // the same mutation epoch until one of them commits.
+ const laterMarkStarted = (readOwnershipRef.current.latestGeneration(`inbox-mark-read:${sessionId}`) ?? 0) > operation.generation;
if (
- !readOwnershipRef.current.isMutationCurrent(operation, `inbox-session:${sessionId}`)
+ !applied
+ || laterMarkStarted
+ || !readOwnershipRef.current.isMutationCurrent(operation, [
+ `inbox-session:${sessionId}`,
+ `inbox-unread-session:${sessionId}`,
+ ])
) {
- return;
+ return applied;
}
+ // The response carries the whole account map, but it describes the other
+ // sessions only as of this write. It is adopted whole only if nothing has
+ // changed or committed the whole map since this write began; otherwise
+ // only this session's count, which nothing newer has touched, is merged.
+ const wholeMapCurrent =
+ readOwnershipRef.current.isMutationCurrent(operation, 'inbox-unread')
+ && committedWholeUnreadGenerationRef.current <= operation.generation;
// A successful write commits after every read that was already in flight,
- // even when one of those reads started later and returns last. The endpoint
- // mutates only this session, so merge only that count; concurrent mark-read
- // writes for other sessions remain independent.
+ // even when one of those reads started later and returns last.
readOwnershipRef.current.acceptMutation([
'inbox-unread',
`inbox-unread-session:${sessionId}`,
@@ -468,10 +486,12 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// The unread map is authoritative for badges; the card's unread styling
// derives from it, so clearing here clears the dot without touching the
// feed order (a read doesn't change last activity).
- if (!result?.unread_by_session) return;
- applyUnreadMap(result.unread_by_session);
+ const map = result.unread_by_session;
+ if (map && wholeMapCurrent) applyUnreadMap(map);
+ else if (map) applySessionUnread(sessionId, map[sessionId] ?? 0);
+ return true;
},
- [api, applyUnreadMap],
+ [api, applySessionUnread, applyUnreadMap],
);
// Resume reconcile: re-read the feed WITHOUT collapsing pagination. A
@@ -833,7 +853,17 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
onInboxUnreadChanged: (data) => {
if (data?.unread_by_session) {
// The event IS the newest whole map: fence the reads in flight, then adopt it.
- acceptUnreadMutation();
+ // Include the session slice when the event names one, so an in-flight
+ // mark-read for that session cannot merge its older count over this map.
+ if (data.session_id) {
+ readOwnershipRef.current.acceptMutation([
+ 'inbox-unread',
+ 'inbox-unread-all',
+ `inbox-unread-session:${data.session_id}`,
+ ]);
+ } else {
+ acceptUnreadMutation();
+ }
applyUnreadMap(data.unread_by_session);
return;
}
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index e2fdca8a5..25f258eaf 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -1064,6 +1064,152 @@ describe('Workbench session read ownership', () => {
expect(inbox?.unreadBySession).toEqual({ [sessionB.id]: 4 });
});
+ const renderInboxWithMarks = async (marks: Array<Promise<unknown>>) => {
+ const markSessionRead = vi.fn();
+ marks.forEach((mark) => markSessionRead.mockReturnValueOnce(mark));
+ apiRef.current = {
+ listInbox: vi.fn().mockResolvedValue({
+ sessions: [inboxRow],
+ next_cursor: null,
+ unread_by_session: { [session.id]: 3, [sessionB.id]: 5 },
+ }),
+ markSessionRead,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ const holder: { inbox: ReturnType<typeof useWorkbenchInbox> | null } = { inbox: null };
+ const Probe = () => {
+ const value = useWorkbenchInbox();
+ useEffect(() => {
+ holder.inbox = value;
+ }, [value]);
+ return null;
+ };
+ render(
+ <WorkbenchInboxProvider>
+ <Probe />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ return holder;
+ };
+
+ it('does not let a mark-read overwrite a newer unread event for the same session', async () => {
+ const mark = deferred({ unread_by_session: {} as Record<string, number> });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox: vi.fn().mockResolvedValue({
+ sessions: [inboxRow],
+ next_cursor: null,
+ unread_by_session: { [session.id]: 1 },
+ }),
+ markSessionRead: vi.fn().mockReturnValue(mark.promise),
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ const holder: { inbox: ReturnType<typeof useWorkbenchInbox> | null } = { inbox: null };
+ const Probe = () => {
+ const value = useWorkbenchInbox();
+ useEffect(() => {
+ holder.inbox = value;
+ }, [value]);
+ return null;
+ };
+ render(
+ <WorkbenchInboxProvider>
+ <Probe />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ act(() => {
+ void holder.inbox?.markRead(session.id, 'msg_old');
+ });
+ await settle();
+ act(() => {
+ handlers?.onInboxUnreadChanged?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ delta: 1,
+ unread_counts: { agent: 1 },
+ unread_by_session: { [session.id]: 1, [sessionB.id]: 2 },
+ });
+ });
+ await act(async () => {
+ mark.resolve({ unread_by_session: {} });
+ await mark.promise;
+ });
+ await settle();
+
+ expect(holder.inbox?.unreadBySession).toEqual({ [session.id]: 1, [sessionB.id]: 2 });
+ });
+
+ it('lets a newer mark-read for the same session land after an older one that finished first', async () => {
+ const older = deferred({ unread_by_session: {} as Record<string, number> });
+ const newer = deferred({ unread_by_session: {} as Record<string, number> });
+ const holder = await renderInboxWithMarks([older.promise, newer.promise]);
+
+ act(() => {
+ void holder.inbox?.markRead(session.id, 'msg_1');
+ void holder.inbox?.markRead(session.id, 'msg_2');
+ });
+ await act(async () => {
+ older.resolve({ unread_by_session: { [session.id]: 1, [sessionB.id]: 5 } });
+ await older.promise;
+ });
+ await act(async () => {
+ newer.resolve({ unread_by_session: { [sessionB.id]: 2 } });
+ await newer.promise;
+ });
+ await settle();
+
+ expect(holder.inbox?.unreadBySession).toEqual({ [sessionB.id]: 2 });
+ });
+
+ it('does not let an older mark-read for the same session land over a newer one', async () => {
+ const older = deferred({ unread_by_session: {} as Record<string, number> });
+ const newer = deferred({ unread_by_session: {} as Record<string, number> });
+ const holder = await renderInboxWithMarks([older.promise, newer.promise]);
+
+ act(() => {
+ void holder.inbox?.markRead(session.id, 'msg_1');
+ void holder.inbox?.markRead(session.id, 'msg_2');
+ });
+ await act(async () => {
+ newer.resolve({ unread_by_session: { [sessionB.id]: 2 } });
+ await newer.promise;
+ });
+ await act(async () => {
+ older.resolve({ unread_by_session: { [session.id]: 1, [sessionB.id]: 5 } });
+ await older.promise;
+ });
+ await settle();
+
+ expect(holder.inbox?.unreadBySession).toEqual({ [sessionB.id]: 2 });
+ });
+
+ it('merges only its own count from a mark-read whose account map another write has superseded', async () => {
+ const markA = deferred({ unread_by_session: {} as Record<string, number> });
+ const markB = deferred({ unread_by_session: {} as Record<string, number> });
+ const holder = await renderInboxWithMarks([markA.promise, markB.promise]);
+
+ act(() => {
+ void holder.inbox?.markRead(session.id);
+ void holder.inbox?.markRead(sessionB.id);
+ });
+ await act(async () => {
+ markB.resolve({ unread_by_session: { [session.id]: 3 } });
+ await markB.promise;
+ });
+ await act(async () => {
+ markA.resolve({ unread_by_session: { [sessionB.id]: 5 } });
+ await markA.promise;
+ });
+ await settle();
+
+ expect(holder.inbox?.unreadBySession).toEqual({});
+ });
+
it('keeps a successful mark-read result when an older unread snapshot finishes last', async () => {
const markReadResult = deferred({ unread_by_session: { [sessionB.id]: 5 } });
const staleRefresh = deferred({
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 352f3ade6..27a0db89c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -5451,5 +5451,33 @@
"gatewayRequired": "Setup requires Model Hub to be enabled. Your saved configuration is unchanged. Restore it through your existing configuration controls, then retry.",
"completionUnconfirmed": "Setup completion could not be confirmed. Try again."
}
+ },
+ "pet": {
+ "state": {
+ "idle": "Vibey is idle",
+ "sleeping": "Vibey is asleep",
+ "listening": "Listening",
+ "running": "Working…",
+ "ready": "Reply ready",
+ "needs_input": "Needs your input",
+ "blocked": "Something went wrong"
+ },
+ "unreadBadge_one": "{{count}} unread reply",
+ "unreadBadge_other": "{{count}} unread replies",
+ "setupPending": "Finish setting up in Avibe to talk to your agent here.",
+ "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 the agent…",
+ "send": "Send",
+ "queued": "Queued — it will run after the current turn.",
+ "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."
}
}
diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.ts
index d3d90917b..b12a9b2f5 100644
--- a/ui/src/i18n/keyCoverage.test.ts
+++ b/ui/src/i18n/keyCoverage.test.ts
@@ -889,6 +889,7 @@ const NON_KEY_LITERALS = [
'avibe.agents.tab.v1',
'avibe.editor.fontSize.v1',
'avibe.editor.recents.v1',
+ 'avibe.pet.devBinding',
'avibe.terminal.fontSize.v1',
'avibe.terminal.sessionId',
'avibe.vault.crypto',
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 9cf4e4794..20334cb6d 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -5451,5 +5451,33 @@
"gatewayRequired": "设置流程需要启用模型网关。已有配置未改变,请通过现有配置管理恢复后重试。",
"completionUnconfirmed": "无法确认设置已完成,请重试"
}
+ },
+ "pet": {
+ "state": {
+ "idle": "云团子空闲中",
+ "sleeping": "云团子睡着了",
+ "listening": "正在听",
+ "running": "正在处理…",
+ "ready": "有新回复",
+ "needs_input": "需要你回应",
+ "blocked": "出了点问题"
+ },
+ "unreadBadge_one": "{{count}} 条未读回复",
+ "unreadBadge_other": "{{count}} 条未读回复",
+ "setupPending": "先在 Avibe 里完成设置,就可以在这里和 agent 对话了。",
+ "openAvibe": "打开 Avibe",
+ "toggle": "展开或收起宠物面板",
+ "panel": "宠物面板",
+ "untitled": "未命名会话",
+ "chooseSession": "选择一个会话",
+ "switchSession": "切换会话",
+ "openInAvibe": "在 Avibe 中打开",
+ "inputPlaceholder": "给 agent 发消息…",
+ "send": "发送",
+ "queued": "已排队,当前这轮结束后执行。",
+ "moreInAvibe": "更多回复请在 Avibe 中查看",
+ "empty": "还没有消息,说点什么开始吧。",
+ "vaultRequest": "需要授权,在 Avibe 中打开",
+ "noSessions": "还没有进行中的会话,先在 Avibe 里新建一个。"
}
}
diff --git a/ui/src/lib/applicationRoutes.ts b/ui/src/lib/applicationRoutes.ts
index c750d1e09..116c9bc57 100644
--- a/ui/src/lib/applicationRoutes.ts
+++ b/ui/src/lib/applicationRoutes.ts
@@ -13,6 +13,7 @@ export const APPLICATION_ROUTE_PATHS = [
'/vaults',
'/projects',
'/more',
+ '/pet',
'/apps',
'/apps/files',
'/apps/terminal',
diff --git a/ui/src/lib/remoteAuth.test.ts b/ui/src/lib/remoteAuth.test.ts
index ab185d8bc..ac4541c58 100644
--- a/ui/src/lib/remoteAuth.test.ts
+++ b/ui/src/lib/remoteAuth.test.ts
@@ -9,6 +9,8 @@ vi.mock('./platform', () => platform);
import {
checkRemoteAuthForPath,
+ isSetupCheckBypassed,
+ isSetupRedirectExempt,
deferRemoteAuthRedirect,
reportRemoteAuthorizationState,
remoteLoginPath,
@@ -72,6 +74,20 @@ describe('remote auth navigation', () => {
},
);
+ it('checks setup on the desktop pet, which is only exempt from the wizard redirect', async () => {
+ await expect(checkRemoteAuthForPath(
+ '/pet',
+ async () => ({ remote: true, authenticated: true }),
+ )).resolves.toEqual({
+ session: { remote: true, authenticated: true },
+ loginRequired: false,
+ checkSetup: true,
+ });
+ expect(isSetupRedirectExempt('/pet')).toBe(true);
+ expect(isSetupCheckBypassed('/pet')).toBe(false);
+ expect(isSetupRedirectExempt('/settings/diagnostics')).toBe(false);
+ });
+
it('checks setup after an authenticated remote session on regular app routes', async () => {
await expect(checkRemoteAuthForPath(
'/inbox',
diff --git a/ui/src/lib/remoteAuth.ts b/ui/src/lib/remoteAuth.ts
index 875f54361..ea7cd57a9 100644
--- a/ui/src/lib/remoteAuth.ts
+++ b/ui/src/lib/remoteAuth.ts
@@ -9,6 +9,11 @@ const SETUP_CHECK_BYPASS_PATHS = new Set([
'/admin/logs',
'/admin/settings/diagnostics',
]);
+// Routes that own their setup state. Unlike the diagnostics bypass above, the
+// guard checks login, authorization and setup as usual and only declines to
+// redirect them to the wizard: the desktop pet shows "finish setting up in
+// Avibe" instead of a pet-sized wizard.
+const SETUP_REDIRECT_EXEMPT_PATHS = new Set(['/pet']);
type PwaContext = {
ios: boolean;
@@ -51,6 +56,10 @@ export function isSetupCheckBypassed(path: string): boolean {
return SETUP_CHECK_BYPASS_PATHS.has(path);
}
+export function isSetupRedirectExempt(path: string): boolean {
+ return SETUP_REDIRECT_EXEMPT_PATHS.has(path);
+}
+
export async function checkRemoteAuthForPath<Session extends RemoteSession>(
path: string,
getSession: () => Promise<Session>,
diff --git a/ui/src/lib/setupState.ts b/ui/src/lib/setupState.ts
new file mode 100644
index 000000000..9d8a231f1
--- /dev/null
+++ b/ui/src/lib/setupState.ts
@@ -0,0 +1,17 @@
+import { hasConfiguredPlatformCredentials } from './platforms';
+
+/**
+ * Whether first-run setup is complete, from a `GET /api/config` payload. The
+ * one rule `AuthGuard` and the desktop pet both apply: the server's
+ * `setup_state.needs_setup` when present, otherwise configured platform
+ * credentials, and always a chosen mode.
+ */
+type SetupConfig = { mode?: unknown; setup_state?: { needs_setup?: unknown } | null } | null | undefined;
+
+export const isSetupComplete = (config: SetupConfig): boolean => {
+ if (!config || !config.mode) return false;
+ const setupState = config.setup_state;
+ return typeof setupState?.needs_setup === 'boolean'
+ ? setupState.needs_setup === false
+ : hasConfiguredPlatformCredentials(config);
+};
diff --git a/ui/src/lib/usePendingVaultRequests.test.ts b/ui/src/lib/usePendingVaultRequests.test.ts
new file mode 100644
index 000000000..85317704c
--- /dev/null
+++ b/ui/src/lib/usePendingVaultRequests.test.ts
@@ -0,0 +1,56 @@
+/* @vitest-environment jsdom */
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { usePendingVaultRequests } from './usePendingVaultRequests';
+
+type Handlers = {
+ onAuthorizationChanged?: (data: unknown) => void;
+ onEventBridgeStatus?: (data: { connected: boolean }) => void;
+};
+
+const handlers: Handlers[] = [];
+const connectWorkbenchEvents = vi.fn((next: Handlers) => {
+ handlers.push(next);
+ return () => {
+ const at = handlers.indexOf(next);
+ if (at >= 0) handlers.splice(at, 1);
+ };
+});
+const getVaultRequests = vi.fn();
+
+vi.mock('@/context/ApiContext', () => ({
+ useApi: () => ({ connectWorkbenchEvents, getVaultRequests }),
+}));
+
+const request = { id: 'vr_1', request_type: 'access', session_id: 'ses_1', card: null };
+
+afterEach(() => {
+ handlers.length = 0;
+ vi.clearAllMocks();
+ getVaultRequests.mockReset();
+});
+
+describe('usePendingVaultRequests', () => {
+ it('drops rows read under the old authorization and reads them again', async () => {
+ let answerReread: (value: { requests: unknown[] }) => void = () => undefined;
+ getVaultRequests.mockResolvedValue({ requests: [request] });
+
+ const { result } = renderHook(() => usePendingVaultRequests('ses_1'));
+ await waitFor(() => expect(result.current.requests).toHaveLength(1));
+ // A healthy bridge stops the fallback poll, so only events refresh now.
+ act(() => handlers.forEach((h) => h.onEventBridgeStatus?.({ connected: true })));
+
+ await act(async () => undefined);
+ const readsBefore = getVaultRequests.mock.calls.length;
+ getVaultRequests.mockReturnValueOnce(new Promise((resolve) => { answerReread = resolve; }));
+
+ act(() => handlers.forEach((h) => h.onAuthorizationChanged?.({})));
+ expect(result.current.requests).toEqual([]);
+ expect(getVaultRequests).toHaveBeenCalledTimes(readsBefore + 1);
+
+ await act(async () => answerReread({ requests: [{ ...request, id: 'vr_2' }] }));
+ expect(result.current.requests.map((r) => r.id)).toEqual(['vr_2']);
+ });
+});
diff --git a/ui/src/lib/usePendingVaultRequests.ts b/ui/src/lib/usePendingVaultRequests.ts
index 296c75b92..3d4221a6f 100644
--- a/ui/src/lib/usePendingVaultRequests.ts
+++ b/ui/src/lib/usePendingVaultRequests.ts
@@ -6,7 +6,8 @@ import { useLatestRef } from './useLatestRef';
/**
* Pending vault requests (access/sign/provision) for one chat session. Fed by
- * `vaults.updated`, with polling only when the controller event bridge is down.
+ * `vaults.updated`, with polling only when the controller event bridge is down,
+ * and cleared and re-read when the viewer's authorization changes.
* A timer also refreshes at the earliest visible `expires_at` because expiry
* emits no event. Lifted into a hook so the in-scroll cards and floating
* approval bar share one source.
@@ -56,6 +57,16 @@ export function usePendingVaultRequests(sessionId: string): { requests: VaultReq
useVaultRequestRefresh(load);
+ // Requests read under the old authorization may no longer be this viewer's to
+ // approve, and no `vaults.updated` is promised for that: drop them at once and
+ // re-read. The new load's token fences any read still in flight.
+ useEffect(() => api.connectWorkbenchEvents({
+ onAuthorizationChanged: () => {
+ setRequests([]);
+ void load();
+ },
+ }), [api, load]);
+
// Expiry has no SSE event → refresh at the earliest visible expires_at.
useEffect(() => {
const now = Date.now();
diff --git a/ui/src/pet/PetAvatar.tsx b/ui/src/pet/PetAvatar.tsx
new file mode 100644
index 000000000..13b402dd9
--- /dev/null
+++ b/ui/src/pet/PetAvatar.tsx
@@ -0,0 +1,90 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import vibey from '@/assets/pet/vibey.png';
+import vibeyCelebrate from '@/assets/pet/vibey-celebrate.png';
+import vibeyError from '@/assets/pet/vibey-error.png';
+import vibeyFocus from '@/assets/pet/vibey-focus.png';
+import vibeyMessage from '@/assets/pet/vibey-message.png';
+import vibeySleep from '@/assets/pet/vibey-sleep.png';
+import vibeyThinking from '@/assets/pet/vibey-thinking.png';
+import { usePageActive } from '@/lib/pageActivity';
+
+import type { PetState } from './petState';
+import './pet.css';
+
+/** What the avatar draws: a pet state, plus the two pose-only states. */
+export type PetPose = PetState | 'listening' | 'sleeping';
+
+const POSES: Record<PetPose, string> = {
+ idle: vibey,
+ sleeping: vibeySleep,
+ listening: vibeyFocus,
+ running: vibeyThinking,
+ ready: vibeyCelebrate,
+ needs_input: vibeyMessage,
+ blocked: vibeyError,
+};
+
+// Breathing stops after a while in a resting pose, so a pet left alone costs
+// 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 }> = ({
+ pose,
+ badge = 0,
+ activities = 0,
+}) => {
+ const { t } = useTranslation();
+ return (
+ <div className="pet-avatar" data-pose={pose}>
+ {/* Keyed by pose: a state change remounts the image, which plays the
+ one-shot change animation and restarts the breathing timer. */}
+ <PetPoseImage key={pose} pose={pose} alt={t(`pet.state.${pose}`)} />
+ {badge > 0 && (
+ <span
+ className="absolute right-1 top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1.5 text-[11px] font-semibold leading-none text-destructive-foreground"
+ aria-label={t('pet.unreadBadge', { count: badge })}
+ >
+ {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>
+ );
+};
+
+const PetPoseImage: React.FC<{ pose: PetPose; alt: string }> = ({ pose, alt }) => {
+ const pageActive = usePageActive();
+ const resting = pose === 'idle' || pose === 'sleeping';
+ const [settled, setSettled] = useState(false);
+
+ useEffect(() => {
+ if (!resting) return undefined;
+ const timer = window.setTimeout(() => setSettled(true), BREATHING_SETTLE_MS);
+ return () => window.clearTimeout(timer);
+ }, [resting]);
+
+ return (
+ <img
+ className="pet-avatar__pose"
+ src={POSES[pose]}
+ alt={alt}
+ data-breathing={pageActive && !settled ? 'true' : 'false'}
+ draggable={false}
+ />
+ );
+};
diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsx
new file mode 100644
index 000000000..30adb5bc2
--- /dev/null
+++ b/ui/src/pet/PetPage.test.tsx
@@ -0,0 +1,1247 @@
+/* @vitest-environment jsdom */
+
+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { WorkbenchEventHandlers, WorkbenchMessage, WorkbenchSession, WorkbenchSessionReadResult } from '@/context/ApiContext';
+
+import { ApiError } from '@/context/ApiContext';
+
+import { PET_BOUND_EVENT, PET_SUMMON_EVENT } from './petBridge';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const handlers = new Set<WorkbenchEventHandlers>();
+const emit = (pick: (h: WorkbenchEventHandlers) => void) => act(() => handlers.forEach(pick));
+
+type Deferred<T> = { promise: Promise<T>; resolve: (value: T) => void; reject: (error: unknown) => void };
+const deferred = <T,>(): Deferred<T> => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+};
+
+const session = (id: string, overrides: Partial<WorkbenchSession> = {}): WorkbenchSession => ({
+ id,
+ scope_id: 'scope',
+ project_id: 'project',
+ title: `Session ${id}`,
+ agent_id: null,
+ agent_name: null,
+ agent_backend: 'claude',
+ agent_variant: null,
+ model: null,
+ reasoning_effort: null,
+ status: 'active',
+ visibility: 'foreground',
+ pinned: false,
+ agent_status: 'idle',
+ workdir: null,
+ native_session_id: null,
+ created_at: '2026-10-04T00:00:00Z',
+ updated_at: '2026-10-04T00:00:00Z',
+ last_active_at: null,
+ metadata: {},
+ ...overrides,
+});
+
+const message = (id: string, sessionId: string, overrides: Partial<WorkbenchMessage> = {}): WorkbenchMessage => ({
+ id,
+ scope_id: 'scope',
+ session_id: sessionId,
+ platform: 'avibe',
+ author: 'agent',
+ type: 'result',
+ source: 'agent',
+ author_id: null,
+ author_name: null,
+ native_message_id: null,
+ parent_native_message_id: null,
+ text: `reply ${id}`,
+ content: {},
+ metadata: {},
+ created_at: '2026-10-04T00:00:00Z',
+ updated_at: '2026-10-04T00:00:00Z',
+ delivered_at: null,
+ read_at: '2026-10-04T00:00:01Z',
+ ...overrides,
+});
+
+const idleTurn = {
+ in_flight: false,
+ foreground: 'idle' as const,
+ native_turn_started: false,
+ pending_input_count: 0,
+ background_activities: [],
+ pending_activity_output_count: 0,
+ connection: 'connected' as const,
+};
+
+let setupDone = true;
+let sessionReads: Record<string, () => Promise<WorkbenchSessionReadResult>> = {};
+let tails: Record<string, WorkbenchMessage[]> = {};
+let switcherSessions: WorkbenchSession[] = [];
+let unreadBySession: Record<string, number> = {};
+// Like the provider, a mark-read response installs a new unread map, so every
+// consumer re-renders with a new inbox object.
+let inboxVersion = 0;
+const inboxListeners = new Set<() => void>();
+const markRead = vi.fn(async (): Promise<boolean> => {
+ inboxVersion += 1;
+ inboxListeners.forEach((listener) => listener());
+ return true;
+});
+
+const api = {
+ getConfig: vi.fn(async () => (setupDone
+ ? { mode: 'self_host', setup_state: { needs_setup: false } }
+ : { mode: 'self_host', setup_state: { needs_setup: true } })),
+ getSessionResult: vi.fn((id: string) => (sessionReads[id]
+ ? 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: [] })),
+ sendSessionMessage: vi.fn(async () => message('sent', 'S', { author: 'user', type: 'user' })),
+ connectWorkbenchEvents: (h: WorkbenchEventHandlers) => {
+ handlers.add(h);
+ return () => handlers.delete(h);
+ },
+};
+
+vi.mock('@/context/ApiContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/context/ApiContext')>()),
+ useApi: () => api,
+}));
+let canChat = true;
+vi.mock('@/context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({ capabilities: { can_chat: canChat } }),
+}));
+vi.mock('@/context/WorkbenchInboxContext', async () => {
+ const { useSyncExternalStore } = await import('react');
+ return {
+ useWorkbenchInbox: () => {
+ useSyncExternalStore((listener) => {
+ inboxListeners.add(listener);
+ return () => inboxListeners.delete(listener);
+ }, () => inboxVersion);
+ return { unreadBySession: { ...unreadBySession }, markRead };
+ },
+ };
+});
+
+// An in-memory Storage, so the test does not depend on the runtime's own
+// localStorage (Node 25+ shadows jsdom's without a backing file).
+const memoryStorage = (): Storage => {
+ const items = new Map<string, string>();
+ return {
+ get length() { return items.size; },
+ clear: () => items.clear(),
+ getItem: (key) => items.get(key) ?? null,
+ key: (index) => Array.from(items.keys())[index] ?? null,
+ removeItem: (key) => { items.delete(key); },
+ setItem: (key, value) => { items.set(key, String(value)); },
+ };
+};
+Object.defineProperty(window, 'localStorage', { value: memoryStorage(), configurable: true });
+// The window has focus unless a test says otherwise (jsdom reports none).
+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 };
+};
+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') => act(() => {
+ window.dispatchEvent(new CustomEvent(PET_SUMMON_EVENT, { detail: { intent } }));
+});
+const pose = () => document.querySelector('.pet-avatar')?.getAttribute('data-pose');
+
+// The shell store lives for one document, so each test loads a fresh module
+// graph instead of resetting it.
+let PetPage: typeof import('./PetPage').PetPage;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ PetPage } = await import('./PetPage'));
+ setupDone = true;
+ windowFocused = true;
+ canChat = true;
+ sessionReads = {};
+ tails = {};
+ switcherSessions = [];
+ unreadBySession = {};
+ markRead.mockClear();
+ inboxVersion = 0;
+ api.getSessionResult.mockClear();
+ api.listSessions.mockClear();
+ window.localStorage.clear();
+});
+
+afterEach(() => {
+ cleanup();
+ handlers.clear();
+ api.sendSessionMessage.mockClear();
+ delete (window as { __AVIBE_DESKTOP_SHELL__?: unknown }).__AVIBE_DESKTOP_SHELL__;
+ delete (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
+});
+
+describe('PetPage setup', () => {
+ it('stays on its own setup-pending state instead of redirecting to setup', async () => {
+ setupDone = false;
+ render(<PetPage />);
+ expect(await screen.findByText('pet.setupPending')).toBeTruthy();
+ expect(window.location.pathname).not.toBe('/setup');
+ });
+
+ it('leaves setup-pending on the next summon once setup finished elsewhere', async () => {
+ setupDone = false;
+ render(<PetPage />);
+ await screen.findByText('pet.setupPending');
+ setupDone = true;
+ summon('show');
+ await waitFor(() => expect(screen.queryByText('pet.setupPending')).toBeNull());
+ expect(api.getConfig).toHaveBeenLastCalledWith({ cache: false });
+ });
+
+ it('also re-reads setup when the window regains focus', async () => {
+ setupDone = false;
+ render(<PetPage />);
+ await screen.findByText('pet.setupPending');
+ setupDone = true;
+ act(() => {
+ window.dispatchEvent(new Event('focus'));
+ });
+ await waitFor(() => expect(screen.queryByText('pet.setupPending')).toBeNull());
+ });
+});
+
+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');
+ render(<PetPage />);
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('A'));
+ await bound('B');
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('B'));
+ await act(async () => lateA.resolve({ status: 404, session: null }));
+ summon('show');
+ expect(await screen.findByText('Session B')).toBeTruthy();
+ expect(devBinding().binding).toBe('B');
+ });
+
+ 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' }),
+ });
+ switcherSessions = [session('fresh', { title: 'Brand new' })];
+ devBind('ses-workspace-notices');
+ render(<PetPage />);
+ await waitFor(() => expect(devBinding().binding).toBeNull());
+ summon('listen');
+ expect(await screen.findByText('Brand new')).toBeTruthy();
+ });
+
+ 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' }),
+ ];
+ render(<PetPage />);
+ 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 state', () => {
+ it('shows Needs input for an open quick-reply group and clears it on message.updated', async () => {
+ const asking = message('q', 'S', { content: { quick_replies: ['Yes', 'No'] } });
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), asking];
+ devBind('S');
+ render(<PetPage />);
+ await waitFor(() => expect(pose()).toBe('needs_input'));
+ await emit((h) => h.onMessageUpdated?.({ ...asking, content: { ...asking.content, quick_reply_chosen: 'Yes' } }));
+ await waitFor(() => expect(pose()).toBe('idle'));
+ });
+
+ 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');
+ 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');
+ render(<PetPage />);
+ await waitFor(() => expect(api.getTurnState).toHaveBeenCalled());
+ const before = api.getTurnState.mock.calls.length;
+ await emit((h) => h.onRunsUpdated?.({ run_id: 'r', status: 'running', session_id: 'executor' } as never));
+ await waitFor(() => expect(api.getTurnState.mock.calls.length).toBeGreaterThan(before));
+ });
+
+ it('marks read through the last rendered unread result only when all unread rows are loaded', async () => {
+ tails.S = [
+ message('r1', 'S'),
+ message('u', 'S', { author: 'user', type: 'user' }),
+ message('r2', 'S', { read_at: null }),
+ message('r3', 'S', { read_at: null }),
+ ];
+ unreadBySession = { S: 2 };
+ devBind('S');
+ render(<PetPage />);
+ await waitFor(() => expect(pose()).toBe('ready'));
+ summon('show');
+ await screen.findByText('reply r3');
+ await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r3'));
+ });
+
+ it('does not mark read when unread rows may reach past the loaded tail', async () => {
+ tails.S = [message('r2', 'S', { read_at: null })];
+ api.listSessionMessages.mockImplementationOnce(async (id: string) => ({
+ messages: tails[id] ?? [], next_after_id: null, next_before_id: 'older',
+ }));
+ unreadBySession = { S: 5 };
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
+ expect(markRead).not.toHaveBeenCalled();
+ });
+});
+
+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');
+ render(<PetPage />);
+ summon('show');
+ await screen.findByText('reply r1');
+ await waitFor(() => expect(markRead).toHaveBeenCalled());
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
+ expect(markRead).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not put a reply for A into B when the binding changes mid-send', async () => {
+ const pending = deferred<WorkbenchMessage>();
+ api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
+ tails.B = [message('b1', 'B', { text: 'B only' })];
+ devBind('A');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.type(input, 'hello{Enter}');
+ await bound('B');
+ await screen.findByText('B only');
+ 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();
+ expect(screen.queryByText('pet.state.running')).toBeNull();
+ expect(pose()).toBe('idle');
+ });
+
+ it('acts on the binding pet_ready returns together with a pending summon', 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 />);
+ // 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.
+ 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 />);
+ summon('show');
+ 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.findByText('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 })];
+ unreadBySession = { S: 1 };
+ markRead.mockImplementationOnce(async (): Promise<boolean> => {
+ throw new Error('offline');
+ });
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ });
+ summon('show');
+ await waitFor(() => expect(markRead).toHaveBeenCalledTimes(2));
+ expect(markRead).toHaveBeenLastCalledWith('S', 'r1');
+ });
+
+ it('keeps a draft typed after submitting when the send completes', async () => {
+ const pending = deferred<WorkbenchMessage>();
+ api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
+ devBind('S');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
+ await userEvent.type(input, 'first{Enter}');
+ await userEvent.type(input, ' and more');
+ await act(async () => pending.resolve(message('sent', 'S', { author: 'user', type: 'user' })));
+ expect(input.value).toBe('first and more');
+ });
+});
+
+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');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.type(input, 'once{Enter}{Enter}{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ await act(async () => pending.resolve(message('sent', 'S', { author: 'user', type: 'user' })));
+ });
+
+ it('marks a reply read when a hidden, still-open pet is shown again', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null })];
+ unreadBySession = { S: 1 };
+ let visibility: DocumentVisibilityState = 'hidden';
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
+ try {
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await screen.findByText('reply r1');
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+ expect(markRead).not.toHaveBeenCalled();
+ visibility = 'visible';
+ act(() => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r1'));
+ } finally {
+ delete (document as { visibilityState?: unknown }).visibilityState;
+ }
+ });
+
+ 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 }));
+ summon('show');
+ expect(await screen.findByText('Session B')).toBeTruthy();
+ });
+});
+
+describe('PetPage independent sweep', () => {
+ it('retries mark-read the server did not apply, without a network error', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null })];
+ unreadBySession = { S: 1 };
+ markRead.mockImplementationOnce(async () => false);
+ let visibility: DocumentVisibilityState = 'visible';
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
+ try {
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
+ // The panel stays open; the window is hidden and shown again.
+ visibility = 'hidden';
+ act(() => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ visibility = 'visible';
+ act(() => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await waitFor(() => expect(markRead).toHaveBeenCalledTimes(2));
+ } finally {
+ delete (document as { visibilityState?: unknown }).visibilityState;
+ }
+ });
+
+ it('lands a bound summon on the session even if the switcher was left open', async () => {
+ switcherSessions = [session('S')];
+ render(<PetPage />);
+ summon('show');
+ expect(await screen.findByText('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');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
+ await userEvent.type(input, 'deploy{Enter}');
+ await bound('B');
+ await act(async () => pending.resolve(message('a-sent', 'A', { author: 'user', type: 'user' })));
+ expect((screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement).value).toBe('');
+ });
+
+ 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');
+ render(<PetPage />);
+ await waitFor(() => expect(api.listSessionMessages).toHaveBeenCalled());
+ // 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) {
+ h.onMessageNew?.(message(`n${index}`, 'S', { author: 'user', type: 'user', text: `note ${index}` }));
+ }
+ h.onMessageNew?.(message('r2', 'S', { read_at: null, text: 'reply r2' }));
+ });
+ summon('show');
+ expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
+ expect(markRead).not.toHaveBeenCalled();
+ });
+});
+
+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 />);
+ summon('show');
+ expect(await screen.findByText('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)));
+ summon('show');
+ // The invalid session is never offered as usable: the switcher shows.
+ expect(await screen.findByText('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');
+ render(<PetPage />);
+ summon('listen');
+ await screen.findByLabelText('pet.panel');
+ expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ expect(api.sendSessionMessage).not.toHaveBeenCalled();
+ await act(async () => validation.resolve({
+ status: 200,
+ session: session('S'),
+ capabilities: { can_chat: true },
+ }));
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.type(input, 'hello{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('starts an empty draft when the binding changes', async () => {
+ devBind('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 screen.findByText('Session B');
+ 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', () => {
+ it('keeps a live summon that lands before the pet_ready answer', 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 });
+ tails.S = [];
+ render(<PetPage />);
+ await screen.findByLabelText('pet.toggle');
+ // The live summon is newer than the pending one pet_ready still carries.
+ await shellBound('S', 1);
+ summon('show');
+ await screen.findByText('Session S');
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ });
+ await act(async () => ready.resolve({ binding: 'S', revision: 1, summon_pending: { intent: 'listen' } }));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+ // The stale pending summon did not reopen the panel.
+ expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ });
+});
+
+describe('PetPage review fixes, round 8', () => {
+ it('does not replay a reply it already marked read when a newer one arrives', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null, text: 'first reply' })];
+ unreadBySession = { S: 1 };
+ markRead.mockImplementationOnce(async () => {
+ // The server applied the read: the tail now reports r1 read.
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { text: 'first reply' })];
+ return true;
+ });
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r1'));
+ await waitFor(() => expect(api.listSessionMessages.mock.calls.length).toBeGreaterThan(1));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+ const r2 = message('r2', 'S', { read_at: null, text: 'second reply' });
+ tails.S = [...tails.S, r2];
+ await emit((h) => h.onMessageNew?.(r2));
+ await screen.findByText('second reply');
+ expect(screen.queryByText('first reply')).toBeNull();
+ });
+
+ it('keeps one message in flight across text and quick replies', async () => {
+ 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');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.click(await screen.findByText('Yes'));
+ await userEvent.type(input, 'also this{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ await act(async () => pending.resolve(message('sent', 'S', { author: 'user', type: 'user' })));
+ });
+
+ 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');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
+ await userEvent.type(input, 'continue{Enter}');
+ await bound('B');
+ await screen.findByText('Session B');
+ 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' })));
+ expect((screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement).value).toBe('continue');
+ });
+});
+
+describe('PetPage review fixes, round 9', () => {
+ it('shows a background-work count on the collapsed pet without changing its pose', async () => {
+ api.getTurnState.mockImplementation(async () => ({
+ ...idleTurn,
+ background_activities: [
+ { id: 'r1', backend: 'codex', runtime_key: 'k', session_id: 'x', kind: 'agent_run', status: 'running', description: null, started_at: '', updated_at: '' },
+ { id: 'w1', backend: 'codex', runtime_key: 'k', session_id: 'x', kind: 'watch', status: 'running', description: null, started_at: '', updated_at: '' },
+ ],
+ }) as never);
+ try {
+ devBind('S');
+ render(<PetPage />);
+ expect(await screen.findByLabelText('chat.activities.running')).toBeTruthy();
+ expect(screen.getByLabelText('chat.activities.running').textContent).toBe('2');
+ expect(pose()).toBe('idle');
+ } finally {
+ api.getTurnState.mockImplementation(async () => idleTurn);
+ }
+ });
+});
+
+describe('PetPage review fixes, round 10', () => {
+ it('does not mark a reply read while another app has focus', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null, text: 'unseen' })];
+ unreadBySession = { S: 1 };
+ windowFocused = false;
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await screen.findByText('unseen');
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+ expect(markRead).not.toHaveBeenCalled();
+ windowFocused = true;
+ act(() => {
+ window.dispatchEvent(new Event('focus'));
+ });
+ 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 />);
+ summon('show');
+ await screen.findByText('Session A');
+ await userEvent.click(screen.getByLabelText('pet.switchSession'));
+ await userEvent.click(await screen.findByText('Session B'));
+ 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', () => {
+ it('keeps the panel matching the native frame when a resize fails', async () => {
+ const invoke = vi.fn((command: string) => {
+ if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
+ if (command === 'pet_set_expanded') return Promise.reject(new Error('no monitor'));
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ render(<PetPage />);
+ await userEvent.click(await screen.findByLabelText('pet.toggle'));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
+ await waitFor(() => expect(screen.queryByLabelText('pet.panel')).toBeNull());
+ expect(screen.getByLabelText('pet.toggle').getAttribute('aria-expanded')).toBe('false');
+ });
+});
+
+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');
+ render(<PetPage />);
+ summon('listen');
+ await screen.findByLabelText('pet.panel');
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+ expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ expect(screen.queryByText('Yes')).toBeNull();
+ });
+
+ it('offers no composer or quick replies when the bound session is project-viewer', async () => {
+ canChat = true;
+ sessionReads.S = async () => ({
+ status: 200,
+ session: session('S'),
+ capabilities: { can_chat: false },
+ });
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q', 'S', { content: { quick_replies: ['Yes'] } })];
+ devBind('S');
+ render(<PetPage />);
+ summon('listen');
+ await screen.findByLabelText('pet.panel');
+ await screen.findByText('Session S');
+ expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ expect(screen.queryByText('Yes')).toBeNull();
+ await userEvent.keyboard('should not send{Enter}');
+ expect(api.sendSessionMessage).not.toHaveBeenCalled();
+ });
+
+ it('ends the post-send Running grace on an authoritative turn.end', async () => {
+ devBind('S');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('S'));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));
+ await userEvent.type(input, 'quick{Enter}');
+ await waitFor(() => expect(pose()).toBe('running'));
+ await emit((h) => h.onTurnEnd?.({ session_id: 'S' }));
+ await waitFor(() => expect(pose()).toBe('idle'));
+ });
+
+ 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');
+ render(<PetPage />);
+ summon('show');
+ 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());
+ });
+});
+
+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 />);
+ summon('show');
+ await screen.findByText('Session A');
+ await userEvent.click(screen.getByLabelText('pet.switchSession'));
+ await userEvent.click(await screen.findByText('Session B'));
+ 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.findByText('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 />);
+ summon('show');
+ 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');
+ render(<PetPage />);
+ summon('show');
+ await screen.findByLabelText('pet.panel');
+ await emit((h) => h.onMessageNew?.(message('live', 'S', { read_at: null })));
+ await screen.findByText('reply live');
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+ expect(markRead).not.toHaveBeenCalled();
+ // The snapshot shows older unread rows past the tail: still not marked.
+ await act(async () => tail.resolve({
+ messages: [message('older', 'S', { read_at: null }), message('live', 'S', { read_at: null })],
+ next_after_id: null,
+ next_before_id: 'earlier',
+ }));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+ expect(markRead).not.toHaveBeenCalled();
+ });
+
+ 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');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('S'));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));
+ await userEvent.type(input, 'deploy{Enter}');
+ expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
+ expect(input.value).toBe('deploy');
+ expect(screen.queryByText('Yes')).toBeNull();
+ await userEvent.type(input, '{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ // Looking at the conversation in Avibe lifts it.
+ const notice = screen.getByRole('status');
+ await userEvent.click(within(notice).getByRole('button', { name: 'pet.openInAvibe' }));
+ expect(screen.queryByText('newSession.sendUncertain')).toBeNull();
+ await userEvent.type(input, '{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps input open when the server refused the send', async () => {
+ api.sendSessionMessage.mockRejectedValueOnce(new ApiError('conflict', 409, null));
+ devBind('S');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('S'));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));
+ await userEvent.type(input, 'again{Enter}');
+ await waitFor(() => expect(api.sendSessionMessage).toHaveBeenCalledTimes(1));
+ expect(screen.queryByText('newSession.sendUncertain')).toBeNull();
+ await userEvent.type(input, '{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(2);
+ });
+
+ it('leaves setup-pending when one of two overlapping checks sees setup finished', async () => {
+ setupDone = false;
+ render(<PetPage />);
+ await screen.findByText('pet.setupPending');
+ const seesDone = deferred<unknown>();
+ api.getConfig
+ .mockImplementationOnce(() => seesDone.promise as never)
+ .mockImplementationOnce(() => Promise.reject(new Error('network')));
+ // One wake: focus, then the summon, each re-reading setup.
+ act(() => {
+ window.dispatchEvent(new Event('focus'));
+ });
+ summon('show');
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));
+ await act(async () => seesDone.resolve({ mode: 'self_host', setup_state: { needs_setup: false } }));
+ await waitFor(() => expect(screen.queryByText('pet.setupPending')).toBeNull());
+ });
+});
+
+describe('PetPage live convergence', () => {
+ const settle = () => act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+
+ it('keeps the send lock when opening the conversation fails', async () => {
+ api.sendSessionMessage.mockRejectedValueOnce(new ApiError('dispatch pending', 504, null));
+ const invoke = vi.fn((command: string) => {
+ if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
+ if (command === 'pet_set_expanded') return Promise.resolve({ panel_side: 'left', panel_edge: 'bottom' });
+ if (command === 'pet_open') return Promise.reject(new Error('main window gone'));
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
+ await settle();
+ await userEvent.type(input, 'to S{Enter}');
+ expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
+ const notice = screen.getByRole('status');
+ await userEvent.click(within(notice).getByRole('button', { name: 'pet.openInAvibe' }));
+ await settle();
+ expect(screen.getByText('newSession.sendUncertain')).toBeTruthy();
+ await userEvent.type(input, '{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps each session closed after its own uncertain send', async () => {
+ api.sendSessionMessage
+ .mockRejectedValueOnce(new ApiError('dispatch pending', 504, null))
+ .mockRejectedValueOnce(new ApiError('dispatch pending', 504, null));
+ devBind('A');
+ render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
+ await settle();
+ await userEvent.type(input, 'to A{Enter}');
+ expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
+
+ await bound('B');
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('B'));
+ const inputB = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
+ await settle();
+ expect(screen.queryByText('newSession.sendUncertain')).toBeNull();
+ await userEvent.type(inputB, 'to B{Enter}');
+ expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
+
+ await bound('A');
+ await settle();
+ expect(screen.getByText('newSession.sendUncertain')).toBeTruthy();
+ await userEvent.type(screen.getByLabelText('pet.inputPlaceholder'), 'again{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps an already-open panel when a later expand request fails', async () => {
+ const first = deferred<unknown>();
+ const second = deferred<unknown>();
+ let expands = 0;
+ const invoke = vi.fn((command: string) => {
+ if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
+ if (command === 'pet_set_expanded') {
+ expands += 1;
+ return expands === 1 ? first.promise : second.promise;
+ }
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
+ render(<PetPage />);
+ 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');
+
+ summon('show');
+ 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();
+ expect(screen.getByLabelText('pet.panel')).toBeTruthy();
+ });
+
+ it('shows the panel and marks replies read only once the shell has grown the frame', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r', 'S', { read_at: null })];
+ unreadBySession = { S: 1 };
+ const grow = 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_set_expanded') return grow.promise;
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ render(<PetPage />);
+ summon('show');
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
+ await settle();
+ expect(screen.queryByLabelText('pet.panel')).toBeNull();
+ expect(markRead).not.toHaveBeenCalled();
+
+ await act(async () => grow.reject(new Error('resize failed')));
+ await settle();
+ expect(screen.queryByLabelText('pet.panel')).toBeNull();
+ expect(markRead).not.toHaveBeenCalled();
+ });
+
+ it('reads the session on a status event when no read has supplied it yet', async () => {
+ sessionReads.S = vi.fn()
+ .mockResolvedValueOnce({ status: 500, session: null })
+ .mockResolvedValue({ status: 200, session: session('S') });
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await screen.findByLabelText('pet.panel');
+ await settle();
+ expect(screen.queryByText('Session S')).toBeNull();
+
+ await emit((h) => h.onSessionStatus?.({ session_id: 'S', agent_status: 'idle' }));
+ expect(await screen.findByText('Session S')).toBeTruthy();
+ });
+
+ it('reads the tail on a live row when no tail read has landed yet', async () => {
+ api.listSessionMessages.mockRejectedValueOnce(new Error('network'));
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await screen.findByLabelText('pet.panel');
+ await settle();
+ const reads = api.listSessionMessages.mock.calls.filter(([id]) => id === 'S').length;
+
+ await emit((h) => h.onMessageNew?.(message('live', 'S')));
+ await settle();
+ expect(api.listSessionMessages.mock.calls.filter(([id]) => id === 'S')).toHaveLength(reads + 1);
+ });
+
+ it('re-reads the tail when the session is marked read in another window', async () => {
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ await screen.findByLabelText('pet.panel');
+ await settle();
+ const reads = api.listSessionMessages.mock.calls.filter(([id]) => id === 'S').length;
+
+ await emit((h) => h.onInboxUnreadChanged?.({ session_id: 'S', delta: -1, unread_counts: {} }));
+ await settle();
+ expect(api.listSessionMessages.mock.calls.filter(([id]) => id === 'S')).toHaveLength(reads + 1);
+ });
+});
+
+describe('PetPage review fixes, round 14', () => {
+ it('does not mark read when the inbox count is ahead of the loaded unread results', async () => {
+ tails.S = [message('r1', 'S')];
+ unreadBySession = { S: 2 };
+ api.listSessionMessages.mockImplementationOnce(async (id: string) => ({
+ messages: tails[id] ?? [], next_after_id: null, next_before_id: 'older',
+ }));
+ devBind('S');
+ render(<PetPage />);
+ summon('show');
+ expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
+ expect(markRead).not.toHaveBeenCalled();
+ });
+
+ it('keeps an in-flight send locked across a page remount', async () => {
+ const pending = deferred<WorkbenchMessage>();
+ api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
+ devBind('S');
+ const first = render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.type(input, 'hello{Enter}');
+ await waitFor(() => expect(api.sendSessionMessage).toHaveBeenCalledTimes(1));
+ first.unmount();
+ render(<PetPage />);
+ summon('listen');
+ const again = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.type(again, 'again{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ await act(async () => pending.resolve(message('sent', 'S', { author: 'user', type: 'user' })));
+ });
+
+ it('keeps an uncertain send locked across a page recheck', async () => {
+ api.sendSessionMessage.mockRejectedValueOnce(new ApiError('dispatch pending', 504, null));
+ devBind('S');
+ const first = render(<PetPage />);
+ summon('listen');
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.type(input, 'hello{Enter}');
+ expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
+ first.unmount();
+ render(<PetPage />);
+ summon('listen');
+ expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
+ const again = await screen.findByLabelText('pet.inputPlaceholder');
+ await userEvent.type(again, 'again{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('sends overlapping native resizes in the order they were asked', async () => {
+ const first = deferred<unknown>();
+ const second = deferred<unknown>();
+ const order: boolean[] = [];
+ const invoke = vi.fn((command: string, args?: { expanded?: boolean }) => {
+ if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
+ if (command === 'pet_set_expanded') {
+ order.push(Boolean(args?.expanded));
+ return order.length === 1 ? first.promise : second.promise;
+ }
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
+ render(<PetPage />);
+ 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
+ // (the panel is hidden until the frame grows), so the avatar toggle is
+ // the overlapping command. The native collapse waits its turn.
+ await userEvent.click(screen.getByLabelText('pet.toggle'));
+ expect(order).toEqual([true]);
+ await act(async () => first.resolve({ panel_side: 'left', panel_edge: 'bottom' }));
+ await waitFor(() => expect(order).toEqual([true, false]));
+ await act(async () => second.resolve({ panel_side: 'left', panel_edge: 'bottom' }));
+ });
+
+ it('focuses the input only after the native panel has grown and the composer is on screen', async () => {
+ const grow = 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_set_expanded') return grow.promise;
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
+ render(<PetPage />);
+ summon('listen');
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
+ expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+
+ await act(async () => grow.resolve({ panel_side: 'left', panel_edge: 'bottom' }));
+ const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await waitFor(() => expect(document.activeElement).toBe(input));
+ });
+});
+
diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsx
new file mode 100644
index 000000000..c45a0031e
--- /dev/null
+++ b/ui/src/pet/PetPage.tsx
@@ -0,0 +1,604 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import { Activity, ArrowUp, ExternalLink, KeyRound, Shuffle } from 'lucide-react';
+
+import { ApiError, useApi, type SessionActivityState, 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 { StatusPill } from '@/components/visual';
+import {
+ activityKindI18nKey,
+ resolveActivityLabel,
+ sortBackgroundActivities,
+} from '@/lib/backgroundActivity';
+import { usePageActive } from '@/lib/pageActivity';
+import { usePendingVaultRequests } from '@/lib/usePendingVaultRequests';
+
+import { PetAvatar, type PetPose } from './PetAvatar';
+import {
+ SETTINGS_LINK,
+ petBridge,
+ sessionLink,
+ vaultRequestLink,
+ type PetIntent,
+} from './petBridge';
+import { petComposer, usePetComposer } from './petComposer';
+import { petPanel, usePetPanel } from './petPanel';
+import { petShell, useOnSummon, usePetBinding } from './petShell';
+import { derivePetState, latestExchange, openQuickReplies } from './petState';
+import { usePetSession } from './usePetSession';
+import { usePetSetup } from './usePetSetup';
+import { useSessionSwitcher } from './useSessionSwitcher';
+
+// An idle pet falls asleep after this long without a state change.
+const SLEEP_AFTER_MS = 5 * 60 * 1000;
+// A pointer that moves this far after pressing the pet drags the window.
+const DRAG_THRESHOLD_PX = 4;
+// Answers that prove the server refused a message, as on the new-session
+// sheet; anything else (a lost response, a 5xx, `dispatch_pending`) may have
+// started a turn, so the send is uncertain.
+const REFUSED_SEND_STATUSES = new Set([400, 403, 404, 409, 422]);
+const sendRefused = (error: unknown) => error instanceof ApiError && REFUSED_SEND_STATUSES.has(error.status);
+
+/**
+ * `/pet`: the desktop pet window's page. Outside the Workbench shell and the
+ * setup redirect; see docs/plans/2026-10-01-desktop-pet.md.
+ */
+export const PetPage: React.FC = () => {
+ // Listen to the shell from the first frame, before setup is known.
+ usePetBinding();
+ const { setup, recheck } = usePetSetup();
+ if (setup === 'checking') return null;
+ if (setup === 'pending') return <PetSetupPending recheck={recheck} />;
+ return <PetSurface />;
+};
+
+const PetSetupPending: React.FC<{ recheck: () => void }> = ({ recheck }) => {
+ const { t } = useTranslation();
+ const { expanded, layout, setPanel } = usePetPanel();
+ // The collapsed native frame is avatar-sized; grow it as soon as this card
+ // is the page, and again on a summon (which also re-reads setup so the pet
+ // surface can take over once setup is complete).
+ useEffect(() => { void setPanel(true); }, [setPanel]);
+ // Stable: `useOnSummon` replays a still-pending summon on each new
+ // listener, and this view must not take it — PetSurface acts on it once
+ // setup is complete.
+ const onSetupSummon = useCallback(() => {
+ recheck();
+ void setPanel(true);
+ }, [recheck, setPanel]);
+ useOnSummon(onSetupSummon);
+ const card = expanded ? (
+ <div className="max-w-[220px] rounded-xl border border-border bg-card p-3 text-[12px] text-foreground shadow-lg">
+ <p className="mb-2">{t('pet.setupPending')}</p>
+ <Button size="sm" onClick={() => void petBridge.open(SETTINGS_LINK)}>
+ {t('pet.openAvibe')}
+ </Button>
+ </div>
+ ) : null;
+ return (
+ <div
+ className={clsx(
+ 'flex h-full w-full gap-2 p-2',
+ layout.panel_side === 'left' ? 'flex-row' : 'flex-row-reverse',
+ layout.panel_edge === 'bottom' ? 'items-end' : 'items-start',
+ )}
+ >
+ {card}
+ <PetAvatar pose="idle" />
+ </div>
+ );
+};
+
+const PetSurface: React.FC = () => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const inbox = useWorkbenchInbox({ feed: false });
+
+ const binding = usePetBinding() ?? null;
+ const { capabilities } = useInstanceAuthorization();
+ const { expanded, layout, setPanel } = usePetPanel();
+ const [switcherOpen, setSwitcherOpen] = useState(false);
+ // Draft, in-flight send and per-session uncertainty live for the document,
+ // so an AuthGuard recheck cannot drop a lock or the text that belongs to it.
+ const { draft, uncertain, sending, listenPending, setDraft, setUncertain } = usePetComposer(binding);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+
+ const data = usePetSession(binding, petShell.unbind);
+ // Sending is a chat capability, as in the chat page: instance can_chat and
+ // the bound session's project grant. Unknown or failed reads deny.
+ const canChat = capabilities.can_chat && data.canChat === true;
+ const { requests: vaultRequests } = usePendingVaultRequests(binding ?? '');
+ const unreadCount = binding ? inbox.unreadBySession[binding] ?? 0 : 0;
+
+ const state = derivePetState({
+ session: data.session,
+ messages: data.messages,
+ turn: data.running ? { foreground: 'running', in_flight: true } : data.turn,
+ pendingVaultRequests: vaultRequests.length,
+ unreadCount,
+ });
+
+ const summon = useCallback((intent: PetIntent, bound: string | null) => {
+ void setPanel(true);
+ // An unbound pet shows the switcher by itself (`switcherOpen || !binding`);
+ // a bound summon always lands on the session, never on a list left open.
+ if (!bound) return;
+ setSwitcherOpen(false);
+ // Voice ships in a later PR; until then a `listen` summon focuses the text
+ // input once the panel and composer have actually mounted. `setPanel` waits
+ // for the native frame, and a cold load still waits on the session grant.
+ if (intent === 'listen') petComposer.requestListen();
+ }, [setPanel]);
+
+ // Act on a waiting summon, including one that arrived before this surface
+ // mounted (while setup was pending or the page was loading).
+ const onSummon = useCallback(() => {
+ const intent = petShell.takeSummon();
+ // Read the store, not the render: `pet_ready` may have set the binding in
+ // the same tick that delivered this summon.
+ if (intent) summon(intent, petShell.currentBinding() ?? null);
+ }, [summon]);
+ useOnSummon(onSummon);
+
+ // A listen summon waits until the composer is actually on screen: expansion
+ // is async, and a cold load still waits on the session grant. Do not consume
+ // the pending listen until the textarea is mounted — AuthGuard can remount
+ // the page, and the store must still hold the request until focus lands.
+ useEffect(() => {
+ if (!listenPending || !expanded || !canChat || !binding || switcherOpen) return;
+ const input = inputRef.current;
+ if (!input) return;
+ input.focus();
+ petComposer.takeListen();
+ }, [listenPending, expanded, canChat, binding, switcherOpen]);
+
+ // Esc collapses.
+ useEffect(() => {
+ if (!expanded) return undefined;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') void setPanel(false);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [expanded, setPanel]);
+
+ // Blur collapses, unless there is unsent text.
+ useEffect(() => {
+ if (!expanded) return undefined;
+ const onBlur = () => {
+ if (!draft.trim()) void setPanel(false);
+ };
+ window.addEventListener('blur', onBlur);
+ return () => window.removeEventListener('blur', onBlur);
+ }, [expanded, draft, setPanel]);
+
+ // Idle → asleep after a while without a state change.
+ const [asleep, setAsleep] = useState(false);
+ useEffect(() => {
+ setAsleep(false);
+ if (state !== 'idle') return undefined;
+ const timer = window.setTimeout(() => setAsleep(true), SLEEP_AFTER_MS);
+ return () => window.clearTimeout(timer);
+ }, [state, binding]);
+ const pose: PetPose = state === 'idle' && asleep ? 'sleeping' : state;
+
+ const exchange = useMemo(
+ () => latestExchange(data.messages, data.hasOlder, unreadCount),
+ [data.messages, data.hasOlder, unreadCount],
+ );
+ const quickReplies = openQuickReplies(data.messages);
+
+ const { markRead } = inbox;
+
+ // One message in flight at a time, from any entry point (text or a quick
+ // reply): a second turn must not race the first. The document store, so two
+ // sends in one tick are also one, and a remount cannot start a second turn.
+ const send = useCallback(async (text: string, metadata?: Record<string, unknown>) => {
+ // Only a session this page has validated as writable accepts input; a
+ // restored or just-picked binding waits for its first successful read.
+ if (!canChat || !binding || data.session?.id !== binding || !text.trim()) return false;
+ if (petComposer.isSending() || petComposer.isUncertain(binding)) return false;
+ petComposer.setSending(true);
+ try {
+ const row = await api.sendSessionMessage(binding, { text, ...(metadata ? { metadata } : {}) });
+ // The binding may have changed while the POST was pending: the reply
+ // belongs to the session it was sent to, never to the current one.
+ if (petShell.currentBinding() === binding) {
+ data.noteSent(row && typeof row === 'object' && 'id' in row ? row : null);
+ }
+ return true;
+ } catch (error) {
+ if (!sendRefused(error)) setUncertain(binding, true);
+ return false;
+ } finally {
+ petComposer.setSending(false);
+ }
+ }, [api, binding, canChat, data, setUncertain]);
+
+ // A completed send clears the draft only if it is still the same text in
+ // the same session it was submitted from. A binding change already empties
+ // the draft, so sent text never lingers for another session, and text typed
+ // there afterwards is never cleared by the old send.
+ const submit = async () => {
+ const submitted = draft;
+ const submittedFor = binding;
+ const text = submitted.trim();
+ if (!text) return;
+ if (!(await send(text))) return;
+ if (petShell.currentBinding() !== submittedFor) return;
+ petComposer.clearDraftIf(submitted);
+ };
+
+ // QuickReplies locks the group locally; the Runtime's message.updated for the
+ // answered row then clears Needs input in every window.
+ const choose = (message: WorkbenchMessage, choice: string) => send(choice, { quick_reply_for: message.id });
+
+ const pressRef = useRef<{ x: number; y: number; dragged: boolean } | null>(null);
+ const avatar = (
+ <button
+ type="button"
+ className="shrink-0 cursor-pointer rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={t('pet.toggle')}
+ aria-expanded={expanded}
+ onPointerDown={(event) => {
+ pressRef.current = { x: event.clientX, y: event.clientY, dragged: false };
+ }}
+ onPointerMove={(event) => {
+ const press = pressRef.current;
+ if (!press || press.dragged || event.buttons !== 1) return;
+ if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < DRAG_THRESHOLD_PX) return;
+ press.dragged = true;
+ petBridge.startDragging();
+ }}
+ onClick={() => {
+ const dragged = pressRef.current?.dragged;
+ pressRef.current = null;
+ if (dragged) return;
+ void setPanel(!petPanel.want());
+ }}
+ >
+ <PetAvatar
+ pose={pose}
+ badge={state === 'ready' ? unreadCount : 0}
+ activities={data.turn?.background_activities.length ?? 0}
+ />
+ </button>
+ );
+
+ const panel = expanded ? (
+ <PetPanel
+ binding={binding}
+ title={data.session?.title ?? null}
+ switcherOpen={switcherOpen || !binding}
+ onToggleSwitcher={() => setSwitcherOpen((open) => !open)}
+ onPick={(sessionId) => {
+ setSwitcherOpen(false);
+ petShell.pick(sessionId);
+ }}
+ exchange={exchange}
+ markRead={markRead}
+ onRead={data.refreshTail}
+ running={data.running}
+ queued={(data.turn?.pending_input_count ?? 0) > 0}
+ activities={data.turn?.background_activities ?? []}
+ vaultRequestIds={vaultRequests.map((request) => request.id)}
+ quickReplies={quickReplies}
+ onChoose={choose}
+ draft={draft}
+ onDraft={setDraft}
+ onSubmit={() => void submit()}
+ sending={sending}
+ canChat={canChat}
+ canSend={canChat && !uncertain && Boolean(binding) && data.session?.id === binding}
+ uncertain={uncertain}
+ onInspect={() => {
+ // Looking at the conversation resolves the doubt: the user sees whether
+ // the message went through before deciding to send again. Only a
+ // successful open counts as looking; a failed one must not unlock send.
+ if (!binding) return;
+ const sessionId = binding;
+ void petBridge.open(sessionLink(sessionId)).then(
+ () => setUncertain(sessionId, false),
+ () => undefined,
+ );
+ }}
+ inputRef={inputRef}
+ />
+ ) : null;
+
+ return (
+ <div
+ className={clsx(
+ 'flex h-full w-full gap-2 p-2',
+ layout.panel_side === 'left' ? 'flex-row' : 'flex-row-reverse',
+ layout.panel_edge === 'bottom' ? 'items-end' : 'items-start',
+ )}
+ data-state={state}
+ >
+ {panel}
+ {avatar}
+ </div>
+ );
+};
+
+type PanelProps = {
+ binding: string | null;
+ title: string | null;
+ switcherOpen: boolean;
+ onToggleSwitcher: () => void;
+ onPick: (sessionId: string) => void;
+ exchange: ReturnType<typeof latestExchange>;
+ markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>;
+ /** Re-read the tail after a read is applied, so rendered rows converge. */
+ onRead: () => void;
+ running: boolean;
+ queued: boolean;
+ activities: SessionActivityState[];
+ vaultRequestIds: string[];
+ quickReplies: ReturnType<typeof openQuickReplies>;
+ onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>;
+ draft: string;
+ onDraft: (value: string) => void;
+ onSubmit: () => void;
+ sending: boolean;
+ /** The bound session has been read and is writable. */
+ canSend: boolean;
+ /** Instance and project chat grants are both true. */
+ canChat: boolean;
+ /** The last send may have started a turn; resending waits for a look. */
+ uncertain: boolean;
+ onInspect: () => void;
+ inputRef: React.RefObject<HTMLTextAreaElement | null>;
+};
+
+const PetPanel: React.FC<PanelProps> = ({ inputRef, ...props }) => {
+ const { t } = useTranslation();
+ const { binding } = props;
+ return (
+ <section
+ className="flex max-h-full w-[320px] min-w-0 flex-col overflow-hidden rounded-2xl border border-border bg-card text-foreground shadow-xl"
+ aria-label={t('pet.panel')}
+ >
+ <header className="flex items-center gap-1.5 border-b border-border px-3 py-2">
+ <span className="min-w-0 flex-1 truncate text-[12px] font-medium">
+ {binding ? (props.title || t('pet.untitled')) : t('pet.chooseSession')}
+ </span>
+ {binding && (
+ <Button variant="ghost" size="icon" className="size-7" aria-label={t('pet.switchSession')} onClick={props.onToggleSwitcher}>
+ <Shuffle className="size-3.5" />
+ </Button>
+ )}
+ {binding && (
+ <Button variant="ghost" size="icon" className="size-7" aria-label={t('pet.openInAvibe')} onClick={() => void petBridge.open(sessionLink(binding))}>
+ <ExternalLink className="size-3.5" />
+ </Button>
+ )}
+ </header>
+ {props.switcherOpen ? (
+ <SessionSwitcher current={binding} onPick={props.onPick} />
+ ) : binding ? (
+ <>
+ <ExchangeView
+ exchange={props.exchange}
+ running={props.running}
+ binding={binding}
+ markRead={props.markRead}
+ onRead={props.onRead}
+ />
+ <ActivityLine activities={props.activities} />
+ <NeedsInput
+ vaultRequestIds={props.vaultRequestIds}
+ quickReplies={props.canChat && !props.uncertain ? props.quickReplies : null}
+ onChoose={props.onChoose}
+ />
+ {props.uncertain && (
+ <div className="flex flex-col items-start gap-1 border-t border-border px-3 py-2 text-[12px] text-muted" role="status">
+ <p>{t('newSession.sendUncertain')}</p>
+ <Button variant="link" size="sm" className="px-0" onClick={props.onInspect}>
+ {t('pet.openInAvibe')}
+ </Button>
+ </div>
+ )}
+ {props.canChat && (
+ <form
+ className="flex items-end gap-1.5 border-t border-border p-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ props.onSubmit();
+ }}
+ >
+ <textarea
+ ref={inputRef}
+ rows={1}
+ value={props.draft}
+ onChange={(event) => props.onDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ props.onSubmit();
+ }
+ }}
+ placeholder={t('pet.inputPlaceholder')}
+ aria-label={t('pet.inputPlaceholder')}
+ className="max-h-24 min-h-8 flex-1 resize-none rounded-lg border border-input bg-background px-2.5 py-1.5 text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ <Button type="submit" size="icon" className="size-8" disabled={props.sending || !props.canSend || !props.draft.trim()} aria-label={t('pet.send')}>
+ <ArrowUp className="size-4" />
+ </Button>
+ </form>
+ )}
+ {props.queued && <p className="px-3 pb-2 text-[11px] text-muted">{t('pet.queued')}</p>}
+ </>
+ ) : null}
+ </section>
+ );
+};
+
+/**
+ * The latest exchange, and the one place the pet marks replies read: this view
+ * is mounted only while the user can see it (panel open, switcher closed), so
+ * "rendered" is decided by what is on screen rather than by panel flags.
+ */
+const ExchangeView: React.FC<{
+ exchange: ReturnType<typeof latestExchange>;
+ running: boolean;
+ binding: string;
+ markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>;
+ onRead: () => void;
+}> = ({ exchange, running, binding, markRead, onRead }) => {
+ const { t } = useTranslation();
+ usePetMarkRead(binding, exchange, markRead, onRead);
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 py-2 text-[13px]">
+ {exchange.user && (
+ <div className="self-end max-w-[85%] rounded-xl bg-muted-soft px-2.5 py-1.5">
+ <Markdown content={exchange.user.text} softBreaks />
+ </div>
+ )}
+ {exchange.results.map((message) => (
+ <div key={message.id} className="min-w-0">
+ <Markdown content={message.text} softBreaks />
+ </div>
+ ))}
+ {running && <p className="text-[12px] text-muted">{t('pet.state.running')}</p>}
+ {!exchange.unreadComplete && (
+ <Button variant="link" size="sm" className="self-start px-0" onClick={() => void petBridge.open(sessionLink(binding))}>
+ {t('pet.moreInAvibe')}
+ </Button>
+ )}
+ {!exchange.user && exchange.results.length === 0 && !running && (
+ <p className="text-[12px] text-muted">{t('pet.empty')}</p>
+ )}
+ </div>
+ );
+};
+
+const ActivityLine: React.FC<{ activities: PanelProps['activities'] }> = ({ activities }) => {
+ const { t } = useTranslation();
+ const sorted = useMemo(() => sortBackgroundActivities(activities), [activities]);
+ if (sorted.length === 0) return null;
+ const first = sorted[0];
+ const label = resolveActivityLabel(first, t(`chat.activities.kind.${activityKindI18nKey(first)}`));
+ return (
+ <div className="px-3 pb-2">
+ <StatusPill
+ tone="running"
+ role="status"
+ className="min-h-6 max-w-full gap-2 px-2.5 py-0.5 text-[11px] font-normal"
+ indicator={<Activity className="size-3 shrink-0 text-mint-ink" aria-hidden="true" />}
+ label={(
+ <span className="min-w-0 truncate text-muted">
+ {t('chat.activities.running', { count: sorted.length })}
+ {label ? ` · ${label}` : ''}
+ </span>
+ )}
+ />
+ </div>
+ );
+};
+
+const NeedsInput: React.FC<{
+ vaultRequestIds: string[];
+ quickReplies: ReturnType<typeof openQuickReplies>;
+ onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>;
+}> = ({ vaultRequestIds, quickReplies, onChoose }) => {
+ const { t } = useTranslation();
+ if (vaultRequestIds.length === 0 && !quickReplies) return null;
+ return (
+ <div className="flex flex-col gap-2 px-3 pb-2">
+ {vaultRequestIds.map((requestId) => (
+ <Button
+ key={requestId}
+ variant="outline"
+ size="sm"
+ className="justify-start gap-2"
+ onClick={() => void petBridge.open(vaultRequestLink(requestId))}
+ >
+ <KeyRound className="size-3.5" />
+ {t('pet.vaultRequest')}
+ </Button>
+ ))}
+ {quickReplies && (
+ <QuickReplies
+ key={quickReplies.message.id}
+ options={quickReplies.options}
+ chosen={null}
+ onChoose={(choice) => onChoose(quickReplies.message, choice)}
+ />
+ )}
+ </div>
+ );
+};
+
+const SessionSwitcher: React.FC<{
+ current: string | null;
+ onPick: (sessionId: string) => void;
+}> = ({ current, onPick }) => {
+ const { t } = useTranslation();
+ const { sessions, loading } = useSessionSwitcher(true);
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto py-1">
+ {sessions.length === 0 && (
+ <p className="px-3 py-2 text-[12px] text-muted">{loading ? t('common.loading') : t('pet.noSessions')}</p>
+ )}
+ {sessions.map((session) => (
+ <button
+ key={session.id}
+ type="button"
+ className={clsx(
+ 'truncate px-3 py-1.5 text-left text-[13px] hover:bg-muted-soft',
+ session.id === current && 'font-medium text-primary-ink',
+ )}
+ onClick={() => onPick(session.id)}
+ >
+ {session.title || t('pet.untitled')}
+ </button>
+ ))}
+ </div>
+ );
+};
+
+/**
+ * Mark read through the last rendered unread result, once per row, and only
+ * when every unread result is in the loaded tail (otherwise reading is left to
+ * the Workbench). The tail keeps `read_at: null` until its next read, so a
+ * marker records what was sent. A request the server did not apply (an error
+ * status or a network failure) clears it, so the next chance to read
+ * (reopening the panel, the window coming back, a new tail) retries, without
+ * a retry loop against a failing server.
+ */
+function usePetMarkRead(
+ binding: string,
+ exchange: ReturnType<typeof latestExchange>,
+ markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>,
+ onRead: () => void,
+): void {
+ const last = exchange.results[exchange.results.length - 1];
+ const unreadId = last && last.read_at === null ? last.id : null;
+ // Seen means visible and focused: an open panel can stay up behind another
+ // app (it keeps an unsent draft), and a reply arriving then is not seen. The
+ // shared page-activity signal is the same one the chat page uses.
+ const active = usePageActive();
+ const markedRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (!unreadId || !exchange.unreadComplete || !active) return;
+ const marker = `${binding}\u0000${unreadId}`;
+ if (markedRef.current === marker) return;
+ markedRef.current = marker;
+ const forget = () => {
+ if (markedRef.current === marker) markedRef.current = null;
+ };
+ markRead(binding, unreadId).then((applied) => {
+ // An applied read converges the rendered rows from the server, so a
+ // later reply never replays this one as unread.
+ if (applied) onRead();
+ else forget();
+ }, forget);
+ }, [binding, unreadId, exchange.unreadComplete, active, markRead, onRead]);
+}
+
diff --git a/ui/src/pet/PetWindow.tsx b/ui/src/pet/PetWindow.tsx
new file mode 100644
index 000000000..6fe73474d
--- /dev/null
+++ b/ui/src/pet/PetWindow.tsx
@@ -0,0 +1,17 @@
+import { useLayoutEffect, type ReactNode } from 'react';
+
+import './pet-window.css';
+
+/**
+ * Route shell for `/pet`. The transparent window style has to outlive
+ * AuthGuard: on startup and on every authorization recheck the guard paints
+ * its own loading state and unmounts the page, and the native window is
+ * transparent, so an opaque body would show as a solid square.
+ */
+export function PetWindow({ children }: { children: ReactNode }) {
+ useLayoutEffect(() => {
+ document.documentElement.classList.add('pet-window');
+ return () => document.documentElement.classList.remove('pet-window');
+ }, []);
+ return children;
+}
diff --git a/ui/src/pet/fencedSource.test.ts b/ui/src/pet/fencedSource.test.ts
new file mode 100644
index 000000000..54a6dbd7a
--- /dev/null
+++ b/ui/src/pet/fencedSource.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { FencedSource } from './fencedSource';
+
+type Deferred<T> = { promise: Promise<T>; resolve: (value: T) => void; reject: (error: unknown) => void };
+const deferred = <T,>(): Deferred<T> => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+};
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+const harness = () => {
+ const pending: Array<{ key: string; reply: Deferred<string> }> = [];
+ const applied: Array<[string, string]> = [];
+ const failed: string[] = [];
+ const source = new FencedSource<string, string>({
+ read: (key) => {
+ const reply = deferred<string>();
+ pending.push({ key, reply });
+ return reply.promise;
+ },
+ apply: (key, value) => applied.push([key, value]),
+ fail: (key) => failed.push(key),
+ });
+ return { source, pending, applied, failed };
+};
+
+describe('FencedSource', () => {
+ it('applies a read for the current key', async () => {
+ const { source, pending, applied } = harness();
+ source.setKey('A');
+ source.refresh();
+ pending[0].reply.resolve('a1');
+ await flush();
+ expect(applied).toEqual([['A', 'a1']]);
+ });
+
+ it('drops a late result and a late failure for a previous key', async () => {
+ const { source, pending, applied, failed } = harness();
+ source.setKey('A');
+ source.refresh();
+ source.refresh();
+ source.setKey('B');
+ pending[0].reply.reject(new Error('404 for A'));
+ await flush();
+ // A's queued trailing read was dropped with the key change.
+ expect(pending).toHaveLength(1);
+ source.refresh();
+ pending[1].reply.resolve('b1');
+ await flush();
+ expect(failed).toEqual([]);
+ expect(applied).toEqual([['B', 'b1']]);
+ });
+
+ it('drops a read that started before a live merge, then re-reads once', async () => {
+ const { source, pending, applied } = harness();
+ source.setKey('S');
+ source.refresh();
+ source.noteLiveMerge();
+ pending[0].reply.resolve('stale');
+ await flush();
+ expect(applied).toEqual([]);
+ expect(pending).toHaveLength(2);
+ pending[1].reply.resolve('fresh');
+ await flush();
+ expect(applied).toEqual([['S', 'fresh']]);
+ });
+
+ it('coalesces a burst to one read in flight and one trailing read', async () => {
+ const { source, pending, applied } = harness();
+ source.setKey('S');
+ for (let index = 0; index < 5; index += 1) source.refresh();
+ expect(pending).toHaveLength(1);
+ pending[0].reply.resolve('first');
+ await flush();
+ expect(pending).toHaveLength(2);
+ pending[1].reply.resolve('second');
+ await flush();
+ expect(pending).toHaveLength(2);
+ // The read in flight when a refresh was asked for is superseded by it.
+ expect(applied.map(([, value]) => value)).toEqual(['second']);
+ });
+
+ it('drops a read superseded by a refresh, even if the trailing read fails', async () => {
+ const { source, pending, applied } = harness();
+ source.setKey('S');
+ source.refresh();
+ source.refresh();
+ pending[0].reply.resolve('running');
+ await flush();
+ expect(applied).toEqual([]);
+ pending[1].reply.reject(new Error('offline'));
+ await flush();
+ expect(applied).toEqual([]);
+ });
+
+ it('reads nothing without a key', () => {
+ const read = vi.fn();
+ const source = new FencedSource<string, string>({ read, apply: vi.fn() });
+ source.refresh();
+ expect(read).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/pet/fencedSource.ts b/ui/src/pet/fencedSource.ts
new file mode 100644
index 000000000..7819d7fdf
--- /dev/null
+++ b/ui/src/pet/fencedSource.ts
@@ -0,0 +1,96 @@
+/**
+ * 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 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
+ * one trailing read, so the source still converges on the server's state.
+ *
+ * A refresh asked for while a read is in flight means that read may already
+ * be stale (the trigger is newer than it), so it is dropped like a merged
+ * event, and the trailing read answers instead. Reads coalesce to at most one
+ * in flight plus one trailing.
+ */
+export type FencedSourceOptions<K, T> = {
+ read: (key: K) => Promise<T>;
+ apply: (key: K, value: T) => void;
+ /** Called only for a fresh read, so a late failure for an old key is dropped. */
+ fail?: (key: K, error: unknown) => void;
+};
+
+export class FencedSource<K, T> {
+ private generation = 0;
+ /** The generation of the read in flight for the current key, or 0. */
+ private inFlight = 0;
+ private trailing = false;
+ private key: K | null = null;
+
+ private readonly options: FencedSourceOptions<K, T>;
+
+ constructor(options: FencedSourceOptions<K, T>) {
+ this.options = options;
+ }
+
+ /** Re-read from the server, coalesced. */
+ refresh(): void {
+ if (this.inFlight !== 0) {
+ this.generation += 1;
+ this.trailing = true;
+ return;
+ }
+ void this.run();
+ }
+
+ /**
+ * A live event was merged into this source's state. Any read already in
+ * flight started before it and is dropped; one trailing read follows.
+ */
+ noteLiveMerge(): void {
+ this.generation += 1;
+ if (this.inFlight !== 0) this.trailing = true;
+ }
+
+ /**
+ * Point the source at `key` (null: nothing to read). A change drops whatever
+ * is in flight or queued for the old key.
+ */
+ setKey(key: K | null): void {
+ if (Object.is(key, this.key)) return;
+ this.key = key;
+ this.generation += 1;
+ this.trailing = false;
+ // A read for the old key no longer holds the slot: the new key reads now.
+ this.inFlight = 0;
+ }
+
+ private async run(): Promise<void> {
+ const key = this.key;
+ if (key === null) return;
+ const generation = ++this.generation;
+ this.inFlight = generation;
+ try {
+ const value = await this.options.read(key);
+ if (this.isFresh(key, generation)) this.options.apply(key, value);
+ } catch (error) {
+ if (this.isFresh(key, generation)) this.options.fail?.(key, error);
+ } finally {
+ // Only the read that still holds the slot releases it and runs the
+ // trailing read; a read abandoned by a key change does neither.
+ if (this.inFlight === generation) {
+ this.inFlight = 0;
+ if (this.trailing) {
+ this.trailing = false;
+ void this.run();
+ }
+ }
+ }
+ }
+
+ private isFresh(key: K, generation: number): boolean {
+ return generation === this.generation && Object.is(key, this.key);
+ }
+}
diff --git a/ui/src/pet/pet-window.css b/ui/src/pet/pet-window.css
new file mode 100644
index 000000000..1daad640f
--- /dev/null
+++ b/ui/src/pet/pet-window.css
@@ -0,0 +1,8 @@
+/* The pet window is transparent: nothing but the pet and its panel paints.
+ Installed by PetWindow for the whole /pet route, including AuthGuard
+ loading and authorization rechecks. */
+html.pet-window,
+html.pet-window body,
+html.pet-window #root {
+ background: transparent;
+}
diff --git a/ui/src/pet/pet.css b/ui/src/pet/pet.css
new file mode 100644
index 000000000..6231f675c
--- /dev/null
+++ b/ui/src/pet/pet.css
@@ -0,0 +1,47 @@
+/* Desktop pet motion: CSS only, one pose per state. See
+ docs/plans/2026-10-01-desktop-pet.md ("Rendering and idle cost"). */
+
+.pet-avatar {
+ position: relative;
+ width: 88px;
+ height: 88px;
+}
+
+.pet-avatar__pose {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ pointer-events: none;
+ user-select: none;
+ -webkit-user-drag: none;
+}
+
+/* Every pose plays a short squash when it mounts (a state change remounts it),
+ then breathes slowly while the window is visible and the pose is not resting. */
+.pet-avatar__pose {
+ animation: pet-change 320ms ease-out;
+}
+
+.pet-avatar__pose[data-breathing='true'] {
+ animation: pet-change 320ms ease-out, pet-breathe 3.6s ease-in-out 320ms infinite;
+}
+
+@keyframes pet-breathe {
+ 0%, 100% { transform: translateY(0) scale(1, 1); }
+ 50% { transform: translateY(-3px) scale(1.015, 0.985); }
+}
+
+@keyframes pet-change {
+ 0% { opacity: 0.2; transform: scale(1.08, 0.9); }
+ 60% { opacity: 1; transform: scale(0.97, 1.03); }
+ 100% { opacity: 1; transform: scale(1, 1); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .pet-avatar__pose,
+ .pet-avatar__pose[data-breathing='true'] {
+ animation: none;
+ }
+}
diff --git a/ui/src/pet/petBridge.ts b/ui/src/pet/petBridge.ts
new file mode 100644
index 000000000..ed7b9a9f6
--- /dev/null
+++ b/ui/src/pet/petBridge.ts
@@ -0,0 +1,196 @@
+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
+ *
+ * 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 }
+ *
+ * `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 and lays the panel out to the right, so the route
+ * stays usable without the native window.
+ */
+
+export type PetIntent = 'listen' | 'show';
+
+export type PetLayout = {
+ panel_side: 'left' | 'right';
+ panel_edge: 'top' | 'bottom';
+};
+
+/** The shell's binding, and the revision it was at. */
+export type PetBinding = {
+ binding: string | null;
+ revision: number;
+};
+
+export type PetReady = PetBinding & {
+ summon_pending: { intent: PetIntent } | null;
+};
+
+export const PET_SUMMON_EVENT = 'avibe:pet-summon';
+export const PET_BOUND_EVENT = 'avibe:pet-bound';
+
+// Outside the shell, `{ binding, revision }` as JSON: the dev stand-in for
+// `pet.json` and the shell's revision counter.
+const DEV_BINDING_KEY = 'avibe.pet.devBinding';
+const DEFAULT_LAYOUT: PetLayout = { panel_side: 'left', panel_edge: 'bottom' };
+
+type TauriInternals = { invoke: (command: string, args?: Record<string, unknown>) => Promise<unknown> };
+
+const shellInvoke = (): TauriInternals['invoke'] | null => {
+ if (!isDesktopShell()) return null;
+ const internals = (window as unknown as { __TAURI_INTERNALS__?: TauriInternals }).__TAURI_INTERNALS__;
+ return internals?.invoke ? internals.invoke.bind(internals) : null;
+};
+
+const isIntent = (value: unknown): value is PetIntent => value === 'listen' || value === 'show';
+
+const parseBinding = (value: unknown): PetBinding => {
+ const result = value as { binding?: unknown; revision?: unknown } | null;
+ const revision = result?.revision;
+ if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 0) {
+ throw new Error('pet shell answered without a binding revision');
+ }
+ return {
+ binding: typeof result?.binding === 'string' && result.binding ? result.binding : null,
+ revision,
+ };
+};
+
+let devMemory: PetBinding = { binding: null, revision: 0 };
+
+const readDevBinding = (): PetBinding => {
+ try {
+ const stored = window.localStorage.getItem(DEV_BINDING_KEY);
+ if (stored) devMemory = parseBinding(JSON.parse(stored));
+ } catch {
+ /* storage unavailable or unreadable: keep this page's own copy */
+ }
+ 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 };
+ 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,
+ };
+ },
+
+ setExpanded: async (expanded: boolean): Promise<PetLayout> => {
+ const invoke = shellInvoke();
+ if (!invoke) return DEFAULT_LAYOUT;
+ const layout = (await invoke('pet_set_expanded', { expanded })) as Partial<PetLayout> | null;
+ return {
+ panel_side: layout?.panel_side === 'right' ? 'right' : 'left',
+ panel_edge: layout?.panel_edge === 'top' ? 'top' : 'bottom',
+ };
+ },
+
+ 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> => {
+ const invoke = shellInvoke();
+ if (!invoke) {
+ const current = readDevBinding();
+ return current.binding === sessionId ? writeDevBinding(null) : current;
+ }
+ return parseBinding(await invoke('pet_unbind', { sessionId }));
+ },
+
+ /** Moves the native window with the pointer (`start-dragging`). */
+ startDragging: (): void => {
+ void shellInvoke()?.('plugin:window|start_dragging');
+ },
+
+ /** Opens an `avibe://` link in the main window. */
+ open: async (link: string): Promise<void> => {
+ const invoke = shellInvoke();
+ if (invoke) {
+ await invoke('pet_open', { link });
+ return;
+ }
+ openLinkInNewContext(devPathForLink(link), 'noopener');
+ },
+};
+
+/** The Workbench path for a deep link, used only outside the shell. */
+export const devPathForLink = (link: string): string => {
+ const match = /^avibe:\/\/(session|show)\/([^/?#]+)$/.exec(link);
+ if (match) return `${match[1] === 'session' ? '/chat' : '/apps/show'}/${match[2]}`;
+ const vault = /^avibe:\/\/vaults\/request\/([^/?#]+)$/.exec(link);
+ if (vault) return `/vaults?request_id=${vault[1]}`;
+ return '/settings/general';
+};
+
+export const sessionLink = (sessionId: string): string => `avibe://session/${sessionId}`;
+export const vaultRequestLink = (requestId: string): string => `avibe://vaults/request/${requestId}`;
+export const SETTINGS_LINK = 'avibe://settings';
+
+/** 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
new file mode 100644
index 000000000..9fee30614
--- /dev/null
+++ b/ui/src/pet/petComposer.ts
@@ -0,0 +1,98 @@
+import { useEffect, useSyncExternalStore } from 'react';
+
+/**
+ * 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
+ * recheck — which unmounts the page while it revalidates — cannot drop a send
+ * lock, the text that belongs to it, or a listen that is still waiting for
+ * the composer to mount.
+ */
+let draft = '';
+let draftSession: string | null | undefined;
+const uncertainSessions = new Set<string>();
+let sending = false;
+let pendingListen = false;
+let version = 0;
+const listeners = new Set<() => void>();
+
+const notify = () => {
+ version += 1;
+ listeners.forEach((listener) => listener());
+};
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+};
+
+export const petComposer = {
+ isUncertain: (sessionId: string | null): boolean => (
+ Boolean(sessionId && uncertainSessions.has(sessionId))
+ ),
+ isSending: (): boolean => sending,
+ setUncertain(sessionId: string, value: boolean) {
+ const had = uncertainSessions.has(sessionId);
+ if (value === had) return;
+ if (value) uncertainSessions.add(sessionId);
+ else uncertainSessions.delete(sessionId);
+ notify();
+ },
+ setSending(value: boolean) {
+ if (sending === value) return;
+ sending = value;
+ notify();
+ },
+ setDraft(value: string, sessionId: string | null) {
+ const sessionChanged = draftSession !== sessionId;
+ if (!sessionChanged && draft === value) return;
+ draftSession = sessionId;
+ draft = value;
+ notify();
+ },
+ bind(sessionId: string | null) {
+ if (draftSession === sessionId) return;
+ draftSession = sessionId;
+ draft = '';
+ notify();
+ },
+ clearDraftIf(value: string) {
+ if (draft !== value) return;
+ draft = '';
+ notify();
+ },
+ requestListen() {
+ if (pendingListen) return;
+ pendingListen = true;
+ notify();
+ },
+ takeListen(): boolean {
+ if (!pendingListen) return false;
+ pendingListen = false;
+ notify();
+ return true;
+ },
+};
+
+export function usePetComposer(binding: string | null): {
+ draft: string;
+ uncertain: boolean;
+ sending: boolean;
+ listenPending: boolean;
+ setDraft: (value: string) => void;
+ setUncertain: (sessionId: string, value: boolean) => void;
+} {
+ useSyncExternalStore(subscribe, () => version);
+ useEffect(() => {
+ 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 : '',
+ uncertain: petComposer.isUncertain(binding),
+ sending,
+ listenPending: pendingListen,
+ setDraft: (value: string) => petComposer.setDraft(value, binding),
+ setUncertain: petComposer.setUncertain,
+ };
+}
diff --git a/ui/src/pet/petPanel.test.tsx b/ui/src/pet/petPanel.test.tsx
new file mode 100644
index 000000000..d4498c033
--- /dev/null
+++ b/ui/src/pet/petPanel.test.tsx
@@ -0,0 +1,82 @@
+/* @vitest-environment jsdom */
+
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PET_SUMMON_EVENT } from './petBridge';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const api = {
+ getConfig: vi.fn(async () => ({ mode: 'self_host', setup_state: { needs_setup: true } })),
+ getSessionResult: vi.fn(async () => ({ status: 200, session: null })),
+ listSessionMessages: vi.fn(async () => ({ messages: [], next_after_id: null, next_before_id: null })),
+ getTurnState: vi.fn(async () => ({
+ in_flight: false, foreground: 'idle', native_turn_started: false,
+ pending_input_count: 0, background_activities: [], pending_activity_output_count: 0,
+ connection: 'connected',
+ })),
+ listSessions: vi.fn(async () => ({ sessions: [], next_before_id: null })),
+ getVaultRequests: vi.fn(async () => ({ requests: [] })),
+ sendSessionMessage: vi.fn(),
+ connectWorkbenchEvents: () => () => undefined,
+};
+
+vi.mock('@/context/ApiContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/context/ApiContext')>()),
+ useApi: () => api,
+}));
+vi.mock('@/context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({ capabilities: { can_chat: true } }),
+}));
+vi.mock('@/context/WorkbenchInboxContext', () => ({
+ useWorkbenchInbox: () => ({ unreadBySession: {}, markRead: vi.fn() }),
+}));
+
+Object.defineProperty(document, 'hasFocus', { value: () => true, configurable: true });
+
+let PetPage: typeof import('./PetPage').PetPage;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ PetPage } = await import('./PetPage'));
+ window.localStorage.clear();
+});
+
+afterEach(() => {
+ cleanup();
+ delete (window as { __AVIBE_DESKTOP_SHELL__?: unknown }).__AVIBE_DESKTOP_SHELL__;
+ delete (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
+});
+
+describe('setup-pending expansion', () => {
+ it('grows the native frame before showing the setup-pending card', async () => {
+ let resolveGrow: (value: unknown) => void = () => undefined;
+ const grow = new Promise((resolve) => { resolveGrow = resolve; });
+ const invoke = vi.fn((command: string) => {
+ if (command === 'pet_ready') return Promise.resolve({ binding: null, revision: 0, summon_pending: null });
+ if (command === 'pet_set_expanded') {
+ if (invoke.mock.calls.filter(([c]) => c === 'pet_set_expanded').length > 8) {
+ throw new Error('pet_set_expanded loop');
+ }
+ return grow;
+ }
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ render(<PetPage />);
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
+ expect(screen.queryByText('pet.setupPending')).toBeNull();
+ await act(async () => resolveGrow({ panel_side: 'left', panel_edge: 'bottom' }));
+ expect(await screen.findByText('pet.setupPending')).toBeTruthy();
+ const expands = invoke.mock.calls.filter(([command]) => command === 'pet_set_expanded').length;
+ act(() => {
+ window.dispatchEvent(new CustomEvent(PET_SUMMON_EVENT, { detail: { intent: 'show' } }));
+ });
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 40)));
+ expect(invoke.mock.calls.filter(([command]) => command === 'pet_set_expanded')).toHaveLength(expands + 1);
+ });
+});
diff --git a/ui/src/pet/petPanel.ts b/ui/src/pet/petPanel.ts
new file mode 100644
index 000000000..c3ec34708
--- /dev/null
+++ b/ui/src/pet/petPanel.ts
@@ -0,0 +1,74 @@
+import { useCallback, useSyncExternalStore } from 'react';
+
+import { petBridge, type PetLayout } from './petBridge';
+
+const DEFAULT_LAYOUT: PetLayout = { panel_side: 'left', panel_edge: 'bottom' };
+
+/**
+ * The native frame's expansion, held once per document outside React so the
+ * setup-pending card and the pet surface share it across their unmounts.
+ *
+ * Closing hides the panel at once (a moment of transparent frame is
+ * harmless); opening shows it only once the shell has grown the frame, so
+ * content is never marked seen while still clipped. Native resizes are sent
+ * one at a time in the order they were asked, so an older `pet_set_expanded`
+ * cannot apply after a newer one; only the latest request updates React. A
+ * failed request restores the last confirmed expansion, so a redundant
+ * expand of an already-open panel cannot hide it.
+ */
+let expanded = false;
+let layout: PetLayout = DEFAULT_LAYOUT;
+let requestId = 0;
+let wantExpanded = false;
+let confirmedExpanded = false;
+let chain: Promise<void> = Promise.resolve();
+const listeners = new Set<() => void>();
+
+const notify = () => listeners.forEach((listener) => listener());
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+};
+
+export const petPanel = {
+ current: (): boolean => expanded,
+ want: (): boolean => wantExpanded,
+ layout: (): PetLayout => layout,
+};
+
+export function usePetPanel(): {
+ expanded: boolean;
+ layout: PetLayout;
+ setPanel: (next: boolean) => Promise<void>;
+} {
+ const currentExpanded = useSyncExternalStore(subscribe, () => expanded);
+ const currentLayout = useSyncExternalStore(subscribe, () => layout);
+ const setPanel = useCallback(async (next: boolean) => {
+ wantExpanded = next;
+ const request = ++requestId;
+ if (!next) {
+ expanded = false;
+ notify();
+ }
+ const run = async () => {
+ try {
+ const applied = await petBridge.setExpanded(next);
+ if (request !== requestId) return;
+ confirmedExpanded = next;
+ layout = applied;
+ expanded = next;
+ notify();
+ } catch {
+ if (request !== requestId) return;
+ wantExpanded = confirmedExpanded;
+ expanded = confirmedExpanded;
+ notify();
+ }
+ };
+ const wait = chain.then(run, run);
+ chain = wait.then(() => undefined, () => undefined);
+ await wait;
+ }, []);
+ return { expanded: currentExpanded, layout: currentLayout, setPanel };
+}
diff --git a/ui/src/pet/petShell.ts b/ui/src/pet/petShell.ts
new file mode 100644
index 000000000..49461f6fa
--- /dev/null
+++ b/ui/src/pet/petShell.ts
@@ -0,0 +1,148 @@
+import { useEffect, useSyncExternalStore } from 'react';
+
+import { onPetEvents, petBridge, type PetBinding, type PetIntent } from './petBridge';
+
+/**
+ * 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();
+let pendingSummon: PetIntent | null = null;
+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;
+ binding = 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) => {
+ outstanding += 1;
+ latestChange = next;
+ show();
+ changes = changes
+ .then(send)
+ .then(report, failed)
+ .finally(() => {
+ outstanding -= 1;
+ show();
+ });
+};
+
+const start = () => {
+ if (started) return;
+ started = true;
+ onPetEvents({
+ summon: (intent) => {
+ liveSummons += 1;
+ noteSummon(intent);
+ },
+ bound: report,
+ });
+ const liveSummonsAtRequest = liveSummons;
+ void petBridge.ready().then((ready) => {
+ report(ready);
+ 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 });
+ });
+};
+
+export const petShell = {
+ /** Bind `sessionId`. If the shell cannot, the pet shows what it holds. */
+ pick: (sessionId: string) => change(sessionId, () => petBridge.bind(sessionId), () => undefined),
+
+ /**
+ * 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 };
+ });
+ },
+
+ /** Take the waiting summon, if any. */
+ takeSummon: (): PetIntent | null => {
+ const intent = pendingSummon;
+ pendingSummon = null;
+ return intent;
+ },
+
+ /** The binding now, for callbacks that must not read a stale render. */
+ currentBinding: (): string | null | undefined => binding,
+};
+
+export function usePetBinding(): string | null | undefined {
+ useEffect(start, []);
+ return useSyncExternalStore(
+ (listener) => {
+ storeListeners.add(listener);
+ return () => storeListeners.delete(listener);
+ },
+ () => binding,
+ );
+}
+
+/**
+ * Call `listener` whenever a summon is waiting, including one that arrived
+ * before this component mounted. The listener decides whether to take it.
+ */
+export function useOnSummon(listener: () => void): void {
+ useEffect(() => {
+ start();
+ summonListeners.add(listener);
+ // A summon that is already waiting is delivered after mount, never during it.
+ if (pendingSummon !== null) queueMicrotask(() => {
+ if (summonListeners.has(listener) && pendingSummon !== null) listener();
+ });
+ return () => {
+ summonListeners.delete(listener);
+ };
+ }, [listener]);
+}
diff --git a/ui/src/pet/petState.test.ts b/ui/src/pet/petState.test.ts
new file mode 100644
index 000000000..16b9538ff
--- /dev/null
+++ b/ui/src/pet/petState.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkbenchMessage } from '@/context/ApiContext';
+
+import { derivePetState, latestExchange, openQuickReplies, type PetStateInputs } from './petState';
+
+let nextId = 0;
+const row = (overrides: Partial<WorkbenchMessage>): WorkbenchMessage => ({
+ id: `m${(nextId += 1)}`,
+ scope_id: 'scope',
+ session_id: 'S',
+ platform: 'avibe',
+ author: 'agent',
+ type: 'result',
+ source: 'agent',
+ author_id: null,
+ author_name: null,
+ native_message_id: null,
+ parent_native_message_id: null,
+ text: 'text',
+ content: {},
+ metadata: {},
+ created_at: '2026-10-04T00:00:00Z',
+ updated_at: '2026-10-04T00:00:00Z',
+ delivered_at: null,
+ read_at: '2026-10-04T00:00:01Z',
+ ...overrides,
+});
+
+const user = (text = 'hi') => row({ author: 'user', type: 'user', source: 'user', text });
+const result = (overrides: Partial<WorkbenchMessage> = {}) => row(overrides);
+const asking = (chosen?: string) => result({
+ content: { quick_replies: ['Yes', 'No'], ...(chosen ? { quick_reply_chosen: chosen } : {}) },
+});
+
+const quiet: PetStateInputs = {
+ session: { agent_status: 'idle' },
+ messages: [user(), result()],
+ turn: { foreground: 'idle', in_flight: false },
+ pendingVaultRequests: 0,
+ unreadCount: 0,
+};
+
+describe('derivePetState', () => {
+ it.each<[string, Partial<PetStateInputs>, ReturnType<typeof derivePetState>]>([
+ ['nothing is happening', {}, 'idle'],
+ ['the agent is working', { turn: { foreground: 'running', in_flight: true } }, 'running'],
+ ['a turn is in flight before the foreground flips', { turn: { foreground: 'idle', in_flight: true } }, 'running'],
+ ['a reply is unread and the agent is idle', { unreadCount: 2 }, 'ready'],
+ ['the last run failed', { session: { agent_status: 'failed' } }, 'blocked'],
+ ['a vault request is pending', { pendingVaultRequests: 1 }, 'needs_input'],
+ ['the latest result asks a quick-reply question', { messages: [user(), asking()] }, 'needs_input'],
+ ])('is %s → %s', (_case, override, expected) => {
+ expect(derivePetState({ ...quiet, ...override })).toBe(expected);
+ });
+
+ it('orders Needs input > Blocked > Ready > Running > Idle', () => {
+ const everything: PetStateInputs = {
+ session: { agent_status: 'failed' },
+ messages: [user(), asking()],
+ turn: { foreground: 'running', in_flight: true },
+ pendingVaultRequests: 1,
+ unreadCount: 3,
+ };
+ expect(derivePetState(everything)).toBe('needs_input');
+ expect(derivePetState({ ...everything, messages: [user(), result()], pendingVaultRequests: 0 })).toBe('blocked');
+ expect(derivePetState({
+ ...everything, messages: [], pendingVaultRequests: 0, session: { agent_status: 'idle' }, turn: null,
+ })).toBe('ready');
+ // A running turn is not Ready even with unread replies: the reply is not final yet.
+ expect(derivePetState({
+ ...everything, messages: [], pendingVaultRequests: 0, session: { agent_status: 'idle' },
+ })).toBe('running');
+ });
+
+ it('clears Needs input once the question is answered', () => {
+ expect(derivePetState({ ...quiet, messages: [user(), asking('Yes')] })).toBe('idle');
+ });
+
+ it('ignores an older unanswered group once a newer result exists', () => {
+ const messages = [user(), asking(), user('free text'), result()];
+ expect(openQuickReplies(messages)).toBeNull();
+ expect(derivePetState({ ...quiet, messages })).toBe('idle');
+ });
+});
+
+describe('latestExchange', () => {
+ it('shows the last user message and the last result when nothing is unread', () => {
+ const last = result({ text: 'latest' });
+ const exchange = latestExchange([user('old'), result(), user('ask'), last], true);
+ expect(exchange.user?.text).toBe('ask');
+ expect(exchange.results).toEqual([last]);
+ expect(exchange.unreadComplete).toBe(true);
+ });
+
+ it('shows every unread result, oldest first', () => {
+ const first = result({ read_at: null, text: 'one' });
+ const second = result({ read_at: null, text: 'two' });
+ const exchange = latestExchange([result(), user(), first, second], true);
+ expect(exchange.results).toEqual([first, second]);
+ expect(exchange.unreadComplete).toBe(true);
+ });
+
+ it('is incomplete when unread results may reach past the loaded tail', () => {
+ const tail = [result({ read_at: null }), user(), result({ read_at: null })];
+ expect(latestExchange(tail, true).unreadComplete).toBe(false);
+ // The tail already starts at the session's first row.
+ expect(latestExchange(tail, false).unreadComplete).toBe(true);
+ });
+
+ it('is incomplete when the inbox count is ahead of the loaded unread results', () => {
+ const visible = result({ read_at: null, text: 'visible' });
+ expect(latestExchange([visible], true, 3).unreadComplete).toBe(false);
+ expect(latestExchange([visible], true, 3).results).toEqual([visible]);
+ // Inbox says unread, the loaded tail is all read: those replies sit past it.
+ expect(latestExchange([result({ text: 'read' })], true, 2).unreadComplete).toBe(false);
+ // A leftover count on a fully loaded session is stale.
+ expect(latestExchange([result({ text: 'read' })], false, 2).unreadComplete).toBe(true);
+ });
+
+ it('leaves out process rows', () => {
+ const exchange = latestExchange([user(), row({ type: 'tool_call' }), result({ text: 'done' })], false);
+ expect(exchange.results.map((message) => message.text)).toEqual(['done']);
+ });
+});
diff --git a/ui/src/pet/petState.ts b/ui/src/pet/petState.ts
new file mode 100644
index 000000000..06b5c2987
--- /dev/null
+++ b/ui/src/pet/petState.ts
@@ -0,0 +1,109 @@
+import type { SessionRuntimeState, WorkbenchMessage, WorkbenchSession } from '@/context/ApiContext';
+import { isTranscriptMessage } from '@/lib/chatMessageTypes';
+
+/**
+ * What the desktop pet shows for its bound session. One pure derivation from
+ * the same reads the Workbench already makes; see
+ * docs/plans/2026-10-01-desktop-pet.md ("Pet state").
+ */
+export type PetState = 'needs_input' | 'blocked' | 'ready' | 'running' | 'idle';
+
+export type PetStateInputs = {
+ session: Pick<WorkbenchSession, 'agent_status'> | null;
+ /** The loaded tail, oldest first. */
+ messages: WorkbenchMessage[];
+ turn: Pick<SessionRuntimeState, 'foreground' | 'in_flight'> | null;
+ pendingVaultRequests: number;
+ unreadCount: number;
+};
+
+/** The options of a message's quick-reply group, or `[]` when it has none. */
+export const quickReplyOptions = (message: WorkbenchMessage): string[] => {
+ const content = message.content as { quick_replies?: unknown } | null | undefined;
+ const options = content?.quick_replies;
+ return Array.isArray(options)
+ ? options.filter((option): option is string => typeof option === 'string' && option.length > 0)
+ : [];
+};
+
+export const quickReplyChosen = (message: WorkbenchMessage): string | null => {
+ const chosen = (message.content as { quick_reply_chosen?: unknown } | null | undefined)?.quick_reply_chosen;
+ return typeof chosen === 'string' && chosen ? chosen : null;
+};
+
+const isAgentResult = (message: WorkbenchMessage): boolean =>
+ message.author === 'agent' && message.type === 'result';
+
+/** The latest agent result in the tail, or null. */
+export const latestAgentResult = (messages: WorkbenchMessage[]): WorkbenchMessage | null => {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ if (isAgentResult(messages[index])) return messages[index];
+ }
+ return null;
+};
+
+/**
+ * The quick-reply group the agent is waiting on now: the latest agent result's
+ * group, while unanswered. An older unanswered group is not an open question —
+ * once a newer result exists the agent has moved on — so it never counts
+ * (it stays clickable in the Workbench).
+ */
+export const openQuickReplies = (messages: WorkbenchMessage[]): { message: WorkbenchMessage; options: string[] } | null => {
+ const latest = latestAgentResult(messages);
+ if (!latest || quickReplyChosen(latest)) return null;
+ const options = quickReplyOptions(latest);
+ return options.length > 0 ? { message: latest, options } : null;
+};
+
+const isRunning = (turn: PetStateInputs['turn']): boolean =>
+ turn?.foreground === 'running' || turn?.in_flight === true;
+
+/** Priority: Needs input > Blocked > Ready > Running > Idle. */
+export const derivePetState = (inputs: PetStateInputs): PetState => {
+ if (inputs.pendingVaultRequests > 0 || openQuickReplies(inputs.messages)) return 'needs_input';
+ if (inputs.session?.agent_status === 'failed') return 'blocked';
+ if (!isRunning(inputs.turn) && inputs.unreadCount > 0) return 'ready';
+ if (isRunning(inputs.turn)) return 'running';
+ return 'idle';
+};
+
+/**
+ * The rows the panel shows as the latest exchange: the last user message, then
+ * every unread agent result (oldest first), or the last agent result when none
+ * is unread. `hasOlder` says the server has rows before the loaded tail.
+ * `unreadCount` is the inbox's session count: when it is ahead of the tail,
+ * unread rows may sit past what is loaded even if every loaded result is read.
+ */
+export const latestExchange = (
+ messages: WorkbenchMessage[],
+ hasOlder: boolean,
+ unreadCount = 0,
+): {
+ user: WorkbenchMessage | null;
+ results: WorkbenchMessage[];
+ /** False when unread results may reach past the loaded tail, so the pet
+ * must not mark read and sends the user to the Workbench instead. */
+ unreadComplete: boolean;
+} => {
+ const transcript = messages.filter((message) => isTranscriptMessage(message));
+ let user: WorkbenchMessage | null = null;
+ for (let index = transcript.length - 1; index >= 0; index -= 1) {
+ if (transcript[index].author === 'user') {
+ user = transcript[index];
+ break;
+ }
+ }
+ const results = transcript.filter(isAgentResult);
+ const unread = results.filter((message) => message.read_at === null);
+ if (unread.length === 0) {
+ const last = results[results.length - 1];
+ // Inbox says something is unread, but the tail has no unread result: those
+ // replies sit past the loaded window. A fully-loaded session treats a
+ // leftover count as stale.
+ return { user, results: last ? [last] : [], unreadComplete: unreadCount <= 0 || !hasOlder };
+ }
+ // Unread rows reach past the tail when the oldest loaded result is itself
+ // unread, or when the inbox count is ahead of the unread results we have.
+ const unreadComplete = !hasOlder || (results[0].read_at !== null && unread.length >= unreadCount);
+ return { user, results: unread, unreadComplete };
+};
diff --git a/ui/src/pet/usePetSession.ts b/ui/src/pet/usePetSession.ts
new file mode 100644
index 000000000..91a55efba
--- /dev/null
+++ b/ui/src/pet/usePetSession.ts
@@ -0,0 +1,277 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+
+import {
+ useApi,
+ type SessionRuntimeState,
+ type WorkbenchMessage,
+ type WorkbenchSession,
+ type WorkbenchSessionReadResult,
+} from '@/context/ApiContext';
+import { isSessionReadOnly } from '@/components/workbench/sessionArchived';
+import { isTranscriptMessage } from '@/lib/chatMessageTypes';
+import { onPageReactivated } from '@/lib/pageActivity';
+import { useLatestRef } from '@/lib/useLatestRef';
+
+import { FencedSource } from './fencedSource';
+
+export const PET_TAIL_LIMIT = 30;
+// Same cadences as the chat page: reconcile a dropped turn.end without ever
+// clearing a live turn on a timer, faster while background work is present.
+const WORKING_RECONCILE_INTERVAL_MS = 60 * 1000;
+const ACTIVITY_RECONCILE_INTERVAL_MS = 10 * 1000;
+// A just-sent turn is not in the controller's in-flight map until dispatch
+// lands, so the pet shows Running for this long after a local send.
+export const SEND_GRACE_MS = 4000;
+
+export type PetSessionData = {
+ session: WorkbenchSession | null;
+ /** Project-level chat grant from GET session; null until a read lands. */
+ canChat: boolean | null;
+ messages: WorkbenchMessage[];
+ /** Rows before `messages` may exist: the tail was trimmed, or no tail read
+ * has landed yet, so live rows alone say nothing about what came before. */
+ hasOlder: boolean;
+ turn: SessionRuntimeState | null;
+ /** Running per the server, or a local send inside the registration grace. */
+ running: boolean;
+ /** Merge a row the pet itself just sent. */
+ noteSent: (message: WorkbenchMessage | null) => void;
+ /** Re-read the tail from the server. */
+ refreshTail: () => void;
+};
+
+// `loaded`: a tail read has applied. Until then the rows are only what live
+// events merged, so they cannot be read as a complete window.
+type Tail = { messages: WorkbenchMessage[]; hasOlder: boolean; loaded: boolean };
+const EMPTY_TAIL: Tail = { messages: [], hasOlder: false, loaded: false };
+const TAIL_CAP = PET_TAIL_LIMIT * 2;
+
+/**
+ * Merge a live row into the tail. Only transcript rows are kept (process rows
+ * such as tool calls stream in by the hundred and the pet never shows them),
+ * and the tail is capped; trimming means it no longer starts at the session's
+ * first row, so `hasOlder` turns true and unread rows past it are not marked.
+ */
+const mergeRow = (tail: Tail, row: WorkbenchMessage): Tail => {
+ const index = tail.messages.findIndex((existing) => existing.id === row.id);
+ if (index >= 0) {
+ return { ...tail, messages: tail.messages.map((existing, at) => (at === index ? row : existing)) };
+ }
+ if (!isTranscriptMessage(row)) return tail;
+ const messages = [...tail.messages, row];
+ if (messages.length <= TAIL_CAP) return { ...tail, messages };
+ return { ...tail, messages: messages.slice(-TAIL_CAP), hasOlder: true };
+};
+
+/**
+ * Everything the pet reads about its bound session `S`, per the input-freshness
+ * 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.
+ */
+export function usePetSession(sessionId: string | null, onInvalid: (sessionId: string) => void): PetSessionData {
+ const api = useApi();
+
+ const [session, setSession] = useState<WorkbenchSession | null>(null);
+ 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);
+
+ // Reset during render so a switch never paints the previous session's rows.
+ 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);
+ },
+ 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 }),
+ apply: (_key, value) => {
+ setTail({ messages: value.messages, hasOlder: Boolean(value.next_before_id), loaded: true });
+ },
+ }),
+ turn: new FencedSource<string, SessionRuntimeState>({
+ read: (key) => api.getTurnState(key, { handleError: false }),
+ apply: (_key, value) => {
+ if (value.foreground !== 'unknown') setTurn(value);
+ },
+ }),
+ }), [api]);
+
+ // A live event can only patch rows a read has supplied. Until one has (the
+ // first read failed, say, while the stream stayed up), the event is the
+ // next chance to read instead.
+ const sessionRef = useLatestRef(session);
+ const tailLoadedRef = useLatestRef(tail.loaded);
+
+ const refreshAll = useCallback(() => {
+ sources.session.refresh();
+ sources.tail.refresh();
+ sources.turn.refresh();
+ }, [sources]);
+
+ // Initial read on every binding change.
+ useEffect(() => {
+ sources.session.setKey(sessionId);
+ sources.tail.setKey(sessionId);
+ sources.turn.setKey(sessionId);
+ if (sessionId) refreshAll();
+ }, [sessionId, sources, refreshAll]);
+
+ // Report an invalid binding once, and only while it is still the binding.
+ useEffect(() => {
+ if (invalid && invalid === sessionId) onInvalid(invalid);
+ }, [invalid, sessionId, onInvalid]);
+
+ // Live triggers and the reconnect gap fallback.
+ useEffect(() => {
+ if (!sessionId) return undefined;
+ const mine = (id: string | null | undefined) => id === sessionId;
+ return api.connectWorkbenchEvents({
+ onConnected: refreshAll,
+ onMessageNew: (row) => {
+ if (!mine(row.session_id)) return;
+ sources.tail.noteLiveMerge();
+ setTail((current) => mergeRow(current, row));
+ if (!tailLoadedRef.current) sources.tail.refresh();
+ },
+ onMessageUpdated: (row) => {
+ if (!mine(row.session_id)) return;
+ sources.tail.noteLiveMerge();
+ setTail((current) => ({
+ ...current,
+ messages: current.messages.map((existing) => (existing.id === row.id ? row : existing)),
+ }));
+ if (!tailLoadedRef.current) sources.tail.refresh();
+ },
+ // A mark-read in any window (this one included) changes `read_at` on
+ // rows the pet holds, and only a read brings that in.
+ onInboxUnreadChanged: ({ session_id }) => {
+ if (mine(session_id)) sources.tail.refresh();
+ },
+ onSessionStatus: ({ session_id, agent_status }) => {
+ if (!mine(session_id)) return;
+ if (!sessionRef.current) {
+ sources.session.refresh();
+ return;
+ }
+ sources.session.noteLiveMerge();
+ setSession((current) => (current ? { ...current, agent_status } : current));
+ },
+ onSessionActivity: ({ session_id }) => {
+ if (mine(session_id)) sources.session.refresh();
+ },
+ onTurnStart: ({ session_id }) => {
+ if (mine(session_id)) sources.turn.refresh();
+ },
+ onTurnEnd: ({ session_id }) => {
+ if (!mine(session_id)) return;
+ // An authoritative end: the post-send grace only guards idle reads that
+ // race turn registration, so it ends here too.
+ setInGrace(false);
+ 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.
+ onAuthorizationChanged: () => {
+ setSession(null);
+ setCanChat(null);
+ setTail(EMPTY_TAIL);
+ setTurn(null);
+ refreshAll();
+ },
+ onQueueUpdated: ({ session_id }) => {
+ if (mine(session_id)) sources.turn.refresh();
+ },
+ // Background activities are owned by S through definitions and callback
+ // runs, which neither event names: re-read on every one, coalesced.
+ onRunsUpdated: () => sources.turn.refresh(),
+ onDefinitionsUpdated: () => sources.turn.refresh(),
+ });
+ }, [api, sessionId, sources, refreshAll, sessionRef, tailLoadedRef]);
+
+ // The window coming back is a gap too.
+ useEffect(() => {
+ if (!sessionId) return undefined;
+ return onPageReactivated(refreshAll);
+ }, [sessionId, refreshAll]);
+
+ const serverRunning = turn?.foreground === 'running' || turn?.in_flight === true;
+ const working = serverRunning || inGrace;
+ const hasBackground = (turn?.background_activities.length ?? 0) > 0;
+
+ // Re-read once the send grace expires, so a quick turn whose turn.end was
+ // missed still settles.
+ useEffect(() => {
+ if (sendCount === 0) return undefined;
+ const timer = window.setTimeout(() => {
+ setInGrace(false);
+ sources.turn.refresh();
+ }, SEND_GRACE_MS);
+ return () => window.clearTimeout(timer);
+ }, [sendCount, sources]);
+
+ // Interval reconcile only while work is present and the window is visible.
+ useEffect(() => {
+ if (!sessionId || (!working && !hasBackground)) return undefined;
+ const interval = window.setInterval(() => {
+ if (document.visibilityState === 'visible') sources.turn.refresh();
+ }, hasBackground ? ACTIVITY_RECONCILE_INTERVAL_MS : WORKING_RECONCILE_INTERVAL_MS);
+ return () => window.clearInterval(interval);
+ }, [sessionId, working, hasBackground, sources]);
+
+ const noteSent = useCallback((row: WorkbenchMessage | null) => {
+ setInGrace(true);
+ setSendCount((count) => count + 1);
+ if (row && row.session_id === sessionId && row.id) {
+ sources.tail.noteLiveMerge();
+ setTail((current) => mergeRow(current, row));
+ }
+ sources.tail.refresh();
+ sources.turn.refresh();
+ }, [sources, sessionId]);
+
+ const refreshTail = useCallback(() => sources.tail.refresh(), [sources]);
+
+ return {
+ session,
+ canChat,
+ messages: tail.messages,
+ hasOlder: tail.hasOlder || !tail.loaded,
+ turn,
+ running: working,
+ noteSent,
+ refreshTail,
+ };
+}
diff --git a/ui/src/pet/usePetSetup.ts b/ui/src/pet/usePetSetup.ts
new file mode 100644
index 000000000..7e1da4a27
--- /dev/null
+++ b/ui/src/pet/usePetSetup.ts
@@ -0,0 +1,59 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { useApi } from '@/context/ApiContext';
+import { isSetupComplete } from '@/lib/setupState';
+
+export type PetSetup = 'checking' | 'pending' | 'ready';
+
+/**
+ * Whether first-run setup is complete, for the pet window. Finishing the wizard
+ * in `main` gives this window no route change and no event, so while setup is
+ * pending the pet re-reads the authoritative config (past the config cache) on
+ * every way the user comes back to it: a summon, focus, or becoming visible.
+ * `recheck` is the summon hook.
+ */
+export function usePetSetup(): { setup: PetSetup; recheck: () => void } {
+ const api = useApi();
+ const [setup, setSetup] = useState<PetSetup>('checking');
+ const requestRef = useRef(0);
+
+ // One wake often triggers several checks at once (a summon focuses the
+ // window). Finishing setup is one-way, so any check that sees it complete
+ // wins, whatever order the answers land in. An incomplete answer applies
+ // only from the latest check, and a failure only decides the first one:
+ // it never turns a known state back.
+ const check = useCallback(() => {
+ const request = ++requestRef.current;
+ return api.getConfig({ cache: false }).then(
+ (config) => {
+ if (isSetupComplete(config)) setSetup('ready');
+ else if (request === requestRef.current) setSetup((current) => (current === 'ready' ? current : 'pending'));
+ },
+ () => setSetup((current) => (current === 'checking' ? 'pending' : current)),
+ );
+ }, [api]);
+
+ useEffect(() => {
+ void check();
+ }, [check]);
+
+ useEffect(() => {
+ if (setup !== 'pending') return undefined;
+ const onFocus = () => void check();
+ const onVisibility = () => {
+ if (document.visibilityState === 'visible') void check();
+ };
+ window.addEventListener('focus', onFocus);
+ document.addEventListener('visibilitychange', onVisibility);
+ return () => {
+ window.removeEventListener('focus', onFocus);
+ document.removeEventListener('visibilitychange', onVisibility);
+ };
+ }, [setup, check]);
+
+ const recheck = useCallback(() => {
+ if (setup === 'pending') void check();
+ }, [setup, check]);
+
+ return { setup, recheck };
+}
diff --git a/ui/src/pet/useSessionSwitcher.ts b/ui/src/pet/useSessionSwitcher.ts
new file mode 100644
index 000000000..44917f324
--- /dev/null
+++ b/ui/src/pet/useSessionSwitcher.ts
@@ -0,0 +1,60 @@
+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 };
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 2de946a67..1f6276bef 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9369,19 +9369,45 @@ async def sessions_fork(session_id: str):
return jsonify(session), 201
+def _session_can_chat(conn, authorization_context, session_id: str) -> bool:
+ """Project-level chat grant for this principal on this session.
+
+ Same rule as session bootstrap: the effective project role must be editor.
+ """
+ from storage import project_access_service
+
+ return project_access_service.role_allows(
+ project_access_service.get_effective_session_role(
+ conn,
+ authorization_context,
+ session_id,
+ ),
+ "editor",
+ )
+
+
@app.route("/api/sessions/<session_id>", methods=["GET"])
def sessions_get(session_id: str):
from core.services import sessions as workbench_sessions_service
+ authorization_context = getattr(g, "authorization_context", None)
engine = _projects_engine()
try:
with engine.connect() as conn:
+ session = workbench_sessions_service.get_session(
+ conn,
+ session_id,
+ authorization_context=authorization_context,
+ )
return jsonify(
- workbench_sessions_service.get_session(
- conn,
- session_id,
- authorization_context=getattr(g, "authorization_context", None),
- )
+ {
+ **session,
+ "capabilities": {
+ "can_chat": _session_can_chat(
+ conn, authorization_context, session_id
+ ),
+ },
+ }
)
except LookupError as err:
return jsonify({"error": str(err)}), 404
@@ -9509,7 +9535,7 @@ async def sessions_bootstrap(session_id: str):
"""
from core.services import sessions as workbench_sessions_service
from core.services import settings as settings_service
- from storage import messages_service, project_access_service
+ from storage import messages_service
from vibe import api as vibe_api
from vibe import internal_client
@@ -9524,12 +9550,7 @@ async def sessions_bootstrap(session_id: str):
)
except LookupError as err:
return jsonify({"error": str(err)}), 404
- effective_role = project_access_service.get_effective_session_role(
- conn,
- authorization_context,
- session_id,
- )
- can_chat = project_access_service.role_allows(effective_role, "editor")
+ can_chat = _session_can_chat(conn, authorization_context, session_id)
messages_result = messages_service.list_session_messages(
conn,
session_id=session_id,