TagSpaces is an offline, open source, document manager with tagging support
chore: added ai gen related e2e tests
Ilian Sapundshievb9797c5000af
diff --git a/scripts/extconfig-ai-mock.js b/scripts/extconfig-ai-mock.jsnew file mode 100644index 000000000..9bfea191f--- /dev/null+++ b/scripts/extconfig-ai-mock.js@@ -0,0 +1,21 @@+window.ExtIsFirstRun = false;+window.ExtCheckForUpdatesOnStartup = false;+window.ExtUseGenerateThumbnails = true;+// A single enabled Ollama provider pointing at a host the e2e suite+// intercepts via Playwright route() (see tests/e2e/ai.helpers.js). No real+// Ollama service is contacted. The location is created by the spec via+// createPwLocation(), so no ExtLocations here.+window.ExtAI = {+ defaultEngine: 'e2eMockEngine',+ engines: [+ {+ id: 'e2eMockEngine',+ engine: 'ollama',+ name: 'E2E Mock Ollama',+ url: 'http://127.0.0.1:11434',+ defaultTextModel: 'llama3.2',+ defaultImageModel: 'llava',+ enable: true,+ },+ ],+};diff --git a/scripts/extconfig-ai-no-provider.js b/scripts/extconfig-ai-no-provider.jsnew file mode 100644index 000000000..bd3f3aab8--- /dev/null+++ b/scripts/extconfig-ai-no-provider.js@@ -0,0 +1,12 @@+window.ExtIsFirstRun = false;+window.ExtCheckForUpdatesOnStartup = false;+window.ExtUseGenerateThumbnails = true;+// ExtAI is defined but has no enabled engine, so getDefaultAIProvider()+// resolves to undefined and the selector path is fully deterministic+// (it ignores any redux-persisted provider). This drives the+// "no AI provider configured" guard in the AI generation dialog.+// The location is created by the spec via createPwLocation().+window.ExtAI = {+ defaultEngine: '',+ engines: [],+};diff --git a/tests/e2e/ai-generation.pw.e2e.js b/tests/e2e/ai-generation.pw.e2e.jsnew file mode 100644index 000000000..60e79b6dd--- /dev/null+++ b/tests/e2e/ai-generation.pw.e2e.js@@ -0,0 +1,216 @@+/* Copyright (c) 2016-present - TagSpaces GmbH. All rights reserved. */++// AI generation dialog coverage. Two tiers:+//+// Tier 1 — guard / UI-state, no AI service needed (deterministic):+// TST7001 no AI provider configured -> Start disabled + warning + CTA+// TST7002 only unsupported files selected -> Start disabled; selecting a+// supported file re-enables it+// TST7003 "Max tags" cannot be set to 0 (clamps to >=1)+//+// Tier 2 — generation flow against a mocked Ollama (Playwright route):+// TST7004 tags generated -> file renamed by tag embedding -> the per-file+// "processed" check stays visible (regression: entry uuid churns+// on the tag-rename, the dialog must not lose the check)+//+// All AI features are Pro and don't apply to S3 — tagged [electron,_pro].++import { expect, test } from './fixtures';+import {+ clickOn,+ createLocation,+ expectElementExist,+ expectElementSelected,+ getGridFileSelector,+ isDisabled,+ reloadDirectory,+} from './general.helpers';+import { startTestingApp, stopApp, testDataRefresh } from './hook';+import { clearDataStorage, closeWelcomePlaywright } from './welcome.helpers';+import {+ armOllamaMock,+ disarmOllamaMock,+ openAiGenerationDialog,+} from './ai.helpers';++async function bootWithLocation(+ { isWeb, isS3, webServerPort, testInfo },+ testDataDir,+ extconfig,+) {+ await startTestingApp({ isWeb, isS3, webServerPort, testInfo }, extconfig);+ await closeWelcomePlaywright();+ // Use the suite's blessed helper — it opens the location and waits for the+ // directory grid (not the location-tree) to be populated.+ await createLocation({ isS3, testDataDir }, '', undefined, true);+ // Make sure the files we interact with are actually listed before clicking,+ // so selection isn't racing the directory render.+ await expectElementExist(getGridFileSelector('sample.txt'), true, 30000);+}++async function selectFile(name) {+ await expectElementExist(getGridFileSelector(name), true, 15000);+ await clickOn(getGridFileSelector(name));+ // Selection can lag a beat behind the click under full-suite load.+ await expectElementSelected(name, true, 10000);+}++test.describe('TST70 - AI generation dialog guards [electron,_pro]', () => {+ test.afterEach(async ({ isS3, testDataDir }) => {+ await testDataRefresh(isS3, testDataDir);+ await clearDataStorage();+ await stopApp();+ });++ test('TST7001 - No AI provider: Start disabled, warning + settings CTA [electron,_pro]', async ({+ isWeb,+ isS3,+ webServerPort,+ testDataDir,+ }, testInfo) => {+ await bootWithLocation(+ { isWeb, isS3, webServerPort, testInfo },+ testDataDir,+ 'extconfig-ai-no-provider.js',+ );+ // A supported file is selected so the only reason generation can't+ // start is the missing provider.+ await selectFile('sample.txt');+ await openAiGenerationDialog();++ await expectElementExist('[data-tid=aiCannotGenerateAlertTID]', true, 4000);+ // The "open AI settings" action only renders when there is no provider —+ // this distinguishes the no-provider case from no-supported-files.+ await expectElementExist(+ '[data-tid=openAiSettingsFromAlertTID]',+ true,+ 4000,+ );+ expect(await isDisabled('[data-tid=startTagsGenTID]')).toBe(true);+ });++ test('TST7003 - Max tags cannot be 0 (clamps to >=1) [electron,_pro]', async ({+ isWeb,+ isS3,+ webServerPort,+ testDataDir,+ }, testInfo) => {+ await bootWithLocation(+ { isWeb, isS3, webServerPort, testInfo },+ testDataDir,+ 'extconfig-ai-mock.js',+ );+ await selectFile('sample.txt');+ await openAiGenerationDialog();++ const maxTags = '[data-tid=maxTagsTID] input';+ await global.client.fill(maxTags, '0');+ // onChange clamps non-positive/NaN to 1; the controlled input reflects it.+ await expect+ .poll(() => global.client.inputValue(maxTags), {+ timeout: 4000,+ intervals: [150],+ })+ .toBe('1');+ });+});++test.describe('TST70 - AI generation: supported-files guard [electron,_pro]', () => {+ test.afterEach(async ({ isS3, testDataDir }) => {+ await testDataRefresh(isS3, testDataDir);+ await clearDataStorage();+ await stopApp();+ });++ test('TST7002 - Only unsupported selected disables Start; supported re-enables [electron,_pro]', async ({+ isWeb,+ isS3,+ webServerPort,+ testDataDir,+ }, testInfo) => {+ await bootWithLocation(+ { isWeb, isS3, webServerPort, testInfo },+ testDataDir,+ 'extconfig-ai-mock.js',+ );++ // sample.bmp is neither an AI-supported text nor image type.+ await selectFile('sample.bmp');+ await openAiGenerationDialog();+ await expectElementExist('[data-tid=aiCannotGenerateAlertTID]', true, 4000);+ // Provider IS configured here, so the no-provider CTA must NOT show —+ // the block is purely the unsupported-selection guard.+ await expectElementExist(+ '[data-tid=openAiSettingsFromAlertTID]',+ false,+ 2000,+ );+ expect(await isDisabled('[data-tid=startTagsGenTID]')).toBe(true);++ // Close, select a supported file, reopen -> Start enabled, no warning.+ await clickOn('[data-tid=cancelTagsGenTID]');+ await selectFile('sample.txt');+ await openAiGenerationDialog();+ await expectElementExist('[data-tid=aiCannotGenerateAlertTID]', false, 2000);+ expect(await isDisabled('[data-tid=startTagsGenTID]')).toBe(false);+ });+});++test.describe('TST70 - AI generation: mocked Ollama [electron,_pro]', () => {+ test.afterEach(async ({ isS3, testDataDir }) => {+ await testDataRefresh(isS3, testDataDir);+ await clearDataStorage();+ await stopApp();+ });++ test('TST7004 - Tags generated, file renamed, processed check persists [electron,_pro]', async ({+ isWeb,+ isS3,+ webServerPort,+ testDataDir,+ }, testInfo) => {+ await bootWithLocation(+ { isWeb, isS3, webServerPort, testInfo },+ testDataDir,+ 'extconfig-ai-mock.js',+ );++ const capture = { tags: 0, chat: 0, requests: [] };+ await armOllamaMock(capture, ['e2ealpha', 'e2ebeta', 'e2egamma']);+ try {+ await selectFile('sample.txt');+ await openAiGenerationDialog();+ await clickOn('[data-tid=startTagsGenTID]');++ // Mock was actually exercised (model list + at least one chat call).+ await expect+ .poll(() => capture.chat, { timeout: 30000, intervals: [300] })+ .toBeGreaterThan(0);++ // The per-file processed check appears…+ await expectElementExist('[data-tid=aiEntryProcessedTID]', true, 40000);+ // …and it must STILL be there after the tag-rename has reflected.+ // This is the regression: pre-fix the renamed entry got a fresh uuid+ // (files without a sidecar are re-enhanced with getUuid() on every+ // listing) and the frozen-snapshot was swapped out, losing the check.+ await global.client.waitForTimeout(4000);+ await expectElementExist('[data-tid=aiEntryProcessedTID]', true, 3000);++ // Close the dialog before checking the grid: with the modal open the+ // grid sits behind the backdrop (reflect timing + visibility are+ // racy). Closing + an explicit reload reads the on-disk state, which+ // is the source of truth — the rename already completed on disk by+ // the time the processed check appeared.+ await clickOn('[data-tid=cancelTagsGenTID]');+ await reloadDirectory();+ await expectElementExist(+ getGridFileSelector('sample[e2ealpha e2ebeta e2egamma].txt'),+ true,+ 15000,+ );+ await expectElementExist(getGridFileSelector('sample.txt'), false, 3000);+ } finally {+ await disarmOllamaMock();+ }+ });+});diff --git a/tests/e2e/ai.helpers.js b/tests/e2e/ai.helpers.jsnew file mode 100644index 000000000..4cbb57c11--- /dev/null+++ b/tests/e2e/ai.helpers.js@@ -0,0 +1,134 @@+/* Copyright (c) 2016-present - TagSpaces GmbH. All rights reserved. */++/**+ * Reusable Ollama HTTP mock for the AI generation e2e tests.+ *+ * The renderer talks to Ollama from the browser context via `ollama/browser`+ * (plain `fetch`): model listing hits `GET {host}/api/tags`, generation hits+ * `POST {host}/api/chat`. We intercept the configured mock host with Playwright+ * route() — same approach as update-check.pw.e2e.js — so the suite never needs+ * a real Ollama service and stays deterministic in CI.+ *+ * The mock host MUST match `url` in scripts/extconfig-ai-mock.js.+ */++const OLLAMA_HOST_PATTERN = '**/127.0.0.1:11434/**';++// The ollama lib sends `Content-Type: application/json`, which makes the+// cross-origin fetch non-simple → the browser fires a CORS preflight. Fulfil+// it (and tag every response with permissive CORS headers) or the real+// request never goes out and the route handler is never reached.+const CORS_HEADERS = {+ 'access-control-allow-origin': '*',+ 'access-control-allow-methods': 'GET,POST,OPTIONS',+ 'access-control-allow-headers': '*',+};++function mockModel(name) {+ return {+ name,+ model: name,+ modified_at: new Date().toISOString(),+ size: 1,+ digest: 'e2e-mock-digest',+ details: {+ parent_model: '',+ format: 'gguf',+ family: 'llama',+ families: ['llama'],+ parameter_size: '1B',+ quantization_level: 'Q4_0',+ },+ };+}++function chatResponse(content) {+ return {+ model: 'llama3.2:latest',+ created_at: new Date().toISOString(),+ message: { role: 'assistant', content },+ done: true,+ done_reason: 'stop',+ total_duration: 1,+ load_duration: 1,+ prompt_eval_count: 1,+ prompt_eval_duration: 1,+ eval_count: 1,+ eval_duration: 1,+ };+}++/**+ * Arm the Ollama interceptor.+ *+ * @param capture mutable bucket — { tags, chat, requests } — updated in place+ * so a test can assert how many calls the app actually made.+ * @param tags the tag titles the mocked `/api/chat` returns (the renderer+ * parses the assistant content as JSON and reads `.topics`).+ */+export async function armOllamaMock(+ capture = { tags: 0, chat: 0, requests: [] },+ tags = ['e2ealpha', 'e2ebeta', 'e2egamma'],+) {+ await global.client.route(OLLAMA_HOST_PATTERN, async (route) => {+ const request = route.request();+ const url = request.url();+ const method = request.method();+ capture.requests.push(method + ' ' + url);++ if (method === 'OPTIONS') {+ await route.fulfill({ status: 204, headers: CORS_HEADERS, body: '' });+ return;+ }+ if (url.includes('/api/tags')) {+ capture.tags += 1;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ headers: CORS_HEADERS,+ body: JSON.stringify({+ models: [mockModel('llama3.2:latest'), mockModel('llava:latest')],+ }),+ });+ return;+ }+ if (url.includes('/api/chat')) {+ capture.chat += 1;+ // Tags mode parses the content as JSON and reads `.topics`. Returning+ // this for the model warm-up call too is harmless (that path ignores+ // the content).+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ headers: CORS_HEADERS,+ body: JSON.stringify(chatResponse(JSON.stringify({ topics: tags }))),+ });+ return;+ }+ // Anything else the lib might probe — keep it 200 so nothing throws.+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ headers: CORS_HEADERS,+ body: '{}',+ });+ });+ return capture;+}++export async function disarmOllamaMock() {+ await global.client.unroute(OLLAMA_HOST_PATTERN);+}++/**+ * Open the AI generation dialog from the grid perspective toolbar and wait+ * for it to render. Assumes a location is open and at least one entry is+ * selected (the toolbar AI button is hidden on read-only locations).+ */+export async function openAiGenerationDialog() {+ await global.client.click('[data-tid=gridPerspectiveAiGenTID]');+ await global.client.waitForSelector('[data-tid=startTagsGenTID]', {+ state: 'visible',+ timeout: 10000,+ });+}