π€― 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
β¨ feat: lobehub cli for better agency agent (#12897)
Arvin Xuaa8082d6b2e9
diff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.mdindex c467d535880..8555263d22e 100644--- a/.agents/skills/cli/SKILL.md+++ b/.agents/skills/cli/SKILL.md@@ -8,11 +8,11 @@ disable-model-invocation: true## Overview-LobeHub CLI (`@lobehub/cli`) is a command-line tool for managing and interacting with LobeHub services. The binary is named `lh` and is built with Commander.js + TypeScript.+LobeHub CLI (`@lobehub/cli`) is a command-line tool for managing and interacting with LobeHub services. Built with Commander.js + TypeScript.- **Package**: `apps/cli/`- **Entry**: `apps/cli/src/index.ts`-- **Binary**: `lh`+- **Binaries**: `lh`, `lobe`, `lobehub` (all aliases for the same CLI)- **Build**: tsup- **Runtime**: Node.js / Bun@@ -64,27 +64,27 @@ apps/cli/src/## Command Groups-| Command | Alias | Description |-| ------------- | ----- | ------------------------------------------------- |-| `lh login` | - | Authenticate via OIDC Device Code Flow |-| `lh logout` | - | Clear stored credentials |-| `lh connect` | - | Device gateway connection & daemon management |-| `lh status` | - | Quick gateway connectivity check |-| `lh agent` | - | Agent CRUD, run, status |-| `lh generate` | `gen` | Content generation (text, image, video, tts, asr) |-| `lh doc` | - | Document CRUD |-| `lh file` | - | File list, view, delete, recent |-| `lh kb` | - | Knowledge base management |-| `lh memory` | - | User memory CRUD + extraction |-| `lh message` | - | Message list, search, delete, count, heatmap |-| `lh topic` | - | Topic CRUD + search + recent |-| `lh skill` | - | Skill CRUD + import (GitHub/URL/market) |-| `lh model` | - | Model list, view, toggle, delete |-| `lh provider` | - | Provider list, view, toggle, delete |-| `lh plugin` | - | Plugin install, uninstall, update |-| `lh search` | - | Global search across all types |-| `lh whoami` | - | Current user info |-| `lh usage` | - | Monthly/daily usage statistics |+| Command | Alias | Description |+| ------------- | ----- | ----------------------------------------------------------- |+| `lh login` | - | Authenticate via OIDC Device Code Flow |+| `lh logout` | - | Clear stored credentials |+| `lh connect` | - | Device gateway connection & daemon management |+| `lh status` | - | Quick gateway connectivity check |+| `lh agent` | - | Agent CRUD, run, status |+| `lh generate` | `gen` | Content generation (text, image, video, tts, asr, download) |+| `lh doc` | - | Document CRUD, batch-create, parse, topic linking |+| `lh file` | - | File list, view, delete, recent |+| `lh kb` | - | Knowledge base CRUD, folders, docs, upload, tree view |+| `lh memory` | - | User memory CRUD + extraction |+| `lh message` | - | Message list, search, delete, count, heatmap |+| `lh topic` | - | Topic CRUD + search + recent |+| `lh skill` | - | Skill CRUD + import (GitHub/URL/market) |+| `lh model` | - | Model CRUD, toggle, batch-toggle, clear |+| `lh provider` | - | Provider CRUD, config, test, toggle |+| `lh plugin` | - | Plugin install, uninstall, update |+| `lh search` | - | Global search across all types |+| `lh whoami` | - | Current user info |+| `lh usage` | - | Monthly/daily usage statistics |## Adding a New Command@@ -185,6 +185,8 @@ if (!options.yes) {| Daemon Status | `~/.lobehub/daemon.status` | Connection status JSON || Daemon Log | `~/.lobehub/daemon.log` | Daemon output log |+The base directory (`~/.lobehub/`) can be overridden with the `LOBEHUB_CLI_HOME` env var (e.g. `LOBEHUB_CLI_HOME=.lobehub-dev` for dev mode isolation).+## Key Dependencies- `commander` - CLI framework@@ -199,15 +201,18 @@ if (!options.yes) {## Development```bash-# Run directly (dev mode)+# Run directly (dev mode, uses ~/.lobehub-dev for credentials)cd apps/cli && bun run dev -- <command># Buildcd apps/cli && bun run build-# Test+# Test (unit tests)cd apps/cli && bun run test+# E2E tests (requires authenticated CLI)+cd apps/cli && bunx vitest run e2e/kb.e2e.test.ts+# Link globally for testingcd apps/cli && bun run cli:link```@@ -216,10 +221,8 @@ cd apps/cli && bun run cli:linkSee `references/` for each command group:-- **Authentication**: `references/auth.md` (login, logout)-- **Connection & Gateway**: `references/connect.md` (connect, status, daemon)- **Agent**: `references/agent.md` (CRUD, run, status)-- **Content Generation**: `references/generate.md` (text, image, video, tts, asr)+- **Content Generation**: `references/generate.md` (text, image, video, tts, asr, download)- **Knowledge & Files**: `references/knowledge.md` (kb, file, doc)- **Conversation**: `references/conversation.md` (topic, message)- **Memory**: `references/memory.md` (memory management, extraction)diff --git a/.agents/skills/cli/references/conversation.md b/.agents/skills/cli/references/conversation.mdindex cbec0d12132..ba4d07c22b7 100644--- a/.agents/skills/cli/references/conversation.md+++ b/.agents/skills/cli/references/conversation.md@@ -9,17 +9,16 @@ Manage conversation topics (threads).### `lh topic list````bash-lh topic list [--agent-id [--session-id [-L [--page [--json [fields]] < id > ] < id > ] < n > ] < n > ]+lh topic list [--agent-id [-L [--page [--json [fields]] < id > ] < n > ] < n > ]```-| Option | Description | Default |-| ------------------- | ----------------- | ------- |-| `--agent-id <id>` | Filter by agent | - |-| `--session-id <id>` | Filter by session | - |-| `-L, --limit <n>` | Page size | `30` |-| `--page <n>` | Page number | `1` |+| Option | Description | Default |+| ----------------- | --------------- | ------- |+| `--agent-id <id>` | Filter by agent | - |+| `-L, --limit <n>` | Page size | `30` |+| `--page <n>` | Page number | `1` |-**Table columns**: ID, TITLE, FAVORITE, UPDATED+**Table columns**: ID, TITLE, FAV, UPDATED### `lh topic search <keywords>`@@ -30,15 +29,14 @@ lh topic search [--json [fields]] < keywords > [--agent-id < id > ]### `lh topic create````bash-lh topic create -t [--session-id [--favorite] < title > [--agent-id < id > ] < id > ]+lh topic create -t [--favorite] < title > [--agent-id < id > ]```-| Option | Description | Required |-| --------------------- | ---------------------- | -------- |-| `-t, --title <title>` | Topic title | Yes |-| `--agent-id <id>` | Associate with agent | No |-| `--session-id <id>` | Associate with session | No |-| `--favorite` | Mark as favorite | No |+| Option | Description | Required |+| --------------------- | -------------------- | -------- |+| `-t, --title <title>` | Topic title | Yes |+| `--agent-id <id>` | Associate with agent | No |+| `--favorite` | Mark as favorite | No |### `lh topic edit <id>`@@ -76,16 +74,18 @@ Manage chat messages within topics.lh message list [options] [--json [fields]]```-| Option | Description | Default |-| ------------------- | ----------------- | ------- |-| `--topic-id <id>` | Filter by topic | - |-| `--agent-id <id>` | Filter by agent | - |-| `--session-id <id>` | Filter by session | - |-| `-L, --limit <n>` | Page size | `30` |-| `--page <n>` | Page number | `1` |+| Option | Description | Default |+| ----------------- | ----------------------- | ------- |+| `--topic-id <id>` | Filter by topic | - |+| `--agent-id <id>` | Filter by agent | - |+| `-L, --limit <n>` | Page size | `30` |+| `--page <n>` | Page number | `1` |+| `--user` | Only show user messages | - |**Table columns**: ID, ROLE, CONTENT, CREATED+**Note**: When `--topic-id` or `--agent-id` is provided, uses `message.getMessages`; otherwise uses `message.listAll`.+### `lh message search <keywords>````bashdiff --git a/.agents/skills/cli/references/generate.md b/.agents/skills/cli/references/generate.mdindex 72cf49fbea2..8e15b7df542 100644--- a/.agents/skills/cli/references/generate.md+++ b/.agents/skills/cli/references/generate.md@@ -8,13 +8,14 @@ Generate text, images, videos, speech, and transcriptions.```lh generate (alias: gen)-βββ text <prompt> # Text generation-βββ image <prompt> # Image generation-βββ video <prompt> # Video generation-βββ tts <text> # Text-to-speech-βββ asr <audioFile> # Audio-to-text (speech recognition)-βββ status <genId> <taskId> # Check async task status-βββ list # List generation topics+βββ text <prompt> # Text generation+βββ image <prompt> # Image generation+βββ video <prompt> # Video generation+βββ tts <text> # Text-to-speech+βββ asr <audioFile> # Audio-to-text (speech recognition)+βββ download <genId> <taskId> # Wait & download generation result+βββ status <genId> <taskId> # Check async task status+βββ list # List generation topics```---@@ -53,26 +54,77 @@ cat README.md | lh gen text "summarize this" --pipe## `lh generate image <prompt>` / `lh gen image <prompt>`-Generate images from text prompt.+Generate images from text prompt. This is an async operation β the command submits the task and returns a generation ID + task ID for tracking.**Source**: `apps/cli/src/commands/generate/image.ts````bashlh gen image "A sunset over mountains" [options]+lh gen image "A cute cat" --model dall-e-3 --provider openai --json```-Options follow same pattern as text generation with image-specific model defaults.+| Option | Description | Default |+| --------------------------- | ---------------- | ---------- |+| `-m, --model <model>` | Model ID | `dall-e-3` |+| `-p, --provider <provider>` | Provider name | `openai` |+| `-n, --num <n>` | Number of images | `1` |+| `--width <px>` | Width in pixels | - |+| `--height <px>` | Height in pixels | - |+| `--steps <n>` | Number of steps | - |+| `--seed <n>` | Random seed | - |+| `--json` | Output raw JSON | `false` |++**Output** (non-JSON):++```+β Image generation started+ Batch ID: gb_xxx+ 1 image(s) queued+ Generation gen_xxx β Task <taskId>++Use "lh generate status <generationId> <taskId>" to check progress.+```++**Typical workflow**:++```bash+# Generate image, then wait & download+lh gen image "A cute cat"+lh gen download <generationId> <taskId> -o cat.png+```---## `lh generate video <prompt>` / `lh gen video <prompt>`-Generate video from text prompt.+Generate video from text prompt. This is an async operation.**Source**: `apps/cli/src/commands/generate/video.ts````bash-lh gen video "A cat playing piano" [options]+lh gen video "A cat playing piano" -m < model > -p < provider > [options]+```++| Option | Description | Required |+| --------------------------- | ------------------------ | -------- |+| `-m, --model <model>` | Model ID | Yes |+| `-p, --provider <provider>` | Provider name | Yes |+| `--aspect-ratio <ratio>` | Aspect ratio (e.g. 16:9) | No |+| `--duration <sec>` | Duration in seconds | No |+| `--resolution <res>` | Resolution (e.g. 720p) | No |+| `--seed <n>` | Random seed | No |+| `--json` | Output raw JSON | No |++**Note**: Unlike image, video requires `-m` and `-p` (no defaults). Use `lh model list <provider> --type video` to find available video models.++**Output** (non-JSON):++```+β Video generation started+ Batch ID: gb_xxx+ Generation gen_xxx β Task <taskId>++Use "lh generate status <generationId> <taskId>" to check progress.```---@@ -101,6 +153,46 @@ lh gen asr recording.wav [options]---+## `lh generate download <generationId> <taskId>`++Wait for an async generation task to complete and download the result file.++**Source**: `apps/cli/src/commands/generate/index.ts`++```bash+lh gen download <generationId> <taskId> [-o output.png]+lh gen download gen_xxx task_xxx -o ~/Desktop/result.mp4 --timeout 600+```++| Option | Description | Default |+| --------------------- | ---------------------------------------- | ---------------------- |+| `-o, --output <path>` | Output file path (auto-detect extension) | `<generationId>.<ext>` |+| `--interval <sec>` | Polling interval in seconds | `5` |+| `--timeout <sec>` | Timeout in seconds (0 = no timeout) | `300` |++**Behavior**:++1. Polls `generation.getGenerationStatus` at the specified interval+2. Shows live progress: `β― Status: processing... (42s)`+3. On success: downloads asset URL to local file+4. On error: displays error message and exits+5. On timeout: suggests using `lh gen status` to check later++**Typical workflow**:++```bash+# One-shot: generate and download+lh gen image "A sunset"+# Copy the generation ID and task ID from output+lh gen download gen_xxx taskId_xxx -o sunset.png++# Video (longer timeout)+lh gen video "A cat running" -m model -p provider+lh gen download gen_xxx taskId_xxx -o cat.mp4 --timeout 600+```++---+## `lh generate status <generationId> <taskId>`Check the status of an async generation task.@@ -130,3 +222,25 @@ lh gen list [--json [fields]]```**Table columns**: ID, TITLE, TYPE, UPDATED++---++## Backend Architecture++Image and video generation use an async task pattern:++1. **Create topic** β `generationTopic.createTopic`+2. **Submit generation** β `image.createImage` / `video.createVideo`+ - Creates batch + generation + asyncTask records in a DB transaction+ - Triggers async background task (image via `createAsyncCaller`, video via `initModelRuntimeFromDB`)+ - Returns `{ data: { batch, generations }, success }` with `asyncTaskId` in each generation+3. **Poll status** β `generation.getGenerationStatus`+ - Returns `{ status, error, generation }` (generation includes asset URLs on success)++**Server routes**:++- `src/server/routers/lambda/image/index.ts` β image creation (uses `authedProcedure` + `serverDatabase`)+- `src/server/routers/lambda/video/index.ts` β video creation (uses `authedProcedure` + `serverDatabase`)+- `src/server/routers/lambda/generation.ts` β status checking++**Note**: Image/video routes do NOT use the `keyVaults` middleware β they read API keys from the database via `initModelRuntimeFromDB` or `createAsyncCaller`.diff --git a/.agents/skills/cli/references/knowledge.md b/.agents/skills/cli/references/knowledge.mdindex e11c20a03bf..174e046d95b 100644--- a/.agents/skills/cli/references/knowledge.md+++ b/.agents/skills/cli/references/knowledge.md@@ -2,7 +2,7 @@## Knowledge Base (`lh kb`)-Manage knowledge bases for RAG (Retrieval-Augmented Generation).+Manage knowledge bases for RAG (Retrieval-Augmented Generation). Supports directory tree structure with folders, documents, and file uploads.**Source**: `apps/cli/src/commands/kb.ts`@@ -20,7 +20,9 @@ lh kb list [--json [fields]]lh kb view [fields]] < id > [--json```-**Displays**: Name, description, associated files.+**Displays**: Name, description, full directory tree with all files and documents (recursively fetched). Shows indented tree structure with item type (File/Doc), file type, and size.++**API**: Uses `file.getKnowledgeItems` to recursively fetch items. Folders (`custom/folder` fileType) are traversed in parallel via `Promise.all` for performance.### `lh kb create`@@ -34,7 +36,7 @@ lh kb create -n [--avatar < name > [-d < desc > ] < url > ]| `-d, --description <desc>` | Description | No || `--avatar <url>` | Avatar URL | No |-**Output**: Created KB ID.+**Output**: Created KB ID. Note: backend returns ID as a string directly (not an object).### `lh kb edit <id>`@@ -42,6 +44,8 @@ lh kb create -n [--avatar < name > [-d < desc > ] < url > ]lh kb edit [-d [--avatar < id > [-n < name > ] < desc > ] < url > ]```+Requires at least one change flag. Errors if none specified.+### `lh kb delete <id>````bash@@ -59,12 +63,72 @@ lh kb delete [--yes] < id > [--remove-files]lh kb add-files <kbId> --ids <fileId1> <fileId2> ...```+Link existing files to a knowledge base.+### `lh kb remove-files <knowledgeBaseId>````bashlh kb remove-files <kbId> --ids <fileId1> <fileId2> ... [--yes]```+Unlink files from a knowledge base.++### `lh kb mkdir <knowledgeBaseId>`++```bash+lh kb mkdir < kbId > -n < name > [--parent < folderId > ]+```++Create a folder in a knowledge base. Uses `document.createDocument` with `fileType: 'custom/folder'`.++| Option | Description | Required |+| --------------------- | ---------------- | -------- |+| `-n, --name <name>` | Folder name | Yes |+| `--parent <parentId>` | Parent folder ID | No |++### `lh kb create-doc <knowledgeBaseId>`++```bash+lh kb create-doc [--parent < kbId > -t < title > [-c < content > ] < folderId > ]+```++Create a document in a knowledge base. Uses `document.createDocument` with `fileType: 'custom/document'`.++| Option | Description | Required |+| ---------------------- | ---------------- | -------- |+| `-t, --title <title>` | Document title | Yes |+| `-c, --content <text>` | Document content | No |+| `--parent <parentId>` | Parent folder ID | No |++### `lh kb move <id>`++```bash+lh kb move < id > --type < file | doc > [--parent < folderId > ]+```++Move a file or document to a different folder (or to root if `--parent` is omitted).++| Option | Description | Default |+| --------------------- | -------------------------------- | ------- |+| `--type <type>` | Item type: `file` or `doc` | `file` |+| `--parent <parentId>` | Target folder ID (omit for root) | - |++Uses `document.updateDocument` for docs, `file.updateFile` for files.++### `lh kb upload <knowledgeBaseId> <filePath>`++```bash+lh kb upload <kbId> <filePath> [--parent <folderId>]+```++Upload a local file to a knowledge base via S3 presigned URL.++| Option | Description |+| --------------------- | ---------------- |+| `--parent <parentId>` | Parent folder ID |++**Flow**: Compute SHA-256 hash β get presigned URL via `upload.createS3PreSignedUrl` β PUT to S3 β create file record via `file.createFile`.+---## File Management (`lh file`)@@ -123,13 +187,14 @@ Manage text documents (notes, wiki pages).### `lh doc list````bash-lh doc list [-L [--file-type [--json [fields]] < n > ] < type > ]+lh doc list [-L [--file-type [--source-type [--json [fields]] < n > ] < type > ] < type > ]```-| Option | Description | Default |-| -------------------- | ------------------- | ------- |-| `-L, --limit <n>` | Maximum items | `30` |-| `--file-type <type>` | Filter by file type | - |+| Option | Description | Default |+| ---------------------- | --------------------------------------------- | ------- |+| `-L, --limit <n>` | Maximum items | `30` |+| `--file-type <type>` | Filter by file type | - |+| `--source-type <type>` | Filter by source type (file, web, api, topic) | - |**Table columns**: ID, TITLE, TYPE, UPDATED@@ -139,28 +204,40 @@ lh doc list [-L [--file-type [--json [fields]] < n > ] < type > ]lh doc view [fields]] < id > [--json```-**Displays**: Title, type, updated time, full content.+**Displays**: Title, type, KB association, updated time, full content.### `lh doc create````bash-lh doc create -t [-F [--parent [--slug < title > [-b < body > ] < path > ] < id > ] < slug > ]+lh doc create -t [-F [--parent [--slug [--kb [--file-type < title > [-b < body > ] < path > ] < id > ] < slug > ] < id > ] < type > ]```-| Option | Description | Required |-| ------------------------ | ------------------- | -------- |-| `-t, --title <title>` | Document title | Yes |-| `-b, --body <content>` | Document body text | No |-| `-F, --body-file <path>` | Read body from file | No |-| `--parent <id>` | Parent document ID | No |-| `--slug <slug>` | Custom URL slug | No |+| Option | Description | Required |+| ------------------------ | ----------------------------------------------- | -------- |+| `-t, --title <title>` | Document title | Yes |+| `-b, --body <content>` | Document body text | No |+| `-F, --body-file <path>` | Read body from file | No |+| `--parent <id>` | Parent document ID | No |+| `--slug <slug>` | Custom URL slug | No |+| `--kb <id>` | Knowledge base ID to associate with | No |+| `--file-type <type>` | File type (e.g. custom/document, custom/folder) | No |`-b` and `-F` are mutually exclusive; `-F` reads the file content as the body.+### `lh doc batch-create <file>`++Batch create documents from a JSON file. The file must contain a non-empty array of document objects.++```bash+lh doc batch-create documents.json+```++Each object in the array can have: `title`, `content`, `fileType`, `knowledgeBaseId`, `parentId`, `slug`.+### `lh doc edit <id>````bash-lh doc edit [-b [-F [--parent < id > [-t < title > ] < body > ] < path > ] < id > ]+lh doc edit [-b [-F [--parent [--file-type < id > [-t < title > ] < body > ] < path > ] < id > ] < type > ]```### `lh doc delete <ids...>`@@ -168,3 +245,37 @@ lh doc edit [-b [-F [--parent < id > [-t < title > ] < body > ] < path > ] < id```bashlh doc delete [--yes] < id1 > [id2...]```++### `lh doc parse <fileId>`++Parse an uploaded file into a document.++```bash+lh doc parse [--json [fields]] < fileId > [--with-pages]+```++| Option | Description |+| -------------- | ----------------------- |+| `--with-pages` | Preserve page structure |++**Output**: Parsed title and content preview.++### `lh doc link-topic <docId> <topicId>`++Associate a document with a topic. Creates a linked copy via the notebook router.++```bash+lh doc link-topic <docId> <topicId>+```++### `lh doc topic-docs <topicId>`++List documents associated with a topic.++```bash+lh doc topic-docs [--json [fields]] < topicId > [--type < type > ]+```++| Option | Description |+| --------------- | ------------------------------------------------ |+| `--type <type>` | Filter by type (article, markdown, note, report) |diff --git a/.agents/skills/cli/references/models-providers.md b/.agents/skills/cli/references/models-providers.mdindex 80ed303be9f..2fb187ee000 100644--- a/.agents/skills/cli/references/models-providers.md+++ b/.agents/skills/cli/references/models-providers.md@@ -11,16 +11,22 @@ Manage AI models within providers.List models for a specific provider.```bash-lh model list openai [-L [--enabled] [--json [fields]] < n > ]+lh model list openai+lh model list openai --type image --enabled+lh model list lobehub --type video --json```-| Option | Description | Default |-| ----------------- | ------------------------ | ------- |-| `-L, --limit <n>` | Maximum items | `50` |-| `--enabled` | Only show enabled models | `false` |+| Option | Description | Default |+| ----------------- | -------------------------------------------------------------------------------------- | ------- |+| `-L, --limit <n>` | Maximum items | `50` |+| `--enabled` | Only show enabled models | `false` |+| `--type <type>` | Filter by model type (`chat\|embedding\|tts\|stt\|image\|video\|text2music\|realtime`) | - |+| `--json [fields]` | Output JSON, optionally specify fields | - |**Table columns**: ID, NAME, ENABLED, TYPE+**Backend**: `aiModel.getAiProviderModelList` β `AiInfraRepos.getAiProviderModelList` (supports `type` filter at repository level)+### `lh model view <id>````bash@@ -29,6 +35,25 @@ lh model view [fields]] < modelId > [--json**Displays**: Name, provider, type, enabled status, capabilities.+### `lh model create`++```bash+lh model create --id [--type < id > --provider < providerId > [--display-name < name > ] < type > ]+```++| Option | Description | Default |+| ------------------------- | ------------ | -------- |+| `--id <id>` | Model ID | Required |+| `--provider <providerId>` | Provider ID | Required |+| `--display-name <name>` | Display name | - |+| `--type <type>` | Model type | `chat` |++### `lh model edit <id>`++```bash+lh model edit [--type < modelId > --provider < providerId > [--display-name < name > ] < type > ]+```+### `lh model toggle <id>`Enable or disable a model.@@ -44,16 +69,27 @@ lh model toggle < modelId > --provider < providerId > --disable| `--enable` | Enable the model | One required || `--disable` | Disable the model | One required |+### `lh model batch-toggle <ids...>`++Enable or disable multiple models at once.++```bash+lh model batch-toggle model1 model2 model3 --provider openai --enable+```+### `lh model delete <id>````bashlh model delete < modelId > --provider < providerId > [--yes]```-| Option | Description | Required |-| ------------------------- | ----------------- | -------- |-| `--provider <providerId>` | Provider ID | Yes |-| `--yes` | Skip confirmation | No |+### `lh model clear`++Clear all models (or only remote/fetched models) for a provider.++```bash+lh model clear --provider [--yes] < providerId > [--remote]+```---@@ -79,6 +115,63 @@ lh provider view [fields]] < providerId > [--json**Displays**: Name, enabled status, source, configuration.+### `lh provider create`++```bash+lh provider create --id [-d [--logo [--sdk-type < id > -n < name > [-s < source > ] < desc > ] < url > ] < type > ]+```++| Option | Description | Default |+| -------------------------- | ------------------------------------------------- | -------- |+| `--id <id>` | Provider ID | Required |+| `-n, --name <name>` | Provider name | Required |+| `-s, --source <source>` | Source type (`builtin` or `custom`) | `custom` |+| `-d, --description <desc>` | Provider description | - |+| `--logo <logo>` | Provider logo URL | - |+| `--sdk-type <sdkType>` | SDK type (openai, anthropic, azure, bedrock, ...) | - |++### `lh provider edit <id>`++```bash+lh provider edit [-d [--logo [--sdk-type < providerId > [-n < name > ] < desc > ] < url > ] < type > ]+```++Requires at least one change flag.++### `lh provider config <id>`++Configure provider settings (API key, base URL, etc.).++```bash+lh provider config openai --api-key sk-xxx+lh provider config openai --base-url https://custom-endpoint.com+lh provider config openai --show+lh provider config openai --show --json+```++| Option | Description |+| ------------------------ | --------------------------------- |+| `--api-key <key>` | Set API key |+| `--base-url <url>` | Set base URL |+| `--check-model <model>` | Set connectivity check model |+| `--enable-response-api` | Enable Response API mode (OpenAI) |+| `--disable-response-api` | Disable Response API mode |+| `--fetch-on-client` | Enable fetching models on client |+| `--no-fetch-on-client` | Disable fetching models on client |+| `--show` | Show current config |+| `--json [fields]` | Output JSON (with --show) |++**Important**: The `lobehub` provider is platform-managed. Attempting to set `--api-key` or `--base-url` on it will be rejected with an error message.++### `lh provider test <id>`++Test provider connectivity.++```bash+lh provider test openai+lh provider test openai -m gpt-4o --json+```+### `lh provider toggle <id>````bashdiff --git a/.agents/skills/cli/references/skills-plugins.md b/.agents/skills/cli/references/skills-plugins.mdindex fcbafbd1877..f64f390be13 100644--- a/.agents/skills/cli/references/skills-plugins.md+++ b/.agents/skills/cli/references/skills-plugins.md@@ -57,36 +57,33 @@ lh skill delete < id > [--yes]lh skill search [fields]] < query > [--json```-### Import Commands+### `lh skill install <source>` (alias: `lh skill i`)-#### `lh skill import-github`--Import a skill from a GitHub repository.+Install a skill. Auto-detects source type from the input:```bash-lh skill import-github --url < gitUrl > [--branch < branch > ]-```--| Option | Description | Required |-| ------------------- | ------------------ | ------------------- |-| `--url <gitUrl>` | Git repository URL | Yes |-| `--branch <branch>` | Branch name | No (default branch) |--#### `lh skill import-url`+# GitHub (URL or owner/repo shorthand)+lh skill install lobehub/skill-repo+lh skill install https://github.com/lobehub/skill-repo+lh skill install lobehub/skill-repo --branch dev-Import a skill from a ZIP file URL.+# ZIP URL+lh skill install https://example.com/skill.zip-```bash-lh skill import-url --url <zipUrl>+# Marketplace identifier+lh skill install my-cool-skill+lh skill i my-cool-skill```-#### `lh skill import-market`+| Option | Description | Notes |+| ------------------- | ------------------------- | -------- |+| `--branch <branch>` | Branch name (GitHub only) | Optional |-Import a skill from the LobeHub skill marketplace.+**Detection rules**:-```bash-lh skill import-market -i <identifier>-```+- `https://github.com/...` or `owner/repo` β GitHub+- Other `https://...` URLs β ZIP URL+- Everything else β marketplace identifier### Resource Commandsdiff --git a/apps/cli/e2e/agent.e2e.test.ts b/apps/cli/e2e/agent.e2e.test.tsnew file mode 100644index 00000000000..7bf7cc1a743--- /dev/null+++ b/apps/cli/e2e/agent.e2e.test.ts@@ -0,0 +1,135 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh agent` agent management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ *+ * These tests create a real agent, verify CRUD operations, then clean up.+ * Note: `agent run` and `agent status` are not tested here as they require+ * active SSE connections and running agents.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh agent - E2E', () => {+ const testTitle = `E2E-Agent-${Date.now()}`;+ const testDescription = 'Created by E2E test';+ let createdId: string;++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list agents in table format', () => {+ const output = run('agent list');+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('agent list --json id,title');+ expect(Array.isArray(list)).toBe(true);+ });++ it('should respect limit option', () => {+ const list = runJson<any[]>('agent list --json id -L 3');+ expect(list.length).toBeLessThanOrEqual(3);+ });+ });++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create an agent', () => {+ const output = run(`agent create -t "${testTitle}" -d "${testDescription}"`);+ expect(output).toContain('Created agent');++ const match = output.match(/Created agent\s+(\S+)/);+ expect(match).not.toBeNull();+ createdId = match![1];+ });+ });++ // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('view', () => {+ it('should view agent details', () => {+ const output = run(`agent view ${createdId}`);+ expect(output).toContain(testTitle);+ });++ it('should output JSON', () => {+ const result = runJson<{ title: string }>(`agent view ${createdId} --json title,description`);+ expect(result.title).toBe(testTitle);+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedTitle = `${testTitle}-Updated`;++ it('should update agent title', () => {+ const output = run(`agent edit ${createdId} -t "${updatedTitle}"`);+ expect(output).toContain('Updated agent');+ });++ it('should reflect updates when viewed', () => {+ const result = runJson<{ title: string }>(`agent view ${createdId} --json title`);+ expect(result.title).toBe(updatedTitle);+ });++ it('should error when no changes specified', () => {+ expect(() => run(`agent edit ${createdId}`)).toThrow();+ });+ });++ // ββ duplicate βββββββββββββββββββββββββββββββββββββββββ++ describe('duplicate', () => {+ let duplicatedId: string;++ it('should duplicate an agent', () => {+ const output = run(`agent duplicate ${createdId}`);+ expect(output).toContain('Duplicated agent');++ const match = output.match(/β\s+(\S+)/);+ if (match) duplicatedId = match[1];+ });++ it('should clean up duplicate', () => {+ if (duplicatedId) {+ const output = run(`agent delete ${duplicatedId} --yes`);+ expect(output).toContain('Deleted agent');+ }+ });+ });++ // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the agent', () => {+ const output = run(`agent delete ${createdId} --yes`);+ expect(output).toContain('Deleted agent');+ expect(output).toContain(createdId);+ });+ });+});diff --git a/apps/cli/e2e/doc.e2e.test.ts b/apps/cli/e2e/doc.e2e.test.tsnew file mode 100644index 00000000000..4f19005a0d0--- /dev/null+++ b/apps/cli/e2e/doc.e2e.test.ts@@ -0,0 +1,286 @@+import { execSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh doc` document management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ *+ * These tests create real documents, verify CRUD operations, then clean up.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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 extractDocId(output: string): string {+ const idMatch = output.match(/(docs_\w+)/);+ expect(idMatch).not.toBeNull();+ return idMatch![1];+}++describe('lh doc - E2E', () => {+ const testTitle = `E2E-Doc-${Date.now()}`;+ const testBody = 'Created by E2E test';+ let createdId: string;++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create a document with title and body', () => {+ const output = run(`doc create -t "${testTitle}" -b "${testBody}"`);+ expect(output).toContain('Created document');+ createdId = extractDocId(output);+ });++ it('should appear in the list', () => {+ const list = runJson<{ id: string; title: string }[]>('doc list --json id,title');+ const found = list.find((d) => d.id === createdId);+ expect(found).toBeDefined();+ expect(found!.title).toBe(testTitle);+ });+ });++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list documents in table format', () => {+ const output = run('doc list');+ expect(output).toContain('ID');+ expect(output).toContain('TITLE');+ });++ it('should output JSON with field filtering', () => {+ const list = runJson<{ id: string; title: string }[]>('doc list --json id,title');+ expect(Array.isArray(list)).toBe(true);+ expect(list.length).toBeGreaterThan(0);+ const first = list[0];+ expect(first).toHaveProperty('id');+ expect(first).toHaveProperty('title');+ expect(first).not.toHaveProperty('content');+ });++ it('should respect --limit flag', () => {+ const list = runJson<any[]>('doc list --json id -L 1');+ expect(list.length).toBeLessThanOrEqual(1);+ });++ it('should filter by --file-type', () => {+ const output = run('doc list --file-type custom/document --json id');+ const list = JSON.parse(output);+ expect(Array.isArray(list)).toBe(true);+ });++ it('should filter by --source-type', () => {+ const output = run('doc list --source-type api --json id');+ const list = JSON.parse(output);+ expect(Array.isArray(list)).toBe(true);+ });+ });++ // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('view', () => {+ it('should view document details', () => {+ const output = run(`doc view ${createdId}`);+ expect(output).toContain(testTitle);+ });++ it('should output JSON with --json flag', () => {+ const result = runJson<{ id: string; title: string }>(+ `doc view ${createdId} --json id,title`,+ );+ expect(result.id).toBe(createdId);+ expect(result.title).toBe(testTitle);+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedTitle = `${testTitle}-Updated`;+ const updatedBody = 'Updated by E2E test';++ it('should update document title', () => {+ const output = run(`doc edit ${createdId} -t "${updatedTitle}"`);+ expect(output).toContain('Updated document');+ expect(output).toContain(createdId);+ });++ it('should reflect title update when viewed', () => {+ const result = runJson<{ title: string }>(`doc view ${createdId} --json title`);+ expect(result.title).toBe(updatedTitle);+ });++ it('should update document body', () => {+ const output = run(`doc edit ${createdId} -b "${updatedBody}"`);+ expect(output).toContain('Updated document');+ });++ it('should reflect body update when viewed', () => {+ const result = runJson<{ content: string }>(`doc view ${createdId} --json content`);+ expect(result.content).toBe(updatedBody);+ });++ it('should update body from file with --body-file', () => {+ const tmpFile = path.join(os.tmpdir(), `e2e-doc-body-${Date.now()}.md`);+ fs.writeFileSync(tmpFile, '# File Content\nFrom body-file flag');++ try {+ const output = run(`doc edit ${createdId} -F "${tmpFile}"`);+ expect(output).toContain('Updated document');++ const result = runJson<{ content: string }>(`doc view ${createdId} --json content`);+ expect(result.content).toContain('File Content');+ } finally {+ fs.unlinkSync(tmpFile);+ }+ });++ it('should update file type with --file-type', () => {+ const output = run(`doc edit ${createdId} --file-type custom/document`);+ expect(output).toContain('Updated document');++ const result = runJson<{ fileType: string }>(`doc view ${createdId} --json fileType`);+ expect(result.fileType).toBe('custom/document');+ });++ it('should error when no changes specified', () => {+ expect(() => run(`doc edit ${createdId}`)).toThrow();+ });+ });++ // ββ create with options ββββββββββββββββββββββββββββββββ++ describe('create with options', () => {+ let childDocId: string;++ it('should create a document with --slug', () => {+ const slug = `e2e-slug-${Date.now()}`;+ const output = run(`doc create -t "E2E-Slug-Doc" --slug "${slug}"`);+ expect(output).toContain('Created document');+ childDocId = extractDocId(output);+ });++ it('should create a document with --file-type', () => {+ const output = run(`doc create -t "E2E-Typed-Doc" --file-type custom/document`);+ expect(output).toContain('Created document');+ const id = extractDocId(output);++ const result = runJson<{ fileType: string }>(`doc view ${id} --json fileType`);+ expect(result.fileType).toBe('custom/document');++ run(`doc delete ${id} --yes`);+ });++ it('should create a document from file with --body-file', () => {+ const tmpFile = path.join(os.tmpdir(), `e2e-doc-create-${Date.now()}.md`);+ fs.writeFileSync(tmpFile, '# Created from file\nTest content');++ try {+ const output = run(`doc create -t "E2E-FromFile" -F "${tmpFile}"`);+ expect(output).toContain('Created document');+ const id = extractDocId(output);+ run(`doc delete ${id} --yes`);+ } finally {+ fs.unlinkSync(tmpFile);+ }+ });++ // Clean up the slug doc+ it('should clean up slug doc', () => {+ if (childDocId) {+ const output = run(`doc delete ${childDocId} --yes`);+ expect(output).toContain('Deleted');+ }+ });+ });++ // ββ batch-create ββββββββββββββββββββββββββββββββββββββ++ describe('batch-create', () => {+ let batchDocIds: string[] = [];++ it('should batch create documents from JSON file', () => {+ const tmpFile = path.join(os.tmpdir(), `e2e-batch-${Date.now()}.json`);+ const docs = [+ { title: `E2E-Batch-1-${Date.now()}`, content: 'batch content 1' },+ { title: `E2E-Batch-2-${Date.now()}`, content: 'batch content 2' },+ ];+ fs.writeFileSync(tmpFile, JSON.stringify(docs));++ 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);+ } finally {+ fs.unlinkSync(tmpFile);+ }+ });++ it('should clean up batch created docs', () => {+ if (batchDocIds.length > 0) {+ const output = run(`doc delete ${batchDocIds.join(' ')} --yes`);+ expect(output).toContain('Deleted');+ }+ });+ });++ // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the document', () => {+ const output = run(`doc delete ${createdId} --yes`);+ expect(output).toContain('Deleted');+ });++ it('should no longer appear in the list', () => {+ const list = runJson<{ id: string }[]>('doc list --json id');+ const found = list.find((d) => d.id === createdId);+ expect(found).toBeUndefined();+ });+ });++ // ββ delete multiple βββββββββββββββββββββββββββββββββββ++ describe('delete multiple', () => {+ let docId1: string;+ let docId2: string;++ it('should create two documents for batch delete', () => {+ const output1 = run(`doc create -t "E2E-BatchDel-1" -b "batch test 1"`);+ docId1 = extractDocId(output1);++ const output2 = run(`doc create -t "E2E-BatchDel-2" -b "batch test 2"`);+ docId2 = extractDocId(output2);+ });++ it('should delete multiple documents at once', () => {+ const output = run(`doc delete ${docId1} ${docId2} --yes`);+ expect(output).toContain('Deleted 2');+ });+ });+});diff --git a/apps/cli/e2e/file.e2e.test.ts b/apps/cli/e2e/file.e2e.test.tsnew file mode 100644index 00000000000..92b2b51aae6--- /dev/null+++ b/apps/cli/e2e/file.e2e.test.ts@@ -0,0 +1,93 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh file` file management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh file - E2E', () => {+ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list files in table format', () => {+ const output = run('file list');+ // Either table or "No files found."+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('file list --json id,name');+ expect(Array.isArray(list)).toBe(true);+ if (list.length > 0) {+ expect(list[0]).toHaveProperty('id');+ expect(list[0]).toHaveProperty('name');+ }+ });++ it('should accept limit option', () => {+ // Backend may not strictly enforce limit; verify it doesn't error+ const list = runJson<any[]>('file list --json id -L 5');+ expect(Array.isArray(list)).toBe(true);+ });+ });++ // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('view', () => {+ it('should show file details if files exist', () => {+ const list = runJson<{ id: string }[]>('file list --json id -L 1');+ if (list.length > 0) {+ const output = run(`file view ${list[0].id}`);+ expect(output).toBeTruthy();+ }+ });++ it('should output JSON for file detail', () => {+ const list = runJson<{ id: string }[]>('file list --json id -L 1');+ if (list.length > 0) {+ const result = runJson(`file view ${list[0].id} --json id,name`);+ expect(result).toHaveProperty('id');+ }+ });++ it('should error for nonexistent file', () => {+ expect(() => run('file view nonexistent-file-xyz')).toThrow();+ });+ });++ // ββ recent ββββββββββββββββββββββββββββββββββββββββββββ++ describe('recent', () => {+ it('should list recent files', () => {+ const output = run('file recent');+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('file recent --json id,name');+ expect(Array.isArray(list)).toBe(true);+ });+ });+});diff --git a/apps/cli/e2e/generate.e2e.test.ts b/apps/cli/e2e/generate.e2e.test.tsnew file mode 100644index 00000000000..08a206ee891--- /dev/null+++ b/apps/cli/e2e/generate.e2e.test.ts@@ -0,0 +1,119 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh generate` (alias `lh gen`) content generation commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh generate - E2E', () => {+ // ββ text ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('text', () => {+ it('should generate text (non-streaming, default model)', () => {+ const output = run('gen text "Reply with just the word OK"');+ expect(output).toBeTruthy();+ expect(output.length).toBeGreaterThan(0);+ }, 60_000);++ it('should generate text with --json flag', () => {+ const output = run('gen text "Reply with just the word OK" --json');+ const parsed = JSON.parse(output);+ // OpenAI format+ expect(parsed).toHaveProperty('model');+ expect(parsed.choices?.[0]?.message?.content || parsed.content?.[0]?.text).toBeTruthy();+ }, 60_000);++ it('should generate text with system prompt', () => {+ const output = run('gen text "Say hello" -s "You must reply in French only"');+ expect(output).toBeTruthy();+ }, 60_000);++ it('should generate text with --stream flag', () => {+ const output = run('gen text "Reply with just the word OK" --stream');+ expect(output).toBeTruthy();+ }, 60_000);++ it('should generate text with custom model', () => {+ const output = run('gen text "Reply with just OK" -m "openai/gpt-4o-mini"');+ expect(output).toBeTruthy();+ }, 60_000);++ it('should generate text with temperature option', () => {+ const output = run('gen text "Reply with just the number 42" --temperature 0');+ expect(output).toContain('42');+ }, 60_000);+ });++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list generation topics in table format', () => {+ const output = run('gen list');+ // May have topics or show empty message+ expect(output).toBeTruthy();+ });++ it('should list generation topics with --json', () => {+ const output = run('gen list --json');+ const parsed = JSON.parse(output);+ expect(Array.isArray(parsed)).toBe(true);+ });++ it('should filter JSON fields', () => {+ const items = runJson<any[]>('gen list --json id,type');+ if (items.length > 0) {+ expect(items[0]).toHaveProperty('id');+ expect(items[0]).toHaveProperty('type');+ expect(items[0]).not.toHaveProperty('title');+ }+ });+ });++ // ββ tts βββββββββββββββββββββββββββββββββββββββββββββββ++ describe('tts', () => {+ it('should reject invalid backend', () => {+ expect(() => run('gen tts "hello" --backend invalid')).toThrow();+ });+ });++ // ββ asr βββββββββββββββββββββββββββββββββββββββββββββββ++ describe('asr', () => {+ it('should reject non-existent audio file', () => {+ expect(() => run('gen asr /tmp/nonexistent-audio.mp3')).toThrow();+ });+ });++ // ββ alias βββββββββββββββββββββββββββββββββββββββββββββ++ describe('alias', () => {+ it('should work with "generate" (full name) as well as "gen"', () => {+ const output = run('generate list --json');+ const parsed = JSON.parse(output);+ expect(Array.isArray(parsed)).toBe(true);+ });+ });+});diff --git a/apps/cli/e2e/kb.e2e.test.ts b/apps/cli/e2e/kb.e2e.test.tsnew file mode 100644index 00000000000..f48bb88220c--- /dev/null+++ b/apps/cli/e2e/kb.e2e.test.ts@@ -0,0 +1,252 @@+import { execSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh kb` knowledge base management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ *+ * These tests create a real knowledge base, verify CRUD operations, then clean up.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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 extractId(output: string, prefix: string): string {+ const re = new RegExp(`${prefix}\\w+`);+ const match = output.match(re);+ expect(match).not.toBeNull();+ return match![0];+}++describe('lh kb - E2E', () => {+ const testName = `E2E-Test-${Date.now()}`;+ const testDescription = 'Created by E2E test';+ let createdId: string;++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create a knowledge base and return its id', () => {+ const output = run(`kb create -n "${testName}" -d "${testDescription}"`);+ expect(output).toContain('Created knowledge base');+ createdId = extractId(output, 'kb_');+ });++ it('should appear in the list', () => {+ const list = runJson<{ id: string; name: string }[]>('kb list --json id,name');+ const found = list.find((kb) => kb.id === createdId);+ expect(found).toBeDefined();+ expect(found!.name).toBe(testName);+ });+ });++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list knowledge bases in table format', () => {+ const output = run('kb list');+ expect(output).toContain('ID');+ expect(output).toContain('NAME');+ });++ it('should output JSON with field filtering', () => {+ const list = runJson<{ id: string; name: string }[]>('kb list --json id,name');+ expect(Array.isArray(list)).toBe(true);+ expect(list.length).toBeGreaterThan(0);+ const first = list[0];+ expect(first).toHaveProperty('id');+ expect(first).toHaveProperty('name');+ expect(first).not.toHaveProperty('description');+ });+ });++ // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('view', () => {+ it('should view knowledge base details', () => {+ const output = run(`kb view ${createdId}`);+ expect(output).toContain(testName);+ expect(output).toContain(testDescription);+ });++ it('should output JSON with --json flag', () => {+ const result = runJson<{ description: string; id: string; name: string }>(+ `kb view ${createdId} --json id,name,description`,+ );+ expect(result.id).toBe(createdId);+ expect(result.name).toBe(testName);+ expect(result.description).toBe(testDescription);+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedName = `${testName}-Updated`;+ const updatedDesc = 'Updated by E2E test';++ it('should update knowledge base name and description', () => {+ const output = run(`kb edit ${createdId} -n "${updatedName}" -d "${updatedDesc}"`);+ expect(output).toContain('Updated knowledge base');+ expect(output).toContain(createdId);+ });++ it('should reflect updates when viewed', () => {+ const result = runJson<{ description: string; name: string }>(+ `kb view ${createdId} --json name,description`,+ );+ expect(result.name).toBe(updatedName);+ expect(result.description).toBe(updatedDesc);+ });++ it('should error when no changes specified', () => {+ expect(() => run(`kb edit ${createdId}`)).toThrow();+ });+ });++ // ββ mkdir βββββββββββββββββββββββββββββββββββββββββββββ++ describe('mkdir', () => {+ let folderId: string;++ it('should create a folder in the knowledge base', () => {+ const output = run(`kb mkdir ${createdId} -n "E2E-Folder"`);+ expect(output).toContain('Created folder');+ folderId = extractId(output, 'docs_');+ });++ it('should appear in kb view', () => {+ const output = run(`kb view ${createdId}`);+ expect(output).toContain('E2E-Folder');+ expect(output).toContain('folder');+ });++ it('should create a nested folder', () => {+ const output = run(`kb mkdir ${createdId} -n "E2E-SubFolder" --parent ${folderId}`);+ expect(output).toContain('Created folder');+ });+ });++ // ββ create-doc ββββββββββββββββββββββββββββββββββββββββ++ describe('create-doc', () => {+ let docId: string;+ let folderId: string;++ it('should create a document at root', () => {+ const output = run(`kb create-doc ${createdId} -t "E2E-Doc" -c "test content"`);+ expect(output).toContain('Created document');+ docId = extractId(output, 'docs_');+ });++ it('should create a document inside a folder', () => {+ // First get the folder id+ const viewOutput = run(`kb view ${createdId}`);+ // eslint-disable-next-line regexp/no-super-linear-backtracking,regexp/optimal-quantifier-concatenation+ const folderMatch = viewOutput.match(/(docs_\w+).*E2E-Folder/);+ expect(folderMatch).not.toBeNull();+ folderId = folderMatch![1];++ const output = run(`kb create-doc ${createdId} -t "E2E-NestedDoc" --parent ${folderId}`);+ expect(output).toContain('Created document');+ });++ it('should show documents in kb view', () => {+ const output = run(`kb view ${createdId}`);+ expect(output).toContain('E2E-Doc');+ expect(output).toContain('E2E-NestedDoc');+ });+ });++ // ββ move ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('move', () => {+ let docId: string;+ let folderId: string;++ it('should move a document into a folder', () => {+ // Get doc and folder IDs from view+ const result = runJson<{ files: { fileType: string; id: string; name: string }[] }>(+ `kb view ${createdId} --json files`,+ );+ const doc = result.files.find((f) => f.name === 'E2E-Doc');+ const folder = result.files.find(+ (f) => f.fileType === 'custom/folder' && f.name === 'E2E-Folder',+ );+ expect(doc).toBeDefined();+ expect(folder).toBeDefined();+ docId = doc!.id;+ folderId = folder!.id;++ const output = run(`kb move ${docId} --type doc --parent ${folderId}`);+ expect(output).toContain('Moved');+ expect(output).toContain(folderId);+ });++ it('should move a document back to root', () => {+ const output = run(`kb move ${docId} --type doc`);+ expect(output).toContain('Moved');+ expect(output).toContain('root');+ });+ });++ // ββ upload ββββββββββββββββββββββββββββββββββββββββββββ++ describe('upload', () => {+ let tmpFile: string;++ it('should upload a file to the knowledge base', () => {+ tmpFile = path.join(os.tmpdir(), `e2e-upload-${Date.now()}.txt`);+ fs.writeFileSync(tmpFile, 'E2E upload test content');++ const output = run(`kb upload ${createdId} ${tmpFile}`);+ expect(output).toContain('Uploaded');+ expect(output).toMatch(/file_\w+/);++ fs.unlinkSync(tmpFile);+ });++ it('should show uploaded file in kb view', () => {+ const output = run(`kb view ${createdId}`);+ expect(output).toContain('e2e-upload');+ expect(output).toContain('txt');+ });+ });++ // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the knowledge base', () => {+ const output = run(`kb delete ${createdId} --yes`);+ expect(output).toContain('Deleted knowledge base');+ expect(output).toContain(createdId);+ });++ it('should no longer appear in the list', () => {+ const list = runJson<{ id: string }[]>('kb list --json id');+ const found = list.find((kb) => kb.id === createdId);+ expect(found).toBeUndefined();+ });+ });+});diff --git a/apps/cli/e2e/memory.e2e.test.ts b/apps/cli/e2e/memory.e2e.test.tsnew file mode 100644index 00000000000..cd6c47ef0a2--- /dev/null+++ b/apps/cli/e2e/memory.e2e.test.ts@@ -0,0 +1,177 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh memory` user memory management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ *+ * These tests create real identity memories, verify CRUD operations, then clean up.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 60_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++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 },+);diff --git a/apps/cli/e2e/message.e2e.test.ts b/apps/cli/e2e/message.e2e.test.tsnew file mode 100644index 00000000000..6b94ad874dd--- /dev/null+++ b/apps/cli/e2e/message.e2e.test.ts@@ -0,0 +1,98 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh message` message management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh message - E2E', () => {+ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list messages in table format', () => {+ const output = run('message list');+ // Either shows table or "No messages found."+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('message list --json id,role');+ expect(Array.isArray(list)).toBe(true);+ if (list.length > 0) {+ expect(list[0]).toHaveProperty('id');+ expect(list[0]).toHaveProperty('role');+ }+ });++ it('should respect limit option', () => {+ const list = runJson<any[]>('message list --json id -L 5');+ expect(list.length).toBeLessThanOrEqual(5);+ });+ });++ // ββ search ββββββββββββββββββββββββββββββββββββββββββββ++ describe('search', () => {+ it('should search messages', () => {+ const output = run('message search "hello"');+ expect(typeof output).toBe('string');+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('message search "hello" --json id,role');+ expect(Array.isArray(list)).toBe(true);+ });+ });++ // ββ count βββββββββββββββββββββββββββββββββββββββββββββ++ describe('count', () => {+ it('should show message count', () => {+ const output = run('message count');+ expect(output).toContain('Messages:');+ });++ it('should output JSON', () => {+ const output = run('message count --json');+ const parsed = JSON.parse(output);+ expect(parsed).toHaveProperty('count');+ expect(typeof parsed.count).toBe('number');+ });+ });++ // ββ heatmap βββββββββββββββββββββββββββββββββββββββββββ++ describe('heatmap', () => {+ it('should show heatmap data', () => {+ const output = run('message heatmap');+ expect(output).toBeTruthy();+ });++ it('should accept --json flag without error', () => {+ // Heatmap JSON can be very large; just verify the command doesn't throw+ expect(() => run('message heatmap --json')).not.toThrow();+ });+ });+});diff --git a/apps/cli/e2e/model.e2e.test.ts b/apps/cli/e2e/model.e2e.test.tsnew file mode 100644index 00000000000..3f138f708c3--- /dev/null+++ b/apps/cli/e2e/model.e2e.test.ts@@ -0,0 +1,205 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh model` AI model management commands.+ *+ * Prerequisites:+ * - `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.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;+const TEST_PROVIDER = 'openai';++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh model - E2E', () => {+ const testModelId = `e2e-model-${Date.now()}`;+ const testDisplayName = 'E2E Test Model';++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list 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');+ });++ it('should filter enabled models', () => {+ const output = run(`model list ${TEST_PROVIDER} --enabled`);+ // Every row should have β+ expect(output).not.toContain('β');+ });++ 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');+ }+ });++ it('should respect limit option', () => {+ const list = runJson<any[]>(`model list ${TEST_PROVIDER} --json id -L 3`);+ expect(list.length).toBeLessThanOrEqual(3);+ });+ });++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create a new model', () => {+ const output = run(+ `model create --id ${testModelId} --provider ${TEST_PROVIDER} --display-name "${testDisplayName}" --type chat`,+ );+ expect(output).toContain('Created model');+ });++ 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();+ });+ });++ // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('view', () => {+ it('should view model details', () => {+ const output = run(`model view ${testModelId}`);+ expect(output).toContain(testDisplayName);+ expect(output).toContain(TEST_PROVIDER);+ expect(output).toContain('chat');+ });++ it('should output JSON', () => {+ const result = runJson<{+ displayName: string;+ id: string;+ providerId: string;+ type: string;+ }>(`model view ${testModelId} --json id,displayName,providerId,type`);+ expect(result.id).toBe(testModelId);+ expect(result.displayName).toBe(testDisplayName);+ expect(result.providerId).toBe(TEST_PROVIDER);+ expect(result.type).toBe('chat');+ });++ it('should error for nonexistent model', () => {+ expect(() => run('model view nonexistent-model-xyz')).toThrow();+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedName = `${testDisplayName}-Updated`;++ it('should update model display name', () => {+ const output = run(+ `model edit ${testModelId} --provider ${TEST_PROVIDER} --display-name "${updatedName}"`,+ );+ expect(output).toContain('Updated model');+ });++ it('should reflect updates when viewed', () => {+ const result = runJson<{ displayName: string }>(+ `model view ${testModelId} --json displayName`,+ );+ expect(result.displayName).toBe(updatedName);+ });++ it('should error when no changes specified', () => {+ expect(() => run(`model edit ${testModelId} --provider ${TEST_PROVIDER}`)).toThrow();+ });+ });++ // ββ toggle ββββββββββββββββββββββββββββββββββββββββββββ++ describe('toggle', () => {+ it('should disable model', () => {+ const output = run(`model toggle ${testModelId} --provider ${TEST_PROVIDER} --disable`);+ expect(output).toContain('disabled');+ });++ it('should reflect disabled status', () => {+ const result = runJson<{ enabled: boolean }>(`model view ${testModelId} --json enabled`);+ expect(result.enabled).toBe(false);+ });++ it('should enable model', () => {+ const output = run(`model toggle ${testModelId} --provider ${TEST_PROVIDER} --enable`);+ expect(output).toContain('enabled');+ });++ it('should error when no flag specified', () => {+ expect(() => run(`model toggle ${testModelId} --provider ${TEST_PROVIDER}`)).toThrow();+ });+ });++ // ββ batch-toggle ββββββββββββββββββββββββββββββββββββββ++ describe('batch-toggle', () => {+ it('should batch disable models', () => {+ const output = run(`model batch-toggle ${testModelId} --provider ${TEST_PROVIDER} --disable`);+ expect(output).toContain('Disabled');+ expect(output).toContain('1 model(s)');+ });++ it('should batch enable models', () => {+ const output = run(`model batch-toggle ${testModelId} --provider ${TEST_PROVIDER} --enable`);+ expect(output).toContain('Enabled');+ expect(output).toContain('1 model(s)');+ });+ });++ // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the model', () => {+ const output = run(`model delete ${testModelId} --provider ${TEST_PROVIDER} --yes`);+ expect(output).toContain('Deleted model');+ expect(output).toContain(testModelId);+ });++ it('should no longer be viewable', () => {+ expect(() => run(`model view ${testModelId}`)).toThrow();+ });+ });++ // ββ clear (test with caution) βββββββββββββββββββββββββ++ describe('clear', () => {+ it('should clear remote models for provider', () => {+ const output = run(`model clear --provider ${TEST_PROVIDER} --remote --yes`);+ expect(output).toContain('Cleared remote models');+ expect(output).toContain(TEST_PROVIDER);+ });+ });+});diff --git a/apps/cli/e2e/plugin.e2e.test.ts b/apps/cli/e2e/plugin.e2e.test.tsnew file mode 100644index 00000000000..1b2e2514766--- /dev/null+++ b/apps/cli/e2e/plugin.e2e.test.ts@@ -0,0 +1,73 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh plugin` plugin management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh plugin - E2E', () => {+ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list plugins or show empty message', () => {+ const output = run('plugin list');+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('plugin list --json');+ expect(Array.isArray(list)).toBe(true);+ });++ it('should output JSON with field filtering', () => {+ const list = runJson<any[]>('plugin list --json id,identifier');+ expect(Array.isArray(list)).toBe(true);+ if (list.length > 0) {+ expect(list[0]).toHaveProperty('id');+ expect(list[0]).toHaveProperty('identifier');+ }+ });+ });++ // ββ install / update / uninstall ββββββββββββββββββββββ+ // Note: Full CRUD requires a valid manifest JSON which is complex.+ // We test error handling for invalid inputs instead.++ describe('install', () => {+ it('should reject invalid manifest JSON', () => {+ expect(() => run('plugin install -i "test-plugin" --manifest "not-json"')).toThrow();+ });+ });++ describe('update', () => {+ it('should error when no changes specified', () => {+ expect(() => run('plugin update nonexistent-id')).toThrow();+ });++ it('should reject invalid settings JSON', () => {+ expect(() => run('plugin update some-id --settings "not-json"')).toThrow();+ });+ });+});diff --git a/apps/cli/e2e/provider.e2e.test.ts b/apps/cli/e2e/provider.e2e.test.tsnew file mode 100644index 00000000000..4198fb9f8fe--- /dev/null+++ b/apps/cli/e2e/provider.e2e.test.ts@@ -0,0 +1,220 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh provider` AI provider management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ *+ * These tests create a real provider, verify CRUD operations, then clean up.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh provider - E2E', () => {+ const testId = `e2e-test-${Date.now()}`;+ const testName = 'E2E Test Provider';++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list providers in table format', () => {+ const output = run('provider list');+ expect(output).toContain('ID');+ expect(output).toContain('NAME');+ expect(output).toContain('ENABLED');+ expect(output).toContain('SOURCE');+ });++ it('should output JSON with field filtering', () => {+ const list = runJson<{ id: string; name: string }[]>('provider list --json id,name');+ expect(Array.isArray(list)).toBe(true);+ expect(list.length).toBeGreaterThan(0);+ const first = list[0];+ expect(first).toHaveProperty('id');+ expect(first).toHaveProperty('name');+ expect(first).not.toHaveProperty('description');+ });+ });++ // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('view', () => {+ it('should view a builtin provider', () => {+ const output = run('provider view openai');+ // Should show name or id and status+ expect(output).toMatch(/Enabled|Disabled/);+ expect(output).toContain('builtin');+ });++ it('should output JSON for a provider', () => {+ const result = runJson<{ id: string; source: string }>(+ 'provider view openai --json id,source',+ );+ expect(result.id).toBe('openai');+ expect(result.source).toBe('builtin');+ });++ it('should error for nonexistent provider', () => {+ expect(() => run('provider view nonexistent-provider-xyz')).toThrow();+ });+ });++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create a new provider', () => {+ const output = run(+ `provider create --id ${testId} -n "${testName}" -d "E2E test" --sdk-type openai`,+ );+ expect(output).toContain('Created provider');+ expect(output).toContain(testId);+ });++ it('should appear in the list', () => {+ const list = runJson<{ id: string; name: string }[]>('provider list --json id,name');+ const found = list.find((p) => p.id === testId);+ expect(found).toBeDefined();+ expect(found!.name).toBe(testName);+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedName = `${testName}-Updated`;++ it('should update provider name', () => {+ const output = run(`provider edit ${testId} -n "${updatedName}"`);+ expect(output).toContain('Updated provider');+ expect(output).toContain(testId);+ });++ it('should reflect updates when viewed', () => {+ const result = runJson<{ name: string }>(`provider view ${testId} --json name`);+ expect(result.name).toBe(updatedName);+ });++ it('should error when no changes specified', () => {+ expect(() => run(`provider edit ${testId}`)).toThrow();+ });+ });++ // ββ config ββββββββββββββββββββββββββββββββββββββββββββ++ describe('config', () => {+ it('should set api key and base url', () => {+ const output = run(+ `provider config ${testId} --api-key sk-e2etest123456 --base-url https://api.e2e.test/v1`,+ );+ expect(output).toContain('Updated config');+ });++ it('should set check model', () => {+ const output = run(`provider config ${testId} --check-model gpt-4o`);+ expect(output).toContain('Updated config');+ });++ it('should enable response api', () => {+ const output = run(`provider config ${testId} --enable-response-api`);+ expect(output).toContain('Updated config');+ });++ it('should show current config', () => {+ const output = run(`provider config ${testId} --show`);+ expect(output).toContain('Config for');+ expect(output).toContain('gpt-4o');+ expect(output).toContain('sk-e2ete');+ expect(output).toContain('https://api.e2e.test/v1');+ });++ it('should show config as JSON', () => {+ const result = runJson<{+ checkModel: string;+ keyVaults: { apiKey: string; baseURL: string };+ }>(`provider config ${testId} --show --json`);+ expect(result.checkModel).toBe('gpt-4o');+ expect(result.keyVaults.apiKey).toContain('sk-e2etest');+ expect(result.keyVaults.baseURL).toBe('https://api.e2e.test/v1');+ });++ it('should error when no config specified', () => {+ expect(() => run(`provider config ${testId}`)).toThrow();+ });+ });++ // ββ toggle ββββββββββββββββββββββββββββββββββββββββββββ++ describe('toggle', () => {+ it('should disable provider', () => {+ const output = run(`provider toggle ${testId} --disable`);+ expect(output).toContain('disabled');+ });++ it('should reflect disabled status', () => {+ const result = runJson<{ enabled: boolean }>(`provider view ${testId} --json enabled`);+ expect(result.enabled).toBe(false);+ });++ it('should enable provider', () => {+ const output = run(`provider toggle ${testId} --enable`);+ expect(output).toContain('enabled');+ });++ it('should error when no flag specified', () => {+ expect(() => run(`provider toggle ${testId}`)).toThrow();+ });+ });++ // ββ test (connectivity) βββββββββββββββββββββββββββββββ++ describe('test', () => {+ it('should check provider connectivity (expect fail with fake key)', () => {+ // The e2e test provider has a fake API key, so test should fail+ expect(() => run(`provider test ${testId}`)).toThrow();+ });++ it('should output JSON on failure', () => {+ try {+ run(`provider test ${testId} --json`);+ } catch {+ // Command exits with code 1 but may still output JSON before that+ // This is expected behavior+ }+ });+ });++ // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the provider', () => {+ const output = run(`provider delete ${testId} --yes`);+ expect(output).toContain('Deleted provider');+ expect(output).toContain(testId);+ });++ it('should no longer appear in the list', () => {+ const list = runJson<{ id: string }[]>('provider list --json id');+ const found = list.find((p) => p.id === testId);+ expect(found).toBeUndefined();+ });+ });+});diff --git a/apps/cli/e2e/search.e2e.test.ts b/apps/cli/e2e/search.e2e.test.tsnew file mode 100644index 00000000000..ac5c83366ee--- /dev/null+++ b/apps/cli/e2e/search.e2e.test.ts@@ -0,0 +1,55 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh search` global search command.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh search - E2E', () => {+ it('should search across types', () => {+ const output = run('search "test"');+ // May show results or "No results found."+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const result = runJson('search "test" --json');+ expect(result).toBeTruthy();+ });++ it('should filter by type', () => {+ const output = run('search "test" --type agent');+ expect(output).toBeTruthy();+ });++ it('should respect limit option', () => {+ const result = runJson('search "test" --json -L 3');+ expect(result).toBeTruthy();+ });++ it('should error for invalid type', () => {+ expect(() => run('search "test" --type invalidtype')).toThrow();+ });+});diff --git a/apps/cli/e2e/skill.e2e.test.ts b/apps/cli/e2e/skill.e2e.test.tsnew file mode 100644index 00000000000..9639413eb21--- /dev/null+++ b/apps/cli/e2e/skill.e2e.test.ts@@ -0,0 +1,181 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh skill` agent skill management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ *+ * These tests create a real skill, verify CRUD operations, then clean up.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh skill - E2E', () => {+ const testName = `E2E-Skill-${Date.now()}`;+ const testDescription = 'Created by E2E test';+ const testContent = 'You are a helpful test skill.';+ const testIdentifier = `e2e-test-skill-${Date.now()}`;+ let createdId: string;++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create a skill and return its id', () => {+ const output = run(+ `skill create -n "${testName}" -d "${testDescription}" -c "${testContent}" -i "${testIdentifier}"`,+ );+ expect(output).toContain('Created skill');++ // Extract id from output like "β Created skill xxx"+ const match = output.match(/Created skill\s+(\S+)/);+ expect(match).not.toBeNull();+ createdId = match![1];+ });++ it('should be viewable after creation', () => {+ const result = runJson<{ id: string; name: string }>(+ `skill view ${createdId} --json id,name`,+ );+ expect(result.id).toBe(createdId);+ expect(result.name).toBe(testName);+ });+ });++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should return valid output (table or empty message)', () => {+ const output = run('skill list');+ // May return table or "No skills found." depending on backend state+ expect(output).toBeTruthy();+ });++ it('should output JSON array', () => {+ const list = runJson<any[]>('skill list --json id,name');+ expect(Array.isArray(list)).toBe(true);+ if (list.length > 0) {+ expect(list[0]).toHaveProperty('id');+ expect(list[0]).toHaveProperty('name');+ expect(list[0]).not.toHaveProperty('content');+ }+ });++ it('should filter by source', () => {+ const list = runJson<{ id: string; source: string }[]>(+ 'skill list --source user --json id,source',+ );+ expect(Array.isArray(list)).toBe(true);+ for (const item of list) {+ expect(item.source).toBe('user');+ }+ });+ });++ // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('view', () => {+ it('should view skill details', () => {+ const output = run(`skill view ${createdId}`);+ expect(output).toContain(testName);+ expect(output).toContain(testDescription);+ });++ it('should output JSON with --json flag', () => {+ const result = runJson<{+ description: string;+ id: string;+ name: string;+ }>(`skill view ${createdId} --json id,name,description`);+ expect(result.id).toBe(createdId);+ expect(result.name).toBe(testName);+ expect(result.description).toBe(testDescription);+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedName = `${testName}-Updated`;+ const updatedDesc = 'Updated by E2E test';+ const updatedContent = 'Updated content for test skill.';++ it('should update skill name and description', () => {+ const output = run(`skill edit ${createdId} -n "${updatedName}" -d "${updatedDesc}"`);+ expect(output).toContain('Updated skill');+ expect(output).toContain(createdId);+ });++ it('should reflect name/description updates when viewed', () => {+ const result = runJson<{ description: string; name: string }>(+ `skill view ${createdId} --json name,description`,+ );+ expect(result.name).toBe(updatedName);+ expect(result.description).toBe(updatedDesc);+ });++ it('should update skill content', () => {+ const output = run(`skill edit ${createdId} -c "${updatedContent}"`);+ expect(output).toContain('Updated skill');+ expect(output).toContain(createdId);+ });++ it('should reflect content update when viewed', () => {+ const result = runJson<{ content: string }>(`skill view ${createdId} --json content`);+ expect(result.content).toBe(updatedContent);+ });++ it('should error when no changes specified', () => {+ expect(() => run(`skill edit ${createdId}`)).toThrow();+ });+ });++ // ββ search ββββββββββββββββββββββββββββββββββββββββββββ++ describe('search', () => {+ it('should search skills in table format', () => {+ const output = run(`skill search "${testName}"`);+ // May or may not find results depending on indexing, but should not throw+ expect(typeof output).toBe('string');+ });++ it('should output JSON with --json flag', () => {+ const list = runJson<any[]>(`skill search "${testName}" --json id,name`);+ expect(Array.isArray(list)).toBe(true);+ });+ });++ // ββ delete ββββββββββββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the skill', () => {+ const output = run(`skill delete ${createdId} --yes`);+ expect(output).toContain('Deleted skill');+ expect(output).toContain(createdId);+ });++ it('should no longer appear in the list', () => {+ const list = runJson<{ id: string }[]>('skill list --source user --json id');+ const found = list.find((s) => s.id === createdId);+ expect(found).toBeUndefined();+ });+ });+});diff --git a/apps/cli/e2e/topic.e2e.test.ts b/apps/cli/e2e/topic.e2e.test.tsnew file mode 100644index 00000000000..bcc8eea4b10--- /dev/null+++ b/apps/cli/e2e/topic.e2e.test.ts@@ -0,0 +1,116 @@+import { execSync } from 'node:child_process';++import { describe, expect, it } from 'vitest';++/**+ * E2E tests for `lh topic` conversation topic management commands.+ *+ * Prerequisites:+ * - `lh` CLI is installed and linked globally+ * - User is authenticated (`lh login` completed)+ * - Network access to the LobeHub server+ *+ * These tests create a real topic, verify CRUD operations, then clean up.+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const TIMEOUT = 30_000;++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ 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;+}++describe('lh topic - E2E', () => {+ const testTitle = `E2E-Topic-${Date.now()}`;+ let createdId: string;++ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ describe('create', () => {+ it('should create a topic', () => {+ const output = run(`topic create -t "${testTitle}"`);+ expect(output).toContain('Created topic');++ const match = output.match(/Created topic\s+(\S+)/);+ expect(match).not.toBeNull();+ createdId = match![1];+ });+ });++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('list', () => {+ it('should list topics in table format', () => {+ const output = run('topic list');+ // Should show table headers or "No topics"+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('topic list --json id,title');+ expect(Array.isArray(list)).toBe(true);+ });+ });++ // ββ search ββββββββββββββββββββββββββββββββββββββββββββ++ describe('search', () => {+ it('should search topics', () => {+ const output = run(`topic search "${testTitle}"`);+ expect(typeof output).toBe('string');+ });++ it('should output JSON', () => {+ const list = runJson<any[]>(`topic search "${testTitle}" --json id,title`);+ expect(Array.isArray(list)).toBe(true);+ });+ });++ // ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ++ describe('edit', () => {+ const updatedTitle = `${testTitle}-Updated`;++ it('should update topic title', () => {+ const output = run(`topic edit ${createdId} -t "${updatedTitle}"`);+ expect(output).toContain('Updated topic');+ });++ it('should error when no changes specified', () => {+ expect(() => run(`topic edit ${createdId}`)).toThrow();+ });+ });++ // ββ recent ββββββββββββββββββββββββββββββββββββββββββββ++ describe('recent', () => {+ it('should list recent topics', () => {+ const output = run('topic recent');+ expect(output).toBeTruthy();+ });++ it('should output JSON', () => {+ const list = runJson<any[]>('topic recent --json id,title');+ expect(Array.isArray(list)).toBe(true);+ });+ });++ // ββ delete (cleanup) ββββββββββββββββββββββββββββββββββ++ describe('delete', () => {+ it('should delete the topic', () => {+ const output = run(`topic delete ${createdId} --yes`);+ expect(output).toContain('Deleted');+ expect(output).toContain('1 topic(s)');+ });+ });+});diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 520184c6918..a7a5f0adef4 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -3,7 +3,9 @@"version": "0.0.1-canary.8","type": "module","bin": {- "lh": "./dist/index.js"+ "lh": "./dist/index.js",+ "lobe": "./dist/index.js",+ "lobehub": "./dist/index.js"},"files": ["dist"@@ -12,7 +14,7 @@"build": "npx tsup","cli:link": "bun link","cli:unlink": "bun unlink",- "dev": "bun src/index.ts",+ "dev": "LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts","prepublishOnly": "npm run build","test": "bunx vitest run --config vitest.config.mts --silent='passed-only'","test:coverage": "bunx vitest run --config vitest.config.mts --coverage",diff --git a/apps/cli/src/auth/credentials.ts b/apps/cli/src/auth/credentials.tsindex bbc3fc632aa..79d109de3c3 100644--- a/apps/cli/src/auth/credentials.ts+++ b/apps/cli/src/auth/credentials.ts@@ -9,7 +9,8 @@ export interface StoredCredentials {refreshToken?: string;}-const CREDENTIALS_DIR = path.join(os.homedir(), '.lobehub');+const LOBEHUB_DIR_NAME = process.env.LOBEHUB_CLI_HOME || '.lobehub';+const CREDENTIALS_DIR = path.join(os.homedir(), LOBEHUB_DIR_NAME);const CREDENTIALS_FILE = path.join(CREDENTIALS_DIR, 'credentials.json');// Derive an encryption key from machine-specific infodiff --git a/apps/cli/src/commands/doc.test.ts b/apps/cli/src/commands/doc.test.tsindex 101161ce32c..974f690335f 100644--- a/apps/cli/src/commands/doc.test.ts+++ b/apps/cli/src/commands/doc.test.ts@@ -8,12 +8,19 @@ const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {document: {createDocument: { mutate: vi.fn() },+ createDocuments: { mutate: vi.fn() },deleteDocument: { mutate: vi.fn() },deleteDocuments: { mutate: vi.fn() },getDocumentById: { query: vi.fn() },+ parseDocument: { mutate: vi.fn() },+ parseFileContent: { mutate: vi.fn() },queryDocuments: { query: vi.fn() },updateDocument: { mutate: vi.fn() },},+ notebook: {+ createDocument: { mutate: vi.fn() },+ listDocuments: { query: vi.fn() },+ },},}));@@ -44,16 +51,23 @@ describe('doc command', () => {let exitSpy: ReturnType<typeof vi.spyOn>;let consoleSpy: ReturnType<typeof vi.spyOn>;+ function resetMocks(obj: Record<string, any>) {+ for (const val of Object.values(obj)) {+ if (typeof val === 'object' && val !== null) {+ if (typeof val.mockReset === 'function') {+ val.mockReset();+ } else {+ resetMocks(val);+ }+ }+ }+ }+beforeEach(() => {exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- // Reset all document mock return values- for (const method of Object.values(mockTrpcClient.document)) {- for (const fn of Object.values(method)) {- (fn as ReturnType<typeof vi.fn>).mockReset();- }- }+ resetMocks(mockTrpcClient);});afterEach(() => {@@ -85,10 +99,9 @@ describe('doc command', () => {const program = createProgram();await program.parseAsync(['node', 'test', 'doc', 'list']);- expect(mockTrpcClient.document.queryDocuments.query).toHaveBeenCalledWith({- fileTypes: undefined,- pageSize: 30,- });+ expect(mockTrpcClient.document.queryDocuments.query).toHaveBeenCalledWith(+ expect.objectContaining({ pageSize: 30 }),+ );// Header + 2 rowsexpect(consoleSpy).toHaveBeenCalledTimes(3);expect(consoleSpy.mock.calls[0][0]).toContain('ID');@@ -122,10 +135,20 @@ describe('doc command', () => {const program = createProgram();await program.parseAsync(['node', 'test', 'doc', 'list', '--file-type', 'md']);- expect(mockTrpcClient.document.queryDocuments.query).toHaveBeenCalledWith({- fileTypes: ['md'],- pageSize: 30,- });+ expect(mockTrpcClient.document.queryDocuments.query).toHaveBeenCalledWith(+ expect.objectContaining({ fileTypes: ['md'] }),+ );+ });++ it('should filter by source type', async () => {+ mockTrpcClient.document.queryDocuments.query.mockResolvedValue([]);++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'list', '--source-type', 'topic']);++ expect(mockTrpcClient.document.queryDocuments.query).toHaveBeenCalledWith(+ expect.objectContaining({ sourceTypes: ['topic'] }),+ );});it('should show message when no documents found', async () => {@@ -143,10 +166,9 @@ describe('doc command', () => {const program = createProgram();await program.parseAsync(['node', 'test', 'doc', 'list', '-L', '10']);- expect(mockTrpcClient.document.queryDocuments.query).toHaveBeenCalledWith({- fileTypes: undefined,- pageSize: 10,- });+ expect(mockTrpcClient.document.queryDocuments.query).toHaveBeenCalledWith(+ expect.objectContaining({ pageSize: 10 }),+ );});});@@ -166,11 +188,26 @@ describe('doc command', () => {await program.parseAsync(['node', 'test', 'doc', 'view', 'doc1']);expect(mockTrpcClient.document.getDocumentById.query).toHaveBeenCalledWith({ id: 'doc1' });- // Title, meta, blank line, content = 4 callsexpect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Test Doc'));expect(consoleSpy).toHaveBeenCalledWith('# Hello World');});+ it('should show knowledge base ID in meta', async () => {+ mockTrpcClient.document.getDocumentById.query.mockResolvedValue({+ content: 'test',+ fileType: 'md',+ id: 'doc1',+ knowledgeBaseId: 'kb_123',+ title: 'KB Doc',+ updatedAt: new Date().toISOString(),+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'view', 'doc1']);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('KB: kb_123'));+ });+it('should output JSON when --json flag is used', async () => {const doc = { content: 'test', id: 'doc1', title: 'Test' };mockTrpcClient.document.getDocumentById.query.mockResolvedValue(doc);@@ -271,6 +308,107 @@ describe('doc command', () => {}),);});++ it('should support --kb flag for knowledge base association', async () => {+ mockTrpcClient.document.createDocument.mutate.mockResolvedValue({ id: 'new-doc' });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'doc',+ 'create',+ '--title',+ 'KB Doc',+ '--kb',+ 'kb_123',+ ]);++ expect(mockTrpcClient.document.createDocument.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ knowledgeBaseId: 'kb_123',+ title: 'KB Doc',+ }),+ );+ });++ it('should support --file-type flag', async () => {+ mockTrpcClient.document.createDocument.mutate.mockResolvedValue({ id: 'new-doc' });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'doc',+ 'create',+ '--title',+ 'Folder',+ '--file-type',+ 'custom/folder',+ ]);++ expect(mockTrpcClient.document.createDocument.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ fileType: 'custom/folder',+ title: 'Folder',+ }),+ );+ });+ });++ // ββ batch-create βββββββββββββββββββββββββββββββββββββββ++ describe('batch-create', () => {+ it('should batch create documents from JSON file', async () => {+ const docs = [+ { content: 'content1', title: 'Doc 1' },+ { content: 'content2', title: 'Doc 2' },+ ];+ vi.spyOn(fs, 'existsSync').mockReturnValue(true);+ vi.spyOn(fs, 'readFileSync').mockReturnValue(JSON.stringify(docs));+ mockTrpcClient.document.createDocuments.mutate.mockResolvedValue([+ { id: 'doc1', title: 'Doc 1' },+ { id: 'doc2', title: 'Doc 2' },+ ]);++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'batch-create', 'docs.json']);++ expect(mockTrpcClient.document.createDocuments.mutate).toHaveBeenCalledWith({+ documents: expect.arrayContaining([+ expect.objectContaining({ content: 'content1', title: 'Doc 1' }),+ expect.objectContaining({ content: 'content2', title: 'Doc 2' }),+ ]),+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Created 2'));++ vi.restoreAllMocks();+ });++ it('should error when file not found', async () => {+ vi.spyOn(fs, 'existsSync').mockReturnValue(false);++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'batch-create', 'missing.json']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));+ expect(exitSpy).toHaveBeenCalledWith(1);++ vi.restoreAllMocks();+ });++ it('should error when JSON is not an array', async () => {+ vi.spyOn(fs, 'existsSync').mockReturnValue(true);+ vi.spyOn(fs, 'readFileSync').mockReturnValue('{"not": "array"}');++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'batch-create', 'bad.json']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('non-empty array'));+ expect(exitSpy).toHaveBeenCalledWith(1);++ vi.restoreAllMocks();+ });});// ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ@@ -305,6 +443,28 @@ describe('doc command', () => {);});+ it('should update file type', async () => {+ mockTrpcClient.document.updateDocument.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'doc',+ 'edit',+ 'doc1',+ '--file-type',+ 'custom/folder',+ ]);++ expect(mockTrpcClient.document.updateDocument.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ fileType: 'custom/folder',+ id: 'doc1',+ }),+ );+ });+it('should exit with error when no changes specified', async () => {const program = createProgram();await program.parseAsync(['node', 'test', 'doc', 'edit', 'doc1']);@@ -339,4 +499,149 @@ describe('doc command', () => {expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Deleted 2'));});});++ // ββ parse βββββββββββββββββββββββββββββββββββββββββββββ++ describe('parse', () => {+ it('should parse a file without pages by default', async () => {+ mockTrpcClient.document.parseDocument.mutate.mockResolvedValue({+ content: 'Parsed content',+ title: 'Parsed Doc',+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'parse', 'file_123']);++ expect(mockTrpcClient.document.parseDocument.mutate).toHaveBeenCalledWith({+ id: 'file_123',+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Parsed file'));+ });++ it('should use parseFileContent with --with-pages', async () => {+ mockTrpcClient.document.parseFileContent.mutate.mockResolvedValue({+ content: 'Parsed with pages',+ title: 'Paged Doc',+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'parse', 'file_123', '--with-pages']);++ expect(mockTrpcClient.document.parseFileContent.mutate).toHaveBeenCalledWith({+ id: 'file_123',+ });+ });++ it('should output JSON with --json flag', async () => {+ const result = { content: 'test', title: 'Doc' };+ mockTrpcClient.document.parseDocument.mutate.mockResolvedValue(result);++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'parse', 'file_123', '--json']);++ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(result, null, 2));+ });+ });++ // ββ link-topic ββββββββββββββββββββββββββββββββββββββββ++ describe('link-topic', () => {+ it('should link a document to a topic', async () => {+ mockTrpcClient.document.getDocumentById.query.mockResolvedValue({+ content: 'doc content',+ description: 'desc',+ id: 'doc1',+ title: 'My Doc',+ });+ mockTrpcClient.notebook.createDocument.mutate.mockResolvedValue({ id: 'new-doc' });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'link-topic', 'doc1', 'topic_123']);++ expect(mockTrpcClient.notebook.createDocument.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'doc content',+ title: 'My Doc',+ topicId: 'topic_123',+ }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Linked'));+ });++ it('should error when document not found', async () => {+ mockTrpcClient.document.getDocumentById.query.mockResolvedValue(null);++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'link-topic', 'bad-id', 'topic_123']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+ });++ // ββ topic-docs ββββββββββββββββββββββββββββββββββββββββ++ describe('topic-docs', () => {+ it('should list documents for a topic', async () => {+ mockTrpcClient.notebook.listDocuments.query.mockResolvedValue({+ data: [+ {+ fileType: 'markdown',+ id: 'doc1',+ title: 'Note 1',+ updatedAt: new Date().toISOString(),+ },+ { fileType: 'article', id: 'doc2', title: 'Note 2', updatedAt: new Date().toISOString() },+ ],+ total: 2,+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'topic-docs', 'topic_123']);++ expect(mockTrpcClient.notebook.listDocuments.query).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'topic_123' }),+ );+ // Header + 2 rows+ expect(consoleSpy).toHaveBeenCalledTimes(3);+ });++ it('should filter by --type', async () => {+ mockTrpcClient.notebook.listDocuments.query.mockResolvedValue({ data: [], total: 0 });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'doc',+ 'topic-docs',+ 'topic_123',+ '--type',+ 'article',+ ]);++ expect(mockTrpcClient.notebook.listDocuments.query).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'topic_123', type: 'article' }),+ );+ });++ it('should output JSON with --json flag', async () => {+ const docs = [{ id: 'doc1', title: 'Note' }];+ mockTrpcClient.notebook.listDocuments.query.mockResolvedValue({ data: docs, total: 1 });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'topic-docs', 'topic_123', '--json']);++ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(docs, null, 2));+ });++ it('should show message when no documents found', async () => {+ mockTrpcClient.notebook.listDocuments.query.mockResolvedValue({ data: [], total: 0 });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'doc', 'topic-docs', 'topic_123']);++ expect(consoleSpy).toHaveBeenCalledWith('No documents found for this topic.');+ });+ });});diff --git a/apps/cli/src/commands/doc.ts b/apps/cli/src/commands/doc.tsindex 7b8cd58519c..a257c0896fb 100644--- a/apps/cli/src/commands/doc.ts+++ b/apps/cli/src/commands/doc.ts@@ -32,36 +32,47 @@ export function registerDocCommand(program: Command) {.description('List documents').option('-L, --limit <n>', 'Maximum number of items to fetch', '30').option('--file-type <type>', 'Filter by file type')+ .option('--source-type <type>', 'Filter by source type (file, web, api, topic)').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')- .action(async (options: { fileType?: string; json?: string | boolean; limit?: string }) => {- const client = await getTrpcClient();- const pageSize = Number.parseInt(options.limit || '30', 10);-- const query: { fileTypes?: string[]; pageSize: number } = { pageSize };- if (options.fileType) query.fileTypes = [options.fileType];- const result = await client.document.queryDocuments.query(query);- const docs = Array.isArray(result) ? result : ((result as any).items ?? []);-- if (options.json !== undefined) {- const fields = typeof options.json === 'string' ? options.json : undefined;- outputJson(docs, fields);- return;- }+ .action(+ async (options: {+ fileType?: string;+ json?: string | boolean;+ limit?: string;+ sourceType?: string;+ }) => {+ const client = await getTrpcClient();+ const pageSize = Number.parseInt(options.limit || '30', 10);++ const query: { fileTypes?: string[]; pageSize: number; sourceTypes?: string[] } = {+ pageSize,+ };+ if (options.fileType) query.fileTypes = [options.fileType];+ if (options.sourceType) query.sourceTypes = [options.sourceType];+ const result = await client.document.queryDocuments.query(query);+ const docs = Array.isArray(result) ? result : ((result as any).items ?? []);++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(docs, fields);+ return;+ }- if (docs.length === 0) {- console.log('No documents found.');- return;- }+ if (docs.length === 0) {+ console.log('No documents found.');+ return;+ }- const rows = docs.map((d: any) => [- d.id,- truncate(d.title || d.filename || 'Untitled', 120),- d.fileType || '',- d.updatedAt ? timeAgo(d.updatedAt) : '',- ]);+ const rows = docs.map((d: any) => [+ d.id,+ truncate(d.title || d.filename || 'Untitled', 120),+ d.fileType || '',+ d.updatedAt ? timeAgo(d.updatedAt) : '',+ ]);- printTable(rows, ['ID', 'TITLE', 'TYPE', 'UPDATED']);- });+ printTable(rows, ['ID', 'TITLE', 'TYPE', 'UPDATED']);+ },+ );// ββ view ββββββββββββββββββββββββββββββββββββββββββββββ@@ -89,6 +100,7 @@ export function registerDocCommand(program: Command) {console.log(pc.bold(document.title || 'Untitled'));const meta: string[] = [];if (document.fileType) meta.push(document.fileType);+ if ((document as any).knowledgeBaseId) meta.push(`KB: ${(document as any).knowledgeBaseId}`);if (document.updatedAt) meta.push(`Updated ${timeAgo(document.updatedAt)}`);if (meta.length > 0) console.log(pc.dim(meta.join(' Β· ')));console.log();@@ -110,10 +122,14 @@ export function registerDocCommand(program: Command) {.option('-F, --body-file <path>', 'Read content from file').option('--parent <id>', 'Parent document or folder ID').option('--slug <slug>', 'Custom slug')+ .option('--kb <id>', 'Knowledge base ID to associate with')+ .option('--file-type <type>', 'File type (e.g. custom/document, custom/folder)').action(async (options: {body?: string;bodyFile?: string;+ fileType?: string;+ kb?: string;parent?: string;slug?: string;title: string;@@ -124,6 +140,8 @@ export function registerDocCommand(program: Command) {const result = await client.document.createDocument.mutate({content,editorData: JSON.stringify({ content: content || '', type: 'doc' }),+ fileType: options.fileType,+ knowledgeBaseId: options.kb,parentId: options.parent,slug: options.slug,title: options.title,@@ -133,6 +151,54 @@ export function registerDocCommand(program: Command) {},);+ // ββ batch-create βββββββββββββββββββββββββββββββββββββββ++ doc+ .command('batch-create <file>')+ .description('Batch create documents from a JSON file')+ .action(async (file: string) => {+ if (!fs.existsSync(file)) {+ log.error(`File not found: ${file}`);+ process.exit(1);+ return;+ }++ let documents: any[];+ try {+ const raw = fs.readFileSync(file, 'utf8');+ documents = JSON.parse(raw);+ } catch {+ log.error('Failed to parse JSON file. Expected an array of document objects.');+ process.exit(1);+ return;+ }++ if (!Array.isArray(documents) || documents.length === 0) {+ log.error('JSON file must contain a non-empty array of document objects.');+ process.exit(1);+ return;+ }++ const client = await getTrpcClient();++ const items = documents.map((d) => ({+ content: d.content,+ editorData: JSON.stringify({ content: d.content || '', type: 'doc' }),+ fileType: d.fileType,+ knowledgeBaseId: d.knowledgeBaseId,+ parentId: d.parentId,+ slug: d.slug,+ title: d.title,+ }));++ const result = await client.document.createDocuments.mutate({ documents: items });+ const created = Array.isArray(result) ? result : [result];+ console.log(`${pc.green('β')} Created ${created.length} document(s)`);+ for (const doc of created) {+ console.log(` ${pc.dim('β’')} ${doc.id} β ${doc.title || 'Untitled'}`);+ }+ });+// ββ edit ββββββββββββββββββββββββββββββββββββββββββββββdoc@@ -142,15 +208,24 @@ export function registerDocCommand(program: Command) {.option('-b, --body <content>', 'New content').option('-F, --body-file <path>', 'Read new content from file').option('--parent <id>', 'Move to parent document (empty string for root)')+ .option('--file-type <type>', 'Change file type').action(async (id: string,- options: { body?: string; bodyFile?: string; parent?: string; title?: string },+ options: {+ body?: string;+ bodyFile?: string;+ fileType?: string;+ parent?: string;+ title?: string;+ },) => {const content = readBodyContent(options);- if (!options.title && !content && options.parent === undefined) {- log.error('No changes specified. Use --title, --body, --body-file, or --parent.');+ if (!options.title && !content && options.parent === undefined && !options.fileType) {+ log.error(+ 'No changes specified. Use --title, --body, --body-file, --parent, or --file-type.',+ );process.exit(1);}@@ -165,6 +240,7 @@ export function registerDocCommand(program: Command) {if (options.parent !== undefined) {params.parentId = options.parent || null;}+ if (options.fileType) params.fileType = options.fileType;await client.document.updateDocument.mutate(params as any);console.log(`${pc.green('β')} Updated document ${pc.bold(id)}`);@@ -198,4 +274,98 @@ export function registerDocCommand(program: Command) {console.log(`${pc.green('β')} Deleted ${ids.length} document(s)`);});++ // ββ parse βββββββββββββββββββββββββββββββββββββββββββββ++ doc+ .command('parse <fileId>')+ .description('Parse an uploaded file into a document')+ .option('--with-pages', 'Preserve page structure')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (fileId: string, options: { json?: string | boolean; withPages?: boolean }) => {+ const client = await getTrpcClient();++ const result = options.withPages+ ? await client.document.parseFileContent.mutate({ id: fileId })+ : await client.document.parseDocument.mutate({ id: fileId });++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(result, fields);+ return;+ }++ console.log(`${pc.green('β')} Parsed file ${pc.bold(fileId)}`);+ if ((result as any).title) console.log(` Title: ${(result as any).title}`);+ if ((result as any).content) {+ const preview = truncate((result as any).content, 200);+ console.log(` Content: ${pc.dim(preview)}`);+ }+ });++ // ββ link-topic ββββββββββββββββββββββββββββββββββββββββ++ doc+ .command('link-topic <docId> <topicId>')+ .description('Associate a document with a topic')+ .action(async (docId: string, topicId: string) => {+ const client = await getTrpcClient();++ // Create the document via notebook router which handles topic association+ // First verify the document exists+ const document = await client.document.getDocumentById.query({ id: docId });+ if (!document) {+ log.error(`Document not found: ${docId}`);+ process.exit(1);+ return;+ }++ // Use notebook.createDocument to create a linked copy, associating with the topic+ const result = await client.notebook.createDocument.mutate({+ content: document.content || '',+ description: document.description || '',+ title: document.title || 'Untitled',+ topicId,+ });++ console.log(+ `${pc.green('β')} Linked document ${pc.bold(result.id)} to topic ${pc.bold(topicId)}`,+ );+ });++ // ββ topic-docs ββββββββββββββββββββββββββββββββββββββββ++ doc+ .command('topic-docs <topicId>')+ .description('List documents associated with a topic')+ .option('--type <type>', 'Filter by document type (article, markdown, note, report)')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (topicId: string, options: { json?: string | boolean; type?: string }) => {+ const client = await getTrpcClient();++ const query: { topicId: string; type?: any } = { topicId };+ if (options.type) query.type = options.type;+ const result = await client.notebook.listDocuments.query(query);+ const docs = Array.isArray(result) ? result : ((result as any).data ?? []);++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(docs, fields);+ return;+ }++ if (docs.length === 0) {+ console.log('No documents found for this topic.');+ return;+ }++ const rows = docs.map((d: any) => [+ d.id,+ truncate(d.title || 'Untitled', 120),+ d.fileType || '',+ d.updatedAt ? timeAgo(d.updatedAt) : '',+ ]);++ printTable(rows, ['ID', 'TITLE', 'TYPE', 'UPDATED']);+ });}diff --git a/apps/cli/src/commands/generate/index.ts b/apps/cli/src/commands/generate/index.tsindex bcc76856593..58ce3cbd717 100644--- a/apps/cli/src/commands/generate/index.ts+++ b/apps/cli/src/commands/generate/index.ts@@ -51,6 +51,92 @@ export function registerGenerateCommand(program: Command) {}});+ // ββ download ββββββββββββββββββββββββββββββββββββββββββ+ generate+ .command('download <generationId> <taskId>')+ .description('Wait for generation to complete and download the result')+ .option('-o, --output <path>', 'Output file path (default: auto-detect from asset)')+ .option('--interval <sec>', 'Polling interval in seconds', '5')+ .option('--timeout <sec>', 'Timeout in seconds (0 = no timeout)', '300')+ .action(+ async (+ generationId: string,+ taskId: string,+ options: { interval?: string; output?: string; timeout?: string },+ ) => {+ const client = await getTrpcClient();+ const interval = Number.parseInt(options.interval || '5', 10) * 1000;+ const timeout = Number.parseInt(options.timeout || '300', 10) * 1000;+ const startTime = Date.now();++ console.log(`${pc.yellow('β―')} Waiting for generation ${pc.bold(generationId)}...`);++ // Poll for completion+ while (true) {+ const result = (await client.generation.getGenerationStatus.query({+ asyncTaskId: taskId,+ generationId,+ })) as any;++ if (result.status === 'success' && result.generation) {+ const gen = result.generation;+ const url = gen.asset?.url;++ if (!url) {+ console.log(`${pc.red('β')} Generation succeeded but no asset URL found.`);+ process.exit(1);+ }++ // Determine output path+ const ext = url.split('?')[0].split('.').pop() || 'bin';+ const outputPath = options.output || `${generationId}.${ext}`;++ console.log(`${pc.green('β')} Generation complete. Downloading...`);++ // Download+ const res = await fetch(url);+ if (!res.ok) {+ console.log(`${pc.red('β')} Download failed: ${res.status} ${res.statusText}`);+ process.exit(1);+ }++ const { writeFile } = await import('node:fs/promises');+ const buffer = Buffer.from(await res.arrayBuffer());+ await writeFile(outputPath, buffer);++ console.log(+ `${pc.green('β')} Saved to ${pc.bold(outputPath)} (${(buffer.length / 1024).toFixed(1)} KB)`,+ );+ if (gen.asset?.thumbnailUrl) {+ console.log(` Thumbnail: ${pc.dim(gen.asset.thumbnailUrl)}`);+ }+ return;+ }++ if (result.status === 'error') {+ const errMsg =+ result.error?.body?.detail || result.error?.message || JSON.stringify(result.error);+ console.log(`${pc.red('β')} Generation failed: ${errMsg}`);+ process.exit(1);+ }++ // Check timeout+ if (timeout > 0 && Date.now() - startTime > timeout) {+ console.log(+ `${pc.red('β')} Timed out after ${options.timeout}s. Task still ${result.status}.`,+ );+ console.log(pc.dim(`Run "lh gen status ${generationId} ${taskId}" to check later.`));+ process.exit(1);+ }++ process.stdout.write(+ `\r${pc.yellow('β―')} Status: ${colorStatus(result.status)}... (${Math.round((Date.now() - startTime) / 1000)}s)`,+ );+ await new Promise((r) => setTimeout(r, interval));+ }+ },+ );+// ββ list ββββββββββββββββββββββββββββββββββββββββββββgenerate.command('list')diff --git a/apps/cli/src/commands/generate/text.ts b/apps/cli/src/commands/generate/text.tsindex 5d08a65f7dc..673b5a76232 100644--- a/apps/cli/src/commands/generate/text.ts+++ b/apps/cli/src/commands/generate/text.ts@@ -58,6 +58,9 @@ export function registerTextCommand(parent: Command) {const payload: Record<string, any> = {messages,model,+ // For non-streaming, use responseMode 'json' to get a plain JSON response+ // instead of SSE (the backend converts non-stream to SSE by default)+ responseMode: useStream ? 'stream' : 'json',stream: useStream,};if (options.temperature) payload.temperature = Number.parseFloat(options.temperature);@@ -83,7 +86,12 @@ export function registerTextCommand(parent: Command) {if (options.json) {console.log(JSON.stringify(body, null, 2));} else {- const content = (body as any).choices?.[0]?.message?.content || JSON.stringify(body);+ // Support both OpenAI format (choices[].message.content) and+ // Anthropic format (content[].text)+ const content =+ (body as any).choices?.[0]?.message?.content ||+ (body as any).content?.[0]?.text ||+ JSON.stringify(body);process.stdout.write(content);process.stdout.write('\n');}@@ -128,9 +136,12 @@ async function streamSSEResponse(body: ReadableStream<Uint8Array>, json?: booleaconst parsed = JSON.parse(data);if (json) {console.log(JSON.stringify(parsed));- } else {- const content = parsed.choices?.[0]?.delta?.content;- if (content) process.stdout.write(content);+ } else if (typeof parsed === 'string' && parsed !== 'stop') {+ // LobeHub SSE sends content as JSON strings: "Hello", "world"+ process.stdout.write(parsed);+ } else if (parsed?.choices?.[0]?.delta?.content) {+ // Standard OpenAI SSE format+ process.stdout.write(parsed.choices[0].delta.content);}} catch {// Not JSON, might be raw text chunkdiff --git a/apps/cli/src/commands/generate/video.ts b/apps/cli/src/commands/generate/video.tsindex 3f16e8678c0..ea1f4c6c570 100644--- a/apps/cli/src/commands/generate/video.ts+++ b/apps/cli/src/commands/generate/video.ts@@ -51,12 +51,20 @@ export function registerVideoCommand(parent: Command) {const data = r.data || r;console.log(`${pc.green('β')} Video generation started`);- if (data.generationId) {- console.log(` Generation ID: ${pc.bold(data.generationId)}`);+ if (data.batch?.id) console.log(` Batch ID: ${pc.bold(data.batch.id)}`);++ const generations = data.generations || [];+ if (generations.length > 0) {+ for (const gen of generations) {+ if (gen.asyncTaskId) {+ console.log(` Generation ${pc.bold(gen.id)} β Task ${pc.dim(gen.asyncTaskId)}`);+ }+ }+ console.log();+ console.log(+ pc.dim('Use "lh generate status <generationId> <taskId>" to check progress.'),+ );}- console.log(- pc.dim('Video generation runs asynchronously. Check status or wait for notification.'),- );},);}diff --git a/apps/cli/src/commands/kb.test.ts b/apps/cli/src/commands/kb.test.tsindex 5a70f045604..5793d994bf8 100644--- a/apps/cli/src/commands/kb.test.ts+++ b/apps/cli/src/commands/kb.test.ts@@ -6,6 +6,10 @@ import { registerKbCommand } from './kb';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {+ file: {+ getFiles: { query: vi.fn() },+ getKnowledgeItems: { query: vi.fn() },+ },knowledgeBase: {addFilesToKnowledgeBase: { mutate: vi.fn() },createKnowledgeBase: { mutate: vi.fn() },@@ -44,6 +48,9 @@ describe('kb command', () => {}}}+ // Default: file queries return empty+ mockTrpcClient.file.getFiles.query.mockResolvedValue([]);+ mockTrpcClient.file.getKnowledgeItems.query.mockResolvedValue({ hasMore: false, items: [] });});afterEach(() => {@@ -121,7 +128,7 @@ describe('kb command', () => {describe('create', () => {it('should create a knowledge base', async () => {- mockTrpcClient.knowledgeBase.createKnowledgeBase.mutate.mockResolvedValue({ id: 'kb-new' });+ mockTrpcClient.knowledgeBase.createKnowledgeBase.mutate.mockResolvedValue('kb-new');const program = createProgram();await program.parseAsync([diff --git a/apps/cli/src/commands/kb.ts b/apps/cli/src/commands/kb.tsindex 1297dd763d9..f65ad445eb7 100644--- a/apps/cli/src/commands/kb.ts+++ b/apps/cli/src/commands/kb.ts@@ -1,12 +1,38 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';+import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';+import { getAuthInfo } from '../api/http';import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';import { log } from '../utils/logger';+function formatFileType(fileType: string): string {+ if (!fileType) return '';+ // Simplify common MIME types to readable short names+ const map: Record<string, string> = {+ 'application/msword': 'doc',+ 'application/pdf': 'pdf',+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',+ 'custom/folder': 'folder',+ 'text/markdown': 'md',+ 'text/plain': 'txt',+ };+ if (map[fileType]) return map[fileType];+ // For other types, extract subtype (e.g. "image/png" β "png")+ const parts = fileType.split('/');+ return parts.length > 1 ? parts[1] : fileType;+}+export function registerKbCommand(program: Command) {- const kb = program.command('kb').description('Manage knowledge bases');+ const kb = program+ .command('kb')+ .description('Manage knowledge bases, folders, documents, and files');// ββ list ββββββββββββββββββββββββββββββββββββββββββββββ@@ -54,9 +80,40 @@ export function registerKbCommand(program: Command) {return;}+ // Recursively fetch all items in the knowledge base (with pagination)+ const allItems: any[] = [];+ async function fetchItems(parentId: string | null, depth = 0) {+ const PAGE_SIZE = 100;+ let offset = 0;+ let hasMore = true;++ while (hasMore) {+ const query: any = { knowledgeBaseId: id, limit: PAGE_SIZE, offset, parentId };+ const result = await client.file.getKnowledgeItems.query(query);+ const list = Array.isArray(result) ? result : ((result as any).items ?? []);+ hasMore = Array.isArray(result) ? false : ((result as any).hasMore ?? false);+ offset += list.length;++ // Collect folders for parallel recursive fetch+ const folders: any[] = [];+ for (const item of list) {+ allItems.push({ ...item, _depth: depth });+ if (item.fileType === 'custom/folder') {+ folders.push(item);+ }+ }++ // Fetch all sub-folders in parallel+ if (folders.length > 0) {+ await Promise.all(folders.map((f) => fetchItems(f.id, depth + 1)));+ }+ }+ }+ await fetchItems(null);+if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;- outputJson(result, fields);+ outputJson({ ...result, files: allItems }, fields);return;}@@ -66,19 +123,23 @@ export function registerKbCommand(program: Command) {if ((result as any).updatedAt) meta.push(`Updated ${timeAgo((result as any).updatedAt)}`);if (meta.length > 0) console.log(pc.dim(meta.join(' Β· ')));- // Show files if available- if ((result as any).files && Array.isArray((result as any).files)) {- const files = (result as any).files;- if (files.length > 0) {- console.log();- console.log(pc.bold(`Files (${files.length}):`));- const rows = files.map((f: any) => [+ if (allItems.length > 0) {+ console.log();+ console.log(pc.bold(`Items (${allItems.length}):`));+ const rows = allItems.map((f: any) => {+ const indent = ' '.repeat(f._depth);+ const name = f.name || f.filename || '';+ return [f.id,- truncate(f.name || f.filename || '', 50),- f.fileType || '',- ]);- printTable(rows, ['ID', 'NAME', 'TYPE']);- }+ f.sourceType === 'document' ? 'Doc' : 'File',+ truncate(`${indent}${name}`, 45),+ formatFileType(f.fileType || ''),+ f.size ? `${Math.round(f.size / 1024)}KB` : '',+ ];+ });+ printTable(rows, ['ID', 'SOURCE', 'NAME', 'TYPE', 'SIZE']);+ } else {+ console.log(pc.dim('\nNo files in this knowledge base.'));}});@@ -98,8 +159,8 @@ export function registerKbCommand(program: Command) {if (options.description) input.description = options.description;if (options.avatar) input.avatar = options.avatar;- const result = await client.knowledgeBase.createKnowledgeBase.mutate(input);- console.log(`${pc.green('β')} Created knowledge base ${pc.bold((result as any).id)}`);+ const id = await client.knowledgeBase.createKnowledgeBase.mutate(input);+ console.log(`${pc.green('β')} Created knowledge base ${pc.bold(String(id))}`);});// ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ@@ -193,4 +254,151 @@ export function registerKbCommand(program: Command) {`${pc.green('β')} Removed ${options.ids.length} file(s) from knowledge base ${pc.bold(knowledgeBaseId)}`,);});++ // ββ mkdir βββββββββββββββββββββββββββββββββββββββββββ++ kb.command('mkdir <knowledgeBaseId>')+ .description('Create a folder in a knowledge base')+ .requiredOption('-n, --name <name>', 'Folder name')+ .option('--parent <parentId>', 'Parent folder ID')+ .action(async (knowledgeBaseId: string, options: { name: string; parent?: string }) => {+ const client = await getTrpcClient();+ const result = await client.document.createDocument.mutate({+ editorData: JSON.stringify({}),+ fileType: 'custom/folder',+ knowledgeBaseId,+ parentId: options.parent,+ title: options.name,+ });+ console.log(`${pc.green('β')} Created folder ${pc.bold((result as any).id)}`);+ });++ // ββ create-doc ββββββββββββββββββββββββββββββββββββββ++ kb.command('create-doc <knowledgeBaseId>')+ .description('Create a document in a knowledge base')+ .requiredOption('-t, --title <title>', 'Document title')+ .option('-c, --content <content>', 'Document content (text)')+ .option('--parent <parentId>', 'Parent folder ID')+ .action(+ async (+ knowledgeBaseId: string,+ options: { content?: string; parent?: string; title: string },+ ) => {+ const client = await getTrpcClient();+ const result = await client.document.createDocument.mutate({+ content: options.content,+ editorData: JSON.stringify({}),+ fileType: 'custom/document',+ knowledgeBaseId,+ parentId: options.parent,+ title: options.title,+ });+ console.log(`${pc.green('β')} Created document ${pc.bold((result as any).id)}`);+ },+ );++ // ββ move ββββββββββββββββββββββββββββββββββββββββββββ++ kb.command('move <id>')+ .description('Move a file or document to a different folder')+ .option('--parent <parentId>', 'Target folder ID (omit to move to root)')+ .option('--type <type>', 'Item type: file or doc', 'file')+ .action(async (id: string, options: { parent?: string; type: string }) => {+ const client = await getTrpcClient();+ const parentId = options.parent ?? null;++ if (options.type === 'doc') {+ await client.document.updateDocument.mutate({ id, parentId });+ } else {+ await client.file.updateFile.mutate({ id, parentId });+ }++ const dest = parentId ? `folder ${pc.bold(parentId)}` : 'root';+ console.log(`${pc.green('β')} Moved ${pc.bold(id)} to ${dest}`);+ });++ // ββ upload ββββββββββββββββββββββββββββββββββββββββββ++ kb.command('upload <knowledgeBaseId> <filePath>')+ .description('Upload a file to a knowledge base')+ .option('--parent <parentId>', 'Parent folder ID')+ .action(async (knowledgeBaseId: string, filePath: string, options: { parent?: string }) => {+ const resolved = path.resolve(filePath);+ if (!fs.existsSync(resolved)) {+ log.error(`File not found: ${resolved}`);+ process.exit(1);+ }++ const stat = fs.statSync(resolved);+ const fileName = path.basename(resolved);+ const fileBuffer = fs.readFileSync(resolved);++ // Compute SHA-256 hash+ const hash = crypto.createHash('sha256').update(fileBuffer).digest('hex');++ // Detect MIME type from extension+ const ext = path.extname(fileName).toLowerCase().slice(1);+ const mimeMap: Record<string, string> = {+ csv: 'text/csv',+ doc: 'application/msword',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ gif: 'image/gif',+ jpeg: 'image/jpeg',+ jpg: 'image/jpeg',+ json: 'application/json',+ md: 'text/markdown',+ mp3: 'audio/mpeg',+ mp4: 'video/mp4',+ pdf: 'application/pdf',+ png: 'image/png',+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ svg: 'image/svg+xml',+ txt: 'text/plain',+ webp: 'image/webp',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ };+ const fileType = mimeMap[ext] || 'application/octet-stream';++ const client = await getTrpcClient();+ const { serverUrl, headers } = await getAuthInfo();++ // 1. Get presigned URL+ const date = new Date().toLocaleDateString('en-CA'); // YYYY-MM-DD+ const pathname = `files/${date}/${hash}.${ext}`;+ const presigned = await client.upload.createS3PreSignedUrl.mutate({ pathname });++ // 2. Upload to S3+ const presignedUrl = typeof presigned === 'string' ? presigned : (presigned as any).url;+ const uploadRes = await fetch(presignedUrl, {+ body: fileBuffer,+ headers: { 'Content-Type': fileType },+ method: 'PUT',+ });+ if (!uploadRes.ok) {+ log.error(`Upload failed: ${uploadRes.status} ${uploadRes.statusText}`);+ process.exit(1);+ }++ // 3. Create file record+ const result = await client.file.createFile.mutate({+ fileType,+ hash,+ knowledgeBaseId,+ metadata: {+ date,+ dirname: '',+ filename: fileName,+ path: pathname,+ },+ name: fileName,+ parentId: options.parent,+ size: stat.size,+ url: pathname,+ });++ console.log(+ `${pc.green('β')} Uploaded ${pc.bold(fileName)} β ${pc.bold((result as any).id)}`,+ );+ });}diff --git a/apps/cli/src/commands/memory.ts b/apps/cli/src/commands/memory.tsindex 4be0947892b..0e199243ff7 100644--- a/apps/cli/src/commands/memory.ts+++ b/apps/cli/src/commands/memory.ts@@ -35,21 +35,8 @@ export function registerMemoryCommand(program: Command) {const allResults: Record<string, any[]> = {};for (const cat of categoriesToFetch) {- const getter = `get${capitalize(cat)}` as string;- const getterPlural = `${getter}s` as string;-- // Try plural first (getIdentities, getActivities, etc.), then singular- const router = client.userMemory as any;try {- if (router[getterPlural]) {- allResults[cat] = await router[getterPlural].query();- } else if (router[getter]) {- allResults[cat] = await router[getter].query();- } else {- // Try the special name patterns- const items = await fetchCategory(client, cat);- allResults[cat] = items;- }+ allResults[cat] = await fetchCategory(client, cat);} catch {allResults[cat] = [];}@@ -112,8 +99,11 @@ export function registerMemoryCommand(program: Command) {try {const result = await (client.userMemory as any).createIdentity.mutate(input);- const id = result?.id || 'unknown';- console.log(`${pc.green('β')} Created identity memory ${pc.bold(id)}`);+ const memoryId = result?.userMemoryId || 'unknown';+ const identityId = result?.identityId || 'unknown';+ console.log(+ `${pc.green('β')} Created identity memory ${pc.bold(memoryId)} (identity: ${pc.bold(identityId)})`,+ );} catch (error: any) {log.error(`Failed to create identity: ${error.message}`);process.exit(1);diff --git a/apps/cli/src/commands/message.test.ts b/apps/cli/src/commands/message.test.tsindex a31ed80a25d..dcffe03b939 100644--- a/apps/cli/src/commands/message.test.ts+++ b/apps/cli/src/commands/message.test.ts@@ -9,6 +9,7 @@ const { mockTrpcClient } = vi.hoisted(() => ({count: { query: vi.fn() },getHeatmaps: { query: vi.fn() },getMessages: { query: vi.fn() },+ listAll: { query: vi.fn() },removeMessage: { mutate: vi.fn() },removeMessages: { mutate: vi.fn() },searchMessages: { query: vi.fn() },@@ -54,18 +55,20 @@ describe('message command', () => {}describe('list', () => {- it('should display messages', async () => {- mockTrpcClient.message.getMessages.query.mockResolvedValue([+ it('should use listAll when no filters', async () => {+ mockTrpcClient.message.listAll.query.mockResolvedValue([{ content: 'Hello', createdAt: new Date().toISOString(), id: 'm1', role: 'user' },]);const program = createProgram();await program.parseAsync(['node', 'test', 'message', 'list']);+ expect(mockTrpcClient.message.listAll.query).toHaveBeenCalled();+ expect(mockTrpcClient.message.getMessages.query).not.toHaveBeenCalled();expect(consoleSpy).toHaveBeenCalledTimes(2);});- it('should filter by topic-id', async () => {+ it('should filter by topic-id using getMessages', async () => {mockTrpcClient.message.getMessages.query.mockResolvedValue([]);const program = createProgram();@@ -74,6 +77,7 @@ describe('message command', () => {expect(mockTrpcClient.message.getMessages.query).toHaveBeenCalledWith(expect.objectContaining({ topicId: 't1' }),);+ expect(mockTrpcClient.message.listAll.query).not.toHaveBeenCalled();});});diff --git a/apps/cli/src/commands/message.ts b/apps/cli/src/commands/message.tsindex 04edafe8fba..099dd5628e6 100644--- a/apps/cli/src/commands/message.ts+++ b/apps/cli/src/commands/message.ts@@ -14,9 +14,9 @@ export function registerMessageCommand(program: Command) {.description('List messages').option('--topic-id <id>', 'Filter by topic ID').option('--agent-id <id>', 'Filter by agent ID')- .option('--session-id <id>', 'Filter by session ID').option('-L, --limit <n>', 'Page size', '30').option('--page <n>', 'Page number', '1')+ .option('--user', 'Only show user messages').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)').action(async (options: {@@ -24,20 +24,38 @@ export function registerMessageCommand(program: Command) {json?: string | boolean;limit?: string;page?: string;- sessionId?: string;topicId?: string;+ user?: boolean;}) => {const client = await getTrpcClient();- const input: Record<string, any> = {};- if (options.topicId) input.topicId = options.topicId;- if (options.agentId) input.agentId = options.agentId;- if (options.sessionId) input.sessionId = options.sessionId;- if (options.limit) input.pageSize = Number.parseInt(options.limit, 10);- if (options.page) input.current = Number.parseInt(options.page, 10);+ const hasFilter = options.topicId || options.agentId;+ const pageSize = options.limit ? Number.parseInt(options.limit, 10) : undefined;+ const current = options.page ? Number.parseInt(options.page, 10) : undefined;- const result = await client.message.getMessages.query(input as any);- const items = Array.isArray(result) ? result : ((result as any).items ?? []);+ let items: any[];++ if (hasFilter) {+ const input: Record<string, any> = {};+ if (options.topicId) input.topicId = options.topicId;+ if (options.agentId) input.agentId = options.agentId;+ if (pageSize) input.pageSize = pageSize;+ if (current) input.current = current;++ const result = await client.message.getMessages.query(input as any);+ items = Array.isArray(result) ? result : ((result as any).items ?? []);+ } else {+ const input: Record<string, any> = {};+ if (pageSize) input.pageSize = pageSize;+ if (current) input.current = current;++ const result = await client.message.listAll.query(input as any);+ items = Array.isArray(result) ? result : [];+ }++ if (options.user) {+ items = items.filter((m: any) => m.role === 'user');+ }if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;diff --git a/apps/cli/src/commands/model.test.ts b/apps/cli/src/commands/model.test.tsindex 63bc520d110..d2aa9252554 100644--- a/apps/cli/src/commands/model.test.ts+++ b/apps/cli/src/commands/model.test.ts@@ -7,10 +7,15 @@ import { registerModelCommand } from './model';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {aiModel: {+ batchToggleAiModels: { mutate: vi.fn() },+ clearModelsByProvider: { mutate: vi.fn() },+ clearRemoteModels: { mutate: vi.fn() },+ createAiModel: { mutate: vi.fn() },getAiModelById: { query: vi.fn() },getAiProviderModelList: { query: vi.fn() },removeAiModel: { mutate: vi.fn() },toggleModelEnabled: { mutate: vi.fn() },+ updateAiModel: { mutate: vi.fn() },},},}));@@ -66,6 +71,16 @@ describe('model command', () => {);expect(consoleSpy).toHaveBeenCalledTimes(2);});++ it('should output JSON', async () => {+ const models = [{ displayName: 'GPT-4', id: 'gpt-4' }];+ mockTrpcClient.aiModel.getAiProviderModelList.query.mockResolvedValue(models);++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'model', 'list', 'openai', '--json']);++ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(models, null, 2));+ });});describe('view', () => {@@ -93,6 +108,72 @@ describe('model command', () => {});});+ describe('create', () => {+ it('should create a model', async () => {+ mockTrpcClient.aiModel.createAiModel.mutate.mockResolvedValue('test-model');++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'model',+ 'create',+ '--id',+ 'test-model',+ '--provider',+ 'openai',+ '--display-name',+ 'Test Model',+ '--type',+ 'chat',+ ]);++ expect(mockTrpcClient.aiModel.createAiModel.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'test-model',+ providerId: 'openai',+ displayName: 'Test Model',+ type: 'chat',+ }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Created model'));+ });+ });++ describe('edit', () => {+ it('should update model display name', async () => {+ mockTrpcClient.aiModel.updateAiModel.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'model',+ 'edit',+ 'gpt-4',+ '--provider',+ 'openai',+ '--display-name',+ 'New Name',+ ]);++ expect(mockTrpcClient.aiModel.updateAiModel.mutate).toHaveBeenCalledWith({+ id: 'gpt-4',+ providerId: 'openai',+ value: expect.objectContaining({ displayName: 'New Name' }),+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Updated model'));+ });++ it('should error when no changes specified', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'model', 'edit', 'gpt-4', '--provider', 'openai']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No changes'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+ });+describe('toggle', () => {it('should enable model', async () => {mockTrpcClient.aiModel.toggleModelEnabled.mutate.mockResolvedValue({});@@ -113,6 +194,22 @@ describe('model command', () => {expect.objectContaining({ enabled: true, id: 'gpt-4' }),);});++ it('should error when no flag specified', async () => {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'model',+ 'toggle',+ 'gpt-4',+ '--provider',+ 'openai',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('--enable or --disable'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });});describe('delete', () => {@@ -137,4 +234,83 @@ describe('model command', () => {});});});++ describe('batch-toggle', () => {+ it('should batch enable models', async () => {+ mockTrpcClient.aiModel.batchToggleAiModels.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'model',+ 'batch-toggle',+ 'gpt-4',+ 'gpt-3.5',+ '--provider',+ 'openai',+ '--enable',+ ]);++ expect(mockTrpcClient.aiModel.batchToggleAiModels.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ enabled: true,+ id: 'openai',+ models: ['gpt-4', 'gpt-3.5'],+ }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('2 model(s)'));+ });++ it('should error when no flag specified', async () => {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'model',+ 'batch-toggle',+ 'gpt-4',+ '--provider',+ 'openai',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('--enable or --disable'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+ });++ describe('clear', () => {+ it('should clear all models for provider', async () => {+ mockTrpcClient.aiModel.clearModelsByProvider.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'model', 'clear', '--provider', 'openai', '--yes']);++ expect(mockTrpcClient.aiModel.clearModelsByProvider.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ providerId: 'openai' }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Cleared all models'));+ });++ it('should clear only remote models', async () => {+ mockTrpcClient.aiModel.clearRemoteModels.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'model',+ 'clear',+ '--provider',+ 'openai',+ '--remote',+ '--yes',+ ]);++ expect(mockTrpcClient.aiModel.clearRemoteModels.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ providerId: 'openai' }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('remote models'));+ });+ });});diff --git a/apps/cli/src/commands/model.ts b/apps/cli/src/commands/model.tsindex 02808882683..4eee3e6694e 100644--- a/apps/cli/src/commands/model.ts+++ b/apps/cli/src/commands/model.ts@@ -15,20 +15,29 @@ export function registerModelCommand(program: Command) {.description('List models for a provider').option('-L, --limit <n>', 'Maximum number of items', '50').option('--enabled', 'Only show enabled models')+ .option(+ '--type <type>',+ 'Filter by model type (chat|embedding|tts|stt|image|video|text2music|realtime)',+ ).option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)').action(async (providerId: string,- options: { enabled?: boolean; json?: string | boolean; limit?: string },+ options: { enabled?: boolean; json?: string | boolean; limit?: string; type?: string },) => {const client = await getTrpcClient();const input: Record<string, any> = { id: providerId };if (options.limit) input.limit = Number.parseInt(options.limit, 10);if (options.enabled) input.enabled = true;+ if (options.type) input.type = options.type;const result = await client.aiModel.getAiProviderModelList.query(input as any);- const items = Array.isArray(result) ? result : ((result as any).items ?? []);+ let items = Array.isArray(result) ? result : ((result as any).items ?? []);++ if (options.type) {+ items = items.filter((m: any) => m.type === options.type);+ }if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;@@ -83,6 +92,65 @@ export function registerModelCommand(program: Command) {if (meta.length > 0) console.log(pc.dim(meta.join(' Β· ')));});+ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ model+ .command('create')+ .description('Create a new model')+ .requiredOption('--id <id>', 'Model ID')+ .requiredOption('--provider <providerId>', 'Provider ID')+ .option('--display-name <name>', 'Display name')+ .option(+ '--type <type>',+ 'Model type (chat|embedding|tts|stt|image|video|text2music|realtime)',+ 'chat',+ )+ .action(+ async (options: { displayName?: string; id: string; provider: string; type?: string }) => {+ const client = await getTrpcClient();++ const input: Record<string, any> = {+ id: options.id,+ providerId: options.provider,+ type: options.type || 'chat',+ };+ if (options.displayName) input.displayName = options.displayName;++ const resultId = await client.aiModel.createAiModel.mutate(input as any);+ console.log(`${pc.green('β')} Created model ${pc.bold(resultId || options.id)}`);+ },+ );++ // ββ edit βββββββββββββββββββββββββββββββββββββββββββββ++ model+ .command('edit <id>')+ .description('Update model info')+ .requiredOption('--provider <providerId>', 'Provider ID')+ .option('--display-name <name>', 'Display name')+ .option('--type <type>', 'Model type (chat|embedding|tts|stt|image|video|text2music|realtime)')+ .action(+ async (id: string, options: { displayName?: string; provider: string; type?: string }) => {+ if (!options.displayName && !options.type) {+ log.error('No changes specified. Use --display-name or --type.');+ process.exit(1);+ }++ const client = await getTrpcClient();++ const value: Record<string, any> = {};+ if (options.displayName) value.displayName = options.displayName;+ if (options.type) value.type = options.type;++ await client.aiModel.updateAiModel.mutate({+ id,+ providerId: options.provider,+ value: value as any,+ });+ console.log(`${pc.green('β')} Updated model ${pc.bold(id)}`);+ },+ );+// ββ toggle ββββββββββββββββββββββββββββββββββββββββββββmodel@@ -130,4 +198,62 @@ export function registerModelCommand(program: Command) {await client.aiModel.removeAiModel.mutate({ id, providerId: options.provider });console.log(`${pc.green('β')} Deleted model ${pc.bold(id)}`);});++ // ββ batch-toggle ββββββββββββββββββββββββββββββββββββ++ model+ .command('batch-toggle <ids...>')+ .description('Enable or disable multiple models at once')+ .requiredOption('--provider <providerId>', 'Provider ID')+ .option('--enable', 'Enable the models')+ .option('--disable', 'Disable the models')+ .action(+ async (ids: string[], options: { disable?: boolean; enable?: boolean; provider: string }) => {+ if (options.enable === undefined && options.disable === undefined) {+ log.error('Specify --enable or --disable.');+ process.exit(1);+ }++ const client = await getTrpcClient();+ const enabled = options.enable === true;++ await client.aiModel.batchToggleAiModels.mutate({+ enabled,+ id: options.provider,+ models: ids,+ } as any);+ console.log(+ `${pc.green('β')} ${enabled ? 'Enabled' : 'Disabled'} ${ids.length} model(s) for provider ${pc.bold(options.provider)}`,+ );+ },+ );++ // ββ clear βββββββββββββββββββββββββββββββββββββββββββ++ model+ .command('clear')+ .description('Clear models for a provider')+ .requiredOption('--provider <providerId>', 'Provider ID')+ .option('--remote', 'Only clear remote/fetched models')+ .option('--yes', 'Skip confirmation prompt')+ .action(async (options: { provider: string; remote?: boolean; yes?: boolean }) => {+ const label = options.remote ? 'remote models' : 'all models';+ if (!options.yes) {+ const confirmed = await confirm(+ `Are you sure you want to clear ${label} for provider ${options.provider}?`,+ );+ if (!confirmed) {+ console.log('Cancelled.');+ return;+ }+ }++ const client = await getTrpcClient();+ if (options.remote) {+ await client.aiModel.clearRemoteModels.mutate({ providerId: options.provider } as any);+ } else {+ await client.aiModel.clearModelsByProvider.mutate({ providerId: options.provider } as any);+ }+ console.log(`${pc.green('β')} Cleared ${label} for provider ${pc.bold(options.provider)}`);+ });}diff --git a/apps/cli/src/commands/provider.test.ts b/apps/cli/src/commands/provider.test.tsindex 32f7cb1c239..f6ef6be6a0c 100644--- a/apps/cli/src/commands/provider.test.ts+++ b/apps/cli/src/commands/provider.test.ts@@ -7,10 +7,14 @@ import { registerProviderCommand } from './provider';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {aiProvider: {+ checkProviderConnectivity: { mutate: vi.fn() },+ createAiProvider: { mutate: vi.fn() },getAiProviderById: { query: vi.fn() },getAiProviderList: { query: vi.fn() },removeAiProvider: { mutate: vi.fn() },toggleProviderEnabled: { mutate: vi.fn() },+ updateAiProvider: { mutate: vi.fn() },+ updateAiProviderConfig: { mutate: vi.fn() },},},}));@@ -97,6 +101,195 @@ describe('provider command', () => {expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));});++ it('should exit when empty object returned', async () => {+ mockTrpcClient.aiProvider.getAiProviderById.query.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'view', 'nonexistent']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));+ });+ });++ describe('create', () => {+ it('should create a provider', async () => {+ mockTrpcClient.aiProvider.createAiProvider.mutate.mockResolvedValue('my-provider');++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'provider',+ 'create',+ '--id',+ 'my-provider',+ '-n',+ 'My Provider',+ '-d',+ 'Test desc',+ '--sdk-type',+ 'openai',+ ]);++ expect(mockTrpcClient.aiProvider.createAiProvider.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'my-provider',+ name: 'My Provider',+ description: 'Test desc',+ sdkType: 'openai',+ source: 'custom',+ }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Created provider'));+ });+ });++ describe('edit', () => {+ it('should update provider name', async () => {+ mockTrpcClient.aiProvider.updateAiProvider.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'edit', 'openai', '-n', 'New Name']);++ expect(mockTrpcClient.aiProvider.updateAiProvider.mutate).toHaveBeenCalledWith({+ id: 'openai',+ value: expect.objectContaining({ name: 'New Name' }),+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Updated provider'));+ });++ it('should error when no changes specified', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'edit', 'openai']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No changes'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+ });++ describe('config', () => {+ it('should set api key and base url', async () => {+ mockTrpcClient.aiProvider.updateAiProviderConfig.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'provider',+ 'config',+ 'openai',+ '--api-key',+ 'sk-test',+ '--base-url',+ 'https://api.test.com/v1',+ ]);++ expect(mockTrpcClient.aiProvider.updateAiProviderConfig.mutate).toHaveBeenCalledWith({+ id: 'openai',+ value: expect.objectContaining({+ keyVaults: { apiKey: 'sk-test', baseURL: 'https://api.test.com/v1' },+ }),+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Updated config'));+ });++ it('should enable response api', async () => {+ mockTrpcClient.aiProvider.updateAiProviderConfig.mutate.mockResolvedValue({});++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'provider',+ 'config',+ 'openai',+ '--enable-response-api',+ ]);++ expect(mockTrpcClient.aiProvider.updateAiProviderConfig.mutate).toHaveBeenCalledWith({+ id: 'openai',+ value: expect.objectContaining({+ config: { enableResponseApi: true },+ }),+ });+ });++ it('should show current config', async () => {+ mockTrpcClient.aiProvider.getAiProviderById.query.mockResolvedValue({+ checkModel: 'gpt-4o',+ fetchOnClient: true,+ id: 'openai',+ keyVaults: { apiKey: 'sk-test12345678', baseURL: 'https://api.test.com/v1' },+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'config', 'openai', '--show']);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Config for openai'));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('gpt-4o'));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('https://api.test.com/v1'));+ });++ it('should error when no config specified', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'config', 'openai']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No config specified'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+ });++ describe('test', () => {+ it('should show success when provider is reachable', async () => {+ mockTrpcClient.aiProvider.checkProviderConnectivity.mutate.mockResolvedValue({+ model: 'gpt-4o',+ ok: true,+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'test', 'openai', '--model', 'gpt-4o']);++ expect(mockTrpcClient.aiProvider.checkProviderConnectivity.mutate).toHaveBeenCalledWith({+ id: 'openai',+ model: 'gpt-4o',+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('reachable'));+ });++ it('should show failure and exit 1', async () => {+ mockTrpcClient.aiProvider.checkProviderConnectivity.mutate.mockResolvedValue({+ error: 'InvalidProviderAPIKey',+ model: 'gpt-4o',+ ok: false,+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'test', 'openai', '--model', 'gpt-4o']);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('check failed'));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('InvalidProviderAPIKey'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should output JSON', async () => {+ const result = { model: 'gpt-4o', ok: true };+ mockTrpcClient.aiProvider.checkProviderConnectivity.mutate.mockResolvedValue(result);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'provider',+ 'test',+ 'openai',+ '--model',+ 'gpt-4o',+ '--json',+ ]);++ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(result, null, 2));+ });});describe('toggle', () => {@@ -111,6 +304,14 @@ describe('provider command', () => {id: 'openai',});});++ it('should error when no flag specified', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'provider', 'toggle', 'openai']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('--enable or --disable'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });});describe('delete', () => {diff --git a/apps/cli/src/commands/provider.ts b/apps/cli/src/commands/provider.tsindex f184d952167..ec70fe86aad 100644--- a/apps/cli/src/commands/provider.ts+++ b/apps/cli/src/commands/provider.ts@@ -50,7 +50,7 @@ export function registerProviderCommand(program: Command) {const client = await getTrpcClient();const result = await client.aiProvider.getAiProviderById.query({ id });- if (!result) {+ if (!result || !(result as any).id) {log.error(`Provider not found: ${id}`);process.exit(1);return;@@ -63,13 +63,216 @@ export function registerProviderCommand(program: Command) {}const r = result as any;- console.log(pc.bold(r.name || r.id || 'Unknown'));+ console.log(pc.bold(r.name || r.id));const meta: string[] = [];if (r.enabled !== undefined) meta.push(r.enabled ? 'Enabled' : 'Disabled');if (r.source) meta.push(`Source: ${r.source}`);if (meta.length > 0) console.log(pc.dim(meta.join(' Β· ')));});+ // ββ create ββββββββββββββββββββββββββββββββββββββββββββ++ provider+ .command('create')+ .description('Create a new AI provider')+ .requiredOption('--id <id>', 'Provider ID')+ .requiredOption('-n, --name <name>', 'Provider name')+ .option('-s, --source <source>', 'Source type (builtin|custom)', 'custom')+ .option('-d, --description <desc>', 'Provider description')+ .option('--logo <logo>', 'Provider logo URL')+ .option('--sdk-type <sdkType>', 'SDK type (openai|anthropic|azure|bedrock|...)')+ .action(+ async (options: {+ description?: string;+ id: string;+ logo?: string;+ name: string;+ sdkType?: string;+ source?: string;+ }) => {+ const client = await getTrpcClient();++ const input: Record<string, any> = {+ id: options.id,+ name: options.name,+ source: options.source || 'custom',+ };+ if (options.description) input.description = options.description;+ if (options.logo) input.logo = options.logo;+ if (options.sdkType) input.sdkType = options.sdkType;++ const resultId = await client.aiProvider.createAiProvider.mutate(input as any);+ console.log(`${pc.green('β')} Created provider ${pc.bold(resultId || options.id)}`);+ },+ );++ // ββ edit βββββββββββββββββββββββββββββββββββββββββββββ++ provider+ .command('edit <id>')+ .description('Update provider info')+ .option('-n, --name <name>', 'Provider name')+ .option('-d, --description <desc>', 'Provider description')+ .option('--logo <logo>', 'Provider logo URL')+ .option('--sdk-type <sdkType>', 'SDK type')+ .action(+ async (+ id: string,+ options: { description?: string; logo?: string; name?: string; sdkType?: string },+ ) => {+ if (!options.name && !options.description && !options.logo && !options.sdkType) {+ log.error('No changes specified. Use --name, --description, --logo, or --sdk-type.');+ process.exit(1);+ }++ const client = await getTrpcClient();++ const value: Record<string, any> = {};+ if (options.name) value.name = options.name;+ if (options.description !== undefined) value.description = options.description;+ if (options.logo !== undefined) value.logo = options.logo;+ if (options.sdkType) value.sdkType = options.sdkType;++ await client.aiProvider.updateAiProvider.mutate({ id, value: value as any });+ console.log(`${pc.green('β')} Updated provider ${pc.bold(id)}`);+ },+ );++ // ββ config ββββββββββββββββββββββββββββββββββββββββββ++ provider+ .command('config <id>')+ .description('Configure provider settings (API key, base URL, etc.)')+ .option('--api-key <key>', 'Set API key')+ .option('--base-url <url>', 'Set base URL')+ .option('--check-model <model>', 'Set connectivity check model')+ .option('--enable-response-api', 'Enable Response API mode (OpenAI)')+ .option('--disable-response-api', 'Disable Response API mode')+ .option('--fetch-on-client', 'Enable fetching models on client side')+ .option('--no-fetch-on-client', 'Disable fetching models on client side')+ .option('--show', 'Show current config')+ .option('--json [fields]', 'Output JSON (with --show)')+ .action(+ async (+ id: string,+ options: {+ apiKey?: string;+ baseUrl?: string;+ checkModel?: string;+ disableResponseApi?: boolean;+ enableResponseApi?: boolean;+ fetchOnClient?: boolean;+ json?: string | boolean;+ show?: boolean;+ },+ ) => {+ // lobehub is a platform-managed provider, users cannot configure its API key or base URL+ if (id === 'lobehub' && (options.apiKey !== undefined || options.baseUrl !== undefined)) {+ log.error(+ `Provider "lobehub" is managed by the LobeHub platform. You cannot set --api-key or --base-url for it.`,+ );+ process.exit(1);+ }++ const client = await getTrpcClient();++ // Show current config+ if (options.show) {+ const detail = await client.aiProvider.getAiProviderById.query({ id });+ if (!detail) {+ log.error(`Provider not found: ${id}`);+ process.exit(1);+ return;+ }++ const config: Record<string, any> = {+ checkModel: (detail as any).checkModel || '',+ fetchOnClient: (detail as any).fetchOnClient ?? false,+ keyVaults: (detail as any).keyVaults || {},+ };++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(config, fields);+ } else {+ console.log(pc.bold(`Config for ${id}`));+ if (config.checkModel) console.log(` Check Model: ${config.checkModel}`);+ console.log(` Fetch on Client: ${config.fetchOnClient ? pc.green('β') : pc.dim('β')}`);+ const vaults = config.keyVaults;+ if (vaults.apiKey)+ console.log(` API Key: ${pc.dim(vaults.apiKey.slice(0, 8) + '...')}`);+ if (vaults.baseURL) console.log(` Base URL: ${vaults.baseURL}`);+ }+ return;+ }++ // Build config update+ const hasKeyVaults = options.apiKey !== undefined || options.baseUrl !== undefined;+ const hasConfig = options.enableResponseApi || options.disableResponseApi;+ const hasOther = options.checkModel !== undefined || options.fetchOnClient !== undefined;++ if (!hasKeyVaults && !hasConfig && !hasOther) {+ log.error(+ 'No config specified. Use --api-key, --base-url, --check-model, --enable-response-api, --fetch-on-client, or --show.',+ );+ process.exit(1);+ }++ const input: Record<string, any> = {};++ if (hasKeyVaults) {+ const keyVaults: Record<string, string> = {};+ if (options.apiKey !== undefined) keyVaults.apiKey = options.apiKey;+ if (options.baseUrl !== undefined) keyVaults.baseURL = options.baseUrl;+ input.keyVaults = keyVaults;+ }++ if (hasConfig) {+ input.config = { enableResponseApi: !!options.enableResponseApi };+ }++ if (options.checkModel !== undefined) input.checkModel = options.checkModel;+ if (options.fetchOnClient !== undefined) input.fetchOnClient = options.fetchOnClient;++ await client.aiProvider.updateAiProviderConfig.mutate({ id, value: input as any });+ console.log(`${pc.green('β')} Updated config for provider ${pc.bold(id)}`);+ },+ );++ // ββ test βββββββββββββββββββββββββββββββββββββββββββββ++ provider+ .command('test <id>')+ .description('Test provider connectivity')+ .option('-m, --model <model>', 'Model to test with (defaults to provider checkModel)')+ .option('--json', 'Output result as JSON')+ .action(async (id: string, options: { json?: boolean; model?: string }) => {+ const client = await getTrpcClient();++ console.log(`${pc.yellow('β―')} Testing provider ${pc.bold(id)}...`);++ const result = (await client.aiProvider.checkProviderConnectivity.mutate({+ id,+ model: options.model,+ })) as any;++ if (options.json) {+ outputJson(result);+ return;+ }++ if (result.ok) {+ console.log(+ `${pc.green('β')} Provider ${pc.bold(id)} is reachable (model: ${result.model})`,+ );+ } else {+ console.log(`${pc.red('β')} Provider ${pc.bold(id)} check failed`);+ if (result.model) console.log(` Model: ${result.model}`);+ if (result.error) console.log(` Error: ${pc.dim(result.error)}`);+ process.exit(1);+ }+ });+// ββ toggle ββββββββββββββββββββββββββββββββββββββββββββproviderdiff --git a/apps/cli/src/commands/skill.test.ts b/apps/cli/src/commands/skill.test.tsindex 2db2e0202b5..0205b4fa8db 100644--- a/apps/cli/src/commands/skill.test.ts+++ b/apps/cli/src/commands/skill.test.ts@@ -2,7 +2,7 @@ import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { log } from '../utils/logger';-import { registerSkillCommand } from './skill';+import { detectSourceType, registerSkillCommand } from './skill';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {@@ -232,8 +232,8 @@ describe('skill command', () => {});});- describe('import-github', () => {- it('should import from GitHub', async () => {+ describe('install', () => {+ it('should install from GitHub URL', async () => {mockTrpcClient.agentSkills.importFromGitHub.mutate.mockResolvedValue({id: 'imported',name: 'GH Skill',@@ -244,37 +244,111 @@ describe('skill command', () => {'node','test','skill',- 'import-github',- '--url',+ 'install','https://github.com/user/repo',]);expect(mockTrpcClient.agentSkills.importFromGitHub.mutate).toHaveBeenCalledWith(expect.objectContaining({ gitUrl: 'https://github.com/user/repo' }),);- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Imported'));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Installed'));});- });- describe('import-market', () => {- it('should install from marketplace', async () => {- mockTrpcClient.agentSkills.importFromMarket.mutate.mockResolvedValue({ id: 'mk1' });+ it('should install from GitHub shorthand (owner/repo)', async () => {+ mockTrpcClient.agentSkills.importFromGitHub.mutate.mockResolvedValue({+ id: 'imported',+ name: 'GH Skill',+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'skill', 'install', 'lobehub/skill-repo']);++ expect(mockTrpcClient.agentSkills.importFromGitHub.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ gitUrl: 'https://github.com/lobehub/skill-repo' }),+ );+ });++ it('should install from GitHub with --branch', async () => {+ mockTrpcClient.agentSkills.importFromGitHub.mutate.mockResolvedValue({ id: 'imported' });const program = createProgram();await program.parseAsync(['node','test','skill',- 'import-market',- '--identifier',- 'some-skill',+ 'install',+ 'lobehub/skill-repo',+ '--branch',+ 'dev',]);+ expect(mockTrpcClient.agentSkills.importFromGitHub.mutate).toHaveBeenCalledWith({+ branch: 'dev',+ gitUrl: 'https://github.com/lobehub/skill-repo',+ });+ });++ it('should install from ZIP URL', async () => {+ mockTrpcClient.agentSkills.importFromUrl.mutate.mockResolvedValue({ id: 'zip1' });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'skill',+ 'install',+ 'https://example.com/skill.zip',+ ]);++ expect(mockTrpcClient.agentSkills.importFromUrl.mutate).toHaveBeenCalledWith({+ url: 'https://example.com/skill.zip',+ });+ });++ it('should install from marketplace by identifier', async () => {+ mockTrpcClient.agentSkills.importFromMarket.mutate.mockResolvedValue({ id: 'mk1' });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'skill', 'install', 'some-skill']);+expect(mockTrpcClient.agentSkills.importFromMarket.mutate).toHaveBeenCalledWith({identifier: 'some-skill',});expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('some-skill'));});++ it('should work with alias "i"', async () => {+ mockTrpcClient.agentSkills.importFromMarket.mutate.mockResolvedValue({ id: 'mk1' });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'skill', 'i', 'some-skill']);++ expect(mockTrpcClient.agentSkills.importFromMarket.mutate).toHaveBeenCalledWith({+ identifier: 'some-skill',+ });+ });+ });++ describe('detectSourceType', () => {+ it('should detect GitHub URLs', () => {+ expect(detectSourceType('https://github.com/user/repo')).toBe('github');+ expect(detectSourceType('http://github.com/user/repo')).toBe('github');+ });++ it('should detect GitHub shorthand', () => {+ expect(detectSourceType('lobehub/skill-repo')).toBe('github');+ expect(detectSourceType('user/repo-name')).toBe('github');+ });++ it('should detect ZIP/other URLs', () => {+ expect(detectSourceType('https://example.com/skill.zip')).toBe('url');+ expect(detectSourceType('https://cdn.example.com/pkg')).toBe('url');+ });++ it('should detect marketplace identifiers', () => {+ expect(detectSourceType('my-skill')).toBe('market');+ expect(detectSourceType('some-cool-skill')).toBe('market');+ });});describe('resources', () => {diff --git a/apps/cli/src/commands/skill.ts b/apps/cli/src/commands/skill.tsindex afae9a9367e..a943b9b4ce0 100644--- a/apps/cli/src/commands/skill.ts+++ b/apps/cli/src/commands/skill.ts@@ -5,6 +5,25 @@ import { getTrpcClient } from '../api/client';import { confirm, outputJson, printTable, truncate } from '../utils/format';import { log } from '../utils/logger';+type SourceType = 'github' | 'market' | 'url';++export function detectSourceType(source: string): SourceType {+ // GitHub URL: https://github.com/owner/repo+ if (source.startsWith('https://github.com/') || source.startsWith('http://github.com/')) {+ return 'github';+ }+ // GitHub shorthand: owner/repo (contains exactly one slash, no dots or colons)+ if (/^[\w-]+\/[\w.-]+$/.test(source)) {+ return 'github';+ }+ // Other URLs (ZIP, etc.)+ if (source.startsWith('https://') || source.startsWith('http://')) {+ return 'url';+ }+ // Marketplace identifier+ return 'market';+}+export function registerSkillCommand(program: Command) {const skill = program.command('skill').description('Manage agent skills');@@ -209,54 +228,40 @@ export function registerSkillCommand(program: Command) {printTable(rows, ['ID', 'NAME', 'DESCRIPTION']);});- // ββ import-github βββββββββββββββββββββββββββββββββββββ+ // ββ install (alias: i) βββββββββββββββββββββββββββββββββββskill- .command('import-github')- .description('Import a skill from GitHub')- .requiredOption('--url <gitUrl>', 'GitHub repository URL')- .option('--branch <branch>', 'Branch name')- .action(async (options: { branch?: string; url: string }) => {+ .command('install <source>')+ .alias('i')+ .description(+ 'Install a skill (auto-detects: GitHub URL/shorthand, ZIP URL, or marketplace identifier)',+ )+ .option('--branch <branch>', 'Branch name (GitHub only)')+ .action(async (source: string, options: { branch?: string }) => {const client = await getTrpcClient();+ const sourceType = detectSourceType(source);- const input: { branch?: string; gitUrl: string } = { gitUrl: options.url };- if (options.branch) input.branch = options.branch;-- const result = await client.agentSkills.importFromGitHub.mutate(input);- const r = result as any;- console.log(`${pc.green('β')} Imported skill from GitHub ${pc.bold(r.id || r.name || '')}`);- });-- // ββ import-url ββββββββββββββββββββββββββββββββββββββββ-- skill- .command('import-url')- .description('Import a skill from a ZIP URL')- .requiredOption('--url <zipUrl>', 'URL to skill ZIP file')- .action(async (options: { url: string }) => {- const client = await getTrpcClient();-- const result = await client.agentSkills.importFromUrl.mutate({ url: options.url });- const r = result as any;- console.log(`${pc.green('β')} Imported skill from URL ${pc.bold(r.id || r.name || '')}`);- });-- // ββ import-market βββββββββββββββββββββββββββββββββββββ-- skill- .command('import-market')- .description('Install a skill from the marketplace')- .requiredOption('-i, --identifier <id>', 'Skill identifier in marketplace')- .action(async (options: { identifier: string }) => {- const client = await getTrpcClient();+ if (sourceType === 'github') {+ const gitUrl = source.startsWith('https://') ? source : `https://github.com/${source}`;+ const input: { branch?: string; gitUrl: string } = { gitUrl };+ if (options.branch) input.branch = options.branch;- const result = await client.agentSkills.importFromMarket.mutate({- identifier: options.identifier,- });- const r = result as any;- console.log(- `${pc.green('β')} Installed skill ${pc.bold(options.identifier)} ${r.id ? `(${r.id})` : ''}`,- );+ const result = await client.agentSkills.importFromGitHub.mutate(input);+ const r = result as any;+ console.log(+ `${pc.green('β')} Installed skill from GitHub ${pc.bold(r.id || r.name || '')}`,+ );+ } else if (sourceType === 'url') {+ const result = await client.agentSkills.importFromUrl.mutate({ url: source });+ const r = result as any;+ console.log(`${pc.green('β')} Installed skill from URL ${pc.bold(r.id || r.name || '')}`);+ } else {+ const result = await client.agentSkills.importFromMarket.mutate({ identifier: source });+ const r = result as any;+ console.log(+ `${pc.green('β')} Installed skill ${pc.bold(source)} ${r.id ? `(${r.id})` : ''}`,+ );+ }});// ββ resources βββββββββββββββββββββββββββββββββββββββββdiff --git a/apps/cli/src/commands/topic.ts b/apps/cli/src/commands/topic.tsindex d79faaf1e66..3ee5cee8af4 100644--- a/apps/cli/src/commands/topic.ts+++ b/apps/cli/src/commands/topic.ts@@ -14,7 +14,6 @@ export function registerTopicCommand(program: Command) {.command('list').description('List topics').option('--agent-id <id>', 'Filter by agent ID')- .option('--session-id <id>', 'Filter by session ID').option('-L, --limit <n>', 'Page size', '30').option('--page <n>', 'Page number', '1').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')@@ -24,13 +23,11 @@ export function registerTopicCommand(program: Command) {json?: string | boolean;limit?: string;page?: string;- sessionId?: string;}) => {const client = await getTrpcClient();const input: Record<string, any> = {};if (options.agentId) input.agentId = options.agentId;- if (options.sessionId) input.sessionId = options.sessionId;if (options.limit) input.pageSize = Number.parseInt(options.limit, 10);if (options.page) input.current = Number.parseInt(options.page, 10);@@ -98,27 +95,18 @@ export function registerTopicCommand(program: Command) {.description('Create a topic').requiredOption('-t, --title <title>', 'Topic title').option('--agent-id <id>', 'Agent ID')- .option('--session-id <id>', 'Session ID').option('--favorite', 'Mark as favorite')- .action(- async (options: {- agentId?: string;- favorite?: boolean;- sessionId?: string;- title: string;- }) => {- const client = await getTrpcClient();+ .action(async (options: { agentId?: string; favorite?: boolean; title: string }) => {+ const client = await getTrpcClient();- const input: Record<string, any> = { title: options.title };- if (options.agentId) input.agentId = options.agentId;- if (options.sessionId) input.sessionId = options.sessionId;- if (options.favorite) input.favorite = true;+ const input: Record<string, any> = { title: options.title };+ if (options.agentId) input.agentId = options.agentId;+ if (options.favorite) input.favorite = true;- const result = await client.topic.createTopic.mutate(input as any);- const r = result as any;- console.log(`${pc.green('β')} Created topic ${pc.bold(r.id || r)}`);- },- );+ const result = await client.topic.createTopic.mutate(input as any);+ const r = result as any;+ console.log(`${pc.green('β')} Created topic ${pc.bold(r.id || r)}`);+ });// ββ edit ββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/apps/cli/src/settings/index.ts b/apps/cli/src/settings/index.tsindex 01d129bc503..f98ad52cf79 100644--- a/apps/cli/src/settings/index.ts+++ b/apps/cli/src/settings/index.ts@@ -10,7 +10,8 @@ export interface StoredSettings {serverUrl?: string;}-const SETTINGS_DIR = path.join(os.homedir(), '.lobehub');+const LOBEHUB_DIR_NAME = process.env.LOBEHUB_CLI_HOME || '.lobehub';+const SETTINGS_DIR = path.join(os.homedir(), LOBEHUB_DIR_NAME);const SETTINGS_FILE = path.join(SETTINGS_DIR, 'settings.json');function normalizeUrl(url: string | undefined): string | undefined {diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 6ff0f38f838..afc2324585b 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1194,7 +1194,7 @@ describe('MessageModel Query Tests', () => {});describe('queryAll', () => {- it('should return all messages belonging to the user in ascending order', async () => {+ it('should return all messages belonging to the user in descending order', async () => {// Create test dataawait serverDB.insert(messages).values([{@@ -1223,10 +1223,10 @@ describe('MessageModel Query Tests', () => {// Call queryAll methodconst result = await messageModel.queryAll();- // Assert result+ // Assert result - descending by createdAtexpect(result).toHaveLength(2);- expect(result[0].id).toBe('1');- expect(result[1].id).toBe('2');+ expect(result[0].id).toBe('2');+ expect(result[1].id).toBe('1');});});diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 0bae4963cbc..1857e1cf4d7 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -1055,12 +1055,17 @@ export class MessageModel {return result[0];};- queryAll = async () => {+ queryAll = async (params?: { current?: number; pageSize?: number }) => {+ const { current = 0, pageSize = 100 } = params ?? {};+ const offset = current * pageSize;+const result = await this.db.select().from(messages)- .orderBy(messages.createdAt)- .where(eq(messages.userId, this.userId));+ .where(eq(messages.userId, this.userId))+ .orderBy(desc(messages.createdAt))+ .limit(pageSize)+ .offset(offset);return result as DBMessageItem[];};diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.tsindex dfae7ebb4e1..1d3531e1cd9 100644--- a/packages/database/src/repositories/aiInfra/index.ts+++ b/packages/database/src/repositories/aiInfra/index.ts@@ -394,6 +394,7 @@ export class AiInfraRepos {enabled?: boolean;limit?: number;offset?: number;+ type?: string;},) => {const aiModels = await this.aiModelModel.getModelListByProviderId(providerId);@@ -417,6 +418,10 @@ export class AiInfraRepos {list = list.filter((m) => m.enabled === options.enabled);}+ if (options?.type) {+ list = list.filter((m) => m.type === options.type);+ }+if (typeof options?.offset === 'number' || typeof options?.limit === 'number') {const offset = Math.max(0, options?.offset ?? 0);const limit = options?.limit;diff --git a/src/envs/file.ts b/src/envs/file.tsindex a69cc0e9479..cd84dbffe6d 100644--- a/src/envs/file.ts+++ b/src/envs/file.ts@@ -38,7 +38,7 @@ export const getFileConfig = () => {S3_PUBLIC_DOMAIN,S3_REGION: process.env.S3_REGION,S3_SECRET_ACCESS_KEY: process.env.S3_SECRET_ACCESS_KEY,- S3_SET_ACL: process.env.S3_SET_ACL !== '0',+ S3_SET_ACL: process.env.S3_SET_ACL === '1',},server: {CHUNKS_AUTO_EMBEDDING: z.boolean(),diff --git a/src/server/routers/lambda/__tests__/aiProvider.test.ts b/src/server/routers/lambda/__tests__/aiProvider.test.tsindex 2836a007629..4a4c9ba947b 100644--- a/src/server/routers/lambda/__tests__/aiProvider.test.ts+++ b/src/server/routers/lambda/__tests__/aiProvider.test.ts@@ -1,3 +1,4 @@+// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';import { AiProviderModel } from '@/database/models/aiProvider';diff --git a/src/server/routers/lambda/aiModel.ts b/src/server/routers/lambda/aiModel.tsindex 015db79f5ba..468e3cb90a9 100644--- a/src/server/routers/lambda/aiModel.ts+++ b/src/server/routers/lambda/aiModel.ts@@ -91,6 +91,7 @@ export const aiModelRouter = router({id: z.string(),limit: z.number().int().min(1).max(200).optional(),offset: z.number().int().min(0).optional(),+ type: z.string().optional(),}),).query(async ({ ctx, input }): Promise<AiProviderModelListItem[]> => {@@ -98,6 +99,7 @@ export const aiModelRouter = router({enabled: input.enabled,limit: input.limit,offset: input.offset,+ type: input.type,});}),diff --git a/src/server/routers/lambda/aiProvider.ts b/src/server/routers/lambda/aiProvider.tsindex cb83890d379..87c4b83cdc1 100644--- a/src/server/routers/lambda/aiProvider.ts+++ b/src/server/routers/lambda/aiProvider.ts@@ -7,6 +7,7 @@ import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { getServerGlobalConfig } from '@/server/globalConfig';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { type AiProviderDetailItem, type AiProviderRuntimeState } from '@/types/aiProvider';import {CreateAiProviderSchema,@@ -36,6 +37,53 @@ const aiProviderProcedure = authedProcedure.use(serverDatabase).use(async (opts)});export const aiProviderRouter = router({+ checkProviderConnectivity: aiProviderProcedure+ .input(+ z.object({+ id: z.string(),+ model: z.string().optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ // Get the provider detail to find checkModel+ const detail = await ctx.aiInfraRepos.getAiProviderDetail(+ input.id,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );++ const model = input.model || detail?.checkModel;+ if (!model) {+ return { error: 'No check model configured. Use --model to specify one.', ok: false };+ }++ try {+ const modelRuntime = await initModelRuntimeFromDB(ctx.serverDB, ctx.userId, input.id);++ const response = await modelRuntime.chat({+ messages: [{ content: 'Hi', role: 'user' }],+ model,+ stream: false,+ temperature: 0,+ });++ // If we get a response without error, connectivity is ok+ if (response.ok) {+ return { model, ok: true };+ }++ const errorBody = await response.text();+ return { error: errorBody, model, ok: false, status: response.status };+ } catch (error: any) {+ const errorType = error.errorType || error.type;+ const msg = errorType+ ? errorType+ : typeof error === 'string'+ ? error+ : error.message || (typeof error === 'object' ? JSON.stringify(error) : String(error));+ return { error: msg, model, ok: false };+ }+ }),+createAiProvider: aiProviderProcedure.input(CreateAiProviderSchema).mutation(async ({ input, ctx }) => {diff --git a/src/server/routers/lambda/image/index.test.ts b/src/server/routers/lambda/image/index.test.tsindex d383271bbb8..45dfe077a5e 100644--- a/src/server/routers/lambda/image/index.test.ts+++ b/src/server/routers/lambda/image/index.test.ts@@ -28,11 +28,6 @@ vi.mock('debug', () => ({default: () => () => {},}));-// Mock auth related-vi.mock('@lobechat/utils/server', () => ({- getXorPayload: vi.fn(() => ({})),-}));-// Mock database adaptorvi.mock('@/database/core/db-adaptor', () => ({getServerDB: vi.fn(async () => mockServerDB),@@ -87,7 +82,6 @@ describe('imageRouter', () => {const createMockCtx = (overrides = {}) => ({userId: mockUserId,- authorizationHeader: 'mock-auth-header',...overrides,});diff --git a/src/server/routers/lambda/image/index.ts b/src/server/routers/lambda/image/index.tsindex 3f8ec4e6f78..278de4eb26d 100644--- a/src/server/routers/lambda/image/index.ts+++ b/src/server/routers/lambda/image/index.ts@@ -7,7 +7,7 @@ import { AsyncTaskModel } from '@/database/models/asyncTask';import { type NewGeneration, type NewGenerationBatch } from '@/database/schemas';import { asyncTasks, generationBatches, generations } from '@/database/schemas';import { authedProcedure, router } from '@/libs/trpc/lambda';-import { keyVaults, serverDatabase } from '@/libs/trpc/lambda/middleware';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { createAsyncCaller } from '@/server/routers/async/caller';import { FileService } from '@/server/services/file';import {@@ -22,26 +22,16 @@ import { validateNoUrlsInConfig } from './utils';const log = debug('lobe-image:lambda');-const imageProcedure = authedProcedure- .use(keyVaults)- .use(serverDatabase)- .use(async (opts) => {- const { ctx } = opts;-- const { apiKey } = ctx.jwtPayload;- if (apiKey) {- log('API key found in jwtPayload: %s', apiKey);- } else {- log('No API key found in jwtPayload');- }+const imageProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;- return opts.next({- ctx: {- asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),- fileService: new FileService(ctx.serverDB, ctx.userId),- },- });+ return opts.next({+ ctx: {+ asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),+ fileService: new FileService(ctx.serverDB, ctx.userId),+ },});+});const createImageInputSchema = z.object({generationTopicId: z.string(),@@ -288,7 +278,10 @@ export const imageRouter = router({}}- const createdGenerations = generationsWithTasks.map((item) => item.generation);+ const createdGenerations = generationsWithTasks.map((item) => ({+ ...item.generation,+ asyncTaskId: item.asyncTaskId,+ }));log('Image creation process completed successfully: %O', {batchId: createdBatch.id,generationCount: createdGenerations.length,diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex c8e31896b19..641caf021ed 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -33,6 +33,7 @@ import { homeRouter } from './home';import { imageRouter } from './image';import { importerRouter } from './importer';import { klavisRouter } from './klavis';+import { knowledgeRouter } from './knowledge';import { knowledgeBaseRouter } from './knowledgeBase';import { marketRouter } from './market';import { messageRouter } from './message';@@ -80,6 +81,7 @@ export const lambdaRouter = router({image: imageRouter,importer: importerRouter,klavis: klavisRouter,+ knowledge: knowledgeRouter,knowledgeBase: knowledgeBaseRouter,market: marketRouter,message: messageRouter,diff --git a/src/server/routers/lambda/knowledge.ts b/src/server/routers/lambda/knowledge.tsindex 4b9f39bede4..845de81b108 100644--- a/src/server/routers/lambda/knowledge.ts+++ b/src/server/routers/lambda/knowledge.ts@@ -65,7 +65,7 @@ export const knowledgeRouter = router({embeddingError: embeddingTask?.error ?? null,embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,- url: await ctx.fileService.getFullFileUrl(item.url!),+ url: item.url ? await ctx.fileService.getFullFileUrl(item.url) : undefined,} as FileListItem);} else {// Document item - no chunk processing needed, includes editorDatadiff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.tsindex c6d7acd8987..fc3f5947cbe 100644--- a/src/server/routers/lambda/message.ts+++ b/src/server/routers/lambda/message.ts@@ -51,7 +51,7 @@ export const messageRouter = router({/*** Cancel compression by deleting the compression group and restoring original messages*/-cancelCompression: messageProcedure+ cancelCompression: messageProcedure.input(z.object({agentId: z.string(),@@ -72,8 +72,20 @@ cancelCompression: messageProcedure});}),--count: messageProcedure+ listAll: messageProcedure+ .input(+ z+ .object({+ current: z.number().optional(),+ pageSize: z.number().optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) => {+ return ctx.messageModel.queryAll(input);+ }),++ count: messageProcedure.input(z.object({@@ -87,9 +99,7 @@ count: messageProcedurereturn ctx.messageModel.count(input);}),---countWords: messageProcedure+ countWords: messageProcedure.input(z.object({@@ -103,13 +113,12 @@ countWords: messageProcedurereturn ctx.messageModel.countWords(input);}),--/**+ /*** Create a compression group for old messages* Creates a placeholder group, marks messages as compressed* Returns messages to summarize for frontend AI generation*/-createCompressionGroup: messageProcedure+ createCompressionGroup: messageProcedure.input(z.object({agentId: z.string(),@@ -130,9 +139,7 @@ createCompressionGroup: messageProcedure});}),---createMessage: messageProcedure+ createMessage: messageProcedure.input(CreateNewMessageParamsSchema).mutation(async ({ input, ctx }) => {// If there's no agentId but has sessionId, resolve agentId from sessionId@@ -145,11 +152,10 @@ createMessage: messageProcedurereturn ctx.messageService.createMessage({ ...input, agentId } as any);}),-/*** Finalize compression by updating the group with generated summary*/-finalizeCompression: messageProcedure+ finalizeCompression: messageProcedure.input(z.object({agentId: z.string(),diff --git a/src/server/routers/lambda/video/index.ts b/src/server/routers/lambda/video/index.tsindex b7d663ebd08..298eb31b89d 100644--- a/src/server/routers/lambda/video/index.ts+++ b/src/server/routers/lambda/video/index.ts@@ -17,7 +17,7 @@ import {} from '@/database/schemas';import { appEnv } from '@/envs/app';import { authedProcedure, router } from '@/libs/trpc/lambda';-import { keyVaults, serverDatabase } from '@/libs/trpc/lambda/middleware';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { FileService } from '@/server/services/file';import {@@ -29,19 +29,16 @@ import {const log = debug('lobe-video:lambda');-const videoProcedure = authedProcedure- .use(keyVaults)- .use(serverDatabase)- .use(async (opts) => {- const { ctx } = opts;+const videoProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;- return opts.next({- ctx: {- asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),- fileService: new FileService(ctx.serverDB, ctx.userId),- },- });+ return opts.next({+ ctx: {+ asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),+ fileService: new FileService(ctx.serverDB, ctx.userId),+ },});+});const createVideoInputSchema = z.object({generationTopicId: z.string(),@@ -263,7 +260,7 @@ export const videoRouter = router({return {data: {batch: createdBatch,- generations: [createdGeneration],+ generations: [{ ...createdGeneration, asyncTaskId }],},success: true,};diff --git a/src/server/services/file/impls/s3.ts b/src/server/services/file/impls/s3.tsindex 787ab7520c3..7d8b91e413c 100644--- a/src/server/services/file/impls/s3.ts+++ b/src/server/services/file/impls/s3.ts@@ -65,16 +65,17 @@ export class S3StaticFileImpl implements FileServiceImpl {key = extractedKey;}- // If bucket is not set public read, the preview address needs to be regenerated each time- if (!fileEnv.S3_SET_ACL) {+ // If bucket is not set public read, or S3_PUBLIC_DOMAIN is not configured,+ // the preview address needs to be regenerated each time via presigned URL+ if (!fileEnv.S3_SET_ACL || !fileEnv.S3_PUBLIC_DOMAIN) {return await this.createPreSignedUrlForPreview(key, expiresIn);}if (fileEnv.S3_ENABLE_PATH_STYLE) {- return urlJoin(fileEnv.S3_PUBLIC_DOMAIN!, fileEnv.S3_BUCKET!, key);+ return urlJoin(fileEnv.S3_PUBLIC_DOMAIN, fileEnv.S3_BUCKET!, key);}- return urlJoin(fileEnv.S3_PUBLIC_DOMAIN!, key);+ return urlJoin(fileEnv.S3_PUBLIC_DOMAIN, key);}async getKeyFromFullUrl(url: string): Promise<string | null> {