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.

Remove Assistant status routing residue

rcourtman99fce8e5a3c0
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 58969ea9f3..896ff7266c 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -2956,7 +2956,7 @@
},
{
"id": "RA29",
- "summary": "Interactive Pulse Assistant chat behaves like a governed LLM tool surface, not a Pulse-authored intent router: the operator's selected model receives the user turn and governed tools, decides whether tools are needed, and Pulse must not use prompt heuristics to force tool_choice, force a named tool, retry because an expected tool was not used, or hide tools from the model by keyword detection. Pulse only enforces approvals, resource resolution, FSM gates, and tool policy after that model choice. The chat surface must echo user messages before network/session creation finishes and must not emit Pulse-owned explore or synthetic investigating workflow events before the model acts.",
+ "summary": "Interactive Pulse Assistant chat behaves like a governed LLM tool surface, not a Pulse-authored intent router: the operator's selected model receives the user turn and governed tools, decides whether tools are needed, and Pulse must not use prompt heuristics to force tool_choice, force a named tool, retry because an expected tool was not used, hide tools from the model by keyword detection, or rewrite recent-context turns into Pulse-targeted instructions. Pulse only provides context and enforces approvals, resource resolution, FSM gates, and tool policy after that model choice. The chat surface must echo user messages before network/session creation finishes and must not render Pulse-owned explore or internal workflow status cards as assistant output.",
"kind": "invariant",
"blocking_level": "repo-ready",
"proof_type": "automated",
@@ -2988,7 +2988,31 @@
"test",
"--",
"--run",
- "src/components/AI/Chat/__tests__/useChat.test.ts"
+ "src/components/AI/Chat/__tests__/useChat.test.ts",
+ "src/components/AI/Chat/__tests__/MessageItem.test.tsx"
+ ]
+ },
+ {
+ "id": "assistant-chat-stream-contract-tests",
+ "run": [
+ "npm",
+ "--prefix",
+ "frontend-modern",
+ "test",
+ "--",
+ "--run",
+ "src/api/__tests__/aiChatEvents.test.ts"
+ ]
+ },
+ {
+ "id": "assistant-neutral-session-context-tests",
+ "run": [
+ "go",
+ "test",
+ "./internal/ai/chat",
+ "-run",
+ "TestInjectRecentSessionContext",
+ "-count=1"
]
},
{
@@ -3025,6 +3049,31 @@
"path": "docs/release-control/v6/internal/subsystems/ai-runtime.md",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/subsystems/api-contracts.md",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/subsystems/registry.json",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/api/__tests__/aiChatEvents.test.ts",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/api/generated/aiChatEvents.ts",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts",
@@ -3035,6 +3084,21 @@
"path": "frontend-modern/src/components/AI/Chat/hooks/useChat.ts",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/components/AI/Chat/MessageItem.tsx",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/components/AI/Chat/types.ts",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/ai/chat/agentic.go",
@@ -3050,6 +3114,11 @@
"path": "internal/ai/chat/agentic_final.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/ai/chat/read_routing_hints.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/ai/chat/service.go",
@@ -3060,11 +3129,21 @@
"path": "internal/ai/chat/service_execute_additional_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/ai/chat/service_recent_context_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/ai/chat/service_tooling_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/ai/chat/types.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/ai/tools/tools_file.go",
@@ -3084,6 +3163,16 @@
"repo": "pulse",
"path": "internal/ai/tools/tools_read_test.go",
"kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/api/contract_test.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "scripts/generate-types.go",
+ "kind": "file"
}
]
}
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 60b91be464..ce8bf4afe3 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -34,15 +34,14 @@ runtime cost control, and shared AI transport surfaces.
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`
+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`
## Shared Boundaries
@@ -76,7 +75,7 @@ runtime cost control, and shared AI transport surfaces.
require an explicit `allow_broad_scope` request from a dedicated rule
management surface.
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 streamed-status 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`
+6. Add or change AI provider, control-level, or chat/session 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`, and `frontend-modern/src/utils/aiSessionDiffPresentation.ts`
7. Keep AI chat presentation helpers aligned through `frontend-modern/src/components/AI/Chat/` and the shared `frontend-modern/src/utils/textPresentation.ts`
8. Keep assistant drawer context, session, and org-switch reset state aligned through the shared `frontend-modern/src/stores/aiChat.ts` boundary instead of letting `frontend-modern/src/App.tsx`, `frontend-modern/src/AppLayout.tsx`, or feature callers fork their own assistant shell state
That shared drawer ownership also covers passive resource reads while the
@@ -979,6 +978,11 @@ context, or request an action. Pulse must not use prompt heuristics to force
used, or hide tools from the model based on keyword detection. Pulse
enforcement starts after that model choice: approval mode, FSM gates, strict
resource resolution, and tool policy remain the safety boundary.
+Session continuity context follows the same boundary: Pulse may provide
+neutral recent-resource facts and explicit resource addressing facts, but it
+must not use prompt-keyword or pronoun heuristics to rewrite a user message as
+targeted, inject log-routing instructions, or tell the model which context is
+the answer.
The same runtime ownership now includes the customer-facing AI usage and cost
surface. `frontend-modern/src/components/AI/AICostDashboard.tsx` is the
@@ -993,14 +997,18 @@ helpers used across chat, settings, and usage surfaces.
`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` are the canonical owners
+`frontend-modern/src/utils/aiSessionDiffPresentation.ts` are the canonical owners
for provider naming, provider health labels, control-level semantics,
chat drawer title/subtitle, launcher title/aria copy, session-menu labeling,
discovery hint framing, chat/session empty states, assistant message and
-question-card labels, session-diff badges, and streamed-status labels.
+question-card labels, and session-diff badges.
Settings and chat surfaces must consume those helpers instead of keeping local
AI wording or model/provider inference branches.
+Assistant chat must not render Pulse-authored explore pre-pass cards or
+internal workflow-state cards as assistant output. The user-facing stream is
+model text, model thinking where supported, model-selected tool calls, governed
+approval requests, and model questions; internal runtime telemetry stays out of
+the chat transcript.
The AI transport files are shared with `api-contracts`, not delegated away to
it. `frontend-modern/src/api/ai.ts`,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index aabb4c8703..d08649f475 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -236,6 +236,12 @@ checks, merge tenants, or become the source of truth for telemetry freshness.
actions when the run cannot be resolved. Stored session metadata must be
readable by the handler so follow-up turns can rehydrate the same backend
context without asking the browser to resend provider-bound payloads.
+ Chat stream events are generated from `internal/ai/chat` payload structs
+ into `frontend-modern/src/api/generated/aiChatEvents.ts`; that generated
+ union must not include the retired `explore_status` pre-pass event. Runtime
+ workflow telemetry may remain a transport event, but browser Assistant
+ output is owned by the AI runtime presentation contract rather than by
+ API-client event typing.
34. `internal/api/ai_handlers.go` shared with `ai-runtime`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.
Provider test responses from `/api/ai/test` and provider-specific
`/api/ai/test/{provider}` preflight responses must return one safe
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 61e5ee6304..dbb97f7cc5 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -1142,7 +1142,6 @@
"frontend-modern/src/utils/aiChatPresentation.ts",
"frontend-modern/src/utils/aiControlLevelPresentation.ts",
"frontend-modern/src/utils/aiCostPresentation.ts",
- "frontend-modern/src/utils/aiExplorePresentation.ts",
"frontend-modern/src/utils/aiProviderHealthPresentation.ts",
"frontend-modern/src/utils/aiProviderPresentation.ts",
"frontend-modern/src/utils/aiSessionDiffPresentation.ts",
@@ -1221,7 +1220,6 @@
"match_files": [
"frontend-modern/src/utils/aiChatPresentation.ts",
"frontend-modern/src/utils/aiControlLevelPresentation.ts",
- "frontend-modern/src/utils/aiExplorePresentation.ts",
"frontend-modern/src/utils/aiProviderHealthPresentation.ts",
"frontend-modern/src/utils/aiProviderPresentation.ts",
"frontend-modern/src/utils/aiSessionDiffPresentation.ts"
@@ -1231,7 +1229,6 @@
"exact_files": [
"frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts",
"frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts",
- "frontend-modern/src/utils/__tests__/aiExplorePresentation.test.ts",
"frontend-modern/src/utils/__tests__/aiProviderHealthPresentation.test.ts",
"frontend-modern/src/utils/__tests__/aiProviderPresentation.test.ts",
"frontend-modern/src/utils/__tests__/aiSessionDiffPresentation.test.ts",
diff --git a/frontend-modern/src/api/__tests__/aiChatEvents.test.ts b/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
new file mode 100644
index 0000000000..b5a6afda53
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from 'vitest';
+import aiChatEventsSource from '@/api/generated/aiChatEvents.ts?raw';
+
+describe('AI chat stream event contract', () => {
+ it('does not expose the retired explore pre-pass stream event', () => {
+ expect(aiChatEventsSource).not.toContain('ExploreStatusData');
+ expect(aiChatEventsSource).not.toContain("type: 'explore_status'");
+ });
+});
diff --git a/frontend-modern/src/api/generated/aiChatEvents.ts b/frontend-modern/src/api/generated/aiChatEvents.ts
index e6dece14e8..dcad190e5c 100644
--- a/frontend-modern/src/api/generated/aiChatEvents.ts
+++ b/frontend-modern/src/api/generated/aiChatEvents.ts
@@ -63,13 +63,6 @@ export interface ErrorData {
message: string;
}
-export interface ExploreStatusData {
- phase: string;
- message: string;
- model?: string;
- outcome?: string;
-}
-
export interface Question {
id: string;
type?: string;
@@ -120,7 +113,6 @@ export interface WorkflowStateData {
export type AIChatStreamEvent =
| { type: 'content'; data: ContentData }
| { type: 'thinking'; data: ThinkingData }
- | { type: 'explore_status'; data: ExploreStatusData }
| { type: 'workflow_state'; data: WorkflowStateData }
| { type: 'tool_start'; data: ToolStartData }
| { type: 'tool_end'; data: ToolEndData }
diff --git a/frontend-modern/src/components/AI/Chat/ExploreStatusBlock.tsx b/frontend-modern/src/components/AI/Chat/ExploreStatusBlock.tsx
deleted file mode 100644
index 9cb6c2cadb..0000000000
--- a/frontend-modern/src/components/AI/Chat/ExploreStatusBlock.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { type Component } from 'solid-js';
-import type { ExploreStatus } from './types';
-import { getAIExploreStatusPresentation } from '@/utils/aiExplorePresentation';
-
-interface ExploreStatusBlockProps {
- status: ExploreStatus;
-}
-
-export const ExploreStatusBlock: Component<ExploreStatusBlockProps> = (props) => {
- const presentation = () => getAIExploreStatusPresentation(props.status.phase);
-
- return (
- <div class={`my-2 rounded-md border px-3 py-2 text-xs ${presentation().classes}`}>
- <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
- <span class="font-semibold tracking-wide uppercase">{presentation().label}</span>
- {props.status.model && <span class="font-mono opacity-80">{props.status.model}</span>}
- {props.status.outcome && (
- <span class="font-mono opacity-75">outcome={props.status.outcome}</span>
- )}
- </div>
- <p class="mt-1 leading-relaxed">{props.status.message}</p>
- </div>
- );
-};
diff --git a/frontend-modern/src/components/AI/Chat/MessageItem.tsx b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
index 816db22cbf..12da74245d 100644
--- a/frontend-modern/src/components/AI/Chat/MessageItem.tsx
+++ b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
@@ -1,8 +1,6 @@
import { Component, Show, For, Switch, Match, createMemo } from 'solid-js';
import { renderMarkdown } from '../aiChatUtils';
import { ThinkingBlock } from './ThinkingBlock';
-import { ExploreStatusBlock } from './ExploreStatusBlock';
-import { WorkflowStatusBlock } from './WorkflowStatusBlock';
import { ToolExecutionBlock } from './ToolExecutionBlock';
import { ApprovalCard } from './ApprovalCard';
import { QuestionCard } from './QuestionCard';
@@ -48,18 +46,6 @@ export const MessageItem: Component<MessageItemProps> = (props) => {
continue;
}
- // Explore status events are kept separate
- if (evt.type === 'explore_status') {
- grouped.push(evt);
- continue;
- }
-
- // Workflow status events are kept separate
- if (evt.type === 'workflow') {
- grouped.push(evt);
- continue;
- }
-
// Tool events are kept separate
if (evt.type === 'tool') {
grouped.push(evt);
@@ -174,14 +160,6 @@ export const MessageItem: Component<MessageItemProps> = (props) => {
/>
</Match>
- <Match when={evt.type === 'explore_status' && evt.exploreStatus}>
- <ExploreStatusBlock status={evt.exploreStatus!} />
- </Match>
-
- <Match when={evt.type === 'workflow' && evt.workflow}>
- <WorkflowStatusBlock status={evt.workflow!} />
- </Match>
-
<Match when={evt.type === 'pending_tool' && evt.pendingTool}>
<></>
</Match>
diff --git a/frontend-modern/src/components/AI/Chat/WorkflowStatusBlock.tsx b/frontend-modern/src/components/AI/Chat/WorkflowStatusBlock.tsx
deleted file mode 100644
index 4c2dfcc6e5..0000000000
--- a/frontend-modern/src/components/AI/Chat/WorkflowStatusBlock.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-import { type Component } from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-import CircleCheckIcon from 'lucide-solid/icons/circle-check';
-import CircleDashedIcon from 'lucide-solid/icons/circle-dashed';
-import ClipboardCheckIcon from 'lucide-solid/icons/clipboard-check';
-import HelpCircleIcon from 'lucide-solid/icons/help-circle';
-import PlayIcon from 'lucide-solid/icons/play';
-import SearchIcon from 'lucide-solid/icons/search';
-import ShieldCheckIcon from 'lucide-solid/icons/shield-check';
-import type { WorkflowStatus } from './types';
-import { formatIdentifierLabel } from '@/utils/textPresentation';
-
-interface WorkflowStatusBlockProps {
- status: WorkflowStatus;
-}
-
-const phasePresentation = (phase: string) => {
- switch (phase) {
- case 'investigate':
- return {
- label: 'Investigating',
- classes:
- 'border-blue-200 bg-blue-50 text-blue-800 dark:border-blue-800 dark:bg-blue-950/40 dark:text-blue-200',
- Icon: SearchIcon,
- };
- case 'clarify':
- return {
- label: 'Clarifying',
- classes:
- 'border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-800 dark:bg-sky-950/40 dark:text-sky-200',
- Icon: HelpCircleIcon,
- };
- case 'plan':
- return {
- label: 'Planning',
- classes:
- 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-200',
- Icon: ClipboardCheckIcon,
- };
- case 'approve':
- return {
- label: 'Awaiting Approval',
- classes:
- 'border-orange-200 bg-orange-50 text-orange-800 dark:border-orange-800 dark:bg-orange-950/40 dark:text-orange-200',
- Icon: ShieldCheckIcon,
- };
- case 'execute':
- return {
- label: 'Executing',
- classes:
- 'border-indigo-200 bg-indigo-50 text-indigo-800 dark:border-indigo-800 dark:bg-indigo-950/40 dark:text-indigo-200',
- Icon: PlayIcon,
- };
- case 'verify':
- return {
- label: 'Verifying',
- classes:
- 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200',
- Icon: CircleDashedIcon,
- };
- case 'complete':
- return {
- label: 'Complete',
- classes:
- 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200',
- Icon: CircleCheckIcon,
- };
- default:
- return {
- label: formatIdentifierLabel(phase || 'workflow'),
- classes:
- 'border-border-subtle bg-surface text-base-content dark:border-border-subtle dark:bg-surface',
- Icon: CircleDashedIcon,
- };
- }
-};
-
-export const WorkflowStatusBlock: Component<WorkflowStatusBlockProps> = (props) => {
- const presentation = () => phasePresentation(props.status.phase);
- const toolLabel = () =>
- props.status.tool ? formatIdentifierLabel(props.status.tool, { stripPrefix: 'pulse_' }) : '';
-
- return (
- <div class={`my-2 rounded-md border px-3 py-2 text-xs ${presentation().classes}`}>
- <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
- <Dynamic component={presentation().Icon} class="h-3.5 w-3.5" />
- <span class="font-semibold uppercase">{presentation().label}</span>
- {toolLabel() && <span class="font-mono opacity-80">{toolLabel()}</span>}
- {props.status.state && <span class="font-mono opacity-75">state={props.status.state}</span>}
- </div>
- <p class="mt-1 leading-relaxed">{props.status.message}</p>
- </div>
- );
-};
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/ExploreStatusBlock.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/ExploreStatusBlock.test.tsx
deleted file mode 100644
index b30eed876d..0000000000
--- a/frontend-modern/src/components/AI/Chat/__tests__/ExploreStatusBlock.test.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { afterEach } from 'vitest';
-import { ExploreStatusBlock } from '../ExploreStatusBlock';
-import type { ExploreStatus } from '../types';
-
-afterEach(cleanup);
-
-function makeStatus(overrides?: Partial<ExploreStatus>): ExploreStatus {
- return {
- phase: 'started',
- message: 'Exploring infrastructure...',
- ...overrides,
- };
-}
-
-describe('ExploreStatusBlock', () => {
- // --- Phase label rendering ---
-
- it('renders "Explore Started" for started phase', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ phase: 'started' })} />);
- expect(screen.getByText('Explore Started')).toBeInTheDocument();
- });
-
- it('renders "Explore Completed" for completed phase', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ phase: 'completed' })} />);
- expect(screen.getByText('Explore Completed')).toBeInTheDocument();
- });
-
- it('renders "Explore Failed" for failed phase', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ phase: 'failed' })} />);
- expect(screen.getByText('Explore Failed')).toBeInTheDocument();
- });
-
- it('renders "Explore Skipped" for skipped phase', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ phase: 'skipped' })} />);
- expect(screen.getByText('Explore Skipped')).toBeInTheDocument();
- });
-
- it('renders "Explore Status" for unknown phase', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ phase: 'unknown_phase' })} />);
- expect(screen.getByText('Explore Status')).toBeInTheDocument();
- });
-
- // --- Message rendering ---
-
- it('renders the status message', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ message: 'Scanning 12 nodes...' })} />);
- expect(screen.getByText('Scanning 12 nodes...')).toBeInTheDocument();
- });
-
- // --- Optional model field ---
-
- it('renders model name when provided', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ model: 'gpt-4o' })} />);
- expect(screen.getByText('gpt-4o')).toBeInTheDocument();
- });
-
- it('does not render model span when model is undefined', () => {
- const { container } = render(() => (
- <ExploreStatusBlock status={makeStatus({ model: undefined })} />
- ));
- // With no model and no outcome, the header row should only contain the phase label
- const headerRow = container.querySelector('.flex');
- expect(headerRow).not.toBeNull();
- expect(headerRow!.children.length).toBe(1); // only phase label span
- });
-
- // --- Optional outcome field ---
-
- it('renders outcome when provided', () => {
- render(() => <ExploreStatusBlock status={makeStatus({ outcome: 'success' })} />);
- expect(screen.getByText('outcome=success')).toBeInTheDocument();
- });
-
- it('does not render outcome when undefined', () => {
- const { container } = render(() => (
- <ExploreStatusBlock status={makeStatus({ outcome: undefined })} />
- ));
- expect(container.textContent).not.toContain('outcome=');
- });
-
- it('renders both model and outcome together', () => {
- render(() => (
- <ExploreStatusBlock status={makeStatus({ model: 'claude-3', outcome: 'partial' })} />
- ));
- expect(screen.getByText('claude-3')).toBeInTheDocument();
- expect(screen.getByText('outcome=partial')).toBeInTheDocument();
- });
-
- // --- CSS class application per phase ---
-
- it('applies emerald classes for completed phase', () => {
- const { container } = render(() => (
- <ExploreStatusBlock status={makeStatus({ phase: 'completed' })} />
- ));
- const block = container.firstElementChild as HTMLElement;
- expect(block.classList.contains('bg-emerald-50')).toBe(true);
- expect(block.classList.contains('border-emerald-200')).toBe(true);
- });
-
- it('applies rose classes for failed phase', () => {
- const { container } = render(() => (
- <ExploreStatusBlock status={makeStatus({ phase: 'failed' })} />
- ));
- const block = container.firstElementChild as HTMLElement;
- expect(block.classList.contains('bg-rose-50')).toBe(true);
- expect(block.classList.contains('border-rose-200')).toBe(true);
- });
-
- it('applies amber classes for skipped phase', () => {
- const { container } = render(() => (
- <ExploreStatusBlock status={makeStatus({ phase: 'skipped' })} />
- ));
- const block = container.firstElementChild as HTMLElement;
- expect(block.classList.contains('bg-amber-50')).toBe(true);
- expect(block.classList.contains('border-amber-200')).toBe(true);
- });
-
- it('applies sky classes for started phase', () => {
- const { container } = render(() => (
- <ExploreStatusBlock status={makeStatus({ phase: 'started' })} />
- ));
- const block = container.firstElementChild as HTMLElement;
- expect(block.classList.contains('bg-sky-50')).toBe(true);
- expect(block.classList.contains('border-sky-200')).toBe(true);
- });
-
- it('applies sky (default) classes for unrecognized phase', () => {
- const { container } = render(() => (
- <ExploreStatusBlock status={makeStatus({ phase: 'some_new_phase' })} />
- ));
- const block = container.firstElementChild as HTMLElement;
- expect(block.classList.contains('bg-sky-50')).toBe(true);
- });
-
- // --- Empty string edge cases ---
-
- it('renders empty message without crashing', () => {
- const { container } = render(() => <ExploreStatusBlock status={makeStatus({ message: '' })} />);
- // The wrapper and message paragraph should still render
- expect(container.firstElementChild).not.toBeNull();
- const messageParagraph = container.querySelector('p');
- expect(messageParagraph).not.toBeNull();
- expect(messageParagraph!.textContent).toBe('');
- });
-
- it('does not render model span for empty string (falsy)', () => {
- // Empty string is falsy in JS, so model span should NOT render
- const { container } = render(() => <ExploreStatusBlock status={makeStatus({ model: '' })} />);
- const headerRow = container.querySelector('.flex');
- expect(headerRow).not.toBeNull();
- // Only phase label span should be present (no model, no outcome)
- expect(headerRow!.children.length).toBe(1);
- });
-
- it('renders empty outcome string (falsy, should not show outcome)', () => {
- const { container } = render(() => <ExploreStatusBlock status={makeStatus({ outcome: '' })} />);
- expect(container.textContent).not.toContain('outcome=');
- });
-});
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
index e47f16643d..87a97670de 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
@@ -12,18 +12,6 @@ vi.mock('../ThinkingBlock', () => ({
),
}));
-vi.mock('../ExploreStatusBlock', () => ({
- ExploreStatusBlock: (props: { status: { phase: string; message: string } }) => (
- <div data-testid="explore-status-block">{props.status.message}</div>
- ),
-}));
-
-vi.mock('../WorkflowStatusBlock', () => ({
- WorkflowStatusBlock: (props: { status: { phase: string; message: string } }) => (
- <div data-testid="workflow-status-block">{props.status.message}</div>
- ),
-}));
-
vi.mock('../ToolExecutionBlock', () => ({
ToolExecutionBlock: (props: {
tool: { name: string; input: string; output: string; success: boolean };
@@ -352,51 +340,6 @@ describe('MessageItem', () => {
expect(block.getAttribute('data-streaming')).toBe('true');
});
- it('renders explore status blocks', () => {
- const events: StreamDisplayEvent[] = [
- {
- type: 'explore_status',
- exploreStatus: { phase: 'scanning', message: 'Scanning infrastructure...' },
- },
- ];
-
- render(() => (
- <MessageItem
- message={makeMessage({ role: 'assistant', streamEvents: events })}
- {...makeHandlers()}
- />
- ));
-
- expect(screen.getByTestId('explore-status-block')).toBeInTheDocument();
- expect(screen.getByText('Scanning infrastructure...')).toBeInTheDocument();
- });
-
- it('renders workflow status blocks', () => {
- const events: StreamDisplayEvent[] = [
- {
- type: 'workflow',
- workflow: {
- phase: 'approve',
- message: 'Waiting for approval before executing the planned action.',
- state: 'VERIFYING',
- tool: 'pulse_exec',
- },
- },
- ];
-
- render(() => (
- <MessageItem
- message={makeMessage({ role: 'assistant', streamEvents: events })}
- {...makeHandlers()}
- />
- ));
-
- expect(screen.getByTestId('workflow-status-block')).toBeInTheDocument();
- expect(
- screen.getByText('Waiting for approval before executing the planned action.'),
- ).toBeInTheDocument();
- });
-
it('renders tool execution blocks', () => {
const events: StreamDisplayEvent[] = [
{
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 7a8a1fe042..d4eb1d68ec 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -464,7 +464,7 @@ describe('useChat', () => {
dispose();
});
- it('processes explore_status events', async () => {
+ it('ignores product telemetry events that are not the model response', async () => {
const { getFireEvent } = setupWithEventCapture();
const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
@@ -474,49 +474,11 @@ describe('useChat', () => {
fire({
type: 'explore_status',
data: {
- phase: 'investigating',
- message: 'Checking logs',
+ phase: 'started',
+ message: 'Explore pre-pass running',
model: 'claude-3',
- outcome: 'ok',
},
- });
-
- const assistant = chat.messages().find((m) => m.role === 'assistant')!;
- const exploreEvents =
- assistant.streamEvents?.filter((e) => e.type === 'explore_status') ?? [];
- expect(exploreEvents).toHaveLength(1);
- expect(exploreEvents[0].exploreStatus).toEqual({
- phase: 'investigating',
- message: 'Checking logs',
- model: 'claude-3',
- outcome: 'ok',
- });
- dispose();
- });
-
- it('ignores explore_status with empty message', async () => {
- const { getFireEvent } = setupWithEventCapture();
- const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
-
- await chat.sendMessage('hi');
- const fire = getFireEvent();
-
- fire({ type: 'explore_status', data: { phase: 'x', message: ' ' } });
-
- const assistant = chat.messages().find((m) => m.role === 'assistant')!;
- const exploreEvents =
- assistant.streamEvents?.filter((e) => e.type === 'explore_status') ?? [];
- expect(exploreEvents).toHaveLength(0);
- dispose();
- });
-
- it('processes workflow_state events', async () => {
- const { getFireEvent } = setupWithEventCapture();
- const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
-
- await chat.sendMessage('hi');
- const fire = getFireEvent();
-
+ } as any);
fire({
type: 'workflow_state',
data: {
@@ -528,14 +490,8 @@ describe('useChat', () => {
});
const assistant = chat.messages().find((m) => m.role === 'assistant')!;
- const workflowEvents = assistant.streamEvents?.filter((e) => e.type === 'workflow') ?? [];
- expect(workflowEvents).toHaveLength(1);
- expect(workflowEvents[0].workflow).toEqual({
- phase: 'plan',
- message: 'Planning governed action and safety checks before execution.',
- state: 'READING',
- tool: 'pulse_exec',
- });
+ expect(assistant.content).toBe('');
+ expect(assistant.streamEvents).toEqual([]);
dispose();
});
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index fc13b295d7..60cdb2cd32 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -173,46 +173,6 @@ export function useChat(options: UseChatOptions = {}) {
};
}
- case 'explore_status': {
- const data = (event.data || {}) as {
- phase?: string;
- message?: string;
- model?: string;
- outcome?: string;
- };
- const message = typeof data.message === 'string' ? data.message.trim() : '';
- if (!message) return msg;
- return addStreamEvent(msg, {
- type: 'explore_status',
- exploreStatus: {
- phase: data.phase || 'unknown',
- message,
- model: data.model,
- outcome: data.outcome,
- },
- });
- }
-
- case 'workflow_state': {
- const data = (event.data || {}) as {
- phase?: string;
- message?: string;
- state?: string;
- tool?: string;
- };
- const message = typeof data.message === 'string' ? data.message.trim() : '';
- if (!message) return msg;
- return addStreamEvent(msg, {
- type: 'workflow',
- workflow: {
- phase: data.phase || 'unknown',
- message,
- state: data.state,
- tool: data.tool,
- },
- });
- }
-
case 'tool_start': {
const data = (event.data || {}) as {
id?: string;
diff --git a/frontend-modern/src/components/AI/Chat/types.ts b/frontend-modern/src/components/AI/Chat/types.ts
index 4ccb48dad8..402f06c13a 100644
--- a/frontend-modern/src/components/AI/Chat/types.ts
+++ b/frontend-modern/src/components/AI/Chat/types.ts
@@ -82,25 +82,9 @@ export interface PendingQuestion {
isAnswering?: boolean;
}
-export interface ExploreStatus {
- phase: string;
- message: string;
- model?: string;
- outcome?: string;
-}
-
-export interface WorkflowStatus {
- phase: string;
- message: string;
- state?: string;
- tool?: string;
-}
-
// Unified event for chronological display
export type StreamEventType =
| 'thinking'
- | 'explore_status'
- | 'workflow'
| 'tool'
| 'content'
| 'pending_tool'
@@ -110,8 +94,6 @@ export type StreamEventType =
export interface StreamDisplayEvent {
type: StreamEventType;
thinking?: string;
- exploreStatus?: ExploreStatus;
- workflow?: WorkflowStatus;
tool?: ToolExecution;
pendingTool?: PendingTool;
content?: string;
diff --git a/frontend-modern/src/utils/__tests__/aiExplorePresentation.test.ts b/frontend-modern/src/utils/__tests__/aiExplorePresentation.test.ts
deleted file mode 100644
index 8619159653..0000000000
--- a/frontend-modern/src/utils/__tests__/aiExplorePresentation.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { getAIExploreStatusPresentation } from '@/utils/aiExplorePresentation';
-
-describe('aiExplorePresentation', () => {
- it('returns started presentation', () => {
- expect(getAIExploreStatusPresentation('started')).toMatchObject({
- label: 'Explore Started',
- });
- expect(getAIExploreStatusPresentation('started').classes).toContain('bg-sky-50');
- });
-
- it('returns completed presentation', () => {
- expect(getAIExploreStatusPresentation('completed')).toMatchObject({
- label: 'Explore Completed',
- });
- expect(getAIExploreStatusPresentation('completed').classes).toContain('bg-emerald-50');
- });
-
- it('returns default presentation for unknown phases', () => {
- expect(getAIExploreStatusPresentation('something-new')).toMatchObject({
- label: 'Explore Status',
- });
- expect(getAIExploreStatusPresentation('something-new').classes).toContain('bg-sky-50');
- });
-});
diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
index 9f5a2da43c..7e27d1160a 100644
--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
@@ -329,8 +329,6 @@ import unifiedResourceTableModelSource from '@/components/Infrastructure/unified
import useUnifiedResourcesSource from '@/hooks/useUnifiedResources.ts?raw';
import useWorkloadsSource from '@/hooks/useWorkloads.ts?raw';
import findingsPanelSource from '@/components/AI/FindingsPanel.tsx?raw';
-import exploreStatusBlockSource from '@/components/AI/Chat/ExploreStatusBlock.tsx?raw';
-import aiExplorePresentationSource from '@/utils/aiExplorePresentation.ts?raw';
import discoveryTabSource from '@/components/Discovery/DiscoveryTab.tsx?raw';
import discoveryPresentationSource from '@/utils/discoveryPresentation.ts?raw';
import mailGatewaySource from '@/components/PMG/MailGateway.tsx?raw';
@@ -3144,10 +3142,6 @@ describe('frontend resource type boundaries', () => {
expect(unifiedResourceTableViewportSyncSource).toContain('getBoundingClientRect');
expect(unifiedResourceTableViewportSyncSource).toContain('hostWindowing.onScroll');
expect(unifiedResourceTableViewportSyncSource).not.toContain('scrollIntoView');
- expect(exploreStatusBlockSource).toContain('getAIExploreStatusPresentation');
- expect(exploreStatusBlockSource).not.toContain('const phaseLabel =');
- expect(exploreStatusBlockSource).not.toContain('const phaseClasses =');
- expect(aiExplorePresentationSource).toContain('export function getAIExploreStatusPresentation');
expect(discoveryTabSource).toContain('getDiscoveryURLSuggestionSourceLabel');
expect(discoveryTabSource).toContain('getDiscoveryAnalysisProviderBadgeClass');
expect(discoveryTabSource).toContain('getDiscoveryCategoryBadgeClass');
diff --git a/frontend-modern/src/utils/aiExplorePresentation.ts b/frontend-modern/src/utils/aiExplorePresentation.ts
deleted file mode 100644
index 4ae06ebbfa..0000000000
--- a/frontend-modern/src/utils/aiExplorePresentation.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-export interface AIExploreStatusPresentation {
- label: string;
- classes: string;
-}
-
-const DEFAULT_CLASSES =
- 'border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-500 dark:bg-sky-900 dark:text-sky-200';
-
-const AI_EXPLORE_STATUS_PRESENTATION: Record<string, AIExploreStatusPresentation> = {
- started: {
- label: 'Explore Started',
- classes: DEFAULT_CLASSES,
- },
- completed: {
- label: 'Explore Completed',
- classes:
- 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-500 dark:bg-emerald-900 dark:text-emerald-200',
- },
- failed: {
- label: 'Explore Failed',
- classes:
- 'border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-500 dark:bg-rose-900 dark:text-rose-200',
- },
- skipped: {
- label: 'Explore Skipped',
- classes:
- 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-500 dark:bg-amber-900 dark:text-amber-200',
- },
-};
-
-export function getAIExploreStatusPresentation(phase?: string | null): AIExploreStatusPresentation {
- const normalized = (phase || '').trim().toLowerCase();
- if (!normalized) {
- return {
- label: 'Explore Status',
- classes: DEFAULT_CLASSES,
- };
- }
-
- return (
- AI_EXPLORE_STATUS_PRESENTATION[normalized] || {
- label: 'Explore Status',
- classes: DEFAULT_CLASSES,
- }
- );
-}
diff --git a/internal/ai/chat/read_routing_hints.go b/internal/ai/chat/read_routing_hints.go
index 305840bbe6..ad5d549e11 100644
--- a/internal/ai/chat/read_routing_hints.go
+++ b/internal/ai/chat/read_routing_hints.go
@@ -51,42 +51,20 @@ func readRoutingHintForResolvedResource(kind, adapter, targetHost, displayName,
return buildReadRoutingHint(kind, adapter, targetHost, displayName, resourceID)
}
-func (h readRoutingHint) targetHintSuffix() string {
+func (h readRoutingHint) targetFact() string {
switch h.mode {
case readRoutingTargetHost:
if h.ref != "" {
- return fmt.Sprintf(" Use target_host=\"%s\".", h.ref)
+ return fmt.Sprintf("tool addressing fact: target_host=%q", h.ref)
}
case readRoutingNativeResource, readRoutingQueryOnly:
if h.ref != "" {
- return fmt.Sprintf(" Use resource_id=\"%s\".", h.ref)
+ return fmt.Sprintf("tool addressing fact: resource_id=%q", h.ref)
}
}
return ""
}
-func (h readRoutingHint) recentLogsContext(resourceLabel string) string {
- switch h.mode {
- case readRoutingTargetHost:
- if h.ref == "" {
- return ""
- }
- return fmt.Sprintf("Log routing context for %s: target_host=%q.", resourceLabel, h.ref)
- case readRoutingNativeResource:
- if h.ref == "" {
- return ""
- }
- return fmt.Sprintf("Log routing context for %s: resource_id=%q.", resourceLabel, h.ref)
- case readRoutingQueryOnly:
- if h.ref == "" {
- return ""
- }
- return fmt.Sprintf("Read capability context for %s: shared log reads are not supported; current status, alerts, recent activity, and metrics are available through resource_id=%q.", resourceLabel, h.ref)
- default:
- return ""
- }
-}
-
func (h readRoutingHint) prefetchContext() string {
switch h.mode {
case readRoutingNativeResource:
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 2f116c4d9d..4b23087c2d 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
- "regexp"
"sort"
"strings"
"sync"
@@ -733,10 +732,10 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
}
if !mentionsFound {
- s.injectRecentContextIfNeeded(req.Prompt, session.ID, messages, sessions)
+ s.injectRecentSessionContext(session.ID, messages, sessions)
}
} else {
- s.injectRecentContextIfNeeded(req.Prompt, session.ID, messages, sessions)
+ s.injectRecentSessionContext(session.ID, messages, sessions)
}
// Set session-scoped resolved context on executor for resource validation.
@@ -2793,18 +2792,7 @@ func firstPromptLine(description string) string {
return strings.Join(strings.Fields(description), " ")
}
-var recentContextPronounPattern = regexp.MustCompile(`(?i)\b(it|its|that|those|this|them|previous|earlier|last|same|former|latter)\b`)
-var recentContextNounPattern = regexp.MustCompile(`(?i)\b(the (service|container|vm|node|host|docker|instance|one))\b`)
-
-func shouldInjectRecentContext(prompt string) bool {
- return recentContextPronounPattern.MatchString(prompt) || recentContextNounPattern.MatchString(prompt)
-}
-
-func (s *Service) injectRecentContextIfNeeded(prompt, sessionID string, messages []Message, sessions *SessionStore) {
- if !shouldInjectRecentContext(prompt) {
- return
- }
-
+func (s *Service) injectRecentSessionContext(sessionID string, messages []Message, sessions *SessionStore) {
if sessions == nil {
return
}
@@ -2871,28 +2859,15 @@ func (s *Service) injectRecentContextIfNeeded(prompt, sessionID string, messages
primaryName = primary
}
readHint := readRoutingHintForResolvedResource(primaryKind, primaryAdapter, primaryTarget, primaryName, primaryResourceID)
- targetHint := readHint.targetHintSuffix()
- summary := fmt.Sprintf("Context: The most recently referenced resource is %s. If the user says \"it/its/that\", assume they mean this resource unless they specify otherwise. Do not ask for clarification unless the user names a different resource.%s", primary, targetHint)
- if len(lines) > 1 {
- others := strings.Join(lines[1:], "\n")
- summary += "\nOther recent resources:\n" + others
- }
-
- lowerPrompt := strings.ToLower(prompt)
- if strings.Contains(lowerPrompt, "log") || strings.Contains(lowerPrompt, "journal") {
- instructionTarget := primaryName
- if instructionTarget == "" {
- instructionTarget = primary
- }
- if contextLine := readHint.recentLogsContext(instructionTarget); contextLine != "" {
- summary += "\n" + contextLine
- }
+ targetHint := readHint.targetFact()
+ if targetHint != "" {
+ lines[0] = lines[0] + "; " + targetHint
}
log.Debug().
Str("session_id", sessionID).
Strs("recent_resource_ids", recentIDs).
- Msg("[ChatService] Injecting recent context")
+ Msg("[ChatService] Injecting neutral recent session context")
if len(messages) == 0 {
return
@@ -2902,7 +2877,8 @@ func (s *Service) injectRecentContextIfNeeded(prompt, sessionID string, messages
return
}
- messages[lastIdx].Content = summary + "\n\n---\nExplicit target: " + primaryName + "\nUser question (targeted): " + messages[lastIdx].Content
+ context := "Session context from earlier Assistant turns. Use only if relevant to the user's message; otherwise ignore it or ask a clarifying question.\n" + strings.Join(lines, "\n")
+ messages[lastIdx].Content = context + "\n\n---\nUser message:\n" + messages[lastIdx].Content
}
func (s *Service) toolsForExecutionMode(autonomousMode bool, patrolMode bool) []providers.Tool {
diff --git a/internal/ai/chat/service_recent_context_test.go b/internal/ai/chat/service_recent_context_test.go
index 23e26550ad..b33b960d5b 100644
--- a/internal/ai/chat/service_recent_context_test.go
+++ b/internal/ai/chat/service_recent_context_test.go
@@ -6,19 +6,7 @@ import (
"time"
)
-func TestShouldInjectRecentContext(t *testing.T) {
- if !shouldInjectRecentContext("show me its status") {
- t.Fatalf("expected pronoun prompt to trigger recent context")
- }
- if !shouldInjectRecentContext("restart the service") {
- t.Fatalf("expected noun prompt to trigger recent context")
- }
- if shouldInjectRecentContext("what is the uptime") {
- t.Fatalf("expected unrelated prompt to skip recent context")
- }
-}
-
-func TestInjectRecentContextIfNeeded_InjectsSummaryAndInstruction(t *testing.T) {
+func TestInjectRecentSessionContext_InjectsNeutralResourceFacts(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
if err != nil {
t.Fatalf("failed to create session store: %v", err)
@@ -51,33 +39,30 @@ func TestInjectRecentContextIfNeeded_InjectsSummaryAndInstruction(t *testing.T)
messages := []Message{{Role: "user", Content: "show its logs"}}
service := &Service{}
- service.injectRecentContextIfNeeded("show its logs", session.ID, messages, store)
+ service.injectRecentSessionContext(session.ID, messages, store)
content := messages[0].Content
if content == "show its logs" {
t.Fatalf("expected recent context to be injected")
}
- if !strings.Contains(content, "Context: The most recently referenced resource is api (app-container on minipc).") {
- t.Fatalf("expected primary resource summary, got: %s", content)
- }
- if !strings.Contains(content, "Other recent resources:\n- db (vm on node-2)") {
- t.Fatalf("expected secondary resource summary, got: %s", content)
+ if !strings.Contains(content, "Session context from earlier Assistant turns. Use only if relevant to the user's message; otherwise ignore it or ask a clarifying question.") {
+ t.Fatalf("expected neutral session context framing, got: %s", content)
}
- if !strings.Contains(content, "Use target_host=\"host-1\".") {
- t.Fatalf("expected target host hint, got: %s", content)
+ if !strings.Contains(content, "- api (app-container on minipc); tool addressing fact: target_host=\"host-1\"") {
+ t.Fatalf("expected primary resource facts, got: %s", content)
}
- if !strings.Contains(content, "Log routing context for api: target_host=\"host-1\".") {
- t.Fatalf("expected log routing context, got: %s", content)
+ if !strings.Contains(content, "- db (vm on node-2)") {
+ t.Fatalf("expected secondary resource summary, got: %s", content)
}
- if !strings.Contains(content, "Explicit target: api") {
- t.Fatalf("expected explicit target, got: %s", content)
+ if strings.Contains(content, "Log routing context") || strings.Contains(content, "User question (targeted)") {
+ t.Fatalf("expected no prompt-keyword routing instruction, got: %s", content)
}
- if !strings.Contains(content, "User question (targeted): show its logs") {
- t.Fatalf("expected targeted user question, got: %s", content)
+ if !strings.Contains(content, "User message:\nshow its logs") {
+ t.Fatalf("expected original user message to remain neutral, got: %s", content)
}
}
-func TestInjectRecentContextIfNeeded_NoRecentDoesNotModify(t *testing.T) {
+func TestInjectRecentSessionContext_NoRecentDoesNotModify(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
if err != nil {
t.Fatalf("failed to create session store: %v", err)
@@ -92,14 +77,14 @@ func TestInjectRecentContextIfNeeded_NoRecentDoesNotModify(t *testing.T) {
messages := []Message{{Role: "user", Content: "restart it"}}
service := &Service{}
- service.injectRecentContextIfNeeded("restart it", session.ID, messages, store)
+ service.injectRecentSessionContext(session.ID, messages, store)
if messages[0].Content != "restart it" {
t.Fatalf("expected message to remain unchanged")
}
}
-func TestInjectRecentContextIfNeeded_PrimaryNameFallback(t *testing.T) {
+func TestInjectRecentSessionContext_PrimaryNameFallback(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
if err != nil {
t.Fatalf("failed to create session store: %v", err)
@@ -115,21 +100,18 @@ func TestInjectRecentContextIfNeeded_PrimaryNameFallback(t *testing.T) {
messages := []Message{{Role: "user", Content: "show its logs"}}
service := &Service{}
- service.injectRecentContextIfNeeded("show its logs", session.ID, messages, store)
+ service.injectRecentSessionContext(session.ID, messages, store)
content := messages[0].Content
- if !strings.Contains(content, "Context: The most recently referenced resource is node:alpha.") {
+ if !strings.Contains(content, "- node:alpha; tool addressing fact: target_host=\"node:alpha\"") {
t.Fatalf("expected resource ID label, got: %s", content)
}
- if !strings.Contains(content, "Explicit target: node:alpha") {
- t.Fatalf("expected fallback explicit target, got: %s", content)
- }
- if !strings.Contains(content, "Log routing context for node:alpha: target_host=\"node:alpha\".") {
- t.Fatalf("expected log context to use primary name, got: %s", content)
+ if strings.Contains(content, "Explicit target") || strings.Contains(content, "Log routing context") {
+ t.Fatalf("expected no targeted rewrite or log routing instruction, got: %s", content)
}
}
-func TestInjectRecentContextIfNeeded_UsesResourceIDHintForTrueNASAppLogs(t *testing.T) {
+func TestInjectRecentSessionContext_UsesResourceIDFactForTrueNASApp(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
if err != nil {
t.Fatalf("failed to create session store: %v", err)
@@ -152,18 +134,15 @@ func TestInjectRecentContextIfNeeded_UsesResourceIDHintForTrueNASAppLogs(t *test
messages := []Message{{Role: "user", Content: "show its logs"}}
service := &Service{}
- service.injectRecentContextIfNeeded("show its logs", session.ID, messages, store)
+ service.injectRecentSessionContext(session.ID, messages, store)
content := messages[0].Content
- if !strings.Contains(content, "Use resource_id=\"Nextcloud\".") {
- t.Fatalf("expected resource_id hint, got: %s", content)
- }
- if !strings.Contains(content, "Log routing context for Nextcloud: resource_id=\"Nextcloud\".") {
- t.Fatalf("expected resource-targeted log context, got: %s", content)
+ if !strings.Contains(content, "- Nextcloud (app-container on truenas-main); tool addressing fact: resource_id=\"Nextcloud\"") {
+ t.Fatalf("expected resource_id fact, got: %s", content)
}
}
-func TestInjectRecentContextIfNeeded_UsesQueryResourceIDHintForVMwareLogs(t *testing.T) {
+func TestInjectRecentSessionContext_UsesQueryResourceIDFactForVMware(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
if err != nil {
t.Fatalf("failed to create session store: %v", err)
@@ -185,19 +164,13 @@ func TestInjectRecentContextIfNeeded_UsesQueryResourceIDHintForVMwareLogs(t *tes
messages := []Message{{Role: "user", Content: "show its logs"}}
service := &Service{}
- service.injectRecentContextIfNeeded("show its logs", session.ID, messages, store)
+ service.injectRecentSessionContext(session.ID, messages, store)
content := messages[0].Content
- if !strings.Contains(content, "Use resource_id=\"esxi-01.lab.local\".") {
- t.Fatalf("expected resource_id hint, got: %s", content)
+ if !strings.Contains(content, "- esxi-01.lab.local (agent on Lab VC); tool addressing fact: resource_id=\"esxi-01.lab.local\"") {
+ t.Fatalf("expected resource_id fact, got: %s", content)
}
if strings.Contains(content, "target_host=\"esxi-01.lab.local\"") {
- t.Fatalf("expected VMware recent context to avoid target_host log routing, got: %s", content)
- }
- if !strings.Contains(content, "shared log reads are not supported") {
- t.Fatalf("expected VMware log limitation guidance, got: %s", content)
- }
- if !strings.Contains(content, "current status, alerts, recent activity, and metrics are available through resource_id=\"esxi-01.lab.local\"") {
- t.Fatalf("expected VMware recent context to expose resource_id read context, got: %s", content)
+ t.Fatalf("expected VMware recent context to avoid target_host routing, got: %s", content)
}
}
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
index e1aed596dc..958a475429 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -199,14 +199,6 @@ type ThinkingData struct {
Text string `json:"text"`
}
-// ExploreStatusData is the data for "explore_status" events
-type ExploreStatusData struct {
- Phase string `json:"phase"` // started | completed | failed | skipped
- Message string `json:"message"` // Human-readable status text for the UI
- Model string `json:"model,omitempty"` // Optional provider:model source for the status
- Outcome string `json:"outcome,omitempty"` // success | failed | skipped_no_model | skipped_no_tools
-}
-
// WorkflowStateData is the data for "workflow_state" events.
type WorkflowStateData struct {
Phase string `json:"phase"` // investigate | clarify | plan | approve | execute | verify | complete
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 1c9d29c3cf..359db0fd9f 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -10169,15 +10169,6 @@ func TestContract_ChatStreamEventJSONSnapshots(t *testing.T) {
}),
want: `{"type":"content","data":{"text":"hello"}}`,
},
- {
- name: "explore_status",
- event: mustStreamEvent(t, "explore_status", chat.ExploreStatusData{
- Phase: "started",
- Message: "Context status running.",
- Model: "openai:chat-main",
- }),
- want: `{"type":"explore_status","data":{"phase":"started","message":"Context status running.","model":"openai:chat-main"}}`,
- },
{
name: "workflow_state",
event: mustStreamEvent(t, "workflow_state", chat.WorkflowStateData{
diff --git a/scripts/generate-types.go b/scripts/generate-types.go
index dfe521576c..7f7b375391 100644
--- a/scripts/generate-types.go
+++ b/scripts/generate-types.go
@@ -37,7 +37,6 @@ func main() {
defs := []reflect.Type{
reflect.TypeOf(chat.ContentData{}),
reflect.TypeOf(chat.ThinkingData{}),
- reflect.TypeOf(chat.ExploreStatusData{}),
reflect.TypeOf(chat.WorkflowStateData{}),
reflect.TypeOf(chat.ToolStartData{}),
reflect.TypeOf(chat.ToolEndData{}),
@@ -74,7 +73,6 @@ func main() {
buf.WriteString("export type AIChatStreamEvent =\n")
buf.WriteString(" | { type: 'content'; data: ContentData }\n")
buf.WriteString(" | { type: 'thinking'; data: ThinkingData }\n")
- buf.WriteString(" | { type: 'explore_status'; data: ExploreStatusData }\n")
buf.WriteString(" | { type: 'workflow_state'; data: WorkflowStateData }\n")
buf.WriteString(" | { type: 'tool_start'; data: ToolStartData }\n")
buf.WriteString(" | { type: 'tool_end'; data: ToolEndData }\n")