feat: Add an on/off switch and env var for the n8n Assistant (#42121)

This commit is contained in:
oleg authored and GitHub committed 2026-11-02 08:44:10 +00:00
1 parent dc01388d0c
commit d5bea2f387
25 files changed
+677 -293

No files matched your search

@@ -74,6 +74,7 @@ N8N_PORT=5680 \
N8N_RUNNERS_BROKER_PORT=5681 \
N8N_USER_FOLDER=<printed-temp-directory> \
E2E_TESTS=true \
N8N_INSTANCE_AI_ENABLED=true \
N8N_ENABLED_MODULES=instance-ai,agents \
N8N_AI_ENABLED=true \
N8N_INSTANCE_AI_EVAL_INSTANCE=true \
@@ -127,6 +127,8 @@ flag wins — use it.
a key is missing — and grep its names with `^[A-Za-z0-9_]+=`, since a
`^[A-Z_]*=` pattern silently drops every `N8N_*` var (the digit).
- `E2E_TESTS=true` — exposes `POST /rest/e2e/reset` so you can seed a known owner.
- `N8N_INSTANCE_AI_ENABLED=true` turns the Assistant on. `E2E_TESTS=true`
reports the Enterprise plan, where the Assistant is off by default.
**Seed an owner** (a fresh instance has none → login 401s). Full payload shape in
the [README](../../../packages/@n8n/instance-ai/evaluations/README.md) quick
@@ -147,7 +149,7 @@ second instance its own everything:
# N8N_AI_ANTHROPIC_KEY. Skip .env.local: its staging base-url / port-5678
# defaults fight the settings below.
N8N_PORT=5680 N8N_RUNNERS_BROKER_PORT=5681 N8N_USER_FOLDER=/tmp/n8n-eval-run \
E2E_TESTS=true N8N_INSTANCE_AI_EVAL_INSTANCE=true N8N_AI_ASSISTANT_BASE_URL= \
E2E_TESTS=true N8N_INSTANCE_AI_EVAL_INSTANCE=true N8N_INSTANCE_AI_ENABLED=true N8N_AI_ASSISTANT_BASE_URL= \
npx dotenvx run -f .env.eval -- \
sh -c 'ANTHROPIC_API_KEY="$N8N_AI_ANTHROPIC_KEY" exec pnpm start'
# then seed the owner (above), and run the eval with: --base-url http://localhost:5680
+4
View File
@@ -17,6 +17,10 @@ N8N_ENABLED_MODULES=instance-ai
# Register the eval API routes. Without it the harness gets 404 from them.
N8N_INSTANCE_AI_EVAL_INSTANCE=true
# Turn the Assistant on by default. It is off by default on the Enterprise
# plan, which E2E mode (E2E_TESTS=true) reports.
N8N_INSTANCE_AI_ENABLED=true
# Model key for the builder and the eval helper (mock generation, verifier,
# user-proxy, expectation judge). When the instance runs without the proxy, the
# model client reads ANTHROPIC_API_KEY directly, so export that too if you go
@@ -450,6 +450,7 @@ jobs:
-e EXECUTIONS_DATA_PRUNE=true \
-e EXECUTIONS_DATA_MAX_AGE=1 \
-e E2E_TESTS=true \
-e N8N_INSTANCE_AI_ENABLED=true \
-e N8N_ENABLED_MODULES=instance-ai,agents \
-e N8N_AI_ENABLED=true \
-e INSTANCE_AI_BRAVE_SEARCH_API_KEY="$INSTANCE_AI_BRAVE_SEARCH_API_KEY" \
+2
View File
@@ -191,10 +191,12 @@ jobs:
# agents registers the agent-builder MCP tools so the suite measures
# workflow building with the production tool surface, catching
# tool-choice regressions the extra tools could introduce.
# E2E mode reports the Enterprise plan, where the Assistant is off by default.
for i in "${!PORTS[@]}"; do
port="${PORTS[$i]}"
docker run -d --name "n8n-eval-mcp-$((i + 1))" \
-e E2E_TESTS=true \
-e N8N_INSTANCE_AI_ENABLED=true \
-e N8N_ENABLED_MODULES=instance-ai,agents \
-e N8N_AI_ENABLED=true \
-e N8N_INSTANCE_AI_MODEL_API_KEY="$EVALS_ANTHROPIC_KEY" \
@@ -5,6 +5,14 @@ import { concurrencyLimitSchema } from '../schemas';
@Config
export class InstanceAiConfig {
/**
* Whether the n8n Assistant is on when no admin has turned it on or off in Settings > Assistant.
* When unset, it's off on the Enterprise plan and on for all other plans. A choice saved in
* Settings > Assistant overrides this variable.
*/
@Env('N8N_INSTANCE_AI_ENABLED')
enabled?: boolean;
/**
* Enable workflow suggestions, self-healing investigations, and result review.
*/
@@ -11,6 +11,7 @@ persisted in settings takes precedence over `N8N_INSTANCE_AI_SANDBOX_PROVIDER`.
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `N8N_INSTANCE_AI_ENABLED` | boolean | unset | Whether the n8n Assistant is on when no admin has turned it on or off in Settings > Assistant. When unset, it's off on the Enterprise plan and on for all other plans. A choice saved in Settings > Assistant overrides this variable. |
| `N8N_INSTANCE_AI_MODEL` | string | `anthropic/claude-opus-4-8` | LLM model in `provider/model` format for built-in providers, or a bare model name when `N8N_INSTANCE_AI_MODEL_URL` is set. The effective model must be non-empty for the agent to run successfully. Opus 5: `anthropic/claude-opus-5`. Vertex Claude: `google-vertex-anthropic/claude-opus-4-8`. |
| `N8N_INSTANCE_AI_MODEL_URL` | string | `''` | Base URL for an OpenAI-compatible endpoint (e.g. `http://localhost:1234/v1` for LM Studio). When set, model requests go to this URL instead of the built-in provider. |
| `N8N_INSTANCE_AI_MODEL_API_KEY` | string | `''` | Explicit API key for the environment-selected model. It works with built-in providers and custom endpoints. When it is empty, built-in providers can use their standard API-key environment variable. Some local endpoints do not require a key. |
@@ -75,7 +75,7 @@ You need an n8n instance running with Instance AI enabled, a seeded owner accoun
3. **Create the owner account**. First time only: open `http://localhost:5678`, sign up with the email/password from your `.env.local`. If you'd rather reset to a known state (useful after deleting the DB or between iterations), start the server with `E2E_TESTS=true` and `curl` the reset endpoint:
```bash
N8N_INSTANCE_AI_EVAL_INSTANCE=true E2E_TESTS=true dotenvx run -f .env.local -- pnpm dev:ai
N8N_INSTANCE_AI_EVAL_INSTANCE=true N8N_INSTANCE_AI_ENABLED=true E2E_TESTS=true dotenvx run -f .env.local -- pnpm dev:ai
# then in another shell:
curl -sf -X POST http://localhost:5678/rest/e2e/reset \
-H "Content-Type: application/json" \
@@ -98,6 +98,7 @@ INCLUDE_TEST_CONTROLLER=true pnpm build:docker
# Start a container (E2E_TESTS=true exposes /rest/e2e/reset)
docker run -d --name n8n-eval \
-e E2E_TESTS=true \
-e N8N_INSTANCE_AI_ENABLED=true \
-e N8N_ENABLED_MODULES=instance-ai,agents \
-e N8N_AI_ENABLED=true \
-e N8N_INSTANCE_AI_EVAL_INSTANCE=true \
@@ -1330,6 +1331,8 @@ status.
**`Wrong username or password` on login.** Your instance has no owner. Run the `rest/e2e/reset` curl from [Quick start](#quick-start) (needs `E2E_TESTS=true` on the server).
**`Instance AI is disabled` (403).** The Assistant is off by default on the Enterprise plan, and a server started with `E2E_TESTS=true` reports that plan. Set `N8N_INSTANCE_AI_ENABLED=true` on the server. Turning it on in Settings > Assistant also works, but the `rest/e2e/reset` call deletes that saved choice.
**`Have reached end of quota` mid-run.** You're hitting the hosted AI proxy's per-tenant quota. Set `N8N_AI_ASSISTANT_BASE_URL=""` to hit Anthropic directly with your `N8N_INSTANCE_AI_MODEL_API_KEY`. Also consider lowering `--concurrency`.
**All scenarios timing out.** Check that the server is up (`curl localhost:5678/healthz`) and that `N8N_INSTANCE_AI_MODEL_API_KEY` is set. A full build is ~60–180s; timeouts past `--timeout-ms` usually mean the agent is looping.
@@ -437,6 +437,7 @@ for port in "${PORTS[@]}"; do
# Same bounds as CI (test-evals-instance-ai.yml): capped + restartable
# lanes, pruned executions. An eval instance takes feature flags from env only.
# E2E mode reports the Enterprise plan, where the Assistant is off by default.
docker run -d --name "$name" \
"${DOCKER_RUN_ARGS[@]}" \
--memory 2.5g --memory-swap 2.5g \
@@ -446,6 +447,7 @@ for port in "${PORTS[@]}"; do
-e EXECUTIONS_DATA_PRUNE=true \
-e EXECUTIONS_DATA_MAX_AGE=1 \
-e E2E_TESTS=true \
-e N8N_INSTANCE_AI_ENABLED=true \
-e N8N_INSTANCE_AI_EVAL_INSTANCE=true \
-e N8N_USER_FOLDER=/home/node/.n8n \
-p "${port}:5678" \
@@ -266,6 +266,21 @@ describe('License', () => {
expect(mainPlan).toBeUndefined();
});
describe('isEnterprisePlan', () => {
it.each([
{ planName: 'Enterprise', expected: true },
{ planName: 'Business', expected: false },
])('returns $expected when the plan is $planName', ({ planName, expected }) => {
vi.spyOn(license, 'getPlanName').mockReturnValue(planName);
expect(license.isEnterprisePlan()).toBe(expected);
});
it('returns false when the license has no plan', () => {
expect(license.isEnterprisePlan()).toBe(false);
});
});
describe('onExpirySoon', () => {
it.each([
{
+5
View File
@@ -503,6 +503,11 @@ export class License implements LicenseProvider {
return this.getValue('planName') ?? 'Community';
}
/** Uses `getPlanName()` so that overrides of it, such as in E2E mode, also apply. */
isEnterprisePlan(): boolean {
return this.getPlanName() === 'Enterprise';
}
getExpiryDate(): Date | null {
try {
return this.manager?.getExpiryDate() ?? null;
@@ -5,6 +5,7 @@ import { type EventService, type CredentialsFinderService } from '@n8n/backend-s
import type { InstanceAiConfig } from '@n8n/config';
import type { CredentialsEntity, DbLockService, SettingsRepository, User } from '@n8n/db';
import { Container } from '@n8n/di';
import { jsonParse } from 'n8n-workflow';
import { mock } from 'vitest-mock-extended';
import { UnprocessableRequestError } from '@n8n/errors';
@@ -16,12 +17,14 @@ import {
} from '@/services/sandbox-settings.service';
import type { CredentialsService } from '@/credentials/credentials.service';
import type { InstanceCredentialBroker } from '@/credentials/instance-credential-broker';
import type { License } from '@/license';
import {
INSTANCE_AI_MODEL_CREDENTIAL_POLICY,
INSTANCE_AI_SEARCH_CREDENTIAL_POLICY,
InstanceAiSettingsService,
} from '../instance-ai-settings.service';
import type { InstanceAiThreadRepository } from '../repositories/instance-ai-thread.repository';
type CredentialOperationContext = NonNullable<
Parameters<InstanceCredentialBroker['clearForUse']>[1]
@@ -57,6 +60,8 @@ describe('InstanceAiSettingsService', () => {
const instanceCredentialBroker = mock<InstanceCredentialBroker>();
const sandboxSettingsService = mock<SandboxSettingsService>();
const eventService = mock<EventService>();
const license = mock<License>();
const threadRepository = mock<InstanceAiThreadRepository>();
const logger = mock<Logger>();
let service: InstanceAiSettingsService;
@@ -72,6 +77,8 @@ describe('InstanceAiSettingsService', () => {
instanceCredentialBroker,
sandboxSettingsService,
eventService,
license,
threadRepository,
);
beforeEach(() => {
@@ -101,8 +108,11 @@ describe('InstanceAiSettingsService', () => {
vertexProjectId: '',
vertexLocation: '',
vertexServiceAccountJson: '',
enabled: undefined,
});
globalConfig.deployment.type = 'default';
license.isEnterprisePlan.mockReturnValue(false);
threadRepository.exists.mockResolvedValue(false);
instanceCredentialBroker.listForUse.mockResolvedValue([]);
instanceCredentialBroker.getAssignedCredentialId.mockResolvedValue(null);
sandboxSettingsService.getProvider.mockImplementation(() =>
@@ -1264,6 +1274,110 @@ describe('InstanceAiSettingsService', () => {
});
});
describe('enabled', () => {
it('is on for a non-Enterprise plan when nothing is saved', async () => {
await service.loadFromDb();
expect(service.isInstanceAiEnabled()).toBe(true);
expect(service.isAgentEnabled()).toBe(true);
expect((await service.getAdminSettings()).enabled).toBe(true);
});
it('is off on Enterprise without threads and saves nothing', async () => {
license.isEnterprisePlan.mockReturnValue(true);
await service.loadFromDb();
expect(service.isInstanceAiEnabled()).toBe(false);
expect((await service.getAdminSettings()).enabled).toBe(false);
expect(settingsRepository.upsertByKey).not.toHaveBeenCalled();
});
it('saves enabled for Enterprise with threads and keeps it after the threads are gone', async () => {
license.isEnterprisePlan.mockReturnValue(true);
threadRepository.exists.mockResolvedValue(true);
persistedSettingsValue = JSON.stringify({ mcpAccessEnabled: false });
await service.loadFromDb();
expect(jsonParse(persistedSettingsValue)).toEqual({
mcpAccessEnabled: false,
enabled: true,
});
expect(service.isInstanceAiEnabled()).toBe(true);
threadRepository.exists.mockResolvedValue(false);
service = createService();
await service.loadFromDb();
expect(service.isInstanceAiEnabled()).toBe(true);
});
it('does not overwrite a choice saved before it got the lock', async () => {
license.isEnterprisePlan.mockReturnValue(true);
threadRepository.exists.mockResolvedValue(true);
settingsRepository.findByKeyInContext.mockResolvedValueOnce({
key: 'instanceAi.settings',
value: JSON.stringify({ enabled: false }),
loadOnStartup: true,
} as never);
await service.loadFromDb();
expect(settingsRepository.upsertByKey).not.toHaveBeenCalled();
expect(service.isInstanceAiEnabled()).toBe(false);
});
it('prefers a saved choice over the env var and the plan', async () => {
globalConfig.instanceAi.enabled = true;
persistedSettingsValue = JSON.stringify({ enabled: false });
await service.loadFromDb();
expect(service.isInstanceAiEnabled()).toBe(false);
globalConfig.instanceAi.enabled = false;
license.isEnterprisePlan.mockReturnValue(true);
persistedSettingsValue = JSON.stringify({ enabled: true });
await service.reloadFromDb();
expect(service.isInstanceAiEnabled()).toBe(true);
});
it('prefers the env var over the plan and saves nothing', async () => {
license.isEnterprisePlan.mockReturnValue(true);
threadRepository.exists.mockResolvedValue(true);
globalConfig.instanceAi.enabled = false;
await service.loadFromDb();
expect(service.isInstanceAiEnabled()).toBe(false);
expect(settingsRepository.upsertByKey).not.toHaveBeenCalled();
globalConfig.instanceAi.enabled = true;
expect(service.isInstanceAiEnabled()).toBe(true);
});
it('follows a plan change after load without a reload', async () => {
await service.loadFromDb();
license.isEnterprisePlan.mockReturnValue(true);
expect(service.isInstanceAiEnabled()).toBe(false);
expect(service.isAgentEnabled()).toBe(false);
});
it('does not save enabled when another setting is saved', async () => {
await service.updateAdminSettings({ mcpAccessEnabled: false });
expect(jsonParse(persistedSettingsValue ?? '{}')).not.toHaveProperty('enabled');
license.isEnterprisePlan.mockReturnValue(true);
expect(service.isInstanceAiEnabled()).toBe(false);
});
});
describe('instance model credential', () => {
beforeEach(() => {
aiService.isProxyEnabled.mockReturnValue(false);
@@ -44,6 +44,7 @@ import {
type ResolvedInstanceCredential,
} from '@/credentials/instance-credential-broker';
import { ConflictError, ForbiddenError, UnprocessableRequestError } from '@n8n/errors';
import { License } from '@/license';
import { AiService } from '@/services/ai.service';
import {
INSTANCE_AI_DAYTONA_CREDENTIAL_POLICY,
@@ -54,6 +55,7 @@ import {
export { INSTANCE_AI_DAYTONA_CREDENTIAL_POLICY, INSTANCE_AI_N8N_SANDBOX_CREDENTIAL_POLICY };
import { withModelName } from './model-config-name';
import { InstanceAiThreadRepository } from './repositories/instance-ai-thread.repository';
import {
N8N_SANDBOX_SERVICE_URL_REQUIRED_MESSAGE,
normalizeSandboxProvider,
@@ -282,8 +284,8 @@ export class InstanceAiSettingsService {
private sandboxProviderOverride?: InstanceAiSandboxProvider;
/** Whether n8n Agent is enabled for this instance. */
private enabled = true;
/** The saved on/off choice. Unset means the env var or the license plan decides. */
private enabled?: boolean;
/** Whether users may connect the n8n Assistant to MCP servers from the registry. */
private mcpAccessEnabled = true;
@@ -309,6 +311,8 @@ export class InstanceAiSettingsService {
private readonly instanceCredentialBroker: InstanceCredentialBroker,
private readonly sandboxSettingsService: SandboxSettingsService,
private readonly eventService: EventService,
private readonly license: License,
private readonly threadRepository: InstanceAiThreadRepository,
) {
this.config = globalConfig.instanceAi;
this.deploymentConfig = globalConfig.deployment;
@@ -351,6 +355,29 @@ export class InstanceAiSettingsService {
if (sandboxStatus.unavailableReason) {
logger.warn(`Sandbox unavailable: ${sandboxStatus.unavailableReason}`);
}
await this.keepEnabledIfInUse();
}
/**
* Runs at startup. Enterprise defaults to off, but an instance that already uses the
* Assistant stays on.
* Threads are deleted with their user, so save the choice instead of re-checking them.
*/
private async keepEnabledIfInUse(): Promise<void> {
if (this.enabled !== undefined || this.config.enabled !== undefined) return;
if (!this.license.isEnterprisePlan() || !(await this.threadRepository.exists())) return;
await this.withPersistedAdminSettings(async (ctx, persisted) => {
if (persisted.enabled === undefined) {
persisted.enabled = true;
await this.settingsRepository.upsertByKey(
ADMIN_SETTINGS_KEY,
JSON.stringify(persisted),
true,
ctx,
);
}
this.enabled = persisted.enabled;
});
}
// ── Admin settings ────────────────────────────────────────────────────
@@ -425,7 +452,7 @@ export class InstanceAiSettingsService {
: c.sandboxProvider,
);
return {
enabled: this.enabled,
enabled: this.isInstanceAiEnabled(),
permissions: { ...this.permissions },
mcpAccessEnabled: this.mcpAccessEnabled,
sandboxEnabled: c.sandboxEnabled,
@@ -1237,9 +1264,9 @@ export class InstanceAiSettingsService {
return this.mcpAccessEnabled;
}
/** Whether the n8n Agent is enabled by the admin. */
/** Whether the n8n Agent is enabled for this instance. */
isAgentEnabled(): boolean {
return this.enabled;
return this.isInstanceAiEnabled();
}
isBrowserUseEnabled(): boolean {
@@ -1264,7 +1291,8 @@ export class InstanceAiSettingsService {
/** Whether Instance AI chat and main UI are enabled (settings always available when module loads). */
isInstanceAiEnabled(): boolean {
return this.enabled;
// Resolved on every read because the license plan can change at runtime.
return this.enabled ?? this.config.enabled ?? !this.license.isEnterprisePlan();
}
/** Public, detail-free setup state used to gate member-facing entry points. */
@@ -43,6 +43,7 @@ For example, create `.env.mcp-evals` at the repo root:
N8N_ENABLED_MODULES=instance-ai
N8N_AI_ENABLED=true
N8N_INSTANCE_AI_EVAL_INSTANCE=true
N8N_INSTANCE_AI_ENABLED=true
N8N_INSTANCE_AI_MODEL=anthropic/claude-sonnet-4-5-20250929
N8N_INSTANCE_AI_MODEL_API_KEY=sk-ant-...
@@ -1,4 +1,4 @@
import { testDb } from '@n8n/backend-test-utils';
import { getPersonalProject, testDb, testModules } from '@n8n/backend-test-utils';
import type { User } from '@n8n/db';
import {
CredentialsRepository,
@@ -7,9 +7,11 @@ import {
} from '@n8n/db';
import { Container } from '@n8n/di';
import { CREDENTIAL_BLANKING_VALUE } from 'n8n-workflow';
import { randomUUID } from 'node:crypto';
import { CredentialsService } from '@/credentials/credentials.service';
import { InstanceCredentialBroker } from '@/credentials/instance-credential-broker';
import { License } from '@/license';
import { PolicyEnforcementService } from '@/policy/policy-enforcement.service';
import {
INSTANCE_AI_DAYTONA_CREDENTIAL_POLICY,
@@ -18,6 +20,7 @@ import {
INSTANCE_AI_SEARCH_CREDENTIAL_POLICY,
InstanceAiSettingsService,
} from '@/modules/instance-ai/instance-ai-settings.service';
import { InstanceAiThreadRepository } from '@/modules/instance-ai/repositories/instance-ai-thread.repository';
import { createOwner } from './shared/db/users';
import { initCredentialsTypes } from './shared/utils';
@@ -27,6 +30,7 @@ describe('InstanceAiSettingsService (integration)', () => {
let credentialsRepository: CredentialsRepository;
let assignmentRepository: InstanceCredentialAssignmentRepository;
let settingsRepository: SettingsRepository;
let threadRepository: InstanceAiThreadRepository;
let owner: User;
const modelUpdate = {
@@ -35,6 +39,7 @@ describe('InstanceAiSettingsService (integration)', () => {
};
beforeAll(async () => {
await testModules.loadModules(['instance-ai']);
await testDb.init();
await initCredentialsTypes();
@@ -49,12 +54,14 @@ describe('InstanceAiSettingsService (integration)', () => {
credentialsRepository = Container.get(CredentialsRepository);
assignmentRepository = Container.get(InstanceCredentialAssignmentRepository);
settingsRepository = Container.get(SettingsRepository);
threadRepository = Container.get(InstanceAiThreadRepository);
owner = await createOwner();
});
afterEach(async () => {
vi.restoreAllMocks();
await testDb.truncate(['InstanceCredentialAssignment', 'CredentialsEntity', 'Settings']);
await threadRepository.delete({});
});
afterAll(async () => {
@@ -198,4 +205,23 @@ describe('InstanceAiSettingsService (integration)', () => {
credentialsRepository.findOneByOrFail({ id: workflowCredential.id }),
).resolves.toMatchObject({ name: 'Workflow credential', data: 'workflow-encrypted' });
});
it('saves enabled on Enterprise only once a thread exists', async () => {
vi.spyOn(Container.get(License), 'getPlanName').mockReturnValue('Enterprise');
await service.loadFromDb();
expect(service.isInstanceAiEnabled()).toBe(false);
await expect(settingsRepository.findByKey('instanceAi.settings')).resolves.toBeNull();
const project = await getPersonalProject(owner);
await threadRepository.save(
threadRepository.create({ id: randomUUID(), resourceId: owner.id, projectId: project.id }),
);
await service.loadFromDb();
const persisted = await settingsRepository.findByKey('instanceAi.settings');
expect(persisted?.value).toContain('"enabled":true');
expect(service.isInstanceAiEnabled()).toBe(true);
});
});
@@ -4,9 +4,9 @@ import userEvent from '@testing-library/user-event';
import EnterpriseReadinessBadge from './EnterpriseReadinessBadge.vue';
describe('EnterpriseReadinessBadge', () => {
it('renders the limited enterprise support label', () => {
it('renders the limited enterprise readiness label', () => {
const { getByText } = render(EnterpriseReadinessBadge);
expect(getByText('Limited enterprise support')).toBeInTheDocument();
expect(getByText('Limited enterprise readiness')).toBeInTheDocument();
});
it('renders xxsmall badge correctly', () => {
@@ -23,7 +23,7 @@ describe('EnterpriseReadinessBadge', () => {
const { getByText, findAllByText } = render(EnterpriseReadinessBadge);
await userEvent.tab();
expect(getByText('Limited enterprise support').closest('.n8n-badge')).toHaveFocus();
expect(getByText('Limited enterprise readiness').closest('.n8n-badge')).toHaveFocus();
expect(
await findAllByText(
@@ -19,7 +19,7 @@ exports[`EnterpriseReadinessBadge > renders xsmall badge correctly 1`] = `
>
Limited enterprise support
Limited enterprise readiness
</span>
@@ -53,7 +53,7 @@ exports[`EnterpriseReadinessBadge > renders xxsmall badge correctly 1`] = `
>
Limited enterprise support
Limited enterprise readiness
</span>
@@ -84,7 +84,7 @@ export default {
'codeBlock.expand': 'Expand code',
'codeBlock.collapse': 'Collapse code',
'previewBadge.preview': 'Preview',
'enterpriseReadinessBadge.limited': 'Limited enterprise support',
'enterpriseReadinessBadge.limited': 'Limited enterprise readiness',
'enterpriseReadinessBadge.tooltip':
"Some enterprise capabilities don't cover this feature yet. See docs for details.",
'settingsPageHeader.docsLeadingText': 'Learn more in the ',
@@ -6477,10 +6477,6 @@
"agents.modelSelector.freeCredits.description": "Get {credits} free OpenAI API credits. Try it with gpt-5-mini.",
"settings.n8nAgent.enable.label": "Enable n8n Assistant",
"settings.n8nAgent.enable.description": "When enabled, everyone on this instance can use it.",
"settings.n8nAgent.status.enabled": "Enabled",
"settings.n8nAgent.status.setupRequired": "Setup required",
"settings.n8nAgent.status.enable": "Enable",
"settings.n8nAgent.status.manage": "Manage n8n Assistant status",
"settings.n8nAgent.status.disable": "Disable",
"settings.n8nAgent.status.disable.title": "Disable n8n Assistant?",
"settings.n8nAgent.status.disable.description": "This prevents everyone on this instance from using n8n Assistant. Existing conversations won't be deleted. You can turn it back on later.",
@@ -131,14 +131,14 @@ describe('SettingsChatHubView', () => {
expect(setChatEnabledMock).toHaveBeenCalledWith(true);
});
it('shows the Preview and limited enterprise support badges next to the title on enterprise', () => {
it('shows the Preview and limited enterprise readiness badges next to the title on enterprise', () => {
const { getByText, getByTestId } = renderComponent();
const titleRow = getByText('Chat').parentElement;
expect(titleRow).toContainElement(getByTestId('chat-hub-preview-badge'));
expect(titleRow).toContainElement(getByTestId('chat-hub-enterprise-readiness-badge'));
expect(getByTestId('chat-hub-enterprise-readiness-badge')).toHaveTextContent(
'Limited enterprise support',
'Limited enterprise readiness',
);
});
@@ -3,6 +3,7 @@ import { fireEvent, waitFor } from '@testing-library/vue';
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import { createComponentRenderer } from '@/__tests__/render';
import { MODAL_CONFIRM } from '@/app/constants';
import SettingsInstanceAiView from '../views/SettingsInstanceAiView.vue';
import ConnectionDialog from '../components/settings/ConnectionDialog.vue';
import { useInstanceAiSettingsStore } from '../instanceAiSettings.store';
@@ -47,9 +48,30 @@ vi.mock('@/app/utils/rbac/permissions', () => ({
hasPermission: vi.fn().mockReturnValue(true),
}));
const { contextPreferencesEnabledMock, contextSkillsEnabledMock } = vi.hoisted(() => ({
const {
contextPreferencesEnabledMock,
contextSkillsEnabledMock,
confirmMock,
testSavedCredentialMock,
} = vi.hoisted(() => ({
contextPreferencesEnabledMock: vi.fn(() => true),
contextSkillsEnabledMock: vi.fn(() => true),
confirmMock: vi.fn(),
testSavedCredentialMock: vi.fn(),
}));
vi.mock('../composables/useInstanceCredentialTest', async (importOriginal) => {
const actual = await importOriginal<typeof import('../composables/useInstanceCredentialTest')>();
return {
useInstanceCredentialTest: () => ({
...actual.useInstanceCredentialTest(),
testSavedCredential: testSavedCredentialMock,
}),
};
});
vi.mock('@/app/composables/useMessage', () => ({
useMessage: () => ({ confirm: confirmMock }),
}));
vi.mock('@/features/settings/context/context.utils', () => ({
@@ -78,6 +100,13 @@ function setPlanName(settingsStore: ReturnType<typeof useSettingsStore>, planNam
settingsStore.settings.license = { ...settingsStore.settings.license, planName };
}
const fullyConfigured = {
modelEnvConfigured: true,
sandboxEnabled: true,
sandboxEnvConfigured: true,
searchDisabled: true,
};
function setModuleSettings(
settingsStore: ReturnType<typeof useSettingsStore>,
instanceAi: FrontendModuleSettings['instance-ai'],
@@ -94,6 +123,7 @@ describe('SettingsInstanceAiView', () => {
vi.clearAllMocks();
vi.mocked(fetchSettings).mockResolvedValue(null as never);
vi.mocked(hasPermission).mockReturnValue(true);
testSavedCredentialMock.mockResolvedValue(true);
const pinia = createTestingPinia({ stubActions: false });
setActivePinia(pinia);
fetchCredentialTypesSpy = vi
@@ -278,7 +308,7 @@ describe('SettingsInstanceAiView', () => {
});
describe('page header', () => {
it('shows the limited enterprise support badge next to the title on enterprise', () => {
it('shows the limited enterprise readiness badge next to the title on enterprise', () => {
setPlanName(settingsStore, 'Enterprise');
const { getByRole, getByTestId } = renderComponent();
@@ -288,7 +318,7 @@ describe('SettingsInstanceAiView', () => {
);
});
it('does not show the limited enterprise support badge on other plans', () => {
it('does not show the limited enterprise readiness badge on other plans', () => {
setPlanName(settingsStore, 'Business');
const { queryByTestId } = renderComponent();
@@ -301,84 +331,292 @@ describe('SettingsInstanceAiView', () => {
});
});
describe('status row', () => {
it('renders the enabled status action', () => {
store.$patch({
settings: {
...store.settings!,
modelCredentialId: 'openai-id',
modelEnvConfigured: true,
sandboxEnabled: true,
sandboxEnvConfigured: true,
searchDisabled: true,
},
});
const { getByTestId, getByText } = renderComponent();
expect(getByTestId('n8n-agent-status-menu')).toBeVisible();
expect(getByText('settings.n8nAgent.status.enabled')).toBeVisible();
});
describe('enable switch', () => {
const modelSaveDialog = 'n8n-agent-model-dialog-save';
it('renders a pulsing success dot when enabled and fully configured', () => {
store.$patch({
settings: {
...store.settings!,
modelCredentialId: 'openai-id',
modelEnvConfigured: true,
sandboxEnabled: true,
sandboxEnvConfigured: true,
searchDisabled: true,
},
function mockPersistEnabled() {
vi.mocked(store.fetch).mockResolvedValue(true);
return vi.mocked(store.persistEnabled).mockImplementation(async (value) => {
store.$patch({ settings: { ...store.settings!, enabled: value } });
return true;
});
}
/** Applies each saved draft to the settings, like the server would. */
function mockSave() {
return vi.mocked(store.save).mockImplementation(async () => {
const draft = { ...store.draft };
const next = { ...store.settings! };
if (draft.modelConnection) {
next.modelCredentialId = 'saved-model';
next.modelName = draft.modelName ?? null;
}
if (draft.sandboxEnabled !== undefined) next.sandboxEnabled = draft.sandboxEnabled;
if (draft.searchDisabled !== undefined) next.searchDisabled = draft.searchDisabled;
store.$patch({ settings: next });
for (const key of Object.keys(store.draft)) Reflect.deleteProperty(store.draft, key);
return true;
});
}
function disable(overrides: Record<string, unknown> = {}) {
store.$patch({ settings: { ...store.settings!, enabled: false, ...overrides } });
setModuleSettings(settingsStore, { ...defaultModuleSettings, enabled: false });
}
it('shows the switch on when enabled and fully configured', () => {
store.$patch({ settings: { ...store.settings!, ...fullyConfigured } });
const { getByTestId } = renderComponent();
const dot = getByTestId('n8n-agent-status-dot');
expect(dot.className).toContain('success');
expect(dot.className).toContain('pulse');
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'true');
});
it('renders a static warning dot when setup is required', () => {
store.$patch({
settings: {
...store.settings!,
modelCredentialId: 'openai-id',
modelName: null,
sandboxEnvConfigured: true,
},
});
const { getByTestId } = renderComponent();
const dot = getByTestId('n8n-agent-status-dot');
expect(dot.className).toContain('warning');
expect(dot.className).not.toContain('pulse');
it('keeps the switch on without opening setup when enabled but setup is incomplete', () => {
const { getByTestId, queryByTestId } = renderComponent();
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'true');
expect(getByTestId('n8n-agent-model-add')).toBeVisible();
expect(queryByTestId(modelSaveDialog)).toBeNull();
});
it('shows setup required for a credential-only legacy model assignment', () => {
store.$patch({
settings: {
...store.settings!,
modelCredentialId: 'openai-id',
modelName: null,
sandboxEnvConfigured: true,
},
});
it('shows the switch off with dimmed sections when disabled but configured', () => {
disable({ modelCredentialId: 'openai-id', modelName: 'gpt-4o' });
const { getByTestId, getByText } = renderComponent();
expect(getByTestId('n8n-agent-status-menu')).toBeVisible();
expect(getByText('settings.n8nAgent.status.setupRequired')).toBeVisible();
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'false');
expect(getByText('settings.n8nAgent.permissions.title')).toBeVisible();
});
it('shows an enable button with dimmed sections when disabled but configured', () => {
store.$patch({
settings: {
...store.settings!,
enabled: false,
modelCredentialId: 'openai-id',
modelName: 'gpt-4o',
},
it('does not show the switch to members', () => {
vi.mocked(hasPermission).mockReturnValue(false);
const { queryByTestId } = renderComponent();
expect(queryByTestId('n8n-agent-enable-toggle')).toBeNull();
});
it('saves enabled and opens nothing when setup is complete', async () => {
disable(fullyConfigured);
const persistEnabled = mockPersistEnabled();
const { getByTestId, queryByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await waitFor(() => expect(persistEnabled).toHaveBeenCalledExactlyOnceWith(true));
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'true');
expect(queryByTestId(modelSaveDialog)).toBeNull();
expect(queryByTestId('n8n-agent-sandbox-dialog-save')).toBeNull();
expect(queryByTestId('n8n-agent-search-dialog-save')).toBeNull();
});
it('opens the model dialog without saving enabled when the model is missing', async () => {
disable({ sandboxEnabled: true, sandboxEnvConfigured: true, searchDisabled: true });
const persistEnabled = mockPersistEnabled();
const { findByTestId, getByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
expect(await findByTestId(modelSaveDialog)).toBeVisible();
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'true');
expect(persistEnabled).not.toHaveBeenCalled();
});
it('turns the switch back off without saving enabled when a setup dialog is cancelled', async () => {
disable({ sandboxEnabled: true, sandboxEnvConfigured: true, searchDisabled: true });
const persistEnabled = mockPersistEnabled();
const { findByTestId, getByTestId, queryByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await fireEvent.click(await findByTestId('n8n-agent-model-dialog-cancel'));
await waitFor(() => expect(queryByTestId(modelSaveDialog)).toBeNull());
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'false');
expect(persistEnabled).not.toHaveBeenCalled();
expect(store.settings?.enabled).toBe(false);
});
it('continues to the next missing item after the model is saved', async () => {
disable({ searchDisabled: true });
const persistEnabled = mockPersistEnabled();
mockSave();
vi.mocked(store.verifyModel).mockResolvedValue({ ok: true });
const { findByTestId, getByTestId, queryByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
const modelApiKey = await findByTestId('n8n-agent-model-api-key-input');
await fireEvent.update(modelApiKey.querySelector('input') ?? modelApiKey, 'model-key');
await fireEvent.click(getByTestId(modelSaveDialog));
expect(await findByTestId('n8n-agent-sandbox-dialog-save')).toBeVisible();
await waitFor(() => expect(queryByTestId(modelSaveDialog)).toBeNull());
expect(persistEnabled).not.toHaveBeenCalled();
});
it('saves enabled once the last missing item is saved', async () => {
disable({ modelEnvConfigured: true, sandboxEnabled: true, sandboxEnvConfigured: true });
const persistEnabled = mockPersistEnabled();
mockSave();
const { findByTestId, getByTestId, queryByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await fireEvent.click(await findByTestId('assistant-search-disabled'));
await fireEvent.click(getByTestId('n8n-agent-search-dialog-save'));
await waitFor(() => expect(persistEnabled).toHaveBeenCalledExactlyOnceWith(true));
await waitFor(() => expect(queryByTestId('n8n-agent-search-dialog-save')).toBeNull());
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'true');
});
it('switches on an environment-configured sandbox before saving enabled', async () => {
disable({ modelEnvConfigured: true, sandboxEnvConfigured: true, searchDisabled: true });
const persistEnabled = mockPersistEnabled();
const save = mockSave();
const { getByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await waitFor(() => expect(persistEnabled).toHaveBeenCalledExactlyOnceWith(true));
expect(save).toHaveBeenCalledOnce();
expect(store.settings?.sandboxEnabled).toBe(true);
});
describe('with a saved model credential', () => {
const savedModel = {
modelCredentialId: 'openai-id',
modelName: 'gpt-4o',
sandboxEnabled: true,
sandboxEnvConfigured: true,
searchDisabled: true,
};
beforeEach(() => {
disable(savedModel);
store.$patch({
instanceModelCredentials: [{ id: 'openai-id', name: 'OpenAI', type: 'openAiApi' }],
});
});
it('opens the model dialog without saving enabled when the credential test fails', async () => {
testSavedCredentialMock.mockResolvedValue(false);
const persistEnabled = mockPersistEnabled();
const { findByTestId, getByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
expect(await findByTestId(modelSaveDialog)).toBeVisible();
expect(testSavedCredentialMock).toHaveBeenCalledExactlyOnceWith(
'openai-id',
'OpenAI',
'openAiApi',
);
expect(persistEnabled).not.toHaveBeenCalled();
});
it('saves enabled when the credential test passes', async () => {
const persistEnabled = mockPersistEnabled();
const { getByTestId, queryByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await waitFor(() => expect(persistEnabled).toHaveBeenCalledExactlyOnceWith(true));
expect(testSavedCredentialMock).toHaveBeenCalledOnce();
expect(queryByTestId(modelSaveDialog)).toBeNull();
});
it('does not test credentials when the admin cannot manage instance credentials', async () => {
vi.mocked(hasPermission).mockImplementation(
(_, options) => options?.rbac?.scope !== 'credential:manageInstance',
);
const persistEnabled = mockPersistEnabled();
const { getByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await waitFor(() => expect(persistEnabled).toHaveBeenCalledExactlyOnceWith(true));
expect(testSavedCredentialMock).not.toHaveBeenCalled();
});
});
it.each([
{ missing: 'model', patch: { searchDisabled: true }, dialog: modelSaveDialog },
{
missing: 'sandbox',
patch: { modelEnvConfigured: true, searchDisabled: true },
dialog: 'n8n-agent-sandbox-dialog-save',
},
{
missing: 'search',
patch: { modelEnvConfigured: true, sandboxEnabled: true, sandboxEnvConfigured: true },
dialog: 'n8n-agent-search-dialog-save',
},
])('resumes setup at the missing $missing', async ({ patch, dialog }) => {
disable(patch);
const persistEnabled = mockPersistEnabled();
const { findByTestId, getByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
expect(await findByTestId(dialog)).toBeVisible();
expect(persistEnabled).not.toHaveBeenCalled();
});
it('asks for confirmation and saves disabled when the admin confirms', async () => {
store.$patch({ settings: { ...store.settings!, ...fullyConfigured } });
const persistEnabled = mockPersistEnabled();
confirmMock.mockResolvedValue(MODAL_CONFIRM);
const { getByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await waitFor(() => expect(persistEnabled).toHaveBeenCalledExactlyOnceWith(false));
expect(confirmMock).toHaveBeenCalledOnce();
});
it('keeps the Assistant on when the admin cancels the confirmation', async () => {
store.$patch({ settings: { ...store.settings!, ...fullyConfigured } });
const persistEnabled = mockPersistEnabled();
confirmMock.mockResolvedValue('cancel');
const { getByTestId } = renderComponent();
await fireEvent.click(getByTestId('n8n-agent-enable-toggle'));
await waitFor(() => expect(confirmMock).toHaveBeenCalledOnce());
expect(persistEnabled).not.toHaveBeenCalled();
expect(getByTestId('n8n-agent-enable-toggle')).toHaveAttribute('aria-checked', 'true');
});
});
describe('off state', () => {
it('shows sub-feature switches as disabled and unchecked while off', () => {
store.$patch({ settings: { ...store.settings!, enabled: false, ...fullyConfigured } });
setModuleSettings(settingsStore, { ...defaultModuleSettings, enabled: false });
const { getByTestId, getByText, queryByTestId } = renderComponent();
expect(getByTestId('n8n-agent-enable-button')).toBeVisible();
expect(queryByTestId('n8n-agent-status-menu')).toBeNull();
expect(getByText('settings.n8nAgent.permissions.title')).toBeVisible();
settingsStore.settings.ai = { allowSendingParameterValues: true };
const { getByTestId } = renderComponent();
for (const testId of [
'n8n-agent-browser-use-toggle',
'n8n-agent-mcp-access-toggle',
'n8n-agent-data-sharing-schema-toggle',
'n8n-agent-data-sharing-values-toggle',
]) {
expect(getByTestId(testId)).toBeDisabled();
expect(getByTestId(testId)).toHaveAttribute('aria-checked', 'false');
}
expect(store.settings?.mcpAccessEnabled).toBe(true);
});
it('hides the missing model warning while off', () => {
store.$patch({ settings: { ...store.settings!, enabled: false, searchDisabled: true } });
setModuleSettings(settingsStore, { ...defaultModuleSettings, enabled: false });
const { getByTestId, queryByText } = renderComponent();
expect(getByTestId('n8n-agent-model-row')).toBeVisible();
expect(queryByText('settings.n8nAgent.modelCredential.missing.description')).toBeNull();
});
it('shows the missing model warning while on', () => {
const { getByText } = renderComponent();
expect(getByText('settings.n8nAgent.modelCredential.missing.description')).toBeVisible();
});
});
@@ -392,7 +630,37 @@ describe('SettingsInstanceAiView', () => {
expect(queryByText('settings.n8nAgent.permissions.title')).toBeNull();
});
it('shows the limited enterprise support badge in the empty state', () => {
it('opens the first missing setup item from the empty state without saving enabled', async () => {
store.$patch({ settings: { ...store.settings!, enabled: false } });
setModuleSettings(settingsStore, { ...defaultModuleSettings, enabled: false });
vi.mocked(store.fetch).mockResolvedValue(true);
const persistEnabled = vi.mocked(store.persistEnabled);
const { findByTestId, getByText } = renderComponent();
await fireEvent.click(getByText('settings.n8nAgent.empty.enable'));
expect(await findByTestId('n8n-agent-model-dialog-save')).toBeVisible();
expect(persistEnabled).not.toHaveBeenCalled();
});
it('saves enabled directly from the empty state when the assistant proxy is enabled', async () => {
store.$patch({ settings: { ...store.settings!, enabled: false } });
setModuleSettings(settingsStore, {
...defaultModuleSettings,
enabled: false,
proxyEnabled: true,
});
vi.mocked(store.fetch).mockResolvedValue(true);
const persistEnabled = vi.mocked(store.persistEnabled).mockResolvedValue(true);
const { getByText, queryByTestId } = renderComponent();
await fireEvent.click(getByText('settings.n8nAgent.empty.enable'));
await waitFor(() => expect(persistEnabled).toHaveBeenCalledExactlyOnceWith(true));
expect(queryByTestId('n8n-agent-sandbox-dialog-save')).toBeNull();
});
it('shows the limited enterprise readiness badge in the empty state', () => {
setPlanName(settingsStore, 'Enterprise');
store.$patch({ settings: { ...store.settings!, enabled: false } });
setModuleSettings(settingsStore, { ...defaultModuleSettings, enabled: false });
@@ -1,14 +1,12 @@
<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { computed, onMounted, reactive, ref } from 'vue';
import {
N8nBadge,
N8nButton,
N8nCallout,
N8nDropdownMenu,
N8nEmptyState,
N8nEnterpriseReadinessBadge,
N8nExternalLink,
N8nIcon,
N8nLoading,
N8nOption,
N8nSelect,
@@ -18,10 +16,8 @@ import {
N8nSettingsRowConfigure,
N8nSettingsRowGroup,
N8nSettingsSection,
N8nStatusDot,
N8nSwitch,
N8nText,
type DropdownMenuItemProps,
type EmptyStateIconCards,
} from '@n8n/design-system';
import {
@@ -43,8 +39,8 @@ import {
isContextPreferencesEnabled,
isContextSkillsEnabled,
} from '@/features/settings/context/context.utils';
import { useInstanceCredentialTest } from '../composables/useInstanceCredentialTest';
import { useInstanceAiConfiguration } from '../composables/useInstanceAiConfiguration';
import { useInstanceCredentialTest } from '../composables/useInstanceCredentialTest';
import { useInstanceAiSettingsStore } from '../instanceAiSettings.store';
import { useSetupPageViewTelemetry } from '../instanceAiSetup.telemetry';
import type { InstanceAiConnectionKind } from '../constants';
@@ -113,8 +109,8 @@ const modelValue = computed(() => {
const modelDescription = computed<{ key: BaseTextKey; warning: boolean } | null>(() => {
if (isModelConnectionEnvManaged.value)
return { key: 'settings.n8nAgent.modelCredential.env.description', warning: false };
if (store.settings?.modelCredentialId && store.settings.modelName) return null;
return { key: 'settings.n8nAgent.modelCredential.missing.description', warning: !isOff.value };
if ((store.settings?.modelCredentialId && store.settings.modelName) || isOff.value) return null;
return { key: 'settings.n8nAgent.modelCredential.missing.description', warning: true };
});
const searchValue = computed(() => {
@@ -123,12 +119,11 @@ const searchValue = computed(() => {
return searchCredential.value ? credentialTypeLabel(searchCredential.value.type) : '';
});
const isSetupRequired = computed(
/** Mirrors the backend `setupCompleted`: only a direct self-managed instance needs setup. */
const isSetupComplete = computed(
() =>
isEnabled.value &&
((showCredentialsRows.value && !isModelConfigured.value) ||
(showSandboxRow.value && !isSandboxConfigured.value) ||
(showCredentialsRows.value && searchState.value === 'notset')),
!showCredentialsRows.value ||
(isModelConfigured.value && isSandboxConfigured.value && searchState.value !== 'notset'),
);
const neverConfigured = computed(() => {
if (isEnabled.value) return false;
@@ -142,14 +137,6 @@ const emptyStateIcon: EmptyStateIconCards = {
sides: ['workflow', 'message-square', 'search', 'bot'],
};
const disableMenuItems: Array<DropdownMenuItemProps<string>> = [
{
id: 'disable',
label: i18n.baseText('settings.n8nAgent.status.disable'),
icon: { type: 'icon', value: 'power' },
},
];
const PERMISSION_OPTIONS: InstanceAiPermissionMode[] = [
'require_approval',
'always_allow',
@@ -271,18 +258,23 @@ function permissionOptionsFor(key: keyof InstanceAiPermissions) {
/** Exactly one dialog can be active; transitions between steps never observe an all-closed state. */
const activeDialog = ref<InstanceAiConnectionKind | null>(null);
/** True while walking through the missing setup items, so saving one dialog opens the next. */
const setupChain = ref(false);
const enableAfterSetup = ref(false);
watch(activeDialog, (dialog) => {
if (dialog !== null) return;
setupChain.value = false;
enableAfterSetup.value = false;
});
/** The switch shows on while the walkthrough runs; `enabled` is saved only once setup is complete. */
const isEnabling = ref(false);
const isSwitchOn = computed(() => isEnabled.value || isEnabling.value);
/** Saved credentials that turning on still has to test. Each one is tested at most once. */
let credentialsToTest = new Set<'model' | 'sandbox'>();
function setDialogOpen(kind: InstanceAiConnectionKind, isOpen: boolean) {
if (isOpen) activeDialog.value = kind;
else if (activeDialog.value === kind) activeDialog.value = null;
if (isOpen) {
activeDialog.value = kind;
} else if (activeDialog.value === kind) {
// Dialogs in the walkthrough don't close themselves, so this is a cancel.
activeDialog.value = null;
setupChain.value = false;
isEnabling.value = false;
}
}
function openModelDialog() {
@@ -291,12 +283,6 @@ function openModelDialog() {
activeDialog.value = 'model';
}
function openModelSetup() {
setupChain.value =
(!isSandboxConfigured.value && !isSandboxEnvManaged.value) || searchState.value === 'notset';
activeDialog.value = 'model';
}
function openSandboxDialog() {
if (isSandboxEnvManaged.value) return;
setupChain.value = false;
@@ -309,49 +295,59 @@ function openSearchDialog() {
activeDialog.value = 'search';
}
function openSearchSetup(): void {
activeDialog.value = 'search';
}
/** Returns whether the chain may continue (false only when enabling failed). */
async function finishSetup(): Promise<boolean> {
setupChain.value = false;
if (!enableAfterSetup.value) {
activeDialog.value = null;
return true;
/** A saved credential can stop working, so turning on tests it once. Other paths skip the test. */
async function savedCredentialWorks(kind: 'model' | 'sandbox'): Promise<boolean> {
if (!isEnabling.value || !credentialsToTest.delete(kind)) return true;
if (kind === 'model') {
const id = store.settings?.modelCredentialId;
const credential = modelCredential.value;
if (!id) return true;
return !!credential && (await testSavedCredential(id, credential.name, credential.type));
}
enableAfterSetup.value = false;
const enabled = await store.persistEnabled(true);
if (enabled) activeDialog.value = null;
return enabled;
if (!sandboxCredentialId.value) return true;
const type = store.settings?.sandboxProvider === 'daytona' ? 'daytonaApi' : 'httpHeaderAuth';
return await testSavedCredential(sandboxCredentialId.value, 'n8n Assistant sandbox', type);
}
async function handleModelSaved() {
if ((setupChain.value || enableAfterSetup.value) && !(await enableEnvironmentSandboxIfNeeded()))
return;
if (setupChain.value) {
if (isSandboxConfigured.value || isSandboxEnvManaged.value) {
openSearchSetup();
} else {
activeDialog.value = 'sandbox';
}
return;
async function nextSetupDialog(): Promise<InstanceAiConnectionKind | null> {
if (
showCredentialsRows.value &&
(!isModelConfigured.value || !(await savedCredentialWorks('model')))
) {
return 'model';
}
await finishSetup();
}
async function handleSandboxSaved() {
const chainSearch = setupChain.value && searchState.value === 'notset';
if (chainSearch) {
openSearchSetup();
return;
// An environment-configured sandbox has no dialog. It only needs to be switched on.
if (!(await enableEnvironmentSandboxIfNeeded())) return null;
if (
showSandboxRow.value &&
!isSandboxEnvManaged.value &&
(!isSandboxConfigured.value || !(await savedCredentialWorks('sandbox')))
) {
return 'sandbox';
}
await finishSetup();
if (showCredentialsRows.value && searchState.value === 'notset') return 'search';
return null;
}
async function handleSearchSaved() {
await finishSetup();
/**
* Opens the dialog for the first missing setup item. When none is left, it closes the
* walkthrough and saves a pending switch-on.
*/
async function continueSetup() {
setupChain.value = true;
const next = await nextSetupDialog();
if (!setupChain.value) return;
setupChain.value = next !== null;
activeDialog.value = next;
// The admin saves this credential in its dialog, so the walkthrough does not test it again.
if (next === 'model' || next === 'sandbox') credentialsToTest.delete(next);
if (next !== null || !isEnabling.value) return;
if (isSetupComplete.value) await store.persistEnabled(true);
isEnabling.value = false;
}
async function handleDialogSaved() {
if (setupChain.value) await continueSetup();
}
function credentialTypeLabel(type: string) {
@@ -372,66 +368,23 @@ onMounted(() => {
void credentialsStore.fetchCredentialTypes(false);
});
async function handleEnable() {
if (!showCredentialsRows.value && (!showSandboxRow.value || isSandboxConfigured.value)) {
async function enable() {
credentialsToTest = new Set(
showCredentialsRows.value && store.canManageInstanceCredentials ? ['model', 'sandbox'] : [],
);
if (isSetupComplete.value && credentialsToTest.size === 0) {
await store.persistEnabled(true);
return;
}
enableAfterSetup.value = true;
if (showCredentialsRows.value && !isModelConfigured.value) {
openModelSetup();
return;
}
const modelCredentialId = store.settings?.modelCredentialId;
if (
showCredentialsRows.value &&
modelCredentialId &&
store.canManageInstanceCredentials &&
(!modelCredential.value ||
!(await testSavedCredential(
modelCredentialId,
modelCredential.value.name,
modelCredential.value.type,
)))
) {
openModelSetup();
return;
}
if (!(await enableEnvironmentSandboxIfNeeded())) return;
if (showSandboxRow.value && !isSandboxConfigured.value && !isSandboxEnvManaged.value) {
openSandboxDialog();
return;
}
if (showSandboxRow.value && sandboxCredentialId.value && store.canManageInstanceCredentials) {
const isDaytona = store.settings?.sandboxProvider === 'daytona';
if (
!(await testSavedCredential(
sandboxCredentialId.value,
'n8n Assistant sandbox',
isDaytona ? 'daytonaApi' : 'httpHeaderAuth',
))
) {
openSandboxDialog();
return;
}
}
if (showCredentialsRows.value && searchState.value === 'notset') {
setupChain.value = true;
openSearchSetup();
return;
}
await finishSetup();
isEnabling.value = true;
await continueSetup();
}
async function handleStatusAction(action: string) {
if (action !== 'disable') return;
async function handleEnabledToggle(value: boolean) {
if (value) {
await enable();
return;
}
const confirmed = await message.confirm(
i18n.baseText('settings.n8nAgent.status.disable.description'),
@@ -512,9 +465,9 @@ async function handleDataSharingToggle(value: boolean) {
:heading="i18n.baseText('settings.n8nAgent.empty.title')"
:description="i18n.baseText('settings.n8nAgent.empty.description')"
:button-text="isAdmin ? i18n.baseText('settings.n8nAgent.empty.enable') : undefined"
:button-disabled="store.isSaving || isTestingCredential"
:button-disabled="store.isSaving || isEnabling || isTestingCredential"
button-variant="solid"
@click:button="handleEnable"
@click:button="enable"
>
<template v-if="isAdmin" #additionalContent>
<N8nText size="small" color="text-light">
@@ -531,56 +484,13 @@ async function handleDataSharingToggle(value: boolean) {
:description="i18n.baseText('settings.n8nAgent.enable.description')"
>
<template #action>
<N8nButton
v-if="isOff"
variant="solid"
size="medium"
:label="i18n.baseText('settings.n8nAgent.status.enable')"
:disabled="store.isSaving || isTestingCredential"
data-test-id="n8n-agent-enable-button"
@click="handleEnable"
<N8nSwitch
:model-value="isSwitchOn"
:disabled="store.isSaving || isEnabling || isTestingCredential"
:aria-label="i18n.baseText('settings.n8nAgent.enable.label')"
data-test-id="n8n-agent-enable-toggle"
@update:model-value="handleEnabledToggle"
/>
<N8nDropdownMenu
v-else
:items="disableMenuItems"
placement="bottom-end"
data-test-id="n8n-agent-status-menu"
@select="handleStatusAction"
>
<template #trigger>
<N8nButton
variant="outline"
size="medium"
:disabled="store.isSaving"
:aria-label="i18n.baseText('settings.n8nAgent.status.manage')"
>
<span :class="$style.statusLabel">
<N8nStatusDot
:variant="isSetupRequired ? 'warning' : 'success'"
:pulse="!isSetupRequired"
data-test-id="n8n-agent-status-dot"
/>
{{
isSetupRequired
? i18n.baseText('settings.n8nAgent.status.setupRequired')
: i18n.baseText('settings.n8nAgent.status.enabled')
}}
<N8nIcon icon="chevron-down" size="small" />
</span>
</N8nButton>
</template>
<template #item-leading="{ item }">
<N8nIcon
v-if="item.icon?.type === 'icon'"
:class="$style.danger"
:icon="item.icon.value"
size="small"
/>
</template>
<template #item-label="{ item }">
<span :class="$style.danger">{{ item.label }}</span>
</template>
</N8nDropdownMenu>
</template>
</N8nSettingsRow>
@@ -611,7 +521,7 @@ async function handleDataSharingToggle(value: boolean) {
:label="i18n.baseText('settings.n8nAgent.modelCredential.add')"
:disabled="store.isSaving"
data-test-id="n8n-agent-model-add"
@click="openModelSetup"
@click="continueSetup"
/>
<N8nText
v-else-if="isModelReadOnly"
@@ -639,13 +549,13 @@ async function handleDataSharingToggle(value: boolean) {
<DefaultEditorSetting />
<N8nSettingsSection
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.n8nAgent.capabilities.title')"
:description="i18n.baseText('settings.n8nAgent.capabilities.description')"
>
<N8nSettingsRowGroup>
<N8nSettingsRow
v-if="showCredentialsRows"
:class="{ [$style.dim]: isOff }"
:clickable="!isOff && searchState !== 'notset' && !isSearchEnvManaged"
data-test-id="n8n-agent-search-row"
@click="openSearchDialog"
@@ -690,13 +600,12 @@ async function handleDataSharingToggle(value: boolean) {
</N8nSettingsRow>
<N8nSettingsRow
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.n8nAgent.browserUse.label')"
:description="i18n.baseText('settings.n8nAgent.browserUse.description')"
>
<template #action>
<N8nSwitch
:model-value="store.settings?.browserUseEnabled ?? true"
:model-value="!isOff && (store.settings?.browserUseEnabled ?? true)"
:disabled="store.isSaving || isOff"
:aria-label="i18n.baseText('settings.n8nAgent.browserUse.label')"
data-test-id="n8n-agent-browser-use-toggle"
@@ -708,18 +617,18 @@ async function handleDataSharingToggle(value: boolean) {
</N8nSettingsSection>
<N8nSettingsSection
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.n8nAgent.mcp.title')"
:description="i18n.baseText('settings.n8nAgent.mcp.description')"
>
<N8nSettingsRowGroup>
<N8nSettingsRow
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.n8nAgent.mcpAccess.label')"
:description="i18n.baseText('settings.n8nAgent.mcpAccess.description')"
>
<template #action>
<N8nSwitch
:model-value="isMcpAccessEnabled"
:model-value="!isOff && isMcpAccessEnabled"
:disabled="store.isSaving || isOff"
:aria-label="i18n.baseText('settings.n8nAgent.mcpAccess.label')"
data-test-id="n8n-agent-mcp-access-toggle"
@@ -731,6 +640,7 @@ async function handleDataSharingToggle(value: boolean) {
</N8nSettingsSection>
<N8nSettingsSection
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.n8nAgent.permissions.title')"
:description="i18n.baseText('settings.n8nAgent.permissions.description')"
>
@@ -739,7 +649,7 @@ async function handleDataSharingToggle(value: boolean) {
v-for="group in permissionGroups"
:key="group.id"
v-model="expandedGroups[group.id]"
:class="{ [$style.dim]: isGroupLocked(group) }"
:class="{ [$style.dim]: !isOff && isGroupLocked(group) }"
:title="i18n.baseText(group.labelKey)"
:expandable="!isGroupLocked(group)"
:expand-label="groupSummary(group)"
@@ -787,7 +697,10 @@ async function handleDataSharingToggle(value: boolean) {
</N8nSettingsRowGroup>
</N8nSettingsSection>
<N8nSettingsSection :title="i18n.baseText('settings.n8nAgent.dataSharing.title')">
<N8nSettingsSection
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.n8nAgent.dataSharing.title')"
>
<template #description>
<N8nText size="small" color="text-base">
{{ i18n.baseText('settings.n8nAgent.dataSharing.description') }}
@@ -807,14 +720,13 @@ async function handleDataSharingToggle(value: boolean) {
</template>
<N8nSettingsRowGroup>
<N8nSettingsRow
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.ai.allowSendingSchema.label')"
:description="i18n.baseText('settings.ai.allowSendingSchema.description')"
data-test-id="n8n-agent-data-sharing-schema-row"
>
<template #action>
<N8nSwitch
:model-value="true"
:model-value="!isOff"
disabled
:aria-label="i18n.baseText('settings.ai.allowSendingSchema.label')"
data-test-id="n8n-agent-data-sharing-schema-toggle"
@@ -822,14 +734,13 @@ async function handleDataSharingToggle(value: boolean) {
</template>
</N8nSettingsRow>
<N8nSettingsRow
:class="{ [$style.dim]: isOff }"
:title="i18n.baseText('settings.ai.allowSendingParameterValues.label')"
:description="i18n.baseText('settings.n8nAgent.dataSharing.values.description')"
data-test-id="n8n-agent-data-sharing-values-row"
>
<template #action>
<N8nSwitch
:model-value="isDataSharingEnabled"
:model-value="!isOff && isDataSharingEnabled"
:disabled="!canToggleDataSharing"
:aria-label="i18n.baseText('settings.ai.allowSendingParameterValues.label')"
data-test-id="n8n-agent-data-sharing-values-toggle"
@@ -861,7 +772,7 @@ async function handleDataSharingToggle(value: boolean) {
:open="activeDialog === 'model'"
:setup="setupChain"
@update:open="setDialogOpen('model', $event)"
@saved="handleModelSaved"
@saved="handleDialogSaved"
/>
<ConnectionDialog
v-if="showSandboxRow && !isSandboxEnvManaged"
@@ -869,7 +780,7 @@ async function handleDataSharingToggle(value: boolean) {
:open="activeDialog === 'sandbox'"
:setup="showCredentialsRows && setupChain"
@update:open="setDialogOpen('sandbox', $event)"
@saved="handleSandboxSaved"
@saved="handleDialogSaved"
/>
<ConnectionDialog
v-if="showCredentialsRows && !isSearchEnvManaged"
@@ -877,22 +788,12 @@ async function handleDataSharingToggle(value: boolean) {
:open="activeDialog === 'search'"
:setup="setupChain"
@update:open="setDialogOpen('search', $event)"
@saved="handleSearchSaved"
@saved="handleDialogSaved"
/>
</N8nSettingsLayout>
</template>
<style lang="scss" module>
.statusLabel {
display: inline-flex;
align-items: center;
gap: var(--spacing--3xs);
}
.danger {
color: var(--text-color--danger);
}
.titleWithTag {
display: inline-flex;
align-items: center;
@@ -45,6 +45,8 @@ export const containerFixtures: Fixtures<object, ContainerWorkerFixtures> = {
...override,
services: [...new Set([...(base.services ?? []), ...(override.services ?? [])])],
env: {
// E2E mode reports the Enterprise plan, where the n8n Assistant is off by default.
N8N_INSTANCE_AI_ENABLED: 'true',
...globalEnv,
...base.env,
...override.env,
@@ -82,6 +82,8 @@ if (BACKEND_URL && !SKIP_WEB_SERVER) {
env: {
DB_SQLITE_POOL_SIZE: '40',
E2E_TESTS: 'true',
// E2E mode reports the Enterprise plan, where the n8n Assistant is off by default.
N8N_INSTANCE_AI_ENABLED: 'true',
N8N_PORT: getPortFromUrl(BACKEND_URL),
N8N_USER_FOLDER: USER_FOLDER,
N8N_LOG_LEVEL: 'debug',
@@ -93,6 +93,8 @@ const callerTestEnv = (() => {
const n8nEnv = {
...process.env,
E2E_TESTS: 'true',
// E2E mode reports the Enterprise plan, where the n8n Assistant is off by default.
N8N_INSTANCE_AI_ENABLED: 'true',
N8N_PORT: port,
N8N_RUNNERS_BROKER_PORT: brokerPort,
N8N_USER_FOLDER: userFolder,