Skip to content

🙌 OpenHands: AI-Driven Development

feat: context window usage meter, usage drawer, and manual compaction (#16311)

george larsonbe636f714109
diff --git a/__tests__/api/agent-server-config.test.ts b/__tests__/api/agent-server-config.test.ts
index 21a3b7fd31..4c3cffc974 100644
--- a/__tests__/api/agent-server-config.test.ts
+++ b/__tests__/api/agent-server-config.test.ts
@@ -46,6 +46,7 @@ describe("agent server config", () => {
it("uses the browser origin when no backend URL is configured", () => {
mockWindowLocation("https://work-1.example.dev/settings");
+ vi.stubEnv("VITE_BACKEND_BASE_URL", "");
expect(getAgentServerBaseUrl()).toBe("https://work-1.example.dev");
});
diff --git a/__tests__/api/agent-server-conversation-service-condense.test.ts b/__tests__/api/agent-server-conversation-service-condense.test.ts
new file mode 100644
index 0000000000..4ba8f517c1
--- /dev/null
+++ b/__tests__/api/agent-server-conversation-service-condense.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
+import { callCloudProxy } from "#/api/cloud/proxy";
+import { buildHttpBaseUrl } from "#/utils/websocket-url";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+
+const { mockCondenseConversation } = vi.hoisted(() => ({
+ mockCondenseConversation: vi.fn(),
+}));
+
+vi.mock("@openhands/typescript-client/clients", async () => {
+ const actual = await vi.importActual<
+ typeof import("@openhands/typescript-client/clients")
+ >("@openhands/typescript-client/clients");
+ return {
+ ...actual,
+ ConversationClient: vi.fn(function ConversationClientMock() {
+ return { condenseConversation: mockCondenseConversation };
+ }),
+ };
+});
+
+vi.mock("#/api/cloud/proxy", () => ({
+ callCloudProxy: vi.fn(),
+}));
+
+const cloudBackend: Backend = {
+ id: "prod",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-token",
+ kind: "cloud",
+};
+
+const localBackend: Backend = {
+ id: "local",
+ name: "Local",
+ host: "http://127.0.0.1:8001",
+ apiKey: "",
+ kind: "local",
+};
+
+const RUNTIME_URL = "http://localhost:54928/api/conversations/conv-1";
+
+describe("AgentServerConversationService.condenseConversation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCondenseConversation.mockReset().mockResolvedValue(undefined);
+ vi.mocked(callCloudProxy).mockReset().mockResolvedValue(undefined);
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ });
+
+ afterEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ });
+
+ it("routes cloud conversations to the runtime condense endpoint with the session key", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ await AgentServerConversationService.condenseConversation(
+ "conv-1",
+ RUNTIME_URL,
+ "sess-key",
+ );
+
+ expect(callCloudProxy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ backend: cloudBackend,
+ method: "POST",
+ hostOverride: buildHttpBaseUrl(RUNTIME_URL),
+ path: "/api/conversations/conv-1/condense",
+ authMode: "session-api-key",
+ sessionApiKey: "sess-key",
+ }),
+ );
+ expect(mockCondenseConversation).not.toHaveBeenCalled();
+ });
+
+ it("throws when a cloud conversation has no runtime URL to proxy to", async () => {
+ // getEffectiveLocalBackend only resolves when the ACTIVE backend is
+ // local, so a cloud conversation without a conversation_url has no
+ // ConversationClient fallback: the proxy path is the only route.
+ setRegisteredBackends([cloudBackend, localBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ await expect(
+ AgentServerConversationService.condenseConversation(
+ "conv-1",
+ null,
+ "sess-key",
+ ),
+ ).rejects.toThrow("No backend is configured");
+ expect(callCloudProxy).not.toHaveBeenCalled();
+ expect(mockCondenseConversation).not.toHaveBeenCalled();
+ });
+
+ it("uses the ConversationClient directly on a local backend", async () => {
+ await AgentServerConversationService.condenseConversation(
+ "conv-1",
+ RUNTIME_URL,
+ "sess-key",
+ );
+
+ expect(mockCondenseConversation).toHaveBeenCalledWith("conv-1");
+ expect(callCloudProxy).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/components/features/chat/components/context-window-meter.test.tsx b/__tests__/components/features/chat/components/context-window-meter.test.tsx
new file mode 100644
index 0000000000..1157844ba6
--- /dev/null
+++ b/__tests__/components/features/chat/components/context-window-meter.test.tsx
@@ -0,0 +1,175 @@
+import type { ReactNode } from "react";
+import { fireEvent, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders } from "test-utils";
+import useMetricsStore from "#/stores/metrics-store";
+
+const navigateToTabMock = vi.fn();
+
+vi.mock("#/hooks/use-select-conversation-tab", () => ({
+ useSelectConversationTab: () => ({
+ navigateToTab: navigateToTabMock,
+ selectTab: vi.fn(),
+ isTabActive: vi.fn(),
+ onTabChange: vi.fn(),
+ selectedTab: null,
+ isRightPanelShown: false,
+ }),
+}));
+
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: () => ({ data: undefined }),
+}));
+
+vi.mock("#/hooks/query/use-conversation-metrics", () => ({
+ useConversationMetrics: () => ({ data: undefined }),
+}));
+
+vi.mock("#/hooks/use-compact-context-action", () => ({
+ useCompactContextAction: () => ({
+ handleCompact: vi.fn(),
+ isCompacting: false,
+ isDisabled: false,
+ description: "CONVERSATION$COMPACT_CONTEXT_DESCRIPTION",
+ }),
+}));
+
+vi.mock("#/hooks/use-agent-state", () => ({
+ useAgentState: () => ({ curAgentState: "awaiting_user_input" }),
+}));
+
+// HeroUI Tooltip only mounts content on real-DOM hover; surface it eagerly.
+vi.mock("#/components/shared/buttons/styled-tooltip", () => ({
+ StyledTooltip: ({
+ content,
+ children,
+ }: {
+ content: ReactNode;
+ children: ReactNode;
+ }) => (
+ <>
+ {children}
+ <span data-testid="styled-tooltip-content">{content}</span>
+ </>
+ ),
+}));
+
+// eslint-disable-next-line import/first
+import { ContextWindowMeter } from "#/components/features/chat/components/context-window-meter";
+
+describe("ContextWindowMeter", () => {
+ afterEach(() => {
+ navigateToTabMock.mockClear();
+ useMetricsStore.setState({
+ cost: null,
+ max_budget_per_task: null,
+ usage: null,
+ });
+ });
+
+ it("does not render when context window metrics are unavailable", () => {
+ renderWithProviders(<ContextWindowMeter />);
+
+ expect(
+ screen.queryByTestId("context-window-meter"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows a Show Context tooltip on the ring", () => {
+ useMetricsStore.setState({
+ cost: null,
+ max_budget_per_task: null,
+ usage: {
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 1_000_000,
+ per_turn_token: 198_500,
+ },
+ });
+
+ renderWithProviders(<ContextWindowMeter />);
+
+ expect(screen.getByTestId("styled-tooltip-content")).toHaveTextContent(
+ "CHAT_INTERFACE$SHOW_CONTEXT",
+ );
+ });
+
+ it("opens a popover with compact usage details", () => {
+ useMetricsStore.setState({
+ cost: null,
+ max_budget_per_task: null,
+ usage: {
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 1_000_000,
+ per_turn_token: 198_500,
+ },
+ });
+
+ renderWithProviders(<ContextWindowMeter />);
+
+ fireEvent.click(screen.getByTestId("context-window-meter"));
+
+ expect(
+ screen.getByTestId("context-window-meter-popover"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("20% CONVERSATION$USED (80% CONVERSATION$LEFT)"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("198.5k / 1.0M")).toBeInTheDocument();
+ expect(
+ screen.getByTestId("context-window-compact-button"),
+ ).toHaveTextContent("CONVERSATION$COMPACT_CONTEXT");
+ expect(
+ screen.getByText("CONVERSATION$CONTEXT_WINDOW"),
+ ).toBeInTheDocument();
+ });
+
+ it("opens the Usage drawer from the popover meter", () => {
+ useMetricsStore.setState({
+ cost: 1.25,
+ max_budget_per_task: null,
+ usage: {
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 1_000_000,
+ per_turn_token: 198_500,
+ },
+ });
+
+ renderWithProviders(<ContextWindowMeter />);
+
+ fireEvent.click(screen.getByTestId("context-window-meter"));
+ fireEvent.click(screen.getByTestId("context-window-meter-bar-button"));
+
+ expect(navigateToTabMock).toHaveBeenCalledWith("usage");
+ });
+
+ it("opens the Usage drawer from the usage row", () => {
+ useMetricsStore.setState({
+ cost: 1.25,
+ max_budget_per_task: null,
+ usage: {
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 1_000_000,
+ per_turn_token: 198_500,
+ },
+ });
+
+ renderWithProviders(<ContextWindowMeter />);
+
+ fireEvent.click(screen.getByTestId("context-window-meter"));
+ fireEvent.click(screen.getByTestId("context-window-plan-usage"));
+
+ expect(navigateToTabMock).toHaveBeenCalledWith("usage");
+ });
+});
diff --git a/__tests__/components/features/conversation/conversation-name.test.tsx b/__tests__/components/features/conversation/conversation-name.test.tsx
index 2daffd8721..bb2ca2fdaa 100644
--- a/__tests__/components/features/conversation/conversation-name.test.tsx
+++ b/__tests__/components/features/conversation/conversation-name.test.tsx
@@ -94,7 +94,7 @@ vi.mock("react-i18next", async () => {
BUTTON$DOWNLOAD_VIA_VSCODE: "Download via VS Code",
BUTTON$SHOW_AGENT_TOOLS_AND_METADATA: "Show Agent Tools",
CONVERSATION$SHOW_SKILLS: "Show Skills",
- BUTTON$DISPLAY_COST: "Display Cost",
+ BUTTON$DISPLAY_COST: "Display Usage and Cost",
COMMON$CLOSE_CONVERSATION_STOP_RUNTIME:
"Stop Conversation (Runtime)",
COMMON$STOP_CONVERSATION: "Stop Conversation",
@@ -566,7 +566,7 @@ describe("ConversationNameContextMenu", () => {
"Stop Conversation",
);
expect(screen.getByTestId("display-cost-button")).toHaveTextContent(
- "Display Cost",
+ "Display Usage and Cost",
);
expect(screen.getByTestId("show-agent-tools-button")).toHaveTextContent(
"Show Agent Tools",
diff --git a/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx b/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx
index 0046aefd1c..36c60f3387 100644
--- a/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx
+++ b/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx
@@ -14,7 +14,7 @@ import type { Backend } from "#/api/backend-registry/types";
const CONVERSATION_ID = "conv-abc123";
vi.mock("#/hooks/use-conversation-id", () => ({
- useOptionalConversationId: () => ({ conversationId: "test-conversation-id" }),
+ useOptionalConversationId: () => ({ conversationId: CONVERSATION_ID }),
useConversationId: () => ({ conversationId: CONVERSATION_ID }),
}));
diff --git a/__tests__/components/features/conversation/conversation-tabs.test.tsx b/__tests__/components/features/conversation/conversation-tabs.test.tsx
index fd09411bfc..11b01527e4 100644
--- a/__tests__/components/features/conversation/conversation-tabs.test.tsx
+++ b/__tests__/components/features/conversation/conversation-tabs.test.tsx
@@ -20,7 +20,7 @@ const REAL_CONVERSATION_ID = "conv-abc123";
let mockConversationId = TASK_CONVERSATION_ID;
vi.mock("#/hooks/use-conversation-id", () => ({
- useOptionalConversationId: () => ({ conversationId: "test-conversation-id" }),
+ useOptionalConversationId: () => ({ conversationId: mockConversationId }),
useConversationId: () => ({ conversationId: mockConversationId }),
}));
diff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsx
index bcc05328e7..1147b8dd10 100644
--- a/__tests__/contexts/conversation-websocket-context.test.tsx
+++ b/__tests__/contexts/conversation-websocket-context.test.tsx
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createUserMessageEvent } from "test-utils";
import { ConversationWebSocketProvider } from "#/contexts/conversation-websocket-context";
import { useEventStore } from "#/stores/use-event-store";
+import useMetricsStore from "#/stores/metrics-store";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
import { useBrowserStore } from "#/stores/browser-store";
import { useCommandStore } from "#/stores/command-store";
@@ -104,6 +105,7 @@ describe("ConversationWebSocketProvider — conversation-scoped event store", ()
});
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
useBrowserStore.getState().reset();
+ useMetricsStore.getState().resetMetrics();
useCommandStore.setState({ commands: [] });
useErrorMessageStore.getState().removeErrorMessage();
@@ -468,6 +470,39 @@ describe("ConversationWebSocketProvider — conversation-scoped event store", ()
expect(useBrowserStore.getState().url).toBe("");
});
+ it("resets the metrics store when switching conversations", async () => {
+ const { rerender } = renderProvider("conv-a");
+ await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-a"]));
+
+ useMetricsStore.setState({
+ cost: 1.5,
+ max_budget_per_task: 5,
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ cache_read_tokens: 1,
+ cache_write_tokens: 2,
+ context_window: 128_000,
+ per_turn_token: 500,
+ },
+ });
+
+ rerender(
+ <QueryClientProvider client={queryClient}>
+ <ConversationWebSocketProvider
+ conversationId="conv-b"
+ conversationUrl={null}
+ >
+ <div />
+ </ConversationWebSocketProvider>
+ </QueryClientProvider>,
+ );
+
+ await waitFor(() => expect(useMetricsStore.getState().usage).toBeNull());
+ expect(useMetricsStore.getState().cost).toBeNull();
+ expect(useMetricsStore.getState().max_budget_per_task).toBeNull();
+ });
+
it("keeps events that arrived after history when re-entering the same conversation", async () => {
// Arrange: open conversation A, then receive an agent reply over the socket
// that is not part of the cached REST history page.
diff --git a/__tests__/hooks/use-context-window-usage.test.ts b/__tests__/hooks/use-context-window-usage.test.ts
new file mode 100644
index 0000000000..0d2139ccf2
--- /dev/null
+++ b/__tests__/hooks/use-context-window-usage.test.ts
@@ -0,0 +1,150 @@
+import { renderHook } from "@testing-library/react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import useMetricsStore, { type MetricsState } from "#/stores/metrics-store";
+import type { TokenUsage } from "#/api/conversation-service/agent-server-conversation-service.types";
+
+const useActiveConversationMock = vi.fn();
+const useConversationMetricsMock = vi.fn();
+
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: () => useActiveConversationMock(),
+}));
+
+vi.mock("#/hooks/query/use-conversation-metrics", () => ({
+ useConversationMetrics: (...args: unknown[]) =>
+ useConversationMetricsMock(...args),
+}));
+
+import { useContextWindowUsage } from "#/hooks/use-context-window-usage";
+
+const CONVERSATION = {
+ id: "conv-1",
+ conversation_url: "http://localhost:54928/api/conversations/conv-1",
+ session_api_key: "sess-key",
+};
+
+const storeUsage = (
+ contextWindow: number,
+ perTurnToken: number,
+): NonNullable<MetricsState["usage"]> => ({
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: contextWindow,
+ per_turn_token: perTurnToken,
+});
+
+// The wire can deliver nulls for any token field even though the SDK type
+// says number; the hook's `?? 0` coercion is what these tests pin.
+const restUsage = (
+ contextWindow: number | null,
+ perTurnToken: number | null,
+): TokenUsage =>
+ ({
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: contextWindow,
+ per_turn_token: perTurnToken,
+ }) as unknown as TokenUsage;
+
+describe("useContextWindowUsage", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useMetricsStore.setState({
+ cost: null,
+ max_budget_per_task: null,
+ usage: null,
+ });
+ useActiveConversationMock.mockReturnValue({ data: CONVERSATION });
+ useConversationMetricsMock.mockReturnValue({ data: undefined });
+ });
+
+ it("prefers the live WS store when it reports a usable context window", () => {
+ useMetricsStore.setState({ usage: storeUsage(200_000, 1234) });
+ useConversationMetricsMock.mockReturnValue({
+ data: { accumulated_token_usage: restUsage(128_000, 500) },
+ });
+
+ const { result } = renderHook(() => useContextWindowUsage());
+
+ expect(result.current).toEqual({
+ perTurnToken: 1234,
+ contextWindow: 200_000,
+ });
+ });
+
+ it("falls back to the REST snapshot when the store has no usage", () => {
+ useConversationMetricsMock.mockReturnValue({
+ data: { accumulated_token_usage: restUsage(128_000, 500) },
+ });
+
+ const { result } = renderHook(() => useContextWindowUsage());
+
+ expect(result.current).toEqual({
+ perTurnToken: 500,
+ contextWindow: 128_000,
+ });
+ });
+
+ it("falls through to REST when the store reports a zero context window", () => {
+ useMetricsStore.setState({ usage: storeUsage(0, 999) });
+ useConversationMetricsMock.mockReturnValue({
+ data: { accumulated_token_usage: restUsage(128_000, 500) },
+ });
+
+ const { result } = renderHook(() => useContextWindowUsage());
+
+ expect(result.current).toEqual({
+ perTurnToken: 500,
+ contextWindow: 128_000,
+ });
+ });
+
+ it("returns null when no source reports a positive context window", () => {
+ // The divide-by-zero guard: a model that does not report a context
+ // window must render no meter at all.
+ useConversationMetricsMock.mockReturnValue({
+ data: { accumulated_token_usage: restUsage(0, 500) },
+ });
+
+ const { result } = renderHook(() => useContextWindowUsage());
+
+ expect(result.current).toBeNull();
+ });
+
+ it("coerces a null per_turn_token from the wire to zero", () => {
+ useConversationMetricsMock.mockReturnValue({
+ data: { accumulated_token_usage: restUsage(128_000, null) },
+ });
+
+ const { result } = renderHook(() => useContextWindowUsage());
+
+ expect(result.current).toEqual({
+ perTurnToken: 0,
+ contextWindow: 128_000,
+ });
+ });
+
+ it("polls the REST snapshot only while a conversation is active", () => {
+ renderHook(() => useContextWindowUsage());
+ expect(useConversationMetricsMock).toHaveBeenCalledWith(
+ "conv-1",
+ CONVERSATION.conversation_url,
+ "sess-key",
+ true,
+ );
+
+ useConversationMetricsMock.mockClear();
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ renderHook(() => useContextWindowUsage());
+ expect(useConversationMetricsMock).toHaveBeenCalledWith(
+ undefined,
+ undefined,
+ undefined,
+ false,
+ );
+ });
+});
diff --git a/__tests__/hooks/use-live-conversation-metrics.test.ts b/__tests__/hooks/use-live-conversation-metrics.test.ts
new file mode 100644
index 0000000000..6a5dd2ead5
--- /dev/null
+++ b/__tests__/hooks/use-live-conversation-metrics.test.ts
@@ -0,0 +1,159 @@
+import { renderHook } from "@testing-library/react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import useMetricsStore, { type MetricsState } from "#/stores/metrics-store";
+import type {
+ MetricsSnapshot,
+ TokenUsage,
+} from "#/api/conversation-service/agent-server-conversation-service.types";
+
+const useActiveConversationMock = vi.fn();
+const useConversationMetricsMock = vi.fn();
+
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: () => useActiveConversationMock(),
+}));
+
+vi.mock("#/hooks/query/use-conversation-metrics", () => ({
+ useConversationMetrics: (...args: unknown[]) =>
+ useConversationMetricsMock(...args),
+}));
+
+import { useLiveConversationMetrics } from "#/hooks/use-live-conversation-metrics";
+
+const CONVERSATION = {
+ id: "conv-1",
+ conversation_url: "http://localhost:54928/api/conversations/conv-1",
+ session_api_key: "sess-key",
+};
+
+// The wire can deliver nulls for any token field even though the SDK type
+// says number; the hook's `?? 0` coercion is what these tests pin.
+const restUsage = (overrides: Record<string, number | null> = {}): TokenUsage =>
+ ({
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ cache_read_tokens: 1,
+ cache_write_tokens: 2,
+ context_window: 128_000,
+ per_turn_token: 500,
+ ...overrides,
+ }) as unknown as TokenUsage;
+
+const snapshot = (
+ overrides: Partial<MetricsSnapshot> = {},
+): MetricsSnapshot => ({
+ accumulated_cost: 1.23,
+ max_budget_per_task: 5,
+ accumulated_token_usage: restUsage(),
+ ...overrides,
+});
+
+const storeMetrics: MetricsState = {
+ cost: 9.99,
+ max_budget_per_task: 10,
+ usage: {
+ prompt_tokens: 1,
+ completion_tokens: 2,
+ cache_read_tokens: 3,
+ cache_write_tokens: 4,
+ context_window: 64_000,
+ per_turn_token: 42,
+ },
+};
+
+describe("useLiveConversationMetrics", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useMetricsStore.setState({
+ cost: null,
+ max_budget_per_task: null,
+ usage: null,
+ });
+ useActiveConversationMock.mockReturnValue({ data: CONVERSATION });
+ useConversationMetricsMock.mockReturnValue({ data: undefined });
+ });
+
+ it("prefers the live store over the REST snapshot", () => {
+ useMetricsStore.setState(storeMetrics);
+ useConversationMetricsMock.mockReturnValue({ data: snapshot() });
+
+ const { result } = renderHook(() => useLiveConversationMetrics());
+
+ expect(result.current).toEqual(storeMetrics);
+ });
+
+ it("coerces null token fields from the wire to zero", () => {
+ useConversationMetricsMock.mockReturnValue({
+ data: snapshot({
+ accumulated_token_usage: restUsage({
+ completion_tokens: null,
+ context_window: null,
+ per_turn_token: null,
+ }),
+ }),
+ });
+
+ const { result } = renderHook(() => useLiveConversationMetrics());
+
+ expect(result.current.usage).toEqual({
+ prompt_tokens: 10,
+ completion_tokens: 0,
+ cache_read_tokens: 1,
+ cache_write_tokens: 2,
+ context_window: 0,
+ per_turn_token: 0,
+ });
+ });
+
+ it("maps a missing accumulated_token_usage to null usage", () => {
+ useConversationMetricsMock.mockReturnValue({
+ data: snapshot({ accumulated_token_usage: null }),
+ });
+
+ const { result } = renderHook(() => useLiveConversationMetrics());
+
+ expect(result.current).toEqual({
+ cost: 1.23,
+ max_budget_per_task: 5,
+ usage: null,
+ });
+ });
+
+ it("falls back to the REST snapshot while the store is empty", () => {
+ useConversationMetricsMock.mockReturnValue({ data: snapshot() });
+
+ const { result } = renderHook(() => useLiveConversationMetrics());
+
+ expect(result.current).toEqual({
+ cost: 1.23,
+ max_budget_per_task: 5,
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ cache_read_tokens: 1,
+ cache_write_tokens: 2,
+ context_window: 128_000,
+ per_turn_token: 500,
+ },
+ });
+ });
+
+ it("threads the enabled flag through to the polling query", () => {
+ renderHook(() => useLiveConversationMetrics(false));
+ expect(useConversationMetricsMock).toHaveBeenCalledWith(
+ "conv-1",
+ CONVERSATION.conversation_url,
+ "sess-key",
+ false,
+ );
+
+ useConversationMetricsMock.mockClear();
+ renderHook(() => useLiveConversationMetrics());
+ expect(useConversationMetricsMock).toHaveBeenCalledWith(
+ "conv-1",
+ CONVERSATION.conversation_url,
+ "sess-key",
+ true,
+ );
+ });
+});
diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsx
index a4908d28de..9996390a79 100644
--- a/__tests__/root.test.tsx
+++ b/__tests__/root.test.tsx
@@ -449,7 +449,7 @@ describe("App root agent-server availability guard", () => {
it("shows the manage-backends modal when the connected server reports an old version", async () => {
window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");
server.use(
- http.get("/server_info", () =>
+ http.get("*/server_info", () =>
HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.27.1" }),
),
);
@@ -471,7 +471,7 @@ describe("App root agent-server availability guard", () => {
it("shows the manage-backends modal when the server omits a version field", async () => {
window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");
server.use(
- http.get("/server_info", () =>
+ http.get("*/server_info", () =>
HttpResponse.json({ uptime: 0, idle_time: 0 }),
),
);
diff --git a/__tests__/utils/format-token-count.test.ts b/__tests__/utils/format-token-count.test.ts
new file mode 100644
index 0000000000..90a353c2d4
--- /dev/null
+++ b/__tests__/utils/format-token-count.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import {
+ formatCompactTokenCount,
+ getContextWindowUsagePercentage,
+} from "#/utils/format-token-count";
+
+describe("formatCompactTokenCount", () => {
+ it.each([
+ [500, "500"],
+ [1_985, "2.0k"],
+ [198_500, "198.5k"],
+ [1_000_000, "1.0M"],
+ [1_050_000, "1.1M"],
+ ])("formats %i as %s", (value, expected) => {
+ expect(formatCompactTokenCount(value)).toBe(expected);
+ });
+});
+
+describe("getContextWindowUsagePercentage", () => {
+ it("returns zero when the context window is unavailable", () => {
+ expect(getContextWindowUsagePercentage(100, 0)).toBe(0);
+ });
+
+ it("caps usage at 100 percent", () => {
+ expect(getContextWindowUsagePercentage(2_000_000, 1_000_000)).toBe(100);
+ });
+
+ it("computes the percentage from per-turn tokens", () => {
+ expect(getContextWindowUsagePercentage(200_000, 1_000_000)).toBe(20);
+ });
+});
diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.ts
index 674d8101e7..efd7897e97 100644
--- a/src/api/agent-server-compatibility.ts
+++ b/src/api/agent-server-compatibility.ts
@@ -65,7 +65,9 @@ export const isAgentServerUnavailableError = (
(typeof error === "object" &&
error !== null &&
"name" in error &&
- error.name === "AgentServerUnavailableError");
+ (error.name === "AgentServerUnavailableError" ||
+ error.name === "AgentServerUnsupportedVersionError" ||
+ error.name === "AgentServerUnknownVersionError"));
export class AgentServerUnsupportedVersionError extends AgentServerUnavailableError {
readonly code = AGENT_SERVER_UNSUPPORTED_VERSION_ERROR_CODE;
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index a13e839282..25ae3c99cf 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -663,6 +663,36 @@ class AgentServerConversationService {
};
}
+ /**
+ * Force condensation ("compact") of the conversation history via
+ * `POST /api/conversations/{id}/condense`. Routed the same way as
+ * {@link sendMessage}: through the cloud proxy at the conversation's own
+ * runtime host for cloud backends, directly against that runtime otherwise.
+ */
+ static async condenseConversation(
+ conversationId: string,
+ conversationUrl: string | null | undefined,
+ sessionApiKey?: string | null,
+ ): Promise<void> {
+ const active = getActiveBackend().backend;
+
+ if (active.kind === "cloud" && conversationUrl) {
+ await callCloudProxy({
+ backend: active,
+ method: "POST",
+ hostOverride: buildHttpBaseUrl(conversationUrl),
+ path: `/api/conversations/${conversationId}/condense`,
+ authMode: "session-api-key",
+ sessionApiKey,
+ });
+ return;
+ }
+
+ await new ConversationClient(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).condenseConversation(conversationId);
+ }
+
static async searchConversations(
limit: number = 20,
pageId?: string,
diff --git a/src/api/llm-balance-service.test.ts b/src/api/llm-balance-service.test.ts
new file mode 100644
index 0000000000..134bc8951e
--- /dev/null
+++ b/src/api/llm-balance-service.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
+import LLMBalanceService from "./llm-balance-service";
+
+const localBackend: Backend = {
+ id: "local-test",
+ name: "Local test backend",
+ host: "http://localhost:3000",
+ apiKey: "test-session-key",
+ kind: "local",
+};
+
+const balancePayload = {
+ provider: "openrouter",
+ limit: 20,
+ limit_remaining: 14.96,
+ usage: 5.04,
+ usage_daily: 1.2,
+ usage_weekly: 3.4,
+ usage_monthly: 5.04,
+ is_free_tier: false,
+};
+
+function mockFetchResponse(status: number, body?: unknown) {
+ return vi.fn().mockResolvedValue({
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => body,
+ });
+}
+
+describe("LLMBalanceService.getBalance", () => {
+ beforeEach(() => {
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+ });
+
+ afterEach(() => {
+ setActiveSelection(null);
+ setRegisteredBackends([]);
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ it("normalizes a successful balance response", async () => {
+ const fetchMock = mockFetchResponse(200, balancePayload);
+ vi.stubGlobal("fetch", fetchMock);
+
+ const balance = await LLMBalanceService.getBalance();
+
+ expect(balance).toEqual({
+ provider: "openrouter",
+ limit: 20,
+ limitRemaining: 14.96,
+ usage: 5.04,
+ usageDaily: 1.2,
+ usageWeekly: 3.4,
+ usageMonthly: 5.04,
+ isFreeTier: false,
+ });
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe("http://localhost:3000/api/llm/balance");
+ expect((init.headers as Headers).get("X-Session-API-Key")).toBe(
+ "test-session-key",
+ );
+ });
+
+ it("treats null caps as an uncapped key", async () => {
+ vi.stubGlobal(
+ "fetch",
+ mockFetchResponse(200, {
+ ...balancePayload,
+ limit: null,
+ limit_remaining: null,
+ }),
+ );
+
+ const balance = await LLMBalanceService.getBalance();
+
+ expect(balance?.limit).toBeNull();
+ expect(balance?.limitRemaining).toBeNull();
+ expect(balance?.usage).toBe(5.04);
+ });
+
+ it("returns null when the endpoint is missing (404)", async () => {
+ vi.stubGlobal("fetch", mockFetchResponse(404));
+
+ await expect(LLMBalanceService.getBalance()).resolves.toBeNull();
+ });
+
+ it("returns null for a malformed response body", async () => {
+ vi.stubGlobal("fetch", mockFetchResponse(200, { unexpected: true }));
+
+ await expect(LLMBalanceService.getBalance()).resolves.toBeNull();
+ });
+
+ it("throws on non-404 HTTP failures", async () => {
+ vi.stubGlobal("fetch", mockFetchResponse(500));
+
+ await expect(LLMBalanceService.getBalance()).rejects.toThrow(
+ "Balance request failed with 500",
+ );
+ });
+
+ it("bounds the request with an abort signal", async () => {
+ const fetchMock = mockFetchResponse(200, balancePayload);
+ vi.stubGlobal("fetch", fetchMock);
+
+ await LLMBalanceService.getBalance();
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(init.signal).toBeInstanceOf(AbortSignal);
+ });
+
+ it("throws a named error when the request times out", async () => {
+ // A server that accepts the connection and never answers: fetch rejects
+ // with the signal's TimeoutError rather than resolving.
+ vi.stubGlobal(
+ "fetch",
+ vi
+ .fn()
+ .mockRejectedValue(
+ new DOMException("The operation was aborted.", "TimeoutError"),
+ ),
+ );
+
+ await expect(LLMBalanceService.getBalance()).rejects.toThrow(
+ "Balance request timed out",
+ );
+ });
+});
diff --git a/src/api/llm-balance-service.ts b/src/api/llm-balance-service.ts
new file mode 100644
index 0000000000..5a56b1b58d
--- /dev/null
+++ b/src/api/llm-balance-service.ts
@@ -0,0 +1,103 @@
+import { getAgentServerClientOptions } from "./agent-server-client-options";
+import {
+ LLM_BALANCE_PATH,
+ LLM_BALANCE_TIMEOUT_MS,
+} from "#/constants/llm-balance";
+
+/**
+ * Credit balance reported by the agent server for the active LLM provider
+ * (currently only OpenRouter). Amounts are in USD credits.
+ */
+export interface LLMBalance {
+ provider: string;
+ /** Credit cap configured for the key, or null when uncapped. */
+ limit: number | null;
+ /** Credits remaining under `limit`, or null when uncapped. */
+ limitRemaining: number | null;
+ /** Total credits consumed by the key. */
+ usage: number;
+ usageDaily: number | null;
+ usageWeekly: number | null;
+ usageMonthly: number | null;
+ isFreeTier: boolean;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function numberOrNull(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
+
+/** `AbortSignal.timeout` rejects with a `TimeoutError`; a manual abort uses `AbortError`. */
+function isAbortLike(error: unknown): boolean {
+ return (
+ isRecord(error) &&
+ (error.name === "TimeoutError" || error.name === "AbortError")
+ );
+}
+
+function normalizeBalance(raw: unknown): LLMBalance | null {
+ if (!isRecord(raw) || typeof raw.provider !== "string") return null;
+
+ return {
+ provider: raw.provider,
+ limit: numberOrNull(raw.limit),
+ limitRemaining: numberOrNull(raw.limit_remaining),
+ usage: numberOrNull(raw.usage) ?? 0,
+ usageDaily: numberOrNull(raw.usage_daily),
+ usageWeekly: numberOrNull(raw.usage_weekly),
+ usageMonthly: numberOrNull(raw.usage_monthly),
+ isFreeTier: raw.is_free_tier === true,
+ };
+}
+
+class LLMBalanceService {
+ /**
+ * Fetch the provider balance from the agent server.
+ *
+ * Returns `null` when the server answers 404 (older servers without the
+ * endpoint, or a provider that doesn't support balance reporting) or when
+ * the response doesn't match the expected shape — callers hide the balance
+ * UI in that case. Other HTTP failures throw, as does a request that outlives
+ * `LLM_BALANCE_TIMEOUT_MS`. A timeout stays an error rather than collapsing
+ * into `null`: `null` means "this server has no balance to report" and is
+ * cached under `staleTime: Infinity`, so treating a transient stall as an
+ * absent endpoint would hide the card for the rest of the conversation.
+ */
+ static async getBalance(): Promise<LLMBalance | null> {
+ // Raw fetch is deliberate: /api/llm/balance has no typed client in
+ // @openhands/typescript-client yet. The file is listed in
+ // ALLOWED_AD_HOC_HTTP_FILES (no-direct-agent-server-calls.test.ts) with
+ // this justification.
+ const { host, apiKey } = getAgentServerClientOptions();
+ const headers = new Headers({ Accept: "application/json" });
+ if (apiKey) {
+ headers.set("X-Session-API-Key", apiKey);
+ }
+
+ let response: Response;
+ try {
+ response = await fetch(`${host}${LLM_BALANCE_PATH}`, {
+ headers,
+ signal: AbortSignal.timeout(LLM_BALANCE_TIMEOUT_MS),
+ });
+ } catch (error) {
+ if (isAbortLike(error)) {
+ throw new Error(
+ `Balance request timed out after ${LLM_BALANCE_TIMEOUT_MS}ms`,
+ );
+ }
+ throw error;
+ }
+
+ if (response.status === 404) return null;
+ if (!response.ok) {
+ throw new Error(`Balance request failed with ${response.status}`);
+ }
+ return normalizeBalance(await response.json());
+ }
+}
+
+export default LLMBalanceService;
diff --git a/src/api/no-direct-agent-server-calls.test.ts b/src/api/no-direct-agent-server-calls.test.ts
index 3144c8c1a2..75761392c4 100644
--- a/src/api/no-direct-agent-server-calls.test.ts
+++ b/src/api/no-direct-agent-server-calls.test.ts
@@ -8,6 +8,10 @@ const ALLOWED_AD_HOC_HTTP_FILES = new Set([
"api/automation-service/automation-service.api.ts",
"api/cloud/proxy.ts",
"api/main-app-auth.ts",
+ // GET /api/llm/balance has no typed client in @openhands/typescript-client
+ // yet; the service resolves host/key via getAgentServerClientOptions and
+ // treats 404 as "endpoint absent" for older servers.
+ "api/llm-balance-service.ts",
]);
function collectSourceFiles(dir: string): string[] {
@@ -65,7 +69,10 @@ describe("agent-server API access", () => {
fileViolations.push("uses axios directly for HTTP calls");
}
- if (/\bfetch\s*\([\s\S]{0,200}['"`]\/api\//.test(source)) {
+ if (
+ /\bfetch\s*\([\s\S]{0,200}['"`]\/api\//.test(source) &&
+ !ALLOWED_AD_HOC_HTTP_FILES.has(relPath)
+ ) {
fileViolations.push("calls an /api path with fetch directly");
}
diff --git a/src/components/conversation/index.ts b/src/components/conversation/index.ts
index 95a35e29ed..60b40c32c9 100644
--- a/src/components/conversation/index.ts
+++ b/src/components/conversation/index.ts
@@ -6,4 +6,3 @@ export { ChatInterfaceWrapper } from "../features/conversation/conversation-main
export { ConversationName } from "../features/conversation/conversation-name";
export { ConversationNameWithStatus } from "../features/conversation/conversation-name-with-status";
export { ConversationTabs } from "../features/conversation/conversation-tabs/conversation-tabs";
-export { MetricsModal } from "../features/conversation/metrics-modal/metrics-modal";
diff --git a/src/components/features/chat/components/chat-input-actions.tsx b/src/components/features/chat/components/chat-input-actions.tsx
index 5974edac52..fbf0412790 100644
--- a/src/components/features/chat/components/chat-input-actions.tsx
+++ b/src/components/features/chat/components/chat-input-actions.tsx
@@ -12,6 +12,7 @@ import {
import { resolvePickerKind } from "./resolve-picker-kind";
import { ChatAddFileButton } from "../chat-add-file-button";
import { ChatSendButton } from "../chat-send-button";
+import { ContextWindowMeter } from "./context-window-meter";
import CarretRightFillIcon from "#/icons/carret-right-fill.svg?react";
import LessonPlanIcon from "#/icons/lesson-plan.svg?react";
import ThreeDotsVerticalIcon from "#/icons/three-dots-vertical.svg?react";
@@ -497,6 +498,7 @@ export function ChatInputActions({
isPausing={isPausing}
/>
)}
+ <ContextWindowMeter />
{showButton && (
<ChatSendButton
buttonClassName={buttonClassName}
diff --git a/src/components/features/chat/components/context-window-meter.tsx b/src/components/features/chat/components/context-window-meter.tsx
new file mode 100644
index 0000000000..f9a66b56bc
--- /dev/null
+++ b/src/components/features/chat/components/context-window-meter.tsx
@@ -0,0 +1,179 @@
+import React from "react";
+import { Gauge, Loader2, Minimize } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { useContextWindowUsage } from "#/hooks/use-context-window-usage";
+import { useSelectConversationTab } from "#/hooks/use-select-conversation-tab";
+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";
+import { useCompactContextAction } from "#/hooks/use-compact-context-action";
+import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";
+import { ConversationNameContextMenuIconText } from "#/components/features/conversation/conversation-name-context-menu-icon-text";
+import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";
+import { I18nKey } from "#/i18n/declaration";
+import { Divider } from "#/ui/divider";
+import { cn } from "#/utils/utils";
+import {
+ formatCompactTokenCount,
+ getContextWindowUsagePercentage,
+} from "#/utils/format-token-count";
+import { getContextFillTone } from "#/components/features/conversation/usage-panel/context-meter";
+import { ContextWindowRing } from "./context-window-ring";
+
+const TONE_BAR_CLASS = {
+ neutral: "bg-foreground",
+ warning: "bg-amber-500",
+ danger: "bg-red-500",
+} as const;
+
+const TONE_LABEL_CLASS = {
+ neutral: "text-[var(--oh-muted)]",
+ warning: "text-amber-500",
+ danger: "text-red-500",
+} as const;
+
+export function ContextWindowMeter() {
+ const { t } = useTranslation("openhands");
+ const usage = useContextWindowUsage();
+ const { navigateToTab } = useSelectConversationTab();
+ const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
+ const triggerRef = React.useRef<HTMLButtonElement>(null);
+ const popoverRef = useClickOutsideElement<HTMLDivElement>(
+ () => setIsPopoverOpen(false),
+ triggerRef,
+ );
+ const { handleCompact, isCompacting, isDisabled } = useCompactContextAction(
+ usage?.perTurnToken ?? 0,
+ );
+
+ if (!usage) {
+ return null;
+ }
+
+ const usagePercentage = getContextWindowUsagePercentage(
+ usage.perTurnToken,
+ usage.contextWindow,
+ );
+ const roundedPercentage = Math.round(usagePercentage);
+ const remainingPercentage = Math.max(0, 100 - roundedPercentage);
+ const usagePercentLabel = `${roundedPercentage}% ${t(I18nKey.CONVERSATION$USED)} (${remainingPercentage}% ${t(I18nKey.CONVERSATION$LEFT)})`;
+ const usageTokenSummary = `${formatCompactTokenCount(usage.perTurnToken)} / ${formatCompactTokenCount(usage.contextWindow)}`;
+ const tone = getContextFillTone(usagePercentage);
+
+ const openUsagePanel = () => {
+ setIsPopoverOpen(false);
+ navigateToTab("usage");
+ };
+
+ return (
+ <div className="relative shrink-0">
+ <StyledTooltip
+ content={t(I18nKey.CHAT_INTERFACE$SHOW_CONTEXT)}
+ placement="top"
+ >
+ <button
+ ref={triggerRef}
+ type="button"
+ className="flex size-8 items-center justify-center rounded-full hover:bg-[var(--oh-interactive-hover)] transition-colors"
+ aria-label={`${t(I18nKey.CHAT_INTERFACE$CONTEXT_WINDOW_METER_LABEL)}: ${usagePercentLabel}`}
+ aria-expanded={isPopoverOpen}
+ aria-haspopup="dialog"
+ data-testid="context-window-meter"
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsPopoverOpen((open) => !open);
+ }}
+ >
+ <ContextWindowRing percentage={usagePercentage} />
+ </button>
+ </StyledTooltip>
+
+ {isPopoverOpen && (
+ <div
+ ref={popoverRef}
+ data-testid="context-window-meter-popover"
+ className={cn(
+ "absolute bottom-full right-0 z-[60] mb-2 w-[280px]",
+ "flex flex-col gap-0.5 rounded-md border border-[var(--oh-border-subtle)] bg-tertiary px-1 py-1 shadow-lg",
+ )}
+ >
+ <div className="flex flex-col gap-2 px-2 py-1.5">
+ <div className="flex items-center justify-between gap-2 text-sm">
+ <span className="font-semibold text-[var(--oh-foreground)]">
+ {t(I18nKey.CONVERSATION$CONTEXT_WINDOW)}
+ </span>
+ <span className={cn("shrink-0 text-xs", TONE_LABEL_CLASS[tone])}>
+ {usagePercentLabel}
+ </span>
+ </div>
+
+ <button
+ type="button"
+ data-testid="context-window-meter-bar-button"
+ className="relative h-1.5 w-full rounded-full bg-[var(--oh-border)] cursor-pointer"
+ aria-label={t(I18nKey.COMMON$USAGE)}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openUsagePanel();
+ }}
+ >
+ <span
+ className={cn(
+ "absolute inset-y-0 left-0 rounded-full transition-all duration-300",
+ TONE_BAR_CLASS[tone],
+ )}
+ style={{ width: `${Math.min(100, usagePercentage)}%` }}
+ />
+ </button>
+
+ <div className="flex items-center justify-between gap-2">
+ <button
+ type="button"
+ data-testid="context-window-compact-button"
+ disabled={isDisabled}
+ aria-busy={isCompacting}
+ aria-label={t(I18nKey.CONVERSATION$COMPACT_CONTEXT)}
+ className={cn(
+ "inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs",
+ "text-[var(--oh-muted)] hover:bg-[var(--oh-interactive-hover)] hover:text-[var(--oh-foreground)]",
+ "transition-colors disabled:cursor-not-allowed disabled:opacity-50",
+ )}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ handleCompact();
+ }}
+ >
+ {isCompacting ? (
+ <Loader2 className="size-3 animate-spin" aria-hidden />
+ ) : (
+ <Minimize className="size-3" aria-hidden />
+ )}
+ <span>{t(I18nKey.CONVERSATION$COMPACT_CONTEXT)}</span>
+ </button>
+ <span className="text-xs text-[var(--oh-muted)]">
+ {usageTokenSummary}
+ </span>
+ </div>
+ </div>
+
+ <Divider inset="menu" />
+
+ <ContextMenuListItem
+ testId="context-window-plan-usage"
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openUsagePanel();
+ }}
+ >
+ <ConversationNameContextMenuIconText
+ icon={<Gauge size={16} />}
+ text={t(I18nKey.COMMON$USAGE)}
+ />
+ </ContextMenuListItem>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/features/chat/components/context-window-ring.tsx b/src/components/features/chat/components/context-window-ring.tsx
new file mode 100644
index 0000000000..84c3ab610e
--- /dev/null
+++ b/src/components/features/chat/components/context-window-ring.tsx
@@ -0,0 +1,59 @@
+import { cn } from "#/utils/utils";
+import { getContextFillTone } from "#/components/features/conversation/usage-panel/context-meter";
+
+const CONTEXT_WINDOW_RING_SIZE = 16;
+const CONTEXT_WINDOW_RING_STROKE = 2;
+
+const TONE_STROKE = {
+ neutral: "var(--oh-foreground)",
+ warning: "#f59e0b", // amber-500
+ danger: "#ef4444", // red-500
+} as const;
+
+interface ContextWindowRingProps {
+ percentage: number;
+ className?: string;
+}
+
+export function ContextWindowRing({
+ percentage,
+ className,
+}: ContextWindowRingProps) {
+ const radius = (CONTEXT_WINDOW_RING_SIZE - CONTEXT_WINDOW_RING_STROKE) / 2;
+ const circumference = 2 * Math.PI * radius;
+ const clampedPercentage = Math.min(100, Math.max(0, percentage));
+ const dashOffset = circumference - (clampedPercentage / 100) * circumference;
+ const tone = getContextFillTone(clampedPercentage);
+
+ return (
+ <svg
+ width={CONTEXT_WINDOW_RING_SIZE}
+ height={CONTEXT_WINDOW_RING_SIZE}
+ viewBox={`0 0 ${CONTEXT_WINDOW_RING_SIZE} ${CONTEXT_WINDOW_RING_SIZE}`}
+ className={cn("shrink-0", className)}
+ aria-hidden
+ >
+ <circle
+ cx={CONTEXT_WINDOW_RING_SIZE / 2}
+ cy={CONTEXT_WINDOW_RING_SIZE / 2}
+ r={radius}
+ fill="none"
+ stroke="var(--oh-border)"
+ strokeWidth={CONTEXT_WINDOW_RING_STROKE}
+ />
+ <circle
+ cx={CONTEXT_WINDOW_RING_SIZE / 2}
+ cy={CONTEXT_WINDOW_RING_SIZE / 2}
+ r={radius}
+ fill="none"
+ stroke={TONE_STROKE[tone]}
+ strokeWidth={CONTEXT_WINDOW_RING_STROKE}
+ strokeLinecap="round"
+ strokeDasharray={circumference}
+ strokeDashoffset={dashOffset}
+ transform={`rotate(-90 ${CONTEXT_WINDOW_RING_SIZE / 2} ${CONTEXT_WINDOW_RING_SIZE / 2})`}
+ className="transition-[stroke-dashoffset,stroke] duration-300"
+ />
+ </svg>
+ );
+}
diff --git a/src/components/features/conversation-panel/budget-display.tsx b/src/components/features/conversation-panel/budget-display.tsx
index a77ce49290..e693717ab6 100644
--- a/src/components/features/conversation-panel/budget-display.tsx
+++ b/src/components/features/conversation-panel/budget-display.tsx
@@ -18,7 +18,7 @@ export function BudgetDisplay({ cost, maxBudgetPerTask }: BudgetDisplayProps) {
}
return (
- <div className="border-b border-[var(--oh-border-subtle)]">
+ <div>
{maxBudgetPerTask !== null && maxBudgetPerTask > 0 ? (
<>
<BudgetProgressBar currentCost={cost} maxBudget={maxBudgetPerTask} />
diff --git a/src/components/features/conversation-panel/budget-progress-bar.tsx b/src/components/features/conversation-panel/budget-progress-bar.tsx
index 2f1994780f..80e7343ee0 100644
--- a/src/components/features/conversation-panel/budget-progress-bar.tsx
+++ b/src/components/features/conversation-panel/budget-progress-bar.tsx
@@ -13,10 +13,10 @@ export function BudgetProgressBar({
const isNearLimit = usagePercentage > 80;
return (
- <div className="w-full h-1.5 bg-tertiary rounded-full overflow-hidden mt-1">
+ <div className="relative mt-1 h-1.5 w-full rounded-full bg-tertiary">
<div
className={cn(
- "h-full transition-all duration-300",
+ "absolute inset-y-0 left-0 rounded-full transition-all duration-300",
isNearLimit ? "bg-red-500" : "bg-blue-500",
)}
// runtime usage-percentage width
diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx
index 5be1887d83..cbf723e888 100644
--- a/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx
+++ b/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx
@@ -12,10 +12,10 @@ import EditIcon from "#/icons/u-edit.svg?react";
import SkillsIcon from "#/icons/skills.svg?react";
import ToolsIcon from "#/icons/u-tools.svg?react";
import DownloadIcon from "#/icons/u-download.svg?react";
-import CreditCardIcon from "#/icons/u-credit-card.svg?react";
import CloseIcon from "#/icons/u-close.svg?react";
import DeleteIcon from "#/icons/u-delete.svg?react";
import { Divider } from "#/ui/divider";
+import { Gauge } from "lucide-react";
interface ConversationCardContextMenuProps {
onClose: () => void;
@@ -207,7 +207,7 @@ export function ConversationCardContextMenu({
onClick={onDisplayCost}
>
<ConversationNameContextMenuIconText
- icon={<CreditCardIcon width={16} height={16} />}
+ icon={<Gauge size={16} />}
text={t(I18nKey.BUTTON$DISPLAY_COST)}
/>
</ContextMenuListItem>
diff --git a/src/components/features/conversation/conversation-name-context-menu.tsx b/src/components/features/conversation/conversation-name-context-menu.tsx
index e287e76f9e..e834c06839 100644
--- a/src/components/features/conversation/conversation-name-context-menu.tsx
+++ b/src/components/features/conversation/conversation-name-context-menu.tsx
@@ -1,6 +1,6 @@
import React from "react";
import ReactDOM from "react-dom";
-import { ExternalLink, Share2 } from "lucide-react";
+import { ExternalLink, Gauge, Share2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
@@ -17,7 +17,6 @@ import SkillsIcon from "#/icons/skills.svg?react";
import FishingHookIcon from "#/icons/fishing-hook.svg?react";
import ToolsIcon from "#/icons/u-tools.svg?react";
import DownloadIcon from "#/icons/u-download.svg?react";
-import CreditCardIcon from "#/icons/u-credit-card.svg?react";
import CloseIcon from "#/icons/u-close.svg?react";
import DeleteIcon from "#/icons/u-delete.svg?react";
import CopyIcon from "#/icons/copy.svg?react";
@@ -267,7 +266,7 @@ export function ConversationNameContextMenu({
onClick={onDisplayCost}
>
<ConversationNameContextMenuIconText
- icon={<CreditCardIcon width={16} height={16} />}
+ icon={<Gauge size={16} />}
text={t(I18nKey.BUTTON$DISPLAY_COST)}
/>
</ContextMenuListItem>
diff --git a/src/components/features/conversation/conversation-name.tsx b/src/components/features/conversation/conversation-name.tsx
index c48a91cba7..9705d8f27b 100644
--- a/src/components/features/conversation/conversation-name.tsx
+++ b/src/components/features/conversation/conversation-name.tsx
@@ -13,7 +13,6 @@ import { SkillsModal } from "../conversation-panel/skills-modal";
import { HooksModal } from "../conversation-panel/hooks-modal";
import { ConfirmDeleteModal } from "../conversation-panel/confirm-delete-modal";
import { ConfirmStopModal } from "../conversation-panel/confirm-stop-modal";
-import { MetricsModal } from "./metrics-modal/metrics-modal";
import { TranscriptExportModal } from "./transcript-export-modal";
export function ConversationName() {
@@ -43,8 +42,6 @@ export function ConversationName() {
shareUrl,
handleConfirmDelete,
handleConfirmStop,
- metricsModalVisible,
- setMetricsModalVisible,
systemModalVisible,
setSystemModalVisible,
skillsModalVisible,
@@ -211,12 +208,6 @@ export function ConversationName() {
)}
</div>
- {/* Metrics Modal */}
- <MetricsModal
- isOpen={metricsModalVisible}
- onOpenChange={setMetricsModalVisible}
- />
-
{transcriptExportModalVisible && conversationId && (
<TranscriptExportModal
conversationId={conversationId}
diff --git a/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx b/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx
index cb23978ab2..5b3a47f17f 100644
--- a/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx
+++ b/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx
@@ -13,6 +13,7 @@ const FilesTab = lazy(() => import("#/routes/files-tab"));
const BrowserTab = lazy(() => import("#/routes/browser-tab"));
const PlannerTab = lazy(() => import("#/routes/planner-tab"));
const TaskListTab = lazy(() => import("#/routes/task-list-tab"));
+const UsageTab = lazy(() => import("#/routes/usage-tab"));
const Terminal = lazy(() => import("#/components/features/terminal/terminal"));
const TAB_CONFIG = {
@@ -21,6 +22,7 @@ const TAB_CONFIG = {
browser: { component: BrowserTab },
terminal: { component: Terminal },
planner: { component: PlannerTab },
+ usage: { component: UsageTab },
};
export function ConversationTabContent() {
diff --git a/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx b/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx
index 5e03495c21..66bf11b098 100644
--- a/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx
+++ b/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx
@@ -10,7 +10,7 @@ import {
type ConversationTab,
} from "#/stores/conversation-store";
import { I18nKey } from "#/i18n/declaration";
-import { Globe, ListTodo, SquareChevronRight } from "lucide-react";
+import { Gauge, Globe, ListTodo, SquareChevronRight } from "lucide-react";
import DocumentIcon from "#/icons/document.svg?react";
import PillIcon from "#/icons/pill.svg?react";
import PillFillIcon from "#/icons/pill-fill.svg?react";
@@ -102,6 +102,7 @@ export function ConversationTabsContextMenu({
i18nKey: I18nKey.COMMON$TERMINAL,
},
{ tab: "browser", icon: Globe, i18nKey: I18nKey.COMMON$BROWSER },
+ { tab: "usage", icon: Gauge, i18nKey: I18nKey.COMMON$USAGE },
];
if (hasTaskList) {
diff --git a/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx b/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx
index 2b030251b2..9fa2114168 100644
--- a/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx
+++ b/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { LayoutGroup } from "framer-motion";
-import { Globe, ListTodo, SquareChevronRight } from "lucide-react";
+import { Gauge, Globe, ListTodo, SquareChevronRight } from "lucide-react";
import DocumentIcon from "#/icons/document.svg?react";
import DoubleCheckIcon from "#/icons/double-check.svg?react";
import { EllipsisButton } from "#/components/features/conversation-panel/ellipsis-button";
@@ -119,6 +119,15 @@ export function ConversationTabs({
tooltipAriaLabel: t(I18nKey.COMMON$BROWSER),
label: t(I18nKey.COMMON$BROWSER),
},
+ {
+ tabValue: "usage",
+ isActive: isTabActive("usage"),
+ icon: Gauge,
+ onClick: () => selectTab("usage"),
+ tooltipContent: t(I18nKey.COMMON$USAGE),
+ tooltipAriaLabel: t(I18nKey.COMMON$USAGE),
+ label: t(I18nKey.COMMON$USAGE),
+ },
];
if (hasTaskList) {
diff --git a/src/components/features/conversation/metrics-modal/context-window-section.tsx b/src/components/features/conversation/metrics-modal/context-window-section.tsx
deleted file mode 100644
index 59b26ac59c..0000000000
--- a/src/components/features/conversation/metrics-modal/context-window-section.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-interface ContextWindowSectionProps {
- perTurnToken: number;
- contextWindow: number;
-}
-
-export function ContextWindowSection({
- perTurnToken,
- contextWindow,
-}: ContextWindowSectionProps) {
- const { t } = useTranslation("openhands");
-
- const usagePercentage =
- contextWindow > 0 ? (perTurnToken / contextWindow) * 100 : 0;
- const progressWidth = Math.min(100, usagePercentage);
-
- return (
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between">
- <span className="font-semibold">
- {t(I18nKey.CONVERSATION$CONTEXT_WINDOW)}
- </span>
- </div>
- <div className="w-full h-1.5 bg-tertiary rounded-full overflow-hidden">
- <div
- className="h-full bg-foreground transition-all duration-300"
- // runtime usage-percentage width
- style={{ width: `${progressWidth}%` }}
- />
- </div>
- <div className="flex justify-end">
- <span className="text-xs text-[var(--oh-muted)]">
- {perTurnToken.toLocaleString()} / {contextWindow.toLocaleString()} (
- {usagePercentage.toFixed(2)}% {t(I18nKey.CONVERSATION$USED)})
- </span>
- </div>
- </div>
- );
-}
diff --git a/src/components/features/conversation/metrics-modal/cost-section.tsx b/src/components/features/conversation/metrics-modal/cost-section.tsx
index beb2d33d54..a1cbec5b62 100644
--- a/src/components/features/conversation/metrics-modal/cost-section.tsx
+++ b/src/components/features/conversation/metrics-modal/cost-section.tsx
@@ -16,13 +16,13 @@ export function CostSection({ cost, maxBudgetPerTask }: CostSectionProps) {
return (
<>
- <div className="flex justify-between items-center pb-2">
- <span className="text-lg font-semibold">
+ <BudgetDisplay cost={cost} maxBudgetPerTask={maxBudgetPerTask} />
+ <div className="flex justify-between items-center border-t border-[var(--oh-border-subtle)] pt-2">
+ <span className="font-semibold">
{t(I18nKey.CONVERSATION$TOTAL_COST)}
</span>
<span className="font-semibold">${cost.toFixed(4)}</span>
</div>
- <BudgetDisplay cost={cost} maxBudgetPerTask={maxBudgetPerTask} />
</>
);
}
diff --git a/src/components/features/conversation/metrics-modal/empty-state.tsx b/src/components/features/conversation/metrics-modal/empty-state.tsx
deleted file mode 100644
index a4c598e5e1..0000000000
--- a/src/components/features/conversation/metrics-modal/empty-state.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-export function EmptyState() {
- const { t } = useTranslation("openhands");
-
- return (
- <div className="text-center">
- <p className="text-[var(--oh-muted)]">
- {t(I18nKey.CONVERSATION$NO_METRICS)}
- </p>
- </div>
- );
-}
diff --git a/src/components/features/conversation/metrics-modal/metric-row.tsx b/src/components/features/conversation/metrics-modal/metric-row.tsx
index bb1e134c0b..b1072521e2 100644
--- a/src/components/features/conversation/metrics-modal/metric-row.tsx
+++ b/src/components/features/conversation/metrics-modal/metric-row.tsx
@@ -1,10 +1,12 @@
import { ReactNode } from "react";
+import { cn } from "#/utils/utils";
interface MetricRowProps {
label: ReactNode;
value: ReactNode;
labelClassName?: string;
valueClassName?: string;
+ showBorder?: boolean;
}
export function MetricRow({
@@ -12,9 +14,15 @@ export function MetricRow({
value,
labelClassName = "",
valueClassName = "font-semibold",
+ showBorder = true,
}: MetricRowProps) {
return (
- <div className="flex justify-between items-center border-b border-[var(--oh-border-subtle)] pb-2">
+ <div
+ className={cn(
+ "flex justify-between items-center pb-2",
+ showBorder && "border-b border-[var(--oh-border-subtle)]",
+ )}
+ >
<span className={labelClassName}>{label}</span>
<span className={valueClassName}>{value}</span>
</div>
diff --git a/src/components/features/conversation/metrics-modal/metrics-modal-header.tsx b/src/components/features/conversation/metrics-modal/metrics-modal-header.tsx
deleted file mode 100644
index 85c4f29df7..0000000000
--- a/src/components/features/conversation/metrics-modal/metrics-modal-header.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { BaseModalTitle } from "#/components/shared/modals/confirmation-modals/base-modal";
-import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";
-import { I18nKey } from "#/i18n/declaration";
-
-interface MetricsModalHeaderProps {
- onClose: () => void;
-}
-
-export function MetricsModalHeader({ onClose }: MetricsModalHeaderProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <>
- <ModalCloseButton onClose={onClose} testId="close-metrics-modal" />
- <div className="w-full pr-6">
- <BaseModalTitle title={t(I18nKey.CONVERSATION$METRICS_INFO)} />
- </div>
- </>
- );
-}
diff --git a/src/components/features/conversation/metrics-modal/metrics-modal.tsx b/src/components/features/conversation/metrics-modal/metrics-modal.tsx
deleted file mode 100644
index 5d8ee8f409..0000000000
--- a/src/components/features/conversation/metrics-modal/metrics-modal.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { useMemo } from "react";
-import { MetricsModalHeader } from "./metrics-modal-header";
-import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
-import { ModalBody } from "#/components/shared/modals/modal-body";
-import { CostSection } from "./cost-section";
-import { UsageSection } from "./usage-section";
-import { ContextWindowSection } from "./context-window-section";
-import { EmptyState } from "./empty-state";
-import useMetricsStore from "#/stores/metrics-store";
-import { useActiveConversation } from "#/hooks/query/use-active-conversation";
-import { useConversationMetrics } from "#/hooks/query/use-conversation-metrics";
-
-interface MetricsModalProps {
- isOpen: boolean;
- onOpenChange: (open: boolean) => void;
-}
-
-export function MetricsModal({ isOpen, onOpenChange }: MetricsModalProps) {
- const storeMetrics = useMetricsStore();
- const { data: conversation } = useActiveConversation();
-
- const conversationId = conversation?.id;
- const conversationUrl = conversation?.conversation_url;
- const sessionApiKey = conversation?.session_api_key;
-
- const { data: conversationMetrics } = useConversationMetrics(
- conversationId,
- conversationUrl,
- sessionApiKey,
- isOpen,
- );
-
- const metrics = useMemo(() => {
- if (conversationMetrics) {
- return {
- cost: conversationMetrics.accumulated_cost,
- max_budget_per_task: conversationMetrics.max_budget_per_task,
- usage: conversationMetrics.accumulated_token_usage
- ? {
- prompt_tokens:
- conversationMetrics.accumulated_token_usage.prompt_tokens ?? 0,
- completion_tokens:
- conversationMetrics.accumulated_token_usage.completion_tokens ??
- 0,
- cache_read_tokens:
- conversationMetrics.accumulated_token_usage.cache_read_tokens ??
- 0,
- cache_write_tokens:
- conversationMetrics.accumulated_token_usage
- .cache_write_tokens ?? 0,
- context_window:
- conversationMetrics.accumulated_token_usage.context_window ?? 0,
- per_turn_token:
- conversationMetrics.accumulated_token_usage.per_turn_token ?? 0,
- }
- : null,
- };
- }
-
- return storeMetrics;
- }, [conversationMetrics, storeMetrics]);
-
- if (!isOpen) return null;
-
- return (
- <ModalBackdrop onClose={() => onOpenChange(false)}>
- <ModalBody
- testID="metrics-modal"
- className="relative items-start border border-[var(--oh-border)]"
- >
- <MetricsModalHeader onClose={() => onOpenChange(false)} />
- <div className="w-full">
- {(metrics?.cost !== null || metrics?.usage !== null) && (
- <div className="rounded-md border border-[var(--oh-border)] bg-surface-raised p-3">
- <div className="grid gap-3">
- <CostSection
- cost={metrics?.cost ?? null}
- maxBudgetPerTask={metrics?.max_budget_per_task ?? null}
- />
-
- {metrics?.usage !== null && (
- <>
- <UsageSection usage={metrics.usage} />
- <ContextWindowSection
- perTurnToken={metrics.usage.per_turn_token}
- contextWindow={metrics.usage.context_window}
- />
- </>
- )}
- </div>
- </div>
- )}
-
- {!metrics?.cost && !metrics?.usage && (
- <div className="rounded-md border border-[var(--oh-border)] bg-surface-raised p-3">
- <EmptyState />
- </div>
- )}
- </div>
- </ModalBody>
- </ModalBackdrop>
- );
-}
diff --git a/src/components/features/conversation/metrics-modal/usage-section.tsx b/src/components/features/conversation/metrics-modal/usage-section.tsx
index 91d133cb20..9ddf92a5bc 100644
--- a/src/components/features/conversation/metrics-modal/usage-section.tsx
+++ b/src/components/features/conversation/metrics-modal/usage-section.tsx
@@ -46,6 +46,7 @@ export function UsageSection({ usage }: UsageSectionProps) {
value={(usage.prompt_tokens + usage.completion_tokens).toLocaleString()}
labelClassName="font-semibold"
valueClassName="font-bold"
+ showBorder={false}
/>
</>
);
diff --git a/src/components/features/conversation/usage-panel/compact-context-button.test.tsx b/src/components/features/conversation/usage-panel/compact-context-button.test.tsx
new file mode 100644
index 0000000000..096101e1b7
--- /dev/null
+++ b/src/components/features/conversation/usage-panel/compact-context-button.test.tsx
@@ -0,0 +1,88 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { AgentState } from "#/types/agent-state";
+import { CompactContextButton } from "./compact-context-button";
+
+const mutateMock = vi.fn();
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: () => ({
+ data: {
+ id: "conv-1",
+ conversation_url: null,
+ session_api_key: null,
+ },
+ }),
+}));
+
+vi.mock("#/hooks/use-agent-state", () => ({
+ useAgentState: () => ({ curAgentState: AgentState.AWAITING_USER_INPUT }),
+}));
+
+vi.mock("#/hooks/mutation/use-condense-conversation", () => ({
+ useCondenseConversation: () => ({
+ mutate: mutateMock,
+ isPending: false,
+ }),
+}));
+
+vi.mock("#/hooks/use-await-context-compaction", () => ({
+ useAwaitContextCompaction: vi.fn(),
+ buildContextCompactionResult: vi.fn(),
+}));
+
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: vi.fn(),
+ displaySuccessToast: vi.fn(),
+}));
+
+function renderButton(fillPercent: number) {
+ return render(
+ <QueryClientProvider client={new QueryClient()}>
+ <CompactContextButton fillPercent={fillPercent} />
+ </QueryClientProvider>,
+ );
+}
+
+describe("CompactContextButton", () => {
+ beforeEach(() => {
+ mutateMock.mockClear();
+ });
+
+ it("puts the explanation in an info control beside a content-sized button", () => {
+ renderButton(40);
+
+ expect(
+ screen.queryByText("CONVERSATION$COMPACT_CONTEXT_DESCRIPTION"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("CONVERSATION$CONTEXT_FILLING_UP"),
+ ).not.toBeInTheDocument();
+
+ const info = screen.getByTestId("compact-context-info");
+ expect(info).toHaveAttribute(
+ "aria-label",
+ "CONVERSATION$COMPACT_CONTEXT_DESCRIPTION",
+ );
+
+ const button = screen.getByTestId("compact-context-button");
+ expect(button).toHaveClass("w-fit");
+ expect(button).not.toHaveClass("w-full");
+ });
+
+ it("adds a high-fill warning once the context passes the warning threshold", () => {
+ renderButton(75);
+
+ expect(
+ screen.getByText("CONVERSATION$CONTEXT_FILLING_UP"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("compact-context-button")).toHaveTextContent(
+ "CONVERSATION$COMPACT_CONTEXT",
+ );
+ });
+});
diff --git a/src/components/features/conversation/usage-panel/compact-context-button.tsx b/src/components/features/conversation/usage-panel/compact-context-button.tsx
new file mode 100644
index 0000000000..d499305d97
--- /dev/null
+++ b/src/components/features/conversation/usage-panel/compact-context-button.tsx
@@ -0,0 +1,79 @@
+import { Info, Loader2, Minimize } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";
+import { useCompactContextAction } from "#/hooks/use-compact-context-action";
+import { CONTEXT_FILL_WARNING_PERCENT } from "./context-meter";
+
+interface CompactContextButtonProps {
+ /** Current context fill percentage; past the warning threshold the button becomes a prominent CTA. */
+ fillPercent: number;
+ /** Optional live per-turn token count used as a fallback snapshot before compaction. */
+ perTurnToken?: number;
+}
+
+/**
+ * "Compact context" action: POSTs `/api/conversations/{id}/condense` with a
+ * spinner while in flight and toasts for start, completion (with tokens
+ * freed), and failure. Disabled while the agent is actively running (the
+ * server would race the active step) and promoted to a primary
+ * call-to-action once the context fill passes
+ * {@link CONTEXT_FILL_WARNING_PERCENT}.
+ */
+export function CompactContextButton({
+ fillPercent,
+ perTurnToken = 0,
+}: CompactContextButtonProps) {
+ const { t } = useTranslation("openhands");
+ const { handleCompact, isCompacting, isDisabled, description } =
+ useCompactContextAction(perTurnToken);
+ const isHighFill = fillPercent > CONTEXT_FILL_WARNING_PERCENT;
+
+ return (
+ <div
+ data-testid="compact-context-section"
+ className="flex flex-col gap-2 border-t border-[var(--oh-border-subtle)] pt-3"
+ >
+ {isHighFill && (
+ <span className="text-xs text-amber-500">
+ {t(I18nKey.CONVERSATION$CONTEXT_FILLING_UP)}
+ </span>
+ )}
+ <div className="flex items-center gap-2">
+ <BrandButton
+ testId="compact-context-button"
+ type="button"
+ variant={isHighFill ? "primary" : "secondary"}
+ isDisabled={isDisabled}
+ aria-busy={isCompacting}
+ onClick={handleCompact}
+ startContent={
+ isCompacting ? (
+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
+ ) : (
+ <Minimize className="h-4 w-4" aria-hidden />
+ )
+ }
+ className="w-fit"
+ >
+ {t(I18nKey.CONVERSATION$COMPACT_CONTEXT)}
+ </BrandButton>
+ <StyledTooltip
+ content={description}
+ placement="top"
+ tooltipClassName="max-w-[220px] text-xs font-normal leading-relaxed whitespace-normal"
+ >
+ <button
+ type="button"
+ data-testid="compact-context-info"
+ aria-label={description}
+ className="flex size-5 shrink-0 items-center justify-center rounded-full text-[var(--oh-muted)] hover:text-[var(--oh-foreground)] transition-colors cursor-help"
+ >
+ <Info className="size-3.5" aria-hidden />
+ </button>
+ </StyledTooltip>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/conversation/usage-panel/context-meter.test.tsx b/src/components/features/conversation/usage-panel/context-meter.test.tsx
new file mode 100644
index 0000000000..9c8d99df37
--- /dev/null
+++ b/src/components/features/conversation/usage-panel/context-meter.test.tsx
@@ -0,0 +1,59 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { ContextMeter } from "./context-meter";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+// The percentage math itself (zero-window guard, 100% cap) is covered by
+// __tests__/utils/format-token-count.test.ts; these tests cover rendering.
+describe("ContextMeter", () => {
+ it("renders the raw token numbers", () => {
+ render(<ContextMeter perTurnToken={17994} contextWindow={1000000} />);
+
+ expect(screen.getByTestId("context-meter")).toHaveTextContent(
+ `${(17994).toLocaleString()} / ${(1000000).toLocaleString()}`,
+ );
+ });
+
+ it("stays neutral below the warning threshold", () => {
+ render(<ContextMeter perTurnToken={50} contextWindow={100} />);
+
+ const bar = screen.getByTestId("context-meter-bar");
+ expect(bar).toHaveClass("bg-foreground");
+ expect(bar).toHaveClass("rounded-full");
+ expect(bar.style.width).toBe("50%");
+ });
+
+ it("warns above 70% fill", () => {
+ render(<ContextMeter perTurnToken={75} contextWindow={100} />);
+
+ expect(screen.getByTestId("context-meter-bar")).toHaveClass("bg-amber-500");
+ });
+
+ it("signals danger above 90% fill", () => {
+ render(<ContextMeter perTurnToken={95} contextWindow={100} />);
+
+ expect(screen.getByTestId("context-meter-bar")).toHaveClass("bg-red-500");
+ expect(screen.getByTestId("context-meter")).toHaveTextContent(
+ "95% CONVERSATION$USED (5% CONVERSATION$LEFT)",
+ );
+ });
+
+ it("caps the bar width at 100%", () => {
+ render(<ContextMeter perTurnToken={150} contextWindow={100} />);
+
+ expect(screen.getByTestId("context-meter-bar").style.width).toBe("100%");
+ });
+
+ it("shows an unknown-window state instead of 'x / 0' when the window is unreported", () => {
+ render(<ContextMeter perTurnToken={31778} contextWindow={0} />);
+
+ const meter = screen.getByTestId("context-meter");
+ expect(meter).toHaveTextContent("CONVERSATION$CONTEXT_WINDOW_UNKNOWN");
+ expect(meter).toHaveTextContent((31778).toLocaleString());
+ expect(meter).not.toHaveTextContent("/ 0");
+ expect(meter).not.toHaveTextContent("0.0%");
+ });
+});
diff --git a/src/components/features/conversation/usage-panel/context-meter.tsx b/src/components/features/conversation/usage-panel/context-meter.tsx
new file mode 100644
index 0000000000..dabecf0dcc
--- /dev/null
+++ b/src/components/features/conversation/usage-panel/context-meter.tsx
@@ -0,0 +1,103 @@
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
+import { getContextWindowUsagePercentage } from "#/utils/format-token-count";
+
+/** Context fill percentage above which the meter warns and the compact CTA becomes prominent. */
+export const CONTEXT_FILL_WARNING_PERCENT = 70;
+/** Context fill percentage above which the meter signals danger. */
+export const CONTEXT_FILL_DANGER_PERCENT = 90;
+
+export type ContextFillTone = "neutral" | "warning" | "danger";
+
+export function getContextFillTone(usagePercentage: number): ContextFillTone {
+ if (usagePercentage > CONTEXT_FILL_DANGER_PERCENT) {
+ return "danger";
+ }
+ if (usagePercentage > CONTEXT_FILL_WARNING_PERCENT) {
+ return "warning";
+ }
+ return "neutral";
+}
+
+interface ContextMeterProps {
+ /** Tokens currently held in the agent's context (`per_turn_token`). */
+ perTurnToken: number;
+ /** Model context window size in tokens. */
+ contextWindow: number;
+}
+
+/**
+ * Context-fill progress bar: neutral below
+ * {@link CONTEXT_FILL_WARNING_PERCENT}, amber above it, red above
+ * {@link CONTEXT_FILL_DANGER_PERCENT}. Shows the raw token numbers underneath.
+ */
+export function ContextMeter({
+ perTurnToken,
+ contextWindow,
+}: ContextMeterProps) {
+ const { t } = useTranslation("openhands");
+
+ // Some models (e.g. via OpenRouter) report no context window size; show the
+ // raw token count without a misleading "x / 0" or "0.0% used" readout.
+ const isWindowUnknown = contextWindow <= 0;
+
+ // Capped at 100 by getContextWindowUsagePercentage, so the bar width and
+ // the label never read above a full window.
+ const usagePercentage = getContextWindowUsagePercentage(
+ perTurnToken,
+ contextWindow,
+ );
+ const tone = getContextFillTone(usagePercentage);
+ const isWarning = tone === "warning";
+ const isDanger = tone === "danger";
+ const roundedPercentage = Math.round(usagePercentage);
+ const remainingPercentage = Math.max(0, 100 - roundedPercentage);
+ const usagePercentLabel = isWindowUnknown
+ ? t(I18nKey.CONVERSATION$CONTEXT_WINDOW_UNKNOWN)
+ : `${roundedPercentage}% ${t(I18nKey.CONVERSATION$USED)} (${remainingPercentage}% ${t(I18nKey.CONVERSATION$LEFT)})`;
+
+ return (
+ <div data-testid="context-meter" className="flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="font-semibold">
+ {t(I18nKey.CONVERSATION$CONTEXT_WINDOW)}
+ </span>
+ <span
+ className={cn(
+ "shrink-0 text-xs",
+ isDanger
+ ? "text-red-500"
+ : isWarning
+ ? "text-amber-500"
+ : "text-[var(--oh-muted)]",
+ )}
+ >
+ {usagePercentLabel}
+ </span>
+ </div>
+ <div className="relative h-1.5 w-full rounded-full bg-tertiary">
+ <div
+ data-testid="context-meter-bar"
+ className={cn(
+ "absolute inset-y-0 left-0 rounded-full transition-all duration-300",
+ isDanger
+ ? "bg-red-500"
+ : isWarning
+ ? "bg-amber-500"
+ : "bg-foreground",
+ )}
+ // runtime usage-percentage width
+ style={{ width: `${usagePercentage}%` }}
+ />
+ </div>
+ <div className="flex justify-end">
+ <span className="text-xs text-[var(--oh-muted)]">
+ {isWindowUnknown
+ ? perTurnToken.toLocaleString()
+ : `${perTurnToken.toLocaleString()} / ${contextWindow.toLocaleString()}`}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/conversation/usage-panel/provider-balance-card.tsx b/src/components/features/conversation/usage-panel/provider-balance-card.tsx
new file mode 100644
index 0000000000..2f5f8cee0e
--- /dev/null
+++ b/src/components/features/conversation/usage-panel/provider-balance-card.tsx
@@ -0,0 +1,79 @@
+import { RefreshCw } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useLLMBalance } from "#/hooks/query/use-llm-balance";
+import { MetricRow } from "../metrics-modal/metric-row";
+import { cn } from "#/utils/utils";
+
+function formatCredits(amount: number): string {
+ return `$${amount.toFixed(2)}`;
+}
+
+/**
+ * Remaining credits for the active LLM provider (OpenRouter). Fetched once
+ * per conversation load with a manual refresh icon; hidden entirely when the
+ * agent server has no `/api/llm/balance` endpoint (404) or the request
+ * fails, so older servers degrade gracefully.
+ */
+export function ProviderBalanceCard() {
+ const { t } = useTranslation("openhands");
+ const { data: conversation } = useActiveConversation();
+ const {
+ data: balance,
+ isError,
+ isFetching,
+ refetch,
+ } = useLLMBalance(conversation?.id);
+
+ if (!balance || isError) return null;
+
+ const hasCap = balance.limit !== null && balance.limitRemaining !== null;
+
+ return (
+ <div
+ data-testid="provider-balance-card"
+ className="rounded-md border border-[var(--oh-border)] bg-surface-raised p-3"
+ >
+ <div className="flex items-center justify-between pb-2">
+ <span className="font-semibold">
+ {t(I18nKey.CONVERSATION$PROVIDER_BALANCE)}
+ </span>
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-[var(--oh-muted)]">
+ {balance.provider}
+ {balance.isFreeTier
+ ? ` · ${t(I18nKey.CONVERSATION$FREE_TIER)}`
+ : null}
+ </span>
+ <button
+ type="button"
+ data-testid="provider-balance-refresh"
+ aria-label={t(I18nKey.BUTTON$REFRESH)}
+ disabled={isFetching}
+ onClick={() => refetch()}
+ className="cursor-pointer text-[var(--oh-muted)] hover:text-[var(--oh-foreground)] disabled:cursor-default"
+ >
+ <RefreshCw
+ className={cn("h-3.5 w-3.5", isFetching && "animate-spin")}
+ />
+ </button>
+ </div>
+ </div>
+ <div className="grid gap-3">
+ {hasCap ? (
+ <MetricRow
+ label={t(I18nKey.CONVERSATION$CREDITS_REMAINING)}
+ value={formatCredits(balance.limitRemaining ?? 0)}
+ />
+ ) : null}
+ <MetricRow
+ label={t(I18nKey.CONVERSATION$CREDITS_USED)}
+ value={formatCredits(balance.usage)}
+ valueClassName={hasCap ? "" : "font-semibold"}
+ labelClassName={hasCap ? "text-[var(--oh-muted)]" : ""}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/conversation/usage-panel/usage-panel.tsx b/src/components/features/conversation/usage-panel/usage-panel.tsx
new file mode 100644
index 0000000000..41a75274a1
--- /dev/null
+++ b/src/components/features/conversation/usage-panel/usage-panel.tsx
@@ -0,0 +1,87 @@
+import { Gauge } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { ConversationTabEmptyState } from "#/components/features/conversation/conversation-tab-empty-state";
+import { useLiveConversationMetrics } from "#/hooks/use-live-conversation-metrics";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { CostSection } from "../metrics-modal/cost-section";
+import { UsageSection } from "../metrics-modal/usage-section";
+import { CompactContextButton } from "./compact-context-button";
+import { ContextMeter } from "./context-meter";
+import { ProviderBalanceCard } from "./provider-balance-card";
+import { getContextWindowUsagePercentage } from "#/utils/format-token-count";
+
+/**
+ * "Usage" right-panel tab: context-fill meter with a manual "Compact
+ * context" action, accumulated token/cost stats, and the provider credit
+ * balance (when the agent server reports one).
+ *
+ * Metrics come from {@link useLiveConversationMetrics}: live WebSocket
+ * updates plus a 30s REST poll while the tab is mounted.
+ */
+export function UsagePanel() {
+ const { t } = useTranslation("openhands");
+ const metrics = useLiveConversationMetrics();
+ const { data: conversation } = useActiveConversation();
+ // ACP conversations (e.g. Claude Code) draw on the CLI's own subscription
+ // plan; the dollar figure is an API-equivalent estimate, not a bill.
+ const isAcp = conversation?.agent_kind === "acp";
+
+ const { usage } = metrics;
+ const hasMetrics = metrics.cost !== null || usage !== null;
+
+ if (!hasMetrics) {
+ return (
+ <ConversationTabEmptyState icon={<Gauge />}>
+ {t(I18nKey.CONVERSATION$NO_METRICS)}
+ </ConversationTabEmptyState>
+ );
+ }
+
+ return (
+ <main
+ data-testid="usage-panel"
+ className="h-full overflow-y-auto custom-scrollbar-always flex flex-col gap-3 p-3"
+ >
+ {usage !== null && (
+ <div className="rounded-md border border-[var(--oh-border)] bg-surface-raised p-3">
+ <div className="grid gap-3">
+ <ContextMeter
+ perTurnToken={usage.per_turn_token}
+ contextWindow={usage.context_window}
+ />
+ <CompactContextButton
+ fillPercent={getContextWindowUsagePercentage(
+ usage.per_turn_token,
+ usage.context_window,
+ )}
+ perTurnToken={usage.per_turn_token}
+ />
+ </div>
+ </div>
+ )}
+
+ <div className="rounded-md border border-[var(--oh-border)] bg-surface-raised p-3">
+ <div className="grid gap-3">
+ <div className="flex justify-between items-center pb-2">
+ <span className="text-lg font-semibold">
+ {t(I18nKey.CONVERSATION$TOKEN_USAGE)}
+ </span>
+ </div>
+ {isAcp && (
+ <span className="text-xs text-[var(--oh-muted)]">
+ {t(I18nKey.CONVERSATION$PLAN_USAGE_NOTE)}
+ </span>
+ )}
+ {usage !== null && <UsageSection usage={usage} />}
+ <CostSection
+ cost={metrics.cost}
+ maxBudgetPerTask={metrics.max_budget_per_task}
+ />
+ </div>
+ </div>
+
+ <ProviderBalanceCard />
+ </main>
+ );
+}
diff --git a/src/constants/llm-balance.ts b/src/constants/llm-balance.ts
new file mode 100644
index 0000000000..a8e045c996
--- /dev/null
+++ b/src/constants/llm-balance.ts
@@ -0,0 +1,14 @@
+/**
+ * Agent-server endpoint reporting the LLM provider's credit balance.
+ * Servers without balance support (or providers that can't report one)
+ * answer 404 — callers must treat that as "hide the balance UI".
+ */
+export const LLM_BALANCE_PATH = "/api/llm/balance";
+
+/**
+ * Ceiling on a single balance request. A server that accepts the connection
+ * and then never answers would otherwise leave the request in flight forever:
+ * the query sets `retry: false`, which suppresses retries but does not bound a
+ * stuck request, so the balance card would stay hidden with nothing surfaced.
+ */
+export const LLM_BALANCE_TIMEOUT_MS = 10_000;
diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsx
index d1e984dd30..5c9d93365b 100644
--- a/src/contexts/conversation-websocket-context.tsx
+++ b/src/contexts/conversation-websocket-context.tsx
@@ -58,7 +58,7 @@ import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useConversationStore } from "#/stores/conversation-store";
import { trackError } from "#/utils/error-handler";
import { useReadConversationFile } from "#/hooks/mutation/use-read-conversation-file";
-import useMetricsStore from "#/stores/metrics-store";
+import useMetricsStore, { type MetricsState } from "#/stores/metrics-store";
import { useConversationHistory } from "#/hooks/query/use-conversation-history";
import { setConversationState } from "#/utils/conversation-local-storage";
import {
@@ -191,30 +191,61 @@ export function ConversationWebSocketProvider({
// Helper function to update metrics from stats event
const updateMetricsFromStats = useCallback(
(event: ConversationStateUpdateEventStats) => {
- if (event.value.usage_to_metrics?.agent) {
- const agentMetrics = event.value.usage_to_metrics.agent;
- const metrics = {
- cost: agentMetrics.accumulated_cost,
- max_budget_per_task: agentMetrics.max_budget_per_task ?? null,
- usage: agentMetrics.accumulated_token_usage
- ? {
- prompt_tokens:
- agentMetrics.accumulated_token_usage.prompt_tokens,
- completion_tokens:
- agentMetrics.accumulated_token_usage.completion_tokens,
- cache_read_tokens:
- agentMetrics.accumulated_token_usage.cache_read_tokens,
- cache_write_tokens:
- agentMetrics.accumulated_token_usage.cache_write_tokens,
- context_window:
- agentMetrics.accumulated_token_usage.context_window,
- per_turn_token:
- agentMetrics.accumulated_token_usage.per_turn_token,
- }
- : null,
- };
- useMetricsStore.getState().setMetrics(metrics);
+ const usageToMetrics = event.value.usage_to_metrics;
+ if (!usageToMetrics) {
+ return;
}
+
+ // usage_to_metrics is keyed by arbitrary LLM usage ids ("default",
+ // "condenser", "profile:<name>:<uuid>", …) — combine across all of
+ // them, mirroring getCombinedMetrics on the REST path.
+ const combined = Object.values(usageToMetrics).reduce<{
+ cost: number;
+ maxBudgetPerTask: number | null;
+ usage: MetricsState["usage"];
+ }>(
+ (acc, metrics) => {
+ acc.cost += metrics.accumulated_cost;
+ if (
+ acc.maxBudgetPerTask === null &&
+ metrics.max_budget_per_task !== null
+ ) {
+ acc.maxBudgetPerTask = metrics.max_budget_per_task;
+ }
+ const tokenUsage = metrics.accumulated_token_usage;
+ if (tokenUsage) {
+ acc.usage = {
+ prompt_tokens:
+ (acc.usage?.prompt_tokens ?? 0) + tokenUsage.prompt_tokens,
+ completion_tokens:
+ (acc.usage?.completion_tokens ?? 0) +
+ tokenUsage.completion_tokens,
+ cache_read_tokens:
+ (acc.usage?.cache_read_tokens ?? 0) +
+ tokenUsage.cache_read_tokens,
+ cache_write_tokens:
+ (acc.usage?.cache_write_tokens ?? 0) +
+ tokenUsage.cache_write_tokens,
+ context_window: Math.max(
+ acc.usage?.context_window ?? 0,
+ tokenUsage.context_window,
+ ),
+ per_turn_token: Math.max(
+ acc.usage?.per_turn_token ?? 0,
+ tokenUsage.per_turn_token,
+ ),
+ };
+ }
+ return acc;
+ },
+ { cost: 0, maxBudgetPerTask: null, usage: null },
+ );
+
+ useMetricsStore.getState().setMetrics({
+ cost: combined.cost,
+ max_budget_per_task: combined.maxBudgetPerTask,
+ usage: combined.usage,
+ });
},
[],
);
@@ -257,6 +288,11 @@ export function ConversationWebSocketProvider({
// half-applied state (events gone but the old id still reported).
clearEventsForConversation(nextId);
resetBrowserStore();
+ // The metrics store is conversation-scoped state too: without a reset the
+ // previous conversation's usage/cost keeps rendering in the new
+ // conversation's meter until fresh WS stats arrive — and a brand-new
+ // conversation sends none, so the stale figure stuck indefinitely.
+ useMetricsStore.getState().resetMetrics();
}, [conversationId, clearEventsForConversation, resetBrowserStore]);
useLayoutEffect(() => {
diff --git a/src/hooks/mutation/use-condense-conversation.ts b/src/hooks/mutation/use-condense-conversation.ts
new file mode 100644
index 0000000000..65eb80212c
--- /dev/null
+++ b/src/hooks/mutation/use-condense-conversation.ts
@@ -0,0 +1,31 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+
+interface CondenseConversationVariables {
+ conversationId: string;
+ conversationUrl: string | null;
+ sessionApiKey: string | null;
+}
+
+/**
+ * Manually compact ("condense") a conversation's context via
+ * `POST /api/conversations/{id}/condense`. Refreshes the usage metrics
+ * afterwards so the context meter reflects the shrunken history.
+ */
+export const useCondenseConversation = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: (variables: CondenseConversationVariables) =>
+ AgentServerConversationService.condenseConversation(
+ variables.conversationId,
+ variables.conversationUrl,
+ variables.sessionApiKey,
+ ),
+ onSettled: (_, __, variables) => {
+ queryClient.invalidateQueries({
+ queryKey: ["conversation-metrics", variables.conversationId],
+ });
+ },
+ });
+};
diff --git a/src/hooks/query/use-conversation-metrics.ts b/src/hooks/query/use-conversation-metrics.ts
index aab0be3fd7..351907368f 100644
--- a/src/hooks/query/use-conversation-metrics.ts
+++ b/src/hooks/query/use-conversation-metrics.ts
@@ -30,7 +30,11 @@ export const useConversationMetrics = (
);
return getCombinedMetrics(conversationInfo);
},
- enabled: enabled && !!conversationId && !!conversationUrl,
+ // conversation_url is only set for cloud conversations; local ones are
+ // served by the ConversationClient fallback in getRuntimeConversation.
+ // Gating on it left local conversations with no REST snapshot at all
+ // (zeros after a page reload until live WS metrics arrived).
+ enabled: enabled && !!conversationId,
staleTime: 1000 * 30,
gcTime: 1000 * 60 * 5,
refetchInterval: 1000 * 30,
diff --git a/src/hooks/query/use-llm-balance.ts b/src/hooks/query/use-llm-balance.ts
new file mode 100644
index 0000000000..4cb17c7a78
--- /dev/null
+++ b/src/hooks/query/use-llm-balance.ts
@@ -0,0 +1,28 @@
+import { useQuery } from "@tanstack/react-query";
+import LLMBalanceService from "#/api/llm-balance-service";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+
+/**
+ * Provider credit balance for the active local agent server.
+ *
+ * Fetched once per conversation load (the query key includes the
+ * conversation id); use `refetch()` for the manual refresh affordance.
+ * `data === null` means the server/provider doesn't support balance
+ * reporting (404) — hide the UI. Errors also hide the UI (`retry: false`,
+ * consumers check `isError`).
+ */
+export const useLLMBalance = (conversationId: string | null | undefined) => {
+ const { backend } = useActiveBackend();
+
+ return useQuery({
+ queryKey: ["llm-balance", backend.id, conversationId],
+ queryFn: () => LLMBalanceService.getBalance(),
+ // Cloud conversations talk to the hosted app API, which has no
+ // /api/llm/balance endpoint — don't probe it.
+ enabled: backend.kind !== "cloud" && !!conversationId,
+ staleTime: Infinity,
+ gcTime: 1000 * 60 * 5,
+ retry: false,
+ refetchOnWindowFocus: false,
+ });
+};
diff --git a/src/hooks/use-await-context-compaction.test.ts b/src/hooks/use-await-context-compaction.test.ts
new file mode 100644
index 0000000000..6ed550a3fe
--- /dev/null
+++ b/src/hooks/use-await-context-compaction.test.ts
@@ -0,0 +1,178 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import useMetricsStore from "#/stores/metrics-store";
+import { useEventStore } from "#/stores/use-event-store";
+import type { OpenHandsEvent } from "#/types/agent-server/core";
+import {
+ buildContextCompactionResult,
+ useAwaitContextCompaction,
+} from "./use-await-context-compaction";
+
+function condensationEvent(id: string): OpenHandsEvent {
+ return {
+ id,
+ timestamp: new Date().toISOString(),
+ source: "environment",
+ kind: "Condensation",
+ forgotten_event_ids: ["a", "b"],
+ } as OpenHandsEvent;
+}
+
+describe("buildContextCompactionResult", () => {
+ it("computes tokens saved without going negative", () => {
+ expect(buildContextCompactionResult(1000, 400, "compacted")).toEqual({
+ beforeToken: 1000,
+ afterToken: 400,
+ savedToken: 600,
+ outcome: "compacted",
+ });
+ expect(buildContextCompactionResult(400, 500, "no_change").savedToken).toBe(
+ 0,
+ );
+ });
+});
+
+describe("useAwaitContextCompaction", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ useEventStore.getState().clearEvents();
+ useMetricsStore.getState().setMetrics({
+ cost: null,
+ max_budget_per_task: null,
+ usage: {
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 100_000,
+ per_turn_token: 10_000,
+ },
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ useEventStore.getState().clearEvents();
+ });
+
+ it("reports tokens freed once condensation lands and metrics drop", () => {
+ const onComplete = vi.fn();
+
+ renderHook(() =>
+ useAwaitContextCompaction({
+ beforeToken: 10_000,
+ onComplete,
+ }),
+ );
+
+ act(() => {
+ useEventStore.getState().addEvent(condensationEvent("cond-1"));
+ useMetricsStore.getState().setMetrics({
+ cost: null,
+ max_budget_per_task: null,
+ usage: {
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 100_000,
+ per_turn_token: 4_000,
+ },
+ });
+ });
+
+ expect(onComplete).toHaveBeenCalledWith({
+ beforeToken: 10_000,
+ afterToken: 4_000,
+ savedToken: 6_000,
+ outcome: "compacted",
+ });
+ });
+
+ it("finishes after the settle window when metrics do not drop", () => {
+ const onComplete = vi.fn();
+
+ renderHook(() =>
+ useAwaitContextCompaction({
+ beforeToken: 10_000,
+ onComplete,
+ }),
+ );
+
+ act(() => {
+ useEventStore.getState().addEvent(condensationEvent("cond-2"));
+ });
+ expect(onComplete).not.toHaveBeenCalled();
+
+ act(() => {
+ vi.advanceTimersByTime(2_500);
+ });
+
+ expect(onComplete).toHaveBeenCalledWith({
+ beforeToken: 10_000,
+ afterToken: 10_000,
+ savedToken: 0,
+ outcome: "no_change",
+ });
+ });
+
+ it("reports timeout when no condensation event arrives in time", () => {
+ const onComplete = vi.fn();
+
+ renderHook(() =>
+ useAwaitContextCompaction({
+ beforeToken: 10_000,
+ onComplete,
+ }),
+ );
+
+ act(() => {
+ vi.advanceTimersByTime(90_000);
+ });
+
+ expect(onComplete).toHaveBeenCalledWith({
+ beforeToken: 10_000,
+ afterToken: 10_000,
+ savedToken: 0,
+ outcome: "timeout",
+ });
+ });
+
+ it("detects a condensation that landed before the post-ack effect started", () => {
+ // The condense POST can return only after the server already emitted its
+ // Condensation event. The pre-request baseline (captured before the POST
+ // fired) must not contain it, so it still counts as new.
+ const baseline = new Set(useEventStore.getState().eventIds);
+ act(() => {
+ useEventStore.getState().addEvent(condensationEvent("cond-early"));
+ useMetricsStore.getState().setMetrics({
+ cost: null,
+ max_budget_per_task: null,
+ usage: {
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 100_000,
+ per_turn_token: 4_000,
+ },
+ });
+ });
+
+ const onComplete = vi.fn();
+ renderHook(() =>
+ useAwaitContextCompaction({
+ beforeToken: 10_000,
+ baselineEventIds: baseline,
+ onComplete,
+ }),
+ );
+
+ expect(onComplete).toHaveBeenCalledWith({
+ beforeToken: 10_000,
+ afterToken: 4_000,
+ savedToken: 6_000,
+ outcome: "compacted",
+ });
+ });
+});
diff --git a/src/hooks/use-await-context-compaction.ts b/src/hooks/use-await-context-compaction.ts
new file mode 100644
index 0000000000..3a2d5a1d08
--- /dev/null
+++ b/src/hooks/use-await-context-compaction.ts
@@ -0,0 +1,164 @@
+import { useEffect, useRef } from "react";
+import useMetricsStore from "#/stores/metrics-store";
+import { useEventStore } from "#/stores/use-event-store";
+import { isCondensationEvent } from "#/types/agent-server/type-guards";
+
+/** How long to wait after a Condensation event for a lower per_turn_token. */
+const METRICS_SETTLE_MS = 2_500;
+/** Give up waiting for condensation / metrics and surface whatever we have. */
+const DEFAULT_TIMEOUT_MS = 90_000;
+
+export type ContextCompactionOutcome = "compacted" | "no_change" | "timeout";
+
+export interface ContextCompactionResult {
+ beforeToken: number;
+ afterToken: number;
+ savedToken: number;
+ /**
+ * "compacted" — a Condensation event landed and per_turn_token dropped.
+ * "no_change" — a Condensation event landed but no token drop was measured.
+ * "timeout" — no Condensation event arrived in time; compaction did not
+ * happen (or was never processed), so this is a failure, not a no-op.
+ */
+ outcome: ContextCompactionOutcome;
+}
+
+export function buildContextCompactionResult(
+ beforeToken: number,
+ afterToken: number,
+ outcome: ContextCompactionOutcome,
+): ContextCompactionResult {
+ return {
+ beforeToken,
+ afterToken,
+ savedToken: Math.max(0, beforeToken - afterToken),
+ outcome,
+ };
+}
+
+interface UseAwaitContextCompactionOptions {
+ /**
+ * Snapshot of `per_turn_token` taken when compaction was requested.
+ * Pass `null` when not awaiting a result.
+ */
+ beforeToken: number | null;
+ /**
+ * Event ids that predate the compaction *request*. The condense POST can
+ * return only after the server already emitted its Condensation event, so
+ * snapshotting "known" ids when this effect starts would miss fast
+ * condensations; the baseline must be captured before the request fires.
+ * When omitted, falls back to the ids present when the effect starts.
+ */
+ baselineEventIds?: Set<string | number> | null;
+ onComplete: (result: ContextCompactionResult) => void;
+ timeoutMs?: number;
+}
+
+/**
+ * Waits for a post-request Condensation event (and ideally a lower
+ * `per_turn_token` in the live metrics store), then reports how many tokens
+ * were freed. The HTTP `/condense` ack only means work *started*.
+ */
+export function useAwaitContextCompaction({
+ beforeToken,
+ baselineEventIds,
+ onComplete,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+}: UseAwaitContextCompactionOptions) {
+ const onCompleteRef = useRef(onComplete);
+ onCompleteRef.current = onComplete;
+
+ useEffect(() => {
+ if (beforeToken === null) {
+ return undefined;
+ }
+
+ let completed = false;
+ let sawCondensation = false;
+ let settleTimer: ReturnType<typeof setTimeout> | undefined;
+ const knownEventIds = baselineEventIds
+ ? new Set(baselineEventIds)
+ : new Set(useEventStore.getState().eventIds);
+
+ const readAfterToken = () =>
+ useMetricsStore.getState().usage?.per_turn_token ?? beforeToken;
+
+ const finish = (afterToken: number, outcome: ContextCompactionOutcome) => {
+ if (completed) {
+ return;
+ }
+ completed = true;
+ onCompleteRef.current(
+ buildContextCompactionResult(beforeToken, afterToken, outcome),
+ );
+ };
+
+ const finishFromMetricsIfReady = () => {
+ const afterToken = readAfterToken();
+ if (sawCondensation && afterToken < beforeToken) {
+ finish(afterToken, "compacted");
+ return true;
+ }
+ return false;
+ };
+
+ const scheduleSettleFinish = () => {
+ clearTimeout(settleTimer);
+ settleTimer = setTimeout(() => {
+ finish(readAfterToken(), "no_change");
+ }, METRICS_SETTLE_MS);
+ };
+
+ const scanForNewCondensation = () => {
+ for (const event of useEventStore.getState().events) {
+ const eventId = "id" in event ? event.id : undefined;
+ if (eventId !== undefined) {
+ if (knownEventIds.has(eventId)) {
+ continue;
+ }
+ knownEventIds.add(eventId);
+ }
+ if (!isCondensationEvent(event)) {
+ continue;
+ }
+ sawCondensation = true;
+ if (!finishFromMetricsIfReady()) {
+ scheduleSettleFinish();
+ }
+ return;
+ }
+ };
+
+ scanForNewCondensation();
+
+ const unsubscribeEvents = useEventStore.subscribe(() => {
+ if (completed) {
+ return;
+ }
+ scanForNewCondensation();
+ });
+
+ const unsubscribeMetrics = useMetricsStore.subscribe(() => {
+ if (completed) {
+ return;
+ }
+ if (finishFromMetricsIfReady()) {
+ clearTimeout(settleTimer);
+ }
+ });
+
+ const timeoutTimer = setTimeout(() => {
+ // No Condensation event in time means the compaction never landed —
+ // a failure, not a "nothing to compact" no-op.
+ finish(readAfterToken(), sawCondensation ? "no_change" : "timeout");
+ }, timeoutMs);
+
+ return () => {
+ completed = true;
+ unsubscribeEvents();
+ unsubscribeMetrics();
+ clearTimeout(settleTimer);
+ clearTimeout(timeoutTimer);
+ };
+ }, [beforeToken, baselineEventIds, timeoutMs]);
+}
diff --git a/src/hooks/use-compact-context-action.test.tsx b/src/hooks/use-compact-context-action.test.tsx
new file mode 100644
index 0000000000..e0605a613c
--- /dev/null
+++ b/src/hooks/use-compact-context-action.test.tsx
@@ -0,0 +1,117 @@
+/* Integration: useCompactContextAction end-to-end through real stores. */
+import { act, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import React from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import useMetricsStore from "#/stores/metrics-store";
+import { useEventStore } from "#/stores/use-event-store";
+import type { OpenHandsEvent } from "#/types/agent-server/core";
+
+const mutateMock = vi.fn();
+vi.mock("#/hooks/mutation/use-condense-conversation", () => ({
+ useCondenseConversation: () => ({ mutate: mutateMock, isPending: false }),
+}));
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: () => ({
+ data: { id: "c1", conversation_url: null, session_api_key: null },
+ }),
+}));
+vi.mock("#/hooks/use-agent-state", () => ({
+ useAgentState: () => ({ curAgentState: "FINISHED" }),
+}));
+const successToast = vi.fn();
+const errorToast = vi.fn();
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displaySuccessToast: (...args: unknown[]) => successToast(...args),
+ displayErrorToast: (...args: unknown[]) => errorToast(...args),
+}));
+
+import { useCompactContextAction } from "#/hooks/use-compact-context-action";
+import { I18nKey } from "#/i18n/declaration";
+
+function condensationEvent(id: string): OpenHandsEvent {
+ return {
+ id,
+ timestamp: new Date().toISOString(),
+ source: "environment",
+ kind: "Condensation",
+ forgotten_event_ids: ["a"],
+ } as OpenHandsEvent;
+}
+
+const usage = (perTurn: number) => ({
+ prompt_tokens: perTurn,
+ completion_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 262144,
+ per_turn_token: perTurn,
+});
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ return React.createElement(
+ QueryClientProvider,
+ { client: new QueryClient() },
+ children,
+ );
+}
+
+describe("useCompactContextAction (integration)", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ useEventStore.getState().clearEvents();
+ useMetricsStore.getState().setMetrics({
+ cost: null,
+ max_budget_per_task: null,
+ usage: usage(50_000),
+ });
+ mutateMock.mockImplementation((_vars, opts) => opts.onSuccess());
+ successToast.mockClear();
+ errorToast.mockClear();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ useEventStore.getState().clearEvents();
+ });
+
+ it("toasts counts when condensation lands and metrics drop", () => {
+ const { result } = renderHook(() => useCompactContextAction(50_000), {
+ wrapper,
+ });
+
+ act(() => result.current.handleCompact());
+ expect(successToast).toHaveBeenCalledWith(
+ I18nKey.CONVERSATION$COMPACT_CONTEXT_STARTED,
+ );
+
+ act(() => {
+ useEventStore.getState().addEvent(condensationEvent("cond-x"));
+ useMetricsStore.getState().setMetrics({
+ cost: null,
+ max_budget_per_task: null,
+ usage: usage(20_000),
+ });
+ });
+
+ expect(successToast).toHaveBeenCalledWith(
+ I18nKey.CONVERSATION$COMPACT_CONTEXT_COMPLETE,
+ );
+ expect(errorToast).not.toHaveBeenCalled();
+ });
+
+ it("toasts error when no condensation arrives in time", () => {
+ const { result } = renderHook(() => useCompactContextAction(50_000), {
+ wrapper,
+ });
+
+ act(() => result.current.handleCompact());
+ act(() => {
+ vi.advanceTimersByTime(90_000);
+ });
+
+ expect(errorToast).toHaveBeenCalledWith(
+ I18nKey.CONVERSATION$COMPACT_CONTEXT_FAILED,
+ );
+ });
+});
diff --git a/src/hooks/use-compact-context-action.ts b/src/hooks/use-compact-context-action.ts
new file mode 100644
index 0000000000..f07e89d723
--- /dev/null
+++ b/src/hooks/use-compact-context-action.ts
@@ -0,0 +1,119 @@
+import React from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useAgentState } from "#/hooks/use-agent-state";
+import { useCondenseConversation } from "#/hooks/mutation/use-condense-conversation";
+import {
+ type ContextCompactionResult,
+ useAwaitContextCompaction,
+} from "#/hooks/use-await-context-compaction";
+import { AgentState } from "#/types/agent-state";
+import useMetricsStore from "#/stores/metrics-store";
+import { useEventStore } from "#/stores/use-event-store";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+import { formatCompactTokenCount } from "#/utils/format-token-count";
+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
+
+/**
+ * Shared compact/condense action used by the Usage panel CTA and the
+ * composer context-window popover.
+ */
+export function useCompactContextAction(perTurnToken: number = 0) {
+ const { t } = useTranslation("openhands");
+ const queryClient = useQueryClient();
+ const { data: conversation } = useActiveConversation();
+ const { curAgentState } = useAgentState();
+ const { mutate: condense, isPending } = useCondenseConversation();
+ const [beforeToken, setBeforeToken] = React.useState<number | null>(null);
+ const baselineEventIdsRef = React.useRef<Set<string | number> | null>(null);
+
+ const isAgentBusy =
+ curAgentState === AgentState.RUNNING ||
+ curAgentState === AgentState.LOADING;
+ const isCompacting = isPending || beforeToken !== null;
+ const isDisabled = !conversation?.id || isAgentBusy || isCompacting;
+ const description = t(I18nKey.CONVERSATION$COMPACT_CONTEXT_DESCRIPTION);
+
+ const handleCompactionComplete = React.useEffectEvent(
+ (result: ContextCompactionResult) => {
+ setBeforeToken(null);
+ baselineEventIdsRef.current = null;
+ if (conversation?.id) {
+ queryClient.invalidateQueries({
+ queryKey: ["conversation-metrics", conversation.id],
+ });
+ }
+
+ if (result.outcome === "timeout") {
+ displayErrorToast(t(I18nKey.CONVERSATION$COMPACT_CONTEXT_FAILED));
+ return;
+ }
+
+ if (result.savedToken > 0) {
+ displaySuccessToast(
+ t(I18nKey.CONVERSATION$COMPACT_CONTEXT_COMPLETE, {
+ saved: formatCompactTokenCount(result.savedToken),
+ before: formatCompactTokenCount(result.beforeToken),
+ after: formatCompactTokenCount(result.afterToken),
+ }),
+ );
+ return;
+ }
+
+ displaySuccessToast(
+ t(I18nKey.CONVERSATION$COMPACT_CONTEXT_COMPLETE_NO_CHANGE),
+ );
+ },
+ );
+
+ useAwaitContextCompaction({
+ beforeToken,
+ baselineEventIds: beforeToken !== null ? baselineEventIdsRef.current : null,
+ onComplete: handleCompactionComplete,
+ });
+
+ const handleCompact = () => {
+ if (!conversation?.id || isCompacting) return;
+
+ const snapshot =
+ useMetricsStore.getState().usage?.per_turn_token ?? perTurnToken;
+ // The condense POST can return only after the server already emitted its
+ // Condensation event, so the await baseline must be captured *before* the
+ // request fires, not when the post-ack effect starts.
+ baselineEventIdsRef.current = new Set(useEventStore.getState().eventIds);
+
+ condense(
+ {
+ conversationId: conversation.id,
+ conversationUrl: conversation.conversation_url,
+ sessionApiKey: conversation.session_api_key,
+ },
+ {
+ onSuccess: () => {
+ setBeforeToken(snapshot);
+ displaySuccessToast(t(I18nKey.CONVERSATION$COMPACT_CONTEXT_STARTED));
+ },
+ onError: (error) => {
+ setBeforeToken(null);
+ baselineEventIdsRef.current = null;
+ displayErrorToast(
+ retrieveAxiosErrorMessage(error) ||
+ t(I18nKey.CONVERSATION$COMPACT_CONTEXT_FAILED),
+ );
+ },
+ },
+ );
+ };
+
+ return {
+ handleCompact,
+ isCompacting,
+ isDisabled,
+ description,
+ };
+}
diff --git a/src/hooks/use-context-window-usage.ts b/src/hooks/use-context-window-usage.ts
new file mode 100644
index 0000000000..0efab2462c
--- /dev/null
+++ b/src/hooks/use-context-window-usage.ts
@@ -0,0 +1,52 @@
+import { useMemo } from "react";
+import useMetricsStore from "#/stores/metrics-store";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useConversationMetrics } from "#/hooks/query/use-conversation-metrics";
+
+export interface ContextWindowUsage {
+ perTurnToken: number;
+ contextWindow: number;
+}
+
+function toContextWindowUsage(
+ usage:
+ | {
+ per_turn_token?: number | null;
+ context_window?: number | null;
+ }
+ | null
+ | undefined,
+): ContextWindowUsage | null {
+ const contextWindow = usage?.context_window ?? 0;
+ if (contextWindow <= 0) {
+ return null;
+ }
+
+ return {
+ perTurnToken: usage?.per_turn_token ?? 0,
+ contextWindow,
+ };
+}
+
+export function useContextWindowUsage(): ContextWindowUsage | null {
+ const storeUsage = useMetricsStore((state) => state.usage);
+ const { data: conversation } = useActiveConversation();
+
+ const { data: conversationMetrics } = useConversationMetrics(
+ conversation?.id,
+ conversation?.conversation_url,
+ conversation?.session_api_key,
+ Boolean(conversation?.id),
+ );
+
+ return useMemo(() => {
+ const fromStore = toContextWindowUsage(storeUsage);
+ if (fromStore) {
+ return fromStore;
+ }
+
+ return toContextWindowUsage(
+ conversationMetrics?.accumulated_token_usage ?? null,
+ );
+ }, [storeUsage, conversationMetrics]);
+}
diff --git a/src/hooks/use-conversation-name-context-menu.ts b/src/hooks/use-conversation-name-context-menu.ts
index cf44f29f72..f7715d142c 100644
--- a/src/hooks/use-conversation-name-context-menu.ts
+++ b/src/hooks/use-conversation-name-context-menu.ts
@@ -2,7 +2,6 @@ import React from "react";
import { useTranslation } from "react-i18next";
import { useNavigation } from "#/context/navigation-context";
import { useActiveBackend } from "#/contexts/active-backend-context";
-import useMetricsStore from "#/stores/metrics-store";
import { useDeleteConversation } from "./mutation/use-delete-conversation";
import { useUnifiedPauseConversation } from "./mutation/use-unified-stop-conversation";
import { useUpdateConversationPublicFlag } from "./mutation/use-update-conversation-public-flag";
@@ -19,6 +18,7 @@ import {
} from "#/utils/system-message-adapter";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
import { isExecutionActive } from "#/utils/status";
+import { useSelectConversationTab } from "./use-select-conversation-tab";
interface UseConversationNameContextMenuProps {
conversationId?: string;
@@ -41,9 +41,6 @@ export function useConversationNameContextMenu({
const { mutate: stopConversation } = useUnifiedPauseConversation();
const { mutate: updatePublicFlag } = useUpdateConversationPublicFlag();
const { data: conversation } = useActiveConversation();
- const metrics = useMetricsStore();
-
- const [metricsModalVisible, setMetricsModalVisible] = React.useState(false);
const [systemModalVisible, setSystemModalVisible] = React.useState(false);
const [skillsModalVisible, setSkillsModalVisible] = React.useState(false);
const [pluginsModalVisible, setPluginsModalVisible] = React.useState(false);
@@ -53,6 +50,7 @@ export function useConversationNameContextMenu({
const [confirmStopModalVisible, setConfirmStopModalVisible] =
React.useState(false);
const { mutateAsync: downloadConversation } = useDownloadConversation();
+ const { navigateToTab } = useSelectConversationTab();
const systemMessage: SystemMessageForModal | null =
adaptSystemMessage(events);
@@ -114,7 +112,7 @@ export function useConversationNameContextMenu({
const handleDisplayCost = (event: React.MouseEvent<HTMLButtonElement>) => {
event.stopPropagation();
- setMetricsModalVisible(true);
+ navigateToTab("usage");
onContextMenuToggle?.(false);
};
@@ -195,8 +193,6 @@ export function useConversationNameContextMenu({
handleConfirmStop,
// Modal states
- metricsModalVisible,
- setMetricsModalVisible,
systemModalVisible,
setSystemModalVisible,
skillsModalVisible,
@@ -211,7 +207,6 @@ export function useConversationNameContextMenu({
setConfirmStopModalVisible,
// Data
- metrics,
systemMessage,
shouldShowStop: isExecutionActive(executionStatus),
diff --git a/src/hooks/use-live-conversation-metrics.ts b/src/hooks/use-live-conversation-metrics.ts
new file mode 100644
index 0000000000..399c46f410
--- /dev/null
+++ b/src/hooks/use-live-conversation-metrics.ts
@@ -0,0 +1,85 @@
+import { useMemo } from "react";
+import useMetricsStore, { type MetricsState } from "#/stores/metrics-store";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useConversationMetrics } from "#/hooks/query/use-conversation-metrics";
+
+/**
+ * Combined cost/token metrics for the active conversation.
+ *
+ * Prefers the live WebSocket metrics store, which updates in real time as
+ * agent events stream in, and falls back to the REST snapshot
+ * (`GET /api/conversations/{id}` stats, combined across all usage ids and
+ * refreshed on a 30s interval by {@link useConversationMetrics}) before the
+ * first stats arrive. The store is reset on conversation switch (see
+ * `ConversationWebSocketProvider`), so its contents always belong to the
+ * active conversation — preferring it cannot leak a previous
+ * conversation's figures, and preferring REST would lag the display up to
+ * a poll interval behind what the user just watched happen.
+ *
+ * Pass `enabled: false` to pause the REST polling while the consumer is
+ * hidden (e.g. a closed modal).
+ */
+export function useLiveConversationMetrics(
+ enabled: boolean = true,
+): MetricsState {
+ // Per-field selectors rather than a bare `useMetricsStore()`: subscribing to
+ // the whole store re-runs this hook on any store write, including the action
+ // identity, and matches how `useContextWindowUsage` reads the same store.
+ const storeCost = useMetricsStore((state) => state.cost);
+ const storeMaxBudgetPerTask = useMetricsStore(
+ (state) => state.max_budget_per_task,
+ );
+ const storeUsage = useMetricsStore((state) => state.usage);
+ const { data: conversation } = useActiveConversation();
+
+ const { data: conversationMetrics } = useConversationMetrics(
+ conversation?.id,
+ conversation?.conversation_url,
+ conversation?.session_api_key,
+ enabled,
+ );
+
+ return useMemo(() => {
+ // Live store first: real-time and (post-reset) always the active
+ // conversation's data. Any non-null field counts as data.
+ if (storeCost !== null || storeUsage !== null) {
+ return {
+ cost: storeCost,
+ max_budget_per_task: storeMaxBudgetPerTask,
+ usage: storeUsage,
+ };
+ }
+
+ if (conversationMetrics) {
+ return {
+ cost: conversationMetrics.accumulated_cost,
+ max_budget_per_task: conversationMetrics.max_budget_per_task,
+ usage: conversationMetrics.accumulated_token_usage
+ ? {
+ prompt_tokens:
+ conversationMetrics.accumulated_token_usage.prompt_tokens ?? 0,
+ completion_tokens:
+ conversationMetrics.accumulated_token_usage.completion_tokens ??
+ 0,
+ cache_read_tokens:
+ conversationMetrics.accumulated_token_usage.cache_read_tokens ??
+ 0,
+ cache_write_tokens:
+ conversationMetrics.accumulated_token_usage
+ .cache_write_tokens ?? 0,
+ context_window:
+ conversationMetrics.accumulated_token_usage.context_window ?? 0,
+ per_turn_token:
+ conversationMetrics.accumulated_token_usage.per_turn_token ?? 0,
+ }
+ : null,
+ };
+ }
+
+ return {
+ cost: null,
+ max_budget_per_task: null,
+ usage: null,
+ };
+ }, [conversationMetrics, storeCost, storeMaxBudgetPerTask, storeUsage]);
+}
diff --git a/src/hooks/use-select-conversation-tab.ts b/src/hooks/use-select-conversation-tab.ts
index b5a8ff6b18..aee6d0b94d 100644
--- a/src/hooks/use-select-conversation-tab.ts
+++ b/src/hooks/use-select-conversation-tab.ts
@@ -3,7 +3,7 @@ import {
useConversationStore,
type ConversationTab,
} from "#/stores/conversation-store";
-import { useConversationId } from "#/hooks/use-conversation-id";
+import { useOptionalConversationId } from "#/hooks/use-conversation-id";
/**
* Custom hook for selecting conversation tabs with consistent behavior.
@@ -14,7 +14,7 @@ import { useConversationId } from "#/hooks/use-conversation-id";
* session-only — see `useConversationStore` for the rationale.
*/
export function useSelectConversationTab() {
- const { conversationId } = useConversationId();
+ const { conversationId } = useOptionalConversationId();
const {
selectedTab,
isRightPanelShown,
@@ -23,7 +23,7 @@ export function useSelectConversationTab() {
} = useConversationStore();
const { setSelectedTab: setPersistedSelectedTab } =
- useConversationLocalStorageState(conversationId);
+ useConversationLocalStorageState(conversationId ?? "");
const onTabChange = (value: ConversationTab | null) => {
setSelectedTab(value);
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index d32b2f9822..bc1611e176 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -10778,21 +10778,21 @@
"ca": "Descarrega via VS Code"
},
"BUTTON$DISPLAY_COST": {
- "en": "Display Cost",
- "ja": "コストを表示",
- "zh-CN": "显示成本",
- "zh-TW": "顯示成本",
- "ko-KR": "비용 표시",
- "fr": "Afficher le coût",
- "es": "Mostrar costo",
- "de": "Kosten anzeigen",
- "it": "Mostra costo",
- "pt": "Mostrar custo",
- "ar": "عرض التكلفة",
- "no": "Vis kostnad",
- "tr": "Maliyeti Göster",
- "uk": "Показати вартість",
- "ca": "Mostra el cost"
+ "en": "Display Usage and Cost",
+ "ja": "使用量とコストを表示",
+ "zh-CN": "显示用量和成本",
+ "zh-TW": "顯示用量和成本",
+ "ko-KR": "사용량 및 비용 표시",
+ "fr": "Afficher l’utilisation et le coût",
+ "es": "Mostrar uso y costo",
+ "de": "Nutzung und Kosten anzeigen",
+ "it": "Mostra utilizzo e costo",
+ "pt": "Mostrar uso e custo",
+ "ar": "عرض الاستخدام والتكلفة",
+ "no": "Vis bruk og kostnad",
+ "tr": "Kullanımı ve maliyeti göster",
+ "uk": "Показати використання та вартість",
+ "ca": "Mostra l’ús i el cost"
},
"BUTTON$SHOW_AGENT_TOOLS_AND_METADATA": {
"en": "Show Agent Tools & Metadata",
@@ -37331,6 +37331,312 @@
"uk": "Змінити порядок {{name}}",
"ca": "Reordenar {{name}}"
},
+ "CONVERSATION$CONTEXT_WINDOW_UNKNOWN": {
+ "en": "window size unknown",
+ "ja": "ウィンドウサイズ不明",
+ "zh-CN": "窗口大小未知",
+ "zh-TW": "視窗大小未知",
+ "ko-KR": "윈도우 크기 알 수 없음",
+ "de": "Fenstergröße unbekannt",
+ "no": "ukjent vindusstørrelse",
+ "it": "dimensione della finestra sconosciuta",
+ "pt": "tamanho da janela desconhecido",
+ "es": "tamaño de ventana desconocido",
+ "ar": "حجم النافذة غير معروف",
+ "fr": "taille de fenêtre inconnue",
+ "tr": "pencere boyutu bilinmiyor",
+ "uk": "розмір вікна невідомий",
+ "ca": "mida de finestra desconeguda"
+ },
+ "CONVERSATION$LEFT": {
+ "en": "left",
+ "ja": "残り",
+ "zh-CN": "剩余",
+ "zh-TW": "剩餘",
+ "ko-KR": "남음",
+ "de": "übrig",
+ "no": "igjen",
+ "it": "rimasti",
+ "pt": "restantes",
+ "es": "restante",
+ "ar": "متبقٍ",
+ "fr": "restant",
+ "tr": "kaldı",
+ "uk": "залишилось",
+ "ca": "restant"
+ },
+ "CONVERSATION$COMPACT_CONTEXT_DESCRIPTION": {
+ "en": "Summarizes older messages to free context space while keeping recent details.",
+ "ja": "古いメッセージを要約してコンテキストの空きを作り、直近の詳細は残します。",
+ "zh-CN": "总结较早的消息以释放上下文空间,同时保留近期细节。",
+ "zh-TW": "摘要較早的訊息以釋放上下文空間,同時保留近期細節。",
+ "ko-KR": "이전 메시지를 요약해 컨텍스트 공간을 확보하고, 최근 세부 내용은 유지합니다.",
+ "de": "Fasst ältere Nachrichten zusammen, um Kontextplatz freizugeben, und behält aktuelle Details bei.",
+ "no": "Oppsummerer eldre meldinger for å frigjøre kontekstplass, mens nylige detaljer beholdes.",
+ "it": "Riassume i messaggi più vecchi per liberare spazio nel contesto, mantenendo i dettagli recenti.",
+ "pt": "Resume mensagens antigas para liberar espaço no contexto, mantendo os detalhes recentes.",
+ "es": "Resume mensajes antiguos para liberar espacio de contexto, conservando los detalles recientes.",
+ "ar": "يلخّص الرسائل الأقدم لتحرير مساحة السياق مع الإبقاء على التفاصيل الحديثة.",
+ "fr": "Résume les messages plus anciens pour libérer de l’espace de contexte tout en conservant les détails récents.",
+ "tr": "Yakın ayrıntıları korurken eski iletileri özetleyerek bağlam alanı boşaltır.",
+ "uk": "Стискає старіші повідомлення, звільняючи місце в контексті та зберігаючи недавні деталі.",
+ "ca": "Resumeix els missatges antics per alliberar espai de context i conserva els detalls recents."
+ },
+ "CONVERSATION$COMPACT_CONTEXT_STARTED": {
+ "en": "Context compaction started",
+ "ja": "コンテキストの圧縮を開始しました",
+ "zh-CN": "已开始压缩上下文",
+ "zh-TW": "已開始壓縮上下文",
+ "ko-KR": "컨텍스트 압축을 시작했습니다",
+ "de": "Kontextkomprimierung gestartet",
+ "no": "Kontekstkomprimering startet",
+ "it": "Compressione del contesto avviata",
+ "pt": "Compactação de contexto iniciada",
+ "es": "Se inició la compactación del contexto",
+ "ar": "بدأ ضغط السياق",
+ "fr": "Compactage du contexte démarré",
+ "tr": "Bağlam sıkıştırma başlatıldı",
+ "uk": "Розпочато стиснення контексту",
+ "ca": "S'ha iniciat la compactació del context"
+ },
+ "CONVERSATION$COMPACT_CONTEXT_COMPLETE": {
+ "en": "Context compacted — freed {{saved}} tokens ({{before}} → {{after}})",
+ "ja": "コンテキストを圧縮しました — {{saved}} トークン解放({{before}} → {{after}})",
+ "zh-CN": "上下文已压缩 — 释放 {{saved}} tokens({{before}} → {{after}})",
+ "zh-TW": "上下文已壓縮 — 釋放 {{saved}} tokens({{before}} → {{after}})",
+ "ko-KR": "컨텍스트 압축 완료 — {{saved}} 토큰 확보 ({{before}} → {{after}})",
+ "de": "Kontext komprimiert — {{saved}} Tokens freigegeben ({{before}} → {{after}})",
+ "no": "Kontekst komprimert — frigjorde {{saved}} tokens ({{before}} → {{after}})",
+ "it": "Contesto compresso — liberati {{saved}} token ({{before}} → {{after}})",
+ "pt": "Contexto compactado — liberou {{saved}} tokens ({{before}} → {{after}})",
+ "es": "Contexto compactado — se liberaron {{saved}} tokens ({{before}} → {{after}})",
+ "ar": "تم ضغط السياق — حُرِّر {{saved}} رمزًا ({{before}} → {{after}})",
+ "fr": "Contexte compacté — {{saved}} jetons libérés ({{before}} → {{after}})",
+ "tr": "Bağlam sıkıştırıldı — {{saved}} token boşaltıldı ({{before}} → {{after}})",
+ "uk": "Контекст стиснуто — звільнено {{saved}} токенів ({{before}} → {{after}})",
+ "ca": "Context compactat — s'han alliberat {{saved}} tokens ({{before}} → {{after}})"
+ },
+ "CONVERSATION$COMPACT_CONTEXT_COMPLETE_NO_CHANGE": {
+ "en": "Context compacted",
+ "ja": "コンテキストを圧縮しました",
+ "zh-CN": "上下文已压缩",
+ "zh-TW": "上下文已壓縮",
+ "ko-KR": "컨텍스트 압축 완료",
+ "de": "Kontext komprimiert",
+ "no": "Kontekst komprimert",
+ "it": "Contesto compresso",
+ "pt": "Contexto compactado",
+ "es": "Contexto compactado",
+ "ar": "تم ضغط السياق",
+ "fr": "Contexte compacté",
+ "tr": "Bağlam sıkıştırıldı",
+ "uk": "Контекст стиснуто",
+ "ca": "Context compactat"
+ },
+ "CONVERSATION$COMPACT_CONTEXT_FAILED": {
+ "en": "Failed to compact context",
+ "ja": "コンテキストの圧縮に失敗しました",
+ "zh-CN": "压缩上下文失败",
+ "zh-TW": "壓縮上下文失敗",
+ "ko-KR": "컨텍스트 압축에 실패했습니다",
+ "de": "Kontext konnte nicht komprimiert werden",
+ "no": "Kunne ikke komprimere konteksten",
+ "it": "Impossibile comprimere il contesto",
+ "pt": "Falha ao compactar o contexto",
+ "es": "No se pudo compactar el contexto",
+ "ar": "فشل ضغط السياق",
+ "fr": "Échec du compactage du contexte",
+ "tr": "Bağlam sıkıştırılamadı",
+ "uk": "Не вдалося стиснути контекст",
+ "ca": "No s'ha pogut compactar el context"
+ },
+ "CONVERSATION$TOKEN_USAGE": {
+ "en": "Token Usage",
+ "ja": "トークン使用量",
+ "zh-CN": "Token 用量",
+ "zh-TW": "Token 用量",
+ "ko-KR": "토큰 사용량",
+ "de": "Token-Nutzung",
+ "no": "Tokenbruk",
+ "it": "Utilizzo token",
+ "pt": "Uso de tokens",
+ "es": "Uso de tokens",
+ "ar": "استخدام الرموز",
+ "fr": "Utilisation des jetons",
+ "tr": "Token kullanımı",
+ "uk": "Використання токенів",
+ "ca": "Ús de tokens"
+ },
+ "CONVERSATION$PLAN_USAGE_NOTE": {
+ "en": "Plan usage — API-equivalent estimate",
+ "ja": "プラン使用量 — API換算の推定値",
+ "zh-CN": "套餐用量 — API 等价估算",
+ "zh-TW": "方案用量 — API 等價估算",
+ "ko-KR": "플랜 사용량 — API 환산 추정치",
+ "de": "Abo-Nutzung — API-äquivalente Schätzung",
+ "no": "Abonnementsbruk — API-ekvivalent estimat",
+ "it": "Utilizzo del piano — stima equivalente API",
+ "pt": "Uso do plano — estimativa equivalente à API",
+ "es": "Uso del plan — estimación equivalente a API",
+ "ar": "استخدام الخطة — تقدير مكافئ لواجهة API",
+ "fr": "Utilisation du forfait — estimation équivalente API",
+ "tr": "Plan kullanımı — API eşdeğeri tahmin",
+ "uk": "Використання плану — оцінка в еквіваленті API",
+ "ca": "Ús del pla — estimació equivalent a l'API"
+ },
+ "COMMON$USAGE": {
+ "en": "Usage",
+ "ja": "使用状況",
+ "zh-CN": "用量",
+ "zh-TW": "用量",
+ "ko-KR": "사용량",
+ "de": "Nutzung",
+ "no": "Bruk",
+ "it": "Utilizzo",
+ "pt": "Uso",
+ "es": "Uso",
+ "ar": "الاستخدام",
+ "fr": "Utilisation",
+ "tr": "Kullanım",
+ "uk": "Використання",
+ "ca": "Ús"
+ },
+ "CONVERSATION$COMPACT_CONTEXT": {
+ "en": "Compact context",
+ "ja": "コンテキストを圧縮",
+ "zh-CN": "压缩上下文",
+ "zh-TW": "壓縮上下文",
+ "ko-KR": "컨텍스트 압축",
+ "de": "Kontext komprimieren",
+ "no": "Komprimer kontekst",
+ "it": "Comprimi il contesto",
+ "pt": "Compactar contexto",
+ "es": "Compactar contexto",
+ "ar": "ضغط السياق",
+ "fr": "Compacter le contexte",
+ "tr": "Bağlamı sıkıştır",
+ "uk": "Стиснути контекст",
+ "ca": "Compacta el context"
+ },
+ "CONVERSATION$CONTEXT_FILLING_UP": {
+ "en": "Context is filling up — compacting frees space",
+ "ja": "コンテキストがいっぱいになりつつあります。圧縮すると空き容量が増えます",
+ "zh-CN": "上下文即将占满——压缩可释放空间",
+ "zh-TW": "上下文即將佔滿——壓縮可釋放空間",
+ "ko-KR": "컨텍스트가 가득 차고 있습니다. 압축하면 공간이 확보됩니다",
+ "de": "Der Kontext füllt sich — Komprimieren schafft Platz",
+ "no": "Konteksten fylles opp — komprimering frigjør plass",
+ "it": "Il contesto si sta riempiendo: la compressione libera spazio",
+ "pt": "O contexto está enchendo — compactar libera espaço",
+ "es": "El contexto se está llenando: compactar libera espacio",
+ "ar": "السياق يمتلئ — الضغط يحرر مساحة",
+ "fr": "Le contexte se remplit — le compactage libère de l'espace",
+ "tr": "Bağlam doluyor — sıkıştırmak yer açar",
+ "uk": "Контекст заповнюється — стиснення звільнить місце",
+ "ca": "El context s'està omplint — compactar allibera espai"
+ },
+ "CONVERSATION$PROVIDER_BALANCE": {
+ "en": "Provider balance",
+ "ja": "プロバイダー残高",
+ "zh-CN": "提供商余额",
+ "zh-TW": "供應商餘額",
+ "ko-KR": "공급자 잔액",
+ "de": "Anbieter-Guthaben",
+ "no": "Leverandørsaldo",
+ "it": "Saldo del provider",
+ "pt": "Saldo do provedor",
+ "es": "Saldo del proveedor",
+ "ar": "رصيد المزود",
+ "fr": "Solde du fournisseur",
+ "tr": "Sağlayıcı bakiyesi",
+ "uk": "Баланс провайдера",
+ "ca": "Saldo del proveïdor"
+ },
+ "CONVERSATION$CREDITS_REMAINING": {
+ "en": "Credits remaining",
+ "ja": "残りクレジット",
+ "zh-CN": "剩余额度",
+ "zh-TW": "剩餘額度",
+ "ko-KR": "남은 크레딧",
+ "de": "Verbleibendes Guthaben",
+ "no": "Gjenstående kreditter",
+ "it": "Crediti rimanenti",
+ "pt": "Créditos restantes",
+ "es": "Créditos restantes",
+ "ar": "الرصيد المتبقي",
+ "fr": "Crédits restants",
+ "tr": "Kalan kredi",
+ "uk": "Залишок кредитів",
+ "ca": "Crèdits restants"
+ },
+ "CONVERSATION$CREDITS_USED": {
+ "en": "Credits used",
+ "ja": "使用済みクレジット",
+ "zh-CN": "已用额度",
+ "zh-TW": "已用額度",
+ "ko-KR": "사용한 크레딧",
+ "de": "Verbrauchtes Guthaben",
+ "no": "Brukte kreditter",
+ "it": "Crediti utilizzati",
+ "pt": "Créditos usados",
+ "es": "Créditos usados",
+ "ar": "الرصيد المستخدم",
+ "fr": "Crédits utilisés",
+ "tr": "Kullanılan kredi",
+ "uk": "Використані кредити",
+ "ca": "Crèdits utilitzats"
+ },
+ "CONVERSATION$FREE_TIER": {
+ "en": "Free tier",
+ "ja": "無料プラン",
+ "zh-CN": "免费套餐",
+ "zh-TW": "免費方案",
+ "ko-KR": "무료 요금제",
+ "de": "Kostenlose Stufe",
+ "no": "Gratisnivå",
+ "it": "Piano gratuito",
+ "pt": "Nível gratuito",
+ "es": "Nivel gratuito",
+ "ar": "الفئة المجانية",
+ "fr": "Offre gratuite",
+ "tr": "Ücretsiz katman",
+ "uk": "Безкоштовний рівень",
+ "ca": "Nivell gratuït"
+ },
+ "CHAT_INTERFACE$CONTEXT_WINDOW_METER_LABEL": {
+ "en": "Context window usage",
+ "zh-CN": "上下文窗口用量",
+ "zh-TW": "上下文視窗用量",
+ "de": "Kontextfenster-Nutzung",
+ "ko-KR": "컨텍스트 윈도우 사용량",
+ "no": "Kontekstvindu-bruk",
+ "it": "Utilizzo finestra di contesto",
+ "pt": "Uso da janela de contexto",
+ "es": "Uso de la ventana de contexto",
+ "ar": "استخدام نافذة السياق",
+ "fr": "Utilisation de la fenêtre de contexte",
+ "tr": "Bağlam penceresi kullanımı",
+ "ja": "コンテキストウィンドウ使用量",
+ "uk": "Використання вікна контексту",
+ "ca": "Ús de la finestra de context"
+ },
+ "CHAT_INTERFACE$SHOW_CONTEXT": {
+ "en": "Show Context",
+ "zh-CN": "显示上下文",
+ "zh-TW": "顯示上下文",
+ "de": "Kontext anzeigen",
+ "ko-KR": "컨텍스트 표시",
+ "no": "Vis kontekst",
+ "it": "Mostra contesto",
+ "pt": "Mostrar contexto",
+ "es": "Mostrar contexto",
+ "ar": "إظهار السياق",
+ "fr": "Afficher le contexte",
+ "tr": "Bağlamı göster",
+ "ja": "コンテキストを表示",
+ "uk": "Показати контекст",
+ "ca": "Mostra el context"
+ },
"CONVERSATION$TAGS_OVERFLOW_ARIA": {
"en": "Show {{count}} more tags",
"ja": "他に{{count}}件のタグを表示",
diff --git a/src/routes/usage-tab.tsx b/src/routes/usage-tab.tsx
new file mode 100644
index 0000000000..a6e14f4511
--- /dev/null
+++ b/src/routes/usage-tab.tsx
@@ -0,0 +1,7 @@
+import { UsagePanel } from "#/components/features/conversation/usage-panel/usage-panel";
+
+function UsageTab() {
+ return <UsagePanel />;
+}
+
+export default UsageTab;
diff --git a/src/stores/conversation-store.ts b/src/stores/conversation-store.ts
index 60b405b121..09e0ecd58c 100644
--- a/src/stores/conversation-store.ts
+++ b/src/stores/conversation-store.ts
@@ -10,7 +10,8 @@ export type ConversationTab =
| "browser"
| "terminal"
| "planner"
- | "tasklist";
+ | "tasklist"
+ | "usage";
export type ConversationMode = "code" | "plan";
diff --git a/src/stores/metrics-store.ts b/src/stores/metrics-store.ts
index 32682b2db0..30e2c46212 100644
--- a/src/stores/metrics-store.ts
+++ b/src/stores/metrics-store.ts
@@ -15,13 +15,28 @@ export interface MetricsState {
export interface MetricsStore extends MetricsState {
setMetrics: (metrics: MetricsState) => void;
+ resetMetrics: () => void;
}
-const useMetricsStore = create<MetricsStore>((set) => ({
+const EMPTY_METRICS: MetricsState = {
cost: null,
max_budget_per_task: null,
usage: null,
+};
+
+const useMetricsStore = create<MetricsStore>((set) => ({
+ ...EMPTY_METRICS,
setMetrics: (metrics) => set(metrics),
+ resetMetrics: () => set(EMPTY_METRICS),
}));
+// Dev-only console handle for inspecting the live WS metrics while
+// debugging the usage meter (window.__OH_METRICS_STORE__.getState()).
+// Gated on import.meta.env.DEV so it never reaches production builds.
+if (typeof window !== "undefined" && import.meta.env.DEV) {
+ (
+ window as unknown as { __OH_METRICS_STORE__?: typeof useMetricsStore }
+ ).__OH_METRICS_STORE__ = useMetricsStore;
+}
+
export default useMetricsStore;
diff --git a/src/types/agent-server/core/events/condensation-event.ts b/src/types/agent-server/core/events/condensation-event.ts
index 3cad34435d..ab81ae0db3 100644
--- a/src/types/agent-server/core/events/condensation-event.ts
+++ b/src/types/agent-server/core/events/condensation-event.ts
@@ -3,6 +3,8 @@ import { BaseEvent } from "../base/event";
// Condensation event - indicates conversation history condensation is happening
export interface CondensationEvent extends BaseEvent {
+ kind: "Condensation";
+
/**
* The source is always "environment" for condensation events
*/
@@ -26,6 +28,8 @@ export interface CondensationEvent extends BaseEvent {
// Condensation request event - used to request a condensation of conversation history
export interface CondensationRequestEvent extends BaseEvent {
+ kind: "CondensationRequest";
+
/**
* The source is always "environment" for condensation request events
*/
@@ -34,6 +38,8 @@ export interface CondensationRequestEvent extends BaseEvent {
// Condensation summary event - represents a summary generated by a condenser
export interface CondensationSummaryEvent extends BaseEvent {
+ kind: "CondensationSummaryEvent";
+
/**
* The source is always "environment" for condensation summary events
*/
diff --git a/src/types/agent-server/core/events/conversation-state-event.ts b/src/types/agent-server/core/events/conversation-state-event.ts
index 744d55a872..393eef4e28 100644
--- a/src/types/agent-server/core/events/conversation-state-event.ts
+++ b/src/types/agent-server/core/events/conversation-state-event.ts
@@ -26,7 +26,7 @@ export interface LLMMetrics {
model_name: string;
accumulated_cost: number;
max_budget_per_task: number | null;
- accumulated_token_usage: TokenUsage;
+ accumulated_token_usage: TokenUsage | null;
costs: Array<{
model: string;
cost: number;
@@ -41,12 +41,10 @@ export interface LLMMetrics {
}
/**
- * Usage metrics mapping for different components
+ * Usage metrics keyed by LLM usage id. The server uses arbitrary ids
+ * ("default", "condenser", "profile:<name>:<uuid>", …), not a fixed set.
*/
-export interface UsageToMetrics {
- agent: LLMMetrics;
- condenser: LLMMetrics;
-}
+export type UsageToMetrics = Record<string, LLMMetrics>;
/**
* Stats containing usage metrics
diff --git a/src/types/agent-server/type-guards.ts b/src/types/agent-server/type-guards.ts
index 65504665ba..9964092b51 100644
--- a/src/types/agent-server/type-guards.ts
+++ b/src/types/agent-server/type-guards.ts
@@ -35,6 +35,7 @@ import { HookExecutionEvent } from "./core/events/hook-execution-event";
import { ACPToolCallEvent } from "./core/events/acp-tool-call-event";
import { StreamingDeltaEvent } from "./core/events/streaming-delta-event";
import { SystemPromptEvent } from "./core/events/system-event";
+import { CondensationEvent } from "./core/events/condensation-event";
/**
* Type guard to check if an unknown value is a valid BaseEvent
@@ -279,6 +280,14 @@ export const isStreamingDeltaEvent = (
): event is StreamingDeltaEvent =>
"kind" in event && event.kind === "StreamingDeltaEvent";
+/**
+ * Type guard for condensation completion events (history was compacted).
+ */
+export const isCondensationEvent = (
+ event: OpenHandsEvent,
+): event is CondensationEvent =>
+ "kind" in event && event.kind === "Condensation";
+
// =============================================================================
// COMPATIBILITY TYPE GUARDS
// =============================================================================
diff --git a/src/utils/conversation-local-storage.ts b/src/utils/conversation-local-storage.ts
index 5b6046d757..5697666aeb 100644
--- a/src/utils/conversation-local-storage.ts
+++ b/src/utils/conversation-local-storage.ts
@@ -61,6 +61,7 @@ const VALID_CONVERSATION_TABS: ReadonlySet<ConversationTab> = new Set([
"terminal",
"planner",
"tasklist",
+ "usage",
]);
// Tab keys that *used to* exist and were removed during the Files tab
diff --git a/src/utils/format-token-count.ts b/src/utils/format-token-count.ts
new file mode 100644
index 0000000000..0240b2e40a
--- /dev/null
+++ b/src/utils/format-token-count.ts
@@ -0,0 +1,31 @@
+/** Compact token counts for context-window UI (e.g. 198.5k, 1.0M). */
+export function formatCompactTokenCount(value: number): string {
+ if (value >= 1_000_000) {
+ const millions = value / 1_000_000;
+ if (millions >= 10 && Number.isInteger(millions)) {
+ return `${millions.toFixed(0)}M`;
+ }
+ return `${millions.toFixed(1)}M`;
+ }
+
+ if (value >= 1_000) {
+ const thousands = value / 1_000;
+ if (Number.isInteger(thousands)) {
+ return `${thousands.toFixed(0)}k`;
+ }
+ return `${thousands.toFixed(1)}k`;
+ }
+
+ return value.toLocaleString();
+}
+
+export function getContextWindowUsagePercentage(
+ perTurnToken: number,
+ contextWindow: number,
+): number {
+ if (contextWindow <= 0) {
+ return 0;
+ }
+
+ return Math.min(100, (perTurnToken / contextWindow) * 100);
+}