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.

Route Assistant handoffs through model context

rcourtman812c86692dbb
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 6ad514e343..ba3165443d 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1104,6 +1104,12 @@ Patrol finding chat handoffs follow the same ownership split: when
resource, or action context, the backend-enforced `autonomous_mode:false`
clamp is Assistant action-governance, not agent readiness, fleet command
reachability, or enrollment health.
+Scoped Assistant handoffs from alert or incident surfaces may also send
+bounded `handoff_context` and `handoff_resources` through `/api/ai/chat`
+without a `finding_id`; lifecycle-adjacent surfaces may treat those references
+as AI/runtime explanation context only, and must not reinterpret them as agent
+readiness, install status, command reachability, enrollment health, or fleet
+execution authority.
That same shared `internal/api/` dependency also now assumes SSO test and
metadata-preview routes fail closed on validated outbound URL handling.
Lifecycle-adjacent setup and hosted bootstrap surfaces may depend on those
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 540e8943f7..babfce16e1 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -27,21 +27,22 @@ runtime cost control, and shared AI transport surfaces.
5. `internal/api/ai_hosted_runtime.go`
6. `internal/api/ai_intelligence_handlers.go`
7. `frontend-modern/src/api/ai.ts`
-8. `frontend-modern/src/api/patrol.ts`
-9. `frontend-modern/src/components/AI/AICostDashboard.tsx`
-10. `frontend-modern/src/components/AI/Chat/`
-11. `frontend-modern/src/utils/aiChatPresentation.ts`
-12. `frontend-modern/src/utils/aiControlLevelPresentation.ts`
-13. `frontend-modern/src/utils/aiCostPresentation.ts`
-14. `frontend-modern/src/utils/aiExplorePresentation.ts`
-15. `frontend-modern/src/utils/aiProviderHealthPresentation.ts`
-16. `frontend-modern/src/utils/aiProviderPresentation.ts`
-17. `frontend-modern/src/utils/aiSessionDiffPresentation.ts`
-18. `frontend-modern/src/utils/textPresentation.ts`
-19. `frontend-modern/src/stores/aiRuntimeState.ts`
-20. `frontend-modern/src/stores/aiChat.ts`
-21. `docs/AI.md`
-22. `pkg/aicontracts/investigation.go`
+8. `frontend-modern/src/api/aiChat.ts`
+9. `frontend-modern/src/api/patrol.ts`
+10. `frontend-modern/src/components/AI/AICostDashboard.tsx`
+11. `frontend-modern/src/components/AI/Chat/`
+12. `frontend-modern/src/utils/aiChatPresentation.ts`
+13. `frontend-modern/src/utils/aiControlLevelPresentation.ts`
+14. `frontend-modern/src/utils/aiCostPresentation.ts`
+15. `frontend-modern/src/utils/aiExplorePresentation.ts`
+16. `frontend-modern/src/utils/aiProviderHealthPresentation.ts`
+17. `frontend-modern/src/utils/aiProviderPresentation.ts`
+18. `frontend-modern/src/utils/aiSessionDiffPresentation.ts`
+19. `frontend-modern/src/utils/textPresentation.ts`
+20. `frontend-modern/src/stores/aiRuntimeState.ts`
+21. `frontend-modern/src/stores/aiChat.ts`
+22. `docs/AI.md`
+23. `pkg/aicontracts/investigation.go`
## Shared Boundaries
@@ -56,7 +57,7 @@ runtime cost control, and shared AI transport surfaces.
1. Add or change chat runtime, Patrol orchestration, findings generation, or remediation behavior through `internal/ai/`
2. Add or change canonical AI provider config, provider-scoped model selection, or runtime auth/base-URL defaults through `internal/config/ai.go`
-3. Add or change Pulse Assistant request flow through `internal/api/ai_handler.go` and `frontend-modern/src/api/ai.ts`
+3. Add or change Pulse Assistant request flow through `internal/api/ai_handler.go`, `frontend-modern/src/api/ai.ts`, and `frontend-modern/src/api/aiChat.ts`
4. Add or change Patrol, alert-analysis, or remediation transport through `internal/api/ai_handlers.go`, `internal/api/ai_intelligence_handlers.go`, and `frontend-modern/src/api/patrol.ts`
5. Add or change AI usage/cost dashboard presentation through `frontend-modern/src/components/AI/AICostDashboard.tsx` and `frontend-modern/src/utils/aiCostPresentation.ts`
6. Add or change AI provider, control-level, chat/session, or explore-state presentation through `frontend-modern/src/components/AI/Chat/`, `frontend-modern/src/utils/aiProviderPresentation.ts`, `frontend-modern/src/utils/aiProviderHealthPresentation.ts`, `frontend-modern/src/utils/aiControlLevelPresentation.ts`, `frontend-modern/src/utils/aiChatPresentation.ts`, `frontend-modern/src/utils/aiSessionDiffPresentation.ts`, and `frontend-modern/src/utils/aiExplorePresentation.ts`
@@ -1078,6 +1079,14 @@ only governed prompt/context data, but the submitted chat request must set
`autonomous_mode:false`, preserve the operator's persistent Assistant
control-level setting, and disclose the temporary approval-required mode in
the drawer instead of showing the generic Autonomous warning.
+Scoped Assistant handoffs that originate in owned product surfaces may also
+send bounded `handoff_context` text plus structured `handoff_resources` through
+`frontend-modern/src/api/aiChat.ts` and `/api/ai/chat`. That context is
+model-only session metadata, not saved user-authored message text, and the
+backend must clamp the exchange to approval-required mode whenever such scoped
+handoff context or resources are present. Patrol finding IDs remain stricter:
+when `finding_id` resolves, backend-refreshed durable Patrol context replaces
+browser-supplied handoff text.
Direct alert-investigation runtime handoffs follow the same rule even when
they bypass the chat drawer. `/api/ai/investigate-alert` must set
`ai.ExecuteRequest.AutonomousMode` to false plus
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index ca272f9c1a..1be49b7c5e 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -110,14 +110,18 @@ operator-facing alert routing behavior for live runtime alerts.
`frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx` and
`frontend-modern/src/components/Alerts/alertAssistantHandoffModel.ts`;
these handoffs must preserve alert context, force request-scoped approval
- mode, and render a visible Alerts-owned briefing in the Assistant drawer
- without transferring raw command payloads.
+ mode, send bounded model-only handoff context plus structured resource
+ references through the shared Assistant chat transport, and render a visible
+ Alerts-owned briefing in the Assistant drawer without transferring raw
+ command payloads.
8. Add or change Pulse Assistant incident timeline handoffs through
`frontend-modern/src/components/Alerts/IncidentAssistantHandoffButton.tsx`
and `frontend-modern/src/components/Alerts/incidentAssistantHandoffModel.ts`;
these handoffs must preserve sanitized incident facts and timeline event
- summaries, force request-scoped approval mode, and keep raw command/output
- details in the incident or approval surface rather than the chat handoff.
+ summaries, force request-scoped approval mode, send the same sanitized facts
+ as model-only handoff context plus structured resource references through
+ the shared Assistant chat transport, and keep raw command/output details in
+ the incident or approval surface rather than the chat handoff.
## Forbidden Paths
@@ -707,8 +711,9 @@ and `frontend-modern/src/features/alerts/tabs/HistoryTab.tsx`. Future incident
timeline control flow should land in that feature hook instead of being forked
back into either alert surface. Alert incident timeline handoffs into Pulse
Assistant are now owned by the Alerts incident handoff model and carry only
-sanitized incident facts plus event summaries; raw command and output details
-stay in the incident timeline or approval surface.
+sanitized incident facts plus event summaries into both the visible drawer
+briefing and the backend model-only handoff context; raw command and output
+details stay in the incident timeline or approval surface.
Resource incident panel cards, summary rows, and toggle-button presentation
now also route through `frontend-modern/src/utils/alertIncidentPresentation.ts`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e7f63860ec..73a754611c 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -100,7 +100,8 @@ product API routes free of maintainer commercial analytics.
66. `pkg/aicontracts/investigation.go`
67. `internal/api/ai_intelligence_handlers.go`
68. `frontend-modern/src/api/ai.ts`
-69. `frontend-modern/src/api/patrol.ts`
+69. `frontend-modern/src/api/aiChat.ts`
+70. `frontend-modern/src/api/patrol.ts`
## Shared Boundaries
@@ -1835,6 +1836,15 @@ overrides. Dashboard Pulse Brief and other scoped handoffs may include
execution for that exchange, but the transport must treat the field as a
request override only and must not mutate the user's persistent AI control
setting.
+The same chat payload boundary now carries scoped product handoff context:
+`handoff_context` is bounded model-only text and `handoff_resources` are
+structured resource references used to seed canonical resource-policy, state,
+relationship, and timeline hydration. Frontend handoff builders may send these
+fields for owned alert or incident context, but the backend must not persist
+them as user-authored message text and must treat them as explanation/review
+context only. When a Patrol `finding_id` resolves, backend-refreshed durable
+finding context replaces any browser-supplied handoff text so the model cannot
+continue from stale or spoofed Patrol context.
Patrol finding handoffs are stricter than ordinary chat requests: when
`finding_id` resolves to model-only Patrol briefing, resource, or action
context, `internal/api/ai_handler.go` must clamp the request-local autonomous
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index dc08e1250f..ec83c1c3c7 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -813,6 +813,10 @@ frontend primitive boundary.
context-briefing band from `frontend-modern/src/stores/aiChat.ts`, but
feature-owned helpers must provide the source labels, attention reason,
evidence summaries, operator-decision copy, action copy, and safety note.
+ When those feature-owned helpers attach backend model-only context, the
+ drawer store may carry only bounded handoff text and structured resource
+ references for the shared chat transport; approval, lifecycle, and command
+ authority remain with the owning runtime surfaces.
Patrol finding handoffs should still provide that briefing from current
finding facts when a durable Patrol investigation record is not attached
yet, rather than opening the shared drawer as empty generic chat.
@@ -1052,6 +1056,9 @@ primitives must not fork that string or revive removed nested route labels.
The shared Assistant drawer owns source-named approval banners for governed
handoffs. Patrol handoffs render as Patrol, and alert plus alert incident
timeline handoffs render as alert investigations rather than dashboard briefs.
+Those same drawer handoffs may carry model-only chat context and resource
+references to the backend, but the drawer remains a presentation and transport
+owner rather than the source of approval or execution truth.
`SettingsTab` no longer includes `infrastructure-connections` or
`infrastructure-install`. The single `infrastructure-systems` entry in
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index be0deefa30..110b97ecd9 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -403,6 +403,13 @@ bypass the API fail-closed execution gate.
`finding_id` handoffs with model-only Patrol briefing, resource, or action
context is Assistant action-governance, not a storage/recovery approval,
recovery freshness, or restore-command signal.
+ Alert and incident Assistant handoffs that send bounded model-only
+ `handoff_context` and `handoff_resources` through `/api/ai/chat` without a
+ `finding_id` stay on that same adjacent AI/runtime boundary. Storage and
+ recovery surfaces may consume the explanation context, but must not treat
+ the handoff resource reference as backup freshness, restore eligibility,
+ recovery execution authority, storage health truth, or a storage-local
+ approval shortcut.
That same adjacent boundary also keeps the retired Patrol quickstart
contract out of storage/recovery ownership: shared AI handlers no longer
expose active quickstart credit, token, or hosted-model provider state, and
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index c6b697aacd..c071c0367d 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -143,4 +143,57 @@ describe('AIChatAPI', () => {
}),
);
});
+
+ it('includes model-only handoff context and resource references when supplied', async () => {
+ const read = vi.fn().mockResolvedValueOnce({ done: true, value: undefined });
+ const releaseLock = vi.fn();
+
+ apiFetchMock.mockResolvedValueOnce({
+ ok: true,
+ body: {
+ getReader: () => ({ read, releaseLock }),
+ },
+ } as unknown as Response);
+
+ await AIChatAPI.chat(
+ 'discuss incident',
+ 'session-3',
+ undefined,
+ vi.fn(),
+ undefined,
+ undefined,
+ undefined,
+ false,
+ '[Alert Incident Context]\nIncident ID: incident-1',
+ [
+ {
+ id: 'storage-1',
+ name: 'tank',
+ type: 'storage',
+ node: 'nas-1',
+ },
+ ],
+ );
+
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/ai/chat',
+ expect.objectContaining({
+ body: JSON.stringify({
+ prompt: 'discuss incident',
+ session_id: 'session-3',
+ model: undefined,
+ autonomous_mode: false,
+ handoff_context: '[Alert Incident Context]\nIncident ID: incident-1',
+ handoff_resources: [
+ {
+ id: 'storage-1',
+ name: 'tank',
+ type: 'storage',
+ node: 'nas-1',
+ },
+ ],
+ }),
+ }),
+ );
+ });
});
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index f2d03dcc72..c1a53ae2c1 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -23,6 +23,13 @@ export interface ChatMention {
node?: string;
}
+export interface ChatHandoffResource {
+ id: string;
+ name?: string;
+ type?: string;
+ node?: string;
+}
+
export interface ChatMessage {
id: string;
role: 'user' | 'assistant';
@@ -200,6 +207,8 @@ export class AIChatAPI {
mentions?: ChatMention[],
findingId?: string,
autonomousMode?: boolean,
+ handoffContext?: string,
+ handoffResources?: ChatHandoffResource[],
): Promise<void> {
logger.debug('[AI Chat] Starting chat stream', { prompt: prompt.substring(0, 50) });
@@ -217,6 +226,12 @@ export class AIChatAPI {
if (typeof autonomousMode === 'boolean') {
body.autonomous_mode = autonomousMode;
}
+ if (handoffContext && handoffContext.trim()) {
+ body.handoff_context = handoffContext;
+ }
+ if (handoffResources && handoffResources.length > 0) {
+ body.handoff_resources = handoffResources;
+ }
const response = await apiFetch(`${this.baseUrl}/chat`, {
method: 'POST',
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 bfb09c4ca1..e5ec4a2310 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -80,11 +80,20 @@ const {
autonomousMode: undefined,
context: undefined,
briefing: undefined,
+ handoffContext: undefined,
+ handoffResources: undefined,
} as {
initialPrompt?: string;
findingId?: string;
autonomousMode?: boolean;
context?: Record<string, unknown>;
+ handoffContext?: string;
+ handoffResources?: Array<{
+ id: string;
+ name?: string;
+ type?: string;
+ node?: string;
+ }>;
briefing?: {
sourceLabel: string;
title: string;
@@ -1089,6 +1098,59 @@ describe('AIChat', () => {
screen.queryByText(/Approval required for this dashboard brief/),
).not.toBeInTheDocument();
});
+
+ it('passes model-only handoff context and resources on submit', async () => {
+ mockAIAPI.getSettings.mockResolvedValue({
+ model: 'gpt-4',
+ chat_model: '',
+ control_level: 'autonomous',
+ autonomous_mode: true,
+ discovery_enabled: true,
+ });
+ mockAiChatStore.context = {
+ initialPrompt: undefined,
+ autonomousMode: false,
+ handoffContext:
+ '[Alert Incident Context]\nIncident ID: incident-1\nTimeline Event 1: Command event recorded',
+ handoffResources: [
+ {
+ id: 'storage-1',
+ name: 'tank',
+ type: 'storage',
+ node: 'nas-1',
+ },
+ ],
+ briefing: {
+ sourceLabel: 'Pulse Alerts',
+ title: 'Incident timeline attached',
+ },
+ };
+
+ renderChat();
+
+ const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
+ fireEvent.input(textarea, { target: { value: 'what happened here?' } });
+ fireEvent.keyDown(textarea, { key: 'Enter' });
+
+ expect(mockChat.sendMessage).toHaveBeenCalledWith(
+ 'what happened here?',
+ undefined,
+ undefined,
+ {
+ autonomousMode: false,
+ handoffContext:
+ '[Alert Incident Context]\nIncident ID: incident-1\nTimeline Event 1: Command event recorded',
+ handoffResources: [
+ {
+ id: 'storage-1',
+ name: 'tank',
+ type: 'storage',
+ node: 'nas-1',
+ },
+ ],
+ },
+ );
+ });
});
// ── Discovery hint ───────────────────────────────────────────────────
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 2c015c15a4..ae1f4f2992 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -230,6 +230,37 @@ describe('useChat', () => {
dispose();
});
+ it('passes model-only handoff context and resource references to the API', async () => {
+ mockChat.mockResolvedValue(undefined);
+
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 'sess' }));
+ await chat.sendMessage('explain this incident', undefined, undefined, {
+ autonomousMode: false,
+ handoffContext: '[Alert Incident Context]\nIncident ID: incident-1',
+ handoffResources: [
+ {
+ id: 'storage-1',
+ name: 'tank',
+ type: 'storage',
+ node: 'nas-1',
+ },
+ ],
+ });
+
+ const chatCall = mockChat.mock.calls[0];
+ expect(chatCall[7]).toBe(false);
+ expect(chatCall[8]).toBe('[Alert Incident Context]\nIncident ID: incident-1');
+ expect(chatCall[9]).toEqual([
+ {
+ id: 'storage-1',
+ name: 'tank',
+ type: 'storage',
+ node: 'nas-1',
+ },
+ ]);
+ dispose();
+ });
+
it('aborts current stream when sending mid-stream', async () => {
// First call: capture signal so we can verify it was aborted
let capturedSignal: AbortSignal | undefined;
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index 089cc0f3b9..f56a2fcec8 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -1,5 +1,10 @@
import { createSignal, onCleanup } from 'solid-js';
-import { AIChatAPI, type ChatMention, type StreamEvent } from '@/api/aiChat';
+import {
+ AIChatAPI,
+ type ChatHandoffResource,
+ type ChatMention,
+ type StreamEvent,
+} from '@/api/aiChat';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
import { normalizeChatToolName } from '@/utils/chatIdentifiers';
@@ -22,6 +27,8 @@ export interface UseChatOptions {
export interface SendMessageOptions {
autonomousMode?: boolean;
+ handoffContext?: string;
+ handoffResources?: ChatHandoffResource[];
}
export function useChat(options: UseChatOptions = {}) {
@@ -560,6 +567,8 @@ export function useChat(options: UseChatOptions = {}) {
mentions,
findingId,
sendOptions?.autonomousMode,
+ sendOptions?.handoffContext,
+ sendOptions?.handoffResources,
);
await notifyConversationChanged();
return true;
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index d7224141a3..40820b95fb 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -57,7 +57,7 @@ import {
getPreferredResourceHostname,
} from '@/utils/resourceIdentity';
import { useBreakpoint } from '@/hooks/useBreakpoint';
-import { useChat } from './hooks/useChat';
+import { useChat, type SendMessageOptions } from './hooks/useChat';
import { ChatMessages } from './ChatMessages';
import { ModelSelector } from './ModelSelector';
import { MentionAutocomplete, type MentionResource } from './MentionAutocomplete';
@@ -665,9 +665,21 @@ export const AIChat: Component<AIChatProps> = (props) => {
// Pass findingId from context on the first message, clear after success
const ctx = aiChatStore.context;
const findingId = ctx.findingId;
- const sendOptions =
- typeof ctx.autonomousMode === 'boolean' ? { autonomousMode: ctx.autonomousMode } : undefined;
- const sendPromise = sendOptions
+ const sendOptions: SendMessageOptions = {};
+ if (typeof ctx.autonomousMode === 'boolean') {
+ sendOptions.autonomousMode = ctx.autonomousMode;
+ }
+ if (ctx.handoffContext && ctx.handoffContext.trim()) {
+ sendOptions.handoffContext = ctx.handoffContext;
+ }
+ if (ctx.handoffResources && ctx.handoffResources.length > 0) {
+ sendOptions.handoffResources = ctx.handoffResources;
+ }
+ const hasSendOptions =
+ typeof sendOptions.autonomousMode === 'boolean' ||
+ Boolean(sendOptions.handoffContext) ||
+ Boolean(sendOptions.handoffResources?.length);
+ const sendPromise = hasSendOptions
? chat.sendMessage(prompt, mentionsForAPI, findingId, sendOptions)
: chat.sendMessage(prompt, mentionsForAPI, findingId);
sendPromise.then((ok) => {
diff --git a/frontend-modern/src/components/Alerts/__tests__/alertAssistantHandoffModel.test.ts b/frontend-modern/src/components/Alerts/__tests__/alertAssistantHandoffModel.test.ts
index 8474c3ca5a..1157e982e5 100644
--- a/frontend-modern/src/components/Alerts/__tests__/alertAssistantHandoffModel.test.ts
+++ b/frontend-modern/src/components/Alerts/__tests__/alertAssistantHandoffModel.test.ts
@@ -37,6 +37,14 @@ describe('alertAssistantHandoffModel', () => {
targetType: 'vm',
targetId: 'vm-101',
autonomousMode: false,
+ handoffResources: [
+ {
+ id: 'vm-101',
+ name: 'app-vm',
+ type: 'vm',
+ node: 'pve1',
+ },
+ ],
briefing: {
sourceLabel: 'Pulse Alerts',
title: 'Alert investigation attached',
@@ -60,6 +68,10 @@ describe('alertAssistantHandoffModel', () => {
vmid: 101,
},
});
+ expect(handoff.context.handoffContext).toContain('[Alert Investigation Context]');
+ expect(handoff.context.handoffContext).toContain('Source: Pulse Alerts active alert');
+ expect(handoff.context.handoffContext).toContain('Alert Identifier: alert-1');
+ expect(handoff.context.handoffContext).toContain('Operator Boundary:');
expect(JSON.stringify(handoff)).not.toContain('systemctl');
});
diff --git a/frontend-modern/src/components/Alerts/__tests__/incidentAssistantHandoffModel.test.ts b/frontend-modern/src/components/Alerts/__tests__/incidentAssistantHandoffModel.test.ts
index c2f921bf0b..a850461354 100644
--- a/frontend-modern/src/components/Alerts/__tests__/incidentAssistantHandoffModel.test.ts
+++ b/frontend-modern/src/components/Alerts/__tests__/incidentAssistantHandoffModel.test.ts
@@ -53,6 +53,14 @@ describe('incidentAssistantHandoffModel', () => {
targetType: 'app-container',
targetId: 'docker:app-1',
autonomousMode: false,
+ handoffResources: [
+ {
+ id: 'docker:app-1',
+ name: 'checkout-api',
+ type: 'app-container',
+ node: 'edge-1',
+ },
+ ],
briefing: {
sourceLabel: 'Pulse Alerts',
title: 'Incident timeline attached',
@@ -95,6 +103,11 @@ describe('incidentAssistantHandoffModel', () => {
],
},
});
+ expect(handoff.context.handoffContext).toContain('[Alert Incident Context]');
+ expect(handoff.context.handoffContext).toContain('Source: Pulse Alerts incident timeline');
+ expect(handoff.context.handoffContext).toContain('Timeline Event 1:');
+ expect(handoff.context.handoffContext).toContain('Command | Command event recorded');
+ expect(handoff.context.handoffContext).toContain('Timeline Boundary:');
expect(JSON.stringify(handoff)).not.toContain('systemctl');
expect(JSON.stringify(handoff)).not.toContain('secret-value');
});
diff --git a/frontend-modern/src/components/Alerts/alertAssistantHandoffModel.ts b/frontend-modern/src/components/Alerts/alertAssistantHandoffModel.ts
index 4f76f3c345..a51a69ac1a 100644
--- a/frontend-modern/src/components/Alerts/alertAssistantHandoffModel.ts
+++ b/frontend-modern/src/components/Alerts/alertAssistantHandoffModel.ts
@@ -37,6 +37,15 @@ export function buildAlertAssistantHandoff({
: undefined,
resourceId: alert.resourceId,
});
+ const handoffContext = buildAlertAssistantModelContext({
+ alert,
+ alertIdentifier,
+ currentValue,
+ thresholdValue,
+ durationText,
+ nodeLabel,
+ levelLabel,
+ });
const prompt = `Investigate this ${alert.level.toUpperCase()} alert:
@@ -59,6 +68,15 @@ Please:
targetType,
targetId: alert.resourceId,
autonomousMode: false,
+ handoffContext,
+ handoffResources: [
+ {
+ id: alert.resourceId,
+ name: alert.resourceName,
+ type: targetType,
+ node: alert.node,
+ },
+ ],
briefing: {
sourceLabel: 'Pulse Alerts',
title: 'Alert investigation attached',
@@ -85,6 +103,49 @@ Please:
};
}
+function buildAlertAssistantModelContext({
+ alert,
+ alertIdentifier,
+ currentValue,
+ thresholdValue,
+ durationText,
+ nodeLabel,
+ levelLabel,
+}: {
+ alert: Alert;
+ alertIdentifier: string;
+ currentValue: string;
+ thresholdValue: string;
+ durationText: string;
+ nodeLabel: string;
+ levelLabel: string;
+}): string {
+ return [
+ '[Alert Investigation Context]',
+ 'Source: Pulse Alerts active alert',
+ formatContextLine('Alert Identifier', alertIdentifier),
+ formatContextLine('Alert Type', alert.type),
+ formatContextLine('Alert Level', levelLabel),
+ formatContextLine('Alert Status', 'active'),
+ formatContextLine('Resource', alert.resourceName),
+ formatContextLine('Resource ID', alert.resourceId),
+ formatContextLine('Current Value', currentValue),
+ formatContextLine('Threshold', thresholdValue),
+ formatContextLine('Duration', durationText),
+ formatContextLine('Node', nodeLabel),
+ formatContextLine('Message', alert.message),
+ 'Operator Boundary: This alert handoff is model-only context for explanation and review. Diagnostics, remediation, and any command execution require explicit operator approval.',
+ ]
+ .filter((line): line is string => Boolean(line))
+ .join('\n');
+}
+
+function formatContextLine(label: string, value?: string | number | null): string | undefined {
+ if (value === undefined || value === null) return undefined;
+ const text = String(value).trim();
+ return text ? `${label}: ${text}` : undefined;
+}
+
function formatAlertDuration(startTime: string, now: Date): string {
const startedAt = new Date(startTime).getTime();
const nowMs = now.getTime();
diff --git a/frontend-modern/src/components/Alerts/incidentAssistantHandoffModel.ts b/frontend-modern/src/components/Alerts/incidentAssistantHandoffModel.ts
index 351dd307a1..401740e1ec 100644
--- a/frontend-modern/src/components/Alerts/incidentAssistantHandoffModel.ts
+++ b/frontend-modern/src/components/Alerts/incidentAssistantHandoffModel.ts
@@ -45,6 +45,15 @@ export function buildAlertIncidentAssistantHandoff({
const events = sanitizeIncidentEvents(incident.events ?? []);
const eventCount = events.length;
const eventCountLabel = `${eventCount} timeline event${eventCount === 1 ? '' : 's'}`;
+ const handoffContext = buildIncidentAssistantModelContext({
+ incident,
+ events,
+ resourceLabel,
+ levelLabel,
+ statusLabel,
+ durationText,
+ eventCountLabel,
+ });
const prompt = [
`Discuss this ${levelLabel} alert incident from Pulse Alerts.`,
@@ -73,6 +82,15 @@ export function buildAlertIncidentAssistantHandoff({
targetType,
targetId: incident.resourceId,
autonomousMode: false,
+ handoffContext,
+ handoffResources: [
+ {
+ id: incident.resourceId,
+ name: resourceLabel,
+ type: targetType,
+ node: incident.node,
+ },
+ ],
briefing: {
sourceLabel: 'Pulse Alerts',
title: 'Incident timeline attached',
@@ -110,6 +128,58 @@ export function buildAlertIncidentAssistantHandoff({
};
}
+function buildIncidentAssistantModelContext({
+ incident,
+ events,
+ resourceLabel,
+ levelLabel,
+ statusLabel,
+ durationText,
+ eventCountLabel,
+}: {
+ incident: Incident;
+ events: SanitizedIncidentEvent[];
+ resourceLabel: string;
+ levelLabel: string;
+ statusLabel: string;
+ durationText: string;
+ eventCountLabel: string;
+}): string {
+ const eventLines = events
+ .slice(0, MAX_CONTEXT_EVENTS)
+ .map((event, index) =>
+ formatContextLine(
+ `Timeline Event ${index + 1}`,
+ `${event.timestamp} | ${formatIncidentLabel(event.type)} | ${event.summary}`,
+ ),
+ );
+
+ return [
+ '[Alert Incident Context]',
+ 'Source: Pulse Alerts incident timeline',
+ formatContextLine('Incident ID', incident.id),
+ formatContextLine('Alert Identifier', incident.alertIdentifier),
+ formatContextLine('Alert Type', incident.alertType),
+ formatContextLine('Alert Level', levelLabel),
+ formatContextLine('Incident Status', statusLabel),
+ formatContextLine('Resource', resourceLabel),
+ formatContextLine('Resource ID', incident.resourceId),
+ formatContextLine('Resource Type', incident.resourceType),
+ formatContextLine('Node', incident.node),
+ formatContextLine('Instance', incident.instance),
+ formatContextLine('Opened At', incident.openedAt),
+ formatContextLine('Closed At', incident.closedAt),
+ formatContextLine('Duration', durationText),
+ formatContextLine('Timeline Summary', eventCountLabel),
+ formatContextLine('Message', incident.message),
+ ...eventLines,
+ 'Timeline Boundary: Command events are summarized only; raw command details and output stay in the incident or governed approval surface.',
+ 'Operator Boundary: This incident handoff is model-only context for explanation and review. Diagnostics, remediation, and any command execution require explicit operator approval.',
+ ]
+ .filter((line): line is string => Boolean(line))
+ .join('\n');
+}
+
function sanitizeIncidentEvents(events: IncidentEvent[]): SanitizedIncidentEvent[] {
return events.map((event) => ({
id: event.id,
@@ -129,6 +199,15 @@ function sanitizeIncidentEventSummary(event: IncidentEvent): string {
return summary.length > 0 ? summary : 'Timeline event recorded';
}
+function formatContextLine(
+ label: string,
+ value?: string | number | boolean | null,
+): string | undefined {
+ if (value === undefined || value === null) return undefined;
+ const text = String(value).trim();
+ return text ? `${label}: ${text}` : undefined;
+}
+
function formatIncidentDuration(openedAt: string, closedAt: string | undefined, now: Date): string {
const openedMs = new Date(openedAt).getTime();
const closedMs = closedAt ? new Date(closedAt).getTime() : now.getTime();
diff --git a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
index 1f926791d8..387db9c2f5 100644
--- a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
+++ b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
@@ -19,6 +19,7 @@ import alertHistoryTableAlertRowSource from '@/features/alerts/AlertHistoryTable
import alertHistoryTableGroupRowSource from '@/features/alerts/AlertHistoryTableGroupRow.tsx?raw';
import alertHistoryTableSectionSource from '@/features/alerts/AlertHistoryTableSection.tsx?raw';
import alertResourceIncidentsPanelSource from '@/features/alerts/AlertResourceIncidentsPanel.tsx?raw';
+import alertAssistantHandoffModelSource from '@/components/Alerts/alertAssistantHandoffModel.ts?raw';
import incidentAssistantHandoffButtonSource from '@/components/Alerts/IncidentAssistantHandoffButton.tsx?raw';
import incidentAssistantHandoffModelSource from '@/components/Alerts/incidentAssistantHandoffModel.ts?raw';
import incidentTimelinePanelSource from '@/components/Alerts/IncidentTimelinePanel.tsx?raw';
@@ -473,7 +474,13 @@ describe('tab path helpers', () => {
expect(incidentTimelinePanelSource).toContain('IncidentAssistantHandoffButton');
expect(incidentAssistantHandoffButtonSource).toContain('buildAlertIncidentAssistantHandoff');
expect(incidentAssistantHandoffButtonSource).toContain('aiChatStore.openWithPrompt');
+ expect(alertAssistantHandoffModelSource).toContain('handoffContext');
+ expect(alertAssistantHandoffModelSource).toContain('handoffResources');
+ expect(alertAssistantHandoffModelSource).toContain('[Alert Investigation Context]');
expect(incidentAssistantHandoffModelSource).toContain('autonomousMode: false');
+ expect(incidentAssistantHandoffModelSource).toContain('handoffContext');
+ expect(incidentAssistantHandoffModelSource).toContain('handoffResources');
+ expect(incidentAssistantHandoffModelSource).toContain('[Alert Incident Context]');
expect(incidentAssistantHandoffModelSource).toContain('Command event recorded');
expect(incidentAssistantHandoffModelSource).not.toContain('details.command');
expect(incidentAssistantHandoffModelSource).not.toContain('output_excerpt');
diff --git a/frontend-modern/src/stores/__tests__/aiChat.test.ts b/frontend-modern/src/stores/__tests__/aiChat.test.ts
index aa0f114b4b..51aa39019a 100644
--- a/frontend-modern/src/stores/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiChat.test.ts
@@ -126,6 +126,31 @@ describe('aiChatStore', () => {
expect(aiChatStore.context.autonomousMode).toBe(false);
});
+ it('preserves model-only handoff context and resources for pre-filled prompts', () => {
+ aiChatStore.openWithPrompt('discuss this incident', {
+ targetType: 'storage',
+ targetId: 'storage-1',
+ autonomousMode: false,
+ handoffContext:
+ '[Alert Incident Context]\nTimeline Event 1: 2026-05-07T00:02:00Z | Command | Command event recorded',
+ handoffResources: [{ id: 'storage-1', name: 'tank', type: 'storage', node: 'nas-1' }],
+ });
+
+ expect(aiChatStore.context.initialPrompt).toBe('discuss this incident');
+ expect(aiChatStore.context.handoffContext).toContain('[Alert Incident Context]');
+ expect(aiChatStore.context.handoffResources).toEqual([
+ { id: 'storage-1', name: 'tank', type: 'storage', node: 'nas-1' },
+ ]);
+
+ aiChatStore.clearInitialPrompt();
+
+ expect(aiChatStore.context.initialPrompt).toBeUndefined();
+ expect(aiChatStore.context.handoffContext).toContain('Command event recorded');
+ expect(aiChatStore.context.handoffResources).toEqual([
+ { id: 'storage-1', name: 'tank', type: 'storage', node: 'nas-1' },
+ ]);
+ });
+
it('focusInput returns false when closed and true when open with a registered element', () => {
const textarea = document.createElement('textarea');
document.body.appendChild(textarea);
diff --git a/frontend-modern/src/stores/aiChat.ts b/frontend-modern/src/stores/aiChat.ts
index 54753b11c0..f6d3cbe0ac 100644
--- a/frontend-modern/src/stores/aiChat.ts
+++ b/frontend-modern/src/stores/aiChat.ts
@@ -16,6 +16,13 @@ export interface AIChatContextBriefing {
safetyNote?: string;
}
+export interface AIChatHandoffResource {
+ id: string;
+ name?: string;
+ type?: string;
+ node?: string;
+}
+
export interface AIChatContext {
targetType?: string;
targetId?: string;
@@ -23,6 +30,8 @@ export interface AIChatContext {
initialPrompt?: string;
findingId?: string; // If opened from AI Insights "Get Help", the finding ID to resolve on success
briefing?: AIChatContextBriefing;
+ handoffContext?: string;
+ handoffResources?: AIChatHandoffResource[];
// Per-request execution mode override; false keeps scoped handoffs approval-required.
autonomousMode?: boolean;
}
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 8985405925..69658779b5 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -775,18 +775,22 @@ func canonicalizeChatMentionType(raw string) string {
// ChatRequest represents a chat request
type ChatRequest struct {
- Prompt string `json:"prompt"`
- SessionID string `json:"session_id,omitempty"`
- Model string `json:"model,omitempty"`
- Mentions []ChatMention `json:"mentions,omitempty"`
- FindingID string `json:"finding_id,omitempty"`
- AutonomousMode *bool `json:"autonomous_mode,omitempty"`
-}
+ Prompt string `json:"prompt"`
+ SessionID string `json:"session_id,omitempty"`
+ Model string `json:"model,omitempty"`
+ Mentions []ChatMention `json:"mentions,omitempty"`
+ FindingID string `json:"finding_id,omitempty"`
+ HandoffContext string `json:"handoff_context,omitempty"`
+ HandoffResources []chat.HandoffResource `json:"handoff_resources,omitempty"`
+ AutonomousMode *bool `json:"autonomous_mode,omitempty"`
+}
+
+const (
+ chatRequestHandoffContextMaxBytes = 16 * 1024
+ chatRequestHandoffResourceLimit = 8
+)
-func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction) *bool {
- if strings.TrimSpace(findingID) == "" {
- return requested
- }
+func chatAutonomousModeForScopedHandoff(requested *bool, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction) *bool {
if strings.TrimSpace(handoffContext) == "" && len(handoffResources) == 0 && len(handoffActions) == 0 {
return requested
}
@@ -794,6 +798,49 @@ func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffCont
return &approvalRequired
}
+func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction) *bool {
+ return chatAutonomousModeForScopedHandoff(requested, handoffContext, handoffResources, handoffActions)
+}
+
+func normalizeChatRequestHandoffContext(raw string) string {
+ context := strings.TrimSpace(raw)
+ if len(context) <= chatRequestHandoffContextMaxBytes {
+ return context
+ }
+ return strings.TrimSpace(context[:chatRequestHandoffContextMaxBytes]) + "\n[Handoff Context Truncated]"
+}
+
+func normalizeChatRequestHandoffResources(raw []chat.HandoffResource) []chat.HandoffResource {
+ resources := make([]chat.HandoffResource, 0, min(len(raw), chatRequestHandoffResourceLimit))
+ for _, resource := range raw {
+ if len(resources) >= chatRequestHandoffResourceLimit {
+ break
+ }
+ id := trimChatHandoffField(resource.ID, 256)
+ name := trimChatHandoffField(resource.Name, 256)
+ resourceType := canonicalizeChatMentionType(resource.Type)
+ node := trimChatHandoffField(resource.Node, 256)
+ if id == "" && name == "" {
+ continue
+ }
+ resources = append(resources, chat.HandoffResource{
+ ID: id,
+ Name: name,
+ Type: resourceType,
+ Node: node,
+ })
+ }
+ return resources
+}
+
+func trimChatHandoffField(raw string, limit int) string {
+ value := strings.TrimSpace(raw)
+ if len(value) <= limit {
+ return value
+ }
+ return strings.TrimSpace(value[:limit])
+}
+
const findingChatContextListLimit = 5
type unifiedFindingLookup interface {
@@ -2119,8 +2166,8 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
// Build model-only finding context when discussing a specific finding. The
// chat service injects this into the current model turn without persisting it
// as the user's authored prompt, so conversation history stays readable.
- handoffContext := ""
- var handoffResources []chat.HandoffResource
+ handoffContext := normalizeChatRequestHandoffContext(req.HandoffContext)
+ handoffResources := normalizeChatRequestHandoffResources(req.HandoffResources)
var handoffActions []chat.HandoffAction
findingID := strings.TrimSpace(req.FindingID)
if findingID == "" && strings.TrimSpace(req.SessionID) != "" {
@@ -2149,6 +2196,9 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
}
}
findingID = ""
+ handoffContext = ""
+ handoffResources = nil
+ handoffActions = nil
}
}
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 218db70f36..9304ba6403 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -569,6 +569,44 @@ func TestHandleChat_PassesAutonomousModeOverride(t *testing.T) {
assert.Equal(t, http.StatusOK, w.Code)
}
+func TestHandleChat_PassesScopedHandoffContext(t *testing.T) {
+ cfg := &config.Config{}
+ h := newTestAIHandler(cfg, nil, nil)
+ mockSvc := new(MockAIService)
+ h.defaultService = mockSvc
+
+ mockSvc.On("IsRunning").Return(true)
+ mockSvc.
+ On("ExecuteStream", mock.Anything, mock.Anything, mock.Anything).
+ Return(nil).
+ Run(func(args mock.Arguments) {
+ reqArg := args.Get(1).(chat.ExecuteRequest)
+ assert.Equal(t, "discuss incident", reqArg.Prompt)
+ assert.Equal(t, "", reqArg.FindingID)
+ assert.Contains(t, reqArg.HandoffContext, "[Alert Incident Context]")
+ assert.Contains(t, reqArg.HandoffContext, "Incident ID: incident-1")
+ assert.Contains(t, reqArg.HandoffContext, "Timeline Event 1: Command | Command event recorded")
+ assert.NotContains(t, reqArg.HandoffContext, "systemctl")
+ assert.Equal(t, []chat.HandoffResource{{
+ ID: "storage-1",
+ Name: "tank",
+ Type: "storage",
+ Node: "nas-1",
+ }}, reqArg.HandoffResources)
+ if assert.NotNil(t, reqArg.AutonomousMode) {
+ assert.False(t, *reqArg.AutonomousMode)
+ }
+ })
+
+ body := `{"prompt":"discuss incident","autonomous_mode":true,"handoff_context":"[Alert Incident Context]\nIncident ID: incident-1\nTimeline Event 1: Command | Command event recorded","handoff_resources":[{"id":"storage-1","name":"tank","type":"storage","node":"nas-1"}]}`
+ req := httptest.NewRequest("POST", "/api/ai/chat", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ h.HandleChat(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+}
+
func TestHandleChat_IncludesInvestigationRecordContext(t *testing.T) {
cfg := &config.Config{}
h := newTestAIHandler(cfg, nil, nil)
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index ce80d57a7b..eb2fc643cc 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3627,8 +3627,8 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Shared Boundaries",
"path": "internal/api/access_control_handlers.go",
- "line": 182,
- "heading_line": 105,
+ "line": 183,
+ "heading_line": 106,
}
],
)