The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): show canonical live compression count
Xipong45fc5ebbef28
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.tsindex 0113fe47901..08580ba8669 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts@@ -269,10 +269,33 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {}}- if (sessionId && hasStatePatch) {+ if (sessionId && (hasStatePatch || payload?.usage)) {updateSessionState(sessionId,- state => applySessionInfoStatePatch(state, statePatch),+ state => {+ const nextState = hasStatePatch ? applySessionInfoStatePatch(state, statePatch) : state++ if (!payload?.usage) {+ return nextState+ }++ const previousUsage = nextState.usage++ return {+ ...nextState,+ usage: {+ ...previousUsage,+ ...payload.usage,+ calls: payload.usage.calls ?? previousUsage?.calls ?? 0,+ // session.info is authoritative: omission means unavailable, not+ // "reuse the previous runtime's compression count".+ compressions: payload.usage.compressions,+ input: payload.usage.input ?? previousUsage?.input ?? 0,+ output: payload.usage.output ?? previousUsage?.output ?? 0,+ total: payload.usage.total ?? previousUsage?.total ?? 0+ }+ }+ },payload?.stored_session_id || undefined)}@@ -448,7 +471,12 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {}if (payload?.usage && (!explicitSid || isActiveEvent)) {- setCurrentUsage(current => ({ ...current, ...payload.usage }))+ const usage = payload.usage+ setCurrentUsage(current => ({+ ...current,+ ...usage,+ compressions: usage.compressions+ }))}requestDesktopOnboardingForCredentialWarning(payload?.credential_warning)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsxindex a610d316c73..6c995bbebfd 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx@@ -10,7 +10,7 @@ import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'// $currentUsage mirrors the primary session; ClientSessionState.usage drives// the same status bar when a secondary tile is focused.-const BASELINE = { calls: 2, input: 500, output: 40, total: 540 }+const BASELINE = { calls: 2, compressions: 1, input: 500, output: 40, total: 540 }let stream: MessageStreamHarnesslet sessionStates = new Map<string, ClientSessionState>()@@ -35,16 +35,17 @@ describe('useMessageStream status-bar usage scoping', () => {act(() =>stream.handleEvent({- payload: { usage: { context_percent: 42, input: 1200, total: 1280 } },+ payload: { usage: { compressions: 2, context_percent: 42, input: 1200, total: 1280 } },session_id: SID,type: 'session.usage'}))// Merge, not replace: fields absent from the tick keep their prior values.- expect($currentUsage.get()).toEqual({ ...BASELINE, context_percent: 42, input: 1200, total: 1280 })+ expect($currentUsage.get()).toEqual({ ...BASELINE, compressions: 2, context_percent: 42, input: 1200, total: 1280 })expect(sessionStates.get(SID)?.usage).toEqual({...BASELINE,+ compressions: 2,context_percent: 42,input: 1200,total: 1280@@ -56,7 +57,7 @@ describe('useMessageStream status-bar usage scoping', () => {act(() =>stream.handleEvent({- payload: { usage: { input: 9999, total: 9999 } },+ payload: { usage: { compressions: 9, input: 9999, total: 9999 } },session_id: 'background-session',type: 'session.usage'})@@ -65,24 +66,69 @@ describe('useMessageStream status-bar usage scoping', () => {expect($currentUsage.get()).toEqual(BASELINE)expect(sessionStates.get('background-session')?.usage).toEqual({calls: 0,+ compressions: 9,input: 9999,output: 0,total: 9999})})+ it('caches authoritative session.info usage for a background tile', () => {+ sessionStates.set('background-session', { ...createClientSessionState(), usage: null })+ mountStream()++ act(() =>+ stream.handleEvent({+ payload: { usage: { calls: 3, compressions: 4, input: 700, output: 60, total: 760 } },+ session_id: 'background-session',+ type: 'session.info'+ })+ )++ expect($currentUsage.get()).toEqual(BASELINE)+ expect(sessionStates.get('background-session')?.usage).toEqual({+ calls: 3,+ compressions: 4,+ input: 700,+ output: 60,+ total: 760+ })+ })++ it('clears a stale background compression count when session.info omits it', () => {+ sessionStates.set('background-session', {+ ...createClientSessionState(),+ usage: { ...BASELINE, compressions: 4, context_percent: 55 }+ })+ mountStream()++ act(() =>+ stream.handleEvent({+ payload: { usage: { calls: 3, input: 700, output: 60, total: 760 } },+ session_id: 'background-session',+ type: 'session.info'+ })+ )++ const usage = sessionStates.get('background-session')?.usage+ expect($currentUsage.get()).toEqual(BASELINE)+ expect(usage?.compressions).toBeUndefined()+ expect(usage?.context_percent).toBe(55)+ expect(usage?.calls).toBe(3)+ })+it('applies message.complete usage from the focused session', () => {mountStream()act(() =>stream.handleEvent({- payload: { text: 'done', usage: { calls: 3, input: 1500, output: 90, total: 1590 } },+ payload: { text: 'done', usage: { calls: 3, compressions: 3, input: 1500, output: 90, total: 1590 } },session_id: SID,type: 'message.complete'}))- expect($currentUsage.get()).toEqual({ calls: 3, input: 1500, output: 90, total: 1590 })+ expect($currentUsage.get()).toEqual({ calls: 3, compressions: 3, input: 1500, output: 90, total: 1590 })})it('ignores message.complete usage from a background session', () => {@@ -90,7 +136,7 @@ describe('useMessageStream status-bar usage scoping', () => {act(() =>stream.handleEvent({- payload: { text: 'done', usage: { calls: 9, input: 9999, output: 999, total: 9999 } },+ payload: { text: 'done', usage: { calls: 9, compressions: 9, input: 9999, output: 999, total: 9999 } },session_id: 'background-session',type: 'message.complete'})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 4575c92af64..6fda05e4f61 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -694,6 +694,7 @@ describe('usePromptActions /compress', () => {const requestGateway = vi.fn(async (method: string, _params?: Record<string, unknown>, _timeoutMs?: number) => {if (method === 'session.compress') {return {+ info: { usage: { compressions: 1 } },removed: 8,summary: {headline: 'Compressed: 234 → 226 messages',@@ -728,6 +729,7 @@ describe('usePromptActions /compress', () => {)expect(requestGateway).not.toHaveBeenCalledWith('slash.exec', expect.anything())expect(requestGateway).not.toHaveBeenCalledWith('command.dispatch', expect.anything())+ expect($currentUsage.get().compressions).toBe(1)})it('replaces the transcript from the response messages', async () => {diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 5d52b00b837..82e4454fdb2 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -1428,7 +1428,7 @@ export function useSessionActions({}if (usage) {- setCurrentUsage(current => ({ ...current, ...usage }))+ setCurrentUsage(current => ({ ...current, ...usage, compressions: usage.compressions }))}publishDegradedWarmCache()diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.tsindex 19583b6497d..baa0fc1bf61 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts@@ -10,10 +10,12 @@ import {$currentCwd,$currentModel,$currentProvider,+ $currentUsage,setCurrentBranch,setCurrentCwd,setCurrentModel,setCurrentProvider,+ setCurrentUsage,setSelectedStoredSessionId,workspaceCwdBelongsToSelectedSession} from '@/store/session'@@ -148,6 +150,31 @@ describe('applyRuntimeInfo foreground scoping', () => {expect(patch).toMatchObject({ branch: 'bb/tile', cwd: '/other-worktree' })})+ it('returns authoritative usage for a background runtime snapshot', () => {+ const patch = applyRuntimeInfo(+ { usage: { calls: 3, compressions: 4, input: 100, output: 20, total: 120 } },+ { foreground: false }+ )++ expect(patch?.usage).toEqual({ calls: 3, compressions: 4, input: 100, output: 20, total: 120 })+ })++ it('clears a previous session compression count when the focused snapshot omits it', () => {+ setCurrentUsage({ calls: 2, compressions: 4, input: 10, output: 5, total: 15 })++ applyRuntimeInfo({ usage: { calls: 0, input: 0, output: 0, total: 0 } })++ expect($currentUsage.get().compressions).toBeUndefined()+ })++ it('does not let a background runtime clear the focused compression count', () => {+ setCurrentUsage({ calls: 2, compressions: 4, input: 10, output: 5, total: 15 })++ applyRuntimeInfo({ usage: { calls: 0, input: 0, output: 0, total: 0 } }, { foreground: false })++ expect($currentUsage.get().compressions).toBe(4)+ })+// #71254: `if (info.cwd)` treated '' as "no opinion", so a detached session// never released the previous project and the Files pane stayed on it forever.it('treats an empty runtime cwd as authoritative and releases ownership', () => {@@ -196,6 +223,14 @@ describe('applyStoredSessionPreviewRuntimeInfo workspace paint', () => {expect(workspaceCwdBelongsToSelectedSession()).toBe(true)})+ it('clears live-only compression usage as soon as a cold session switch starts', () => {+ setCurrentUsage({ calls: 2, compressions: 4, input: 10, output: 5, total: 15 })++ applyStoredSessionPreviewRuntimeInfo({ cwd: '/next-project', model: 'gpt' }, 'session-next')++ expect($currentUsage.get().compressions).toBeUndefined()+ })+it('releases ownership when the selected session row reports no workspace', () => {applyStoredSessionPreviewRuntimeInfo({ cwd: '', model: 'gpt' }, 'session-detached')setSelectedStoredSessionId('session-detached')diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex c4a917844e6..c51d5fc137a 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -2148,6 +2148,7 @@ type SessionRuntimeStatePatch = Partial<| 'reasoningEffortPending'| 'reasoningEffortWire'| 'serviceTier'+ | 'usage'| 'yolo'>>@@ -2289,11 +2290,28 @@ export function applyRuntimeInfo(sessionState.yolo = info.yolo}+ if (info.usage) {+ // Runtime info is an authoritative snapshot. Keep a complete per-runtime+ // usage object so a secondary tile can render immediately after create/resume;+ // an omitted compression count intentionally clears a stale tile value.+ sessionState.usage = {+ ...info.usage,+ calls: info.usage.calls ?? 0,+ compressions: info.usage.compressions,+ input: info.usage.input ?? 0,+ output: info.usage.output ?? 0,+ total: info.usage.total ?? 0+ }+ }+if (foreground) {publishRuntimeToComposer(sessionState)if (info.usage) {- setCurrentUsage(current => ({ ...current, ...info.usage }))+ // session.info/session.resume is an authoritative session snapshot, not a+ // partial live tick. Clear a missing compression count so switching from+ // a counted session to an older/cold runtime cannot leak the old value.+ setCurrentUsage(current => ({ ...current, ...info.usage, compressions: info.usage?.compressions }))}}@@ -2304,6 +2322,10 @@ export function applyStoredSessionPreviewRuntimeInfo(stored: { cwd?: null | string; model?: null | string } | undefined,storedSessionId: null | string) {+ // Compression count is live runtime state, not part of a durable session row.+ // Drop the previous session's value immediately while the selected runtime+ // resumes; the authoritative usage snapshot will repopulate it when present.+ setCurrentUsage(current => ({ ...current, compressions: undefined }))// Transient: this is a PREVIEW painted while `session.resume` is still in// flight. If the resume is abandoned (user starts a new chat before it// returns, or the row is switched away), nothing repairs the selectiondiff --git a/apps/desktop/src/app/shell/compression-count-status.test.tsx b/apps/desktop/src/app/shell/compression-count-status.test.tsxnew file mode 100644index 00000000000..bee4c19e13e--- /dev/null+++ b/apps/desktop/src/app/shell/compression-count-status.test.tsx@@ -0,0 +1,25 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it } from 'vitest'++import { CompressionCountStatus } from './compression-count-status'++afterEach(cleanup)++describe('CompressionCountStatus', () => {+ it('renders an explicit zero with a count tooltip', async () => {+ render(<CompressionCountStatus count={0} />)++ const counter = screen.getByTestId('compression-count')+ expect(counter.textContent).toContain('0')+ expect(counter.getAttribute('aria-label')).toBe('Compressions: 0')++ fireEvent.pointerMove(counter, { pointerType: 'mouse' })+ expect((await screen.findByRole('tooltip')).textContent).toBe('Compressions: 0')+ })++ it('does not fabricate a count when live usage omits it', () => {+ const { container } = render(<CompressionCountStatus />)++ expect(container.innerHTML).toBe('')+ })+})diff --git a/apps/desktop/src/app/shell/compression-count-status.tsx b/apps/desktop/src/app/shell/compression-count-status.tsxnew file mode 100644index 00000000000..340b0685fba--- /dev/null+++ b/apps/desktop/src/app/shell/compression-count-status.tsx@@ -0,0 +1,29 @@+import { Tip } from '@/components/ui/tooltip'+import { useI18n } from '@/i18n'++interface CompressionCountStatusProps {+ count?: number+}++/** Current live runtime count from `usage.compressions`.+ * Missing stays missing for older/cold usage snapshots; zero is real data. */+export function CompressionCountStatus({ count }: CompressionCountStatusProps) {+ const { t } = useI18n()++ if (count === undefined) {+ return null+ }++ return (+ <Tip label={t.shell.statusbar.compressions(count)}>+ <div+ aria-label={t.shell.statusbar.compressions(count)}+ className="inline-flex h-full items-center gap-1 px-1.5 text-[0.6875rem] text-(--ui-text-tertiary)"+ data-testid="compression-count"+ >+ <span aria-hidden="true">🗜️</span>+ <span className="tabular-nums">{count}</span>+ </div>+ </Tip>+ )+}diff --git a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsxindex 7e8f019c187..d73b537a8c9 100644--- a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx+++ b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx@@ -7,6 +7,7 @@ import { ProfileSwitcher } from '@/app/chat/sidebar/profile-dropdown-switcher'import type { CommandCenterSection } from '@/app/command-center'import { toggleTerminalPane } from '@/app/right-sidebar/terminal/reveal-focus'import { useApprovalModeStatusbarItem } from '@/app/shell/approval-mode-menu'+import { CompressionCountStatus } from '@/app/shell/compression-count-status'import { ContextUsagePanel } from '@/app/shell/context-usage-panel'import { GatewayMenuPanel } from '@/app/shell/gateway-menu-panel'import { useContextBreakdown } from '@/app/shell/hooks/use-context-breakdown'@@ -688,6 +689,11 @@ export function useStatusbarItems({toggleLabel: copy.toggleContextUsage,variant: 'menu'},+ {+ hidden: contextItemHidden || currentUsage.compressions === undefined,+ id: 'compression-count',+ render: () => <CompressionCountStatus count={currentUsage.compressions} />+ },{icon: <Layers3 className="size-3" />,id: 'cache-hit-rate',@@ -745,8 +751,10 @@ export function useStatusbarItems({contextBar,contextBreakdown,contextBreakdownLoading,+ contextItemHidden,contextUsage,copy,+ currentUsage.compressions,gaugeUsage,sessionStartedAt,gatewayState,diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 9f207d6311b..4c48d03d23e 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -3009,6 +3009,7 @@ export const ar = defineLocale({openCron: 'فتح المهام المجدولة',turnRunning: 'الدور يعمل',contextUsage: 'استخدام السياق',+ compressions: count => `مرات الضغط: ${count}`,focusedSince: 'منذ التركيز',focusedSinceTitle: 'الوقت منذ تركيز هذه المحادثة — وليس مدة الدور',yoloOn: 'YOLO مفعل',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 5492fb50139..babdee1592e 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4755,6 +4755,7 @@ export const en: Translations = {openStarmap: 'Open memory graph',turnRunning: 'Running',contextUsage: 'Context usage',+ compressions: count => `Compressions: ${count}`,systemResources: {title: 'System Resources',loading: 'Resources…',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 5064185c154..62c0f9d06dc 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3478,6 +3478,7 @@ export const ja = defineLocale({openStarmap: 'メモリグラフを開く',turnRunning: '実行中',contextUsage: 'コンテキスト使用状況',+ compressions: count => `圧縮回数: ${count}`,systemResources: {title: 'システムリソース',loading: 'リソース…',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 2c8fe585ee8..bde9087c221 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -3721,6 +3721,7 @@ export const ru = defineLocale({openStarmap: 'Открыть граф памяти',turnRunning: 'Выполняется',contextUsage: 'Использование контекста',+ compressions: count => `Сжатий: ${count}`,contextUsagePanel: {categories: {conversation: 'Диалог',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 418033ba414..e41264cff6f 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -4001,6 +4001,7 @@ export interface Translations {openStarmap: stringturnRunning: stringcontextUsage: string+ compressions: (count: number) => stringsystemResources: {title: stringloading: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 6c70762f7fc..20769f6d9b7 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -3660,6 +3660,7 @@ export const zhHant = defineLocale({openStarmap: '開啟記憶圖譜',turnRunning: '執行中',contextUsage: '上下文使用量',+ compressions: count => `壓縮次數:${count}`,systemResources: {title: '系統資源',loading: '資源…',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex deeca945eb6..c27b362d0a6 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4454,6 +4454,7 @@ export const zh = defineLocale({openStarmap: '打开记忆图谱',turnRunning: '运行中',contextUsage: '上下文用量',+ compressions: count => `压缩次数:${count}`,systemResources: {title: '系统资源',loading: '资源…',diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 9c68d72ac00..3988067ed8e 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -832,6 +832,8 @@ export interface UsageStats {/** Session prompt-cache hit rate, 0–100. Omitted (not 0) when the provider reports no cache reads. */cache_hit_pct?: numbercalls: number+ /** Successful context compressions in the current live agent runtime. */+ compressions?: numbercontext_max?: numbercontext_percent?: numbercontext_estimated?: booleandiff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 66deae5652d..cb923d8ace9 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -1242,6 +1242,16 @@ def test_write_json_drops_detached_ws_frames(monkeypatch):server._sessions.pop("detached-sid", None)[email protected]("count", [0, 3])+def test_get_usage_projects_live_compression_count(count):+ agent = types.SimpleNamespace(+ context_compressor=types.SimpleNamespace(compression_count=count),+ model="test-model",+ )++ assert server._get_usage(agent)["compressions"] == count++def test_usage_ticker_emits_wrapped_usage_payload(monkeypatch):# The live ticker must nest the snapshot under a "usage" key, matching the# message.complete / session.info payloads the desktop & TUI handlers read@@ -10834,7 +10844,7 @@ def test_session_compress_uses_compress_helper(monkeypatch):monkeypatch.setattr(server,"_compress_session_history",- lambda session, focus_topic=None, **_kw: (2, {"total": 42}),+ lambda session, focus_topic=None, **_kw: (2, {"total": 42, "compressions": 2}),)monkeypatch.setattr(server, "_session_info", lambda _agent, *a: {"model": "x"})@@ -10844,7 +10854,7 @@ def test_session_compress_uses_compress_helper(monkeypatch):)assert resp["result"]["removed"] == 2- assert resp["result"]["usage"]["total"] == 42+ assert resp["result"]["usage"] == {"total": 42, "compressions": 2}emit.assert_any_call("session.info", "sid", {"model": "x"})# Final status.update clears the pinned "compressing" indicator so the# status bar can revert to the neutral state when compaction finishes.