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.

Surface System AI provider save context

rcourtmanc31e644f331d
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 2ba06c8009..7c731e3fea 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -729,8 +729,11 @@ frontend primitive boundary.
`frontend-modern/src/components/Settings/useAISettingsState.ts`, and
`frontend-modern/src/utils/aiSettingsPresentation.ts` must present that
surface to operators as `Assistant & Patrol` plus provider/model
- configuration rather than as a generic `AI Services` shell. Runtime
- controls inside `frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx`
+ configuration rather than as a generic `AI Services` shell. Settings-save
+ feedback must preserve provider-specific preflight failures and successful
+ save responses that carry Patrol readiness warnings, including the provider,
+ selected Patrol model, and readiness summary when those fields are present.
+ Runtime controls inside `frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx`
must likewise describe discovery as workload discovery that supplies
concrete service context to Pulse Assistant and Patrol, not as a generic
AI context feature. Assistant-only controls inside the shared shell, such
diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
index 58a0c61284..4991f11e75 100644
--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
import { Route, Router } from '@solidjs/router';
import { resetAIRuntimeState } from '@/stores/aiRuntimeState';
@@ -18,6 +18,7 @@ const revertSessionMock = vi.fn();
const notificationSuccessMock = vi.fn();
const notificationErrorMock = vi.fn();
const notificationInfoMock = vi.fn();
+const notificationWarningMock = vi.fn();
const loggerDebugMock = vi.fn();
const loggerErrorMock = vi.fn();
const hasFeatureMock = vi.fn();
@@ -51,6 +52,7 @@ vi.mock('@/stores/notifications', () => ({
success: (...args: unknown[]) => notificationSuccessMock(...args),
error: (...args: unknown[]) => notificationErrorMock(...args),
info: (...args: unknown[]) => notificationInfoMock(...args),
+ warning: (...args: unknown[]) => notificationWarningMock(...args),
},
}));
@@ -116,6 +118,7 @@ const resetAllMocks = () => {
notificationSuccessMock.mockReset();
notificationErrorMock.mockReset();
notificationInfoMock.mockReset();
+ notificationWarningMock.mockReset();
loggerDebugMock.mockReset();
loggerErrorMock.mockReset();
hasFeatureMock.mockReset();
@@ -479,6 +482,149 @@ describe('AISettings OpenRouter flow', () => {
});
});
+describe('AISettings provider save failure context', () => {
+ beforeEach(() => {
+ resetAllMocks();
+ setupDefaultMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('names the provider and selected model when a settings save fails after preflight', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ configured: true,
+ enabled: true,
+ model: 'openrouter:deepseek/deepseek-r1',
+ patrol_model: 'openrouter:deepseek/deepseek-r1',
+ openrouter_configured: true,
+ deepseek_configured: true,
+ configured_providers: ['openrouter', 'deepseek'],
+ });
+ getModelsMock.mockResolvedValue({
+ models: [
+ {
+ id: 'openrouter:deepseek/deepseek-r1',
+ name: 'DeepSeek R1 via OpenRouter',
+ },
+ ],
+ });
+ testProviderMock.mockImplementation(async (provider: string) => ({
+ success: provider !== 'openrouter',
+ message:
+ provider === 'openrouter'
+ ? 'OpenRouter returned 401 during provider preflight'
+ : `${provider} reachable`,
+ provider,
+ }));
+ updateSettingsMock.mockRejectedValue(new Error('Unable to save Assistant & Patrol settings.'));
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(testProviderMock).toHaveBeenCalledWith('openrouter');
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+
+ await waitFor(() => {
+ expect(notificationErrorMock).toHaveBeenCalledWith(
+ expect.stringContaining('OpenRouter provider'),
+ );
+ });
+ const message = String(notificationErrorMock.mock.calls.at(-1)?.[0] ?? '');
+ expect(message).toContain('model openrouter:deepseek/deepseek-r1');
+ expect(message).toContain('OpenRouter returned 401 during provider preflight');
+ expect(message).toContain('Unable to save Assistant & Patrol settings.');
+ });
+
+ it('warns with Patrol provider and model when settings save but Patrol is not ready', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ configured: true,
+ enabled: true,
+ model: 'openrouter:deepseek/deepseek-r1',
+ patrol_model: 'openrouter:deepseek/deepseek-r1',
+ openrouter_configured: true,
+ configured_providers: ['openrouter'],
+ });
+ updateSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ configured: true,
+ enabled: true,
+ model: 'openrouter:deepseek/deepseek-r1',
+ patrol_model: 'openrouter:deepseek/deepseek-r1',
+ openrouter_configured: true,
+ configured_providers: ['openrouter'],
+ patrol_readiness: {
+ status: 'not_ready',
+ ready: false,
+ cause: 'model_unsupported_tools',
+ summary:
+ 'The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
+ provider: 'openrouter',
+ model: 'openrouter:deepseek/deepseek-r1',
+ checks: [],
+ },
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: /save changes/i })).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+
+ await waitFor(() => {
+ expect(notificationWarningMock).toHaveBeenCalledWith(
+ expect.stringContaining('Assistant & Patrol settings saved, but Patrol is not ready'),
+ );
+ });
+ const message = String(notificationWarningMock.mock.calls.at(-1)?.[0] ?? '');
+ expect(message).toContain('Provider: OpenRouter');
+ expect(message).toContain('Model: openrouter:deepseek/deepseek-r1');
+ expect(message).toContain('reasoning-only model family');
+ expect(notificationSuccessMock).not.toHaveBeenCalledWith('Assistant & Patrol settings saved');
+ });
+
+ it('does not attach provider context to specific backend validation errors', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ configured: true,
+ enabled: true,
+ model: 'openrouter:deepseek/deepseek-r1',
+ openrouter_configured: true,
+ configured_providers: ['openrouter'],
+ });
+ testProviderMock.mockResolvedValue({
+ success: false,
+ message: 'OpenRouter returned 401 during provider preflight',
+ provider: 'openrouter',
+ });
+ updateSettingsMock.mockRejectedValue(new Error('Patrol interval must be at least 10 minutes'));
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(testProviderMock).toHaveBeenCalledWith('openrouter');
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+
+ await waitFor(() => {
+ expect(notificationErrorMock).toHaveBeenCalledWith(
+ 'Patrol interval must be at least 10 minutes',
+ );
+ });
+ const message = String(notificationErrorMock.mock.calls.at(-1)?.[0] ?? '');
+ expect(message).not.toContain('OpenRouter provider');
+ expect(message).not.toContain('openrouter:deepseek/deepseek-r1');
+ });
+});
+
describe('AISettings provider setup flow', () => {
beforeEach(() => {
resetAllMocks();
@@ -489,6 +635,94 @@ describe('AISettings provider setup flow', () => {
cleanup();
});
+ it('warns from setup when the saved provider leaves Patrol not ready', async () => {
+ updateSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ model: 'openrouter:deepseek/deepseek-r1',
+ patrol_model: 'openrouter:deepseek/deepseek-r1',
+ openrouter_configured: true,
+ configured_providers: ['openrouter'],
+ patrol_readiness: {
+ status: 'not_ready',
+ ready: false,
+ cause: 'model_unsupported_tools',
+ summary:
+ 'The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
+ provider: 'openrouter',
+ model: 'openrouter:deepseek/deepseek-r1',
+ checks: [],
+ },
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(getSettingsMock).toHaveBeenCalledTimes(1);
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /enable assistant and patrol/i }));
+ const setupDialog = await screen.findByRole('dialog', {
+ name: 'Set up Assistant and Patrol',
+ });
+ expect(within(setupDialog).getByText('Set Up Assistant & Patrol')).toBeInTheDocument();
+ fireEvent.click(within(setupDialog).getByRole('button', { name: /OpenRouter/i }));
+ fireEvent.input(screen.getByPlaceholderText('sk-or-...'), {
+ target: { value: 'sk-or-test' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Enable Assistant & Patrol' }));
+
+ await waitFor(() => {
+ expect(updateSettingsMock).toHaveBeenCalledWith({
+ enabled: true,
+ openrouter_api_key: 'sk-or-test',
+ });
+ });
+ await waitFor(() => {
+ expect(notificationWarningMock).toHaveBeenCalledWith(
+ expect.stringContaining('Assistant & Patrol enabled, but Patrol is not ready'),
+ );
+ });
+ const message = String(notificationWarningMock.mock.calls.at(-1)?.[0] ?? '');
+ expect(message).toContain('Provider: OpenRouter');
+ expect(message).toContain('Model: openrouter:deepseek/deepseek-r1');
+ expect(message).toContain('reasoning-only model family');
+ expect(notificationSuccessMock).not.toHaveBeenCalledWith(
+ 'Assistant & Patrol enabled! You can customize settings below.',
+ );
+ });
+
+ it('names the setup provider when provider setup save fails generically', async () => {
+ updateSettingsMock.mockRejectedValue(new Error('Unable to save Assistant & Patrol settings.'));
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(getSettingsMock).toHaveBeenCalledTimes(1);
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /enable assistant and patrol/i }));
+ const setupDialog = await screen.findByRole('dialog', {
+ name: 'Set up Assistant and Patrol',
+ });
+ expect(within(setupDialog).getByText('Set Up Assistant & Patrol')).toBeInTheDocument();
+ fireEvent.click(within(setupDialog).getByRole('button', { name: /OpenRouter/i }));
+ fireEvent.input(screen.getByPlaceholderText('sk-or-...'), {
+ target: { value: 'sk-or-test' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Enable Assistant & Patrol' }));
+
+ await waitFor(() => {
+ expect(notificationErrorMock).toHaveBeenCalledWith(
+ expect.stringContaining('OpenRouter provider'),
+ );
+ });
+ expect(String(notificationErrorMock.mock.calls.at(-1)?.[0] ?? '')).toContain(
+ 'Unable to save Assistant & Patrol settings.',
+ );
+ });
+
it('keeps legacy quickstart-only installs on the provider setup path', async () => {
getSettingsMock.mockResolvedValue({
...baseSettings(),
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 5fcf14ec6d..25f8fc5fbc 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -357,7 +357,7 @@ describe('settings architecture guardrails', () => {
it('keeps settings copy aligned with Infrastructure as the default workspace', () => {
expect(generalSettingsPanelSource).toContain(
- 'Replay the four-stop walkthrough of Infrastructure, Workloads, Storage, and',
+ 'Manage appearance, layout, and default monitoring cadence.',
);
expect(generalSettingsPanelSource).not.toContain('Dashboard, Infrastructure');
expect(networkBoundarySettingsSectionSource).toContain('Pulse URL for Notifications');
@@ -394,6 +394,19 @@ describe('settings architecture guardrails', () => {
);
});
+ it('keeps system AI save feedback tied to provider and Patrol readiness context', () => {
+ expect(aiSettingsStateSource).toContain(
+ "import { apiErrorDetails } from '@/api/responseUtils';",
+ );
+ expect(aiSettingsStateSource).toContain('resolveAISettingsSaveProviderFailure');
+ expect(aiSettingsStateSource).toContain('getAISettingsPatrolReadinessSaveMessage(');
+ expect(aiSettingsStateSource).toContain(
+ "getAISettingsPatrolReadinessSaveMessage(\n updated.patrol_readiness,\n 'Assistant & Patrol enabled',",
+ );
+ expect(aiSettingsStateSource).toContain('notificationStore.warning(patrolReadinessMessage);');
+ expect(aiSettingsStateSource).toContain('getAISettingsSaveProviderFailureMessage(');
+ });
+
it('keeps infrastructure on a source-manager landing with route-backed dialogs', () => {
expect(infrastructureWorkspaceSource).toContain(
"import { ConnectionEditor } from './ConnectionEditor/ConnectionEditor';",
diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.ts
index b06b58f764..66ebce7a62 100644
--- a/frontend-modern/src/components/Settings/useAISettingsState.ts
+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts
@@ -9,6 +9,7 @@ import {
type ProviderHealthState,
type ProviderTestResult,
} from '@/components/Settings/aiSettingsModel';
+import { apiErrorDetails } from '@/api/responseUtils';
import {
aiRuntimeModels,
aiRuntimeModelsError,
@@ -37,6 +38,171 @@ import {
} from '@/utils/aiSettingsPresentation';
import { logger } from '@/utils/logger';
+type AISettingsSaveProviderFailure = {
+ provider: string;
+ model?: string;
+ providerMessage?: string;
+};
+
+const AI_SETTINGS_PROVIDER_PAYLOAD_FIELDS: Record<AIProvider, string[]> = {
+ anthropic: ['anthropic_api_key'],
+ openai: ['openai_api_key', 'openai_base_url'],
+ openrouter: ['openrouter_api_key'],
+ deepseek: ['deepseek_api_key'],
+ gemini: ['gemini_api_key'],
+ ollama: ['ollama_base_url'],
+};
+
+const compactUnique = (values: Array<string | undefined>): string[] => {
+ const seen = new Set<string>();
+ const result: string[] = [];
+ for (const value of values) {
+ const normalized = value?.trim();
+ if (!normalized || seen.has(normalized)) continue;
+ seen.add(normalized);
+ result.push(normalized);
+ }
+ return result;
+};
+
+const isKnownAIProvider = (provider: string): provider is AIProvider =>
+ AI_PROVIDERS.includes(provider as AIProvider);
+
+const providerPayloadEntries = (payload: Record<string, unknown>): string[] =>
+ AI_PROVIDERS.filter((provider) =>
+ AI_SETTINGS_PROVIDER_PAYLOAD_FIELDS[provider].some(
+ (field) => typeof payload[field] === 'string' && String(payload[field]).trim().length > 0,
+ ),
+ );
+
+const modelProviderEntries = (models: string[]): Array<{ provider: string; model: string }> =>
+ models
+ .map((model) => model.trim())
+ .filter(Boolean)
+ .map((model) => ({
+ provider: getProviderFromModelId(model),
+ model,
+ }));
+
+const findModelForProvider = (
+ provider: string,
+ models: Array<{ provider: string; model: string }>,
+): string | undefined => models.find((entry) => entry.provider === provider)?.model;
+
+const isGenericAISettingsSaveFailure = (error: unknown): boolean => {
+ const message = error instanceof Error ? error.message.trim().toLowerCase() : '';
+ if (!message) return true;
+ return (
+ message === 'failed to save assistant & patrol settings' ||
+ message === 'unable to save assistant & patrol settings.' ||
+ message === 'unable to save assistant & patrol settings' ||
+ message.includes('failed to save assistant & patrol settings') ||
+ message.startsWith('request failed with status')
+ );
+};
+
+export function getAISettingsSaveProviderFailureMessage(
+ message: string | undefined,
+ failure?: AISettingsSaveProviderFailure | null,
+): string {
+ const baseMessage = getAISettingsSaveErrorMessage(message);
+ if (!failure?.provider) return baseMessage;
+
+ const providerLabel = getAIProviderDisplayName(failure.provider);
+ const lowerBase = baseMessage.toLowerCase();
+ const context = [
+ lowerBase.includes(providerLabel.toLowerCase()) ? undefined : `${providerLabel} provider`,
+ failure.model && !baseMessage.includes(failure.model) ? `model ${failure.model}` : undefined,
+ failure.providerMessage && !baseMessage.includes(failure.providerMessage)
+ ? failure.providerMessage
+ : undefined,
+ ].filter((value): value is string => Boolean(value));
+
+ return context.length > 0 ? `${context.join(' · ')}: ${baseMessage}` : baseMessage;
+}
+
+export function getAISettingsPatrolReadinessSaveMessage(
+ readiness: AISettingsType['patrol_readiness'] | null | undefined,
+ savedLabel = 'Assistant & Patrol settings saved',
+): string | null {
+ if (!readiness || readiness.status === 'ready') return null;
+
+ const provider = readiness.provider ? getAIProviderDisplayName(readiness.provider) : '';
+ const model = readiness.model?.trim();
+ const context = [
+ readiness.summary?.trim(),
+ provider ? `Provider: ${provider}` : undefined,
+ model ? `Model: ${model}` : undefined,
+ ].filter((value): value is string => Boolean(value));
+ const readinessLabel = readiness.status === 'not_ready' ? 'not ready' : 'degraded';
+
+ return context.length > 0
+ ? `${savedLabel}, but Patrol is ${readinessLabel}: ${context.join(' · ')}`
+ : `${savedLabel}, but Patrol is ${readinessLabel}.`;
+}
+
+export function resolveAISettingsSaveProviderFailure(input: {
+ error: unknown;
+ payload: Record<string, unknown>;
+ providerHealth: Record<AIProvider, ProviderHealthState>;
+ models: string[];
+}): AISettingsSaveProviderFailure | null {
+ const details = apiErrorDetails(input.error);
+ const detailProvider = details?.provider?.trim();
+ const detailModel = details?.model?.trim();
+ if (detailProvider) {
+ return {
+ provider: detailProvider,
+ model: detailModel,
+ providerMessage: details?.cause || details?.reason || details?.summary,
+ };
+ }
+
+ const modelEntries = modelProviderEntries(input.models);
+ const payloadProviders = providerPayloadEntries(input.payload);
+ const canUseLocalProviderContext =
+ payloadProviders.length > 0 || isGenericAISettingsSaveFailure(input.error);
+ if (!canUseLocalProviderContext) {
+ return null;
+ }
+ const candidateProviders = compactUnique([
+ ...payloadProviders,
+ ...modelEntries.map((entry) => entry.provider),
+ ]);
+
+ const erroredCandidate = candidateProviders.find(
+ (provider) => isKnownAIProvider(provider) && input.providerHealth[provider].status === 'error',
+ );
+ if (erroredCandidate && isKnownAIProvider(erroredCandidate)) {
+ return {
+ provider: erroredCandidate,
+ model: findModelForProvider(erroredCandidate, modelEntries),
+ providerMessage: input.providerHealth[erroredCandidate].message,
+ };
+ }
+
+ const anyErroredProvider = AI_PROVIDERS.find(
+ (provider) => input.providerHealth[provider].status === 'error',
+ );
+ if (anyErroredProvider) {
+ return {
+ provider: anyErroredProvider,
+ model: findModelForProvider(anyErroredProvider, modelEntries),
+ providerMessage: input.providerHealth[anyErroredProvider].message,
+ };
+ }
+
+ if (candidateProviders.length === 1) {
+ const provider = candidateProviders[0];
+ return {
+ provider,
+ model: findModelForProvider(provider, modelEntries),
+ };
+ }
+
+ return null;
+}
+
export const useAISettingsState = () => {
const [settings, setSettings] = createSignal<AISettingsType | null>(null);
const [loading, setLoading] = createSignal(false);
@@ -379,8 +545,9 @@ export const useAISettingsState = () => {
const handleSetupSubmit = async () => {
setSetupSaving(true);
+ let payload: Record<string, unknown> = {};
try {
- const payload: Record<string, unknown> = { enabled: true };
+ payload = { enabled: true };
if (setupProvider() === 'anthropic') {
if (!setupApiKey().trim()) {
@@ -427,10 +594,29 @@ export const useAISettingsState = () => {
syncModelCatalogForSettings(updated);
void runProviderPreflight(updated);
handleCloseSetupModal();
- notificationStore.success('Assistant & Patrol enabled! You can customize settings below.');
+ const patrolReadinessMessage = getAISettingsPatrolReadinessSaveMessage(
+ updated.patrol_readiness,
+ 'Assistant & Patrol enabled',
+ );
+ if (patrolReadinessMessage) {
+ notificationStore.warning(patrolReadinessMessage);
+ } else {
+ notificationStore.success('Assistant & Patrol enabled! You can customize settings below.');
+ }
} catch (error) {
logger.error('[AISettings] Setup failed:', error);
- notificationStore.error(error instanceof Error ? error.message : 'Setup failed');
+ const providerFailure = resolveAISettingsSaveProviderFailure({
+ error,
+ payload,
+ providerHealth,
+ models: [form.model, form.chatModel, form.patrolModel, form.autoFixModel],
+ });
+ notificationStore.error(
+ getAISettingsSaveProviderFailureMessage(
+ error instanceof Error ? error.message : 'Setup failed',
+ providerFailure,
+ ),
+ );
} finally {
setSetupSaving(false);
}
@@ -548,8 +734,9 @@ export const useAISettingsState = () => {
}
setSaving(true);
+ let payload: Record<string, unknown> = {};
try {
- const payload: Record<string, unknown> = {
+ payload = {
model: selectedModel,
};
@@ -641,11 +828,27 @@ export const useAISettingsState = () => {
resetForm(updated);
syncModelCatalogForSettings(updated);
void runProviderPreflight(updated);
- notificationStore.success('Assistant & Patrol settings saved');
+ const patrolReadinessMessage = getAISettingsPatrolReadinessSaveMessage(
+ updated.patrol_readiness,
+ );
+ if (patrolReadinessMessage) {
+ notificationStore.warning(patrolReadinessMessage);
+ } else {
+ notificationStore.success('Assistant & Patrol settings saved');
+ }
} catch (error) {
logger.error('[AISettings] Failed to save settings:', error);
+ const providerFailure = resolveAISettingsSaveProviderFailure({
+ error,
+ payload,
+ providerHealth,
+ models: [selectedModel, form.chatModel, form.patrolModel, form.autoFixModel],
+ });
notificationStore.error(
- getAISettingsSaveErrorMessage(error instanceof Error ? error.message : ''),
+ getAISettingsSaveProviderFailureMessage(
+ error instanceof Error ? error.message : '',
+ providerFailure,
+ ),
);
} finally {
setSaving(false);
diff --git a/tests/integration/tests/52-ai-settings-provider-setup.spec.ts b/tests/integration/tests/52-ai-settings-provider-setup.spec.ts
index 770b0e8839..4f5c94f191 100644
--- a/tests/integration/tests/52-ai-settings-provider-setup.spec.ts
+++ b/tests/integration/tests/52-ai-settings-provider-setup.spec.ts
@@ -20,6 +20,15 @@ type MockAISettings = {
ollama_base_url: string;
configured_providers: string[];
available_models: Array<{ id: string; name: string; notable?: boolean }>;
+ patrol_readiness?: {
+ status: string;
+ ready: boolean;
+ cause?: string;
+ summary: string;
+ provider?: string;
+ model?: string;
+ checks: Array<Record<string, unknown>>;
+ };
};
const baseSettings = (): MockAISettings => ({
@@ -46,7 +55,10 @@ test.describe("Assistant & Patrol settings provider setup", () => {
test("OpenRouter setup submits credentials without a hardcoded model and renders backend-selected state", async ({
page,
}, testInfo) => {
- test.skip(testInfo.project.name.startsWith("mobile-"), "Desktop-only settings coverage");
+ test.skip(
+ testInfo.project.name.startsWith("mobile-"),
+ "Desktop-only settings coverage",
+ );
await ensureAuthenticated(page);
@@ -63,7 +75,13 @@ test.describe("Assistant & Patrol settings provider setup", () => {
await page.route("**/api/ai/models", async (route) => {
const models = settings.openrouter_configured
- ? [{ id: "openrouter:runtime-selected-model", name: "Runtime Selected Model", notable: true }]
+ ? [
+ {
+ id: "openrouter:runtime-selected-model",
+ name: "Runtime Selected Model",
+ notable: true,
+ },
+ ]
: [];
await route.fulfill({
status: 200,
@@ -76,7 +94,11 @@ test.describe("Assistant & Patrol settings provider setup", () => {
await route.fulfill({
status: 200,
contentType: "application/json",
- body: JSON.stringify({ success: true, message: "Connection successful", provider: "openrouter" }),
+ body: JSON.stringify({
+ success: true,
+ message: "Connection successful",
+ provider: "openrouter",
+ }),
});
});
@@ -89,7 +111,10 @@ test.describe("Assistant & Patrol settings provider setup", () => {
});
await page.route("**/api/settings/ai/update", async (route) => {
- const body = (route.request().postDataJSON() ?? {}) as Record<string, unknown>;
+ const body = (route.request().postDataJSON() ?? {}) as Record<
+ string,
+ unknown
+ >;
updateRequests.push(body);
settings = {
...settings,
@@ -107,18 +132,35 @@ test.describe("Assistant & Patrol settings provider setup", () => {
});
await page.goto("/settings/system-ai", { waitUntil: "domcontentloaded" });
- await expect(page.getByRole("heading", { name: "Assistant & Patrol", level: 1 })).toBeVisible();
await expect(
- page.getByText("Configure providers and models for Pulse Assistant and Patrol.", { exact: true }).first(),
+ page.getByRole("heading", { name: "Assistant & Patrol", level: 1 }),
+ ).toBeVisible();
+ await expect(
+ page
+ .getByText(
+ "Configure providers and models for Pulse Assistant and Patrol.",
+ { exact: true },
+ )
+ .first(),
).toBeVisible();
- await page.getByRole("button", { name: /enable assistant and patrol/i }).click();
- const setupDialog = page.getByRole("dialog", { name: "Set up Assistant and Patrol" });
- await expect(setupDialog.getByText("Set Up Assistant & Patrol")).toBeVisible();
+ await page
+ .getByRole("button", { name: /enable assistant and patrol/i })
+ .click();
+ const setupDialog = page.getByRole("dialog", {
+ name: "Set up Assistant and Patrol",
+ });
+ await expect(
+ setupDialog.getByText("Set Up Assistant & Patrol"),
+ ).toBeVisible();
await setupDialog.getByRole("button", { name: /OpenRouter/i }).click();
- await setupDialog.getByPlaceholder("sk-or-...").fill("sk-or-runtime-selected");
- await setupDialog.getByRole("button", { name: "Enable Assistant & Patrol" }).click();
+ await setupDialog
+ .getByPlaceholder("sk-or-...")
+ .fill("sk-or-runtime-selected");
+ await setupDialog
+ .getByRole("button", { name: "Enable Assistant & Patrol" })
+ .click();
await expect.poll(() => updateRequests.length).toBe(1);
expect(updateRequests[0]).toEqual({
@@ -127,8 +169,12 @@ test.describe("Assistant & Patrol settings provider setup", () => {
});
expect(updateRequests[0]).not.toHaveProperty("model");
- await expect(page.getByText("Assistant & Patrol Model Overrides")).toBeVisible();
- const workloadDiscoveryToggle = page.getByRole("button", { name: /workload discovery/i });
+ await expect(
+ page.getByText("Assistant & Patrol Model Overrides"),
+ ).toBeVisible();
+ const workloadDiscoveryToggle = page.getByRole("button", {
+ name: /workload discovery/i,
+ });
await expect(workloadDiscoveryToggle).toBeVisible();
await workloadDiscoveryToggle.click();
await expect(page.getByText("Enable workload discovery")).toBeVisible();
@@ -138,9 +184,115 @@ test.describe("Assistant & Patrol settings provider setup", () => {
{ exact: true },
),
).toBeVisible();
- await expect(page.getByRole("button", { name: /enable assistant and patrol/i })).toHaveAttribute(
- "aria-pressed",
- "true",
+ await expect(
+ page.getByRole("button", { name: /enable assistant and patrol/i }),
+ ).toHaveAttribute("aria-pressed", "true");
+ });
+
+ test("provider setup surfaces saved Patrol readiness warnings with provider and model context", async ({
+ page,
+ }, testInfo) => {
+ test.skip(
+ testInfo.project.name.startsWith("mobile-"),
+ "Desktop-only settings coverage",
);
+
+ await ensureAuthenticated(page);
+
+ let settings = baseSettings();
+
+ await page.route("**/api/settings/ai", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(settings),
+ });
+ });
+
+ await page.route("**/api/ai/models", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ models: [
+ {
+ id: "openrouter:deepseek/deepseek-r1",
+ name: "DeepSeek R1",
+ notable: true,
+ },
+ ],
+ }),
+ });
+ });
+
+ await page.route("**/api/ai/test/openrouter", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ success: true,
+ message: "Connection successful",
+ provider: "openrouter",
+ }),
+ });
+ });
+
+ await page.route("**/api/ai/chat/sessions", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify([]),
+ });
+ });
+
+ await page.route("**/api/settings/ai/update", async (route) => {
+ settings = {
+ ...settings,
+ enabled: true,
+ configured: true,
+ model: "openrouter:deepseek/deepseek-r1",
+ patrol_model: "openrouter:deepseek/deepseek-r1",
+ openrouter_configured: true,
+ configured_providers: ["openrouter"],
+ patrol_readiness: {
+ status: "not_ready",
+ ready: false,
+ cause: "model_unsupported_tools",
+ summary:
+ "The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.",
+ provider: "openrouter",
+ model: "openrouter:deepseek/deepseek-r1",
+ checks: [],
+ },
+ };
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(settings),
+ });
+ });
+
+ await page.goto("/settings/system-ai", { waitUntil: "domcontentloaded" });
+ await page
+ .getByRole("button", { name: /enable assistant and patrol/i })
+ .click();
+ const setupDialog = page.getByRole("dialog", {
+ name: "Set up Assistant and Patrol",
+ });
+ await setupDialog.getByRole("button", { name: /OpenRouter/i }).click();
+ await setupDialog
+ .getByPlaceholder("sk-or-...")
+ .fill("sk-or-runtime-selected");
+ await setupDialog
+ .getByRole("button", { name: "Enable Assistant & Patrol" })
+ .click();
+
+ await expect(
+ page.getByText("Assistant & Patrol enabled, but Patrol is not ready"),
+ ).toBeVisible();
+ await expect(page.getByText("Provider: OpenRouter")).toBeVisible();
+ await expect(
+ page.getByText("Model: openrouter:deepseek/deepseek-r1"),
+ ).toBeVisible();
});
});