The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): pet reads the active runtime's busy slice, drop the 30s recency TTL
kshitijk4poor8edc4085cf0b
diff --git a/apps/desktop/src/store/pet-overlay.ts b/apps/desktop/src/store/pet-overlay.tsindex a2c841bd9df..2ea6b332cec 100644--- a/apps/desktop/src/store/pet-overlay.ts+++ b/apps/desktop/src/store/pet-overlay.ts@@ -1,8 +1,16 @@import { atom } from 'nanostores'import { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage'-import { $petActivity, $petInfo, $petUnread, clearPetUnread, type PetActivity, type PetInfo } from '@/store/pet'-import { $awaitingResponse, $busy } from '@/store/session'+import {+ $petActivity,+ $petBusy,+ $petInfo,+ $petUnread,+ clearPetUnread,+ type PetActivity,+ type PetInfo+} from '@/store/pet'+import { $awaitingResponse } from '@/store/session'/*** Controller for the pop-out pet overlay (main-renderer side).@@ -144,7 +152,7 @@ function currentPayload(): PetOverlayStatePayload {return {info: $petInfo.get(),activity: $petActivity.get(),- busy: $busy.get(),+ busy: $petBusy.get(),awaiting: $awaitingResponse.get(),unread: $petUnread.get(),reaction: $petReaction.get()@@ -181,7 +189,7 @@ function openOverlay(request: PetOverlayOpenRequest): void {stateUnsubs = [$petInfo.subscribe(pushNow),$petActivity.subscribe(pushNow),- $busy.subscribe(pushNow),+ $petBusy.subscribe(pushNow),$awaitingResponse.subscribe(pushNow),$petUnread.subscribe(pushNow),$petReaction.subscribe(pushNow)diff --git a/apps/desktop/src/store/pet.test.ts b/apps/desktop/src/store/pet.test.tsindex 22bca027f9b..51396f8b956 100644--- a/apps/desktop/src/store/pet.test.ts+++ b/apps/desktop/src/store/pet.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'import { createClientSessionState } from '@/lib/chat-runtime'@@ -12,8 +12,7 @@ import {hasPetSpriteForMeta,mergePetInfoMeta,type PetInfo,- setPetActivity,- STEADY_ACTIVITY_TTL_MS+ setPetActivity} from './pet'import { $activeSessionId, $busy } from './session'import { clearAllSessionStates, publishSessionState } from './session-states'@@ -150,69 +149,34 @@ describe('flashPetActivity', () => {})})-describe('deriveLivePetState recency guard (#84434 / #84438)', () => {- const now = Date.now()+describe('$petState reads the active runtime slice, not the $busy mirror (#84434 / #84438)', () => {+ const runtimeId = 'runtime-live'+ const slice = (busy: boolean) => ({ ...createClientSessionState(null), busy, storedSessionId: 'stored-live' })afterEach(() => {- vi.useRealTimers()clearAllSessionStates()$activeSessionId.set(null)$busy.set(false)$petActivity.set({})})- it('animates a recent toolRunning flag even when $busy reads false', () => {- $petActivity.set({ toolRunning: true, toolRunningAt: now - 5_000 })- expect($petState.get()).toBe('run')- })-- it('animates a recent reasoning flag even when $busy reads false', () => {- $petActivity.set({ reasoning: true, reasoningAt: now - 5_000 })- expect($petState.get()).toBe('review')- })+ it('animates a running tool while the active slice is busy even though $busy reads false', () => {+ $activeSessionId.set(runtimeId)+ publishSessionState(runtimeId, slice(true))+ $petActivity.set({ toolRunning: true })- it('decays a stale flag back to idle (interrupted-turn guard preserved)', () => {- $petActivity.set({ toolRunning: true, toolRunningAt: now - STEADY_ACTIVITY_TTL_MS - 1 })- expect($petState.get()).toBe('idle')- })-- it('setPetActivity stamps the timestamp on set', () => {- const before = Date.now()- setPetActivity({ toolRunning: true })- const activity = $petActivity.get()- expect(activity.toolRunningAt).toBeGreaterThanOrEqual(before)- expect(activity.toolRunningAt).toBeLessThanOrEqual(Date.now())+ expect($petState.get()).toBe('run')+ expect($petAtRest.get()).toBe(false)})- it('keeps a silent long-running tool active while its runtime is busy', () => {- vi.useFakeTimers()- vi.setSystemTime(now + STEADY_ACTIVITY_TTL_MS * 4)- $activeSessionId.set('runtime-long-tool')- $busy.set(false)- publishSessionState('runtime-long-tool', {- ...createClientSessionState(null),- busy: true,- storedSessionId: 'stored-long-tool'- })- $petActivity.set({ toolRunning: true, toolRunningAt: now })-+ it('drops to idle the moment the slice settles, even if no event cleared the steady flag', () => {+ $activeSessionId.set(runtimeId)+ publishSessionState(runtimeId, slice(true))+ $petActivity.set({ toolRunning: true })expect($petState.get()).toBe('run')- publishSessionState('runtime-long-tool', {- ...createClientSessionState(null),- busy: false,- storedSessionId: 'stored-long-tool'- })+ // An interrupted turn flips busy→false without a tool.complete / message.complete.+ publishSessionState(runtimeId, slice(false))expect($petState.get()).toBe('idle')})-- it('clears the matching recency stamp when a steady flag clears', () => {- setPetActivity({ toolRunning: true, reasoning: true })- expect($petActivity.get().toolRunningAt).toBeTypeOf('number')- expect($petActivity.get().reasoningAt).toBeTypeOf('number')-- setPetActivity({ toolRunning: false, reasoning: false })- expect($petActivity.get().toolRunningAt).toBeUndefined()- expect($petActivity.get().reasoningAt).toBeUndefined()- })})diff --git a/apps/desktop/src/store/pet.ts b/apps/desktop/src/store/pet.tsindex df3e0f4ea00..cfd9fdf44df 100644--- a/apps/desktop/src/store/pet.ts+++ b/apps/desktop/src/store/pet.ts@@ -1,9 +1,8 @@import { atom, computed } from 'nanostores'+import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'import { persistBoolean, storedBoolean } from '@/lib/storage'import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'-import { $activeSessionId, $busy } from '@/store/session'-import { $sessionStates } from '@/store/session-states'/*** Petdex mascot state for the desktop floating pet.@@ -95,14 +94,8 @@ export interface PetActivity {error?: booleanjustCompleted?: booleancelebrate?: boolean- /** Date.now() stamps for the recency guard in deriveLivePetState (#84434/#84438). */- toolRunningAt?: number- reasoningAt?: number}-/** How long a steady flag counts without a $busy confirmation. */-export const STEADY_ACTIVITY_TTL_MS = 30_000-/*** Resolve the animation state from coarse activity signals.*@@ -172,24 +165,7 @@ export const markPetUnread = () => $petUnread.set(true)export const clearPetUnread = () => $petUnread.set(false)/** Steady activity flags (toolRunning / reasoning) set + cleared by the stream. */-export const setPetActivity = (next: Partial<PetActivity>) => {- const now = Date.now()- const stamped: PetActivity = { ...next }-- if (next.toolRunning === true) {- stamped.toolRunningAt = now- } else if (next.toolRunning === false) {- stamped.toolRunningAt = undefined- }-- if (next.reasoning === true) {- stamped.reasoningAt = now- } else if (next.reasoning === false) {- stamped.reasoningAt = undefined- }-- $petActivity.set({ ...$petActivity.get(), ...stamped })-}+export const setPetActivity = (next: Partial<PetActivity>) => $petActivity.set({ ...$petActivity.get(), ...next })let flashTimer: ReturnType<typeof setTimeout> | undefined@@ -217,39 +193,32 @@ export const setPetInfo = (info: PetInfo) => $petInfo.set(info)* mirrored to the pop-out overlay through the same atom, so both surfaces agree* without the overlay needing the session list.*/-function deriveLivePetState(activity: PetActivity, busy: boolean, activeSessionBusy?: boolean): PetState {- // The per-runtime cache is the authoritative turn state. `$busy` is only a- // legacy foreground mirror and can miss the first turn of a draft or a turn- // resumed after backend reclaim (#84434/#84438). Keep it as the fallback for- // boot/unbound states where the active runtime has not reached the cache yet.- const live = activity.busy ?? activeSessionBusy ?? busy-- // The global $busy can read false for a session that IS working: a- // reclaimed session reopened after idle timeout (#84434) or a desktop-- // minted draft (#84438) doesn't always flip the busy mirror on its turn,- // so the pet froze idle while tools ran. Honor a steady flag while it is- // RECENT (stream-refreshed) even when busy is stuck false — the stamp is- // re-set on every tool.start / message.start — and let it decay back to- // idle when the stream goes silent, which preserves the original intent- // of ignoring stale flags from interrupted turns.- const now = Date.now()- const recentTool = (activity.toolRunningAt ?? 0) > now - STEADY_ACTIVITY_TTL_MS- const recentReasoning = (activity.reasoningAt ?? 0) > now - STEADY_ACTIVITY_TTL_MS+function deriveLivePetState(activity: PetActivity, busy: boolean): PetState {+ const live = activity.busy ?? busyreturn derivePetState({busy: live,awaitingInput: activity.awaitingInput,- toolRunning: (live || recentTool) && activity.toolRunning,- reasoning: (live || recentReasoning) && activity.reasoning,+ // Steady flags only count mid-turn — ignore stale ones once at rest so an+ // interrupted turn can't pin the pet on `run`/`review`.+ toolRunning: live && activity.toolRunning,+ reasoning: live && activity.reasoning,error: activity.error,justCompleted: activity.justCompleted,celebrate: activity.celebrate})}-const $activeSessionBusy = computed([$activeSessionId, $sessionStates], (runtimeId, states) =>- runtimeId ? states[runtimeId]?.busy : undefined-)+/**+ * Turn-busy of the session the pet is watching. The active runtime's own+ * `$sessionStates` slice is authoritative; the global `$busy` mirror is an+ * RAF-batched copy that can stay false for a whole turn (reclaimed session+ * reopened after idle timeout, desktop-minted draft — #84434 / #84438) and is+ * a leftover from whichever session last published while a stored session+ * has no slice yet. Shared with the pop-out overlay push so both surfaces+ * derive the pose from the same signal.+ */+export const $petBusy = PRIMARY_SESSION_VIEW.$busy/*** Opt-in: let the floating mascot wander around the window on its own while@@ -285,8 +254,8 @@ export const $petRoamDir = atom<-1 | 0 | 1>(0)* `$petMotion`-driven pose and stall the wander.*/export const $petAtRest = computed(- [$petActivity, $busy, $activeSessionBusy],- (activity, busy, activeSessionBusy): boolean => deriveLivePetState(activity, busy, activeSessionBusy) === 'idle'+ [$petActivity, $petBusy],+ (activity, busy): boolean => deriveLivePetState(activity, busy) === 'idle')/**@@ -294,11 +263,8 @@ export const $petAtRest = computed(* a roam pose (walking → `run`, hopping → `jump`) show through, so the wander* reads as deliberate movement.*/-export const $petState = computed(- [$petActivity, $busy, $activeSessionBusy, $petMotion],- (activity, busy, activeSessionBusy, motion): PetState => {- const base = deriveLivePetState(activity, busy, activeSessionBusy)+export const $petState = computed([$petActivity, $petBusy, $petMotion], (activity, busy, motion): PetState => {+ const base = deriveLivePetState(activity, busy)- return base === 'idle' && motion ? motion : base- }-)+ return base === 'idle' && motion ? motion : base+})