π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β test(cli): isolate live E2E and repair stale contracts (#19842)
AmAzing-99fa39e7d2e4
diff --git a/apps/cli/README.md b/apps/cli/README.mdindex de63f3a0962..5b56e0b73a2 100644--- a/apps/cli/README.md+++ b/apps/cli/README.md@@ -85,3 +85,35 @@ which lhlh --helplh agent <TAB>```++## Tests++The default `test` and `test:coverage` scripts run offline unit tests only. Live+E2E uses a separate config and never replaces or removes your selected CLI home.+It always runs this checkout's `dist/index.js`, not a globally installed `lh` or+a caller-supplied `LH_CLI_PATH`.++From `apps/cli`, prepare a dedicated test account (never your everyday account):++```bash+bun run build+export LOBEHUB_CLI_HOME=.lobehub-e2e+export LOBEHUB_SERVER=https://your-test-server.example+node dist/index.js login --server "$LOBEHUB_SERVER"+node dist/index.js whoami++# Explicitly authorize real writes for this test account/server.+export LOBEHUB_E2E_ALLOW_WRITES=1+bun run test:e2e e2e/model.e2e.test.ts --testTimeout=60000 --hookTimeout=60000+```++Without a selected home, server, write opt-in, built CLI, or valid authentication,+the live setup fails before fixture creation. A directory name does not itself+isolate server data: sign in with a dedicated test identity. Model tests own a+temporary provider, including the remote-model clearing case. Other suites may+create data or consume model credits, so do not run them on a personal account.+Collection alone (`bunx vitest list --config vitest.e2e.config.mts`) needs no login.+Signal and VFS tests additionally require their documented Agent ID variables.+Search fixtures wait up to 60 seconds for asynchronous indexing; a timeout fails+the suite rather than accepting empty results. The command above supplies a live+network budget explicitly; this does not change unit-test timeouts or enable retries.diff --git a/apps/cli/e2e/agent-signal.e2e.test.ts b/apps/cli/e2e/agent-signal.e2e.test.tsindex e224758e2de..ce4f8ff856f 100644--- a/apps/cli/e2e/agent-signal.e2e.test.ts+++ b/apps/cli/e2e/agent-signal.e2e.test.ts@@ -1,21 +1,13 @@import { execSync } from 'node:child_process';-import { readFileSync } from 'node:fs';-import { fileURLToPath } from 'node:url';import { describe, expect, it } from 'vitest';-import {- assertGoldenFinalState,- extractGoldenOutcomes,-} from './fixtures/agent-signal/assertGoldenFinalState';-/*** E2E tests for `lh agent-signal trigger`.*- * The "golden fixture" block runs fully offline β it is the structural- * regression baseline that the execAgent migration asserts- * against. The "live trigger" block requires a running server + authenticated- * CLI and is gated behind AGENT_SIGNAL_AGENT_ID (or AGENT_ID).+ * Requires a running server + authenticated CLI and is gated behind+ * AGENT_SIGNAL_AGENT_ID (or AGENT_ID). Offline golden fixture coverage lives+ * in tests/agentSignalGolden.test.ts.** Prerequisites for the live block:* - `lh` (or LH_CLI_PATH) points at the built CLI@@ -27,11 +19,6 @@ const CLI = process.env.LH_CLI_PATH || 'lh';const AGENT_ID = process.env.AGENT_SIGNAL_AGENT_ID || process.env.AGENT_ID;const TIMEOUT = 60_000;-const goldenPath = fileURLToPath(- new URL('./fixtures/agent-signal/nightly-review.golden.json', import.meta.url),-);-const golden = JSON.parse(readFileSync(goldenPath, 'utf-8'));-function run(args: string): string {return execSync(`${CLI} ${args}`, {encoding: 'utf-8',@@ -40,31 +27,6 @@ function run(args: string): string {}).trim();}-describe('agent-signal golden fixture - structural regression', () => {- it('captures a recognizable nightly-review source payload', () => {- expect(golden.source.sourceType).toBe('agent.nightly_review.requested');- expect(golden.source.payload.agentId).toBeTruthy();- expect(golden.source.payload.userId).toBeTruthy();- expect(golden.source.scopeKey).toContain('agent:');- });-- it('extracts ideas / write outcomes / brief from finalState', () => {- const outcomes = extractGoldenOutcomes(golden.finalState);-- expect(outcomes.ideas.length).toBeGreaterThanOrEqual(1);- expect(outcomes.writeOutcomes.length).toBeGreaterThanOrEqual(1);- expect(outcomes.brief).toBeDefined();- });-- it('passes the shared structural assertion', () => {- expect(() => assertGoldenFinalState(golden.finalState)).not.toThrow();- });-- it('rejects an empty finalState', () => {- expect(() => assertGoldenFinalState({ messages: [] })).toThrow(/artifact/i);- });-});-describe.skipIf(!AGENT_ID)('lh agent-signal trigger - live', () => {it('triggers a nightly review and returns a workflow run id', () => {const output = run(diff --git a/apps/cli/e2e/doc.e2e.test.ts b/apps/cli/e2e/doc.e2e.test.tsindex 4f19005a0d0..a432c700e0a 100644--- a/apps/cli/e2e/doc.e2e.test.ts+++ b/apps/cli/e2e/doc.e2e.test.ts@@ -2,8 +2,9 @@ import { execSync } from 'node:child_process';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';+import { stripVTControlCharacters } from 'node:util';-import { describe, expect, it } from 'vitest';+import { afterAll, describe, expect, it } from 'vitest';/*** E2E tests for `lh doc` document management commands.@@ -21,7 +22,7 @@ const TIMEOUT = 30_000;function run(args: string): string {return execSync(`${CLI} ${args}`, {- encoding: 'utf-8',+ encoding: 'utf8',env: { ...process.env, PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}` },timeout: TIMEOUT,}).trim();@@ -220,6 +221,11 @@ describe('lh doc - E2E', () => {describe('batch-create', () => {let batchDocIds: string[] = [];+ afterAll(() => {+ if (batchDocIds.length === 0) return;+ run(`doc delete ${batchDocIds.join(' ')} --yes`);+ });+it('should batch create documents from JSON file', () => {const tmpFile = path.join(os.tmpdir(), `e2e-batch-${Date.now()}.json`);const docs = [@@ -230,12 +236,24 @@ describe('lh doc - E2E', () => {try {const output = run(`doc batch-create "${tmpFile}"`);- expect(output).toContain('Created 2 document(s)');- // Extract IDs from output- const matches = output.matchAll(/(docs_\w+)/g);- batchDocIds = [...matches].map((m) => m[1]);- expect(batchDocIds.length).toBe(2);+ // Each bullet also contains the ID in its URL, so only parse the first ID on each line.+ batchDocIds = stripVTControlCharacters(output)+ .split('\n')+ .flatMap((line) => {+ const match = line.match(/^\s*β’\s+(docs_\w+)\b/);+ return match ? [match[1]] : [];+ });+ expect(output).toContain('Created 2 document(s)');+ expect(batchDocIds).toHaveLength(2);+ expect(new Set(batchDocIds).size).toBe(2);++ for (const [index, id] of batchDocIds.entries()) {+ const document = runJson<{ content: string; id: string; title: string }>(+ `doc view ${id} --json id,title,content`,+ );+ expect(document).toEqual({ id, ...docs[index] });+ }} finally {fs.unlinkSync(tmpFile);}@@ -245,6 +263,7 @@ describe('lh doc - E2E', () => {if (batchDocIds.length > 0) {const output = run(`doc delete ${batchDocIds.join(' ')} --yes`);expect(output).toContain('Deleted');+ batchDocIds = [];}});});diff --git a/apps/cli/e2e/memory.e2e.test.ts b/apps/cli/e2e/memory.e2e.test.tsindex cd6c47ef0a2..a465adc8c3c 100644--- a/apps/cli/e2e/memory.e2e.test.ts+++ b/apps/cli/e2e/memory.e2e.test.ts@@ -1,6 +1,7 @@import { execSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';-import { describe, expect, it } from 'vitest';+import { afterAll, describe, expect, it } from 'vitest';/*** E2E tests for `lh memory` user memory management commands.@@ -18,7 +19,7 @@ const TIMEOUT = 60_000;function run(args: string): string {return execSync(`${CLI} ${args}`, {- encoding: 'utf-8',+ encoding: 'utf8',env: { ...process.env, PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}` },timeout: TIMEOUT,}).trim();@@ -29,149 +30,150 @@ function runJson<T = any>(args: string): T {return JSON.parse(output) as T;}-describe(- 'lh memory - E2E',- () => {- const testDesc = `E2E-Memory-${Date.now()}`;- let createdIdentityId: string;-- // ββ create ββββββββββββββββββββββββββββββββββββββββββββ-- describe('create', () => {- it('should create an identity memory with all options', () => {- const output = run(- `memory create --type personal --role developer --relationship self -d "${testDesc}" --labels e2e test`,- );- expect(output).toContain('Created identity memory');-- // Extract both IDs: "Created identity memory mem_xxx (identity: mem_yyy)"- const memMatch = output.match(/memory\s+(mem_\w+)/);- const idMatch = output.match(/identity:\s+(mem_\w+)/);- expect(memMatch).not.toBeNull();- expect(idMatch).not.toBeNull();- createdIdentityId = idMatch![1];- });-- it('should appear in the identity list', () => {- const list = runJson<any[]>('memory list identity --json id,description');- const found = list.find((m) => m.id === createdIdentityId);- expect(found).toBeDefined();- expect(found.description).toBe(testDesc);- });- });-- // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ-- describe('list', () => {- it('should list all memory categories without error', () => {- expect(() => run('memory list')).not.toThrow();- });-- it('should list a specific category in table format', () => {- const output = run('memory list identity');- expect(output).toContain('Identity');- expect(output).toContain('ID');- });-- it('should output JSON for all categories', () => {- const result = runJson<Record<string, any[]>>('memory list --json');- expect(typeof result).toBe('object');- expect(result).toHaveProperty('identity');- expect(result).toHaveProperty('activity');- expect(result).toHaveProperty('context');- expect(result).toHaveProperty('experience');- expect(result).toHaveProperty('preference');- });-- it('should output JSON array for specific category', () => {- const result = runJson<any[]>('memory list identity --json');- expect(Array.isArray(result)).toBe(true);- expect(result.length).toBeGreaterThan(0);- });-- it('should support JSON field filtering', () => {- const result = runJson<any[]>('memory list identity --json id,description');- expect(Array.isArray(result)).toBe(true);- if (result.length > 0) {- expect(result[0]).toHaveProperty('id');- expect(result[0]).toHaveProperty('description');- }- });-- it('should error for invalid category', () => {- expect(() => run('memory list invalidcategory')).toThrow();- });- });-- // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ-- describe('edit', () => {- const updatedDesc = `${testDesc}-Updated`;-- it('should update identity memory description', () => {- const output = run(`memory edit identity ${createdIdentityId} -d "${updatedDesc}"`);- expect(output).toContain('Updated identity memory');- expect(output).toContain(createdIdentityId);- });-- it('should reflect the update in list', () => {- const list = runJson<any[]>('memory list identity --json id,description');- const found = list.find((m) => m.id === createdIdentityId);- expect(found).toBeDefined();- expect(found.description).toBe(updatedDesc);- });-- it('should error on invalid category', () => {- expect(() => run(`memory edit invalidcat ${createdIdentityId} -d "test"`)).toThrow();- });- });-- // ββ persona βββββββββββββββββββββββββββββββββββββββββββ-- describe('persona', () => {- it('should show persona summary or empty message', () => {- const output = run('memory persona');- expect(output).toBeTruthy();- expect(output.includes('User Persona') || output.includes('No persona data')).toBe(true);- });-- it('should output JSON with --json flag', () => {- const output = run('memory persona --json');- expect(() => JSON.parse(output)).not.toThrow();- });- });-- // ββ extract & extract-status ββββββββββββββββββββββββββββ- // NOTE: `memory extract` requires backend extraction service which returns 500- // in dev environments. These commands are tested only in production E2E runs.- // `memory extract-status` is a read-only check that works without triggering extraction.-- describe('extract-status', () => {- it('should check extraction task status without error', () => {- // extract-status is read-only; it returns latest task or empty- expect(() => run('memory extract-status')).not.toThrow();- });- });-- // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ-- describe('delete', () => {- it('should delete the identity memory', () => {- const output = run(`memory delete identity ${createdIdentityId} --yes`);- expect(output).toContain('Deleted identity memory');- expect(output).toContain(createdIdentityId);- });-- it('should no longer appear in the list', () => {- const list = runJson<any[]>('memory list identity --json id');- const found = list.find((m) => m.id === createdIdentityId);- expect(found).toBeUndefined();- });-- it('should error on invalid category', () => {- expect(() => run('memory delete invalidcat some_id --yes')).toThrow();- });- });- },- { timeout: TIMEOUT },-);+describe('lh memory - E2E', { timeout: TIMEOUT }, () => {+ const testDesc = `E2E-Memory-${Date.now()}`;+ let createdIdentityDeleted = false;+ let createdIdentityId: string;++ afterAll(() => {+ if (!createdIdentityId || createdIdentityDeleted) return;+ run(`memory delete identity ${createdIdentityId} --yes`);+ });++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create an identity memory with all options', () => {+ const output = run(+ `memory create --type personal --role developer --relationship self -d "${testDesc}" --labels e2e test`,+ );+ expect(output).toContain('Created identity memory');++ // Extract both IDs: "Created identity memory mem_xxx (identity: mem_yyy)"+ const memMatch = output.match(/memory\s+(mem_\w+)/);+ const idMatch = output.match(/identity:\s+(mem_\w+)/);+ expect(memMatch).not.toBeNull();+ expect(idMatch).not.toBeNull();+ createdIdentityId = idMatch![1];+ });++ it('should appear in the identity list', () => {+ const list = runJson<any[]>('memory list identity --json id,description');+ const found = list.find((m) => m.id === createdIdentityId);+ expect(found).toBeDefined();+ expect(found.description).toBe(testDesc);+ });+ });++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list all memory categories without error', () => {+ expect(() => run('memory list')).not.toThrow();+ });++ it('should list a specific category in table format', () => {+ const output = run('memory list identity');+ expect(output).toContain('Identity');+ expect(output).toContain('ID');+ });++ it('should output JSON for all categories', () => {+ const result = runJson<Record<string, any[]>>('memory list --json');+ expect(typeof result).toBe('object');+ expect(result).toHaveProperty('identity');+ expect(result).toHaveProperty('activity');+ expect(result).toHaveProperty('context');+ expect(result).toHaveProperty('experience');+ expect(result).toHaveProperty('preference');+ });++ it('should output JSON array for specific category', () => {+ const result = runJson<any[]>('memory list identity --json');+ expect(Array.isArray(result)).toBe(true);+ expect(result).toContainEqual(+ expect.objectContaining({ description: testDesc, id: createdIdentityId }),+ );+ });++ it('should support JSON field filtering', () => {+ const result = runJson<any[]>('memory list identity --json id,description');+ expect(result).toContainEqual({ description: testDesc, id: createdIdentityId });+ });++ it('should error for invalid category', () => {+ expect(() => run('memory list invalidcategory')).toThrow();+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedDesc = `${testDesc}-Updated`;++ it('should update identity memory description', () => {+ const output = run(`memory edit identity ${createdIdentityId} -d "${updatedDesc}"`);+ expect(output).toContain('Updated identity memory');+ expect(output).toContain(createdIdentityId);+ });++ it('should reflect the update in list', () => {+ const list = runJson<any[]>('memory list identity --json id,description');+ const found = list.find((m) => m.id === createdIdentityId);+ expect(found).toBeDefined();+ expect(found.description).toBe(updatedDesc);+ });++ it('should error on invalid category', () => {+ expect(() => run(`memory edit invalidcat ${createdIdentityId} -d "test"`)).toThrow();+ });+ });++ // ββ persona βββββββββββββββββββββββββββββββββββββββββββ++ describe('persona', () => {+ it('should show persona summary or empty message', () => {+ const output = run('memory persona');+ expect(output).toBeTruthy();+ expect(output.includes('User Persona') || output.includes('No persona data')).toBe(true);+ });++ it('should output JSON with --json flag', () => {+ const output = run('memory persona --json');+ expect(() => JSON.parse(output)).not.toThrow();+ });+ });++ // ββ extract & extract-status ββββββββββββββββββββββββββββ+ // NOTE: `memory extract` requires backend extraction service which returns 500+ // in dev environments. These commands are tested only in production E2E runs.+ // Use an unknown task ID: querying an existing timed-out task can update its status.++ describe('extract-status', () => {+ it('should return empty for an unknown task ID', () => {+ const result = runJson<null>(`memory extract-status --task-id ${randomUUID()} --json`);+ expect(result).toBeNull();+ });+ });++ // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the identity memory', () => {+ const output = run(`memory delete identity ${createdIdentityId} --yes`);+ expect(output).toContain('Deleted identity memory');+ expect(output).toContain(createdIdentityId);+ createdIdentityDeleted = true;+ });++ it('should no longer appear in the list', () => {+ const list = runJson<any[]>('memory list identity --json id');+ const found = list.find((m) => m.id === createdIdentityId);+ expect(found).toBeUndefined();+ });++ it('should error on invalid category', () => {+ expect(() => run('memory delete invalidcat some_id --yes')).toThrow();+ });+ });+});diff --git a/apps/cli/e2e/model.e2e.test.ts b/apps/cli/e2e/model.e2e.test.tsindex 3f138f708c3..63a60d10e05 100644--- a/apps/cli/e2e/model.e2e.test.ts+++ b/apps/cli/e2e/model.e2e.test.ts@@ -1,6 +1,6 @@import { execSync } from 'node:child_process';-import { describe, expect, it } from 'vitest';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';/*** E2E tests for `lh model` AI model management commands.@@ -9,65 +9,107 @@ import { describe, expect, it } from 'vitest';* - `lh` CLI is installed and linked globally* - User is authenticated (`lh login` completed)* - Network access to the LobeHub server- * - At least one provider (e.g. openai) must be available*- * These tests create a real model, verify CRUD operations, then clean up.+ * The suite owns a uniquely named provider and deletes it after the run. It+ * never changes models belonging to an existing provider on the user account.*/const CLI = process.env.LH_CLI_PATH || 'lh';const TIMEOUT = 30_000;-const TEST_PROVIDER = 'openai';+const suiteId = `${Date.now()}-${process.pid}`;+const TEST_PROVIDER = `e2e-model-provider-${suiteId}`;+const TEST_PROVIDER_NAME = `E2E Model Provider ${suiteId}`;++const listFixtures = [+ { enabled: true, id: `e2e-list-chat-a-${suiteId}`, type: 'chat' },+ { enabled: true, id: `e2e-list-chat-b-${suiteId}`, type: 'chat' },+ { enabled: true, id: `e2e-list-embedding-${suiteId}`, type: 'embedding' },+ { enabled: false, id: `e2e-list-disabled-chat-${suiteId}`, type: 'chat' },+ { enabled: false, id: `e2e-list-disabled-tts-${suiteId}`, type: 'tts' },+] as const;function run(args: string): string {return execSync(`${CLI} ${args}`, {- encoding: 'utf-8',+ encoding: 'utf8',env: { ...process.env, PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}` },timeout: TIMEOUT,}).trim();}-function runJson<T = any>(args: string): T {+function runJson<T>(args: string): T {const output = run(args);return JSON.parse(output) as T;}describe('lh model - E2E', () => {- const testModelId = `e2e-model-${Date.now()}`;+ const testModelId = `e2e-model-${suiteId}`;const testDisplayName = 'E2E Test Model';+ let providerCreated = false;++ beforeAll(() => {+ run(+ `provider create --id ${TEST_PROVIDER} --name "${TEST_PROVIDER_NAME}" --source custom --sdk-type openai`,+ );+ providerCreated = true;++ for (const fixture of listFixtures) {+ run(+ `model create --id ${fixture.id} --provider ${TEST_PROVIDER} --display-name "${fixture.id}" --type ${fixture.type}`,+ );+ if (!fixture.enabled) {+ run(`model toggle ${fixture.id} --provider ${TEST_PROVIDER} --disable`);+ }+ }+ }, TIMEOUT * 2);++ afterAll(() => {+ if (providerCreated) run(`provider delete ${TEST_PROVIDER} --yes`);+ });// ββ list ββββββββββββββββββββββββββββββββββββββββββββββdescribe('list', () => {- it('should list models for a provider in table format', () => {+ it('should list the suite models for a provider in table format', () => {const output = run(`model list ${TEST_PROVIDER}`);expect(output).toContain('ID');expect(output).toContain('NAME');expect(output).toContain('ENABLED');expect(output).toContain('TYPE');+ for (const fixture of listFixtures) expect(output).toContain(fixture.id);});- it('should filter enabled models', () => {- const output = run(`model list ${TEST_PROVIDER} --enabled`);- // Every row should have β- expect(output).not.toContain('β');+ it('should return only the enabled fixture models', () => {+ const list = runJson<{ enabled: boolean; id: string }[]>(+ `model list ${TEST_PROVIDER} --enabled --json id,enabled`,+ );+ const ids = list.map(({ id }) => id);++ expect(ids).toEqual(+ expect.arrayContaining(listFixtures.filter((model) => model.enabled).map(({ id }) => id)),+ );+ expect(ids).not.toEqual(+ expect.arrayContaining(listFixtures.filter((model) => !model.enabled).map(({ id }) => id)),+ );+ expect(list.every(({ enabled }) => enabled)).toBe(true);});it('should output JSON with field filtering', () => {const list = runJson<{ id: string; type: string }[]>(`model list ${TEST_PROVIDER} --json id,type -L 5`,);- expect(Array.isArray(list)).toBe(true);- expect(list.length).toBeLessThanOrEqual(5);- if (list.length > 0) {- expect(list[0]).toHaveProperty('id');- expect(list[0]).toHaveProperty('type');- expect(list[0]).not.toHaveProperty('displayName');- }+ expect(list).toHaveLength(5);+ expect(list.map(({ id }) => id)).toEqual(+ expect.arrayContaining(listFixtures.map(({ id }) => id)),+ );+ expect(list[0]).toHaveProperty('id');+ expect(list[0]).toHaveProperty('type');+ expect(list[0]).not.toHaveProperty('displayName');});- it('should respect limit option', () => {- const list = runJson<any[]>(`model list ${TEST_PROVIDER} --json id -L 3`);- expect(list.length).toBeLessThanOrEqual(3);+ it('should respect limit option with more fixtures than the limit', () => {+ const list = runJson<{ id: string }[]>(`model list ${TEST_PROVIDER} --json id -L 3`);+ expect(list).toHaveLength(3);+ expect(list.every(({ id }) => listFixtures.some((fixture) => fixture.id === id))).toBe(true);});});@@ -83,8 +125,7 @@ describe('lh model - E2E', () => {it('should appear in the model list', () => {const list = runJson<{ id: string }[]>(`model list ${TEST_PROVIDER} --json id`);- const found = list.find((m) => m.id === testModelId);- expect(found).toBeDefined();+ expect(list.some(({ id }) => id === testModelId)).toBe(true);});});@@ -112,7 +153,7 @@ describe('lh model - E2E', () => {});it('should error for nonexistent model', () => {- expect(() => run('model view nonexistent-model-xyz')).toThrow();+ expect(() => run(`model view nonexistent-model-${suiteId}`)).toThrow();});});@@ -179,7 +220,7 @@ describe('lh model - E2E', () => {});});- // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ+ // ββ delete ββββββββββββββββββββββββββββββββββββββββββββdescribe('delete', () => {it('should delete the model', () => {@@ -193,13 +234,45 @@ describe('lh model - E2E', () => {});});- // ββ clear (test with caution) βββββββββββββββββββββββββ+ // ββ clear βββββββββββββββββββββββββββββββββββββββββββββdescribe('clear', () => {- it('should clear remote models for provider', () => {+ it('should clear a remote model while preserving a custom model', () => {+ const remoteModelId = `e2e-remote-${suiteId}`;+ const customModelId = `e2e-custom-${suiteId}`;+ const remoteModels = JSON.stringify([+ {+ displayName: 'E2E Remote Model',+ enabled: true,+ id: remoteModelId,+ source: 'remote',+ type: 'chat',+ },+ ]);+ run(`model batch-update ${TEST_PROVIDER} --models '${remoteModels}'`);+ run(+ `model create --id ${customModelId} --provider ${TEST_PROVIDER} --display-name "E2E Custom Model" --type chat`,+ );++ const seeded = runJson<{ id: string; source: string }[]>(+ `model list ${TEST_PROVIDER} --json id,source`,+ );+ expect(seeded).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: remoteModelId, source: 'remote' }),+ expect.objectContaining({ id: customModelId, source: 'custom' }),+ ]),+ );+const output = run(`model clear --provider ${TEST_PROVIDER} --remote --yes`);expect(output).toContain('Cleared remote models');expect(output).toContain(TEST_PROVIDER);++ const remaining = runJson<{ id: string }[]>(`model list ${TEST_PROVIDER} --json id`).map(+ ({ id }) => id,+ );+ expect(remaining).not.toContain(remoteModelId);+ expect(remaining).toContain(customModelId);});});});diff --git a/apps/cli/e2e/search.e2e.test.ts b/apps/cli/e2e/search.e2e.test.tsindex ac5c83366ee..1952562edc4 100644--- a/apps/cli/e2e/search.e2e.test.ts+++ b/apps/cli/e2e/search.e2e.test.ts@@ -1,6 +1,6 @@import { execSync } from 'node:child_process';-import { describe, expect, it } from 'vitest';+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';/*** E2E tests for `lh search` global search command.@@ -14,42 +14,128 @@ import { describe, expect, it } from 'vitest';const CLI = process.env.LH_CLI_PATH || 'lh';const TIMEOUT = 30_000;+interface SearchResult {+ id: string;+ title?: string;+ type: string;+}+function run(args: string): string {return execSync(`${CLI} ${args}`, {- encoding: 'utf-8',+ encoding: 'utf8',env: { ...process.env, PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}` },timeout: TIMEOUT,}).trim();}-function runJson<T = any>(args: string): T {- const output = run(args);- return JSON.parse(output) as T;+function runJson<T>(args: string): T {+ return JSON.parse(run(args)) as T;+}++function extractId(output: string, pattern: RegExp): string {+ const match = output.match(pattern);+ expect(match).not.toBeNull();+ return match![1];}describe('lh search - E2E', () => {- it('should search across types', () => {- const output = run('search "test"');- // May show results or "No results found."- expect(output).toBeTruthy();+ const fixtureKey = `E2ESearch${Date.now()}`;+ const agentIds: string[] = [];+ let docId: string;++ beforeAll(async () => {+ for (let index = 1; index <= 4; index += 1) {+ const output = run(+ `agent create -t "${fixtureKey} Agent ${index}" -d "Owned search fixture ${fixtureKey}"`,+ );+ agentIds.push(extractId(output, /Created agent\s+(\S+)/));+ }++ const output = run(+ `doc create -t "${fixtureKey} Document" -b "Owned search fixture ${fixtureKey}"`,+ );+ docId = extractId(output, /Created document\s+(docs_\w+)/);++ // Elasticsearch deployments project writes asynchronously. Wait for our+ // fixtures using read-only queries; never retry creation or accept an empty result.+ await vi.waitFor(+ () => {+ expect({+ agents: runJson<SearchResult[]>(+ `search --query "${fixtureKey}" --type agent --json -L 10`,+ ).map(({ id }) => id),+ pages: runJson<SearchResult[]>(+ `search --query "${fixtureKey}" --type page --json -L 10`,+ ).map(({ id }) => id),+ }).toEqual({+ agents: expect.arrayContaining(agentIds),+ pages: expect.arrayContaining([docId]),+ });+ },+ { interval: 2000, timeout: 60_000 },+ );+ }, 120_000);++ afterAll(() => {+ const errors: unknown[] = [];+ if (docId) {+ try {+ run(`doc delete ${docId} --yes`);+ } catch (error) {+ errors.push(error);+ }+ }+ for (const id of agentIds) {+ try {+ run(`agent delete ${id} --yes`);+ } catch (error) {+ errors.push(error);+ }+ }+ if (errors.length > 0) throw new AggregateError(errors, 'Search fixture cleanup failed');});- it('should output JSON', () => {- const result = runJson('search "test" --json');- expect(result).toBeTruthy();+ it('searches the owned agent and document fixtures by query', () => {+ const results = runJson<SearchResult[]>(`search --query "${fixtureKey}" --json -L 10`);++ expect(Array.isArray(results)).toBe(true);+ expect(results).toContainEqual(expect.objectContaining({ id: docId, type: 'page' }));+ // Untyped search deliberately caps each group at three in FtsSearchRepo.+ // Explicitly typed search is the path that uses the requested limit.+ const agents = results.filter((result) => result.type === 'agent');+ expect(agents).toHaveLength(3);+ expect(agents.every((result) => agentIds.includes(result.id))).toBe(true);});- it('should filter by type', () => {- const output = run('search "test" --type agent');- expect(output).toBeTruthy();+ it('filters results by type', () => {+ const results = runJson<SearchResult[]>(+ `search --query "${fixtureKey}" --type page --json -L 10`,+ );++ expect(results).toContainEqual(expect.objectContaining({ id: docId, type: 'page' }));+ expect(results.every((result) => result.type === 'page')).toBe(true);+ expect(results.some((result) => agentIds.includes(result.id))).toBe(false);});- it('should respect limit option', () => {- const result = runJson('search "test" --json -L 3');- expect(result).toBeTruthy();+ it('applies the requested limit to an explicit result type', () => {+ const results = runJson<SearchResult[]>(+ `search --query "${fixtureKey}" --type agent --json -L 2`,+ );+ expect(results).toHaveLength(2);+ expect(results.every((result) => result.type === 'agent' && agentIds.includes(result.id))).toBe(+ true,+ );});- it('should error for invalid type', () => {- expect(() => run('search "test" --type invalidtype')).toThrow();+ it('reports the exact error for an invalid type', () => {+ try {+ run(`search --query "${fixtureKey}" --type invalidtype`);+ throw new Error('Expected search to reject an invalid type');+ } catch (error) {+ const stderr = (error as { stderr?: string }).stderr?.trim();+ expect(stderr).toBe(+ 'Invalid type: invalidtype. Must be one of: agent, topic, file, folder, message, page, memory, mcp, plugin, communityAgent, knowledgeBase',+ );+ }});});diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex a5df47de3a0..2aa1a222b8a 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -25,6 +25,7 @@"prepublishOnly": "npm run build && npm run man:generate","test": "bunx vitest run --config vitest.config.mts --silent='passed-only'","test:coverage": "bunx vitest run --config vitest.config.mts --coverage",+ "test:e2e": "bunx vitest run --config vitest.e2e.config.mts --silent='passed-only'","type-check": "tsc --noEmit"},"dependencies": {diff --git a/apps/cli/tests/agentSignalGolden.test.ts b/apps/cli/tests/agentSignalGolden.test.tsnew file mode 100644index 00000000000..c01ff3bca31--- /dev/null+++ b/apps/cli/tests/agentSignalGolden.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import {+ assertGoldenFinalState,+ extractGoldenOutcomes,+} from '../e2e/fixtures/agent-signal/assertGoldenFinalState';+import golden from '../e2e/fixtures/agent-signal/nightly-review.golden.json';++describe('agent-signal golden fixture - structural regression', () => {+ it('captures a recognizable nightly-review source payload', () => {+ expect(golden.source.sourceType).toBe('agent.nightly_review.requested');+ expect(golden.source.payload.agentId).toBeTruthy();+ expect(golden.source.payload.userId).toBeTruthy();+ expect(golden.source.scopeKey).toContain('agent:');+ });++ it('extracts ideas / write outcomes / brief from finalState', () => {+ const outcomes = extractGoldenOutcomes(golden.finalState);+ expect(outcomes.ideas.length).toBeGreaterThanOrEqual(1);+ expect(outcomes.writeOutcomes.length).toBeGreaterThanOrEqual(1);+ expect(outcomes.brief).toBeDefined();+ });++ it('passes the shared structural assertion', () => {+ expect(() => assertGoldenFinalState(golden.finalState)).not.toThrow();+ });++ it('rejects an empty finalState', () => {+ expect(() => assertGoldenFinalState({ messages: [] })).toThrow(/artifact/i);+ });+});diff --git a/apps/cli/tests/e2eEnvironment.test.ts b/apps/cli/tests/e2eEnvironment.test.tsnew file mode 100644index 00000000000..77c07f2f938--- /dev/null+++ b/apps/cli/tests/e2eEnvironment.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';++import { validateE2EEnvironment } from './e2eEnvironment';++const selectedEnvironment = {+ LOBEHUB_CLI_HOME: '.lobehub-e2e',+ LOBEHUB_E2E_ALLOW_WRITES: '1',+ LOBEHUB_SERVER: 'http://localhost:3010',+};++describe('live E2E environment', () => {+ it('requires explicit write authorization', () => {+ expect(() =>+ validateE2EEnvironment({ ...selectedEnvironment, LOBEHUB_E2E_ALLOW_WRITES: undefined }),+ ).toThrow('ALLOW_WRITES');+ });++ it.each([undefined, '', '.lobehub', '/tmp/../home/.lobehub/'])(+ 'rejects an absent or default home: %s',+ (home) => {+ expect(() =>+ validateE2EEnvironment({ ...selectedEnvironment, LOBEHUB_CLI_HOME: home }),+ ).toThrow('dedicated');+ },+ );++ it.each([undefined, 'file:///tmp/server', 'https://user:[email protected]'])(+ 'rejects a missing or unsafe server: %s',+ (server) => {+ expect(() =>+ validateE2EEnvironment({ ...selectedEnvironment, LOBEHUB_SERVER: server }),+ ).toThrow();+ },+ );++ it('preserves the selected home and environment', () => {+ const env = Object.freeze({ ...selectedEnvironment });+ expect(() => validateE2EEnvironment(env)).not.toThrow();+ expect(env).toEqual(selectedEnvironment);+ });+});diff --git a/apps/cli/tests/e2eEnvironment.ts b/apps/cli/tests/e2eEnvironment.tsnew file mode 100644index 00000000000..773670f4130--- /dev/null+++ b/apps/cli/tests/e2eEnvironment.ts@@ -0,0 +1,19 @@+import path from 'node:path';++/** Live tests must opt in to writes and select their own account home and server. */+export function validateE2EEnvironment(env: NodeJS.ProcessEnv) {+ if (env.LOBEHUB_E2E_ALLOW_WRITES !== '1') {+ throw new Error('Live E2E writes real data. Set LOBEHUB_E2E_ALLOW_WRITES=1 to opt in.');+ }++ const home = env.LOBEHUB_CLI_HOME?.trim();+ if (!home || path.basename(path.normalize(home)) === '.lobehub') {+ throw new Error('Set LOBEHUB_CLI_HOME to a dedicated test account directory, not .lobehub.');+ }++ if (!env.LOBEHUB_SERVER) throw new Error('Set LOBEHUB_SERVER explicitly for live E2E.');+ const server = new URL(env.LOBEHUB_SERVER);+ if (!['http:', 'https:'].includes(server.protocol) || server.username || server.password) {+ throw new Error('LOBEHUB_SERVER must be an HTTP(S) URL without credentials.');+ }+}diff --git a/apps/cli/tests/setup.e2e.ts b/apps/cli/tests/setup.e2e.tsnew file mode 100644index 00000000000..e195fda1572--- /dev/null+++ b/apps/cli/tests/setup.e2e.ts@@ -0,0 +1,24 @@+import { execFile } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++import { beforeAll } from 'vitest';++import { validateE2EEnvironment } from './e2eEnvironment';++const cli = fileURLToPath(new URL('../dist/index.js', import.meta.url));+// Legacy suites execute a shell command. Pin both paths instead of relying on a+// globally installed lh or accepting a command that overrides the selected home.+const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;+process.env.LH_CLI_PATH = `${quote(process.execPath)} ${quote(cli)}`;++beforeAll(async () => {+ validateE2EEnvironment(process.env);+ const execute = promisify(execFile);+ const options = { env: process.env, timeout: 30_000 };+ const { stdout } = await execute(process.execPath, [cli, '--version'], options);+ console.info(`Live E2E CLI: ${stdout.trim()}`);+ // Verify the explicitly selected identity before any suite creates fixtures.+ // Do not print account details, copy credentials, or delete the caller's home.+ await execute(process.execPath, [cli, 'whoami', '--json'], options);+}, 60_000);diff --git a/apps/cli/vitest.config.mts b/apps/cli/vitest.config.mtsindex 3cd309a6333..df7488a34ce 100644--- a/apps/cli/vitest.config.mts+++ b/apps/cli/vitest.config.mts@@ -36,6 +36,7 @@ export default defineConfig({],},test: {+ include: ['src/**/*.test.ts', 'scripts/**/*.test.ts', 'tests/**/*.test.ts', '*.test.ts'],coverage: {reporter: ['text', 'json', 'lcov', 'text-summary'],},diff --git a/apps/cli/vitest.config.test.ts b/apps/cli/vitest.config.test.tsnew file mode 100644index 00000000000..d8a9783ce46--- /dev/null+++ b/apps/cli/vitest.config.test.ts@@ -0,0 +1,23 @@+import fg from 'fast-glob';+import { describe, expect, it } from 'vitest';++import unitConfig from './vitest.config.mts';+import liveConfig from './vitest.e2e.config.mts';++describe('CLI test boundaries', () => {+ it('keeps every live E2E out of the default offline test entry', async () => {+ const unitFiles = await fg(unitConfig.test!.include!);+ const liveFiles = await fg(liveConfig.test!.include!);+ expect(liveFiles).toContain('e2e/memory.e2e.test.ts');+ expect(unitFiles).toContain('tests/agentSignalGolden.test.ts');+ expect(unitFiles).toContain('src/commands/login.test.ts');+ expect(unitFiles).toContain('scripts/ensureWorkspaceLinks.test.ts');+ expect(unitFiles).toContain('tsdown.config.test.ts');+ expect(unitFiles.filter((file) => liveFiles.includes(file))).toEqual([]);+ });++ it('never applies the disposable unit home setup to live tests', () => {+ expect(unitConfig.test!.setupFiles).toEqual(['./tests/setup.ts']);+ expect(liveConfig.test!.setupFiles).toEqual(['./tests/setup.e2e.ts']);+ });+});diff --git a/apps/cli/vitest.e2e.config.mts b/apps/cli/vitest.e2e.config.mtsnew file mode 100644index 00000000000..b83e6c177bd--- /dev/null+++ b/apps/cli/vitest.e2e.config.mts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ include: ['e2e/**/*.e2e.test.ts'],+ setupFiles: ['./tests/setup.e2e.ts'],+ },+});