Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Show Assistant last-turn usage in composer

rcourtman9cb3e3aaca5b
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index d7d0ee3266..7c918873bc 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -690,7 +690,17 @@ runtime cost control, and shared AI transport surfaces.
than token counts. Pulse Assistant rows adapt that by keeping visible token
accounting out of the transcript while showing a compact completed-turn
duration beside the effective model label once a turn reaches `done`,
- `error`, or user interruption.
+ `error`, or user interruption. Runtime token usage may surface in the
+ composer chrome instead: OpenCode commit
+ `9ed17da55ab1f7360cc0e01075f763e27fa899e9`
+ `packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx` derives
+ prompt usage from the last assistant message with output tokens in `Prompt`
+ lines 246-264 and renders it in the prompt footer at lines 1652-1667. Pulse
+ adapts that source-backed contract by deriving the latest completed
+ `ChatMessage.tokens` with positive output tokens and rendering only the
+ backend-proven total/input/output counts in the Assistant composer footer;
+ cost and context-limit percentages stay absent until the runtime exposes
+ those values through a governed contract.
7. Keep AI chat presentation helpers aligned through `frontend-modern/src/components/AI/Chat/` and the shared `frontend-modern/src/utils/textPresentation.ts`
8. Keep assistant drawer context, session, and org-switch reset state aligned through the shared `frontend-modern/src/stores/aiChat.ts` boundary instead of letting `frontend-modern/src/App.tsx`, `frontend-modern/src/AppLayout.tsx`, or feature callers fork their own assistant shell state
That shared drawer ownership also covers passive resource reads while the
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
index 2f277b12e4..728db0326d 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -3341,6 +3341,77 @@ describe('AIChat', () => {
});
});
+ // ── Last-turn usage footer ────────────────────────────────────────────────
+
+ describe('last-turn usage footer', () => {
+ it('shows completed assistant token usage in the composer chrome', () => {
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'asst-1',
+ role: 'assistant' as const,
+ content: 'Done.',
+ timestamp: new Date(),
+ completedAt: new Date(),
+ isStreaming: false,
+ tokens: { input: 500, output: 200 },
+ },
+ ]);
+
+ renderChat();
+
+ const usage = screen.getByLabelText(/Last assistant turn usage/);
+ expect(usage).toHaveTextContent('700 tokens');
+ expect(usage).toHaveTextContent('500 in / 200 out');
+ });
+
+ it('uses the latest completed assistant turn with output tokens', () => {
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'asst-1',
+ role: 'assistant' as const,
+ content: 'Earlier result.',
+ timestamp: new Date(),
+ completedAt: new Date(),
+ isStreaming: false,
+ tokens: { input: 100, output: 50 },
+ },
+ {
+ id: 'asst-2',
+ role: 'assistant' as const,
+ content: 'Streaming result.',
+ timestamp: new Date(),
+ isStreaming: true,
+ tokens: { input: 900, output: 800 },
+ },
+ ]);
+
+ renderChat();
+
+ const usage = screen.getByLabelText(/Last assistant turn usage/);
+ expect(usage).toHaveTextContent('150 tokens');
+ expect(usage).toHaveTextContent('100 in / 50 out');
+ expect(usage).not.toHaveTextContent('1,700 tokens');
+ });
+
+ it('does not show usage before an assistant turn has output tokens', () => {
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'asst-1',
+ role: 'assistant' as const,
+ content: '',
+ timestamp: new Date(),
+ completedAt: new Date(),
+ isStreaming: false,
+ tokens: { input: 500, output: 0 },
+ },
+ ]);
+
+ renderChat();
+
+ expect(screen.queryByLabelText(/Last assistant turn usage/)).not.toBeInTheDocument();
+ });
+ });
+
// ── Finding ID passthrough ───────────────────────────────────────────
describe('finding ID context', () => {
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index 482eff2b9a..f07e9e0f53 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -37,6 +37,7 @@ import {
AI_CHAT_DISCOVERY_HINT_TITLE,
AI_CHAT_DRAWER_TITLE,
AI_CHAT_INPUT_PLACEHOLDER,
+ AI_CHAT_LAST_TURN_USAGE_LABEL,
AI_CHAT_NEW_SESSION_BUTTON_TITLE,
AI_CHAT_NEW_SESSION_MENU_LABEL,
AI_CHAT_NEW_SESSION_SHORT_LABEL,
@@ -129,6 +130,12 @@ interface ComposerDraftStash {
editingQueuedFollowUp: QueuedFollowUp | null;
}
+interface AssistantUsageSummary {
+ detail: string;
+ label: string;
+ title: string;
+}
+
interface AIChatProps {
onClose: () => void;
}
@@ -145,6 +152,38 @@ const compactText = (items: Array<string | undefined>): string[] =>
const pluralizeCount = (count: number, singular: string, plural: string) =>
`${count} ${count === 1 ? singular : plural}`;
+const tokenNumberFormat = new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 });
+
+const normalizeAssistantTokenCount = (value: number | undefined): number => {
+ if (!Number.isFinite(value) || !value || value < 0) return 0;
+ return Math.floor(value);
+};
+
+const formatAssistantTokenCount = (count: number): string => tokenNumberFormat.format(count);
+
+const getAssistantUsageSummary = (message: ChatMessage): AssistantUsageSummary | null => {
+ if (message.role !== 'assistant' || message.isStreaming) return null;
+ const input = normalizeAssistantTokenCount(message.tokens?.input);
+ const output = normalizeAssistantTokenCount(message.tokens?.output);
+ if (output <= 0) return null;
+
+ const total = input + output;
+ const totalLabel = `${formatAssistantTokenCount(total)} ${total === 1 ? 'token' : 'tokens'}`;
+ const inputLabel = `${formatAssistantTokenCount(input)} in`;
+ const outputLabel = `${formatAssistantTokenCount(output)} out`;
+ const titleDetail = [
+ `${formatAssistantTokenCount(total)} total`,
+ `${formatAssistantTokenCount(input)} input`,
+ `${formatAssistantTokenCount(output)} output`,
+ ].join(', ');
+
+ return {
+ label: totalLabel,
+ detail: `${inputLabel} / ${outputLabel}`,
+ title: `${AI_CHAT_LAST_TURN_USAGE_LABEL}: ${titleDetail}`,
+ };
+};
+
const normalizePromptHistoryEntry = (value: unknown): PromptHistoryEntry | null => {
if (!value || typeof value !== 'object') return null;
const record = value as Record<string, unknown>;
@@ -1314,6 +1353,14 @@ export const AIChat: Component<AIChatProps> = (props) => {
if (elapsedSeconds < 2) return status.text;
return `${status.text} (${elapsedSeconds}s)`;
});
+ const lastAssistantUsage = createMemo(() => {
+ const messages = chat.messages();
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const usage = getAssistantUsageSummary(messages[index]);
+ if (usage) return usage;
+ }
+ return null;
+ });
createEffect(() => {
input();
@@ -2784,6 +2831,19 @@ export const AIChat: Component<AIChatProps> = (props) => {
</div>
</div>
</form>
+ <Show when={lastAssistantUsage()}>
+ {(usage) => (
+ <div
+ class="mt-1.5 flex min-h-4 min-w-0 items-center justify-end gap-1.5 text-[10px] font-medium text-muted"
+ aria-label={usage().title}
+ title={usage().title}
+ >
+ <span class="truncate">{usage().label}</span>
+ <span class="h-1 w-1 shrink-0 rounded-full bg-border" aria-hidden="true" />
+ <span class="shrink-0">{usage().detail}</span>
+ </div>
+ )}
+ </Show>
</div>
</Show>
</div>
diff --git a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
index 9ca2d9fb39..75534522e7 100644
--- a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
@@ -9,6 +9,7 @@ import {
AI_CHAT_EMPTY_STATE_SUBTITLE,
AI_CHAT_EMPTY_STATE_TITLE,
AI_CHAT_LAUNCHER_ARIA_LABEL,
+ AI_CHAT_LAST_TURN_USAGE_LABEL,
AI_CHAT_MODEL_SELECTOR_EMPTY_STATE,
AI_CHAT_NEW_SESSION_MENU_LABEL,
AI_CHAT_NEW_SESSION_SHORT_LABEL,
@@ -58,6 +59,7 @@ describe('aiChatPresentation', () => {
expect(AI_CHAT_QUESTION_CARD_TITLE).toBe('Pulse Assistant needs your input');
expect(AI_CHAT_ASSISTANT_MESSAGE_LABEL).toBe('Pulse Assistant');
expect(AI_CHAT_CONTEXT_USED_LABEL).toBe('Context used');
+ expect(AI_CHAT_LAST_TURN_USAGE_LABEL).toBe('Last assistant turn usage');
expect(AI_CHAT_PROVIDER_READINESS_SETTINGS_HREF).toBe('/settings/system-ai');
expect(AI_CHAT_PROVIDER_READINESS_SETTINGS_LABEL).toBe('Open settings');
expect(AI_CHAT_PROVIDER_READINESS_RETRY_LABEL).toBe('Retry');
diff --git a/frontend-modern/src/utils/aiChatPresentation.ts b/frontend-modern/src/utils/aiChatPresentation.ts
index 1db9ee4aa7..57ac012bce 100644
--- a/frontend-modern/src/utils/aiChatPresentation.ts
+++ b/frontend-modern/src/utils/aiChatPresentation.ts
@@ -26,6 +26,7 @@ export const AI_CHAT_QUESTION_CARD_TITLE = 'Pulse Assistant needs your input';
export const AI_CHAT_QUESTION_CARD_PLACEHOLDER = 'Type your answer...';
export const AI_CHAT_ASSISTANT_MESSAGE_LABEL = 'Pulse Assistant';
export const AI_CHAT_CONTEXT_USED_LABEL = 'Context used';
+export const AI_CHAT_LAST_TURN_USAGE_LABEL = 'Last assistant turn usage';
export const AI_CHAT_PROVIDER_READINESS_SETTINGS_HREF = '/settings/system-ai';
export const AI_CHAT_PROVIDER_READINESS_SETTINGS_LABEL = 'Open settings';
export const AI_CHAT_PROVIDER_READINESS_RETRY_LABEL = 'Retry';