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.

Search Assistant session history

rcourtman49c23d6bed99
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f30da3a5ae..044cecc629 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -218,9 +218,14 @@ Assistant session-history reads from the shared AI endpoints are likewise
API-owned browser-safe projections: lifecycle surfaces, MCP adapters, and
agents must not depend on `reasoning_content`, raw `pulse_*` / `patrol_*`
tool-call prose, token accounting text, or assistant transcript prose as an
-agent command grant, install-token disclosure, or host-execution shortcut. When a
-planned resource capability is actually executed from an agent-lifecycle
-surface, that handoff must route through `POST /api/actions/{id}/execute` so
+agent command grant, install-token disclosure, or host-execution shortcut.
+Searchable Assistant session-list queries on `GET /api/ai/sessions` are the
+same browser-safe history navigation projection; lifecycle surfaces may not
+reinterpret search matches, handoff summaries, or message counts as agent
+capability state, command authority, enrollment evidence, or install-token
+availability. When a planned resource capability is actually executed from an
+agent-lifecycle surface, that handoff must route through
+`POST /api/actions/{id}/execute` so
the API-owned action audit records `executing` before dispatch and the
terminal execution result afterward. Dry-run-only plans remain planning evidence
only; lifecycle surfaces must not present them as executable, dispatch them
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 55a76d53d7..a0712e8839 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -521,6 +521,24 @@ runtime cost control, and shared AI transport surfaces.
atomically readable through temp-file plus rename so a large recent-session
list cannot block `EnsureSession`, `AddMessage`, or stored handoff reads on
a new prompt.
+ Assistant session navigation must provide a searchable history path in the
+ drawer-owned picker, using the canonical `/api/ai/sessions` contract rather
+ than a separate recent-chat store. Search is applied before result limiting
+ so the picker can narrow older sessions without hiding matches behind a
+ recency cap, the picker must open immediately with cached sessions while any
+ refresh/search is still running, and loading/error states must stay inside
+ the picker instead of making the main send path look busy. The referenced
+ OpenCode source at fetched `origin/dev` commit
+ `1399323b78a04229d9bfe00c7436d7f41770fda8` implements
+ `SessionSwitcherDialog` in
+ `packages/opencode/src/cli/cmd/tui/feature-plugins/session/dialog.tsx` with
+ `createDebouncedSignal("", 150)`,
+ `sdk.client.session.list({ search: input.query, limit: 30, ...input.filter })`,
+ recency ordering through
+ `orderByRecency`, and pinned/current session options before navigation.
+ Pulse adapts that source workflow with a debounced Assistant session search
+ field, `GET /api/ai/sessions?search=...&limit=30`, and searched result rows
+ that resume through the same session-loading path as the normal recent list.
The empty Assistant drawer may surface recent non-empty sessions as direct
resume actions using the backend session list already owned by the drawer;
it must not create a parallel recent-chat store or product-authored prompt
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d821f927c2..a192f9f704 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -420,6 +420,14 @@ payload shape change when the portal presents compact client rows.
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.
+ `GET /api/ai/sessions` also owns the Assistant history lookup contract:
+ optional `search` text must filter the browser-safe session projection
+ before optional `limit` truncation, and matching may use only safe session
+ identity, title, timestamps, and handoff-summary fields. Search must not
+ expose provider-bound model context, stored prompts, raw tool output, or
+ remediation details, and frontend clients must route searchable picker
+ requests through the shared `AIChatAPI.listSessions({ search, limit })`
+ helper rather than inventing a parallel local history endpoint.
Resource-context follow-up turns are different from Patrol-run rehydration:
browser-safe `handoff_metadata.kind=resource_context` must not replace a
stored rich handoff envelope with a partial metadata-only envelope, and the
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index b8e8c19c6d..a417615f03 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -642,6 +642,11 @@ recovery scope, or a storage/recovery-owned secret source.
raw `pulse_*` / `patrol_*` tool-call prose, token accounting text, and
provider thinking text are not recovery evidence, backup freshness, restore
eligibility, storage-local approval state, or recovery execution authority.
+ Searchable Assistant session-list queries on `GET /api/ai/sessions` remain
+ the same adjacent browser-safe history navigation projection: storage and
+ recovery surfaces may not reinterpret search hits, handoff summaries, or
+ message counts as backup coverage, recovery freshness, restore capability,
+ or storage-local action authority.
That same adjacent `internal/api/` boundary still carries Patrol-run
execution identity. Storage and recovery may observe shared Patrol
transport through `internal/api/chat_service_adapter.go`, but they must not
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index 10b101054e..344eda0190 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -59,6 +59,16 @@ describe('AIChatAPI', () => {
expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/sessions');
});
+ it('passes session search and limit as query parameters', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce([]);
+
+ await expect(AIChatAPI.listSessions({ search: ' backup jobs ', limit: 30 })).resolves.toEqual(
+ [],
+ );
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/sessions?search=backup+jobs&limit=30');
+ });
+
it('normalizes a null sessions payload to an empty array (#1149)', async () => {
apiFetchJSONMock.mockResolvedValueOnce(null);
await expect(AIChatAPI.listSessions()).resolves.toEqual([]);
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index 6590a993e5..2e6ff69afb 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -15,6 +15,11 @@ export interface ChatSession {
handoff_summary?: ChatSessionHandoffSummary;
}
+export interface ListChatSessionsOptions {
+ search?: string;
+ limit?: number;
+}
+
export type ChatMentionType = 'vm' | 'system-container' | 'app-container' | 'agent' | 'storage';
export interface ChatMention {
@@ -158,8 +163,15 @@ export class AIChatAPI {
// List all chat sessions. Normalizes a null/non-array payload (e.g. a server
// error body) to an empty array so callers can rely on array semantics and do
// not crash on .length/.some()/.map() (#1149).
- static async listSessions(): Promise<ChatSession[]> {
- const value = await apiFetchJSON(`${this.baseUrl}/sessions`);
+ static async listSessions(options: ListChatSessionsOptions = {}): Promise<ChatSession[]> {
+ const params = new URLSearchParams();
+ const search = options.search?.trim();
+ if (search) params.set('search', search);
+ if (typeof options.limit === 'number' && Number.isFinite(options.limit) && options.limit > 0) {
+ params.set('limit', String(Math.floor(options.limit)));
+ }
+ const suffix = params.toString();
+ const value = await apiFetchJSON(`${this.baseUrl}/sessions${suffix ? `?${suffix}` : ''}`);
return Array.isArray(value) ? (value as ChatSession[]) : [];
}
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 e6d6e68d35..2c717d8394 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -1791,6 +1791,59 @@ describe('AIChat', () => {
});
});
+ it('searches assistant sessions from the picker', async () => {
+ mockAIChatAPI.listSessions
+ .mockResolvedValueOnce([
+ { id: 's1', title: 'Session One', created_at: '', updated_at: '', message_count: 5 },
+ {
+ id: 's2',
+ title: 'Backup Patrol Follow-up',
+ created_at: '',
+ updated_at: '',
+ message_count: 3,
+ },
+ ])
+ .mockResolvedValueOnce([
+ { id: 's1', title: 'Session One', created_at: '', updated_at: '', message_count: 5 },
+ {
+ id: 's2',
+ title: 'Backup Patrol Follow-up',
+ created_at: '',
+ updated_at: '',
+ message_count: 3,
+ },
+ ])
+ .mockResolvedValueOnce([
+ {
+ id: 's2',
+ title: 'Backup Patrol Follow-up',
+ created_at: '',
+ updated_at: '',
+ message_count: 3,
+ },
+ ]);
+
+ renderChat();
+ await waitFor(() => {
+ expect(mockAIChatAPI.listSessions).toHaveBeenCalledTimes(1);
+ });
+
+ fireEvent.click(screen.getByTitle('Pulse Assistant sessions'));
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText('Search sessions...')).toBeInTheDocument();
+ });
+
+ fireEvent.input(screen.getByPlaceholderText('Search sessions...'), {
+ target: { value: 'backup' },
+ });
+
+ await waitFor(() => {
+ expect(mockAIChatAPI.listSessions).toHaveBeenCalledWith({ search: 'backup', limit: 30 });
+ expect(screen.getByText('Backup Patrol Follow-up')).toBeInTheDocument();
+ expect(screen.queryByText('Session One')).not.toBeInTheDocument();
+ });
+ });
+
it('loads a session when clicked in the dropdown', async () => {
mockAIChatAPI.listSessions.mockResolvedValue([
{ id: 's1', title: 'Session One', created_at: '', updated_at: '', message_count: 5 },
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index 8703d11d12..1c202ff4f9 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -18,6 +18,7 @@ import SettingsIcon from 'lucide-solid/icons/settings';
import XIcon from 'lucide-solid/icons/x';
import { AIAPI } from '@/api/ai';
import { AIChatAPI, type ChatSession, type ChatSessionHandoffSummary } from '@/api/aiChat';
+import { SearchField } from '@/components/shared/SearchField';
import { notificationStore } from '@/stores/notifications';
import { aiChatStore, type AIChatContext } from '@/stores/aiChat';
import {
@@ -44,6 +45,12 @@ import {
AI_CHAT_PROVIDER_READINESS_SETTINGS_LABEL,
AI_CHAT_SESSION_MENU_TITLE,
AI_CHAT_SESSION_EMPTY_STATE,
+ AI_CHAT_SESSION_LOADING_STATE,
+ AI_CHAT_SESSION_SEARCH_EMPTY_STATE,
+ AI_CHAT_SESSION_SEARCH_ERROR_STATE,
+ AI_CHAT_SESSION_SEARCH_LOADING_STATE,
+ AI_CHAT_SESSION_SEARCH_PLACEHOLDER,
+ AI_CHAT_SESSION_SEARCH_TITLE,
getAIChatEmptyStatePresentation,
getAIChatProviderReadinessPresentation,
} from '@/utils/aiChatPresentation';
@@ -92,6 +99,8 @@ const DEFAULT_SESSION_KEY = '__default__';
const AI_CHAT_MIN_DOCKED_VIEWPORT_WIDTH = 1200;
const AI_CHAT_PROMPT_HISTORY_LIMIT = 100;
const AI_CHAT_RECENT_MODEL_LIMIT = 8;
+const AI_CHAT_SESSION_SEARCH_DEBOUNCE_MS = 150;
+const AI_CHAT_SESSION_SEARCH_LIMIT = 30;
const STRUCTURED_PATROL_CONTEXT_TARGETS = new Set(['patrol-configuration', 'patrol-run']);
const STRUCTURED_RESOURCE_CONTEXT_HANDOFF_KINDS = new Set(['resource_context']);
@@ -463,8 +472,14 @@ export const AIChat: Component<AIChatProps> = (props) => {
const [savedPromptDraft, setSavedPromptDraft] = createSignal<PromptHistoryEntry | null>(null);
const [sessions, setSessions] = createSignal<ChatSession[]>([]);
const [showSessions, setShowSessions] = createSignal(false);
+ const [sessionRefreshLoading, setSessionRefreshLoading] = createSignal(false);
+ const [sessionSearchQuery, setSessionSearchQuery] = createSignal('');
+ const [sessionSearchResults, setSessionSearchResults] = createSignal<ChatSession[] | null>(null);
+ const [sessionSearchLoading, setSessionSearchLoading] = createSignal(false);
+ const [sessionSearchError, setSessionSearchError] = createSignal('');
const [sessionDropdownPosition, setSessionDropdownPosition] = createSignal({ top: 0, right: 0 });
let sessionButtonRef: HTMLButtonElement | undefined;
+ let sessionSearchRequestId = 0;
const [modelSelectorOpenRequest, setModelSelectorOpenRequest] = createSignal(0);
const [defaultModel, setDefaultModel] = createSignal('');
const [chatOverrideModel, setChatOverrideModel] = createSignal('');
@@ -768,6 +783,36 @@ export const AIChat: Component<AIChatProps> = (props) => {
setSessions(sessionList);
};
+ const normalizedSessionSearchQuery = createMemo(() => sessionSearchQuery().trim());
+ const sessionPickerSessions = createMemo(() =>
+ normalizedSessionSearchQuery() ? (sessionSearchResults() ?? []) : sessions(),
+ );
+ const sessionPickerEmptyText = createMemo(() => {
+ if (sessionSearchError()) return sessionSearchError();
+ if (!normalizedSessionSearchQuery()) {
+ return sessionRefreshLoading() ? AI_CHAT_SESSION_LOADING_STATE : AI_CHAT_SESSION_EMPTY_STATE;
+ }
+ if (sessionSearchLoading()) return AI_CHAT_SESSION_SEARCH_LOADING_STATE;
+ return AI_CHAT_SESSION_SEARCH_EMPTY_STATE;
+ });
+ const sessionPickerLoadingText = createMemo(() => {
+ if (normalizedSessionSearchQuery()) {
+ return sessionSearchLoading() ? AI_CHAT_SESSION_SEARCH_LOADING_STATE : '';
+ }
+ return sessionRefreshLoading() ? AI_CHAT_SESSION_LOADING_STATE : '';
+ });
+ const resetSessionSearch = () => {
+ sessionSearchRequestId += 1;
+ setSessionSearchQuery('');
+ setSessionSearchResults(null);
+ setSessionSearchLoading(false);
+ setSessionSearchError('');
+ };
+
+ const findKnownSession = (sessionId: string) =>
+ sessions().find((candidate) => candidate.id === sessionId) ||
+ sessionSearchResults()?.find((candidate) => candidate.id === sessionId);
+
// Chat hook
const chat = useChat({
model: '',
@@ -1208,6 +1253,46 @@ export const AIChat: Component<AIChatProps> = (props) => {
void initializeWhenOpen();
});
+ createEffect(() => {
+ if (!showSessions()) {
+ return;
+ }
+
+ const query = normalizedSessionSearchQuery();
+ if (!query) {
+ sessionSearchRequestId += 1;
+ setSessionSearchResults(null);
+ setSessionSearchLoading(false);
+ setSessionSearchError('');
+ return;
+ }
+
+ const requestId = ++sessionSearchRequestId;
+ setSessionSearchResults(null);
+ setSessionSearchLoading(true);
+ setSessionSearchError('');
+
+ const timeoutId = window.setTimeout(() => {
+ AIChatAPI.listSessions({ search: query, limit: AI_CHAT_SESSION_SEARCH_LIMIT })
+ .then((sessionList) => {
+ if (requestId !== sessionSearchRequestId) return;
+ setSessionSearchResults(sessionList);
+ })
+ .catch((error) => {
+ if (requestId !== sessionSearchRequestId) return;
+ logger.error('[AIChat] Failed to search sessions:', error);
+ setSessionSearchResults([]);
+ setSessionSearchError(AI_CHAT_SESSION_SEARCH_ERROR_STATE);
+ })
+ .finally(() => {
+ if (requestId !== sessionSearchRequestId) return;
+ setSessionSearchLoading(false);
+ });
+ }, AI_CHAT_SESSION_SEARCH_DEBOUNCE_MS);
+
+ onCleanup(() => window.clearTimeout(timeoutId));
+ });
+
createEffect(() => {
if (!chat.isLoading() && interruptArmed()) {
clearInterruptArm();
@@ -1279,6 +1364,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
// Only close if click is outside dropdown containers
if (!target.closest('[data-dropdown]')) {
setShowSessions(false);
+ setSessionRefreshLoading(false);
+ resetSessionSearch();
setShowControlMenu(false);
}
// Close mention autocomplete when clicking outside
@@ -1777,6 +1864,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
setEditingQueuedFollowUp(null);
aiChatStore.clearContext?.();
setShowSessions(false);
+ setSessionRefreshLoading(false);
+ resetSessionSearch();
focusComposer();
};
@@ -1784,6 +1873,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
const next = !showSessions();
if (!next) {
setShowSessions(false);
+ setSessionRefreshLoading(false);
+ resetSessionSearch();
return;
}
@@ -1795,20 +1886,23 @@ export const AIChat: Component<AIChatProps> = (props) => {
});
}
+ resetSessionSearch();
+ setShowSessions(true);
+ setSessionRefreshLoading(true);
+
try {
await refreshSessions();
} catch (error) {
logger.error('[AIChat] Failed to refresh sessions before opening picker:', error);
notificationStore.error('Failed to refresh assistant sessions');
- return;
+ } finally {
+ setSessionRefreshLoading(false);
}
-
- setShowSessions(true);
};
// Load session
const handleLoadSession = async (sessionId: string) => {
- const session = sessions().find((candidate) => candidate.id === sessionId);
+ const session = findKnownSession(sessionId);
const loaded = await chat.loadSession(sessionId);
if (!loaded) return;
resetPromptHistoryNavigation();
@@ -1820,6 +1914,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
aiChatStore.clearContext?.();
}
setShowSessions(false);
+ setSessionRefreshLoading(false);
+ resetSessionSearch();
focusComposer();
};
@@ -1830,6 +1926,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
try {
await AIChatAPI.deleteSession(sessionId);
setSessions((prev) => prev.filter((s) => s.id !== sessionId));
+ setSessionSearchResults((prev) => prev?.filter((s) => s.id !== sessionId) ?? null);
updateStoredModel(sessionId, '');
if (chat.sessionId() === sessionId) {
chat.clearMessages();
@@ -2073,7 +2170,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
<Show when={showSessions()}>
<div
- class="fixed w-72 max-h-96 bg-surface rounded-md shadow-sm border border-border z-[9999] overflow-hidden"
+ class="fixed w-80 max-h-[28rem] bg-surface rounded-md shadow-sm border border-border z-[9999] overflow-hidden"
style={{
top: `${sessionDropdownPosition().top}px`,
right: `${sessionDropdownPosition().right}px`,
@@ -2094,16 +2191,36 @@ export const AIChat: Component<AIChatProps> = (props) => {
<span class="font-medium">{AI_CHAT_NEW_SESSION_MENU_LABEL}</span>
</button>
- <div class="max-h-64 overflow-y-auto">
+ <div class="border-b border-border px-3 py-2">
+ <SearchField
+ value={sessionSearchQuery()}
+ onChange={setSessionSearchQuery}
+ placeholder={AI_CHAT_SESSION_SEARCH_PLACEHOLDER}
+ title={AI_CHAT_SESSION_SEARCH_TITLE}
+ inputClass="py-1.5 text-xs"
+ />
+ </div>
+
+ <Show when={sessionPickerLoadingText()}>
+ <div
+ class="border-b border-border px-3 py-1.5 text-[11px] text-muted"
+ role="status"
+ aria-live="polite"
+ >
+ {sessionPickerLoadingText()}
+ </div>
+ </Show>
+
+ <div class="max-h-72 overflow-y-auto">
<Show
- when={sessions().length > 0}
+ when={sessionPickerSessions().length > 0}
fallback={
<div class="px-3 py-6 text-center text-xs text-muted">
- {AI_CHAT_SESSION_EMPTY_STATE}
+ {sessionPickerEmptyText()}
</div>
}
>
- <For each={sessions()}>
+ <For each={sessionPickerSessions()}>
{(session) => (
<div
class={`group relative px-3 py-2.5 flex items-start gap-2 hover:bg-surface-hover cursor-pointer ${chat.sessionId() === session.id ? 'bg-blue-50 dark:bg-blue-900' : ''}`}
diff --git a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
index 8a919de8f8..9ca2d9fb39 100644
--- a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
@@ -17,7 +17,13 @@ import {
AI_CHAT_PROVIDER_READINESS_SETTINGS_LABEL,
AI_CHAT_QUESTION_CARD_TITLE,
AI_CHAT_SESSION_EMPTY_STATE,
+ AI_CHAT_SESSION_LOADING_STATE,
AI_CHAT_SESSION_MENU_TITLE,
+ AI_CHAT_SESSION_SEARCH_EMPTY_STATE,
+ AI_CHAT_SESSION_SEARCH_ERROR_STATE,
+ AI_CHAT_SESSION_SEARCH_LOADING_STATE,
+ AI_CHAT_SESSION_SEARCH_PLACEHOLDER,
+ AI_CHAT_SESSION_SEARCH_TITLE,
getAIChatProviderReadinessPresentation,
getAIChatLauncherTitle,
getAIChatEmptyStatePresentation,
@@ -42,6 +48,12 @@ describe('aiChatPresentation', () => {
expect(AI_CHAT_LAUNCHER_ARIA_LABEL).toBe('Expand Pulse Assistant');
expect(AI_CHAT_SESSION_MENU_TITLE).toBe('Pulse Assistant sessions');
expect(AI_CHAT_SESSION_EMPTY_STATE).toBe('No previous assistant sessions');
+ expect(AI_CHAT_SESSION_LOADING_STATE).toBe('Loading assistant sessions...');
+ expect(AI_CHAT_SESSION_SEARCH_PLACEHOLDER).toBe('Search sessions...');
+ expect(AI_CHAT_SESSION_SEARCH_TITLE).toBe('Search Assistant sessions');
+ expect(AI_CHAT_SESSION_SEARCH_EMPTY_STATE).toBe('No sessions match your search');
+ expect(AI_CHAT_SESSION_SEARCH_LOADING_STATE).toBe('Searching assistant sessions...');
+ expect(AI_CHAT_SESSION_SEARCH_ERROR_STATE).toBe('Failed to search assistant sessions');
expect(AI_CHAT_MODEL_SELECTOR_EMPTY_STATE).toBe('No matching models.');
expect(AI_CHAT_QUESTION_CARD_TITLE).toBe('Pulse Assistant needs your input');
expect(AI_CHAT_ASSISTANT_MESSAGE_LABEL).toBe('Pulse Assistant');
diff --git a/frontend-modern/src/utils/aiChatPresentation.ts b/frontend-modern/src/utils/aiChatPresentation.ts
index 33131349e8..1db9ee4aa7 100644
--- a/frontend-modern/src/utils/aiChatPresentation.ts
+++ b/frontend-modern/src/utils/aiChatPresentation.ts
@@ -8,6 +8,12 @@ export const AI_CHAT_NEW_SESSION_SHORT_LABEL = 'New';
export const AI_CHAT_NEW_SESSION_BUTTON_TITLE = 'New assistant session';
export const AI_CHAT_NEW_SESSION_MENU_LABEL = 'New session';
export const AI_CHAT_SESSION_EMPTY_STATE = 'No previous assistant sessions';
+export const AI_CHAT_SESSION_LOADING_STATE = 'Loading assistant sessions...';
+export const AI_CHAT_SESSION_SEARCH_PLACEHOLDER = 'Search sessions...';
+export const AI_CHAT_SESSION_SEARCH_TITLE = 'Search Assistant sessions';
+export const AI_CHAT_SESSION_SEARCH_EMPTY_STATE = 'No sessions match your search';
+export const AI_CHAT_SESSION_SEARCH_LOADING_STATE = 'Searching assistant sessions...';
+export const AI_CHAT_SESSION_SEARCH_ERROR_STATE = 'Failed to search assistant sessions';
export const AI_CHAT_MODEL_SELECTOR_EMPTY_STATE = 'No matching models.';
export const AI_CHAT_DISCOVERY_HINT_TITLE = 'Workload Discovery is off.';
export const AI_CHAT_DISCOVERY_HINT_BODY =
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 2841cca277..27713c21e0 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -2638,6 +2638,10 @@ func (h *AIHandler) HandleSessions(w http.ResponseWriter, r *http.Request) {
return
}
+ if query := r.URL.Query().Get("search"); strings.TrimSpace(query) != "" {
+ sessions = filterAIChatSessionsForSearch(sessions, query)
+ }
+
// Optional limit parameter (for relay proxy clients with body size constraints)
if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
if limit, err := strconv.Atoi(limitStr); err == nil && limit > 0 && limit < len(sessions) {
@@ -2649,6 +2653,61 @@ func (h *AIHandler) HandleSessions(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(sessions)
}
+func filterAIChatSessionsForSearch(sessions []chat.Session, query string) []chat.Session {
+ terms := strings.Fields(strings.ToLower(strings.TrimSpace(query)))
+ if len(terms) == 0 {
+ return sessions
+ }
+
+ filtered := make([]chat.Session, 0, len(sessions))
+ for _, session := range sessions {
+ haystack := aiChatSessionSearchText(session)
+ matched := true
+ for _, term := range terms {
+ if !strings.Contains(haystack, term) {
+ matched = false
+ break
+ }
+ }
+ if matched {
+ filtered = append(filtered, session)
+ }
+ }
+ return filtered
+}
+
+func aiChatSessionSearchText(session chat.Session) string {
+ parts := []string{
+ session.ID,
+ session.Title,
+ session.CreatedAt.Format(time.RFC3339),
+ session.UpdatedAt.Format(time.RFC3339),
+ }
+
+ if summary := session.HandoffSummary; summary != nil {
+ parts = append(parts,
+ summary.Kind,
+ summary.FindingID,
+ summary.RunID,
+ summary.RunType,
+ summary.RunStatus,
+ summary.LastKnownApprovalStatus,
+ summary.LastKnownActionState,
+ summary.LastKnownActionRisk,
+ )
+ if summary.PrimaryResource != nil {
+ parts = append(parts,
+ summary.PrimaryResource.ID,
+ summary.PrimaryResource.Name,
+ summary.PrimaryResource.Type,
+ summary.PrimaryResource.Node,
+ )
+ }
+ }
+
+ return strings.ToLower(strings.Join(parts, " "))
+}
+
// HandleCreateSession handles POST /api/ai/sessions - create session
func (h *AIHandler) HandleCreateSession(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index ff5f0ae29c..a0b590a710 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -468,6 +468,61 @@ func TestHandleSessions(t *testing.T) {
assert.Equal(t, http.StatusOK, w.Code)
}
+func TestHandleSessionsSearchAndLimit(t *testing.T) {
+ cfg := &config.Config{}
+ h := newTestAIHandler(cfg, nil, nil)
+ mockSvc := new(MockAIService)
+ h.defaultService = mockSvc
+
+ now := time.Now().UTC()
+ sessions := []chat.Session{
+ {
+ ID: "s-backup",
+ Title: "PBS backup follow-up",
+ CreatedAt: now.Add(-3 * time.Hour),
+ UpdatedAt: now.Add(-2 * time.Hour),
+ MessageCount: 2,
+ HandoffSummary: &chat.SessionHandoffSummary{
+ Kind: "patrol_finding",
+ FindingID: "finding-backup-age",
+ PrimaryResource: &chat.HandoffResource{
+ Name: "pbs-store-1",
+ Type: "storage",
+ Node: "pve-1",
+ },
+ },
+ },
+ {
+ ID: "s-unrelated",
+ Title: "Container cleanup",
+ CreatedAt: now.Add(-2 * time.Hour),
+ UpdatedAt: now.Add(-1 * time.Hour),
+ MessageCount: 4,
+ },
+ {
+ ID: "s-backup-second",
+ Title: "Backup verification",
+ CreatedAt: now.Add(-90 * time.Minute),
+ UpdatedAt: now.Add(-30 * time.Minute),
+ MessageCount: 1,
+ },
+ }
+ mockSvc.On("IsRunning").Return(true)
+ mockSvc.On("ListSessions", mock.Anything).Return(sessions, nil)
+
+ req := httptest.NewRequest("GET", "/api/ai/sessions?search=backup&limit=1", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleSessions(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+ var got []chat.Session
+ assert.NoError(t, json.NewDecoder(w.Body).Decode(&got))
+ if assert.Len(t, got, 1) {
+ assert.Equal(t, "s-backup", got[0].ID)
+ }
+}
+
func TestHandleCreateSession(t *testing.T) {
cfg := &config.Config{}
h := newTestAIHandler(cfg, nil, nil)