The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): plugin SDK pet bubble (ctx.pet.say)
Tekniumecb66f60dd17
diff --git a/apps/desktop/src/app/pet-overlay/pet-overlay-app.tsx b/apps/desktop/src/app/pet-overlay/pet-overlay-app.tsxindex a800adbd38f..82319976a16 100644--- a/apps/desktop/src/app/pet-overlay/pet-overlay-app.tsx+++ b/apps/desktop/src/app/pet-overlay/pet-overlay-app.tsx@@ -9,6 +9,7 @@ import { Mail } from '@/lib/icons'import { isSubmitEnter } from '@/lib/ime'import { $petActivity, $petInfo, setPetInfo } from '@/store/pet'import { overlayWindowSize } from '@/store/pet-overlay'+import { mirrorPetPluginMessages } from '@/store/pet-plugin-messages'import { setAwaitingResponse, setBusy } from '@/store/session'// Fallbacks mirror pet-sprite's defaults; the gateway normally sends real values.@@ -96,6 +97,7 @@ export function PetOverlayApp() {setBusy(Boolean(payload.busy))setAwaitingResponse(Boolean(payload.awaiting))setUnread(Boolean(payload.unread))+ mirrorPetPluginMessages(payload.pluginMessages)// Play a reaction on a new id (ignore the first sync, which just primes it).const reaction = payload.reaction ?? nulldiff --git a/apps/desktop/src/components/pet/floating-pet.tsx b/apps/desktop/src/components/pet/floating-pet.tsxindex f60d7c7cd2a..64d8d4fcfba 100644--- a/apps/desktop/src/components/pet/floating-pet.tsx+++ b/apps/desktop/src/components/pet/floating-pet.tsx@@ -5,6 +5,7 @@ import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'import { useOnProfileSwitch } from '@/app/hooks/use-on-profile-switch'import { useRouteOverlayActive } from '@/app/hooks/use-route-overlay-active'import { PetHeartField } from '@/components/chat/vibe-hearts'+import { PetBubble } from '@/components/pet/pet-bubble'import { persistString, storedString } from '@/lib/storage'import { $changeEventsAvailable, $petChange } from '@/store/live-sync'import {@@ -508,6 +509,22 @@ export function FloatingPet() {{/* Hearts puff off the pet; its celebrate ("yay"/jump) pose is driven byburstVibeHearts's router. */}<PetHeartField petH={petH} petW={petW} />+ {/* Plugin lines (ctx.pet.say) float above the pet, upright (outside the+ mirrored sprite wrapper) and grown toward the window's middle so a pet+ parked at an edge never pushes its bubble off-screen. Core status+ lines stay in the pop-out overlay; in-window the app is the surface. */}+ <div+ style={{+ bottom: '100%',+ marginBottom: 4,+ pointerEvents: 'none',+ position: 'absolute',+ zIndex: 2,+ ...(position.x + petW / 2 < (window.innerWidth || 800) / 2 ? { left: 0 } : { right: 0 })+ }}+ >+ <PetBubble showStatus={false} />+ </div></div>)}diff --git a/apps/desktop/src/components/pet/pet-bubble.tsx b/apps/desktop/src/components/pet/pet-bubble.tsxindex cd843f04b35..8bdcbbf7f5e 100644--- a/apps/desktop/src/components/pet/pet-bubble.tsx+++ b/apps/desktop/src/components/pet/pet-bubble.tsx@@ -3,13 +3,18 @@ import { useEffect, useState } from 'react'import { AlertCircle, Clock, type IconComponent } from '@/lib/icons'import { $petActivity, $petState, type PetState } from '@/store/pet'+import { $petPluginMessage, type PetMessageTone } from '@/store/pet-plugin-messages'/**- * Speech bubble + status glyph for the popped-out pet overlay — the- * "notification" half of the mascot. It externalizes what the agent is doing- * (Codex-style) so a glance at the desktop pet replaces switching back to the- * window. The in-window pet doesn't show it (the app itself is the surface);- * only the overlay renders it.+ * Speech bubble + status glyph for the pet — the "notification" half of the+ * mascot. It externalizes what the agent is doing (Codex-style) so a glance at+ * the desktop pet replaces switching back to the window. The core status lines+ * show only in the popped-out overlay (`showStatus`); in-window the app itself+ * is the surface, so the in-window pet renders the bubble for plugin lines only.+ *+ * Plugin lines (`ctx.pet.say`, see store/pet-plugin-messages) share the bubble:+ * the newest live line shows with its plugin's name as a small label, unless+ * the agent is in an error or waiting-on-you state — those keep the bubble.** Text is derived purely from the same `$petState` / `$petActivity` the sprite* already reacts to, so it never drifts from the animation. The bubble is shown@@ -17,7 +22,7 @@ import { $petActivity, $petState, type PetState } from '@/store/pet'* done/error beat / waiting on the user) and is hidden at plain idle.*/-type Tone = 'error' | 'wait'+type Tone = PetMessageToneinterface Spec {lines: string[]@@ -70,9 +75,28 @@ const SPECS: Partial<Record<PetState, Spec>> = {const TONE_COLOR: Record<Tone, string> = {error: 'var(--ui-red)',+ info: 'currentColor',wait: 'var(--ui-yellow)'}+const TONE_GLYPH: Partial<Record<Tone, IconComponent>> = { error: AlertCircle, wait: Clock }++// Core states that outrank a plugin line: the pet is flagging trouble or the+// turn is paused on the user, and a plugin must not talk over that.+const PRIORITY_TONES: ReadonlySet<Tone | undefined> = new Set(['error', 'wait'])++const BUBBLE_SURFACE = {+ // Solid, theme-driven surface (the prior --ui-bg-card mixes in+ // `transparent`, so the bubble was see-through).+ background: 'var(--ui-bg-elevated)',+ border: '1px solid var(--ui-stroke-secondary)',+ boxShadow: '0 4px 14px rgba(0,0,0,0.22)',+ color: 'var(--foreground)',+ fontSize: 11,+ fontWeight: 500,+ pointerEvents: 'none'+} as const+// Random pick that avoids repeating the line we're already showing.function pick(lines: string[], prev: string): string {if (lines.length <= 1) {@@ -88,9 +112,16 @@ function pick(lines: string[], prev: string): string {return next}-export function PetBubble() {+export interface PetBubbleProps {+ /** Render the core status lines (working…, your turn). The overlay passes+ * true; the in-window pet leaves them to the app and shows plugin lines only. */+ showStatus?: boolean+}++export function PetBubble({ showStatus = true }: PetBubbleProps = {}) {const state = useStore($petState)const activity = useStore($petActivity)+ const pluginLine = useStore($petPluginMessage)const [line, setLine] = useState('')// Finish beats are carried by the sprite/mail icon; idle only speaks up when@@ -124,7 +155,52 @@ export function PetBubble() {const spec = specKey ? SPECS[specKey] : null- if (!spec) {+ if (pluginLine && !PRIORITY_TONES.has(spec?.tone)) {+ const Glyph = TONE_GLYPH[pluginLine.tone]++ return (+ <div+ data-pet-plugin={pluginLine.pluginId}+ data-slot="pet-plugin-bubble"+ style={{+ ...BUBBLE_SURFACE,+ borderRadius: 10,+ display: 'inline-flex',+ flexDirection: 'column',+ gap: 3,+ lineHeight: 1.3,+ maxWidth: 220,+ padding: '5px 8px',+ width: 'max-content'+ }}+ >+ <span+ style={{+ color: 'var(--ui-text-secondary, var(--muted-foreground))',+ fontSize: 9,+ fontWeight: 600,+ letterSpacing: 0.2,+ lineHeight: 1,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap'+ }}+ >+ {pluginLine.pluginName}+ </span>+ <span style={{ alignItems: 'flex-start', display: 'inline-flex', gap: 5, overflowWrap: 'anywhere' }}>+ {Glyph && (+ <span style={{ display: 'inline-flex', flex: 'none', paddingTop: 1 }}>+ <Glyph style={{ color: TONE_COLOR[pluginLine.tone], height: 12, width: 12 }} />+ </span>+ )}+ {pluginLine.text}+ </span>+ </div>+ )+ }++ if (!spec || !showStatus) {return null}@@ -135,22 +211,14 @@ export function PetBubble() {return (<divstyle={{+ ...BUBBLE_SURFACE,alignItems: 'center',- // Solid, theme-driven surface (the prior --ui-bg-card mixes in- // `transparent`, so the bubble was see-through).- background: 'var(--ui-bg-elevated)',- border: '1px solid var(--ui-stroke-secondary)',borderRadius: hasText ? 10 : 999,- boxShadow: '0 4px 14px rgba(0,0,0,0.22)',- color: 'var(--foreground)',display: 'inline-flex',- fontSize: 11,- fontWeight: 500,gap: hasText ? 5 : 0,lineHeight: 1,// Glyph-only bubbles collapse to a tight, symmetric badge.padding: hasText ? '5px 8px' : 5,- pointerEvents: 'none',whiteSpace: 'nowrap'}}>diff --git a/apps/desktop/src/contrib/plugin-pet.test.tsx b/apps/desktop/src/contrib/plugin-pet.test.tsxnew file mode 100644index 00000000000..500007c02ed--- /dev/null+++ b/apps/desktop/src/contrib/plugin-pet.test.tsx@@ -0,0 +1,295 @@+import { act, cleanup, render, screen } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { FloatingPet } from '@/components/pet/floating-pet'+import { PetBubble } from '@/components/pet/pet-bubble'+import { $petActivity, setPetInfo } from '@/store/pet'+import { $petOverlayActive, popInPet, popOutPet } from '@/store/pet-overlay'+import { $petPluginMessages, mirrorPetPluginMessages, resetPetPluginMessages } from '@/store/pet-plugin-messages'++import { createPluginContext } from './plugin'+import { publishPlugin } from './plugins-store'++// The in-window pet's gateway/theme plumbing is unrelated to the bubble; the+// sprite is a canvas jsdom can't paint, so stand it in with the same a11y+// label the real one carries.+vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({+ useGatewayRequest: () => ({ requestGateway: vi.fn(async () => null) })+}))+vi.mock('@/themes/context', () => ({ useTheme: () => ({ resolvedMode: 'dark' }) }))+vi.mock('@/components/pet/pet-sprite', () => ({+ PetSprite: () => <canvas aria-label="Boba pet" />,+ roamWalkRow: () => ({ mirror: false, row: undefined })+}))++const PET = {+ displayName: 'Boba',+ enabled: true,+ frameH: 208,+ frameW: 192,+ scale: 0.33,+ spritesheetBase64: 'stub'+}++// Each test gets its own plugin id, so per-plugin rate windows never leak+// between tests; afterEach resets the store so a live line cannot leak.+let n = 0++function plugin(name = 'Pet Wallet') {+ const id = `pet-wallet-${++n}`+ const disposers: Array<() => void> = []+ publishPlugin({ id, kind: 'disk', name, status: 'loaded' })+ const ctx = createPluginContext(id, dispose => disposers.push(dispose))++ return { ctx, id, unload: () => act(() => disposers.splice(0).forEach(dispose => dispose())) }+}++function mountPet() {+ return render(+ <MemoryRouter>+ <FloatingPet />+ </MemoryRouter>+ )+}++const bubble = () => document.querySelector('[data-slot="pet-plugin-bubble"]')++describe('ctx.pet — plugin lines in the core pet bubble', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ $petActivity.set({})+ $petOverlayActive.set(false)+ setPetInfo(PET)+ })++ afterEach(() => {+ cleanup()+ resetPetPluginMessages()+ vi.clearAllTimers()+ vi.useRealTimers()+ setPetInfo({ enabled: false })+ })++ it('shows the line above the in-window pet, labelled with the plugin name', () => {+ const { ctx, id } = plugin()+ mountPet()+ expect(bubble()).toBeNull()++ act(() => void ctx.pet.say('DeepSeek ¥12.40 left'))++ expect(screen.getByText('DeepSeek ¥12.40 left')).toBeTruthy()+ expect(bubble()?.getAttribute('data-pet-plugin')).toBe(id)+ expect(bubble()?.textContent).toContain('Pet Wallet')+ expect(ctx.pet.visible.get()).toBe(true)+ })++ it('clears the line when its TTL runs out (default 6 s, clamped)', () => {+ const { ctx } = plugin()+ mountPet()++ act(() => void ctx.pet.say('short', { ttlMs: 2_000 }))+ expect(screen.queryByText('short')).toBeTruthy()+ act(() => void vi.advanceTimersByTime(1_999))+ expect(screen.queryByText('short')).toBeTruthy()+ act(() => void vi.advanceTimersByTime(1))+ expect(screen.queryByText('short')).toBeNull()++ act(() => void ctx.pet.say('default'))+ act(() => void vi.advanceTimersByTime(5_999))+ expect(screen.queryByText('default')).toBeTruthy()+ act(() => void vi.advanceTimersByTime(1))+ expect(screen.queryByText('default')).toBeNull()++ // A huge TTL is capped at 30 s — a plugin can't pin the bubble forever.+ act(() => void ctx.pet.say('forever', { ttlMs: 10 * 60_000 }))+ act(() => void vi.advanceTimersByTime(30_000))+ expect(screen.queryByText('forever')).toBeNull()+ })++ it('clears the line through the returned disposer and through clear(id)', () => {+ const { ctx } = plugin()+ mountPet()++ let dispose = () => {}+ act(() => void (dispose = ctx.pet.say('bye soon')))+ act(() => dispose())+ expect(screen.queryByText('bye soon')).toBeNull()++ act(() => void ctx.pet.say('keyed', { id: 'balance' }))+ act(() => ctx.pet.clear('balance'))+ expect(bubble()).toBeNull()+ })++ it('replaces a line in place when the same id is said again', () => {+ const { ctx } = plugin()+ mountPet()++ let first = () => {}+ act(() => void (first = ctx.pet.say('balance ¥12', { id: 'balance' })))+ act(() => void ctx.pet.say('balance ¥11', { id: 'balance' }))+ expect(screen.queryByText('balance ¥12')).toBeNull()+ expect(screen.getByText('balance ¥11')).toBeTruthy()++ // The first line's disposer must not retire its replacement.+ act(() => first())+ expect(screen.getByText('balance ¥11')).toBeTruthy()+ })++ it('clears every line a plugin has up when the plugin unloads or is disabled', () => {+ const a = plugin('Pet Wallet')+ const b = plugin('Other')+ mountPet()++ act(() => void b.ctx.pet.say('from other', { ttlMs: 30_000 }))+ act(() => void a.ctx.pet.say('from wallet', { ttlMs: 30_000 }))+ expect(screen.getByText('from wallet')).toBeTruthy()++ a.unload()++ expect(screen.queryByText('from wallet')).toBeNull()+ // Only the unloaded plugin's lines go; another plugin's line resurfaces.+ expect(screen.getByText('from other')).toBeTruthy()+ })++ it('renders plain text only: markup stays literal, control chars go, length is capped', () => {+ const { ctx } = plugin('<b>Evil</b> Wallet')+ mountPet()++ act(() => void ctx.pet.say('<img src=x onerror="alert(1)"> hi\u202e\n\tthere'))+ expect(bubble()?.querySelector('img, b')).toBeNull()+ expect(screen.getByText('<img src=x onerror="alert(1)"> hi there')).toBeTruthy()+ expect(bubble()?.textContent).toContain('<b>Evil</b> Wallet')++ act(() => void ctx.pet.say('x'.repeat(500), { id: 'long' }))+ const shown = screen.getByText(/^x+…$/).textContent ?? ''+ expect(shown.length).toBe(120)++ // Nothing to say → nothing shown, and a no-op disposer.+ act(() => void ctx.pet.say(' \n ', { id: 'blank' }))+ expect(screen.queryByText(' ')).toBeNull()+ })++ it('shows nothing while the pet is hidden or turned off', () => {+ const { ctx } = plugin()+ setPetInfo({ enabled: false })+ mountPet()++ act(() => void ctx.pet.say('anyone there?', { ttlMs: 30_000 }))+ expect(screen.queryByText('anyone there?')).toBeNull()+ expect(ctx.pet.visible.get()).toBe(false)++ // Turning the pet on while the line is live shows it — the host gates on+ // the user's pet setting, not the plugin.+ act(() => setPetInfo(PET))+ expect(screen.getByText('anyone there?')).toBeTruthy()+ act(() => setPetInfo({ enabled: false }))+ expect(screen.queryByText('anyone there?')).toBeNull()+ })++ it('rate-limits a chatty plugin', () => {+ const { ctx } = plugin()+ mountPet()+ vi.spyOn(console, 'warn').mockImplementation(() => {})++ act(() => {+ for (let i = 0; i < 10; i++) {+ ctx.pet.say(`line ${i}`, { id: `l${i % 3}` })+ }+ })+ expect(screen.getByText('line 9')).toBeTruthy()++ act(() => void ctx.pet.say('one too many'))+ expect(screen.queryByText('one too many')).toBeNull()++ act(() => void vi.advanceTimersByTime(10_000))+ act(() => void ctx.pet.say('window reopened'))+ expect(screen.getByText('window reopened')).toBeTruthy()+ })+})++describe('PetBubble — core status keeps priority', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ $petActivity.set({})+ })++ afterEach(() => {+ cleanup()+ resetPetPluginMessages()+ vi.clearAllTimers()+ vi.useRealTimers()+ $petActivity.set({})+ })++ it('lets error / waiting-on-you states win over a plugin line, then yields back', () => {+ const { ctx } = plugin()+ render(<PetBubble />)++ act(() => void ctx.pet.say('balance ¥12', { ttlMs: 30_000 }))+ expect(screen.getByText('balance ¥12')).toBeTruthy()++ act(() => $petActivity.set({ error: true }))+ expect(screen.queryByText('balance ¥12')).toBeNull()++ act(() => $petActivity.set({ awaitingInput: true }))+ expect(screen.queryByText('balance ¥12')).toBeNull()++ act(() => $petActivity.set({}))+ expect(screen.getByText('balance ¥12')).toBeTruthy()+ })++ it('shows a plugin tone glyph and leaves the core status line to the overlay', () => {+ const { ctx } = plugin()+ render(<PetBubble showStatus={false} />)++ // In-window (showStatus=false) a busy turn says nothing on its own…+ act(() => $petActivity.set({ busy: true }))+ expect(document.body.textContent).toBe('')++ // …but a plugin line still shows, with its tone glyph.+ act(() => void ctx.pet.say('quota low', { tone: 'wait' }))+ expect(screen.getByText('quota low')).toBeTruthy()+ expect(bubble()?.querySelector('svg')).toBeTruthy()+ })+})++describe('pop-out overlay', () => {+ afterEach(() => {+ popInPet()+ cleanup()+ resetPetPluginMessages()+ delete (window as { hermesDesktop?: unknown }).hermesDesktop+ setPetInfo({ enabled: false })+ })++ it('pushes live plugin lines to the overlay window, which renders them in its bubble', async () => {+ // The overlay is a separate gateway-less window: the main renderer pushes+ // its pet state over IPC. Capture that push and replay it the way the+ // overlay's onState handler does.+ const pushState = vi.fn()++ ;(window as { hermesDesktop?: unknown }).hermesDesktop = {+ petOverlay: { close: vi.fn(async () => ({ ok: true })), open: vi.fn(async () => ({ ok: true })), pushState }+ }+ setPetInfo(PET)+ popOutPet({ height: 70, width: 64, x: 10, y: 10 })++ const { ctx, id } = plugin()+ act(() => void ctx.pet.say('popped-out hello', { ttlMs: 30_000 }))++ const last = pushState.mock.calls.at(-1)?.[0] as { pluginMessages?: unknown[] }+ expect(last.pluginMessages).toEqual([expect.objectContaining({ pluginId: id, text: 'popped-out hello' })])++ // Overlay side: adopt the pushed list verbatim and render the core bubble.+ const pushed = structuredClone(last.pluginMessages)+ resetPetPluginMessages()+ act(() => mirrorPetPluginMessages(pushed))+ render(<PetBubble />)+ expect(screen.getByText('popped-out hello')).toBeTruthy()++ // A malformed push clears rather than throws.+ act(() => mirrorPetPluginMessages(undefined))+ expect($petPluginMessages.get()).toEqual([])+ })+})diff --git a/apps/desktop/src/contrib/plugin.ts b/apps/desktop/src/contrib/plugin.tsindex c3909e24b61..93fa7c3725f 100644--- a/apps/desktop/src/contrib/plugin.ts+++ b/apps/desktop/src/contrib/plugin.ts@@ -12,12 +12,17 @@* through the plugin host loader (next phase); this is that seam.*/+import type { ReadableAtom } from 'nanostores'+import { pluginRest, type PluginRestOptions, pluginSocket } from '@/hermes'import { createPluginI18n, type PluginI18n } from '@/i18n'import { readKey, writeKey } from '@/lib/storage'import { dispatchPluginNativeNotification, type PluginNativeNotificationInput } from '@/store/native-notifications'+import { $petActive } from '@/store/pet'+import { clearPetMessages, type PetSayOptions, sayPetMessage } from '@/store/pet-plugin-messages'import { type GatewayEventListener, onGatewayEvent } from './events'+import { $pluginRecords } from './plugins-store'import { registry } from './registry'import { type PluginSettingsPage, settingsPageContribution } from './settings-pages'@@ -27,6 +32,7 @@ import type { Contribution } from './types'export type { PluginRestOptions } from '@/hermes'export type { HermesOpenTarget } from '@/lib/hermes-open-target'export type { PluginNativeNotificationInput, PluginNotificationAction } from '@/store/native-notifications'+export type { PetMessageTone, PetSayOptions } from '@/store/pet-plugin-messages'/** A contribution as a plugin author writes it — provenance + id scoping are* the host's job, so those fields are off-limits here. */@@ -70,6 +76,24 @@ export interface PluginOs {writeClipboard: (text: string) => Promise<boolean>}+/** The pet door: short lines in the core pet's speech bubble, attributed to+ * this plugin, instead of locating the pet in the app DOM and drawing over+ * it. The host renders them in the in-window pet and the pop-out overlay;+ * they show only while the user has a pet visible. */+export interface PluginPet {+ /** Show one plain-text line (no HTML; control characters stripped, capped+ * at 120 chars) with this plugin's name as a small label. Lasts `ttlMs`+ * (default 6 s, clamped 1–30 s); the same `id` replaces in place. Core+ * error / waiting-on-you states keep priority over it. Rate-limited per+ * plugin. Returns a disposer that removes the line early. */+ say: (text: string, options?: PetSayOptions) => () => void+ /** Remove one line by `id`, or every line this plugin has up. */+ clear: (id?: string) => void+ /** True while a pet is installed and shown (in-window or popped out). A+ * plugin can fall back to its own chip or pane while this is false. */+ visible: ReadableAtom<boolean>+}+export interface PluginFileDialogOptions {defaultPath?: stringfilters?: Array<{ extensions: string[]; name: string }>@@ -125,6 +149,10 @@ export interface PluginContext {* manager, clipboard — attributed to this plugin, result-shaped (never* throws for a missing capability). */os: PluginOs+ /** The pet door: lines in the core pet's speech bubble, attributed to this+ * plugin and cleared when it unloads. Feature-detect on older hosts:+ * `ctx.pet?.say(...)`. */+ pet: PluginPet/** Plugin-scoped persistence. */storage: PluginStorage/** Plugin-scoped i18n: ship + register locale bundles under this plugin,@@ -222,6 +250,26 @@ function createPluginOs(pluginId: string): PluginOs {}}+// Lines are attributed by the inventory name the loader published before+// register() ran; the id is the fallback. Every line this plugin still has up+// is cleared with it on unload/disable (tracked on first use).+function createPluginPet(pluginId: string, track: (dispose: () => void) => () => void): PluginPet {+ let tracked = false++ return {+ clear: id => clearPetMessages(pluginId, id),+ say: (text, options) => {+ if (!tracked) {+ tracked = true+ track(() => clearPetMessages(pluginId))+ }++ return sayPetMessage(pluginId, $pluginRecords.get()[pluginId]?.name ?? pluginId, text, options)+ },+ visible: $petActive+ }+}+/** Timers and DOM listeners a plugin takes out through `ctx`, retired as ONE* tracked disposer. A fired timeout drops out of the set on its own, so a* long-lived plugin firing many one-shots does not accumulate cleanups. */@@ -300,6 +348,7 @@ export function createPluginContext(pluginId: string, onDispose?: (dispose: () =rest: <T>(path: string, opts?: PluginRestOptions) => pluginRest<T>(pluginId, path, opts),socket: (path, onMessage) => track(pluginSocket(pluginId, path, onMessage)),os: createPluginOs(pluginId),+ pet: createPluginPet(pluginId, track),storage: createPluginStorage(pluginId),i18n: createPluginI18n(pluginId, track)}diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 98e532ad965..fc3b3e5fdb6 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -1882,11 +1882,14 @@ export { Tip, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@export type { GatewayEventListener } from '@/contrib/events'export type {HermesPlugin,+ PetMessageTone,+ PetSayOptions,PluginContext,PluginContribution,PluginNativeNotificationInput,PluginNotificationAction,PluginOs,+ PluginPet,PluginRestOptions,PluginSettingsPage,PluginSettingsSubpage,diff --git a/apps/desktop/src/store/pet-overlay.ts b/apps/desktop/src/store/pet-overlay.tsindex 532634adcdf..d47f67023fb 100644--- a/apps/desktop/src/store/pet-overlay.ts+++ b/apps/desktop/src/store/pet-overlay.ts@@ -3,6 +3,7 @@ import { atom } from 'nanostores'import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'import { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage'import { $petActivity, $petInfo, $petUnread, clearPetUnread, type PetActivity, type PetInfo } from '@/store/pet'+import { $petPluginMessages, type PetPluginMessage } from '@/store/pet-plugin-messages'/*** Controller for the pop-out pet overlay (main-renderer side).@@ -48,6 +49,8 @@ export interface PetOverlayStatePayload {unread: boolean/** Latest reaction — bumping its id forwards a burst to the overlay. */reaction: PetReaction | null+ /** Live plugin bubble lines (`ctx.pet.say`); this renderer owns their expiry. */+ pluginMessages?: PetPluginMessage[]}export type PetOverlayControl =@@ -147,7 +150,8 @@ function currentPayload(): PetOverlayStatePayload {busy: PRIMARY_SESSION_VIEW.$busy.get(),awaiting: PRIMARY_SESSION_VIEW.$awaitingResponse.get(),unread: $petUnread.get(),- reaction: $petReaction.get()+ reaction: $petReaction.get(),+ pluginMessages: $petPluginMessages.get()}}@@ -184,7 +188,8 @@ function openOverlay(request: PetOverlayOpenRequest): void {PRIMARY_SESSION_VIEW.$busy.subscribe(pushNow),PRIMARY_SESSION_VIEW.$awaitingResponse.subscribe(pushNow),$petUnread.subscribe(pushNow),- $petReaction.subscribe(pushNow)+ $petReaction.subscribe(pushNow),+ $petPluginMessages.subscribe(pushNow)]}diff --git a/apps/desktop/src/store/pet-plugin-messages.ts b/apps/desktop/src/store/pet-plugin-messages.tsnew file mode 100644index 00000000000..406d19be289--- /dev/null+++ b/apps/desktop/src/store/pet-plugin-messages.ts@@ -0,0 +1,203 @@+import { atom, computed } from 'nanostores'++/**+ * Plugin lines for the pet's speech bubble — the store behind `ctx.pet.say`.+ *+ * A plugin hands the host a short plain-text line; the host owns where and+ * when it shows (the core `PetBubble`, in-window and in the pop-out overlay),+ * so no plugin ever has to locate the pet in the app DOM or float its own+ * overlay over it. Every line is:+ *+ * - plain text: control characters stripped, whitespace collapsed, capped at+ * `PET_MESSAGE_MAX_CHARS` (rendered as a React text node, never HTML);+ * - attributed: it carries the plugin id and its display name, which the+ * bubble prints as a small label;+ * - short-lived: a TTL (default `PET_MESSAGE_DEFAULT_TTL_MS`, clamped) retires+ * it, and the disposer `say` returns retires it early;+ * - bounded: each plugin holds at most `PET_MESSAGE_MAX_PER_PLUGIN` live lines+ * and gets `PET_MESSAGE_RATE_LIMIT` says per `PET_MESSAGE_RATE_WINDOW_MS`.+ *+ * The bubble shows the newest live line. The owning plugin's context clears+ * all of its lines when it unloads or is disabled.+ */++export type PetMessageTone = 'error' | 'info' | 'wait'++export interface PetSayOptions {+ /** Stable key within your plugin. Saying again with the same id replaces+ * that line in place (a ticking counter, a refreshed balance). */+ id?: string+ /** Visual tone: `info` (default, no glyph), `wait` (clock), `error` (alert). */+ tone?: PetMessageTone+ /** How long the line stays up, in ms. Clamped to 1 s – 30 s; default 6 s. */+ ttlMs?: number+}++/** One live plugin line. Plain data so it can cross to the overlay window. */+export interface PetPluginMessage {+ /** `<pluginId>:<id>` — unique across plugins. */+ key: string+ pluginId: string+ /** Display label (the plugin's name, else its id). */+ pluginName: string+ text: string+ tone: PetMessageTone+ /** Monotonic; the bubble shows the highest. */+ seq: number+}++export const PET_MESSAGE_MAX_CHARS = 120+export const PET_MESSAGE_LABEL_MAX_CHARS = 32+export const PET_MESSAGE_DEFAULT_TTL_MS = 6_000+export const PET_MESSAGE_MIN_TTL_MS = 1_000+export const PET_MESSAGE_MAX_TTL_MS = 30_000+export const PET_MESSAGE_MAX_PER_PLUGIN = 3+export const PET_MESSAGE_RATE_LIMIT = 10+export const PET_MESSAGE_RATE_WINDOW_MS = 10_000++const TONES: ReadonlySet<PetMessageTone> = new Set(['error', 'info', 'wait'])++export const $petPluginMessages = atom<PetPluginMessage[]>([])++/** The line the bubble shows: the newest live one, or null. */+export const $petPluginMessage = computed($petPluginMessages, list =>+ list.reduce<null | PetPluginMessage>((top, m) => (!top || m.seq > top.seq ? m : top), null)+)++const timers = new Map<string, ReturnType<typeof setTimeout>>()+const sayLog = new Map<string, number[]>()+let seq = 0++// C0/C1 control characters and the bidi overrides/isolates, which could make+// a line render as something other than what the plugin passed.+// eslint-disable-next-line no-control-regex+const UNSAFE_CHARS = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g++/** Normalise arbitrary input to one capped line of plain text ('' = nothing to say). */+export function sanitizePetText(value: unknown, max = PET_MESSAGE_MAX_CHARS): string {+ const text = String(value ?? '')+ .replace(UNSAFE_CHARS, ' ')+ .replace(/\s+/g, ' ')+ .trim()++ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text+}++function clampTtl(ttlMs: unknown): number {+ const n = typeof ttlMs === 'number' && Number.isFinite(ttlMs) ? ttlMs : PET_MESSAGE_DEFAULT_TTL_MS++ return Math.min(PET_MESSAGE_MAX_TTL_MS, Math.max(PET_MESSAGE_MIN_TTL_MS, Math.round(n)))+}++function allowSay(pluginId: string, now: number): boolean {+ const recent = (sayLog.get(pluginId) ?? []).filter(at => now - at < PET_MESSAGE_RATE_WINDOW_MS)++ if (recent.length >= PET_MESSAGE_RATE_LIMIT) {+ sayLog.set(pluginId, recent)++ return false+ }++ recent.push(now)+ sayLog.set(pluginId, recent)++ return true+}++function remove(key: string, expectedSeq?: number): void {+ const list = $petPluginMessages.get()+ const hit = list.find(m => m.key === key)++ // A disposer from a replaced line must not retire its replacement.+ if (!hit || (expectedSeq !== undefined && hit.seq !== expectedSeq)) {+ return+ }++ clearTimeout(timers.get(key))+ timers.delete(key)+ $petPluginMessages.set(list.filter(m => m.key !== key))+}++const noop = () => {}++/**+ * Show `text` in the pet bubble on behalf of `pluginId`. Returns a disposer+ * that removes the line early (idempotent; a no-op once replaced or expired).+ * Empty text, or a say over the plugin's rate limit, shows nothing.+ */+export function sayPetMessage(+ pluginId: string,+ pluginName: string,+ text: unknown,+ options: PetSayOptions = {}+): () => void {+ const clean = sanitizePetText(text)++ if (!clean) {+ return noop+ }++ if (!allowSay(pluginId, Date.now())) {+ console.warn(`[plugins] ${pluginId}: pet.say rate limit hit — line dropped`)++ return noop+ }++ const localId = sanitizePetText(options.id ?? '', 64) || `m${seq + 1}`+ const key = `${pluginId}:${localId}`+ const tone: PetMessageTone = options.tone && TONES.has(options.tone) ? options.tone : 'info'++ const message: PetPluginMessage = {+ key,+ pluginId,+ pluginName: sanitizePetText(pluginName, PET_MESSAGE_LABEL_MAX_CHARS) || pluginId,+ seq: ++seq,+ text: clean,+ tone+ }++ clearTimeout(timers.get(key))++ let next = [...$petPluginMessages.get().filter(m => m.key !== key), message]+ const own = next.filter(m => m.pluginId === pluginId)++ // Keep each plugin to its newest few lines; evict the oldest.+ for (const stale of own.slice(0, Math.max(0, own.length - PET_MESSAGE_MAX_PER_PLUGIN))) {+ clearTimeout(timers.get(stale.key))+ timers.delete(stale.key)+ next = next.filter(m => m.key !== stale.key)+ }++ $petPluginMessages.set(next)+ timers.set(+ key,+ setTimeout(() => remove(key, message.seq), clampTtl(options.ttlMs))+ )++ return () => remove(key, message.seq)+}++/** Remove one of a plugin's lines by its `id`, or every line it owns. */+export function clearPetMessages(pluginId: string, id?: string): void {+ const prefix = `${pluginId}:`+ const key = id === undefined ? null : `${prefix}${sanitizePetText(id, 64)}`++ for (const m of $petPluginMessages.get()) {+ if (m.pluginId === pluginId && (key === null || m.key === key)) {+ remove(m.key)+ }+ }+}++/** Overlay window: adopt the main renderer's list verbatim (it owns expiry). */+export function mirrorPetPluginMessages(list: unknown): void {+ $petPluginMessages.set(Array.isArray(list) ? (list as PetPluginMessage[]) : [])+}++/** Test seam: drop every line, timer, and rate-limit window. */+export function resetPetPluginMessages(): void {+ timers.forEach(clearTimeout)+ timers.clear()+ sayLog.clear()+ $petPluginMessages.set([])+}diff --git a/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md b/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.mdindex 6e3867ec092..707f5879d75 100644--- a/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md+++ b/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md@@ -127,6 +127,13 @@ The ONLY import surface is `@hermes/plugin-sdk` (plus `react` /`ctx.os.openExternal(url)`, `ctx.os.revealPath(path)`, and`ctx.os.writeClipboard(text)` resolve `false` (never throw) when thecapability isn't available.+- `ctx.pet.say(text, { id?, tone?: 'info'|'wait'|'error', ttlMs? })` — a short+ plain-text line in the core pet's speech bubble (in-window and popped out),+ labelled with your plugin name; returns a disposer. 120-char cap, TTL default+ 6 s (1–30 s), same `id` replaces, rate-limited, cleared on unload; core+ error/waiting states win; nothing shows without a visible pet+ (`ctx.pet.visible`). `ctx.pet.clear(id?)`. Never locate the pet canvas in+ the DOM or overlay it yourself.- `ctx.i18n.register({ en, ja, ... })` — ship your OWN locale bundles, scopedto your plugin (never edit core `en.ts`). Values are literal strings orinterpolator functions; nested trees are addressed by dot-path. Read themdiff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex 4277c1fe8e6..a54df00fe3f 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -198,6 +198,8 @@ interface PluginContext {addEventListener: (target: EventTarget, type: string, listener: EventListener, options?: AddEventListenerOptions | boolean) => () => void/** The curated OS door: native notification, open-external, reveal-in-file-manager, clipboard. */os: PluginOs+ /** Lines in the core pet's speech bubble, attributed to this plugin (see "Pet bubble"). */+ pet: PluginPet/** Plugin-scoped JSON persistence (keys live under `hermes.plugin.<id>.`). */storage: PluginStorage}@@ -543,7 +545,8 @@ A multi-session plugin keeps its per-session state on its side (which sessionits panel is editing) and passes that id here; the bus guarantees oneplugin write can never land in another session's composer.-**Migrating off DOM reach-in** (the held catalog plugins that motivated this API):+**Migrating off DOM reach-in** (the held catalog plugins that motivated this API+and its siblings; the pet-wallet row uses the [pet bubble](#pet-bubble) door):| Plugin | Was | Now ||---|---|---|@@ -552,6 +555,7 @@ plugin write can never land in another session's composer.| prompt-enhancer (#116031) | walks the editor's child nodes to serialize, rebuilds chip DOM, `replaceChildren` + synthetic `InputEvent` | `const draft = await host.composer.getDraft(sid)` → transform → `await host.composer.setDraft(sid, enhanced)` (chips hydrate app-side); revert is another `setDraft` || memory-review (#115966) | `host.request('slash.exec', { session_id, command })` for `/memory …` — already SDK-only | optional: `host.composer.insertText(sid, '/memory pending', { mode: 'prefix' })` to seat the command for the user instead of executing it || intelligent-tool-break (#115964) | "Message" button only toasts "type /break" (no composer write) | `host.composer.setDraft(host.state.focusedSessionId.get(), '/break ')` then `host.composer.focus(null)` restores the intended behaviour |+| pet-wallet (#135178) | `document.querySelector('canvas[aria-label$=" pet"]')` to find the core pet, a `position:fixed; z-index:9999` overlay on `document.body` that follows it every frame, document-wide capture-phase pointer listeners | `ctx.pet.say(text, { id: 'balance', tone?, ttlMs? })` — the core bubble shows it over the pet, in-window and popped out, labelled with the plugin name; `ctx.pet.visible` tells you when there is no pet so you can fall back to your status-bar chip |`sessionId` in the table is the id the plugin's UI is bound to; for a composerslot render it is `host.state.focusedSessionId.get()`.@@ -1085,6 +1089,9 @@ ctx.os.notify({ title, body?, silent?, icon?, activate?, onActivate?, actions? }ctx.os.openExternal(url) // OS default handler (browser, mail, spotify:) → Promise<boolean>ctx.os.revealPath(path) // reveal in Finder / Explorer → Promise<boolean>ctx.os.writeClipboard(text) // system clipboard → Promise<boolean>+ctx.pet.say(text, { id?, tone?, ttlMs? }) // line in the core pet's speech bubble → disposer+ctx.pet.clear(id?) // drop one line (or all of yours)+ctx.pet.visible // ReadableAtom<boolean> — is a pet on screen?host.navigate('/route') // hash-route navigationhost.openSession(id, { profile?, intent? }) // open a stored session core-style;// profile: soft-swap to that profile's backend first@@ -1238,6 +1245,70 @@ The other doors (`openExternal`, `revealPath`, `writeClipboard`) resolve`false` instead of throwing when the capability isn't available (older desktopshell, plain browser) — branch on the result rather than sniffing the bridge.+### Pet bubble — `ctx.pet` {#pet-bubble}++The core pet (the petdex mascot, in-window or popped out into its own OS+window) has a speech bubble. `ctx.pet` lets a plugin put a short line in it,+so you never have to find the pet in the app DOM or float your own overlay+over it:++```ts+register(ctx) {+ // Shows "DeepSeek ¥12.40 left" over the pet for 8 s, labelled "Pet Wallet".+ const dispose = ctx.pet.say('DeepSeek ¥12.40 left', { id: 'balance', ttlMs: 8000 })++ // Same id → replaces the line in place (a refreshed balance, a countdown).+ ctx.pet.say('DeepSeek ¥11.90 left', { id: 'balance' })++ // Tones: 'info' (default), 'wait' (clock glyph), 'error' (alert glyph).+ ctx.pet.say('Codex 5h quota at 90%', { id: 'quota', tone: 'wait' })++ dispose() // remove early, or+ ctx.pet.clear('quota') // by id, or ctx.pet.clear() for all of yours++ // No pet on screen? Fall back to your own status-bar chip or pane.+ const visible = ctx.pet.visible.get()+}+```++```ts+interface PluginPet {+ say(text: string, options?: { id?: string; tone?: 'info' | 'wait' | 'error'; ttlMs?: number }): () => void+ clear(id?: string): void+ visible: ReadableAtom<boolean>+}+```++What the host guarantees, so you don't have to:++- **Plain text.** Control characters and bidi overrides are stripped,+ whitespace collapses to one line, and the text is capped at 120 characters.+ It renders as a text node; markup shows literally.+- **Attributed.** Your plugin's name (from the Plugins inventory) is printed+ above the line, so the user can tell your words from the pet's.+- **Short-lived.** Each line expires after `ttlMs` (default 6 s, clamped to+ 1–30 s). Re-`say` with the same `id` to keep a value up. At most 3 lines per+ plugin are live (the oldest is evicted) and the bubble shows the newest+ line from any plugin.+- **Rate-limited.** 10 `say` calls per plugin per 10 s; extra calls are dropped+ with a console warning and return a no-op disposer.+- **Core first.** When the agent hits an error or is waiting on the user, the+ core status bubble wins; your line shows again once that clears (if it+ hasn't expired).+- **The user's pet setting wins.** If no pet is adopted, or it is turned off,+ nothing shows. `ctx.pet.visible` lets you branch on that.+- **Cleaned up with you.** Disabling, unloading, or hot-reloading your plugin+ removes every line it still has up.++In-window, the bubble appears only for plugin lines (the app itself shows the+agent's status). In the popped-out overlay, plugin lines share the bubble with+the core status lines. The overlay is a separate window that loads no plugin+code; the main window sends it the live lines with the rest of the pet state.++Pointer input on the pet (drag, shift-click pop-out, overlay click) belongs to+the host and has no plugin hook. Use a palette command, a status-bar item, or+your own pane for actions.+### Desktop appearance settings — `host.settings``host.settings` is the supported door for the small set of Desktop-local@@ -1820,7 +1891,7 @@ pipeline as a trust boundary.| Category | Exports ||----------|---------|| Host | `host` (`.state.*`, `.settings`, `.notify`, `.notifyError`, `.navigate`, `.onEvent`, `.logs`, `.status`, `.restartGateway`, `.request`, `.composer`, `.sessions`, `.skills`, `.toolsets`, `.profiles`, `.pluginDecisions`) |-| Plugin contract | `HermesPlugin`, `PluginContext`, `PluginContribution`, `PluginStorage`, `PluginOs`, `PluginRestOptions`, `PluginNativeNotificationInput`, `PluginNotificationAction`, `HermesOpenTarget`, `Contribution` |+| Plugin contract | `HermesPlugin`, `PluginContext`, `PluginContribution`, `PluginStorage`, `PluginOs`, `PluginPet`, `PetSayOptions`, `PetMessageTone`, `PluginRestOptions`, `PluginNativeNotificationInput`, `PluginNotificationAction`, `HermesOpenTarget`, `Contribution` || Area constants | `PANES_AREA`, `ROUTES_AREA`, `SIDEBAR_NAV_AREA`, `STATUSBAR_AREAS`, `TITLEBAR_AREAS`, `WORKSPACE_PAGE_HEADER_AREA`, `PALETTE_AREA`, `KEYBINDS_AREA`, `THEMES_AREA`, `COMPOSER_AREAS`, `MODEL_MENU_ROW_AREA`, `SESSION_ROW_AREAS`, `SIDEBAR_NAV_PREFS_AREA`, `APPEARANCE_AREAS`, `SETTINGS_PLUGINS_AREA` || Area payloads | `PluginSettingsPage`, `PluginSettingsSubpage` (+ `pluginSettingsHref`), `RouteContribution`, `SidebarNavContribution`, `StatusbarItem`, `TitlebarTool`, `PaletteContribution`, `KeybindContribution`, `ComposerMiddleware`, `ComposerAttachmentProvider`, `SessionRowSlotContribution`, `SidebarNavPrefsContribution` || React / state | `useValue`, `atom`, `computed`, `useQuery`, `useMutation`, `useQueryClient`, `queryClient`, `Contribute`, `WorkspacePageHeaderControl` |