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.

Restore Patrol run Assistant session identity

rcourtmanff9cb5c13371
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 37839906db..adfba81582 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -391,6 +391,11 @@ profile and assignment columns, but embedded table framing must route through
proof, or auto-approval policy. Any approval or action-audit status snapshot
refreshed for Assistant review remains read-only AI/runtime context and must
not become command-websocket authority or lifecycle execution state.
+ Patrol run `handoff_metadata` retained for saved Assistant sessions follows
+ the same isolation rule: a run ID, run type/status, runtime-failure flag, or
+ scoped resource label may restore Assistant presentation, but it must not
+ become agent enrollment evidence, installer state, command-websocket
+ identity, or fleet-control authority.
Assistant operator-decision and action-posture briefing text derived from
those same recovered handoff action references stays under that review-only
boundary; lifecycle surfaces must not reinterpret a clearer approval posture
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 7818f8c899..b816f6fb6d 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -282,14 +282,15 @@ runtime cost control, and shared AI transport surfaces.
`handoff_summary` for this private model-context metadata so reloaded
Assistant sessions can still be identified as scoped Patrol/product
handoffs. That summary may include the handoff kind, finding ID, resource
- and action counts, a primary resource label, last-known approval/action
- status, risk level, and timestamp, but it must not expose model-only
- handoff text, action preflight/result bodies, remediation descriptions, raw
- commands, or approval command payloads. Its `requires_approval` field is a
- current operator-decision flag only: pending approval states may set it, but
- approved, denied, rejected, executing, completed, failed, expired, or
- otherwise historical action references must remain action context without
- being relabeled as requiring approval.
+ and Patrol run ID, safe run type/status/runtime-failure flags, resource and
+ action counts, a primary resource label, last-known approval/action status,
+ risk level, and timestamp, but it must not expose model-only handoff text,
+ runtime failure detail, action preflight/result bodies, remediation
+ descriptions, raw commands, or approval command payloads. Its
+ `requires_approval` field is a current operator-decision flag only: pending
+ approval states may set it, but approved, denied, rejected, executing,
+ completed, failed, expired, or otherwise historical action references must
+ remain action context without being relabeled as requiring approval.
When the Assistant drawer restores any session from that `handoff_summary`,
it must restore the scoped request-local approval boundary as well as the
safe visible briefing: the next chat turn must carry
@@ -310,9 +311,10 @@ runtime cost control, and shared AI transport surfaces.
opening the session picker instead of presenting mount-time cached
summaries as the operator's decision surface.
Browser-originated `handoff_context`, `handoff_resources`, and
- `handoff_actions` are one-shot request seeds for the first successful chat
- turn. After that send succeeds, the drawer must clear those request payloads
- while preserving the safe visible briefing and request-local
+ `handoff_actions` plus safe `handoff_metadata` are one-shot request seeds
+ for the first successful chat turn. After that send succeeds, the drawer
+ must clear those request payloads while preserving the safe visible
+ briefing and request-local
approval-required posture; later turns must rely on backend-owned session
model-context hydration and current canonical stores instead of resending
stale browser handoff payloads. Patrol approval-row Assistant entries are
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index cd74558d9e..05dba4a6cb 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1902,23 +1902,27 @@ The same chat payload boundary now carries scoped product handoff context:
`handoff_context` is bounded model-only text, `handoff_resources` are structured
resource references used to seed canonical resource-policy, state, relationship,
and timeline hydration, and `handoff_actions` are structured approval/action
-references used to seed canonical approval and action-audit refresh. Frontend
-handoff builders may send these fields for owned alert, incident, or Patrol
-assessment 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 remains
-canonical; the handler may merge only recognized same-finding Patrol product
-handoff text and same-finding resource/action references as secondary
-model-only review context, while dropping mismatched references and raw command
-payload lines so the model cannot continue from stale or spoofed Patrol
-authority.
+references used to seed canonical approval and action-audit refresh.
+`handoff_metadata` is the browser-safe identity envelope for restoring saved
+product handoffs, currently including Patrol run kind, run ID, safe run
+type/status, and a runtime-failure boolean rather than runtime failure detail.
+Frontend handoff builders may send these fields for owned alert, incident,
+Patrol assessment, or Patrol run-history 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 remains canonical; the handler may
+merge only recognized same-finding Patrol product handoff text and same-finding
+resource/action references as secondary model-only review context, while
+dropping mismatched references and raw command payload lines so the model cannot
+continue from stale or spoofed Patrol authority.
The `/api/ai/sessions` response may expose `handoff_summary` for sessions that
carry private Assistant model-context metadata, but that payload is a safe
-reload marker only. It may carry the handoff kind, finding ID, counts,
-primary-resource label, last-known approval/action status, risk level, and
-summary timestamp; it must not serialize the model-only `handoff_context`,
-action preflight/result bodies, remediation descriptions, raw commands, or
-approval command payloads.
+reload marker only. It may carry the handoff kind, finding ID, Patrol run ID,
+safe run type/status/runtime-failure flags, counts, primary-resource label,
+last-known approval/action status, risk level, and summary timestamp; it must
+not serialize the model-only `handoff_context`, runtime failure detail, action
+preflight/result bodies, remediation descriptions, raw commands, or approval
+command payloads.
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 310c388654..951b90303d 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -183,15 +183,19 @@ work extends shared components instead of creating new local variants.
briefing state so Patrol and alert context does not visually leak between
conversations. Browser-originated model handoff payloads are one-shot
request seeds: after the first successful chat send, this store must clear
- `handoffContext`, `handoffResources`, and `handoffActions` while preserving
- the safe visible briefing and scoped approval-required posture, so later
- turns rely on backend session hydration instead of resending stale browser
- context. The drawer must treat `handoff_summary.requires_approval` as a
- current pending-decision flag, not a historical action marker, so completed
- or rejected handoff actions render as action context rather than pending
- approval. Session-load and new-conversation transitions must be
- success-bound: if the underlying session operation fails, the shared drawer
- store must not clear or replace the current scoped handoff context.
+ `handoffContext`, `handoffResources`, `handoffActions`, and safe
+ `handoffMetadata` while preserving the safe visible briefing and scoped
+ approval-required posture, so later turns rely on backend session hydration
+ instead of resending stale browser context. The drawer must treat
+ `handoff_summary.requires_approval` as a current pending-decision flag, not a
+ historical action marker, so completed or rejected handoff actions render as
+ action context rather than pending approval. A restored Patrol run summary
+ must remain visibly sourced to Pulse Patrol, restore a `patrol-run` target
+ plus run ID/type/status/runtime-failure presentation only, and must not
+ rehydrate model-only runtime failure detail into browser context.
+ Session-load and new-conversation transitions must be success-bound: if the
+ underlying session operation fails, the shared drawer store must not clear or
+ replace the current scoped handoff context.
9. `frontend-modern/src/utils/platformSupportManifest.generated.ts` shared with `unified-resources`: the generated platform support projection is both a canonical unified-resource platform union boundary and a shared frontend source/platform vocabulary boundary.
10. `frontend-modern/src/utils/sourcePlatforms.ts` shared with `unified-resources`: the source platform normalizer is both a canonical unified-resource source adapter boundary and a shared frontend source/platform vocabulary boundary.
That shared boundary must preserve `availability` as the agentless
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 42926d067e..28f4da9ec5 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -249,7 +249,10 @@ Patrol-specific presentation helpers.
history facts such as run ID/type/status, trigger, timing, coverage, scope,
findings snapshot availability, outcome counts, tool/triage effort,
`error_summary`, `error_detail`, sanitized Patrol analysis, and scoped
- resource references as model-only context. It must force request-local
+ resource references as model-only context. It must also send safe
+ `handoff_metadata` for the saved-session identity envelope: kind
+ `patrol_run`, run ID, safe run type/status, and a runtime-failure boolean,
+ never runtime failure detail or analysis text. It must force request-local
approval-required mode, present a source-named visible drawer briefing, and
frame Assistant as explanation and next-step review rather than execution or
automatic retry authority.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 2ae8f51489..7be730ad1f 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1092,6 +1092,11 @@ approval policy, plan expiry, and dry-run posture, but they must not reinterpret
a recovered approval or clearer proposed-fix posture as backup freshness,
restore authority, recovery proof, or storage-local remediation execution
state.
+Patrol run `handoff_metadata` retained for saved Assistant sessions is also
+AI/runtime review identity only. Storage and recovery may display or link from
+the safe run ID, run type/status, runtime-failure flag, or scoped resource label
+as incident context, but they must not reinterpret it as backup freshness,
+restore proof, storage health authority, or recovery-local remediation state.
That same storage ownership also includes the shared storage-source presentation
contract in `frontend-modern/src/utils/storageSources.ts`: storage pages and
cross-surface storage links must reuse one canonical ordering, label, tone, and
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index 2d0b0ffd8c..a67aef236c 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -144,6 +144,58 @@ describe('AIChatAPI', () => {
);
});
+ it('includes browser-safe Patrol run handoff metadata 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 run',
+ 'session-run',
+ undefined,
+ vi.fn(),
+ undefined,
+ undefined,
+ undefined,
+ false,
+ undefined,
+ undefined,
+ undefined,
+ {
+ kind: 'patrol_run',
+ runId: 'run-runtime-error',
+ runType: 'Scoped run',
+ runStatus: 'error',
+ runtimeFailure: true,
+ },
+ );
+
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/ai/chat',
+ expect.objectContaining({
+ body: JSON.stringify({
+ prompt: 'discuss run',
+ session_id: 'session-run',
+ model: undefined,
+ autonomous_mode: false,
+ handoff_metadata: {
+ kind: 'patrol_run',
+ run_id: 'run-runtime-error',
+ run_type: 'Scoped run',
+ run_status: 'error',
+ runtime_failure: true,
+ },
+ }),
+ }),
+ );
+ });
+
it('includes a Patrol finding id when supplied for Assistant context', async () => {
const read = vi.fn().mockResolvedValueOnce({ done: true, value: undefined });
const releaseLock = vi.fn();
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index fa942cee45..9cfdc58876 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -41,6 +41,10 @@ export interface ChatSessionHandoffResource {
export interface ChatSessionHandoffSummary {
kind?: string;
finding_id?: string;
+ run_id?: string;
+ run_type?: string;
+ run_status?: string;
+ runtime_failure?: boolean;
has_model_context: boolean;
resource_count?: number;
primary_resource?: ChatSessionHandoffResource;
@@ -52,6 +56,14 @@ export interface ChatSessionHandoffSummary {
updated_at?: string;
}
+export interface ChatHandoffMetadata {
+ kind?: string;
+ runId?: string;
+ runType?: string;
+ runStatus?: string;
+ runtimeFailure?: boolean;
+}
+
export interface ChatHandoffAction {
findingId?: string;
recordId?: string;
@@ -264,6 +276,7 @@ export class AIChatAPI {
handoffContext?: string,
handoffResources?: ChatHandoffResource[],
handoffActions?: ChatHandoffAction[],
+ handoffMetadata?: ChatHandoffMetadata,
): Promise<void> {
logger.debug('[AI Chat] Starting chat stream', { prompt: prompt.substring(0, 50) });
@@ -290,6 +303,15 @@ export class AIChatAPI {
if (handoffActions && handoffActions.length > 0) {
body.handoff_actions = handoffActions.map(serializeChatHandoffAction);
}
+ if (handoffMetadata) {
+ body.handoff_metadata = {
+ kind: handoffMetadata.kind,
+ run_id: handoffMetadata.runId,
+ run_type: handoffMetadata.runType,
+ run_status: handoffMetadata.runStatus,
+ runtime_failure: handoffMetadata.runtimeFailure,
+ };
+ }
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 273af7dfb0..b65ff4e361 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -610,7 +610,13 @@ describe('AIChat', () => {
mockAIChatAPI.listSessions
.mockResolvedValueOnce([])
.mockResolvedValueOnce([
- { id: 's-fresh', title: 'Fresh session', created_at: '', updated_at: '', message_count: 1 },
+ {
+ id: 's-fresh',
+ title: 'Fresh session',
+ created_at: '',
+ updated_at: '',
+ message_count: 1,
+ },
]);
renderChat();
@@ -721,6 +727,84 @@ describe('AIChat', () => {
expect(restoredContext.handoffActions).toBeUndefined();
});
+ it('restores safe Patrol run handoff state from a loaded session summary', async () => {
+ mockAIChatAPI.listSessions.mockResolvedValue([
+ {
+ id: 's-patrol-run',
+ title: 'Runtime failure follow-up',
+ created_at: '',
+ updated_at: '',
+ message_count: 2,
+ handoff_summary: {
+ kind: 'patrol_run',
+ run_id: 'run-runtime-error',
+ run_type: 'Scoped run',
+ run_status: 'error',
+ runtime_failure: true,
+ has_model_context: true,
+ resource_count: 1,
+ primary_resource: {
+ id: 'vm-100',
+ type: 'vm',
+ },
+ action_count: 0,
+ requires_approval: false,
+ },
+ },
+ ]);
+
+ renderChat();
+ await waitFor(() => {
+ expect(mockAIChatAPI.listSessions).toHaveBeenCalled();
+ });
+ fireEvent.click(screen.getByTitle('Pulse Assistant sessions'));
+
+ await waitFor(() => {
+ expect(screen.getByText('Pulse Patrol')).toBeInTheDocument();
+ expect(screen.getByText('Runtime issue')).toBeInTheDocument();
+ expect(screen.getByText(/run error/)).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByText('Runtime failure follow-up'));
+
+ await waitFor(() => {
+ expect(mockChat.loadSession).toHaveBeenCalledWith('s-patrol-run');
+ expect(mockAiChatStore.setContext).toHaveBeenCalledWith(
+ expect.objectContaining({
+ targetType: 'patrol-run',
+ targetId: 'run-runtime-error',
+ findingId: undefined,
+ autonomousMode: false,
+ context: expect.objectContaining({
+ kind: 'patrol_run',
+ runId: 'run-runtime-error',
+ runType: 'Scoped run',
+ runStatus: 'error',
+ runtimeFailure: true,
+ }),
+ briefing: expect.objectContaining({
+ sourceLabel: 'Pulse Patrol',
+ title: 'Patrol run run-runtime-error',
+ subject: 'Run run-runtime-error',
+ actionLabel: 'Review Patrol runtime issue',
+ commandSummary: expect.stringContaining('runtime issue'),
+ }),
+ }),
+ );
+ });
+ const restoredContext = mockAiChatStore.setContext.mock.calls[0]?.[0];
+ expect(restoredContext.handoffContext).toBeUndefined();
+ expect(restoredContext.handoffMetadata).toBeUndefined();
+
+ const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
+ fireEvent.input(textarea, { target: { value: 'what failed?' } });
+ fireEvent.keyDown(textarea, { key: 'Enter' });
+
+ expect(mockChat.sendMessage).toHaveBeenCalledWith('what failed?', undefined, undefined, {
+ autonomousMode: false,
+ });
+ });
+
it('does not restore handoff context when loading a session fails', async () => {
mockChat.loadSession.mockResolvedValueOnce(false);
mockAIChatAPI.listSessions.mockResolvedValue([
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index bdd9c65df0..dcf318e858 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -2,6 +2,7 @@ import { createSignal, onCleanup } from 'solid-js';
import {
AIChatAPI,
type ChatHandoffAction,
+ type ChatHandoffMetadata,
type ChatHandoffResource,
type ChatMention,
type StreamEvent,
@@ -31,6 +32,7 @@ export interface SendMessageOptions {
handoffContext?: string;
handoffResources?: ChatHandoffResource[];
handoffActions?: ChatHandoffAction[];
+ handoffMetadata?: ChatHandoffMetadata;
}
export function useChat(options: UseChatOptions = {}) {
@@ -572,6 +574,7 @@ export function useChat(options: UseChatOptions = {}) {
sendOptions?.handoffContext,
sendOptions?.handoffResources,
sendOptions?.handoffActions,
+ sendOptions?.handoffMetadata,
);
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 ec0d82fb3a..ec14bd2c99 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -78,9 +78,15 @@ const compactText = (items: Array<string | undefined>): string[] =>
const pluralizeCount = (count: number, singular: string, plural: string) =>
`${count} ${count === 1 ? singular : plural}`;
-const isPatrolSessionHandoff = (summary: ChatSessionHandoffSummary) =>
+const isPatrolFindingSessionHandoff = (summary: ChatSessionHandoffSummary) =>
summary.kind === 'patrol_finding' || Boolean(summary.finding_id);
+const isPatrolRunSessionHandoff = (summary: ChatSessionHandoffSummary) =>
+ summary.kind === 'patrol_run' || Boolean(summary.run_id);
+
+const isPatrolSessionHandoff = (summary: ChatSessionHandoffSummary) =>
+ isPatrolFindingSessionHandoff(summary) || isPatrolRunSessionHandoff(summary);
+
const getSessionHandoffSourceLabel = (summary: ChatSessionHandoffSummary) =>
isPatrolSessionHandoff(summary) ? 'Pulse Patrol' : 'Pulse Assistant';
@@ -98,8 +104,14 @@ const formatSessionHandoffResourceDetail = (summary: ChatSessionHandoffSummary)
return label;
};
-const formatSessionHandoffStatus = (summary: ChatSessionHandoffSummary) =>
- compactText([
+const formatSessionHandoffStatus = (summary: ChatSessionHandoffSummary) => {
+ if (isPatrolRunSessionHandoff(summary)) {
+ return compactText([
+ summary.run_status ? `run ${formatIdentifierLabel(summary.run_status)}` : undefined,
+ summary.runtime_failure ? 'runtime issue' : undefined,
+ ]).join(' · ');
+ }
+ return compactText([
summary.last_known_approval_status
? `approval ${formatIdentifierLabel(summary.last_known_approval_status)}`
: undefined,
@@ -110,10 +122,14 @@ const formatSessionHandoffStatus = (summary: ChatSessionHandoffSummary) =>
? `${formatIdentifierLabel(summary.last_known_action_risk)} risk`
: undefined,
]).join(' · ');
+};
const getSessionHandoffBadgeLabel = (summary: ChatSessionHandoffSummary) => {
if (summary.requires_approval) return 'Approval required';
if ((summary.action_count ?? 0) > 0) return 'Action context';
+ if (isPatrolRunSessionHandoff(summary)) {
+ return summary.runtime_failure ? 'Runtime issue' : 'Run context';
+ }
return summary.has_model_context ? 'Context attached' : 'Scoped handoff';
};
@@ -128,24 +144,36 @@ const buildSessionHandoffContext = (session?: ChatSession): AIChatContext | unde
const actionCount = summary.action_count ?? 0;
const resourceCount = summary.resource_count ?? 0;
const findingId = summary.finding_id?.trim() || undefined;
- const isPatrol = isPatrolSessionHandoff(summary);
- const title = isPatrol
- ? resourceLabel
- ? `Patrol finding on ${resourceLabel}`
- : findingId
- ? `Patrol finding ${findingId}`
- : 'Patrol finding handoff'
- : resourceLabel
- ? `Assistant handoff for ${resourceLabel}`
- : 'Assistant handoff';
+ const runId = summary.run_id?.trim() || undefined;
+ const runType = summary.run_type?.trim() || undefined;
+ const runStatus = summary.run_status?.trim() || undefined;
+ const isPatrolFinding = isPatrolFindingSessionHandoff(summary);
+ const isPatrolRun = isPatrolRunSessionHandoff(summary);
+ const title = isPatrolRun
+ ? runId
+ ? `Patrol run ${runId}`
+ : 'Patrol run handoff'
+ : isPatrolFinding
+ ? resourceLabel
+ ? `Patrol finding on ${resourceLabel}`
+ : findingId
+ ? `Patrol finding ${findingId}`
+ : 'Patrol finding handoff'
+ : resourceLabel
+ ? `Assistant handoff for ${resourceLabel}`
+ : 'Assistant handoff';
return {
- targetType: summary.primary_resource?.type,
- targetId: summary.primary_resource?.id,
+ targetType: isPatrolRun ? 'patrol-run' : summary.primary_resource?.type,
+ targetId: isPatrolRun ? runId : summary.primary_resource?.id,
context: {
source: 'session_handoff_summary',
kind: summary.kind,
findingId,
+ runId,
+ runType,
+ runStatus,
+ runtimeFailure: summary.runtime_failure ?? false,
hasModelContext: summary.has_model_context,
resourceCount,
actionCount,
@@ -160,9 +188,14 @@ const buildSessionHandoffContext = (session?: ChatSession): AIChatContext | unde
briefing: {
sourceLabel,
title,
- subject: findingId ? `Finding ${findingId}` : undefined,
- statusLabel: statusLabel || (summary.requires_approval ? 'approval required' : undefined),
+ subject:
+ isPatrolRun && runId ? `Run ${runId}` : findingId ? `Finding ${findingId}` : undefined,
+ statusLabel:
+ statusLabel ||
+ (summary.requires_approval ? 'approval required' : undefined) ||
+ (isPatrolRun && summary.runtime_failure ? 'runtime issue' : undefined),
detailLines: compactText([
+ isPatrolRun && runType ? `Run type: ${runType}` : undefined,
resourceDetail ? `Resource: ${resourceDetail}` : undefined,
resourceCount > 1
? pluralizeCount(resourceCount, 'linked resource', 'linked resources')
@@ -174,21 +207,42 @@ const buildSessionHandoffContext = (session?: ChatSession): AIChatContext | unde
]),
actionLabel: summary.requires_approval
? 'Approval required'
+ : isPatrolRun && summary.runtime_failure
+ ? 'Review Patrol runtime issue'
+ : isPatrolRun
+ ? 'Review Patrol run'
+ : actionCount > 0
+ ? 'Governed action context'
+ : undefined,
+ commandSummary: statusLabel
+ ? isPatrolRun
+ ? `Run state: ${statusLabel}`
+ : `Last known state: ${statusLabel}`
+ : undefined,
+ safetyNote: isPatrolRun
+ ? 'Patrol run context is review-only; actions still require governed approval.'
: actionCount > 0
- ? 'Governed action context'
- : undefined,
- commandSummary: statusLabel ? `Last known state: ${statusLabel}` : undefined,
- safetyNote:
- actionCount > 0
? 'Detailed command payloads stay in governed approval context.'
: undefined,
- suggestedPrompts: isPatrol
- ? [
- 'What changed since this finding was opened?',
- 'What evidence supports this finding?',
- 'What should I verify next?',
- ]
- : ['Summarize this handoff', 'What needs attention?', 'What should I verify next?'],
+ suggestedPrompts: isPatrolRun
+ ? summary.runtime_failure
+ ? [
+ 'Explain this Patrol runtime issue',
+ 'What should I check before retrying?',
+ 'What should I verify next?',
+ ]
+ : [
+ 'Explain this Patrol run',
+ 'What changed during this run?',
+ 'What should I verify next?',
+ ]
+ : isPatrolFinding
+ ? [
+ 'What changed since this finding was opened?',
+ 'What evidence supports this finding?',
+ 'What should I verify next?',
+ ]
+ : ['Summarize this handoff', 'What needs attention?', 'What should I verify next?'],
},
};
};
@@ -809,18 +863,23 @@ export const AIChat: Component<AIChatProps> = (props) => {
if (ctx.handoffActions && ctx.handoffActions.length > 0) {
sendOptions.handoffActions = ctx.handoffActions;
}
+ if (ctx.handoffMetadata) {
+ sendOptions.handoffMetadata = ctx.handoffMetadata;
+ }
const hasSendOptions =
typeof sendOptions.autonomousMode === 'boolean' ||
Boolean(sendOptions.handoffContext) ||
Boolean(sendOptions.handoffResources?.length) ||
- Boolean(sendOptions.handoffActions?.length);
+ Boolean(sendOptions.handoffActions?.length) ||
+ Boolean(sendOptions.handoffMetadata);
const sendPromise = hasSendOptions
? chat.sendMessage(prompt, mentionsForAPI, findingId, sendOptions)
: chat.sendMessage(prompt, mentionsForAPI, findingId);
const hasRequestHandoffPayload =
Boolean(ctx.handoffContext?.trim()) ||
Boolean(ctx.handoffResources?.length) ||
- Boolean(ctx.handoffActions?.length);
+ Boolean(ctx.handoffActions?.length) ||
+ Boolean(ctx.handoffMetadata);
sendPromise.then((ok) => {
if (!ok) return;
if (findingId) {
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
index 75d6d4a3cb..96901137af 100644
--- a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
@@ -424,6 +424,13 @@ describe('patrolInvestigationContextModel', () => {
},
});
expect(handoff.context.handoffResources).toEqual([{ id: 'vm-100', type: 'vm' }]);
+ expect(handoff.context.handoffMetadata).toEqual({
+ kind: 'patrol_run',
+ runId: 'run-runtime-error',
+ runType: 'Scoped run',
+ runStatus: 'error',
+ runtimeFailure: true,
+ });
expect(handoff.context.handoffContext).toContain('[Patrol Run Context]');
expect(handoff.context.handoffContext).toContain('Source: Pulse Patrol run history');
expect(handoff.context.handoffContext).toContain('Run Type: Scoped run');
diff --git a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
index d6c149c80b..5f24054b4e 100644
--- a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
+++ b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
@@ -584,6 +584,13 @@ export function buildPatrolRunAssistantHandoff(run: PatrolRunRecord): PatrolRunA
autonomousMode: false,
handoffContext: buildPatrolRunAssistantModelContext(run, kindLabel, statusLabel),
handoffResources: handoffResources.length > 0 ? handoffResources : undefined,
+ handoffMetadata: {
+ kind: 'patrol_run',
+ runId: runId || undefined,
+ runType: kindLabel,
+ runStatus: statusLabel,
+ runtimeFailure: Boolean(runtimeFailure),
+ },
briefing: buildPatrolRunAssistantBriefing(run, kindLabel, statusLabel, runtimeFailure),
context: {
source: 'pulse-patrol-run',
diff --git a/frontend-modern/src/stores/__tests__/aiChat.test.ts b/frontend-modern/src/stores/__tests__/aiChat.test.ts
index b70d6f3635..a6acb192f3 100644
--- a/frontend-modern/src/stores/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiChat.test.ts
@@ -182,6 +182,13 @@ describe('aiChatStore', () => {
'[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' }],
handoffActions: [{ findingId: 'finding-1', approvalId: 'approval-1' }],
+ handoffMetadata: {
+ kind: 'patrol_run',
+ runId: 'run-runtime-error',
+ runType: 'Scoped run',
+ runStatus: 'error',
+ runtimeFailure: true,
+ },
});
aiChatStore.clearRequestHandoffPayload();
@@ -189,6 +196,7 @@ describe('aiChatStore', () => {
expect(aiChatStore.context.handoffContext).toBeUndefined();
expect(aiChatStore.context.handoffResources).toBeUndefined();
expect(aiChatStore.context.handoffActions).toBeUndefined();
+ expect(aiChatStore.context.handoffMetadata).toBeUndefined();
expect(aiChatStore.context.targetId).toBe('storage-1');
expect(aiChatStore.context.findingId).toBe('finding-1');
expect(aiChatStore.context.autonomousMode).toBe(false);
diff --git a/frontend-modern/src/stores/aiChat.ts b/frontend-modern/src/stores/aiChat.ts
index 6fb2a92a7f..c83e2c74e3 100644
--- a/frontend-modern/src/stores/aiChat.ts
+++ b/frontend-modern/src/stores/aiChat.ts
@@ -56,6 +56,14 @@ export interface AIChatHandoffAction {
targetNode?: string;
}
+export interface AIChatHandoffMetadata {
+ kind?: string;
+ runId?: string;
+ runType?: string;
+ runStatus?: string;
+ runtimeFailure?: boolean;
+}
+
export interface AIChatContext {
targetType?: string;
targetId?: string;
@@ -66,6 +74,7 @@ export interface AIChatContext {
handoffContext?: string;
handoffResources?: AIChatHandoffResource[];
handoffActions?: AIChatHandoffAction[];
+ handoffMetadata?: AIChatHandoffMetadata;
// Per-request execution mode override; false keeps scoped handoffs approval-required.
autonomousMode?: boolean;
}
@@ -482,13 +491,19 @@ export const aiChatStore = {
// them as model-only session context.
clearRequestHandoffPayload() {
setAIChatContext((prev) => {
- if (!prev.handoffContext && !prev.handoffResources?.length && !prev.handoffActions?.length) {
+ if (
+ !prev.handoffContext &&
+ !prev.handoffResources?.length &&
+ !prev.handoffActions?.length &&
+ !prev.handoffMetadata
+ ) {
return prev;
}
const {
handoffContext: _handoffContext,
handoffResources: _handoffResources,
handoffActions: _handoffActions,
+ handoffMetadata: _handoffMetadata,
...rest
} = prev;
return rest;
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 26423b848b..f3b1dd75d1 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -462,46 +462,29 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
handoffContext := strings.TrimSpace(req.HandoffContext)
handoffResources := normalizeHandoffResources(req.HandoffResources)
handoffActions := normalizeHandoffActions(req.HandoffActions)
+ handoffMetadata := NormalizeHandoffMetadata(req.HandoffMetadata)
handoffFindingID := strings.TrimSpace(req.FindingID)
- if handoffFindingID != "" {
- if err := sessions.SetModelHandoffFindingID(session.ID, handoffFindingID); err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff finding reference")
- }
- }
- if handoffContext != "" {
- if err := sessions.SetModelHandoffContext(session.ID, handoffContext); err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff context")
- }
- if err := sessions.SetModelHandoffResources(session.ID, handoffResources); err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff resources")
- }
- if err := sessions.SetModelHandoffActions(session.ID, handoffActions); err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff actions")
+ hasRequestHandoffEnvelope := handoffFindingID != "" ||
+ handoffContext != "" ||
+ len(handoffResources) > 0 ||
+ len(handoffActions) > 0 ||
+ !handoffMetadataEmpty(handoffMetadata)
+ if hasRequestHandoffEnvelope {
+ if err := sessions.SetModelHandoffEnvelope(session.ID, handoffFindingID, handoffContext, handoffResources, handoffActions, handoffMetadata); err != nil {
+ log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff envelope")
}
} else {
- if len(handoffResources) > 0 {
- if err := sessions.SetModelHandoffResources(session.ID, handoffResources); err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff resources")
- }
+ storedHandoffResources, err := sessions.GetModelHandoffResources(session.ID)
+ if err != nil {
+ log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to load model handoff resources")
} else {
- storedHandoffResources, err := sessions.GetModelHandoffResources(session.ID)
- if err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to load model handoff resources")
- } else {
- handoffResources = storedHandoffResources
- }
+ handoffResources = storedHandoffResources
}
- if len(handoffActions) > 0 {
- if err := sessions.SetModelHandoffActions(session.ID, handoffActions); err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist model handoff actions")
- }
+ storedHandoffActions, err := sessions.GetModelHandoffActions(session.ID)
+ if err != nil {
+ log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to load model handoff actions")
} else {
- storedHandoffActions, err := sessions.GetModelHandoffActions(session.ID)
- if err != nil {
- log.Warn().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to load model handoff actions")
- } else {
- handoffActions = storedHandoffActions
- }
+ handoffActions = storedHandoffActions
}
storedHandoffContext, err := sessions.GetModelHandoffContext(session.ID)
if err != nil {
diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.go
index fee9e80b13..4ade9d6a6d 100644
--- a/internal/ai/chat/session.go
+++ b/internal/ai/chat/session.go
@@ -55,6 +55,7 @@ type sessionModelContext struct {
HandoffContext string `json:"handoff_context,omitempty"`
HandoffResources []HandoffResource `json:"handoff_resources,omitempty"`
HandoffActions []HandoffAction `json:"handoff_actions,omitempty"`
+ HandoffMetadata HandoffMetadata `json:"handoff_metadata,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
@@ -136,6 +137,90 @@ func normalizeHandoffActions(actions []HandoffAction) []HandoffAction {
return normalized
}
+func trimHandoffMetadataField(value string, maxRunes int) string {
+ value = strings.TrimSpace(value)
+ if len([]rune(value)) <= maxRunes {
+ return value
+ }
+ runes := []rune(value)
+ return strings.TrimSpace(string(runes[:maxRunes]))
+}
+
+// NormalizeHandoffMetadata returns the browser-safe subset of product-originated
+// handoff identity that can be persisted and exposed in session summaries.
+func NormalizeHandoffMetadata(metadata HandoffMetadata) HandoffMetadata {
+ kind := strings.ToLower(trimHandoffMetadataField(metadata.Kind, 64))
+ switch kind {
+ case sessionHandoffKindPatrolRun:
+ default:
+ return HandoffMetadata{}
+ }
+
+ normalized := HandoffMetadata{
+ Kind: kind,
+ RunID: trimHandoffMetadataField(metadata.RunID, 256),
+ RunType: trimHandoffMetadataField(metadata.RunType, 128),
+ RunStatus: trimHandoffMetadataField(metadata.RunStatus, 128),
+ RuntimeFailure: metadata.RuntimeFailure,
+ }
+ if normalized.Kind == sessionHandoffKindPatrolRun && normalized.RunID == "" {
+ return HandoffMetadata{}
+ }
+ return normalized
+}
+
+func handoffMetadataEmpty(metadata HandoffMetadata) bool {
+ return NormalizeHandoffMetadata(metadata) == (HandoffMetadata{})
+}
+
+func inferPatrolRunHandoffMetadata(handoffContext string) HandoffMetadata {
+ lines := strings.Split(strings.TrimSpace(handoffContext), "\n")
+ if len(lines) == 0 {
+ return HandoffMetadata{}
+ }
+
+ var metadata HandoffMetadata
+ sawRunContext := false
+ sawRunHistorySource := false
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line == "[Patrol Run Context]" {
+ sawRunContext = true
+ continue
+ }
+ if !sawRunContext {
+ continue
+ }
+
+ label, value, ok := strings.Cut(line, ":")
+ if !ok {
+ continue
+ }
+ label = strings.ToLower(strings.TrimSpace(label))
+ value = strings.TrimSpace(value)
+ switch label {
+ case "source":
+ if strings.EqualFold(value, "Pulse Patrol run history") {
+ sawRunHistorySource = true
+ }
+ case "run id":
+ metadata.RunID = value
+ case "run type":
+ metadata.RunType = value
+ case "status":
+ metadata.RunStatus = value
+ case "runtime failure":
+ metadata.RuntimeFailure = value != ""
+ }
+ }
+
+ if !sawRunContext || !sawRunHistorySource || strings.TrimSpace(metadata.RunID) == "" {
+ return HandoffMetadata{}
+ }
+ metadata.Kind = sessionHandoffKindPatrolRun
+ return NormalizeHandoffMetadata(metadata)
+}
+
func modelContextEmpty(modelContext *sessionModelContext) bool {
if modelContext == nil {
return true
@@ -143,11 +228,13 @@ func modelContextEmpty(modelContext *sessionModelContext) bool {
return strings.TrimSpace(modelContext.HandoffFindingID) == "" &&
strings.TrimSpace(modelContext.HandoffContext) == "" &&
len(normalizeHandoffResources(modelContext.HandoffResources)) == 0 &&
- len(normalizeHandoffActions(modelContext.HandoffActions)) == 0
+ len(normalizeHandoffActions(modelContext.HandoffActions)) == 0 &&
+ handoffMetadataEmpty(modelContext.HandoffMetadata)
}
const (
sessionHandoffKindPatrolFinding = "patrol_finding"
+ sessionHandoffKindPatrolRun = "patrol_run"
sessionHandoffKindScopedContext = "scoped_context"
)
@@ -177,6 +264,10 @@ func modelContextHandoffSummary(modelContext *sessionModelContext) *SessionHando
resources := normalizeHandoffResources(modelContext.HandoffResources)
actions := normalizeHandoffActions(modelContext.HandoffActions)
+ metadata := NormalizeHandoffMetadata(modelContext.HandoffMetadata)
+ if handoffMetadataEmpty(metadata) {
+ metadata = inferPatrolRunHandoffMetadata(modelContext.HandoffContext)
+ }
findingID := strings.TrimSpace(modelContext.HandoffFindingID)
if findingID == "" {
for _, action := range actions {
@@ -190,15 +281,27 @@ func modelContextHandoffSummary(modelContext *sessionModelContext) *SessionHando
kind := sessionHandoffKindScopedContext
if findingID != "" {
kind = sessionHandoffKindPatrolFinding
+ } else if metadata.Kind == sessionHandoffKindPatrolRun {
+ kind = sessionHandoffKindPatrolRun
}
summary := &SessionHandoffSummary{
Kind: kind,
FindingID: findingID,
+ RunID: metadata.RunID,
+ RunType: metadata.RunType,
+ RunStatus: metadata.RunStatus,
+ RuntimeFailure: metadata.RuntimeFailure,
HasModelContext: strings.TrimSpace(modelContext.HandoffContext) != "",
ResourceCount: len(resources),
ActionCount: len(actions),
}
+ if kind != sessionHandoffKindPatrolRun {
+ summary.RunID = ""
+ summary.RunType = ""
+ summary.RunStatus = ""
+ summary.RuntimeFailure = false
+ }
if !modelContext.UpdatedAt.IsZero() {
updatedAt := modelContext.UpdatedAt
summary.UpdatedAt = &updatedAt
@@ -503,6 +606,43 @@ func (s *SessionStore) SetModelHandoffFindingID(id, findingID string) error {
return s.writeSession(*data)
}
+// SetModelHandoffEnvelope replaces the session's product-originated handoff
+// as one coherent scope. This avoids stale finding, run, resource, or action
+// identity leaking between separate handoffs within the same chat session.
+func (s *SessionStore) SetModelHandoffEnvelope(id string, findingID string, handoffContext string, handoffResources []HandoffResource, handoffActions []HandoffAction, handoffMetadata HandoffMetadata) error {
+ findingID = strings.TrimSpace(findingID)
+ handoffContext = strings.TrimSpace(handoffContext)
+ resources := normalizeHandoffResources(handoffResources)
+ actions := normalizeHandoffActions(handoffActions)
+ metadata := NormalizeHandoffMetadata(handoffMetadata)
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return err
+ }
+
+ now := time.Now()
+ modelContext := &sessionModelContext{
+ HandoffFindingID: findingID,
+ HandoffContext: handoffContext,
+ HandoffResources: resources,
+ HandoffActions: actions,
+ HandoffMetadata: metadata,
+ UpdatedAt: now,
+ }
+ if modelContextEmpty(modelContext) {
+ data.ModelContext = nil
+ } else {
+ data.ModelContext = modelContext
+ }
+ data.UpdatedAt = now
+
+ return s.writeSession(*data)
+}
+
// SetModelHandoffContext stores model-only handoff context for future turns.
// It is intentionally session metadata, not a user-authored chat message.
func (s *SessionStore) SetModelHandoffContext(id, handoffContext string) error {
@@ -586,6 +726,33 @@ func (s *SessionStore) SetModelHandoffActions(id string, handoffActions []Handof
return s.writeSession(*data)
}
+// SetModelHandoffMetadata stores browser-safe handoff identity for future
+// session summaries without exposing private model context details.
+func (s *SessionStore) SetModelHandoffMetadata(id string, handoffMetadata HandoffMetadata) error {
+ metadata := NormalizeHandoffMetadata(handoffMetadata)
+ if handoffMetadataEmpty(metadata) {
+ return nil
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return err
+ }
+
+ now := time.Now()
+ if data.ModelContext == nil {
+ data.ModelContext = &sessionModelContext{}
+ }
+ data.ModelContext.HandoffMetadata = metadata
+ data.ModelContext.UpdatedAt = now
+ data.UpdatedAt = now
+
+ return s.writeSession(*data)
+}
+
// GetModelHandoffFindingID returns the stored product-originated finding
// reference for a session.
func (s *SessionStore) GetModelHandoffFindingID(id string) (string, error) {
diff --git a/internal/ai/chat/session_additional_test.go b/internal/ai/chat/session_additional_test.go
index 7676f9b7e0..7c6d4d944a 100644
--- a/internal/ai/chat/session_additional_test.go
+++ b/internal/ai/chat/session_additional_test.go
@@ -419,6 +419,109 @@ func TestSessionStore_ListIncludesSafeHandoffSummary(t *testing.T) {
}
}
+func TestSessionStore_ListIncludesSafePatrolRunHandoffSummary(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ handoffContext := strings.Join([]string{
+ "[Patrol Run Context]",
+ "Source: Pulse Patrol run history",
+ "Run ID: run-runtime-error",
+ "Run Type: Scoped run",
+ "Status: error",
+ "Runtime Failure: Selected model does not support Patrol tools: No endpoints found that support the provided 'tool_choice' value.",
+ "Patrol Analysis: Runtime failure prevented analysis.",
+ }, "\n")
+ if err := store.SetModelHandoffEnvelope(session.ID, "", handoffContext, []HandoffResource{{
+ ID: " vm-100 ",
+ Type: " vm ",
+ }}, nil, HandoffMetadata{
+ Kind: " patrol_run ",
+ RunID: " run-runtime-error ",
+ RunType: " Scoped run ",
+ RunStatus: " error ",
+ RuntimeFailure: true,
+ }); err != nil {
+ t.Fatalf("SetModelHandoffEnvelope failed: %v", err)
+ }
+
+ sessions, err := store.List()
+ if err != nil {
+ t.Fatalf("List failed: %v", err)
+ }
+ if len(sessions) != 1 {
+ t.Fatalf("sessions = %#v, want one session", sessions)
+ }
+
+ summary := sessions[0].HandoffSummary
+ if summary == nil {
+ t.Fatalf("expected handoff summary")
+ }
+ if summary.Kind != sessionHandoffKindPatrolRun {
+ t.Fatalf("handoff kind = %q, want %q", summary.Kind, sessionHandoffKindPatrolRun)
+ }
+ if summary.FindingID != "" {
+ t.Fatalf("finding ID = %q, want empty Patrol run summary", summary.FindingID)
+ }
+ if summary.RunID != "run-runtime-error" || summary.RunType != "Scoped run" || summary.RunStatus != "error" || !summary.RuntimeFailure {
+ t.Fatalf("run summary = %#v, want safe Patrol run identity", summary)
+ }
+ if !summary.HasModelContext {
+ t.Fatalf("expected summary to report model context")
+ }
+ if summary.ResourceCount != 1 || summary.PrimaryResource == nil || summary.PrimaryResource.ID != "vm-100" {
+ t.Fatalf("resource summary = %#v, want normalized primary resource", summary)
+ }
+ if summary.ActionCount != 0 || summary.RequiresApproval {
+ t.Fatalf("action summary = %#v, want review-only run context without action authority", summary)
+ }
+
+ payload, err := json.Marshal(sessions)
+ if err != nil {
+ t.Fatalf("Marshal sessions failed: %v", err)
+ }
+ publicJSON := string(payload)
+ for _, forbidden := range []string{
+ "Selected model",
+ "No endpoints found",
+ "tool_choice",
+ "Runtime failure prevented analysis",
+ } {
+ if strings.Contains(publicJSON, forbidden) {
+ t.Fatalf("public session JSON leaked %q: %s", forbidden, publicJSON)
+ }
+ }
+}
+
+func TestModelContextHandoffSummaryInfersPatrolRunMetadataForExistingSessions(t *testing.T) {
+ summary := modelContextHandoffSummary(&sessionModelContext{
+ HandoffContext: strings.Join([]string{
+ "[Patrol Run Context]",
+ "Source: Pulse Patrol run history",
+ "Run ID: run-existing",
+ "Run Type: Scheduled run",
+ "Status: completed",
+ "Runtime Failure: Selected model failed during Patrol execution.",
+ }, "\n"),
+ })
+ if summary == nil {
+ t.Fatalf("summary is nil")
+ }
+ if summary.Kind != sessionHandoffKindPatrolRun {
+ t.Fatalf("handoff kind = %q, want %q", summary.Kind, sessionHandoffKindPatrolRun)
+ }
+ if summary.RunID != "run-existing" || summary.RunType != "Scheduled run" || summary.RunStatus != "completed" || !summary.RuntimeFailure {
+ t.Fatalf("run summary = %#v, want inferred Patrol run identity", summary)
+ }
+}
+
func TestModelContextHandoffSummaryRequiresApprovalOnlyForCurrentPendingApproval(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
index 5240bd2463..3366576dc1 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -27,6 +27,10 @@ type Session struct {
type SessionHandoffSummary struct {
Kind string `json:"kind,omitempty"`
FindingID string `json:"finding_id,omitempty"`
+ RunID string `json:"run_id,omitempty"`
+ RunType string `json:"run_type,omitempty"`
+ RunStatus string `json:"run_status,omitempty"`
+ RuntimeFailure bool `json:"runtime_failure,omitempty"`
HasModelContext bool `json:"has_model_context"`
ResourceCount int `json:"resource_count,omitempty"`
PrimaryResource *HandoffResource `json:"primary_resource,omitempty"`
@@ -153,6 +157,17 @@ type HandoffAction struct {
TargetNode string `json:"target_node,omitempty"`
}
+// HandoffMetadata carries browser-safe identity for a product-originated
+// model-only handoff. It must not include model context text, command payloads,
+// remediation details, or provider/runtime error detail.
+type HandoffMetadata struct {
+ Kind string `json:"kind,omitempty"`
+ RunID string `json:"run_id,omitempty"`
+ RunType string `json:"run_type,omitempty"`
+ RunStatus string `json:"run_status,omitempty"`
+ RuntimeFailure bool `json:"runtime_failure,omitempty"`
+}
+
// ExecuteRequest represents a chat execution request
type ExecuteRequest struct {
Prompt string `json:"prompt"`
@@ -163,6 +178,7 @@ type ExecuteRequest struct {
HandoffContext string `json:"handoff_context,omitempty"` // Model-only context for scoped handoffs; not persisted as user-authored text.
HandoffResources []HandoffResource `json:"handoff_resources,omitempty"` // Product-originated resources to seed governed session validation.
HandoffActions []HandoffAction `json:"handoff_actions,omitempty"` // Product-originated approval/action references for model-only review context.
+ HandoffMetadata HandoffMetadata `json:"handoff_metadata,omitempty"` // Browser-safe identity for restoring saved product handoffs.
MaxTurns int `json:"max_turns,omitempty"` // Override max agentic turns (0 = use default)
AutonomousMode *bool `json:"autonomous_mode,omitempty"` // Per-request autonomous override (nil = use service default)
}
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 217513f6c0..43b20e8ef0 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -783,6 +783,7 @@ type ChatRequest struct {
HandoffContext string `json:"handoff_context,omitempty"`
HandoffResources []chat.HandoffResource `json:"handoff_resources,omitempty"`
HandoffActions []chat.HandoffAction `json:"handoff_actions,omitempty"`
+ HandoffMetadata chat.HandoffMetadata `json:"handoff_metadata,omitempty"`
AutonomousMode *bool `json:"autonomous_mode,omitempty"`
}
@@ -792,16 +793,16 @@ const (
chatRequestHandoffActionLimit = 4
)
-func chatAutonomousModeForScopedHandoff(requested *bool, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction) *bool {
- if strings.TrimSpace(handoffContext) == "" && len(handoffResources) == 0 && len(handoffActions) == 0 {
+func chatAutonomousModeForScopedHandoff(requested *bool, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction, handoffMetadata chat.HandoffMetadata) *bool {
+ if strings.TrimSpace(handoffContext) == "" && len(handoffResources) == 0 && len(handoffActions) == 0 && chat.NormalizeHandoffMetadata(handoffMetadata) == (chat.HandoffMetadata{}) {
return requested
}
approvalRequired := false
return &approvalRequired
}
-func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction) *bool {
- return chatAutonomousModeForScopedHandoff(requested, handoffContext, handoffResources, handoffActions)
+func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction, handoffMetadata chat.HandoffMetadata) *bool {
+ return chatAutonomousModeForScopedHandoff(requested, handoffContext, handoffResources, handoffActions, handoffMetadata)
}
func normalizeChatRequestHandoffContext(raw string) string {
@@ -2508,6 +2509,7 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
handoffContext := normalizeChatRequestHandoffContext(req.HandoffContext)
handoffResources := normalizeChatRequestHandoffResources(req.HandoffResources)
handoffActions := normalizeChatRequestHandoffActions(req.HandoffActions)
+ handoffMetadata := chat.NormalizeHandoffMetadata(req.HandoffMetadata)
requestHandoffContext := handoffContext
requestHandoffResources := handoffResources
requestHandoffActions := handoffActions
@@ -2529,6 +2531,7 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
handoffActions = mergeUnifiedFindingRequestHandoffActions(f, buildUnifiedFindingHandoffActions(f, orgID), requestHandoffActions)
handoffContext = mergeUnifiedFindingRequestHandoffContext(buildUnifiedFindingChatContext(f, store, handoffActions), requestHandoffContext, f.ID)
handoffResources = mergeUnifiedFindingRequestHandoffResources(f, buildUnifiedFindingHandoffResources(f, store), requestHandoffResources)
+ handoffMetadata = chat.HandoffMetadata{}
}
}
if !findingResolved {
@@ -2541,6 +2544,7 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
handoffContext = ""
handoffResources = nil
handoffActions = nil
+ handoffMetadata = chat.HandoffMetadata{}
}
}
@@ -2555,7 +2559,8 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
HandoffContext: handoffContext,
HandoffResources: handoffResources,
HandoffActions: handoffActions,
- AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions),
+ HandoffMetadata: handoffMetadata,
+ AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions, handoffMetadata),
}, func(event chat.StreamEvent) {
if event.Type == "done" {
serviceSentDone = true
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 066d25c8a2..b38eaf159e 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -627,6 +627,41 @@ func TestHandleChat_PassesScopedHandoffContext(t *testing.T) {
assert.Equal(t, http.StatusOK, w.Code)
}
+func TestHandleChat_PassesPatrolRunHandoffMetadata(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 run", reqArg.Prompt)
+ assert.Equal(t, "", reqArg.FindingID)
+ assert.Equal(t, chat.HandoffMetadata{
+ Kind: "patrol_run",
+ RunID: "run-runtime-error",
+ RunType: "Scoped run",
+ RunStatus: "error",
+ RuntimeFailure: true,
+ }, reqArg.HandoffMetadata)
+ if assert.NotNil(t, reqArg.AutonomousMode) {
+ assert.False(t, *reqArg.AutonomousMode)
+ }
+ })
+
+ body := `{"prompt":"discuss run","autonomous_mode":true,"handoff_metadata":{"kind":"patrol_run","run_id":" run-runtime-error ","run_type":" Scoped run ","run_status":" error ","runtime_failure":true}}`
+ 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/internal/api/contract_test.go b/internal/api/contract_test.go
index e84dded01a..8c68f2ede1 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -188,7 +188,9 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
`svc.GetModelHandoffFindingID(ctx, req.SessionID)`,
`svc.ClearModelHandoffContext(ctx, sessionID)`,
`HandoffActions []chat.HandoffAction ` + "`json:\"handoff_actions,omitempty\"`",
+ `HandoffMetadata chat.HandoffMetadata ` + "`json:\"handoff_metadata,omitempty\"`",
"handoffActions := normalizeChatRequestHandoffActions(req.HandoffActions)",
+ "handoffMetadata := chat.NormalizeHandoffMetadata(req.HandoffMetadata)",
"chatRequestHandoffActionLimit",
"requestHandoffContext := handoffContext",
"requestHandoffResources := handoffResources",
@@ -202,8 +204,8 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
"chat.HydrateHandoffActionFromApproval(&action, liveApproval)",
"ApprovalRequestedAt",
"ApprovalExpiresAt",
- "func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction) *bool",
- "AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions)",
+ "func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction, handoffMetadata chat.HandoffMetadata) *bool",
+ "AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions, handoffMetadata)",
`appendChatContextLine(&b, "Finding Status", unifiedFindingChatStatus(f, time.Now()))`,
`appendChatContextLine(&b, "Finding Detected At", f.DetectedAt.Format(time.RFC3339))`,
`appendChatContextLine(&b, "Finding Last Seen At", f.LastSeenAt.Format(time.RFC3339))`,
@@ -250,6 +252,7 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
"HandoffContext:",
"HandoffResources: handoffResources",
"HandoffActions: handoffActions",
+ "HandoffMetadata: handoffMetadata",
} {
if !strings.Contains(handlerText, required) {
t.Fatalf("ai_handler.go must preserve model-only finding handoff contract: missing %q", required)
@@ -263,13 +266,13 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
for _, required := range []string{
"handoffContext := strings.TrimSpace(req.HandoffContext)",
"handoffFindingID := strings.TrimSpace(req.FindingID)",
- "sessions.SetModelHandoffFindingID(session.ID, handoffFindingID)",
+ "handoffMetadata := NormalizeHandoffMetadata(req.HandoffMetadata)",
+ "hasRequestHandoffEnvelope",
+ "sessions.SetModelHandoffEnvelope(session.ID, handoffFindingID, handoffContext, handoffResources, handoffActions, handoffMetadata)",
"ClearModelHandoffContext",
"handoffResources := normalizeHandoffResources(req.HandoffResources)",
- "sessions.SetModelHandoffContext(session.ID, handoffContext)",
"GetModelHandoffFindingID",
"sessions.GetModelHandoffContext(session.ID)",
- "sessions.SetModelHandoffResources(session.ID, handoffResources)",
"sessions.GetModelHandoffResources(session.ID)",
"sessions.SetModelHandoffActions(session.ID, handoffActions)",
"sessions.GetModelHandoffActions(session.ID)",
@@ -311,6 +314,7 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
for _, required := range []string{
"ModelContext *sessionModelContext",
"SetModelHandoffFindingID",
+ "SetModelHandoffEnvelope",
"GetModelHandoffFindingID",
"ClearModelHandoffContext",
"HandoffFindingID string",
@@ -322,6 +326,8 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
"SetModelHandoffActions",
"GetModelHandoffActions",
"HandoffActions []HandoffAction",
+ "SetModelHandoffMetadata",
+ "HandoffMetadata HandoffMetadata",
} {
if !strings.Contains(chatSessionText, required) {
t.Fatalf("chat session store must persist model-only handoff metadata outside messages: missing %q", required)
@@ -334,6 +340,8 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
"HandoffResources []HandoffResource",
"type HandoffAction struct",
"HandoffActions []HandoffAction",
+ "type HandoffMetadata struct",
+ "HandoffMetadata HandoffMetadata",
"ApprovalStatus",
"ActionID",
"ActionState",
diff --git a/tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts b/tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts
index 32ed96d09f..edce47bcd8 100644
--- a/tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts
+++ b/tests/integration/tests/73-patrol-assistant-operator-briefing.spec.ts
@@ -97,6 +97,29 @@ test.describe("Patrol Assistant operator briefing", () => {
updated_at: "2026-05-06T12:09:00Z",
},
};
+ const patrolRunHandoffSession = {
+ id: "session-patrol-run",
+ title: "Runtime failure follow-up",
+ created_at: "2026-05-06T12:04:00Z",
+ updated_at: "2026-05-06T12:10:00Z",
+ message_count: 1,
+ handoff_summary: {
+ kind: "patrol_run",
+ run_id: "run-runtime-error",
+ run_type: "Scoped run",
+ run_status: "error",
+ runtime_failure: true,
+ has_model_context: true,
+ resource_count: 1,
+ primary_resource: {
+ id: "vm-100",
+ type: "vm",
+ },
+ action_count: 0,
+ requires_approval: false,
+ updated_at: "2026-05-06T12:10:00Z",
+ },
+ };
await page.route("**/api/security/status", async (route) => {
await route.fulfill({
@@ -193,7 +216,11 @@ test.describe("Patrol Assistant operator briefing", () => {
await route.fulfill({
status: 200,
contentType: "application/json",
- body: JSON.stringify([handoffSession, contextOnlyHandoffSession]),
+ body: JSON.stringify([
+ handoffSession,
+ contextOnlyHandoffSession,
+ patrolRunHandoffSession,
+ ]),
});
});
@@ -607,7 +634,31 @@ test.describe("Patrol Assistant operator briefing", () => {
"Finding finding-context-only",
);
await expect(
- contextOnlyAssistantContext.getByText("systemctl restart workload.service"),
+ contextOnlyAssistantContext.getByText(
+ "systemctl restart workload.service",
+ ),
+ ).toHaveCount(0);
+
+ await page.getByTitle("Pulse Assistant sessions").click();
+ await expect(page.getByText("Runtime failure follow-up")).toBeVisible();
+ await expect(page.getByText("Runtime issue").last()).toBeVisible();
+ await expect(page.getByText(/run error/).last()).toBeVisible();
+ await page.getByText("Runtime failure follow-up").click();
+
+ const runAssistantContext = page.getByLabel("Assistant context");
+ await expect(runAssistantContext).toBeVisible();
+ await expect(runAssistantContext).toContainText(
+ "Patrol run run-runtime-error",
+ );
+ await expect(runAssistantContext).toContainText("Run run-runtime-error");
+ await expect(runAssistantContext).toContainText("Run type: Scoped run");
+ await expect(runAssistantContext).toContainText("Run state: run error");
+ await expect(runAssistantContext).toContainText(
+ "Review Patrol runtime issue",
+ );
+ await expect(runAssistantContext.getByText("tool_choice")).toHaveCount(0);
+ await expect(
+ runAssistantContext.getByText("No endpoints found"),
).toHaveCount(0);
includePendingApproval = false;