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.

Improve Assistant inventory and activity flow

rcourtman73b0635c2194
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 3cdee5bf39..dc338cdffc 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -6767,11 +6767,11 @@
{
"id": "codex-lane-followup-architecture-post-rc-canonicalization",
"agent_id": "codex",
- "summary": "Improve Assistant frontend in-flight progress and session ergonomics toward OpenCode parity",
+ "summary": "Improve Assistant inventory context and OpenCode-style activity flow",
"target_id": "v6-product-lane-expansion",
"claimed_at": "2026-06-05T21:57:48Z",
- "heartbeat_at": "2026-06-05T21:57:48Z",
- "expires_at": "2026-06-05T23:57:48Z",
+ "heartbeat_at": "2026-06-05T23:04:17Z",
+ "expires_at": "2026-06-06T01:04:17Z",
"work_item": {
"kind": "lane-followup",
"id": "architecture-post-rc-canonicalization"
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 62b33d1aa3..e45c5ce5b8 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -67,7 +67,10 @@ runtime cost control, and shared AI transport surfaces.
OpenRouter preflights affordability against the requested maximum completion
budget, so leaving the field unset can make tiny chat turns reserve a
model-scale output default and fail against per-key total limits despite the
- account having credit. The provider boundary owns this request-shape fix;
+ account having credit. That bounded default must still be high enough for
+ normal detailed Assistant answers such as inventory breakdowns; provider
+ request shaping must not make an ordinary answer finish mid-sentence. The
+ provider boundary owns this request-shape fix;
UI code must not work around it with route-specific retry copy. If the
provider still rejects the request because the requested completion budget
exceeds the key limit, the Assistant error message must name that key-limit
@@ -191,6 +194,10 @@ runtime cost control, and shared AI transport surfaces.
progress, not answer content; once visible assistant text, tool progress,
approvals, or questions begin, stale workflow text must clear so the row does
not keep saying it is waiting on a phase that has already been superseded.
+ OpenCode-parity Assistant UX work must reference OpenCode's actual source
+ implementation for message parts, tool-state mutation, and progress
+ rendering before changing Pulse behavior; parity means adapting the proven
+ interaction model, not guessing from screenshots or observed behavior alone.
Streamed provider startup must be bounded by the configured Assistant request
timeout and the OpenAI-compatible SSE response-header guard; transient
startup failures may retry once before surfacing failed-turn recovery, but a
@@ -202,19 +209,46 @@ runtime cost control, and shared AI transport surfaces.
the selected model owns investigation and action choice inside Pulse policy.
Direct text turns such as exact-reply diagnostics must withhold tools and
use a scoped system prompt that does not advertise unavailable tools.
- Inventory, count, overview, and status prompts that only need canonical
- Pulse resource state must expose the canonical query/clarification path
- instead of shell/read/control tools, so prompts like "how many devices in
- this" route toward Pulse inventory rather than `/dev` inspection. Those
- count/overview turns may prefetch a bounded canonical inventory summary
- before the model request and then withhold tools so the first visible answer
- is fast and cannot drift into shell inspection. If a query-only turn still
- reaches a model-owned `pulse_query` topology call, omitting `summary_only`
- must default to summary-only before execution; detailed topology remains
- available in the full governed path or when the model explicitly asks for
- detail. The system prompt for a turn must describe only the tools actually
- offered to the provider for that turn; generic tool-governance prose must not
- name tools hidden from the current manifest.
+ Inventory, count, overview, status, list, and breakdown prompts that only
+ need canonical Pulse resource state must expose the canonical
+ query/clarification path instead of shell/read/control tools, so prompts
+ like "how many devices in this" and "give me an inventory breakdown by node"
+ route toward Pulse inventory rather than `/dev` inspection. Those query-only
+ turns may prefetch canonical topology context before the model request,
+ including aggregate counts plus per-node and workload detail where available,
+ and then withhold tools so the first visible answer is fast and cannot drift
+ into shell inspection. The prefetch contract must tell the provider whether
+ the topology detail is complete or context-truncated, and should pass a
+ compact user-visible inventory payload rather than raw governed tool JSON so
+ policy metadata cannot cause providers to hide ordinary topology labels.
+ The compact payload must include exact `answer_label` fields for nodes and
+ workloads; the provider-facing instruction must tell the model to copy those
+ labels exactly instead of substituting generic labels like `Node 1`, `VM
+ 100`, or `CT 101`. For external model routes, only this exact
+ Pulse-generated compact inventory context may bypass resource-label text
+ redaction; operator prompts, handoff text, tool payloads, raw IDs, IPs,
+ config, and secret-like text remain governed by the model-bound sanitizer.
+ The normal inventory fast-path prompt must not seed provider output with
+ redaction vocabulary; raw secrets, config values, IP addresses, routing
+ metadata, provider internals, and shell command claims remain out of scope
+ for normal inventory answers. The Assistant transcript should show compact
+ activity as work happens: local context reads, governed tool names, provider
+ routing, fallback, and first-token waiting must appear as a replacing live
+ status/header status rather than a dead-looking wait state or a dumped list
+ of transient phases. Hide or collapse unsafe details and bulky outputs, but
+ do not hide the fact that Pulse is running a local read, invoking a governed
+ tool, or waiting on a provider. If a query-only
+ turn still reaches a model-owned `pulse_query` topology call, omitting
+ `summary_only` must default to summary-only before execution; detailed
+ topology remains available in the full governed path or when the model
+ explicitly asks for detail. Assistant answer style should stay operational
+ and must not use emoji, warning icons, or decorative symbols unless the user
+ explicitly asks for that tone.
+ The system prompt for a turn must describe only the tools actually offered to the
+ provider for that turn; generic tool-governance prose must not name tools
+ hidden from the current manifest. Deterministic provider-request capture is
+ the primary proof harness for this fast path; live OpenRouter/browser checks
+ are final smoke tests, not the iteration loop.
Restored Assistant sessions must hydrate saved assistant content and
persisted tool calls into the same transcript event shape used by live
streams so switching sessions does not hide prior tool evidence or collapse
diff --git a/frontend-modern/src/components/AI/Chat/MessageItem.tsx b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
index 1a2ba2061c..7497b5dca0 100644
--- a/frontend-modern/src/components/AI/Chat/MessageItem.tsx
+++ b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
@@ -1,4 +1,14 @@
-import { Component, Show, For, Switch, Match, createMemo, createSignal } from 'solid-js';
+import {
+ Component,
+ Show,
+ For,
+ Switch,
+ Match,
+ createEffect,
+ createMemo,
+ createSignal,
+ onCleanup,
+} from 'solid-js';
import CheckIcon from 'lucide-solid/icons/check';
import CircleAlertIcon from 'lucide-solid/icons/circle-alert';
import ClockIcon from 'lucide-solid/icons/clock';
@@ -18,6 +28,7 @@ import type {
PendingApproval,
PendingQuestion,
StreamDisplayEvent,
+ WorkflowStatus,
} from './types';
import {
AI_CHAT_ASSISTANT_MESSAGE_LABEL,
@@ -109,7 +120,31 @@ export const MessageItem: Component<MessageItemProps> = (props) => {
!props.message.content.trim() &&
!hasRenderableStreamEvents() &&
!props.message.error;
- const workflowStatusText = createMemo(() => props.message.workflowStatus?.message?.trim() || '');
+ const [statusNow, setStatusNow] = createSignal(Date.now());
+ createEffect(() => {
+ const status = props.message.workflowStatus;
+ if (!props.message.isStreaming || !status?.startedAt) return;
+ setStatusNow(Date.now());
+ const interval = window.setInterval(() => setStatusNow(Date.now()), 1000);
+ onCleanup(() => window.clearInterval(interval));
+ });
+ const formatWorkflowStatus = (status?: WorkflowStatus, includeElapsed = false) => {
+ const message = status?.message?.trim();
+ if (!message) return '';
+ const tool = status?.tool?.trim();
+ const toolSuffix = tool && !message.includes(tool) ? ` · ${formatIdentifierLabel(tool)}` : '';
+ let elapsedSuffix = '';
+ if (includeElapsed && status?.startedAt) {
+ const elapsedSeconds = Math.max(0, Math.floor((statusNow() - status.startedAt) / 1000));
+ if (elapsedSeconds >= 2) {
+ elapsedSuffix = ` (${elapsedSeconds}s)`;
+ }
+ }
+ return `${message}${toolSuffix}${elapsedSuffix}`;
+ };
+ const workflowStatusText = createMemo(() =>
+ formatWorkflowStatus(props.message.workflowStatus, true),
+ );
const inlineStreamingStatusText = createMemo(() => {
return workflowStatusText() || 'Thinking...';
});
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
index 174117eabc..7c7bf553d7 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
@@ -527,7 +527,7 @@ describe('MessageItem', () => {
));
expect(
- screen.getByText('Planning governed action and safety checks before execution.'),
+ screen.getByText('Planning governed action and safety checks before execution. · pulse exec'),
).toBeInTheDocument();
expect(screen.queryByText('Thinking...')).not.toBeInTheDocument();
});
@@ -543,7 +543,7 @@ describe('MessageItem', () => {
streamEvents: [{ type: 'content', content: 'Partial answer' }],
workflowStatus: {
phase: 'provider_start',
- message: 'Waiting for OpenRouter to start responding.',
+ message: 'Sent request to OpenRouter; waiting for the first token.',
},
})}
{...makeHandlers()}
@@ -551,7 +551,7 @@ describe('MessageItem', () => {
));
expect(screen.getByText('Partial answer')).toBeInTheDocument();
- expect(screen.getByText('Waiting for OpenRouter to start responding.')).toBeInTheDocument();
+ expect(screen.getByText('Sent request to OpenRouter; waiting for the first token.')).toBeInTheDocument();
expect(screen.queryByText('Thinking...')).not.toBeInTheDocument();
});
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
index 1cdafcf0d2..dd7588ed82 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -897,7 +897,11 @@ describe('useChat', () => {
);
expect(assistant.content).not.toContain('pulse_read');
expect(assistant.content).not.toContain('raw arguments');
- expect(assistant.streamEvents?.map((e) => e.type)).toEqual(['content', 'tool', 'content']);
+ expect(assistant.streamEvents?.map((e) => e.type)).toEqual([
+ 'content',
+ 'tool',
+ 'content',
+ ]);
dispose();
});
@@ -929,12 +933,14 @@ describe('useChat', () => {
const assistant = chat.messages().find((m) => m.role === 'assistant')!;
expect(assistant.content).toBe('');
expect(assistant.streamEvents).toEqual([]);
- expect(assistant.workflowStatus).toEqual({
- phase: 'plan',
- message: 'Planning governed action and safety checks before execution.',
- state: 'READING',
- tool: 'pulse_exec',
- });
+ expect(assistant.workflowStatus).toEqual(
+ expect.objectContaining({
+ phase: 'plan',
+ message: 'Planning governed action and safety checks before execution.',
+ state: 'READING',
+ tool: 'pulse_exec',
+ }),
+ );
dispose();
});
@@ -959,13 +965,85 @@ describe('useChat', () => {
const assistant = chat.messages().find((m) => m.role === 'assistant')!;
expect(assistant.model).toBe('gemini:gemini-3.1-flash-lite');
- expect(assistant.workflowStatus).toEqual({
- phase: 'provider_fallback',
- message: 'OpenRouter did not start a response; trying Gemini.',
- });
+ expect(assistant.workflowStatus).toEqual(
+ expect.objectContaining({
+ phase: 'provider_fallback',
+ message: 'OpenRouter did not start a response; trying Gemini.',
+ }),
+ );
dispose();
});
+ it('paces rapid workflow progress as one replacing live status', async () => {
+ vi.useFakeTimers();
+ const { getFireEvent } = setupWithEventCapture();
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
+
+ try {
+ await chat.sendMessage('hi');
+ const fire = getFireEvent();
+
+ fire({
+ type: 'workflow_state',
+ data: {
+ phase: 'context',
+ message: 'Reading current Pulse inventory with pulse_query.',
+ tool: 'pulse_query',
+ },
+ });
+ fire({
+ type: 'workflow_state',
+ data: {
+ phase: 'context',
+ message: 'Built compact inventory context for the model.',
+ tool: 'pulse_query',
+ },
+ });
+ fire({
+ type: 'workflow_state',
+ data: {
+ phase: 'provider_start',
+ message: 'Sent request to OpenRouter; waiting for the first token.',
+ },
+ });
+
+ let assistant = chat.messages().find((m) => m.role === 'assistant')!;
+ expect(assistant.streamEvents).toEqual([]);
+ expect(assistant.workflowStatus).toEqual(
+ expect.objectContaining({
+ message: 'Reading current Pulse inventory with pulse_query.',
+ }),
+ );
+
+ await vi.advanceTimersByTimeAsync(449);
+ assistant = chat.messages().find((m) => m.role === 'assistant')!;
+ expect(assistant.workflowStatus).toEqual(
+ expect.objectContaining({
+ message: 'Reading current Pulse inventory with pulse_query.',
+ }),
+ );
+
+ await vi.advanceTimersByTimeAsync(1);
+ assistant = chat.messages().find((m) => m.role === 'assistant')!;
+ expect(assistant.workflowStatus).toEqual(
+ expect.objectContaining({
+ message: 'Built compact inventory context for the model.',
+ }),
+ );
+
+ await vi.advanceTimersByTimeAsync(450);
+ assistant = chat.messages().find((m) => m.role === 'assistant')!;
+ expect(assistant.workflowStatus).toEqual(
+ expect.objectContaining({
+ message: 'Sent request to OpenRouter; waiting for the first token.',
+ }),
+ );
+ } finally {
+ dispose();
+ vi.useRealTimers();
+ }
+ });
+
it('clears workflow progress when visible answer content starts streaming', async () => {
const { getFireEvent } = setupWithEventCapture();
const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
@@ -977,7 +1055,7 @@ describe('useChat', () => {
type: 'workflow_state',
data: {
phase: 'provider_start',
- message: 'Waiting for OpenRouter to start responding.',
+ message: 'Sent request to OpenRouter; waiting for the first token.',
},
});
fire({ type: 'content', data: 'Here is the answer.' });
@@ -1433,7 +1511,7 @@ describe('useChat', () => {
const assistant = chat.messages().find((m) => m.role === 'assistant')!;
const types = assistant.streamEvents!.map((e) => e.type);
- // Content, pending_tool, content (thinking is retained internally, not rendered)
+ // Content, pending_tool, content. Thinking is retained internally, not rendered.
expect(types).toEqual(['content', 'pending_tool', 'content']);
dispose();
});
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index aaecccf9f2..939d7e88bb 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -30,10 +30,18 @@ import type {
const generateId = () => Math.random().toString(36).substring(2, 9);
type AssistantInterruption = NonNullable<ChatMessage['interruption']>;
-const INITIAL_ASSISTANT_WORKFLOW_STATUS: WorkflowStatus = {
+const WORKFLOW_STATUS_MIN_DWELL_MS = 450;
+
+const createInitialAssistantWorkflowStatus = (): WorkflowStatus => ({
phase: 'request_start',
message: 'Preparing Pulse context.',
-};
+ startedAt: Date.now(),
+});
+
+interface WorkflowStatusQueue {
+ statuses: WorkflowStatus[];
+ timer: number | undefined;
+}
export interface UseChatOptions {
sessionId?: string;
@@ -90,6 +98,8 @@ export function useChat(options: UseChatOptions = {}) {
let isDrainingQueuedFollowUps = false;
const suppressedRawContentMessageIds = new Set<string>();
const outputArtifactStreamStates = new Map<string, AssistantOutputArtifactStreamState>();
+ const workflowStatusQueues = new Map<string, WorkflowStatusQueue>();
+ const lastDisplayedWorkflowStatuses = new Map<string, WorkflowStatus>();
const outputArtifactStateFor = (assistantId: string) => {
let state = outputArtifactStreamStates.get(assistantId);
@@ -109,6 +119,90 @@ export function useChat(options: UseChatOptions = {}) {
clearOutputArtifactState(assistantId);
};
+ const workflowStatusesMatch = (a?: WorkflowStatus, b?: WorkflowStatus) =>
+ !!a &&
+ !!b &&
+ (a.phase || '') === (b.phase || '') &&
+ a.message === b.message &&
+ (a.state || '') === (b.state || '') &&
+ (a.tool || '') === (b.tool || '');
+
+ const clearWorkflowStatusQueue = (assistantId: string) => {
+ const queue = workflowStatusQueues.get(assistantId);
+ if (queue?.timer !== undefined) {
+ window.clearTimeout(queue.timer);
+ }
+ workflowStatusQueues.delete(assistantId);
+ lastDisplayedWorkflowStatuses.delete(assistantId);
+ };
+
+ const clearAllWorkflowStatusQueues = () => {
+ for (const assistantId of workflowStatusQueues.keys()) {
+ clearWorkflowStatusQueue(assistantId);
+ }
+ lastDisplayedWorkflowStatuses.clear();
+ };
+
+ const setAssistantWorkflowStatus = (
+ assistantId: string,
+ requestId: number,
+ workflowStatus: WorkflowStatus,
+ ) => {
+ if (requestId !== activeRequestId) return;
+ lastDisplayedWorkflowStatuses.set(assistantId, workflowStatus);
+ setMessages((prev) =>
+ prev.map((msg) => (msg.id === assistantId ? { ...msg, workflowStatus } : msg)),
+ );
+ };
+
+ const drainWorkflowStatusQueue = (assistantId: string, requestId: number) => {
+ const queue = workflowStatusQueues.get(assistantId);
+ if (!queue) return;
+
+ const nextStatus = queue.statuses.shift();
+ if (!nextStatus) {
+ queue.timer = undefined;
+ return;
+ }
+
+ setAssistantWorkflowStatus(assistantId, requestId, nextStatus);
+ queue.timer = window.setTimeout(() => {
+ if (requestId !== activeRequestId) {
+ clearWorkflowStatusQueue(assistantId);
+ return;
+ }
+ const currentQueue = workflowStatusQueues.get(assistantId);
+ if (!currentQueue) return;
+ currentQueue.timer = undefined;
+ if (currentQueue.statuses.length > 0) {
+ drainWorkflowStatusQueue(assistantId, requestId);
+ }
+ }, WORKFLOW_STATUS_MIN_DWELL_MS);
+ };
+
+ const enqueueWorkflowStatus = (
+ assistantId: string,
+ requestId: number,
+ workflowStatus: WorkflowStatus,
+ ) => {
+ let queue = workflowStatusQueues.get(assistantId);
+ if (!queue) {
+ queue = { statuses: [], timer: undefined };
+ workflowStatusQueues.set(assistantId, queue);
+ }
+
+ const lastQueuedStatus = queue.statuses[queue.statuses.length - 1];
+ const lastDisplayedStatus = lastDisplayedWorkflowStatuses.get(assistantId);
+ if (workflowStatusesMatch(lastQueuedStatus || lastDisplayedStatus, workflowStatus)) {
+ return;
+ }
+
+ queue.statuses.push(workflowStatus);
+ if (queue.timer === undefined) {
+ drainWorkflowStatusQueue(assistantId, requestId);
+ }
+ };
+
const abortBackendSession = (targetSessionId: string): Promise<void> | null => {
const normalizedSessionId = targetSessionId.trim();
if (!normalizedSessionId) return null;
@@ -137,6 +231,7 @@ export function useChat(options: UseChatOptions = {}) {
abortControllerRef = null;
}
activeRequestId += 1;
+ clearAllWorkflowStatusQueues();
setMessages((prev) =>
prev.map((msg) =>
@@ -190,6 +285,7 @@ export function useChat(options: UseChatOptions = {}) {
// Cleanup on unmount
onCleanup(() => {
+ clearAllWorkflowStatusQueues();
void cancelActiveRequest();
});
@@ -363,6 +459,7 @@ export function useChat(options: UseChatOptions = {}) {
phase: phase || undefined,
state: state || undefined,
tool: tool || undefined,
+ startedAt: Date.now(),
};
};
@@ -490,6 +587,22 @@ export function useChat(options: UseChatOptions = {}) {
applyStreamSessionId(extractSessionId(event.data));
}
+ if (event.type === 'workflow_state') {
+ const workflowStatus = extractWorkflowStatus(event.data);
+ const nextModel = extractWorkflowNextModel(event.data);
+ if (!workflowStatus && !nextModel) return;
+
+ if (nextModel) {
+ setMessages((prev) =>
+ prev.map((msg) => (msg.id === assistantId ? { ...msg, model: nextModel } : msg)),
+ );
+ }
+ if (workflowStatus) {
+ enqueueWorkflowStatus(assistantId, requestId, workflowStatus);
+ }
+ return;
+ }
+
setMessages((prev) =>
prev.map((msg) => {
if (msg.id !== assistantId) return msg;
@@ -497,6 +610,7 @@ export function useChat(options: UseChatOptions = {}) {
try {
switch (event.type) {
case 'content': {
+ clearWorkflowStatusQueue(assistantId);
if (suppressedRawContentMessageIds.has(assistantId)) {
return msg;
}
@@ -536,18 +650,8 @@ export function useChat(options: UseChatOptions = {}) {
};
}
- case 'workflow_state': {
- const workflowStatus = extractWorkflowStatus(event.data);
- const nextModel = extractWorkflowNextModel(event.data);
- if (!workflowStatus && !nextModel) return msg;
- return {
- ...msg,
- ...(workflowStatus ? { workflowStatus } : {}),
- ...(nextModel ? { model: nextModel } : {}),
- };
- }
-
case 'tool_start': {
+ clearWorkflowStatusQueue(assistantId);
clearSuppressedOutputBoundary(assistantId);
const data = (event.data || {}) as {
id?: string;
@@ -586,6 +690,7 @@ export function useChat(options: UseChatOptions = {}) {
}
case 'tool_end': {
+ clearWorkflowStatusQueue(assistantId);
clearSuppressedOutputBoundary(assistantId);
const data = event.data as {
id?: string;
@@ -690,6 +795,7 @@ export function useChat(options: UseChatOptions = {}) {
}
case 'approval_needed': {
+ clearWorkflowStatusQueue(assistantId);
clearSuppressedOutputBoundary(assistantId);
const data = event.data as {
command: string;
@@ -772,6 +878,7 @@ export function useChat(options: UseChatOptions = {}) {
}
case 'question': {
+ clearWorkflowStatusQueue(assistantId);
clearSuppressedOutputBoundary(assistantId);
const data = event.data as { question_id: string; questions: Array<any> };
@@ -808,6 +915,7 @@ export function useChat(options: UseChatOptions = {}) {
}
case 'done': {
+ clearWorkflowStatusQueue(assistantId);
const pendingText = suppressedRawContentMessageIds.has(assistantId)
? ''
: flushPendingAssistantOutputText(outputArtifactStateFor(assistantId));
@@ -841,6 +949,7 @@ export function useChat(options: UseChatOptions = {}) {
}
case 'error': {
+ clearWorkflowStatusQueue(assistantId);
clearSuppressedOutputBoundary(assistantId);
const errorMsg = extractErrorMessage(event.data);
// Keep any content streamed before the failure; surface the error
@@ -931,6 +1040,7 @@ export function useChat(options: UseChatOptions = {}) {
const assistantId = generateId();
const requestModel = effectiveModelRoute();
+ const initialWorkflowStatus = createInitialAssistantWorkflowStatus();
const streamingMessage: ChatMessage = {
id: assistantId,
role: 'assistant',
@@ -941,8 +1051,9 @@ export function useChat(options: UseChatOptions = {}) {
pendingTools: [],
toolCalls: [],
streamEvents: [],
- workflowStatus: INITIAL_ASSISTANT_WORKFLOW_STATUS,
+ workflowStatus: initialWorkflowStatus,
};
+ lastDisplayedWorkflowStatuses.set(assistantId, initialWorkflowStatus);
if (options?.queuedMessageId) {
setMessages((prev) => [
@@ -1002,7 +1113,9 @@ export function useChat(options: UseChatOptions = {}) {
setMessages((prev) =>
prev.map((msg) =>
- msg.id === assistantId ? { ...msg, isStreaming: false, error: errorMessage } : msg,
+ msg.id === assistantId
+ ? { ...msg, isStreaming: false, workflowStatus: undefined, error: errorMessage }
+ : msg,
),
);
await notifyConversationChanged();
@@ -1065,6 +1178,7 @@ export function useChat(options: UseChatOptions = {}) {
// Clear messages and reset session (for starting fresh)
const clearMessages = () => {
void cancelActiveRequest();
+ clearAllWorkflowStatusQueues();
setQueuedFollowUps([]);
setMessages([]);
setSessionId(''); // Clear session so next message creates a new one
@@ -1073,6 +1187,7 @@ export function useChat(options: UseChatOptions = {}) {
// Load session messages
const loadSession = async (id: string): Promise<boolean> => {
void cancelActiveRequest();
+ clearAllWorkflowStatusQueues();
setQueuedFollowUps([]);
try {
const msgs = await AIChatAPI.getMessages(id);
@@ -1107,6 +1222,7 @@ export function useChat(options: UseChatOptions = {}) {
// next chat stream so the UI does not create empty server-side sessions.
const newSession = async (): Promise<boolean> => {
void cancelActiveRequest();
+ clearAllWorkflowStatusQueues();
setQueuedFollowUps([]);
setSessionId('');
setMessages([]);
diff --git a/frontend-modern/src/components/AI/Chat/types.ts b/frontend-modern/src/components/AI/Chat/types.ts
index 3ce8293d74..96a66ff284 100644
--- a/frontend-modern/src/components/AI/Chat/types.ts
+++ b/frontend-modern/src/components/AI/Chat/types.ts
@@ -113,6 +113,7 @@ export interface WorkflowStatus {
message: string;
state?: string;
tool?: string;
+ startedAt?: number;
}
export interface ChatMessageRequestContext {
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 0e9b702afd..4daea606bc 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -759,12 +759,15 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
len(handoffActions) > 0 ||
handoffFindingID != "" ||
!handoffMetadataEmpty(handoffMetadata)
+ modelBoundaryAllowedInventoryContext := ""
assistantToolScope := assistantToolScopeForPrompt(req.Prompt, hasModelHandoffContext)
if assistantToolScope == assistantTurnToolScopeQueryOnly {
- emitWorkflowState(streamCallback, "context", "Reading current Pulse inventory.", "", "pulse_query")
- if summaryContext := s.prefetchAssistantInventorySummaryContext(ctx, baseExecutor); summaryContext != "" {
+ emitWorkflowState(streamCallback, "context", "Reading current Pulse inventory with pulse_query.", "", "pulse_query")
+ if summaryContext := s.prefetchAssistantInventoryTopologyContext(ctx, baseExecutor); summaryContext != "" {
+ modelBoundaryAllowedInventoryContext = summaryContext
injectHandoffContextIntoLatestUserMessage(messages, summaryContext)
assistantToolScope = assistantTurnToolScopeTextOnly
+ emitWorkflowState(streamCallback, "context_ready", "Built compact inventory context for the model.", "", "pulse_query")
log.Debug().
Str("session_id", session.ID).
Msg("[ChatService] Prefetched canonical inventory summary for query-only Assistant turn")
@@ -830,7 +833,11 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
loop.SetOrgID(s.orgID)
loop.SetAutonomousMode(autonomousMode)
loop.SetPreferSummaryOnlyQueries(assistantToolScope == assistantTurnToolScopeQueryOnly)
- loop.SetRequestSanitizer(modelboundary.RequestSanitizerForModel(attempt.Model, unifiedResourceProvider))
+ sanitizerOptions := []modelboundary.RequestSanitizerOption{}
+ if modelBoundaryAllowedInventoryContext != "" {
+ sanitizerOptions = append(sanitizerOptions, modelboundary.AllowResourcePolicyText(modelBoundaryAllowedInventoryContext))
+ }
+ loop.SetRequestSanitizer(modelboundary.RequestSanitizerForModel(attempt.Model, unifiedResourceProvider, sanitizerOptions...))
loop.SetSuppressProviderErrorEvents(true)
loop.SetSessionFSM(sessionFSM)
loop.SetKnowledgeAccumulator(ka)
@@ -849,7 +856,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
emitWorkflowState(
streamCallback,
"provider_start",
- fmt.Sprintf("Waiting for %s to start responding.", providerLabelForAttempt(attempt)),
+ fmt.Sprintf("Sent request to %s; waiting for the first token.", providerLabelForAttempt(attempt)),
sessionFSMState(sessionFSM),
"",
)
@@ -968,13 +975,26 @@ func injectHandoffContextIntoLatestUserMessage(messages []Message, handoffContex
}
}
-func (s *Service) prefetchAssistantInventorySummaryContext(ctx context.Context, executor *tools.PulseToolExecutor) string {
+func (s *Service) prefetchAssistantInventoryTopologyContext(ctx context.Context, executor *tools.PulseToolExecutor) string {
+ if contextText := strings.TrimSpace(s.prefetchAssistantInventoryTopologyContextFromReadState()); contextText != "" {
+ return assistantInventoryTopologyContextPreamble(contextText) + "\n" +
+ truncateToolResultForModel(contextText)
+ }
if executor == nil {
return ""
}
result, err := executor.ExecuteTool(ctx, "pulse_query", map[string]interface{}{
- "action": "topology",
- "summary_only": true,
+ "action": "topology",
+ "summary_only": false,
+ "max_proxmox_nodes": 0,
+ "max_vms_per_node": 0,
+ "max_containers_per_node": 0,
+ "max_docker_hosts": 0,
+ "max_docker_containers_per_host": 0,
+ "max_k8s_clusters": 0,
+ "max_k8s_nodes_per_cluster": 0,
+ "max_k8s_deployments_per_cluster": 0,
+ "max_k8s_pods_per_cluster": 0,
})
if err != nil || result.IsError {
log.Debug().
@@ -987,8 +1007,490 @@ func (s *Service) prefetchAssistantInventorySummaryContext(ctx context.Context,
if resultText == "" {
return ""
}
- return "Pulse inventory summary from current canonical resource state. Use this context to answer the user's count, overview, or status question. Do not claim shell inspection or host command execution.\n" +
- truncateToolResultForModel(resultText)
+ contextText := resultText
+ var topology tools.TopologyResponse
+ if err := json.Unmarshal([]byte(resultText), &topology); err == nil {
+ if inventoryText, marshalErr := marshalAssistantInventoryTopologyContext(topology.NormalizeCollections()); marshalErr == nil && strings.TrimSpace(inventoryText) != "" {
+ contextText = inventoryText
+ }
+ }
+ return assistantInventoryTopologyContextPreamble(contextText) + "\n" +
+ truncateToolResultForModel(contextText)
+}
+
+func (s *Service) prefetchAssistantInventoryTopologyContextFromReadState() string {
+ if s == nil || s.readState == nil {
+ return ""
+ }
+ contextText, err := marshalAssistantInventoryTopologyContextFromReadState(s.readState)
+ if err != nil {
+ log.Debug().Err(err).Msg("[ChatService] Unable to prefetch Assistant inventory context from ReadState")
+ return ""
+ }
+ return strings.TrimSpace(contextText)
+}
+
+func marshalAssistantInventoryTopologyContextFromReadState(rs unifiedresources.ReadState) (string, error) {
+ if rs == nil {
+ return "", nil
+ }
+
+ context := assistantInventoryTopologyContext{
+ Proxmox: assistantInventoryProxmoxTopology{Nodes: []assistantInventoryProxmoxNode{}},
+ Docker: assistantInventoryDockerTopology{Hosts: []assistantInventoryDockerHost{}},
+ Kubernetes: assistantInventoryKubernetesTopology{Clusters: []assistantInventoryKubernetesCluster{}},
+ }
+ nodeMap := make(map[string]*assistantInventoryProxmoxNode)
+ ensureNode := func(name, status string) *assistantInventoryProxmoxNode {
+ name = firstNonEmptyString(name, "unknown")
+ key := strings.ToLower(name)
+ if existing := nodeMap[key]; existing != nil {
+ if existing.Status == "" || existing.Status == "unknown" {
+ existing.Status = firstNonEmptyString(status, existing.Status, "unknown")
+ }
+ return existing
+ }
+ node := &assistantInventoryProxmoxNode{
+ AnswerLabel: assistantInventoryNodeAnswerLabel(name),
+ Name: name,
+ Status: firstNonEmptyString(status, "unknown"),
+ VMs: []assistantInventoryWorkload{},
+ Containers: []assistantInventoryWorkload{},
+ VMCount: 0,
+ ContainerCount: 0,
+ }
+ nodeMap[key] = node
+ return node
+ }
+
+ for _, node := range rs.Nodes() {
+ if node == nil {
+ continue
+ }
+ context.Summary.TotalNodes++
+ ensureNode(firstNonEmptyString(node.NodeName(), node.Name()), string(node.Status()))
+ }
+ for _, vm := range rs.VMs() {
+ if vm == nil {
+ continue
+ }
+ context.Summary.TotalVMs++
+ if statusIsRunningOrOnline(string(vm.Status())) {
+ context.Summary.RunningVMs++
+ }
+ node := ensureNode(vm.Node(), "unknown")
+ node.VMCount++
+ name := strings.TrimSpace(vm.Name())
+ node.VMs = append(node.VMs, assistantInventoryWorkload{
+ AnswerLabel: assistantInventoryGuestAnswerLabel("VM", vm.VMID(), name),
+ VMID: vm.VMID(),
+ Name: name,
+ Status: string(vm.Status()),
+ CPUPercent: vm.CPUPercent(),
+ MemoryPercent: vm.MemoryPercent(),
+ })
+ }
+ for _, container := range rs.Containers() {
+ if container == nil {
+ continue
+ }
+ context.Summary.TotalSystemContainers++
+ if statusIsRunningOrOnline(string(container.Status())) {
+ context.Summary.RunningContainers++
+ }
+ node := ensureNode(container.Node(), "unknown")
+ node.ContainerCount++
+ name := strings.TrimSpace(container.Name())
+ node.Containers = append(node.Containers, assistantInventoryWorkload{
+ AnswerLabel: assistantInventoryGuestAnswerLabel("CT", container.VMID(), name),
+ VMID: container.VMID(),
+ Name: name,
+ Status: string(container.Status()),
+ CPUPercent: container.CPUPercent(),
+ MemoryPercent: container.MemoryPercent(),
+ })
+ }
+
+ for _, node := range nodeMap {
+ context.Proxmox.Nodes = append(context.Proxmox.Nodes, *node)
+ }
+ sort.Slice(context.Proxmox.Nodes, func(i, j int) bool {
+ return strings.ToLower(context.Proxmox.Nodes[i].Name) < strings.ToLower(context.Proxmox.Nodes[j].Name)
+ })
+ for i := range context.Proxmox.Nodes {
+ sort.Slice(context.Proxmox.Nodes[i].VMs, func(a, b int) bool {
+ return context.Proxmox.Nodes[i].VMs[a].VMID < context.Proxmox.Nodes[i].VMs[b].VMID
+ })
+ sort.Slice(context.Proxmox.Nodes[i].Containers, func(a, b int) bool {
+ return context.Proxmox.Nodes[i].Containers[a].VMID < context.Proxmox.Nodes[i].Containers[b].VMID
+ })
+ }
+
+ if len(context.Proxmox.Nodes) == 0 &&
+ context.Summary.TotalVMs == 0 &&
+ context.Summary.TotalSystemContainers == 0 {
+ return "", nil
+ }
+ encoded, err := json.Marshal(context)
+ if err != nil {
+ return "", err
+ }
+ return string(encoded), nil
+}
+
+func marshalAssistantInventoryTopologyContext(topology tools.TopologyResponse) (string, error) {
+ context := assistantInventoryTopologyContext{
+ Summary: topology.Summary,
+ Proxmox: assistantInventoryProxmoxTopology{
+ Nodes: make([]assistantInventoryProxmoxNode, 0, len(topology.Proxmox.Nodes)),
+ },
+ Docker: assistantInventoryDockerTopology{
+ Hosts: make([]assistantInventoryDockerHost, 0, len(topology.Docker.Hosts)),
+ },
+ Kubernetes: assistantInventoryKubernetesTopology{
+ Clusters: make([]assistantInventoryKubernetesCluster, 0, len(topology.Kubernetes.Clusters)),
+ },
+ }
+ for _, node := range topology.Proxmox.Nodes {
+ nodeContext := assistantInventoryProxmoxNode{
+ AnswerLabel: assistantInventoryNodeAnswerLabel(node.Name),
+ Name: node.Name,
+ Status: node.Status,
+ AgentConnected: node.AgentConnected,
+ CanExecute: node.CanExecute,
+ VMCount: node.VMCount,
+ ContainerCount: node.ContainerCount,
+ VMs: make([]assistantInventoryWorkload, 0, len(node.VMs)),
+ Containers: make([]assistantInventoryWorkload, 0, len(node.Containers)),
+ }
+ for _, vm := range node.VMs {
+ nodeContext.VMs = append(nodeContext.VMs, assistantInventoryWorkload{
+ AnswerLabel: assistantInventoryGuestAnswerLabel("VM", vm.VMID, vm.Name),
+ VMID: vm.VMID,
+ Name: vm.Name,
+ Status: vm.Status,
+ CPUPercent: vm.CPU,
+ MemoryPercent: vm.Memory,
+ })
+ }
+ for _, container := range node.Containers {
+ nodeContext.Containers = append(nodeContext.Containers, assistantInventoryWorkload{
+ AnswerLabel: assistantInventoryGuestAnswerLabel("CT", container.VMID, container.Name),
+ VMID: container.VMID,
+ Name: container.Name,
+ Status: container.Status,
+ CPUPercent: container.CPU,
+ MemoryPercent: container.Memory,
+ })
+ }
+ context.Proxmox.Nodes = append(context.Proxmox.Nodes, nodeContext)
+ }
+ for _, host := range topology.Docker.Hosts {
+ hostContext := assistantInventoryDockerHost{
+ AnswerLabel: firstNonEmptyString(host.DisplayName, host.Hostname),
+ Hostname: host.Hostname,
+ DisplayName: host.DisplayName,
+ AgentConnected: host.AgentConnected,
+ CanExecute: host.CanExecute,
+ ContainerCount: host.ContainerCount,
+ RunningCount: host.RunningCount,
+ Containers: make([]assistantInventoryAppContainer, 0, len(host.Containers)),
+ }
+ for _, container := range host.Containers {
+ hostContext.Containers = append(hostContext.Containers, assistantInventoryAppContainer{
+ AnswerLabel: firstNonEmptyString(container.Name, container.ID),
+ ID: container.ID,
+ Name: container.Name,
+ State: container.State,
+ Health: container.Health,
+ })
+ }
+ context.Docker.Hosts = append(context.Docker.Hosts, hostContext)
+ }
+ for _, cluster := range topology.Kubernetes.Clusters {
+ clusterContext := assistantInventoryKubernetesCluster{
+ AnswerLabel: firstNonEmptyString(cluster.Name, cluster.ID),
+ Name: cluster.Name,
+ ID: cluster.ID,
+ Status: cluster.Status,
+ NodeCount: cluster.NodeCount,
+ DeploymentCount: cluster.DeploymentCount,
+ PodCount: cluster.PodCount,
+ Nodes: make([]assistantInventoryKubernetesNode, 0, len(cluster.Nodes)),
+ Deployments: make([]assistantInventoryKubernetesDeployment, 0, len(cluster.Deployments)),
+ Pods: make([]assistantInventoryKubernetesPod, 0, len(cluster.Pods)),
+ }
+ for _, node := range cluster.Nodes {
+ clusterContext.Nodes = append(clusterContext.Nodes, assistantInventoryKubernetesNode{
+ AnswerLabel: node.Name,
+ Name: node.Name,
+ Status: node.Status,
+ Ready: node.Ready,
+ Roles: node.Roles,
+ CPUPercent: node.CPU,
+ MemoryPercent: node.Memory,
+ })
+ }
+ for _, deployment := range cluster.Deployments {
+ clusterContext.Deployments = append(clusterContext.Deployments, assistantInventoryKubernetesDeployment{
+ AnswerLabel: deployment.Name,
+ Name: deployment.Name,
+ Namespace: deployment.Namespace,
+ Status: deployment.Status,
+ DesiredReplicas: deployment.DesiredReplicas,
+ ReadyReplicas: deployment.ReadyReplicas,
+ })
+ }
+ for _, pod := range cluster.Pods {
+ clusterContext.Pods = append(clusterContext.Pods, assistantInventoryKubernetesPod{
+ AnswerLabel: pod.Name,
+ Name: pod.Name,
+ Namespace: pod.Namespace,
+ Status: pod.Status,
+ Restarts: pod.Restarts,
+ OwnerKind: pod.OwnerKind,
+ OwnerName: pod.OwnerName,
+ })
+ }
+ context.Kubernetes.Clusters = append(context.Kubernetes.Clusters, clusterContext)
+ }
+
+ encoded, err := json.Marshal(context)
+ if err != nil {
+ return "", err
+ }
+ return string(encoded), nil
+}
+
+type assistantInventoryTopologyContext struct {
+ Proxmox assistantInventoryProxmoxTopology `json:"proxmox"`
+ Docker assistantInventoryDockerTopology `json:"docker"`
+ Kubernetes assistantInventoryKubernetesTopology `json:"kubernetes"`
+ Summary tools.TopologySummary `json:"summary"`
+}
+
+type assistantInventoryProxmoxTopology struct {
+ Nodes []assistantInventoryProxmoxNode `json:"nodes"`
+}
+
+type assistantInventoryDockerTopology struct {
+ Hosts []assistantInventoryDockerHost `json:"hosts"`
+}
+
+type assistantInventoryKubernetesTopology struct {
+ Clusters []assistantInventoryKubernetesCluster `json:"clusters"`
+}
+
+type assistantInventoryProxmoxNode struct {
+ AnswerLabel string `json:"answer_label"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ AgentConnected bool `json:"agent_connected,omitempty"`
+ CanExecute bool `json:"can_execute,omitempty"`
+ VMCount int `json:"vm_count"`
+ ContainerCount int `json:"container_count"`
+ VMs []assistantInventoryWorkload `json:"vms"`
+ Containers []assistantInventoryWorkload `json:"containers"`
+}
+
+type assistantInventoryWorkload struct {
+ AnswerLabel string `json:"answer_label"`
+ VMID int `json:"vmid"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ CPUPercent float64 `json:"cpu_percent,omitempty"`
+ MemoryPercent float64 `json:"memory_percent,omitempty"`
+}
+
+type assistantInventoryDockerHost struct {
+ AnswerLabel string `json:"answer_label"`
+ Hostname string `json:"hostname"`
+ DisplayName string `json:"display_name,omitempty"`
+ AgentConnected bool `json:"agent_connected,omitempty"`
+ CanExecute bool `json:"can_execute,omitempty"`
+ ContainerCount int `json:"container_count"`
+ RunningCount int `json:"running_count"`
+ Containers []assistantInventoryAppContainer `json:"containers"`
+}
+
+type assistantInventoryAppContainer struct {
+ AnswerLabel string `json:"answer_label"`
+ ID string `json:"id,omitempty"`
+ Name string `json:"name"`
+ State string `json:"state"`
+ Health string `json:"health,omitempty"`
+}
+
+type assistantInventoryKubernetesCluster struct {
+ AnswerLabel string `json:"answer_label"`
+ Name string `json:"name"`
+ ID string `json:"id,omitempty"`
+ Status string `json:"status"`
+ NodeCount int `json:"node_count"`
+ DeploymentCount int `json:"deployment_count"`
+ PodCount int `json:"pod_count"`
+ Nodes []assistantInventoryKubernetesNode `json:"nodes"`
+ Deployments []assistantInventoryKubernetesDeployment `json:"deployments"`
+ Pods []assistantInventoryKubernetesPod `json:"pods"`
+}
+
+type assistantInventoryKubernetesNode struct {
+ AnswerLabel string `json:"answer_label"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Ready bool `json:"ready"`
+ Roles []string `json:"roles"`
+ CPUPercent float64 `json:"cpu_percent,omitempty"`
+ MemoryPercent float64 `json:"memory_percent,omitempty"`
+}
+
+type assistantInventoryKubernetesDeployment struct {
+ AnswerLabel string `json:"answer_label"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Status string `json:"status"`
+ DesiredReplicas int32 `json:"desired_replicas,omitempty"`
+ ReadyReplicas int32 `json:"ready_replicas,omitempty"`
+}
+
+type assistantInventoryKubernetesPod struct {
+ AnswerLabel string `json:"answer_label"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Status string `json:"status"`
+ Restarts int `json:"restarts,omitempty"`
+ OwnerKind string `json:"owner_kind,omitempty"`
+ OwnerName string `json:"owner_name,omitempty"`
+}
+
+func assistantInventoryTopologyContextPreamble(resultText string) string {
+ var lines []string
+ lines = append(lines,
+ "Pulse inventory summary from current canonical resource state, including per-node and workload detail where available.",
+ "Use this context to answer the user's count, overview, status, list, or inventory-breakdown question. Do not claim shell inspection or host command execution.",
+ "The answer_label fields are UI-visible inventory labels. Copy answer_label exactly when listing nodes, VMs, system containers, Docker containers, Kubernetes nodes, deployments, or pods.",
+ "Do not shorten answer_label values or substitute generic labels like Node 1, VM 100, or CT 101 when an answer_label is available.",
+ "Do not include raw secrets, config values, IP addresses, routing metadata, provider internals, or shell command claims in the answer.",
+ )
+
+ var topology tools.TopologyResponse
+ if err := json.Unmarshal([]byte(resultText), &topology); err != nil {
+ lines = append(lines, "Completeness: The topology detail could not be counted before the model request; if the payload is marked TRUNCATED, say which details may be omitted instead of claiming every workload is listed.")
+ return strings.Join(lines, "\n")
+ }
+ topology = topology.NormalizeCollections()
+ included := assistantInventoryIncludedTopologyCounts(topology)
+ complete := !toolResultWouldTruncateForModel(resultText) &&
+ included.proxmoxNodes >= topology.Summary.TotalNodes &&
+ included.vms >= topology.Summary.TotalVMs &&
+ included.systemContainers >= topology.Summary.TotalSystemContainers &&
+ included.dockerHosts >= topology.Summary.TotalDockerHosts &&
+ included.dockerContainers >= topology.Summary.TotalDockerContainers &&
+ included.k8sClusters >= topology.Summary.TotalK8sClusters &&
+ included.k8sNodes >= topology.Summary.TotalK8sNodes &&
+ included.k8sDeployments >= topology.Summary.TotalK8sDeployments &&
+ included.k8sPods >= topology.Summary.TotalK8sPods
+ if complete {
+ lines = append(lines, "Completeness: The topology detail below includes every Proxmox node, VM, system container, Docker host/container, and Kubernetes resource currently visible in Pulse.")
+ } else {
+ lines = append(lines, fmt.Sprintf("Completeness: The topology detail below may be capped or context-truncated. Included detail counts are nodes=%d/%d, VMs=%d/%d, system_containers=%d/%d, docker_hosts=%d/%d, docker_containers=%d/%d, k8s_clusters=%d/%d, k8s_nodes=%d/%d, k8s_deployments=%d/%d, k8s_pods=%d/%d. If included counts do not match totals or a TRUNCATED marker appears, say what may be omitted instead of claiming every workload is listed.",
+ included.proxmoxNodes,
+ topology.Summary.TotalNodes,
+ included.vms,
+ topology.Summary.TotalVMs,
+ included.systemContainers,
+ topology.Summary.TotalSystemContainers,
+ included.dockerHosts,
+ topology.Summary.TotalDockerHosts,
+ included.dockerContainers,
+ topology.Summary.TotalDockerContainers,
+ included.k8sClusters,
+ topology.Summary.TotalK8sClusters,
+ included.k8sNodes,
+ topology.Summary.TotalK8sNodes,
+ included.k8sDeployments,
+ topology.Summary.TotalK8sDeployments,
+ included.k8sPods,
+ topology.Summary.TotalK8sPods,
+ ))
+ }
+ return strings.Join(lines, "\n")
+}
+
+func assistantInventoryNodeAnswerLabel(name string) string {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return "Node unknown"
+ }
+ return "Node " + name
+}
+
+func assistantInventoryGuestAnswerLabel(kind string, id int, name string) string {
+ kind = strings.TrimSpace(kind)
+ name = strings.TrimSpace(name)
+ prefix := kind
+ if id > 0 {
+ prefix = fmt.Sprintf("%s %d", kind, id)
+ }
+ if name == "" {
+ return prefix
+ }
+ return prefix + " " + name
+}
+
+func firstNonEmptyString(values ...string) string {
+ for _, value := range values {
+ if trimmed := strings.TrimSpace(value); trimmed != "" {
+ return trimmed
+ }
+ }
+ return ""
+}
+
+func statusIsRunningOrOnline(status string) bool {
+ switch strings.ToLower(strings.TrimSpace(status)) {
+ case "running", "online", "ready", "healthy":
+ return true
+ default:
+ return false
+ }
+}
+
+type assistantInventoryTopologyCounts struct {
+ proxmoxNodes int
+ vms int
+ systemContainers int
+ dockerHosts int
+ dockerContainers int
+ k8sClusters int
+ k8sNodes int
+ k8sDeployments int
+ k8sPods int
+}
+
+func assistantInventoryIncludedTopologyCounts(topology tools.TopologyResponse) assistantInventoryTopologyCounts {
+ counts := assistantInventoryTopologyCounts{
+ proxmoxNodes: len(topology.Proxmox.Nodes),
+ dockerHosts: len(topology.Docker.Hosts),
+ k8sClusters: len(topology.Kubernetes.Clusters),
+ }
+ for _, node := range topology.Proxmox.Nodes {
+ counts.vms += len(node.VMs)
+ counts.systemContainers += len(node.Containers)
+ }
+ for _, host := range topology.Docker.Hosts {
+ counts.dockerContainers += len(host.Containers)
+ }
+ for _, cluster := range topology.Kubernetes.Clusters {
+ counts.k8sNodes += len(cluster.Nodes)
+ counts.k8sDeployments += len(cluster.Deployments)
+ counts.k8sPods += len(cluster.Pods)
+ }
+ return counts
+}
+
+func toolResultWouldTruncateForModel(text string) bool {
+ return MaxToolResultCharsLimit > 0 && len(text) > MaxToolResultCharsLimit
}
func sanitizeHandoffContextForResourcePolicy(handoffContext string, handoffResources []HandoffResource, provider tools.UnifiedResourceProvider) string {
@@ -3153,6 +3655,8 @@ You are like a colleague doing pair programming on infrastructure tasks. Tool ca
5. BE DIRECT: Acknowledge mistakes or complications honestly. If something won't work as the user expects, say so clearly.
+6. KEEP FORMATTING CLEAN: Use concise headings, bullets, and tables where they help. Do not use emoji, warning icons, or decorative symbols in normal operational answers unless the user explicitly asks for that tone.
+
## TASK COMPLETION
- After successful control actions, respond once you have enough evidence to explain the result.
- If a tool call is blocked, treat the result as a policy boundary, not a tool-routing instruction.
@@ -3686,6 +4190,8 @@ func assistantPromptIsInventoryQuery(normalized string) bool {
" services ",
" cluster ",
" clusters ",
+ " inventory ",
+ " inventories ",
})
if !hasInventoryNoun {
return false
@@ -3698,6 +4204,11 @@ func assistantPromptIsInventoryQuery(normalized string) bool {
" totals ",
" list ",
" show ",
+ " inventory ",
+ " breakdown ",
+ " detail ",
+ " details ",
+ " detailed ",
" overview ",
" status ",
" running ",
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index c7b07331e0..c5ace61f84 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"net/http"
"net/http/httptest"
"reflect"
@@ -451,7 +452,7 @@ func TestService_ExecuteStream_EmitsProviderStartupBeforeProviderCall(t *testing
}
if data.Phase == "provider_start" {
providerStartSeen.Store(true)
- if data.Message != "Waiting for OpenRouter to start responding." {
+ if data.Message != "Sent request to OpenRouter; waiting for the first token." {
t.Fatalf("provider_start message = %q", data.Message)
}
}
@@ -506,7 +507,7 @@ func TestService_ExecuteStream_EmitsSessionBeforeInventoryPrefetch(t *testing.T)
if err := json.Unmarshal(event.Data, &data); err != nil {
t.Fatalf("unmarshal workflow state: %v", err)
}
- if data.Phase == "context" && data.Message == "Reading current Pulse inventory." {
+ if data.Phase == "context" && data.Message == "Reading current Pulse inventory with pulse_query." {
inventoryProgressSeen.Store(true)
}
}
@@ -948,6 +949,143 @@ func TestService_ExecuteStream_InventoryCountPrefetchesSummaryWithoutTools(t *te
}
}
+func TestService_ExecuteStream_PrefetchedInventoryIncludesCompleteTopologyDetail(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ var capturedReq providers.ChatRequest
+ provider := &stubServiceProvider{
+ streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ capturedReq = req
+ callback(providers.StreamEvent{
+ Type: "content",
+ Data: providers.ContentEvent{Text: "Inventory breakdown ready."},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{InputTokens: 1, OutputTokens: 1},
+ })
+ return nil
+ },
+ }
+
+ state := models.StateSnapshot{
+ Nodes: []models.Node{{
+ ID: "node1",
+ Name: "node1",
+ Instance: "pve1",
+ Status: "online",
+ }},
+ VMs: []models.VM{{
+ ID: "qemu/pve1/node1/100",
+ Name: "vm1",
+ VMID: 100,
+ Instance: "pve1",
+ Status: "running",
+ Node: "node1",
+ }},
+ }
+ for i := 1; i <= 13; i++ {
+ status := "running"
+ if i == 1 {
+ status = "stopped"
+ }
+ state.Containers = append(state.Containers, models.Container{
+ ID: fmt.Sprintf("lxc/pve1/node1/%d", 200+i),
+ Name: fmt.Sprintf("ct%d", i),
+ VMID: 200 + i,
+ Instance: "pve1",
+ Status: status,
+ Node: "node1",
+ })
+ }
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestSnapshot(state)
+ service := NewService(Config{
+ AIConfig: &config.AIConfig{ChatModel: "openai:gpt-4o", ControlLevel: config.ControlLevelControlled},
+ StateProvider: &mockStateProvider{state: state},
+ ReadState: unifiedresources.NewMonitorAdapter(registry),
+ AgentServer: &mockAgentServer{},
+ })
+ service.sessions = store
+ service.provider = provider
+ service.unifiedResourceProvider = handoffUnifiedProvider{resources: map[unifiedresources.ResourceType][]unifiedresources.Resource{
+ unifiedresources.ResourceTypeVM: {{
+ ID: "vm-100",
+ Type: unifiedresources.ResourceTypeVM,
+ Name: "vm1",
+ Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"vm1"}},
+ Proxmox: &unifiedresources.ProxmoxData{VMID: 100, NodeName: "node1"},
+ }},
+ unifiedresources.ResourceTypeSystemContainer: {{
+ ID: "ct-201",
+ Type: unifiedresources.ResourceTypeSystemContainer,
+ Name: "ct1",
+ Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"ct1"}},
+ Proxmox: &unifiedresources.ProxmoxData{VMID: 201, NodeName: "node1"},
+ }, {
+ ID: "ct-213",
+ Type: unifiedresources.ResourceTypeSystemContainer,
+ Name: "ct13",
+ Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"ct13"}},
+ Proxmox: &unifiedresources.ProxmoxData{VMID: 213, NodeName: "node1"},
+ }},
+ }}
+ service.started = true
+
+ err = service.ExecuteStream(context.Background(), ExecuteRequest{
+ SessionID: "inventory-detail-fast-path",
+ Prompt: "give me a detailed inventory breakdown by node",
+ }, func(event StreamEvent) {})
+ if err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+ if len(capturedReq.Tools) != 0 {
+ t.Fatalf("expected prefetched inventory detail turn to withhold tools, got %d", len(capturedReq.Tools))
+ }
+ if len(capturedReq.Messages) == 0 {
+ t.Fatal("expected provider request messages")
+ }
+ lastMessage := capturedReq.Messages[len(capturedReq.Messages)-1].Content
+ for _, want := range []string{
+ "per-node and workload detail",
+ "answer_label fields are UI-visible inventory labels",
+ "Do not shorten answer_label values",
+ "includes every Proxmox node, VM, system container",
+ `"proxmox":{"nodes":[`,
+ `"nodes":[`,
+ `"answer_label":"Node node1"`,
+ `"name":"node1"`,
+ `"vms":[`,
+ `"answer_label":"VM 100 vm1"`,
+ `"name":"vm1"`,
+ `"containers":[`,
+ `"answer_label":"CT 201 ct1"`,
+ `"name":"ct1"`,
+ `"answer_label":"CT 213 ct13"`,
+ `"name":"ct13"`,
+ "User message: give me a detailed inventory breakdown by node",
+ } {
+ if !strings.Contains(lastMessage, want) {
+ t.Fatalf("expected prefetched inventory context to contain %q, got %q", want, lastMessage)
+ }
+ }
+ for _, forbidden := range []string{
+ `"policy":`,
+ `"ai_safe_summary"`,
+ `"routing":`,
+ `"sensitivity":`,
+ `redacted`,
+ } {
+ if strings.Contains(lastMessage, forbidden) {
+ t.Fatalf("expected prefetched inventory context to omit policy metadata %q, got %q", forbidden, lastMessage)
+ }
+ }
+}
+
func TestResourceContextTurnIsContextOnly(t *testing.T) {
resources := []HandoffResource{{ID: "system-container:ha-node:101", Name: "homeassistant", Type: "system-container"}}
metadata := HandoffMetadata{Kind: "resource_context"}
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index 25602568f9..38ff0685ec 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -179,6 +179,28 @@ func TestToolsForAssistantTurn_InventoryCountUsesQueryOnly(t *testing.T) {
}
}
+func TestToolsForAssistantTurn_InventoryBreakdownUsesQueryOnly(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ StateProvider: fakeStateProvider{},
+ AgentServer: fakeAgentServer{},
+ ReadState: &fakeCanonicalReadState{},
+ ControlLevel: tools.ControlLevelControlled,
+ })
+
+ svc := &Service{executor: exec}
+ toolsList := svc.toolsForAssistantTurn("give me a detailed inventory breakdown by node", false, false, false)
+ set := toolNameSet(toolsList)
+
+ if !set["pulse_query"] {
+ t.Fatalf("expected inventory breakdown prompt to expose pulse_query, got %#v", set)
+ }
+ for _, blocked := range []string{"pulse_read", "pulse_control", "pulse_file_edit", "pulse_docker"} {
+ if set[blocked] {
+ t.Fatalf("expected inventory breakdown prompt not to expose %s, got %#v", blocked, set)
+ }
+ }
+}
+
func TestToolsForAssistantTurn_ActionAndDiagnosticsKeepFullManifest(t *testing.T) {
exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
StateProvider: fakeStateProvider{},
@@ -258,6 +280,9 @@ func TestBuildSystemPrompt_DoesNotClaimGenericVMControl(t *testing.T) {
if !strings.Contains(prompt, "pulse_kubernetes") {
t.Fatalf("expected system prompt to include the governed Kubernetes tool contract, got %q", prompt)
}
+ if !strings.Contains(prompt, "Do not use emoji, warning icons, or decorative symbols") {
+ t.Fatalf("expected system prompt to keep Assistant formatting operational, got %q", prompt)
+ }
}
func TestBuildSystemPrompt_CurrentResourceRequiresResourceHandoff(t *testing.T) {
diff --git a/internal/ai/modelboundary/resource_policy_sanitizer.go b/internal/ai/modelboundary/resource_policy_sanitizer.go
index f039d8ef45..2dc0955dc5 100644
--- a/internal/ai/modelboundary/resource_policy_sanitizer.go
+++ b/internal/ai/modelboundary/resource_policy_sanitizer.go
@@ -1,6 +1,8 @@
package modelboundary
import (
+ "fmt"
+ "sort"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
@@ -19,21 +21,50 @@ type allUnifiedResourceProvider interface {
GetAll() []unifiedresources.Resource
}
+type requestSanitizerOptions struct {
+ resourcePolicyAllowedText []string
+}
+
+// RequestSanitizerOption scopes model-bound sanitizer behavior for
+// Pulse-originated exports. Options must never be derived from raw user text.
+type RequestSanitizerOption func(*requestSanitizerOptions)
+
+// AllowResourcePolicyText preserves exact Pulse-generated text spans from the
+// resource-policy text redactor while still applying prompt-secret sanitation.
+func AllowResourcePolicyText(values ...string) RequestSanitizerOption {
+ return func(opts *requestSanitizerOptions) {
+ for _, value := range values {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ continue
+ }
+ opts.resourcePolicyAllowedText = append(opts.resourcePolicyAllowedText, value)
+ }
+ }
+}
+
// RequestSanitizerForModel returns a sanitizer for non-local model traffic.
// It is intentionally applied at the final provider transport boundary so
// operator-entered prompts, handoff text, tool-result turns, and provider-bound
// tool schemas cannot bypass prompt-secret or resource-policy sanitation.
-func RequestSanitizerForModel(model string, provider UnifiedResourceProvider) func(providers.ChatRequest) providers.ChatRequest {
+func RequestSanitizerForModel(model string, provider UnifiedResourceProvider, opts ...RequestSanitizerOption) func(providers.ChatRequest) providers.ChatRequest {
if !ModelUsesExternalProvider(model) {
return nil
}
+ options := requestSanitizerOptions{}
+ for _, opt := range opts {
+ if opt != nil {
+ opt(&options)
+ }
+ }
resources := resourcePolicySanitizerResources(provider)
return func(req providers.ChatRequest) providers.ChatRequest {
req = sanitizeProviderRequestForPromptSecrets(req)
if len(resources) == 0 {
return req
}
- return sanitizeProviderRequestForResources(req, resources)
+ allowedText := sanitizeResourcePolicyAllowedText(options.resourcePolicyAllowedText)
+ return sanitizeProviderRequestForResources(req, resources, allowedText)
}
}
@@ -99,94 +130,145 @@ func resourcesWithPolicy(resources []unifiedresources.Resource) []unifiedresourc
return filtered
}
-func sanitizeProviderRequestForResources(req providers.ChatRequest, resources []unifiedresources.Resource) providers.ChatRequest {
+func sanitizeProviderRequestForResources(req providers.ChatRequest, resources []unifiedresources.Resource, allowedText []string) providers.ChatRequest {
if len(resources) == 0 {
return req
}
- req.System = sanitizeResourcePolicyText(req.System, resources)
+ req.System = sanitizeResourcePolicyText(req.System, resources, allowedText)
if len(req.Messages) > 0 {
req.Messages = append([]providers.Message(nil), req.Messages...)
for i := range req.Messages {
- req.Messages[i] = sanitizeProviderMessageForResources(req.Messages[i], resources)
+ req.Messages[i] = sanitizeProviderMessageForResources(req.Messages[i], resources, allowedText)
}
}
if len(req.Tools) > 0 {
req.Tools = append([]providers.Tool(nil), req.Tools...)
for i := range req.Tools {
- req.Tools[i] = sanitizeProviderToolForResources(req.Tools[i], resources)
+ req.Tools[i] = sanitizeProviderToolForResources(req.Tools[i], resources, allowedText)
}
}
return req
}
-func sanitizeProviderMessageForResources(msg providers.Message, resources []unifiedresources.Resource) providers.Message {
- msg.Content = sanitizeResourcePolicyText(msg.Content, resources)
- msg.ReasoningContent = sanitizeResourcePolicyText(msg.ReasoningContent, resources)
+func sanitizeProviderMessageForResources(msg providers.Message, resources []unifiedresources.Resource, allowedText []string) providers.Message {
+ msg.Content = sanitizeResourcePolicyText(msg.Content, resources, allowedText)
+ msg.ReasoningContent = sanitizeResourcePolicyText(msg.ReasoningContent, resources, allowedText)
if msg.ToolResult != nil {
toolResult := *msg.ToolResult
- toolResult.Content = sanitizeResourcePolicyText(toolResult.Content, resources)
+ toolResult.Content = sanitizeResourcePolicyText(toolResult.Content, resources, allowedText)
msg.ToolResult = &toolResult
}
if len(msg.ToolCalls) > 0 {
msg.ToolCalls = append([]providers.ToolCall(nil), msg.ToolCalls...)
for i := range msg.ToolCalls {
- msg.ToolCalls[i].Input = sanitizeResourcePolicyMap(msg.ToolCalls[i].Input, resources)
+ msg.ToolCalls[i].Input = sanitizeResourcePolicyMap(msg.ToolCalls[i].Input, resources, allowedText)
}
}
return msg
}
-func sanitizeProviderToolForResources(tool providers.Tool, resources []unifiedresources.Resource) providers.Tool {
- tool.Description = sanitizeResourcePolicyText(tool.Description, resources)
- tool.InputSchema = sanitizeResourcePolicyMap(tool.InputSchema, resources)
+func sanitizeProviderToolForResources(tool providers.Tool, resources []unifiedresources.Resource, allowedText []string) providers.Tool {
+ tool.Description = sanitizeResourcePolicyText(tool.Description, resources, allowedText)
+ tool.InputSchema = sanitizeResourcePolicyMap(tool.InputSchema, resources, allowedText)
return tool
}
-func sanitizeResourcePolicyText(value string, resources []unifiedresources.Resource) string {
+func sanitizeResourcePolicyText(value string, resources []unifiedresources.Resource, allowedText []string) string {
if strings.TrimSpace(value) == "" || len(resources) == 0 {
return value
}
- redacted := value
+ protected, restore := protectResourcePolicyAllowedText(value, allowedText)
+ redacted := protected
for _, resource := range resources {
redacted = unifiedresources.ResourcePolicyRedactedText(redacted, resource)
}
+ for placeholder, original := range restore {
+ redacted = strings.ReplaceAll(redacted, placeholder, original)
+ }
return redacted
}
-func sanitizeResourcePolicyMap(values map[string]interface{}, resources []unifiedresources.Resource) map[string]interface{} {
+func sanitizeResourcePolicyAllowedText(values []string) []string {
+ if len(values) == 0 {
+ return nil
+ }
+ out := make([]string, 0, len(values))
+ seen := make(map[string]struct{}, len(values))
+ for _, value := range values {
+ value = strings.TrimSpace(sanitizePromptSecretText(value))
+ if value == "" {
+ continue
+ }
+ if _, ok := seen[value]; ok {
+ continue
+ }
+ seen[value] = struct{}{}
+ out = append(out, value)
+ }
+ sortStringsByLengthDesc(out)
+ return out
+}
+
+func protectResourcePolicyAllowedText(value string, allowedText []string) (string, map[string]string) {
+ if strings.TrimSpace(value) == "" || len(allowedText) == 0 {
+ return value, nil
+ }
+ protected := value
+ restore := make(map[string]string)
+ for idx, allowed := range allowedText {
+ if allowed == "" || !strings.Contains(protected, allowed) {
+ continue
+ }
+ placeholder := fmt.Sprintf("\x00pulse-allowed-resource-export-%d\x00", idx)
+ protected = strings.ReplaceAll(protected, allowed, placeholder)
+ restore[placeholder] = allowed
+ }
+ return protected, restore
+}
+
+func sortStringsByLengthDesc(values []string) {
+ sort.Slice(values, func(i, j int) bool {
+ if len(values[i]) == len(values[j]) {
+ return values[i] < values[j]
+ }
+ return len(values[i]) > len(values[j])
+ })
+}
+
+func sanitizeResourcePolicyMap(values map[string]interface{}, resources []unifiedresources.Resource, allowedText []string) map[string]interface{} {
if len(values) == 0 {
return values
}
sanitized := make(map[string]interface{}, len(values))
for key, value := range values {
- sanitized[key] = sanitizeResourcePolicyValue(value, resources)
+ sanitized[key] = sanitizeResourcePolicyValue(value, resources, allowedText)
}
return sanitized
}
-func sanitizeResourcePolicyValue(value interface{}, resources []unifiedresources.Resource) interface{} {
+func sanitizeResourcePolicyValue(value interface{}, resources []unifiedresources.Resource, allowedText []string) interface{} {
switch typed := value.(type) {
case string:
- return sanitizeResourcePolicyText(typed, resources)
+ return sanitizeResourcePolicyText(typed, resources, allowedText)
case []string:
out := make([]string, len(typed))
for i := range typed {
- out[i] = sanitizeResourcePolicyText(typed[i], resources)
+ out[i] = sanitizeResourcePolicyText(typed[i], resources, allowedText)
}
return out
case []interface{}:
out := make([]interface{}, len(typed))
for i := range typed {
- out[i] = sanitizeResourcePolicyValue(typed[i], resources)
+ out[i] = sanitizeResourcePolicyValue(typed[i], resources, allowedText)
}
return out
case map[string]interface{}:
- return sanitizeResourcePolicyMap(typed, resources)
+ return sanitizeResourcePolicyMap(typed, resources, allowedText)
case map[string]string:
out := make(map[string]string, len(typed))
for key, nested := range typed {
- out[key] = sanitizeResourcePolicyText(nested, resources)
+ out[key] = sanitizeResourcePolicyText(nested, resources, allowedText)
}
return out
default:
diff --git a/internal/ai/modelboundary/resource_policy_sanitizer_test.go b/internal/ai/modelboundary/resource_policy_sanitizer_test.go
index 9391b278eb..b06e6cbd2d 100644
--- a/internal/ai/modelboundary/resource_policy_sanitizer_test.go
+++ b/internal/ai/modelboundary/resource_policy_sanitizer_test.go
@@ -109,6 +109,45 @@ func TestRequestSanitizerForModelRedactsExternalModelRequest(t *testing.T) {
}
}
+func TestRequestSanitizerForModelAllowsPulseGeneratedInventoryExportOnly(t *testing.T) {
+ resource := unifiedresources.Resource{
+ ID: "vm-100",
+ Type: unifiedresources.ResourceTypeVM,
+ Name: "vm1",
+ Identity: unifiedresources.ResourceIdentity{
+ Hostnames: []string{"vm1"},
+ },
+ Proxmox: &unifiedresources.ProxmoxData{VMID: 100, NodeName: "node1"},
+ }
+ allowedInventoryContext := `Pulse-generated inventory context:
+{"answer_label":"VM 100 vm1","name":"vm1","status":"running"}`
+ sanitizer := RequestSanitizerForModel(
+ "openai:gpt-4o",
+ policySanitizerProvider{resources: []unifiedresources.Resource{resource}},
+ AllowResourcePolicyText(allowedInventoryContext),
+ )
+ if sanitizer == nil {
+ t.Fatal("expected external model sanitizer")
+ }
+
+ got := sanitizer(providers.ChatRequest{
+ Messages: []providers.Message{{
+ Role: "user",
+ Content: allowedInventoryContext + "\n\n---\nUser message: vm1 should still be governed in free text",
+ }},
+ })
+ content := got.Messages[0].Content
+ if !strings.Contains(content, `"answer_label":"VM 100 vm1"`) {
+ t.Fatalf("Pulse-generated inventory label was redacted: %q", content)
+ }
+ if strings.Contains(content, "User message: vm1 should still be governed") {
+ t.Fatalf("user-authored resource identity bypassed sanitizer: %q", content)
+ }
+ if !strings.Contains(content, "User message: redacted by policy should still be governed") {
+ t.Fatalf("user-authored resource identity was not redacted: %q", content)
+ }
+}
+
func TestRequestSanitizerForModelSkipsLocalModel(t *testing.T) {
resource := unifiedresources.Resource{
ID: "agent/pve-secret",
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index 059ceb74bf..3750b91515 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -26,8 +26,10 @@ const (
openrouterAppTitle = "Pulse"
// OpenRouter preflights affordability against the requested maximum
// completion budget. Leaving it unset can make small chat turns reserve a
- // model-scale default and fail against per-key total limits.
- openrouterDefaultMaxCompletionTokens = 1024
+ // model-scale default and fail against per-key total limits. Keep this high
+ // enough for normal detailed Assistant answers; 1024 cuts off ordinary
+ // inventory breakdowns mid-sentence.
+ openrouterDefaultMaxCompletionTokens = 4096
)
// OpenAIClient implements the Provider interface for OpenAI's API