mirror of
https://github.com/lobehub/lobe-chat.git
synced 2026-06-15 12:10:16 +00:00
Compare commits
258 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0469464c37 | |||
| b6a47debfd | |||
| 147ff3976f | |||
| 034c7c203b | |||
| b0b6684294 | |||
| 36d2427947 | |||
| 4d15979fab | |||
| 53786e30b6 | |||
| 7300b53e99 | |||
| 6f3897a6e8 | |||
| a6e330cfa9 | |||
| accc173068 | |||
| 81ab8aa07b | |||
| 12ee7c9e9a | |||
| 8d8b60e4f9 | |||
| 19aedcdf56 | |||
| 3bb09e0ef9 | |||
| 13fc65faa2 | |||
| de8761cf29 | |||
| 4f2f0055e1 | |||
| 2290929255 | |||
| a2eab24536 | |||
| b279c108b6 | |||
| 7a6fd8e865 | |||
| 1206db7c12 | |||
| bd61b61843 | |||
| 0c49b0a039 | |||
| 1beb9d4eb6 | |||
| 021fd07deb | |||
| 33f729cd1a | |||
| 8b3c871d08 | |||
| bd8143c464 | |||
| 68762fc4ae | |||
| 1a58d530fb | |||
| ca01385666 | |||
| 5231bbbcac | |||
| 496b10f5c0 | |||
| 1800110748 | |||
| b068c427d4 | |||
| d5eec83a72 | |||
| 6c9cbb07ee | |||
| b92ee0ade5 | |||
| 3327b293d6 | |||
| d7e5d4645d | |||
| 918e4a8fa1 | |||
| f58015bb23 | |||
| e6244aaea6 | |||
| e9d43cb43f | |||
| 5b03f009ee | |||
| 25cf3bfafd | |||
| 3cb7206d90 | |||
| e364b9a516 | |||
| a7e3d198df | |||
| 14cd81b624 | |||
| bd345d35a8 | |||
| 40d0825d79 | |||
| ea725aca9e | |||
| dbdbe16da9 | |||
| 5cd4e390e3 | |||
| 5c17a0d652 | |||
| ec3dd471b1 | |||
| 1d7a0d6bd8 | |||
| 71df4aa473 | |||
| 48d14bfb7e | |||
| 74bcf41fe8 | |||
| 210f020092 | |||
| 306691b4d7 | |||
| f531c65fbb | |||
| 6d742388fa | |||
| aec2d30506 | |||
| eb086b8456 | |||
| 3dd91a04fa | |||
| 9264a9c66d | |||
| f9f7283fec | |||
| 25e851b359 | |||
| f2a95f9ae6 | |||
| 4e0bcf1c4d | |||
| bbcb3304dc | |||
| 3b316e3a4e | |||
| 251e12c7d1 | |||
| 3b13a1b6d4 | |||
| 126db9612f | |||
| dd7819b1be | |||
| 3415df3715 | |||
| 0dc8930750 | |||
| 9f2d7daa17 | |||
| 249483c3e1 | |||
| eb2731183f | |||
| d9c50b97f8 | |||
| 8b445a1dc3 | |||
| be99aaebd0 | |||
| f96edd56fb | |||
| 074de037cd | |||
| 297c884b88 | |||
| 04b32e3152 | |||
| bbd09d6785 | |||
| 6a2ca59592 | |||
| 8aeb47eda3 | |||
| da1bccfd20 | |||
| 03c7a3fd42 | |||
| be8903e707 | |||
| d8534c2966 | |||
| d25db6e6f8 | |||
| df6d8f19f8 | |||
| 8af28a778b | |||
| 6ecae1bbd1 | |||
| 60a59e89f6 | |||
| 7fd6d67fe3 | |||
| 453db9f165 | |||
| 19f90e3d9a | |||
| fee0fe5699 | |||
| 88246e5719 | |||
| aaefe6c0d2 | |||
| cbc9bfccaa | |||
| 3e056ad37a | |||
| 46bac5b540 | |||
| 57ed8f8541 | |||
| 132893549a | |||
| d717d5da20 | |||
| 58fa4f869d | |||
| 32e36e330a | |||
| ee8cab8305 | |||
| 393653e20c | |||
| 560f598789 | |||
| 993dfe1bb0 | |||
| 967302269e | |||
| 674c849254 | |||
| f327e377a6 | |||
| e7be5b1928 | |||
| b54a41968d | |||
| f39f5e9fd6 | |||
| 7be18092d3 | |||
| c60c02bcfe | |||
| ec3443d1db | |||
| e76ab1f990 | |||
| c59c066330 | |||
| 7097167613 | |||
| 2c2795e73a | |||
| 965fc929e1 | |||
| 491aba4dbd | |||
| 6402656ec7 | |||
| f6314cc673 | |||
| cded932f1a | |||
| e7c496352f | |||
| 296c6f3cb3 | |||
| 53d0ee9ca5 | |||
| 689d5a51e8 | |||
| 23eab8769b | |||
| 0e57fd9955 | |||
| 2f5a31fc99 | |||
| 143a15fdb9 | |||
| 9c08fa5cdf | |||
| 59d8d878a2 | |||
| 0439a29189 | |||
| 4a63ea3dcc | |||
| 91b2653c71 | |||
| 8c8e7dd992 | |||
| a9cd2f7301 | |||
| b6c66dbdd7 | |||
| 5e1738ad4b | |||
| 4dc3c4ea1d | |||
| bc9ae6b4e5 | |||
| 70091935ba | |||
| 50e373ad1c | |||
| 966f943175 | |||
| c7c2b56f3b | |||
| 841c1d2ef2 | |||
| 26449e522a | |||
| f4c4ba7db5 | |||
| 83f8f0319c | |||
| 197a0cc8f1 | |||
| 6b4046eb17 | |||
| 9e27bef8fa | |||
| 11318f8ab9 | |||
| aaff9af3b7 | |||
| feb50e7007 | |||
| dc9adf8f10 | |||
| 3d592ca70d | |||
| 8d0ac45476 | |||
| 953033355b | |||
| 48b5927024 | |||
| 6e86912e7f | |||
| 4576059f4f | |||
| 9e9ba3e6c3 | |||
| 46602be0b3 | |||
| 14b278fba8 | |||
| 53c5708c9f | |||
| edc8920703 | |||
| 926de076d9 | |||
| 9b7beca85e | |||
| 0724d8ca60 | |||
| 9f36fe95ac | |||
| 3f148005e4 | |||
| 4e60d87514 | |||
| d2a16d0714 | |||
| 0f04463708 | |||
| 093fa7bcae | |||
| ac8a9ec0f8 | |||
| aa48b856fb | |||
| b4d27c7232 | |||
| dd192eda3e | |||
| c6b0f868ef | |||
| 3bea920193 | |||
| ca16a40a44 | |||
| 59e19310fe | |||
| b005a9c73b | |||
| 2c657670fe | |||
| 4dd271c968 | |||
| b76db6bcbd | |||
| 84674b1e10 | |||
| 1cb13d9f93 | |||
| 169f11b63b | |||
| 2c7a3f934d | |||
| a1e91ab30d | |||
| 4a7c89ec25 | |||
| 684a186e3b | |||
| e8a948cfaf | |||
| 11daf645e9 | |||
| a4a03eadc4 | |||
| 04ddb992d1 | |||
| 991de25b97 | |||
| 056f390abc | |||
| 9b9949befa | |||
| 366b02bb46 | |||
| ad2087cf65 | |||
| 0689dd68a3 | |||
| 75ea33153f | |||
| dbff1e0668 | |||
| afefe217db | |||
| fed8b39957 | |||
| f853537695 | |||
| 0cdaf117cb | |||
| ada555789d | |||
| 007d2dc554 | |||
| 995d5ea354 | |||
| 72ba8c8923 | |||
| 6f65b1e65e | |||
| 383caceb77 | |||
| b4862f2942 | |||
| d1affa8e44 | |||
| 6e3053fcb3 | |||
| b845ba4476 | |||
| 7c00650be5 | |||
| 5bc015a746 | |||
| 6757e10ec2 | |||
| 48428594c3 | |||
| 6a45414b46 | |||
| 0f53490633 | |||
| 66fba60194 | |||
| fadaeef8d3 | |||
| 3c5249eae7 | |||
| 9eca3d2ec0 | |||
| 4e89a00d2a | |||
| 89a0211adf | |||
| ecde45b4ce | |||
| 1df02300bc | |||
| 637ef4a84e | |||
| b53abaa3b2 |
@@ -0,0 +1,218 @@
|
||||
---
|
||||
name: cli-backend-testing
|
||||
description: >
|
||||
CLI + Backend integration testing workflow. Use when verifying backend API changes
|
||||
(TRPC routers, services, models) via the LobeHub CLI against a local dev server.
|
||||
Triggers on 'cli test', 'test with cli', 'verify with cli', 'local cli test',
|
||||
'backend test with cli', or when needing to validate server-side changes end-to-end.
|
||||
---
|
||||
|
||||
# CLI + Backend Integration Testing
|
||||
|
||||
Standard workflow for verifying backend changes using the LobeHub CLI (`lh`) against a local dev server.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Verifying TRPC router / service / model changes end-to-end
|
||||
- Testing new API fields or response structure changes
|
||||
- Validating CLI command output after backend modifications
|
||||
- Debugging data flow issues between server and CLI
|
||||
|
||||
## Prerequisites
|
||||
|
||||
| Requirement | Details |
|
||||
| ------------ | ------------------------------------------------------------- |
|
||||
| Dev server | `localhost:3011` (Next.js) |
|
||||
| CLI source | `lobehub/apps/cli/` |
|
||||
| CLI dev mode | Uses `LOBEHUB_CLI_HOME=.lobehub-dev` for isolated credentials |
|
||||
| Auth | Device Code Flow login to local server |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
All CLI dev commands run from `lobehub/apps/cli/`:
|
||||
|
||||
```bash
|
||||
# Shorthand for all commands below
|
||||
CLI="LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts"
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Ensure Dev Server is Running
|
||||
|
||||
Check if the dev server is already running:
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w '%{http_code}' http://localhost:3011/ 2> /dev/null
|
||||
```
|
||||
|
||||
- **If reachable** (returns any HTTP status): server is running. Skip to Step 2.
|
||||
- **If unreachable**: start the server:
|
||||
|
||||
```bash
|
||||
# From cloud repo root
|
||||
pnpm run dev:next
|
||||
```
|
||||
|
||||
To **restart** (pick up server-side code changes):
|
||||
|
||||
```bash
|
||||
lsof -ti:3011 | xargs kill
|
||||
pnpm run dev:next
|
||||
```
|
||||
|
||||
**Important:** Server-side code changes in the submodule (`lobehub/src/server/`, `lobehub/packages/`) require a server restart. Next.js hot-reload may not pick up changes in submodule packages.
|
||||
|
||||
### Step 2: Check CLI Authentication
|
||||
|
||||
Check if dev credentials already exist:
|
||||
|
||||
```bash
|
||||
cat lobehub/apps/cli/.lobehub-dev/settings.json 2> /dev/null
|
||||
```
|
||||
|
||||
- **If file exists and contains `"serverUrl": "http://localhost:3011"`**: already authenticated. Skip to Step 3.
|
||||
- **If file missing or points to wrong server**: login is needed. Ask the user to run:
|
||||
|
||||
```bash
|
||||
! cd lobehub/apps/cli && LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts login --server http://localhost:3011
|
||||
```
|
||||
|
||||
> Login requires interactive browser authorization (OIDC Device Code Flow), so the user must run it themselves via `!` prefix. After login, credentials are saved to `lobehub/apps/cli/.lobehub-dev/` and persist across sessions.
|
||||
|
||||
### Step 3: Test with CLI Commands
|
||||
|
||||
CLI runs from source (`bun src/index.ts`), so CLI-side code changes take effect immediately without rebuilding.
|
||||
|
||||
```bash
|
||||
cd lobehub/apps/cli
|
||||
LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts <command>
|
||||
```
|
||||
|
||||
### Step 4: Clean Up Test Data
|
||||
|
||||
Delete any test data created during verification:
|
||||
|
||||
```bash
|
||||
LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts task delete < id > -y
|
||||
LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts agent delete < id > -y
|
||||
```
|
||||
|
||||
## Common Testing Patterns
|
||||
|
||||
### Task System
|
||||
|
||||
```bash
|
||||
# List tasks
|
||||
$CLI task list
|
||||
|
||||
# Create test data with nesting
|
||||
$CLI task create -n "Root Task" -i "Test instruction"
|
||||
$CLI task create -n "Child Task" -i "Sub instruction" --parent T-1
|
||||
|
||||
# View task detail (tests getTaskDetail service)
|
||||
$CLI task view T-1
|
||||
|
||||
# View task tree
|
||||
$CLI task tree T-1
|
||||
|
||||
# Test lifecycle
|
||||
$CLI task edit T-1 --status running
|
||||
$CLI task comment T-1 -m "Test comment"
|
||||
|
||||
# Clean up
|
||||
$CLI task delete T-1 -y
|
||||
```
|
||||
|
||||
### Agent System
|
||||
|
||||
```bash
|
||||
# List agents
|
||||
$CLI agent list
|
||||
|
||||
# View agent detail
|
||||
$CLI agent view <agent-id>
|
||||
|
||||
# Run agent (tests agent execution pipeline)
|
||||
$CLI agent run <agent-id> -m "Test prompt"
|
||||
```
|
||||
|
||||
### Document & Knowledge Base
|
||||
|
||||
```bash
|
||||
# List documents
|
||||
$CLI doc list
|
||||
|
||||
# Create and view
|
||||
$CLI doc create -t "Test Doc" -c "Content here"
|
||||
$CLI doc view <doc-id>
|
||||
|
||||
# Knowledge base
|
||||
$CLI kb list
|
||||
$CLI kb tree <kb-id>
|
||||
```
|
||||
|
||||
### Model & Provider
|
||||
|
||||
```bash
|
||||
# List models and providers
|
||||
$CLI model list
|
||||
$CLI provider list
|
||||
|
||||
# Test provider connectivity
|
||||
$CLI provider test <provider-id>
|
||||
```
|
||||
|
||||
## Dev-Test Cycle
|
||||
|
||||
The standard cycle for backend development:
|
||||
|
||||
```
|
||||
1. Make code changes (service/model/router/type)
|
||||
|
|
||||
2. Run unit tests (fast feedback)
|
||||
bunx vitest run --silent='passed-only' '<test-file>'
|
||||
|
|
||||
3. Restart dev server (if server-side changes)
|
||||
lsof -ti:3011 | xargs kill && pnpm run dev:next
|
||||
|
|
||||
4. CLI verification (end-to-end)
|
||||
LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts <command>
|
||||
|
|
||||
5. Clean up test data
|
||||
```
|
||||
|
||||
### When Server Restart is Needed
|
||||
|
||||
| Change Location | Restart? |
|
||||
| ----------------------------------------- | -------- |
|
||||
| `lobehub/src/server/` (routers, services) | Yes |
|
||||
| `lobehub/packages/database/` (models) | Yes |
|
||||
| `lobehub/packages/types/` | Yes |
|
||||
| `lobehub/packages/prompts/` | Yes |
|
||||
| `lobehub/apps/cli/` (CLI code) | No |
|
||||
| `src/` (cloud overrides) | Yes |
|
||||
|
||||
### When Server Restart is NOT Needed
|
||||
|
||||
CLI runs from source via `bun src/index.ts`, so any changes to `lobehub/apps/cli/src/` take effect immediately on next command invocation.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Solution |
|
||||
| --------------------------- | --------------------------------------------------------------------- |
|
||||
| `No authentication found` | Run `login --server http://localhost:3011` |
|
||||
| `UNAUTHORIZED` on API calls | Token expired; re-run login |
|
||||
| `ECONNREFUSED` | Dev server not running; start with `pnpm run dev:next` |
|
||||
| CLI shows old data/behavior | Server needs restart to pick up code changes |
|
||||
| `EADDRINUSE` on port 3011 | Server already running; kill with `lsof -ti:3011 \| xargs kill` |
|
||||
| Login opens wrong server | Must use `--server http://localhost:3011` flag (env var doesn't work) |
|
||||
|
||||
## Credential Isolation
|
||||
|
||||
| Mode | Credential Dir | Server |
|
||||
| ---------- | -------------------------------- | ----------------- |
|
||||
| Dev | `lobehub/apps/cli/.lobehub-dev/` | `localhost:3011` |
|
||||
| Production | `~/.lobehub/` | `app.lobehub.com` |
|
||||
|
||||
The two environments are completely isolated. Dev mode credentials are gitignored.
|
||||
@@ -37,6 +37,10 @@ description: 'Code review checklist for LobeHub. Use when reviewing PRs, diffs,
|
||||
- Keys added to `src/locales/default/{namespace}.ts` with `{feature}.{context}.{action|status}` naming
|
||||
- For PRs: `locales/` translations for all languages updated (`pnpm i18n`)
|
||||
|
||||
### SPA / routing
|
||||
|
||||
- **`desktopRouter` pair:** If the diff touches `src/spa/router/desktopRouter.config.tsx`, does it also update `src/spa/router/desktopRouter.config.desktop.tsx` with the same route paths and nesting? Single-file edits often cause drift and blank screens.
|
||||
|
||||
### Reuse
|
||||
|
||||
- Newly written code duplicates existing utilities in `packages/utils` or shared modules?
|
||||
|
||||
@@ -20,9 +20,11 @@ This is NON-NEGOTIABLE. Skipping Linear comments is a workflow violation.
|
||||
## Workflow
|
||||
|
||||
1. **Retrieve issue details** before starting: `mcp__linear-server__get_issue`
|
||||
2. **Check for sub-issues**: Use `mcp__linear-server__list_issues` with `parentId` filter
|
||||
3. **Update issue status** when completing: `mcp__linear-server__update_issue`
|
||||
4. **Add completion comment** (REQUIRED): `mcp__linear-server__create_comment`
|
||||
2. **Read images**: If the issue description contains images, MUST use `mcp__linear-server__extract_images` to read image content for full context
|
||||
3. **Check for sub-issues**: Use `mcp__linear-server__list_issues` with `parentId` filter
|
||||
4. **Mark as In Progress**: When starting to plan or implement an issue, immediately update status to **"In Progress"** via `mcp__linear-server__update_issue`
|
||||
5. **Update issue status** when completing: `mcp__linear-server__update_issue`
|
||||
6. **Add completion comment** (REQUIRED): `mcp__linear-server__create_comment`
|
||||
|
||||
## Creating Issues
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# capture-app-window.sh — Capture a screenshot of a specific app window
|
||||
#
|
||||
# Uses CGWindowList via Swift to find the window by process name, then
|
||||
# screencapture -l <windowID> to capture only that window.
|
||||
# Falls back to full-screen capture if the window is not found.
|
||||
#
|
||||
# Usage:
|
||||
# ./capture-app-window.sh <process_name> <output_path>
|
||||
#
|
||||
# Arguments:
|
||||
# process_name — The process/owner name as shown in Activity Monitor
|
||||
# (e.g., "Discord", "Slack", "Telegram", "WeChat", "QQ", "Lark")
|
||||
# output_path — Path to save the screenshot (e.g., /tmp/screenshot.png)
|
||||
#
|
||||
# Examples:
|
||||
# ./capture-app-window.sh "Discord" /tmp/discord.png
|
||||
# ./capture-app-window.sh "Slack" /tmp/slack.png
|
||||
# ./capture-app-window.sh "微信" /tmp/wechat.png
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
PROCESS="${1:?Usage: capture-app-window.sh <process_name> <output_path>}"
|
||||
OUTPUT="${2:?Usage: capture-app-window.sh <process_name> <output_path>}"
|
||||
|
||||
# Find the CGWindowID for the target process using Swift + CGWindowList
|
||||
# Pass process name via environment variable (swift -e doesn't support -- args)
|
||||
WINDOW_ID=$(TARGET_PROCESS="$PROCESS" swift -e '
|
||||
import Cocoa
|
||||
import Foundation
|
||||
let target = ProcessInfo.processInfo.environment["TARGET_PROCESS"] ?? ""
|
||||
let windowList = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as! [[String: Any]]
|
||||
for w in windowList {
|
||||
let owner = w["kCGWindowOwnerName"] as? String ?? ""
|
||||
let layer = w["kCGWindowLayer"] as? Int ?? -1
|
||||
let bounds = w["kCGWindowBounds"] as? [String: Any] ?? [:]
|
||||
let ww = bounds["Width"] as? Double ?? 0
|
||||
let wh = bounds["Height"] as? Double ?? 0
|
||||
let wid = w["kCGWindowNumber"] as? Int ?? 0
|
||||
// Match process name, normal window layer (0), and reasonable size
|
||||
if owner == target && layer == 0 && ww > 200 && wh > 200 {
|
||||
print(wid)
|
||||
break
|
||||
}
|
||||
}
|
||||
' 2>/dev/null || true)
|
||||
|
||||
if [ -n "$WINDOW_ID" ]; then
|
||||
screencapture -l "$WINDOW_ID" -x "$OUTPUT"
|
||||
else
|
||||
echo "[capture] Warning: Could not find window for '$PROCESS', falling back to full screen"
|
||||
screencapture -x "$OUTPUT"
|
||||
fi
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# electron-dev.sh — Manage Electron dev environment for testing
|
||||
#
|
||||
# Usage:
|
||||
# ./electron-dev.sh start # Kill existing, start fresh, wait until ready
|
||||
# ./electron-dev.sh stop # Kill all Electron-related processes
|
||||
# ./electron-dev.sh status # Check if Electron is running and CDP is reachable
|
||||
# ./electron-dev.sh restart # Stop then start
|
||||
#
|
||||
# Environment variables:
|
||||
# CDP_PORT — Chrome DevTools Protocol port (default: 9222)
|
||||
# ELECTRON_LOG — Log file path (default: /tmp/electron-dev.log)
|
||||
# ELECTRON_WAIT_S — Max seconds to wait for Electron process (default: 60)
|
||||
# RENDERER_WAIT_S — Max seconds to wait for renderer/SPA (default: 60)
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
CDP_PORT="${CDP_PORT:-9222}"
|
||||
ELECTRON_LOG="${ELECTRON_LOG:-/tmp/electron-dev.log}"
|
||||
ELECTRON_WAIT_S="${ELECTRON_WAIT_S:-60}"
|
||||
RENDERER_WAIT_S="${RENDERER_WAIT_S:-60}"
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
|
||||
PIDFILE="/tmp/electron-dev-cdp-${CDP_PORT}.pid"
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
# Get the Electron binary path used by this project
|
||||
electron_bin_pattern() {
|
||||
echo "${PROJECT_ROOT}/apps/desktop/node_modules/.pnpm/electron@*/node_modules/electron/dist/Electron.app"
|
||||
}
|
||||
|
||||
# Find all PIDs related to the project's Electron dev session
|
||||
find_electron_pids() {
|
||||
local pids=""
|
||||
|
||||
# 1. Main Electron process (launched with --remote-debugging-port)
|
||||
local main_pids
|
||||
main_pids=$(pgrep -f "Electron\.app.*--remote-debugging-port=${CDP_PORT}" 2>/dev/null || true)
|
||||
[ -n "$main_pids" ] && pids="$pids $main_pids"
|
||||
|
||||
# 2. Electron Helper processes (gpu, renderer, utility) spawned from the project's electron binary
|
||||
local helper_pids
|
||||
helper_pids=$(pgrep -f "${PROJECT_ROOT}/apps/desktop/node_modules/.*Electron Helper" 2>/dev/null || true)
|
||||
[ -n "$helper_pids" ] && pids="$pids $helper_pids"
|
||||
|
||||
# 3. electron-vite dev server
|
||||
local vite_pids
|
||||
vite_pids=$(pgrep -f "electron-vite.*dev" 2>/dev/null || true)
|
||||
[ -n "$vite_pids" ] && pids="$pids $vite_pids"
|
||||
|
||||
# 4. PID from pidfile (fallback)
|
||||
if [ -f "$PIDFILE" ]; then
|
||||
local saved_pid
|
||||
saved_pid=$(cat "$PIDFILE")
|
||||
if kill -0 "$saved_pid" 2>/dev/null; then
|
||||
pids="$pids $saved_pid"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Deduplicate
|
||||
echo "$pids" | tr ' ' '\n' | sort -u | grep -v '^$' | tr '\n' ' ' || true
|
||||
}
|
||||
|
||||
do_stop() {
|
||||
echo "[electron-dev] Stopping Electron dev environment..."
|
||||
|
||||
local pids
|
||||
pids=$(find_electron_pids)
|
||||
|
||||
if [ -z "$pids" ]; then
|
||||
echo "[electron-dev] No Electron processes found."
|
||||
else
|
||||
echo "[electron-dev] Killing PIDs: $pids"
|
||||
for pid in $pids; do
|
||||
kill "$pid" 2>/dev/null || true
|
||||
done
|
||||
|
||||
# Wait up to 5s for graceful exit, then force-kill survivors
|
||||
local waited=0
|
||||
while [ $waited -lt 5 ]; do
|
||||
local alive=""
|
||||
for pid in $pids; do
|
||||
kill -0 "$pid" 2>/dev/null && alive="$alive $pid"
|
||||
done
|
||||
[ -z "$alive" ] && break
|
||||
sleep 1
|
||||
waited=$((waited + 1))
|
||||
done
|
||||
|
||||
# Force-kill any remaining
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
echo "[electron-dev] Force-killing PID $pid"
|
||||
kill -9 "$pid" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Also close any agent-browser sessions connected to this port
|
||||
agent-browser --cdp "$CDP_PORT" close --all 2>/dev/null || true
|
||||
|
||||
rm -f "$PIDFILE"
|
||||
echo "[electron-dev] Stopped."
|
||||
}
|
||||
|
||||
do_status() {
|
||||
local pids
|
||||
pids=$(find_electron_pids)
|
||||
|
||||
if [ -z "$pids" ]; then
|
||||
echo "[electron-dev] Electron is NOT running."
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "[electron-dev] Electron is running (PIDs: $pids)"
|
||||
|
||||
# Check CDP connectivity
|
||||
if agent-browser --cdp "$CDP_PORT" get url >/dev/null 2>&1; then
|
||||
local url
|
||||
url=$(agent-browser --cdp "$CDP_PORT" get url 2>&1 | tail -1)
|
||||
echo "[electron-dev] CDP port ${CDP_PORT} is reachable. URL: $url"
|
||||
return 0
|
||||
else
|
||||
echo "[electron-dev] CDP port ${CDP_PORT} is NOT reachable (Electron may still be loading)."
|
||||
return 2
|
||||
fi
|
||||
}
|
||||
|
||||
wait_for_electron() {
|
||||
echo "[electron-dev] Waiting for Electron process (up to ${ELECTRON_WAIT_S}s)..."
|
||||
local elapsed=0
|
||||
local interval=3
|
||||
while [ $elapsed -lt "$ELECTRON_WAIT_S" ]; do
|
||||
if strings "$ELECTRON_LOG" 2>/dev/null | grep -q "starting electron"; then
|
||||
echo "[electron-dev] Electron process started."
|
||||
return 0
|
||||
fi
|
||||
sleep "$interval"
|
||||
elapsed=$((elapsed + interval))
|
||||
echo "[electron-dev] Still waiting... (${elapsed}/${ELECTRON_WAIT_S}s)"
|
||||
done
|
||||
echo "[electron-dev] ERROR: Electron did not start within ${ELECTRON_WAIT_S}s"
|
||||
echo "[electron-dev] Last 20 lines of log:"
|
||||
tail -20 "$ELECTRON_LOG" 2>/dev/null || true
|
||||
return 1
|
||||
}
|
||||
|
||||
wait_for_renderer() {
|
||||
echo "[electron-dev] Waiting for renderer/SPA to load (up to ${RENDERER_WAIT_S}s)..."
|
||||
|
||||
# Initial delay — renderer needs time to bootstrap
|
||||
sleep 10
|
||||
|
||||
local elapsed=10
|
||||
local interval=5
|
||||
while [ $elapsed -lt "$RENDERER_WAIT_S" ]; do
|
||||
if agent-browser --cdp "$CDP_PORT" wait 2000 >/dev/null 2>&1; then
|
||||
# Check if interactive elements are present (SPA loaded)
|
||||
local snap
|
||||
snap=$(agent-browser --cdp "$CDP_PORT" snapshot -i 2>&1 || true)
|
||||
if echo "$snap" | grep -qE 'link |button '; then
|
||||
echo "[electron-dev] Renderer ready (interactive elements found)."
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
sleep "$interval"
|
||||
elapsed=$((elapsed + interval))
|
||||
echo "[electron-dev] SPA still loading... (${elapsed}/${RENDERER_WAIT_S}s)"
|
||||
done
|
||||
|
||||
echo "[electron-dev] WARNING: Timed out waiting for renderer, proceeding anyway."
|
||||
return 0
|
||||
}
|
||||
|
||||
do_start() {
|
||||
# If already running and healthy, skip
|
||||
local status_ok=0
|
||||
do_status >/dev/null 2>&1 || status_ok=$?
|
||||
if [ "$status_ok" -eq 0 ]; then
|
||||
echo "[electron-dev] Electron is already running and CDP is reachable. Skipping start."
|
||||
echo "[electron-dev] Use 'restart' to force a fresh session, or 'stop' to tear down."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Clean up any stale processes
|
||||
do_stop
|
||||
|
||||
# Start fresh
|
||||
echo "[electron-dev] Starting Electron dev server..."
|
||||
echo "[electron-dev] Project: $PROJECT_ROOT"
|
||||
echo "[electron-dev] CDP port: $CDP_PORT"
|
||||
echo "[electron-dev] Log: $ELECTRON_LOG"
|
||||
|
||||
: > "$ELECTRON_LOG" # Truncate log
|
||||
|
||||
(
|
||||
cd "$PROJECT_ROOT/apps/desktop" && \
|
||||
ELECTRON_ENABLE_LOGGING=1 npx electron-vite dev -- --remote-debugging-port="$CDP_PORT" \
|
||||
>> "$ELECTRON_LOG" 2>&1
|
||||
) &
|
||||
local bg_pid=$!
|
||||
echo "$bg_pid" > "$PIDFILE"
|
||||
echo "[electron-dev] Background PID: $bg_pid"
|
||||
|
||||
# Wait for Electron process to start
|
||||
if ! wait_for_electron; then
|
||||
echo "[electron-dev] Failed to start. Cleaning up..."
|
||||
do_stop
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Wait for renderer to be interactive
|
||||
if ! wait_for_renderer; then
|
||||
echo "[electron-dev] Renderer not ready, but Electron is running. You may need to wait more."
|
||||
fi
|
||||
|
||||
echo "[electron-dev] Ready! Use: agent-browser --cdp $CDP_PORT snapshot -i"
|
||||
}
|
||||
|
||||
do_restart() {
|
||||
do_stop
|
||||
sleep 2
|
||||
do_start
|
||||
}
|
||||
|
||||
# ── Main ─────────────────────────────────────────────────────────────
|
||||
|
||||
case "${1:-help}" in
|
||||
start) do_start ;;
|
||||
stop) do_stop ;;
|
||||
status) do_status ;;
|
||||
restart) do_restart ;;
|
||||
*)
|
||||
echo "Usage: $0 {start|stop|status|restart}"
|
||||
echo ""
|
||||
echo " start — Start Electron dev with CDP (idempotent, skips if already running)"
|
||||
echo " stop — Kill all Electron dev processes (main + helpers + vite)"
|
||||
echo " status — Check if Electron is running and CDP is reachable"
|
||||
echo " restart — Stop then start"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,353 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# record-electron-demo.sh — Record an automated demo of the Electron app
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/record-electron-demo.sh [script.sh] [output.mp4]
|
||||
#
|
||||
# script.sh — A shell script containing agent-browser commands to automate.
|
||||
# It receives the CDP port as $1. Defaults to a built-in queue-edit demo.
|
||||
# output.mp4 — Output file path. Defaults to /tmp/electron-demo.mp4
|
||||
#
|
||||
# Prerequisites:
|
||||
# - agent-browser CLI installed globally
|
||||
# - ffmpeg installed (brew install ffmpeg)
|
||||
# - Electron app NOT already running (script manages lifecycle)
|
||||
#
|
||||
# Examples:
|
||||
# # Run built-in demo
|
||||
# ./scripts/record-electron-demo.sh
|
||||
#
|
||||
# # Run custom automation script
|
||||
# ./scripts/record-electron-demo.sh ./my-demo.sh /tmp/my-demo.mp4
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
CDP_PORT=9222
|
||||
DEMO_SCRIPT="${1:-}"
|
||||
OUTPUT="${2:-/tmp/electron-demo.mp4}"
|
||||
ELECTRON_LOG="/tmp/electron-dev.log"
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
|
||||
RECORD_PID=""
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
cleanup() {
|
||||
echo "[cleanup] Stopping all processes..."
|
||||
[ -n "$RECORD_PID" ] && kill -INT "$RECORD_PID" 2>/dev/null && sleep 2
|
||||
pkill -f "electron-vite" 2>/dev/null || true
|
||||
pkill -f "Electron" 2>/dev/null || true
|
||||
pkill -f "agent-browser" 2>/dev/null || true
|
||||
echo "[cleanup] Done."
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
wait_for_electron() {
|
||||
echo "[wait] Waiting for Electron to start..."
|
||||
for i in $(seq 1 24); do
|
||||
sleep 5
|
||||
if strings "$ELECTRON_LOG" 2>/dev/null | grep -q "starting electron"; then
|
||||
echo "[wait] Electron process ready."
|
||||
return 0
|
||||
fi
|
||||
echo "[wait] Still waiting... (${i}/24)"
|
||||
done
|
||||
echo "[error] Electron failed to start within 120s"
|
||||
exit 1
|
||||
}
|
||||
|
||||
wait_for_renderer() {
|
||||
echo "[wait] Waiting for renderer to load..."
|
||||
sleep 15
|
||||
agent-browser --cdp "$CDP_PORT" wait 3000
|
||||
|
||||
# Poll until interactive elements appear (SPA may take extra time)
|
||||
for i in $(seq 1 12); do
|
||||
local snap
|
||||
snap=$(agent-browser --cdp "$CDP_PORT" snapshot -i 2>&1)
|
||||
if echo "$snap" | grep -q 'link "'; then
|
||||
echo "[wait] Renderer ready (interactive elements found)."
|
||||
return 0
|
||||
fi
|
||||
echo "[wait] SPA still loading... (${i}/12)"
|
||||
sleep 5
|
||||
done
|
||||
echo "[warn] Timed out waiting for interactive elements, proceeding anyway."
|
||||
}
|
||||
|
||||
get_window_and_screen_info() {
|
||||
# Returns: window_x window_y window_w window_h screen_index
|
||||
# Uses Swift to find the Electron window bounds and which screen it's on
|
||||
swift -e '
|
||||
import Cocoa
|
||||
let windowList = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as! [[String: Any]]
|
||||
for w in windowList {
|
||||
let owner = w["kCGWindowOwnerName"] as? String ?? ""
|
||||
let name = w["kCGWindowName"] as? String ?? ""
|
||||
let layer = w["kCGWindowLayer"] as? Int ?? -1
|
||||
let bounds = w["kCGWindowBounds"] as? [String: Any] ?? [:]
|
||||
let wx = bounds["X"] as? Double ?? 0
|
||||
let wy = bounds["Y"] as? Double ?? 0
|
||||
let ww = bounds["Width"] as? Double ?? 0
|
||||
let wh = bounds["Height"] as? Double ?? 0
|
||||
if (owner == "Electron" || owner == "LobeHub") && layer == 0 && name == "LobeHub" && ww > 200 && wh > 200 {
|
||||
// Find which screen this window is on
|
||||
let screens = NSScreen.screens
|
||||
var screenIdx = 0
|
||||
let windowCenter = NSPoint(x: wx + ww / 2, y: wy + wh / 2)
|
||||
for (i, screen) in screens.enumerated() {
|
||||
let frame = screen.frame
|
||||
// Convert CG coords (top-left origin) to NSScreen coords (bottom-left origin)
|
||||
let mainHeight = screens[0].frame.height
|
||||
let screenTop = mainHeight - frame.origin.y - frame.height
|
||||
let screenBottom = screenTop + frame.height
|
||||
let screenLeft = frame.origin.x
|
||||
let screenRight = screenLeft + frame.width
|
||||
if windowCenter.x >= screenLeft && windowCenter.x <= screenRight &&
|
||||
windowCenter.y >= screenTop && windowCenter.y <= screenBottom {
|
||||
screenIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
// Compute window position relative to the screen it is on
|
||||
let screen = screens[screenIdx]
|
||||
let mainHeight = screens[0].frame.height
|
||||
let screenTop = mainHeight - screen.frame.origin.y - screen.frame.height
|
||||
let relX = wx - screen.frame.origin.x
|
||||
let relY = wy - screenTop
|
||||
let scale = Int(screen.backingScaleFactor)
|
||||
print("\(Int(relX)) \(Int(relY)) \(Int(ww)) \(Int(wh)) \(screenIdx) \(scale)")
|
||||
break
|
||||
}
|
||||
}
|
||||
'
|
||||
}
|
||||
|
||||
start_recording() {
|
||||
local rel_x=$1 rel_y=$2 w=$3 h=$4 screen_idx=$5 scale=$6
|
||||
|
||||
# ffmpeg avfoundation device index for screens
|
||||
# List devices and find the one matching our screen index
|
||||
local device_idx
|
||||
device_idx=$(ffmpeg -f avfoundation -list_devices true -i "" 2>&1 \
|
||||
| grep "Capture screen ${screen_idx}" \
|
||||
| grep -oE '\[[0-9]+\]' | tr -d '[]' || true)
|
||||
|
||||
if [ -z "$device_idx" ]; then
|
||||
echo "[warn] Could not find capture device for screen $screen_idx, trying default (3)"
|
||||
device_idx=3
|
||||
fi
|
||||
|
||||
# Scale coordinates to native resolution
|
||||
local cx=$((rel_x * scale))
|
||||
local cy=$((rel_y * scale))
|
||||
local cw=$((w * scale))
|
||||
local ch=$((h * scale))
|
||||
|
||||
echo "[record] Window: ${rel_x},${rel_y} ${w}x${h} on screen ${screen_idx} (scale=${scale})"
|
||||
echo "[record] Crop: ${cx},${cy} ${cw}x${ch}, device: ${device_idx}"
|
||||
echo "[record] Output: $OUTPUT"
|
||||
|
||||
ffmpeg -y \
|
||||
-f avfoundation -framerate 30 -capture_cursor 1 -i "${device_idx}:" \
|
||||
-vf "crop=${cw}:${ch}:${cx}:${cy},scale=${w}:${h}" \
|
||||
-c:v libx264 -crf 23 -preset fast -an \
|
||||
"$OUTPUT" \
|
||||
> /tmp/ffmpeg-record.log 2>&1 &
|
||||
RECORD_PID=$!
|
||||
sleep 2
|
||||
|
||||
if ! kill -0 "$RECORD_PID" 2>/dev/null; then
|
||||
echo "[error] ffmpeg failed to start. Log:"
|
||||
cat /tmp/ffmpeg-record.log
|
||||
RECORD_PID=""
|
||||
return 1
|
||||
fi
|
||||
echo "[record] Recording started (PID=$RECORD_PID)"
|
||||
}
|
||||
|
||||
stop_recording() {
|
||||
if [ -n "$RECORD_PID" ]; then
|
||||
echo "[record] Stopping recording..."
|
||||
kill -INT "$RECORD_PID" 2>/dev/null || true
|
||||
wait "$RECORD_PID" 2>/dev/null || true
|
||||
RECORD_PID=""
|
||||
echo "[record] Saved to $OUTPUT"
|
||||
ls -lh "$OUTPUT"
|
||||
fi
|
||||
}
|
||||
|
||||
# ── Built-in demo: Queue Edit ────────────────────────────────────────
|
||||
|
||||
find_input_ref() {
|
||||
local port=$1
|
||||
agent-browser --cdp "$port" snapshot -i -C 2>&1 \
|
||||
| grep "editable" \
|
||||
| grep -oE 'ref=e[0-9]+' \
|
||||
| head -1 \
|
||||
| sed 's/ref=//'
|
||||
}
|
||||
|
||||
builtin_demo() {
|
||||
local port=$1
|
||||
|
||||
echo "[demo] Step 1: Navigate to first available agent"
|
||||
local snapshot agent_ref
|
||||
snapshot=$(agent-browser --cdp "$port" snapshot -i 2>&1)
|
||||
# Try Lobe AI first, then fall back to any agent link in the sidebar
|
||||
agent_ref=$(echo "$snapshot" | grep -oE 'link "Lobe AI" \[ref=e[0-9]+\]' | grep -oE 'e[0-9]+' || true)
|
||||
if [ -z "$agent_ref" ]; then
|
||||
# Pick the first agent-like link (skip nav links)
|
||||
agent_ref=$(echo "$snapshot" | grep 'link "' | grep -vE '"Home"|"Pages"|"Settings"|"Search"|"Resources"|"Marketplace"' | head -1 | grep -oE 'ref=e[0-9]+' | sed 's/ref=//' || true)
|
||||
fi
|
||||
if [ -z "$agent_ref" ]; then
|
||||
echo "[error] No agent link found in snapshot"
|
||||
echo "$snapshot" | head -30
|
||||
return 1
|
||||
fi
|
||||
echo "[demo] Clicking agent ref: @$agent_ref"
|
||||
agent-browser --cdp "$port" click "@$agent_ref"
|
||||
sleep 3
|
||||
|
||||
echo "[demo] Step 2: Send first message (triggers AI generation)"
|
||||
local input_ref
|
||||
input_ref=$(find_input_ref "$port")
|
||||
agent-browser --cdp "$port" click "@$input_ref"
|
||||
agent-browser --cdp "$port" type "@$input_ref" "Write a 3000 word essay about the complete history of space exploration from Sputnik to the James Webb Space Telescope"
|
||||
sleep 1
|
||||
agent-browser --cdp "$port" press Enter
|
||||
sleep 3
|
||||
|
||||
echo "[demo] Step 3: Queue message 1"
|
||||
input_ref=$(find_input_ref "$port")
|
||||
agent-browser --cdp "$port" click "@$input_ref"
|
||||
agent-browser --cdp "$port" type "@$input_ref" "This message should be edited"
|
||||
sleep 1
|
||||
agent-browser --cdp "$port" press Enter
|
||||
sleep 1
|
||||
|
||||
echo "[demo] Step 4: Queue message 2"
|
||||
input_ref=$(find_input_ref "$port")
|
||||
agent-browser --cdp "$port" click "@$input_ref"
|
||||
agent-browser --cdp "$port" type "@$input_ref" "Another queued message"
|
||||
sleep 1
|
||||
agent-browser --cdp "$port" press Enter
|
||||
sleep 1
|
||||
|
||||
echo "[demo] Step 5: Verify queue has messages"
|
||||
local queue_count
|
||||
queue_count=$(agent-browser --cdp "$port" eval --stdin << 'EVALEOF'
|
||||
(function() {
|
||||
var chat = window.__LOBE_STORES.chat();
|
||||
var total = 0;
|
||||
Object.keys(chat.queuedMessages).forEach(function(k) {
|
||||
total += chat.queuedMessages[k].length;
|
||||
});
|
||||
return String(total);
|
||||
})()
|
||||
EVALEOF
|
||||
)
|
||||
echo "[demo] Queue count: $queue_count"
|
||||
|
||||
if [ "$queue_count" = "0" ] || [ "$queue_count" = '"0"' ]; then
|
||||
echo "[demo] Queue was already drained. Retrying..."
|
||||
input_ref=$(find_input_ref "$port")
|
||||
agent-browser --cdp "$port" click "@$input_ref"
|
||||
agent-browser --cdp "$port" type "@$input_ref" "Now write another 3000 word essay about artificial intelligence from Turing to transformers covering every major breakthrough"
|
||||
sleep 1
|
||||
agent-browser --cdp "$port" press Enter
|
||||
sleep 2
|
||||
input_ref=$(find_input_ref "$port")
|
||||
agent-browser --cdp "$port" click "@$input_ref"
|
||||
agent-browser --cdp "$port" type "@$input_ref" "This message should be edited"
|
||||
sleep 1
|
||||
agent-browser --cdp "$port" press Enter
|
||||
sleep 1
|
||||
input_ref=$(find_input_ref "$port")
|
||||
agent-browser --cdp "$port" click "@$input_ref"
|
||||
agent-browser --cdp "$port" type "@$input_ref" "Another queued message"
|
||||
sleep 1
|
||||
agent-browser --cdp "$port" press Enter
|
||||
sleep 1
|
||||
fi
|
||||
|
||||
echo "[demo] Step 6: Scroll to show queue tray"
|
||||
agent-browser --cdp "$port" scroll down 5000
|
||||
sleep 2
|
||||
|
||||
echo "[demo] Step 7: Click edit button on first queued message"
|
||||
agent-browser --cdp "$port" eval --stdin << 'EVALEOF'
|
||||
(function() {
|
||||
var chat = window.__LOBE_STORES.chat();
|
||||
var keys = Object.keys(chat.queuedMessages);
|
||||
for (var k = 0; k < keys.length; k++) {
|
||||
var queue = chat.queuedMessages[keys[k]];
|
||||
if (queue.length > 0) {
|
||||
var targetText = queue[0].content;
|
||||
var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null);
|
||||
while (walker.nextNode()) {
|
||||
var node = walker.currentNode;
|
||||
if (node.textContent.trim() === targetText) {
|
||||
var row = node.parentElement.parentElement;
|
||||
var buttons = row.querySelectorAll('[role="button"]');
|
||||
if (buttons.length >= 1) {
|
||||
buttons[0].click();
|
||||
return 'clicked edit on: ' + targetText;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 'edit button not found';
|
||||
})()
|
||||
EVALEOF
|
||||
sleep 3
|
||||
|
||||
echo "[demo] Step 8: Show result — content restored to input"
|
||||
sleep 3
|
||||
|
||||
echo "[demo] Complete!"
|
||||
}
|
||||
|
||||
# ── Main ─────────────────────────────────────────────────────────────
|
||||
|
||||
echo "=== Electron Demo Recorder ==="
|
||||
|
||||
# 1. Kill existing instances
|
||||
echo "[setup] Cleaning up existing processes..."
|
||||
pkill -f "Electron" 2>/dev/null || true
|
||||
pkill -f "electron-vite" 2>/dev/null || true
|
||||
pkill -f "agent-browser" 2>/dev/null || true
|
||||
sleep 3
|
||||
|
||||
# 2. Start Electron
|
||||
echo "[setup] Starting Electron..."
|
||||
cd "$PROJECT_ROOT/apps/desktop"
|
||||
ELECTRON_ENABLE_LOGGING=1 npx electron-vite dev -- --remote-debugging-port="$CDP_PORT" > "$ELECTRON_LOG" 2>&1 &
|
||||
|
||||
wait_for_electron
|
||||
wait_for_renderer
|
||||
|
||||
# 3. Get window position and start recording
|
||||
WIN_INFO=$(get_window_and_screen_info)
|
||||
if [ -z "$WIN_INFO" ]; then
|
||||
echo "[error] Could not find Electron window"
|
||||
exit 1
|
||||
fi
|
||||
read -r WIN_X WIN_Y WIN_W WIN_H SCREEN_IDX SCALE <<< "$WIN_INFO"
|
||||
start_recording "$WIN_X" "$WIN_Y" "$WIN_W" "$WIN_H" "$SCREEN_IDX" "$SCALE"
|
||||
|
||||
# 4. Run demo script
|
||||
if [ -n "$DEMO_SCRIPT" ] && [ -f "$DEMO_SCRIPT" ]; then
|
||||
echo "[demo] Running custom script: $DEMO_SCRIPT"
|
||||
bash "$DEMO_SCRIPT" "$CDP_PORT"
|
||||
else
|
||||
echo "[demo] Running built-in queue-edit demo"
|
||||
builtin_demo "$CDP_PORT"
|
||||
fi
|
||||
|
||||
# 5. Stop recording
|
||||
stop_recording
|
||||
|
||||
echo "=== Done! Output: $OUTPUT ==="
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# test-discord-bot.sh — Send a message to a Discord bot and capture the response
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/test-discord-bot.sh <channel> <message> [wait_seconds] [screenshot_path]
|
||||
#
|
||||
# channel — Channel name to navigate to via Quick Switcher (Cmd+K)
|
||||
# message — Message to send to the bot
|
||||
# wait_seconds — Seconds to wait for bot response (default: 10)
|
||||
# screenshot_path — Output screenshot path (default: /tmp/discord-bot-test.png)
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Discord desktop app installed and logged in
|
||||
# - Accessibility permission granted (System Preferences > Privacy > Accessibility)
|
||||
#
|
||||
# Examples:
|
||||
# ./scripts/test-discord-bot.sh "bot-testing" "!ping"
|
||||
# ./scripts/test-discord-bot.sh "bot-testing" "/ask Tell me a joke" 30
|
||||
# ./scripts/test-discord-bot.sh "general" "Hello bot" 15 /tmp/my-test.png
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CHANNEL="${1:?Usage: test-discord-bot.sh <channel> <message> [wait_seconds] [screenshot_path]}"
|
||||
MESSAGE="${2:?Usage: test-discord-bot.sh <channel> <message> [wait_seconds] [screenshot_path]}"
|
||||
WAIT="${3:-10}"
|
||||
SCREENSHOT="${4:-/tmp/discord-bot-test.png}"
|
||||
|
||||
APP="Discord"
|
||||
|
||||
echo "[$APP] Activating..."
|
||||
osascript -e "tell application \"$APP\" to activate"
|
||||
sleep 1
|
||||
|
||||
echo "[$APP] Navigating to channel: $CHANNEL"
|
||||
osascript -e '
|
||||
tell application "System Events"
|
||||
-- Quick Switcher
|
||||
keystroke "k" using command down
|
||||
delay 0.8
|
||||
keystroke "'"$CHANNEL"'"
|
||||
delay 1.5
|
||||
key code 36 -- Enter
|
||||
end tell
|
||||
'
|
||||
sleep 2
|
||||
|
||||
echo "[$APP] Sending message: $MESSAGE"
|
||||
osascript -e '
|
||||
set the clipboard to "'"$MESSAGE"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 0.3
|
||||
key code 36 -- Enter
|
||||
end tell
|
||||
'
|
||||
|
||||
echo "[$APP] Waiting ${WAIT}s for bot response..."
|
||||
sleep "$WAIT"
|
||||
|
||||
echo "[$APP] Capturing screenshot..."
|
||||
"$SCRIPT_DIR/capture-app-window.sh" "$APP" "$SCREENSHOT"
|
||||
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# test-lark-bot.sh — Send a message to a Lark/Feishu bot and capture the response
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/test-lark-bot.sh <chat> <message> [wait_seconds] [screenshot_path]
|
||||
#
|
||||
# chat — Chat or contact name to search for
|
||||
# message — Message to send to the bot
|
||||
# wait_seconds — Seconds to wait for bot response (default: 10)
|
||||
# screenshot_path — Output screenshot path (default: /tmp/lark-bot-test.png)
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Lark (飞书) desktop app installed and logged in
|
||||
# - Accessibility permission granted (System Preferences > Privacy > Accessibility)
|
||||
#
|
||||
# Notes:
|
||||
# - The app name may be "Lark" or "飞书" depending on version/locale
|
||||
# - Uses Cmd+K to open search/quick switcher
|
||||
# - Enter sends message by default
|
||||
#
|
||||
# Examples:
|
||||
# ./scripts/test-lark-bot.sh "TestBot" "Hello"
|
||||
# ./scripts/test-lark-bot.sh "bot-testing" "/ask Tell me a joke" 30
|
||||
# ./scripts/test-lark-bot.sh "MyBot" "Help me summarize this" 60 /tmp/my-test.png
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CHAT="${1:?Usage: test-lark-bot.sh <chat> <message> [wait_seconds] [screenshot_path]}"
|
||||
MESSAGE="${2:?Usage: test-lark-bot.sh <chat> <message> [wait_seconds] [screenshot_path]}"
|
||||
WAIT="${3:-10}"
|
||||
SCREENSHOT="${4:-/tmp/lark-bot-test.png}"
|
||||
|
||||
# Detect app name — "Lark" or "飞书"
|
||||
APP=""
|
||||
if osascript -e 'tell application "Lark" to name' &>/dev/null; then
|
||||
APP="Lark"
|
||||
elif osascript -e 'tell application "飞书" to name' &>/dev/null; then
|
||||
APP="飞书"
|
||||
else
|
||||
echo "[error] Lark/飞书 app not found. Install Lark or 飞书."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[$APP] Activating..."
|
||||
osascript -e "tell application \"$APP\" to activate"
|
||||
sleep 1
|
||||
|
||||
echo "[$APP] Searching for chat: $CHAT"
|
||||
osascript -e '
|
||||
tell application "System Events"
|
||||
-- Quick Switcher / Search (Cmd+K)
|
||||
keystroke "k" using command down
|
||||
delay 0.8
|
||||
end tell
|
||||
'
|
||||
# Use clipboard for chat name (supports CJK characters)
|
||||
osascript -e '
|
||||
set the clipboard to "'"$CHAT"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 1.5
|
||||
key code 36 -- Enter to select first result
|
||||
end tell
|
||||
'
|
||||
sleep 2
|
||||
|
||||
echo "[$APP] Sending message: $MESSAGE"
|
||||
osascript -e '
|
||||
set the clipboard to "'"$MESSAGE"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 0.3
|
||||
key code 36 -- Enter to send
|
||||
end tell
|
||||
'
|
||||
|
||||
echo "[$APP] Waiting ${WAIT}s for bot response..."
|
||||
sleep "$WAIT"
|
||||
|
||||
echo "[$APP] Capturing screenshot..."
|
||||
"$SCRIPT_DIR/capture-app-window.sh" "$APP" "$SCREENSHOT"
|
||||
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# test-qq-bot.sh — Send a message to a QQ bot and capture the response
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/test-qq-bot.sh <contact> <message> [wait_seconds] [screenshot_path]
|
||||
#
|
||||
# contact — Contact, group, or bot name to search for
|
||||
# message — Message to send
|
||||
# wait_seconds — Seconds to wait for bot response (default: 10)
|
||||
# screenshot_path — Output screenshot path (default: /tmp/qq-bot-test.png)
|
||||
#
|
||||
# Prerequisites:
|
||||
# - QQ desktop app installed and logged in
|
||||
# - Accessibility permission granted (System Preferences > Privacy > Accessibility)
|
||||
#
|
||||
# Notes:
|
||||
# - The app name is "QQ"
|
||||
# - Uses Cmd+F to open search
|
||||
# - Enter sends message by default; Shift+Enter for newlines
|
||||
# - Uses clipboard paste for CJK character support
|
||||
#
|
||||
# Examples:
|
||||
# ./scripts/test-qq-bot.sh "TestBot" "Hello"
|
||||
# ./scripts/test-qq-bot.sh "bot-testing" "Hello bot" 30
|
||||
# ./scripts/test-qq-bot.sh "MyBot" "/help" 15 /tmp/my-test.png
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CONTACT="${1:?Usage: test-qq-bot.sh <contact> <message> [wait_seconds] [screenshot_path]}"
|
||||
MESSAGE="${2:?Usage: test-qq-bot.sh <contact> <message> [wait_seconds] [screenshot_path]}"
|
||||
WAIT="${3:-10}"
|
||||
SCREENSHOT="${4:-/tmp/qq-bot-test.png}"
|
||||
|
||||
APP="QQ"
|
||||
|
||||
echo "[$APP] Activating..."
|
||||
osascript -e "tell application \"$APP\" to activate"
|
||||
sleep 1
|
||||
|
||||
echo "[$APP] Searching for contact: $CONTACT"
|
||||
osascript -e '
|
||||
tell application "System Events"
|
||||
-- Search (Cmd+F)
|
||||
keystroke "f" using command down
|
||||
delay 0.8
|
||||
end tell
|
||||
'
|
||||
# Use clipboard for contact name (supports CJK characters)
|
||||
osascript -e '
|
||||
set the clipboard to "'"$CONTACT"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 1.5
|
||||
key code 36 -- Enter to select first result
|
||||
end tell
|
||||
'
|
||||
sleep 2
|
||||
|
||||
echo "[$APP] Sending message: $MESSAGE"
|
||||
osascript -e '
|
||||
set the clipboard to "'"$MESSAGE"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 0.3
|
||||
key code 36 -- Enter to send
|
||||
end tell
|
||||
'
|
||||
|
||||
echo "[$APP] Waiting ${WAIT}s for bot response..."
|
||||
sleep "$WAIT"
|
||||
|
||||
echo "[$APP] Capturing screenshot..."
|
||||
"$SCRIPT_DIR/capture-app-window.sh" "$APP" "$SCREENSHOT"
|
||||
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# test-slack-bot.sh — Send a message to a Slack bot and capture the response
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/test-slack-bot.sh <channel> <message> [wait_seconds] [screenshot_path]
|
||||
#
|
||||
# channel — Channel name to navigate to via Quick Switcher (Cmd+K)
|
||||
# message — Message to send (e.g., "@mybot hello" or "/ask question")
|
||||
# wait_seconds — Seconds to wait for bot response (default: 10)
|
||||
# screenshot_path — Output screenshot path (default: /tmp/slack-bot-test.png)
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Slack desktop app installed and logged in
|
||||
# - Accessibility permission granted (System Preferences > Privacy > Accessibility)
|
||||
#
|
||||
# Examples:
|
||||
# ./scripts/test-slack-bot.sh "bot-testing" "@mybot hello"
|
||||
# ./scripts/test-slack-bot.sh "bot-testing" "/ask What is 2+2?" 20
|
||||
# ./scripts/test-slack-bot.sh "general" "Hey bot" 15 /tmp/my-test.png
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CHANNEL="${1:?Usage: test-slack-bot.sh <channel> <message> [wait_seconds] [screenshot_path]}"
|
||||
MESSAGE="${2:?Usage: test-slack-bot.sh <channel> <message> [wait_seconds] [screenshot_path]}"
|
||||
WAIT="${3:-10}"
|
||||
SCREENSHOT="${4:-/tmp/slack-bot-test.png}"
|
||||
|
||||
APP="Slack"
|
||||
|
||||
echo "[$APP] Activating..."
|
||||
osascript -e "tell application \"$APP\" to activate"
|
||||
sleep 1
|
||||
|
||||
echo "[$APP] Navigating to channel: $CHANNEL"
|
||||
osascript -e '
|
||||
tell application "System Events"
|
||||
-- Quick Switcher
|
||||
keystroke "k" using command down
|
||||
delay 0.8
|
||||
keystroke "'"$CHANNEL"'"
|
||||
delay 1.5
|
||||
key code 36 -- Enter
|
||||
end tell
|
||||
'
|
||||
sleep 2
|
||||
|
||||
echo "[$APP] Sending message: $MESSAGE"
|
||||
osascript -e '
|
||||
set the clipboard to "'"$MESSAGE"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 0.3
|
||||
key code 36 -- Enter
|
||||
end tell
|
||||
'
|
||||
|
||||
echo "[$APP] Waiting ${WAIT}s for bot response..."
|
||||
sleep "$WAIT"
|
||||
|
||||
echo "[$APP] Capturing screenshot..."
|
||||
"$SCRIPT_DIR/capture-app-window.sh" "$APP" "$SCREENSHOT"
|
||||
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# test-telegram-bot.sh — Send a message to a Telegram bot and capture the response
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/test-telegram-bot.sh <bot_or_chat> <message> [wait_seconds] [screenshot_path]
|
||||
#
|
||||
# bot_or_chat — Bot username or chat name to search for
|
||||
# message — Message to send to the bot
|
||||
# wait_seconds — Seconds to wait for bot response (default: 10)
|
||||
# screenshot_path — Output screenshot path (default: /tmp/telegram-bot-test.png)
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Telegram desktop app installed and logged in
|
||||
# - Accessibility permission granted (System Preferences > Privacy > Accessibility)
|
||||
#
|
||||
# Notes:
|
||||
# - The app name may be "Telegram" or "Telegram Desktop" depending on installation
|
||||
# - Uses Cmd+F to search for the bot, then Enter to open the chat
|
||||
#
|
||||
# Examples:
|
||||
# ./scripts/test-telegram-bot.sh "MyTestBot" "/start"
|
||||
# ./scripts/test-telegram-bot.sh "MyTestBot" "Hello bot" 30
|
||||
# ./scripts/test-telegram-bot.sh "GPTBot" "/ask What is AI?" 60 /tmp/my-test.png
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
BOT="${1:?Usage: test-telegram-bot.sh <bot_or_chat> <message> [wait_seconds] [screenshot_path]}"
|
||||
MESSAGE="${2:?Usage: test-telegram-bot.sh <bot_or_chat> <message> [wait_seconds] [screenshot_path]}"
|
||||
WAIT="${3:-10}"
|
||||
SCREENSHOT="${4:-/tmp/telegram-bot-test.png}"
|
||||
|
||||
# Detect app name — "Telegram" or "Telegram Desktop"
|
||||
APP=""
|
||||
if osascript -e 'tell application "Telegram" to name' &>/dev/null; then
|
||||
APP="Telegram"
|
||||
elif osascript -e 'tell application "Telegram Desktop" to name' &>/dev/null; then
|
||||
APP="Telegram Desktop"
|
||||
else
|
||||
echo "[error] Telegram app not found. Install Telegram or Telegram Desktop."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[$APP] Activating..."
|
||||
osascript -e "tell application \"$APP\" to activate"
|
||||
sleep 1
|
||||
|
||||
echo "[$APP] Searching for: $BOT"
|
||||
osascript -e '
|
||||
tell application "System Events"
|
||||
-- Search (Escape first to clear any existing state)
|
||||
key code 53 -- Escape
|
||||
delay 0.3
|
||||
keystroke "f" using command down
|
||||
delay 0.8
|
||||
keystroke "'"$BOT"'"
|
||||
delay 2
|
||||
key code 36 -- Enter to select first result
|
||||
end tell
|
||||
'
|
||||
sleep 2
|
||||
|
||||
echo "[$APP] Sending message: $MESSAGE"
|
||||
osascript -e '
|
||||
set the clipboard to "'"$MESSAGE"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 0.3
|
||||
key code 36 -- Enter
|
||||
end tell
|
||||
'
|
||||
|
||||
echo "[$APP] Waiting ${WAIT}s for bot response..."
|
||||
sleep "$WAIT"
|
||||
|
||||
echo "[$APP] Capturing screenshot..."
|
||||
"$SCRIPT_DIR/capture-app-window.sh" "$APP" "$SCREENSHOT"
|
||||
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# test-wechat-bot.sh — Send a message to a WeChat bot and capture the response
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/test-wechat-bot.sh <contact> <message> [wait_seconds] [screenshot_path]
|
||||
#
|
||||
# contact — Contact or bot name to search for
|
||||
# message — Message to send
|
||||
# wait_seconds — Seconds to wait for bot response (default: 10)
|
||||
# screenshot_path — Output screenshot path (default: /tmp/wechat-bot-test.png)
|
||||
#
|
||||
# Prerequisites:
|
||||
# - WeChat (微信) desktop app installed and logged in
|
||||
# - Accessibility permission granted (System Preferences > Privacy > Accessibility)
|
||||
#
|
||||
# Notes:
|
||||
# - The app name may be "微信" or "WeChat" depending on system language
|
||||
# - WeChat sends on Enter by default; use Shift+Enter for newlines
|
||||
# - For Chinese text, always uses clipboard paste (keystroke can't handle CJK)
|
||||
#
|
||||
# Examples:
|
||||
# ./scripts/test-wechat-bot.sh "TestBot" "Hello"
|
||||
# ./scripts/test-wechat-bot.sh "文件传输助手" "test message" 5
|
||||
# ./scripts/test-wechat-bot.sh "MyBot" "Tell me a joke" 30 /tmp/my-test.png
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CONTACT="${1:?Usage: test-wechat-bot.sh <contact> <message> [wait_seconds] [screenshot_path]}"
|
||||
MESSAGE="${2:?Usage: test-wechat-bot.sh <contact> <message> [wait_seconds] [screenshot_path]}"
|
||||
WAIT="${3:-10}"
|
||||
SCREENSHOT="${4:-/tmp/wechat-bot-test.png}"
|
||||
|
||||
# Detect app name — "微信" or "WeChat"
|
||||
APP=""
|
||||
if osascript -e 'tell application "微信" to name' &>/dev/null; then
|
||||
APP="微信"
|
||||
elif osascript -e 'tell application "WeChat" to name' &>/dev/null; then
|
||||
APP="WeChat"
|
||||
else
|
||||
echo "[error] WeChat app not found. Install 微信 (WeChat)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[$APP] Activating..."
|
||||
osascript -e "tell application \"$APP\" to activate"
|
||||
sleep 1
|
||||
|
||||
echo "[$APP] Searching for contact: $CONTACT"
|
||||
osascript -e '
|
||||
tell application "System Events"
|
||||
-- Search (Cmd+F)
|
||||
keystroke "f" using command down
|
||||
delay 0.8
|
||||
end tell
|
||||
'
|
||||
# Use clipboard for contact name (supports CJK characters)
|
||||
osascript -e '
|
||||
set the clipboard to "'"$CONTACT"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 1.5
|
||||
key code 36 -- Enter to select first result
|
||||
end tell
|
||||
'
|
||||
sleep 2
|
||||
|
||||
echo "[$APP] Sending message: $MESSAGE"
|
||||
# Always use clipboard paste — keystroke can't handle CJK or special characters
|
||||
osascript -e '
|
||||
set the clipboard to "'"$MESSAGE"'"
|
||||
tell application "System Events"
|
||||
keystroke "v" using command down
|
||||
delay 0.3
|
||||
key code 36 -- Enter to send
|
||||
end tell
|
||||
'
|
||||
|
||||
echo "[$APP] Waiting ${WAIT}s for bot response..."
|
||||
sleep "$WAIT"
|
||||
|
||||
echo "[$APP] Capturing screenshot..."
|
||||
"$SCRIPT_DIR/capture-app-window.sh" "$APP" "$SCREENSHOT"
|
||||
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
|
||||
@@ -7,7 +7,10 @@ description: React component development guide. Use when working with React comp
|
||||
|
||||
- Use antd-style for complex styles; for simple cases, use inline `style` attribute
|
||||
- Use `Flexbox` and `Center` from `@lobehub/ui` for layouts (see `references/layout-kit.md`)
|
||||
- Component priority: `src/components` > installed packages > `@lobehub/ui` > antd
|
||||
- Component priority: `src/components` > `@lobehub/ui/base-ui` > `@lobehub/ui` > custom implementation
|
||||
- Always prefer `@lobehub/ui/base-ui` primitives (Select, Modal, DropdownMenu, Popover, Switch, ScrollArea…) over antd equivalents
|
||||
- Fall back to `@lobehub/ui` higher-level components when base-ui has no match
|
||||
- Only implement a custom component as a last resort — never reach for antd directly
|
||||
- Use selectors to access zustand store data
|
||||
|
||||
## @lobehub/ui Components
|
||||
@@ -29,18 +32,31 @@ Reference: `node_modules/@lobehub/ui/es/index.mjs` for all available components.
|
||||
|
||||
Hybrid routing: Next.js App Router (static pages) + React Router DOM (main SPA).
|
||||
|
||||
| Route Type | Use Case | Implementation |
|
||||
| ------------------ | --------------------------------- | ---------------------------- |
|
||||
| Next.js App Router | Auth pages (login, signup, oauth) | `src/app/[variants]/(auth)/` |
|
||||
| React Router DOM | Main SPA (chat, settings) | `desktopRouter.config.tsx` |
|
||||
| Route Type | Use Case | Implementation |
|
||||
| ------------------ | --------------------------------- | ---------------------------------------------------------------------------- |
|
||||
| Next.js App Router | Auth pages (login, signup, oauth) | `src/app/[variants]/(auth)/` |
|
||||
| React Router DOM | Main SPA (chat, settings) | `desktopRouter.config.tsx` + `desktopRouter.config.desktop.tsx` (must match) |
|
||||
|
||||
### Key Files
|
||||
|
||||
- Entry: `src/spa/entry.web.tsx` (web), `src/spa/entry.mobile.tsx`, `src/spa/entry.desktop.tsx`
|
||||
- Desktop router: `src/spa/router/desktopRouter.config.tsx`
|
||||
- Desktop router (pair — **always edit both** when changing routes): `src/spa/router/desktopRouter.config.tsx` (dynamic imports) and `src/spa/router/desktopRouter.config.desktop.tsx` (sync imports). Drift can cause unregistered routes / blank screen.
|
||||
- Mobile router: `src/spa/router/mobileRouter.config.tsx`
|
||||
- Router utilities: `src/utils/router.tsx`
|
||||
|
||||
### `.desktop.{ts,tsx}` File Sync Rule
|
||||
|
||||
**CRITICAL**: Some files have a `.desktop.ts(x)` variant that Electron uses instead of the base file. When editing a base file, **always check** if a `.desktop` counterpart exists and update it in sync. Drift causes blank pages or missing features in Electron.
|
||||
|
||||
Known pairs that must stay in sync:
|
||||
|
||||
| Base file (web, dynamic imports) | Desktop file (Electron, sync imports) |
|
||||
| ----------------------------------------------------- | ------------------------------------------------------------- |
|
||||
| `src/spa/router/desktopRouter.config.tsx` | `src/spa/router/desktopRouter.config.desktop.tsx` |
|
||||
| `src/routes/(main)/settings/features/componentMap.ts` | `src/routes/(main)/settings/features/componentMap.desktop.ts` |
|
||||
|
||||
**How to check**: After editing any `.ts` / `.tsx` file, run `Glob` for `<filename>.desktop.{ts,tsx}` in the same directory. If a match exists, update it with the equivalent sync-import change.
|
||||
|
||||
### Router Utilities
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: spa-routes
|
||||
description: SPA route and feature structure. Use when adding or modifying SPA routes in src/routes, defining new route segments, or moving route logic into src/features. Covers how to keep routes thin and how to divide files between routes and features.
|
||||
description: MUST use when editing src/routes/ segments, src/spa/router/desktopRouter.config.tsx or desktopRouter.config.desktop.tsx (always change both together), mobileRouter.config.tsx, or when moving UI/logic between routes and src/features/.
|
||||
---
|
||||
|
||||
# SPA Routes and Features Guide
|
||||
@@ -13,6 +13,8 @@ SPA structure:
|
||||
|
||||
This project uses a **roots vs features** split: `src/routes/` only holds page segments; business logic and UI live in `src/features/` by domain.
|
||||
|
||||
**Agent constraint — desktop router parity:** Edits to the desktop route tree must update **both** `src/spa/router/desktopRouter.config.tsx` and `src/spa/router/desktopRouter.config.desktop.tsx` in the same change (same paths, nesting, index routes, and segment registration). Updating only one causes drift; the missing tree can fail to register routes and surface as a **blank screen** or broken navigation on the affected build.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Adding a new SPA route or route segment
|
||||
@@ -73,8 +75,21 @@ Each feature should:
|
||||
- Layout: `export { default } from '@/features/MyFeature/MyLayout'` or compose a few feature components + `<Outlet />`.
|
||||
- Page: import from `@/features/MyFeature` (or a specific subpath) and render; no business logic in the route file.
|
||||
|
||||
5. **Register the route**
|
||||
- Add the segment to `src/spa/router/desktopRouter.config.tsx` (or the right router config) with `dynamicElement` / `dynamicLayout` pointing at the new route paths (e.g. `@/routes/(main)/my-feature`).
|
||||
5. **Register the route (desktop — two files, always)**
|
||||
- **`desktopRouter.config.tsx`:** Add the segment with `dynamicElement` / `dynamicLayout` pointing at route modules (e.g. `@/routes/(main)/my-feature`).
|
||||
- **`desktopRouter.config.desktop.tsx`:** Mirror the **same** `RouteObject` shape: identical `path` / `index` / parent-child structure. Use the static imports and elements already used in that file (see neighboring routes). Do **not** register in only one of these files.
|
||||
- **Mobile-only flows:** use `mobileRouter.config.tsx` instead (no need to duplicate into the desktop pair unless the route truly exists on both).
|
||||
|
||||
---
|
||||
|
||||
## 3a. Desktop router pair (`desktopRouter.config` × 2)
|
||||
|
||||
| File | Role |
|
||||
|------|------|
|
||||
| `desktopRouter.config.tsx` | Dynamic imports via `dynamicElement` / `dynamicLayout` — code-splitting; used by `entry.web.tsx` and `entry.desktop.tsx`. |
|
||||
| `desktopRouter.config.desktop.tsx` | Same route tree with **synchronous** imports — kept for Electron / local parity and predictable bundling. |
|
||||
|
||||
Anything that changes the tree (new segment, renamed `path`, moved layout, new child route) must be reflected in **both** files in one PR or commit. Remove routes from both when deleting.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -162,11 +162,15 @@ describe('ModuleName', () => {
|
||||
### 5. Create Pull Request
|
||||
|
||||
- Create a new branch: `automatic/add-tests-[module-name]-[date]`
|
||||
|
||||
- Commit changes with message format:
|
||||
|
||||
```
|
||||
✅ test: add unit tests for [module-name]
|
||||
```
|
||||
|
||||
- Push the branch
|
||||
|
||||
- Create a PR with:
|
||||
|
||||
- Title: `✅ test: add unit tests for [module-name]`
|
||||
@@ -198,6 +202,7 @@ describe('ModuleName', () => {
|
||||
- Test approach: [brief description]
|
||||
|
||||
---
|
||||
|
||||
🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
||||
```
|
||||
|
||||
|
||||
@@ -77,20 +77,24 @@ Create `e2e/src/features/{module-name}/README.md` with:
|
||||
# {Module} 模块 E2E 测试覆盖
|
||||
|
||||
## 模块概述
|
||||
|
||||
**路由**: `/module`, `/module/[id]`
|
||||
|
||||
## 功能清单与测试覆盖
|
||||
|
||||
### 1. 功能分组名称
|
||||
|
||||
| 功能点 | 描述 | 优先级 | 状态 | 测试文件 |
|
||||
| ------ | ---- | ------ | ---- | -------- |
|
||||
| 功能点 | 描述 | 优先级 | 状态 | 测试文件 |
|
||||
| ------ | ---- | ------ | ---- | ------------- |
|
||||
| 功能A | xxx | P0 | ✅ | `xxx.feature` |
|
||||
| 功能B | xxx | P1 | ⏳ | |
|
||||
| 功能B | xxx | P1 | ⏳ | |
|
||||
|
||||
## 测试文件结构
|
||||
|
||||
## 测试执行
|
||||
|
||||
## 已知问题
|
||||
|
||||
## 更新记录
|
||||
```
|
||||
|
||||
@@ -228,7 +232,7 @@ const testId = pickle.tags.find(
|
||||
tag.name.startsWith('@COMMUNITY-') ||
|
||||
tag.name.startsWith('@AGENT-') ||
|
||||
tag.name.startsWith('@HOME-') ||
|
||||
tag.name.startsWith('@PAGE-') || // Add new prefix
|
||||
tag.name.startsWith('@PAGE-') || // Add new prefix
|
||||
tag.name.startsWith('@ROUTES-'),
|
||||
);
|
||||
```
|
||||
@@ -300,11 +304,15 @@ HEADLESS=true BASE_URL=http://localhost:3006 \
|
||||
### 10. Create Pull Request
|
||||
|
||||
- Branch name: `test/e2e-{module-name}`
|
||||
|
||||
- Commit message format:
|
||||
|
||||
```
|
||||
✅ test: add E2E tests for {module-name}
|
||||
```
|
||||
|
||||
- PR title: `✅ test: add E2E tests for {module-name}`
|
||||
|
||||
- PR body template:
|
||||
|
||||
````markdown
|
||||
|
||||
@@ -36,6 +36,7 @@ If you detect any leaked secrets, respond IMMEDIATELY with:
|
||||
⚠️ **Security Warning**: Your comment appears to contain sensitive information (API keys, secrets, or credentials).
|
||||
|
||||
**Please delete your comment immediately** to protect your account security, then:
|
||||
|
||||
1. Rotate/regenerate any exposed credentials
|
||||
2. Re-post your question with secrets redacted (e.g., `AUTH_SECRET=***`)
|
||||
|
||||
@@ -73,12 +74,17 @@ Look for the "Troubleshooting" or "FAQ" section in the migration docs and match
|
||||
## Response Guidelines
|
||||
|
||||
1. **Be helpful and friendly** - Users are often frustrated when migration doesn't work
|
||||
|
||||
2. **Be specific** - Provide exact commands or configuration examples
|
||||
|
||||
3. **Reference documentation** - Point users to relevant docs sections
|
||||
|
||||
4. **Ask for logs** - If the issue is unclear, ask for Docker logs:
|
||||
|
||||
```bash
|
||||
docker logs <container_name> 2>&1 | tail -100
|
||||
```
|
||||
|
||||
5. **One issue at a time** - Focus on solving one problem before moving to the next
|
||||
|
||||
## Response Format
|
||||
@@ -90,6 +96,7 @@ Use this format for your responses:
|
||||
|
||||
[If missing information]
|
||||
To help you effectively, please provide:
|
||||
|
||||
- [List missing items]
|
||||
|
||||
[If you can help]
|
||||
@@ -102,6 +109,7 @@ Based on your description, here's what I suggest:
|
||||
|
||||
[If the issue is complex or unknown]
|
||||
This issue needs further investigation. I've notified the team. In the meantime, please:
|
||||
|
||||
1. [Any immediate steps they can try]
|
||||
2. Share your Docker logs if you haven't already
|
||||
```
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
## Quick Reference by Name
|
||||
|
||||
- **@arvinxx**: Last resort only, mention for priority:high issues, tool calling , mcp
|
||||
- **@arvinxx**: Last resort only, mention for priority:high issues, tool calling, mcp, database
|
||||
- **@canisminor1990**: Design, UI components, editor, markdown rendering
|
||||
- **@tjx666**: Image/video generation, vision, cloud version, documentation, TTS, auth, login/register
|
||||
- **@ONLY-yours**: Performance, streaming, settings, general bugs, web platform, marketplace
|
||||
- **@RiverTwilight**: Knowledge base, files (KB-related), group chat
|
||||
- **@nekomeowww**: Memory, backend, deployment, DevOps
|
||||
- **@tjx666**: Image/video generation, vision, cloud version, documentation, TTS, auth, login/register, database
|
||||
- **@ONLY-yours**: Performance, streaming, settings, general bugs, web platform, marketplace, agent builder, schedule task
|
||||
- **@Innei**: Knowledge base, files (KB-related), group chat, Electron, desktop client, build system
|
||||
- **@nekomeowww**: Memory, backend, deployment, DevOps, database
|
||||
- **@sudongyuer**: Mobile app (React Native)
|
||||
- **@sxjeru**: Model providers and configuration
|
||||
- **@rdmclin2**: Team workspace
|
||||
- **@rdmclin2**: Team workspace, IM and bot integration
|
||||
- **@tcmonster**: Subscription, refund, recharge, business cooperation
|
||||
|
||||
Quick reference for assigning issues based on labels.
|
||||
@@ -28,7 +28,7 @@ Quick reference for assigning issues based on labels.
|
||||
| Label | Owner | Notes |
|
||||
| ------------------ | ----------- | -------------------------------------- |
|
||||
| `platform:mobile` | @sudongyuer | React Native mobile app |
|
||||
| `platform:desktop` | @ONLY-yours | Electron desktop client (general) |
|
||||
| `platform:desktop` | @Innei | Electron desktop client, build system |
|
||||
| `platform:web` | @ONLY-yours | Web platform (unless specific feature) |
|
||||
|
||||
### Feature Labels (feature:\*)
|
||||
@@ -38,8 +38,8 @@ Quick reference for assigning issues based on labels.
|
||||
| `feature:image` | @tjx666 | AI image generation |
|
||||
| `feature:dalle` | @tjx666 | DALL-E related |
|
||||
| `feature:vision` | @tjx666 | Vision/multimodal generation |
|
||||
| `feature:knowledge-base` | @RiverTwilight | Knowledge base and RAG |
|
||||
| `feature:files` | @RiverTwilight | File upload/management (when KB-related)<br>@ONLY-yours (general files) |
|
||||
| `feature:knowledge-base` | @Innei | Knowledge base and RAG |
|
||||
| `feature:files` | @Innei | File upload/management (when KB-related)<br>@ONLY-yours (general files) |
|
||||
| `feature:editor` | @canisminor1990 | Lobe Editor |
|
||||
| `feature:markdown` | @canisminor1990 | Markdown rendering |
|
||||
| `feature:auth` | @tjx666 | Authentication/authorization |
|
||||
@@ -57,9 +57,12 @@ Quick reference for assigning issues based on labels.
|
||||
| `feature:search` | @ONLY-yours | Search functionality |
|
||||
| `feature:tts` | @tjx666 | Text-to-speech |
|
||||
| `feature:export` | @ONLY-yours | Export functionality |
|
||||
| `feature:group-chat` | @RiverTwilight | Group chat functionality |
|
||||
| `feature:group-chat` | @arvinxx | Group chat functionality |
|
||||
| `feature:memory` | @nekomeowww | Memory feature |
|
||||
| `feature:team-workspace` | @rdmclin2 | Team workspace application |
|
||||
| `feature:im-integration` | @rdmclin2 | IM and bot integration (Slack, Discord, etc.) |
|
||||
| `feature:agent-builder` | @ONLY-yours | Agent builder |
|
||||
| `feature:schedule-task` | @ONLY-yours | Schedule task |
|
||||
| `feature:subscription` | @tcmonster | Subscription and billing |
|
||||
| `feature:refund` | @tcmonster | Refund requests |
|
||||
| `feature:recharge` | @tcmonster | Recharge and payment |
|
||||
@@ -125,18 +128,18 @@ Quick reference for assigning issues based on labels.
|
||||
|
||||
**Single owner:**
|
||||
|
||||
```
|
||||
```plaintext
|
||||
@username - This is a [feature/component] issue. Please take a look.
|
||||
```
|
||||
|
||||
**Multiple owners:**
|
||||
|
||||
```
|
||||
```plaintext
|
||||
@primary @secondary - This involves [features]. Please coordinate.
|
||||
```
|
||||
|
||||
**High priority:**
|
||||
|
||||
```
|
||||
```plaintext
|
||||
@owner @arvinxx - High priority [feature] issue.
|
||||
```
|
||||
|
||||
@@ -72,11 +72,15 @@ Module granularity examples:
|
||||
### 5. Create Pull Request
|
||||
|
||||
- Create a new branch: `automatic/translate-comments-[module-name]-[date]`
|
||||
|
||||
- Commit changes with message format:
|
||||
|
||||
```
|
||||
🌐 chore: translate non-English comments to English in [module-name]
|
||||
```
|
||||
|
||||
- Push the branch
|
||||
|
||||
- Create a PR with:
|
||||
|
||||
- Title: `🌐 chore: translate non-English comments to English in [module-name]`
|
||||
@@ -100,6 +104,7 @@ Module granularity examples:
|
||||
`[module-path]`
|
||||
|
||||
---
|
||||
|
||||
🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
||||
```
|
||||
|
||||
|
||||
@@ -9,16 +9,10 @@ inputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ inputs.node-version }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Setup Environment
|
||||
description: Setup Node.js, pnpm (install) and Bun (script runner) for workflows
|
||||
|
||||
inputs:
|
||||
node-version:
|
||||
description: Node.js version
|
||||
required: false
|
||||
default: '24.11.1'
|
||||
package-manager-cache:
|
||||
description: Pass-through to actions/setup-node package-manager-cache
|
||||
required: false
|
||||
default: 'false'
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
run_install: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ inputs.node-version }}
|
||||
package-manager-cache: ${{ inputs.package-manager-cache }}
|
||||
@@ -0,0 +1,13 @@
|
||||
AmAzing129
|
||||
arvinxx
|
||||
canisminor1990
|
||||
ilimei
|
||||
Innei
|
||||
lobehubbot
|
||||
nekomeowww
|
||||
ONLY-yours
|
||||
rdmclin2
|
||||
rivertwilight
|
||||
sudongyuer
|
||||
tcmonster
|
||||
tjx666
|
||||
@@ -3,7 +3,7 @@ name: Daily i18n Update
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * *'
|
||||
workflow_dispatch:
|
||||
workflow_dispatch: {}
|
||||
|
||||
# Add permissions configuration
|
||||
permissions:
|
||||
@@ -25,13 +25,11 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.ref }}
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: ${{ secrets.BUN_VERSION }}
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Update i18n
|
||||
run: bun run i18n
|
||||
|
||||
@@ -26,8 +26,9 @@ jobs:
|
||||
|
||||
- name: Detect release PR (version from title)
|
||||
id: release
|
||||
env:
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
run: |
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
echo "PR Title: $PR_TITLE"
|
||||
|
||||
# Match "🚀 release: v{x.x.x}" format (strict semver: x.y.z with optional -prerelease or +build)
|
||||
@@ -44,9 +45,10 @@ jobs:
|
||||
- name: Detect patch PR (branch first, title fallback)
|
||||
id: patch
|
||||
if: steps.release.outputs.should_tag != 'true'
|
||||
env:
|
||||
HEAD_REF: ${{ github.event.pull_request.head.ref }}
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
run: |
|
||||
HEAD_REF="${{ github.event.pull_request.head.ref }}"
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
echo "Head ref: $HEAD_REF"
|
||||
echo "PR Title: $PR_TITLE"
|
||||
|
||||
@@ -72,22 +74,13 @@ jobs:
|
||||
git checkout main
|
||||
git pull --rebase origin main
|
||||
|
||||
- name: Setup Node.js
|
||||
- name: Setup environment
|
||||
if: steps.release.outputs.should_tag == 'true' || steps.patch.outputs.should_tag == 'true'
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
if: steps.release.outputs.should_tag == 'true' || steps.patch.outputs.should_tag == 'true'
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
if: steps.release.outputs.should_tag == 'true' || steps.patch.outputs.should_tag == 'true'
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Resolve patch version (patch bump)
|
||||
id: patch-version
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Bundle Analyzer
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -9,7 +9,6 @@ permissions:
|
||||
|
||||
env:
|
||||
NODE_VERSION: 24.11.1
|
||||
BUN_VERSION: 1.2.23
|
||||
|
||||
jobs:
|
||||
bundle-analyzer:
|
||||
@@ -20,19 +19,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: ${{ env.BUN_VERSION }}
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm i
|
||||
|
||||
|
||||
@@ -51,11 +51,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Install Playwright browsers (with system deps)
|
||||
run: bunx playwright install --with-deps chromium
|
||||
|
||||
@@ -29,11 +29,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
|
||||
@@ -18,6 +18,16 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Check if author is a team member
|
||||
id: check-team
|
||||
run: |
|
||||
ISSUE_AUTHOR="${{ github.event.issue.user.login }}"
|
||||
if grep -iq "^${ISSUE_AUTHOR}$" .github/maintainers.txt; then
|
||||
echo "is_team=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_team=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Copy triage prompts
|
||||
run: |
|
||||
mkdir -p /tmp/claude-prompts
|
||||
@@ -62,7 +72,7 @@ jobs:
|
||||
**IMPORTANT**:
|
||||
- Follow ALL steps in the issue-triage.md guide
|
||||
- Apply labels according to the guide's rules
|
||||
- Post a mention comment to the appropriate team member(s) based on team-assignment.md
|
||||
- ${{ steps.check-team.outputs.is_team == 'true' && 'The issue author is a team member. Do NOT post any @mention comment.' || 'Post a mention comment to the appropriate team member(s) based on team-assignment.md' }}
|
||||
- Replace [ISSUE_NUMBER] with: ${{ github.event.issue.number }}
|
||||
|
||||
**Start the triage process now.**
|
||||
|
||||
@@ -21,7 +21,18 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Check if author is a team member
|
||||
id: check-team
|
||||
run: |
|
||||
PR_AUTHOR="${{ github.event.pull_request.user.login }}"
|
||||
if grep -iq "^${PR_AUTHOR}$" .github/maintainers.txt; then
|
||||
echo "is_team=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_team=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Copy prompts
|
||||
if: steps.check-team.outputs.is_team == 'false'
|
||||
run: |
|
||||
mkdir -p /tmp/claude-prompts
|
||||
cp .claude/prompts/pr-assign.md /tmp/claude-prompts/
|
||||
@@ -29,6 +40,7 @@ jobs:
|
||||
cp .claude/prompts/security-rules.md /tmp/claude-prompts/
|
||||
|
||||
- name: Run Claude Code for PR Reviewer Assignment
|
||||
if: steps.check-team.outputs.is_team == 'false'
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
github_token: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
@@ -55,5 +55,5 @@ jobs:
|
||||
# Security: Allow only specific safe commands - no gh commands to prevent token exfiltration
|
||||
# These tools are restricted to code analysis and build operations only
|
||||
claude_args: |
|
||||
--allowedTools "Bash(git:*),Bash(gh:*),Bash(bun run:*),Bash(pnpm run:*),Bash(npm run:*),Bash(npx:*),Bash(bunx:*),Bash(vitest:*),Bash(rg:*),Bash(find:*),Bash(sed:*),Bash(grep:*),Bash(awk:*),Bash(wc:*),Bash(xargs:*)"
|
||||
--allowedTools "Bash(git:*),Bash(gh:*),Bash(bun run:*),Bash(bunx:*),Bash(pnpm:*),Bash(npm run:*),Bash(npx:*),Bash(vitest:*),Bash(rg:*),Bash(find:*),Bash(sed:*),Bash(grep:*),Bash(awk:*),Bash(wc:*),Bash(xargs:*)"
|
||||
--append-system-prompt "$(cat /tmp/claude-prompts/security-rules.md)"
|
||||
|
||||
@@ -61,13 +61,11 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install dependencies (bun)
|
||||
run: bun install
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Install Playwright browsers (with system deps)
|
||||
run: bunx playwright install --with-deps chromium
|
||||
|
||||
@@ -3,7 +3,7 @@ description: Auto-closes issues that are duplicates of existing issues
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch:
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
auto-close-duplicates:
|
||||
@@ -17,10 +17,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Auto-close duplicate issues
|
||||
run: bun run .github/scripts/auto-close-duplicates.ts
|
||||
|
||||
@@ -28,9 +28,21 @@ jobs:
|
||||
✅ @{{ author }}
|
||||
|
||||
This issue is closed, If you have any questions, you can comment and reply.
|
||||
- name: Checkout repository
|
||||
if: github.event_name == 'pull_request_target' && github.event.pull_request.merged == true
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check if PR author is maintainer
|
||||
if: github.event.pull_request.merged == true
|
||||
id: maintainer-check
|
||||
run: |
|
||||
if [ -f .github/maintainers.txt ] && grep -qx "${{ github.event.pull_request.user.login }}" .github/maintainers.txt; then
|
||||
echo "skip=true" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Auto Comment on Pull Request Merged
|
||||
uses: actions-cool/pr-welcome@main
|
||||
if: github.event.pull_request.merged == true
|
||||
if: github.event.pull_request.merged == true && steps.maintainer-check.outputs.skip != 'true'
|
||||
with:
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
comment: |
|
||||
|
||||
@@ -6,10 +6,10 @@ on:
|
||||
channel:
|
||||
description: 'Release channel for desktop build (affects version suffix and workflow:set-desktop-version)'
|
||||
required: true
|
||||
default: nightly
|
||||
default: canary
|
||||
type: choice
|
||||
options:
|
||||
- nightly
|
||||
- canary
|
||||
- beta
|
||||
- stable
|
||||
build_macos:
|
||||
@@ -41,7 +41,6 @@ permissions:
|
||||
|
||||
env:
|
||||
NODE_VERSION: 24.11.1
|
||||
BUN_VERSION: 1.2.23
|
||||
|
||||
jobs:
|
||||
version:
|
||||
@@ -102,18 +101,10 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node & pnpm
|
||||
uses: ./.github/actions/setup-node-pnpm
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: 'false'
|
||||
|
||||
# node-linker=hoisted 模式将可以确保 asar 压缩可用
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --node-linker=hoisted &
|
||||
npm run install-isolated --prefix=./apps/desktop &
|
||||
wait
|
||||
|
||||
- name: Set package version
|
||||
run: npm run workflow:set-desktop-version ${{ needs.version.outputs.version }} ${{ inputs.channel }}
|
||||
@@ -127,8 +118,8 @@ jobs:
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
CSC_LINK: ${{ secrets.APPLE_CERTIFICATE_BASE64 }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'beta' && secrets.UMAMI_BETA_DESKTOP_PROJECT_ID || secrets.UMAMI_NIGHTLY_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'beta' && secrets.UMAMI_BETA_DESKTOP_BASE_URL || secrets.UMAMI_NIGHTLY_DESKTOP_BASE_URL }}
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_PROJECT_ID || secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_BASE_URL || secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
CSC_FOR_PULL_REQUEST: true
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
@@ -193,8 +184,8 @@ jobs:
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'beta' && secrets.UMAMI_BETA_DESKTOP_PROJECT_ID || secrets.UMAMI_NIGHTLY_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'beta' && secrets.UMAMI_BETA_DESKTOP_BASE_URL || secrets.UMAMI_NIGHTLY_DESKTOP_BASE_URL }}
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_PROJECT_ID || secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_BASE_URL || secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
TEMP: C:\temp
|
||||
TMP: C:\temp
|
||||
|
||||
@@ -222,17 +213,10 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node & pnpm
|
||||
uses: ./.github/actions/setup-node-pnpm
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: 'false'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --node-linker=hoisted &
|
||||
npm run install-isolated --prefix=./apps/desktop &
|
||||
wait
|
||||
|
||||
- name: Set package version
|
||||
run: npm run workflow:set-desktop-version ${{ needs.version.outputs.version }} ${{ inputs.channel }}
|
||||
@@ -244,8 +228,8 @@ jobs:
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'beta' && secrets.UMAMI_BETA_DESKTOP_PROJECT_ID || secrets.UMAMI_NIGHTLY_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'beta' && secrets.UMAMI_BETA_DESKTOP_BASE_URL || secrets.UMAMI_NIGHTLY_DESKTOP_BASE_URL }}
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_PROJECT_ID || secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_BASE_URL || secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
@@ -274,12 +258,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node & Bun
|
||||
uses: ./.github/actions/setup-node-bun
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
bun-version: ${{ env.BUN_VERSION }}
|
||||
package-manager-cache: 'false'
|
||||
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
|
||||
@@ -27,15 +27,11 @@ jobs:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node & Bun
|
||||
uses: ./.github/actions/setup-node-bun
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
bun-version: latest
|
||||
package-manager-cache: 'false'
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
|
||||
@@ -93,29 +89,10 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node & pnpm
|
||||
uses: ./.github/actions/setup-node-pnpm
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: 'false'
|
||||
|
||||
# node-linker=hoisted 模式将可以确保 asar 压缩可用
|
||||
- name: Install dependencies
|
||||
run: pnpm install --node-linker=hoisted
|
||||
|
||||
# 移除国内 electron 镜像配置,GitHub Actions 使用官方源更快
|
||||
- name: Remove China electron mirror from .npmrc
|
||||
shell: bash
|
||||
run: |
|
||||
NPMRC_FILE="./apps/desktop/.npmrc"
|
||||
if [ -f "$NPMRC_FILE" ]; then
|
||||
sed -i.bak '/^electron_mirror=/d; /^electron_builder_binaries_mirror=/d' "$NPMRC_FILE"
|
||||
rm -f "${NPMRC_FILE}.bak"
|
||||
echo "✅ Removed electron mirror config from .npmrc"
|
||||
fi
|
||||
|
||||
- name: Install deps on Desktop
|
||||
run: npm run install-isolated --prefix=./apps/desktop
|
||||
|
||||
# 设置 package.json 的版本号
|
||||
- name: Set package version
|
||||
@@ -228,12 +205,8 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node & Bun
|
||||
uses: ./.github/actions/setup-node-bun
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
bun-version: latest
|
||||
package-manager-cache: 'false'
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
# 下载所有平台的构建产物
|
||||
- name: Download artifacts
|
||||
@@ -251,13 +224,11 @@ jobs:
|
||||
- name: Install yaml only for merge step
|
||||
run: |
|
||||
cd scripts/electronWorkflow
|
||||
# 在脚本目录创建最小 package.json,防止 bun 向上寻找根 package.json
|
||||
if [ ! -f package.json ]; then
|
||||
echo '{"name":"merge-mac-release","private":true}' > package.json
|
||||
fi
|
||||
bun add --no-save yaml@2.8.1
|
||||
|
||||
# 合并 macOS YAML 文件 (使用 bun 运行 JavaScript)
|
||||
- name: Merge latest-mac.yml files
|
||||
run: bun run scripts/electronWorkflow/mergeMacReleaseFiles.js
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ name: Release Desktop Beta
|
||||
# 如: v2.0.0-beta.1, v2.0.0-alpha.1, v2.0.0-rc.1
|
||||
#
|
||||
# 注意: Stable 版本 (如 v2.0.0) 由 release-desktop-stable.yml 处理
|
||||
# 注意: Nightly 版本 (如 v2.1.0-nightly.xxx) 由 release-desktop-nightly.yml 处理
|
||||
# 注意: Nightly 版本已停用,不再参与 Desktop 发布流程
|
||||
# ============================================
|
||||
|
||||
on:
|
||||
@@ -41,10 +41,10 @@ jobs:
|
||||
version="${version#v}"
|
||||
echo "version=${version}" >> $GITHUB_OUTPUT
|
||||
|
||||
# Beta 版本包含 beta/alpha/rc (nightly 由 release-desktop-nightly.yml 处理)
|
||||
# Beta 版本包含 beta/alpha/rc;nightly 标签已停用
|
||||
if [[ "$version" == *"nightly"* ]]; then
|
||||
echo "is_beta=false" >> $GITHUB_OUTPUT
|
||||
echo "⏭️ Skipping: $version is a nightly release (handled by release-desktop-nightly.yml)"
|
||||
echo "⏭️ Skipping: $version is a disabled nightly release tag"
|
||||
elif [[ "$version" == *"beta"* ]] || [[ "$version" == *"alpha"* ]] || [[ "$version" == *"rc"* ]]; then
|
||||
echo "is_beta=true" >> $GITHUB_OUTPUT
|
||||
echo "✅ Beta release detected: $version"
|
||||
@@ -62,19 +62,13 @@ jobs:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
@@ -168,16 +162,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
# 下载所有平台的构建产物
|
||||
- name: Download artifacts
|
||||
@@ -195,13 +183,11 @@ jobs:
|
||||
- name: Install yaml only for merge step
|
||||
run: |
|
||||
cd scripts/electronWorkflow
|
||||
# 在脚本目录创建最小 package.json,防止 bun 向上寻找根 package.json
|
||||
if [ ! -f package.json ]; then
|
||||
echo '{"name":"merge-mac-release","private":true}' > package.json
|
||||
fi
|
||||
bun add --no-save yaml@2.8.1
|
||||
|
||||
# 合并 macOS YAML 文件 (使用 bun 运行 JavaScript)
|
||||
- name: Merge latest-mac.yml files
|
||||
run: bun run scripts/electronWorkflow/mergeMacReleaseFiles.js
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ jobs:
|
||||
name: Calculate Canary Version
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
release_notes: ${{ steps.release-notes.outputs.release_notes }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
should_build: ${{ steps.check.outputs.should_build }}
|
||||
@@ -121,6 +122,66 @@ jobs:
|
||||
echo "✅ Canary version: ${version}"
|
||||
echo "🏷️ Tag: ${tag}"
|
||||
|
||||
- name: Generate canary release notes
|
||||
if: steps.check.outputs.should_build == 'true'
|
||||
id: release-notes
|
||||
env:
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
run: |
|
||||
previous_canary=$(git tag --sort=-creatordate | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+-canary\.[0-9]+$' | head -n 1)
|
||||
latest_stable=$(git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1)
|
||||
|
||||
if [ -n "$previous_canary" ]; then
|
||||
compare_from="$previous_canary"
|
||||
compare_range="${previous_canary}..HEAD"
|
||||
elif [ -n "$latest_stable" ]; then
|
||||
compare_from="$latest_stable"
|
||||
compare_range="${latest_stable}..HEAD"
|
||||
else
|
||||
compare_from="initial commit"
|
||||
compare_range="HEAD"
|
||||
fi
|
||||
|
||||
commit_count=$(git rev-list --count "$compare_range")
|
||||
commits=$(git log --no-merges --pretty='- `%h` %s (%an)' "$compare_range")
|
||||
|
||||
if [ -z "$commits" ]; then
|
||||
commits='- No new commits recorded.'
|
||||
fi
|
||||
|
||||
{
|
||||
echo "release_notes<<EOF"
|
||||
echo "## 🐤 Canary Build — ${TAG}"
|
||||
echo
|
||||
echo "> Automated canary build from \`canary\` branch."
|
||||
echo
|
||||
echo "### Commit Information"
|
||||
echo
|
||||
echo "- Based on changes since \`${compare_from}\`"
|
||||
echo "- Commit count: ${commit_count}"
|
||||
echo
|
||||
printf '%s\n' "$commits"
|
||||
echo
|
||||
echo "### ⚠️ Important Notes"
|
||||
echo
|
||||
echo "- **This is an automated canary build and is NOT intended for production use.**"
|
||||
echo "- Canary builds are triggered by \`build\`/\`fix\`/\`style\` commits on the \`canary\` branch."
|
||||
echo "- May contain **unstable or incomplete changes**. **Use at your own risk.**"
|
||||
echo "- It is strongly recommended to **back up your data** before using a canary build."
|
||||
echo
|
||||
echo "### 📦 Installation"
|
||||
echo
|
||||
echo "Download the appropriate installer for your platform from the assets below."
|
||||
echo
|
||||
echo "| Platform | File |"
|
||||
echo "|----------|------|"
|
||||
echo "| macOS (Apple Silicon) | \`.dmg\` (arm64) |"
|
||||
echo "| macOS (Intel) | \`.dmg\` (x64) |"
|
||||
echo "| Windows | \`.exe\` |"
|
||||
echo "| Linux | \`.AppImage\` / \`.deb\` |"
|
||||
echo "EOF"
|
||||
} >> $GITHUB_OUTPUT
|
||||
|
||||
# ============================================
|
||||
# 代码质量检查
|
||||
# ============================================
|
||||
@@ -133,19 +194,13 @@ jobs:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
@@ -188,6 +243,7 @@ jobs:
|
||||
env:
|
||||
UPDATE_CHANNEL: canary
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -207,6 +263,7 @@ jobs:
|
||||
env:
|
||||
UPDATE_CHANNEL: canary
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -222,6 +279,7 @@ jobs:
|
||||
env:
|
||||
UPDATE_CHANNEL: canary
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -247,16 +305,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
@@ -311,28 +363,7 @@ jobs:
|
||||
tag_name: ${{ needs.calculate-version.outputs.tag }}
|
||||
name: 'Desktop Canary ${{ needs.calculate-version.outputs.tag }}'
|
||||
prerelease: true
|
||||
body: |
|
||||
## 🐤 Canary Build — ${{ needs.calculate-version.outputs.tag }}
|
||||
|
||||
> Automated canary build from `canary` branch.
|
||||
|
||||
### ⚠️ Important Notes
|
||||
|
||||
- **This is an automated canary build and is NOT intended for production use.**
|
||||
- Canary builds are triggered by `build`/`fix`/`style` commits on the `canary` branch.
|
||||
- May contain **unstable or incomplete changes**. **Use at your own risk.**
|
||||
- It is strongly recommended to **back up your data** before using a canary build.
|
||||
|
||||
### 📦 Installation
|
||||
|
||||
Download the appropriate installer for your platform from the assets below.
|
||||
|
||||
| Platform | File |
|
||||
|----------|------|
|
||||
| macOS (Apple Silicon) | `.dmg` (arm64) |
|
||||
| macOS (Intel) | `.dmg` (x64) |
|
||||
| Windows | `.exe` |
|
||||
| Linux | `.AppImage` / `.deb` |
|
||||
body: ${{ needs.calculate-version.outputs.release_notes }}
|
||||
files: |
|
||||
release/latest*
|
||||
release/*.dmg*
|
||||
|
||||
@@ -1,427 +0,0 @@
|
||||
name: Release Desktop Nightly
|
||||
|
||||
# ============================================
|
||||
# Nightly 自动发版工作流
|
||||
# ============================================
|
||||
# 触发条件:
|
||||
# 1. 定时: 每天 UTC+8 14:00 (UTC 06:00)
|
||||
# 2. 手动触发 (workflow_dispatch)
|
||||
#
|
||||
# 版本策略:
|
||||
# 基于最新 tag 的 minor+1, 格式: X.(Y+1).0-nightly.YYYYMMDDHHMM
|
||||
# 例: 当前 tag v2.0.12 → v2.1.0-nightly.202502091400
|
||||
# 使用精确到分钟的时间戳避免同一天多次触发时 tag 冲突
|
||||
# ============================================
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 6 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: 'Force build (skip diff check)'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions: read-all
|
||||
|
||||
env:
|
||||
NODE_VERSION: '24.11.1'
|
||||
|
||||
jobs:
|
||||
# ============================================
|
||||
# 计算 Nightly 版本号
|
||||
# ============================================
|
||||
calculate-version:
|
||||
name: Calculate Nightly Version
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
has_changes: ${{ steps.changes.outputs.has_changes }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check for code changes since last nightly
|
||||
id: changes
|
||||
run: |
|
||||
# 手动触发 + force 时跳过 diff 检查
|
||||
if [ "${{ inputs.force }}" == "true" ]; then
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
echo "🔧 Force build requested, skipping diff check"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 查找上一个 nightly tag
|
||||
last_nightly=$(git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+-nightly\.' | head -n 1)
|
||||
|
||||
if [ -z "$last_nightly" ]; then
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
echo "📦 No previous nightly tag found, proceeding with first nightly build"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "📌 Last nightly tag: $last_nightly"
|
||||
|
||||
# 对比指定目录是否有变更
|
||||
changes=$(git diff --name-only "$last_nightly"..HEAD -- package.json src/ packages/ apps/desktop/)
|
||||
|
||||
if [ -z "$changes" ]; then
|
||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
||||
echo "⏭️ No code changes since $last_nightly, skipping nightly build"
|
||||
else
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
change_count=$(echo "$changes" | wc -l | tr -d ' ')
|
||||
echo "✅ ${change_count} file(s) changed since $last_nightly:"
|
||||
echo "$changes" | head -20
|
||||
[ "$change_count" -gt 20 ] && echo " ... and $((change_count - 20)) more"
|
||||
fi
|
||||
|
||||
- name: Calculate nightly version
|
||||
if: steps.changes.outputs.has_changes == 'true'
|
||||
id: version
|
||||
run: |
|
||||
# 获取最新的 tag (排除 nightly tag)
|
||||
latest_tag=$(git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1)
|
||||
|
||||
if [ -z "$latest_tag" ]; then
|
||||
echo "❌ No stable tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📌 Latest stable tag: $latest_tag"
|
||||
|
||||
# 去掉 v 前缀
|
||||
base_version="${latest_tag#v}"
|
||||
|
||||
# 解析 major.minor.patch
|
||||
IFS='.' read -r major minor patch <<< "$base_version"
|
||||
|
||||
# minor + 1, patch 归零
|
||||
new_minor=$((minor + 1))
|
||||
timestamp=$(date -u +"%Y%m%d%H%M")
|
||||
|
||||
version="${major}.${new_minor}.0-nightly.${timestamp}"
|
||||
tag="v${version}"
|
||||
|
||||
echo "version=${version}" >> $GITHUB_OUTPUT
|
||||
echo "tag=${tag}" >> $GITHUB_OUTPUT
|
||||
echo "✅ Nightly version: ${version}"
|
||||
echo "🏷️ Tag: ${tag}"
|
||||
|
||||
# ============================================
|
||||
# 代码质量检查
|
||||
# ============================================
|
||||
test:
|
||||
name: Code quality check
|
||||
needs: [calculate-version]
|
||||
if: needs.calculate-version.outputs.has_changes == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
# ============================================
|
||||
# 多平台构建
|
||||
# ============================================
|
||||
build:
|
||||
needs: [calculate-version, test]
|
||||
if: needs.calculate-version.outputs.has_changes == 'true'
|
||||
name: Build Desktop App
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-15, macos-15-intel, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Set package version
|
||||
run: npm run workflow:set-desktop-version ${{ needs.calculate-version.outputs.version }} nightly
|
||||
|
||||
# macOS 构建前清理 (修复 hdiutil 问题 https://github.com/electron-userland/electron-builder/issues/8415)
|
||||
- name: Clean previous build artifacts (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: |
|
||||
sudo rm -rf apps/desktop/release || true
|
||||
sudo rm -rf apps/desktop/dist || true
|
||||
sudo rm -rf /tmp/electron-builder* || true
|
||||
|
||||
# macOS 构建
|
||||
- name: Build artifact on macOS
|
||||
if: runner.os == 'macOS'
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: nightly
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
CSC_LINK: ${{ secrets.APPLE_CERTIFICATE_BASE64 }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
CSC_FOR_PULL_REQUEST: true
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
|
||||
# Windows 构建
|
||||
- name: Build artifact on Windows
|
||||
if: runner.os == 'Windows'
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: nightly
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
TEMP: C:\temp
|
||||
TMP: C:\temp
|
||||
|
||||
# Linux 构建
|
||||
- name: Build artifact on Linux
|
||||
if: runner.os == 'Linux'
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: nightly
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: ./.github/actions/desktop-upload-artifacts
|
||||
with:
|
||||
artifact-name: release-${{ matrix.os }}
|
||||
retention-days: 3
|
||||
|
||||
# ============================================
|
||||
# 合并 macOS 多架构 latest-mac.yml 文件
|
||||
# ============================================
|
||||
merge-mac-files:
|
||||
needs: [build]
|
||||
name: Merge macOS Release Files
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: release
|
||||
pattern: release-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: List downloaded artifacts
|
||||
run: ls -R release
|
||||
|
||||
- name: Install yaml only for merge step
|
||||
run: |
|
||||
cd scripts/electronWorkflow
|
||||
if [ ! -f package.json ]; then
|
||||
echo '{"name":"merge-mac-release","private":true}' > package.json
|
||||
fi
|
||||
bun add --no-save yaml@2.8.1
|
||||
|
||||
- name: Merge latest-mac.yml files
|
||||
run: bun run scripts/electronWorkflow/mergeMacReleaseFiles.js
|
||||
|
||||
- name: Upload artifacts with merged macOS files
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: merged-release
|
||||
path: release/
|
||||
retention-days: 1
|
||||
|
||||
# ============================================
|
||||
# 创建 Nightly Release
|
||||
# ============================================
|
||||
publish-release:
|
||||
needs: [merge-mac-files, calculate-version]
|
||||
name: Publish Nightly Release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Download merged artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: merged-release
|
||||
path: release
|
||||
|
||||
- name: List final artifacts
|
||||
run: ls -R release
|
||||
|
||||
- name: Create Nightly Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ needs.calculate-version.outputs.tag }}
|
||||
name: 'Desktop Nightly ${{ needs.calculate-version.outputs.tag }}'
|
||||
prerelease: true
|
||||
body: |
|
||||
## 🌙 Nightly Build — ${{ needs.calculate-version.outputs.tag }}
|
||||
|
||||
> Automated nightly build from `main` branch.
|
||||
|
||||
### ⚠️ Important Notes
|
||||
|
||||
- **This is an automated nightly build and is NOT intended for production use.**
|
||||
- Nightly builds are generated from the latest `main` branch and may contain **unstable, untested, or incomplete features**.
|
||||
- **No guarantees** are made regarding stability, data integrity, or backward compatibility.
|
||||
- Bugs, crashes, and breaking changes are expected. **Use at your own risk.**
|
||||
- **Do NOT report bugs** from nightly builds unless you can reproduce them on the latest beta or stable release.
|
||||
- Nightly builds may have **different update channels** — they will not auto-update to/from stable or beta versions.
|
||||
- It is strongly recommended to **back up your data** before using a nightly build.
|
||||
|
||||
### 📦 Installation
|
||||
|
||||
Download the appropriate installer for your platform from the assets below.
|
||||
|
||||
| Platform | File |
|
||||
|----------|------|
|
||||
| macOS (Apple Silicon) | `.dmg` (arm64) |
|
||||
| macOS (Intel) | `.dmg` (x64) |
|
||||
| Windows | `.exe` |
|
||||
| Linux | `.AppImage` / `.deb` |
|
||||
files: |
|
||||
release/latest*
|
||||
release/*.dmg*
|
||||
release/*.zip*
|
||||
release/*.exe*
|
||||
release/*.AppImage
|
||||
release/*.deb*
|
||||
release/*.snap*
|
||||
release/*.rpm*
|
||||
release/*.tar.gz*
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# ============================================
|
||||
# 发布到 S3 更新服务器
|
||||
# ============================================
|
||||
publish-s3:
|
||||
needs: [merge-mac-files, calculate-version]
|
||||
name: Publish to S3
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ./.github/actions/desktop-publish-s3
|
||||
with:
|
||||
channel: nightly
|
||||
version: ${{ needs.calculate-version.outputs.version }}
|
||||
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
s3-region: ${{ secrets.UPDATE_S3_REGION }}
|
||||
s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
|
||||
# ============================================
|
||||
# 清理旧的 Nightly Releases (保留最近 7 个)
|
||||
# ============================================
|
||||
cleanup-old-nightlies:
|
||||
needs: [publish-release, publish-s3]
|
||||
name: Cleanup Old Nightly Releases
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Delete old nightly GitHub releases
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const { data: releases } = await github.rest.repos.listReleases({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const nightlyReleases = releases
|
||||
.filter(r => r.tag_name.includes('-nightly.'))
|
||||
.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
|
||||
|
||||
const toDelete = nightlyReleases.slice(7);
|
||||
|
||||
for (const release of toDelete) {
|
||||
console.log(`🗑️ Deleting old nightly release: ${release.tag_name}`);
|
||||
|
||||
// Delete the release
|
||||
await github.rest.repos.deleteRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: release.id,
|
||||
});
|
||||
|
||||
// Delete the tag
|
||||
try {
|
||||
await github.rest.git.deleteRef({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
ref: `tags/${release.tag_name}`,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(`⚠️ Could not delete tag ${release.tag_name}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ Cleanup complete. Kept ${Math.min(nightlyReleases.length, 7)} nightly releases, deleted ${toDelete.length}.`);
|
||||
|
||||
- name: Cleanup old S3 versions
|
||||
uses: ./.github/actions/desktop-cleanup-s3
|
||||
with:
|
||||
channel: nightly
|
||||
keep-count: '15'
|
||||
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
s3-region: ${{ secrets.UPDATE_S3_REGION }}
|
||||
s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
@@ -266,16 +266,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
name: Release ModelBank
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- canary
|
||||
paths:
|
||||
- packages/model-bank/**
|
||||
workflow_dispatch: {}
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build ModelBank
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build package
|
||||
run: pnpm --filter model-bank build
|
||||
|
||||
publish:
|
||||
name: Publish ModelBank
|
||||
if: ${{ github.event_name == 'workflow_dispatch' }}
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Bump patch version
|
||||
id: version
|
||||
run: |
|
||||
npm version patch --no-git-tag-version --prefix packages/model-bank
|
||||
echo "version=$(node -p 'require(\"./packages/model-bank/package.json\").version')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build package
|
||||
run: pnpm --filter model-bank build
|
||||
|
||||
- name: Publish to npm
|
||||
run: npm publish --provenance
|
||||
working-directory: packages/model-bank
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Commit version bump
|
||||
env:
|
||||
MODEL_BANK_VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
git config user.name "lobehubbot"
|
||||
git config user.email "i@lobehub.com"
|
||||
git add packages/model-bank/package.json
|
||||
git commit -m "🔖 chore(model-bank): release v${MODEL_BANK_VERSION}"
|
||||
git push
|
||||
@@ -37,19 +37,11 @@ jobs:
|
||||
with:
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
@@ -15,15 +15,13 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: ${{ secrets.BUN_VERSION }}
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: sync database schema to dbdocs
|
||||
env:
|
||||
DBDOCS_TOKEN: ${{ secrets.DBDOCS_TOKEN }}
|
||||
run: npm run db:visualize
|
||||
run: bun run db:visualize
|
||||
|
||||
+14
-46
@@ -37,19 +37,11 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: ${{ secrets.BUN_VERSION }}
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Test packages with coverage
|
||||
run: |
|
||||
@@ -111,19 +103,11 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Run tests
|
||||
run: bunx vitest --coverage --silent='passed-only' --reporter=default --reporter=blob --shard=${{ matrix.shard }}/2
|
||||
@@ -146,13 +130,11 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
run: pnpm install
|
||||
|
||||
- name: Download blob reports
|
||||
uses: actions/download-artifact@v7
|
||||
@@ -181,16 +163,8 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 10
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: pnpm install
|
||||
@@ -235,20 +209,14 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
- name: Setup environment
|
||||
uses: ./.github/actions/setup-env
|
||||
|
||||
- name: Install deps
|
||||
run: pnpm i
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Test Coverage
|
||||
run: pnpm --filter @lobechat/database test:coverage
|
||||
|
||||
+5
-1
@@ -52,6 +52,7 @@ bun.lockb
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
public/_spa/
|
||||
public/spa/
|
||||
es/
|
||||
lib/
|
||||
@@ -134,4 +135,7 @@ i18n-unused-keys-report.json
|
||||
|
||||
pnpm-lock.yaml
|
||||
.turbo
|
||||
spaHtmlTemplates.ts
|
||||
spaHtmlTemplates.ts
|
||||
|
||||
.superpowers/
|
||||
docs/superpowers
|
||||
@@ -47,6 +47,7 @@ lobehub/
|
||||
- Git commit messages should prefix with gitmoji
|
||||
- Git branch name format: `feat/feature-name`
|
||||
- Use `.github/PULL_REQUEST_TEMPLATE.md` for PR descriptions
|
||||
- **Protection of local changes**: Never use `git restore`, `git checkout --`, `git reset --hard`, or any other command or workflow that can forcibly overwrite, discard, or silently replace user-owned uncommitted changes. Before any revert or restoration affecting existing files, inspect the working tree carefully and obtain explicit user confirmation.
|
||||
|
||||
### Package Management
|
||||
|
||||
@@ -89,7 +90,8 @@ cd packages/[package-name] && bunx vitest run --silent='passed-only' '[file-path
|
||||
|
||||
- **`src/routes/`** holds only page segments (`_layout/index.tsx`, `index.tsx`, `[id]/index.tsx`). Keep route files **thin** — import from `@/features/*` and compose, no business logic.
|
||||
- **`src/features/`** holds business components by **domain** (e.g. `Pages`, `PageEditor`, `Home`). Layout pieces, hooks, and domain UI go here.
|
||||
- See the **spa-routes** skill for the full convention and file-division rules.
|
||||
- **Desktop router parity:** When changing the main SPA route tree, update **both** `src/spa/router/desktopRouter.config.tsx` (dynamic imports) and `src/spa/router/desktopRouter.config.desktop.tsx` (sync imports) so paths and nesting match. Changing only one can leave routes unregistered and cause **blank screens**.
|
||||
- See the **spa-routes** skill (`.agents/skills/spa-routes/SKILL.md`) for the full convention and file-division rules.
|
||||
|
||||
## Skills (Auto-loaded)
|
||||
|
||||
|
||||
@@ -2,6 +2,64 @@
|
||||
|
||||
# Changelog
|
||||
|
||||
### [Version 2.1.45](https://github.com/lobehub/lobe-chat/compare/v2.1.44...v2.1.45)
|
||||
|
||||
<sup>Released on **2026-03-26**</sup>
|
||||
|
||||
#### 👷 Build System
|
||||
|
||||
- **misc**: add agent task system database schema.
|
||||
|
||||
<br/>
|
||||
|
||||
<details>
|
||||
<summary><kbd>Improvements and Fixes</kbd></summary>
|
||||
|
||||
#### Build System
|
||||
|
||||
- **misc**: add agent task system database schema, closes [#13280](https://github.com/lobehub/lobe-chat/issues/13280) ([b005a9c](https://github.com/lobehub/lobe-chat/commit/b005a9c))
|
||||
|
||||
</details>
|
||||
|
||||
<div align="right">
|
||||
|
||||
[](#readme-top)
|
||||
|
||||
</div>
|
||||
|
||||
### [Version 2.1.44](https://github.com/lobehub/lobe-chat/compare/v2.2.0-nightly.202603200623...v2.1.44)
|
||||
|
||||
<sup>Released on **2026-03-20**</sup>
|
||||
|
||||
#### 🐛 Bug Fixes
|
||||
|
||||
- **misc**: misc UI/UX improvements and bug fixes.
|
||||
|
||||
#### 💄 Styles
|
||||
|
||||
- **misc**: add image/video switch.
|
||||
|
||||
<br/>
|
||||
|
||||
<details>
|
||||
<summary><kbd>Improvements and Fixes</kbd></summary>
|
||||
|
||||
#### What's fixed
|
||||
|
||||
- **misc**: misc UI/UX improvements and bug fixes, closes [#13153](https://github.com/lobehub/lobe-chat/issues/13153) ([abd152b](https://github.com/lobehub/lobe-chat/commit/abd152b))
|
||||
|
||||
#### Styles
|
||||
|
||||
- **misc**: add image/video switch, closes [#13152](https://github.com/lobehub/lobe-chat/issues/13152) ([2067cb2](https://github.com/lobehub/lobe-chat/commit/2067cb2))
|
||||
|
||||
</details>
|
||||
|
||||
<div align="right">
|
||||
|
||||
[](#readme-top)
|
||||
|
||||
</div>
|
||||
|
||||
### [Version 2.1.43](https://github.com/lobehub/lobe-chat/compare/v2.1.42...v2.1.43)
|
||||
|
||||
<sup>Released on **2026-03-16**</sup>
|
||||
|
||||
@@ -60,6 +60,7 @@ When adding or changing SPA routes:
|
||||
1. In `src/routes/`, add only the route segment files (layout + page) that delegate to features.
|
||||
2. Implement layout and page content under `src/features/<Domain>/` and export from there.
|
||||
3. In route files, use `import { X } from '@/features/<Domain>'` (or `import Y from '@/features/<Domain>/...'`). Do not add new `features/` folders inside `src/routes/`.
|
||||
4. **Register the desktop route tree in both configs:** `src/spa/router/desktopRouter.config.tsx` and `src/spa/router/desktopRouter.config.desktop.tsx` must stay in sync (same paths and nesting). Updating only one can cause **blank screens** if the other build path expects the route.
|
||||
|
||||
See the **spa-routes** skill (`.agents/skills/spa-routes/SKILL.md`) for the full convention and file-division rules.
|
||||
|
||||
|
||||
+7
-7
@@ -1,8 +1,8 @@
|
||||
# Lobe Chat - Contributing Guide 🌟
|
||||
# LobeHub - Contributing Guide 🌟
|
||||
|
||||
We're thrilled that you want to contribute to Lobe Chat, the future of communication! 😄
|
||||
We're thrilled that you want to contribute to LobeHub, the future of communication! 😄
|
||||
|
||||
Lobe Chat is an open-source project, and we welcome your collaboration. Before you jump in, let's make sure you're all set to contribute effectively and have loads of fun along the way!
|
||||
LobeHub is an open-source project, and we welcome your collaboration. Before you jump in, let's make sure you're all set to contribute effectively and have loads of fun along the way!
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -69,11 +69,11 @@ git fetch upstream
|
||||
git merge upstream/main
|
||||
```
|
||||
|
||||
This ensures you're working on the most current version of Lobe Chat. Stay fresh! 💨
|
||||
This ensures you're working on the most current version of LobeHub. Stay fresh! 💨
|
||||
|
||||
## Open a Pull Request
|
||||
|
||||
🚀 Time to share your contribution! Head over to the original Lobe Chat repository and open a Pull Request (PR). Our maintainers will review your work.
|
||||
🚀 Time to share your contribution! Head over to the original LobeHub repository and open a Pull Request (PR). Our maintainers will review your work.
|
||||
|
||||
## Review and Collaboration
|
||||
|
||||
@@ -81,8 +81,8 @@ This ensures you're working on the most current version of Lobe Chat. Stay fresh
|
||||
|
||||
## Celebrate 🎉
|
||||
|
||||
🎈 Congratulations! Your contribution is now part of Lobe Chat. 🥳
|
||||
🎈 Congratulations! Your contribution is now part of LobeHub. 🥳
|
||||
|
||||
Thank you for making Lobe Chat even more magical. We can't wait to see what you create! 🌠
|
||||
Thank you for making LobeHub even more magical. We can't wait to see what you create! 🌠
|
||||
|
||||
Happy Coding! 🚀🦄
|
||||
|
||||
+1
-1
@@ -111,7 +111,7 @@ COPY --from=base /distroless/ /
|
||||
COPY --from=builder /app/.next/standalone /app/
|
||||
COPY --from=builder /app/.next/static /app/.next/static
|
||||
# Copy SPA assets (Vite build output)
|
||||
COPY --from=builder /app/public/spa /app/public/spa
|
||||
COPY --from=builder /app/public/_spa /app/public/_spa
|
||||
# Copy database migrations
|
||||
COPY --from=builder /app/packages/database/migrations /app/migrations
|
||||
COPY --from=builder /app/scripts/migrateServerDB/docker.cjs /app/docker.cjs
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
We only provide security fixes for the **latest 2.x release**. Older versions (including all 1.x releases) are end-of-life and will not receive patches.
|
||||
|
||||
| Version | Supported |
|
||||
| ------------ | --------- |
|
||||
| 2.x (latest) | ✅ |
|
||||
| 1.x | ❌ |
|
||||
| 0.x | ❌ |
|
||||
|
||||
If you are running a 1.x deployment, we strongly recommend upgrading to the latest 2.x release.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please report security vulnerabilities through the GitHub Security Advisory ["Report a Vulnerability"](https://github.com/lobehub/lobehub/security/advisories/new) tab.
|
||||
|
||||
**Please do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
### Response Timeline
|
||||
|
||||
- **Acknowledgement**: We aim to respond to all reports within **7 days**.
|
||||
- **Fix**: Confirmed vulnerabilities will be addressed within **30 days**.
|
||||
- **Urgent issues**: If you believe the vulnerability is critical and actively exploitable, you can reach out directly on Discord (`arvinxu`) for faster coordination.
|
||||
|
||||
### What to Include
|
||||
|
||||
A good vulnerability report should include:
|
||||
|
||||
- A clear description of the issue and its potential impact
|
||||
- The affected version (must be the latest 2.x release)
|
||||
- Step-by-step reproduction instructions or a working PoC
|
||||
- Any relevant logs, screenshots, or code references
|
||||
|
||||
## Scope
|
||||
|
||||
### In Scope
|
||||
|
||||
- Security issues affecting the **latest 2.x release** of LobeHub
|
||||
- Vulnerabilities in the **server-side deployment** (LobeHub Cloud or self-hosted server mode)
|
||||
- Issues that can be exploited **without requiring admin/owner access** to the deployment
|
||||
|
||||
### Out of Scope (Not a Vulnerability)
|
||||
|
||||
The following are considered **by design** or **out of scope** and will not be accepted as vulnerability reports:
|
||||
|
||||
#### 1. End-of-Life Versions
|
||||
|
||||
Any issue that only affects 1.x or earlier versions. This includes but is not limited to the `X-lobe-chat-auth` header mechanism, `webapi` route authentication, and other 1.x-specific architectures that have been completely removed in 2.x.
|
||||
|
||||
#### 2. File Proxy Public Access (`/f/:id`)
|
||||
|
||||
The file proxy endpoint `/f/:id` uses randomly generated, non-enumerable IDs as [capability URLs](https://www.w3.org/TR/capability-urls/). This is a deliberate design choice, similar to how S3 presigned URLs or Google Docs sharing links work. Knowing the URL grants access — this is by design, not an authorization bypass.
|
||||
|
||||
#### 3. User Enumeration on Login Flows
|
||||
|
||||
Endpoints such as `check-user` that indicate whether an account exists are part of the standard login UX. This is a common and intentional pattern used by most modern authentication flows.
|
||||
|
||||
#### 4. Self-Hosted Client-Side API Key Storage
|
||||
|
||||
In self-hosted client-side mode, users configure their own API keys which are stored in the browser's local storage. This is the expected behavior for client-side deployments where the user is both the operator and the consumer.
|
||||
|
||||
#### 5. Issues Requiring Admin or Owner Privileges
|
||||
|
||||
Actions that require administrative access to the deployment (e.g., environment variable configuration, server-side settings) are not considered security vulnerabilities, as the admin is already a trusted party.
|
||||
|
||||
#### 6. Theoretical Attacks Without Practical Impact
|
||||
|
||||
Reports based on theoretical attack scenarios without a working proof of concept against a realistic deployment, or issues that require unlikely preconditions (e.g., physical access to the server, pre-existing compromise of the host system).
|
||||
|
||||
## Disclosure Policy
|
||||
|
||||
- We follow [coordinated vulnerability disclosure](https://en.wikipedia.org/wiki/Coordinated_vulnerability_disclosure).
|
||||
- We will credit reporters in the security advisory unless they prefer to remain anonymous.
|
||||
- Please allow us reasonable time to address the issue before any public disclosure.
|
||||
|
||||
## Contact
|
||||
|
||||
- **Primary**: [GitHub Security Advisories](https://github.com/lobehub/lobehub/security/advisories/new)
|
||||
- **Urgent**: Discord — `arvinxu`
|
||||
@@ -0,0 +1,55 @@
|
||||
# @lobehub/cli
|
||||
|
||||
LobeHub command-line interface.
|
||||
|
||||
## Local Development
|
||||
|
||||
| Task | Command |
|
||||
| ------------------------------------------ | -------------------------- |
|
||||
| Run in dev mode | `bun run dev -- <command>` |
|
||||
| Build the CLI | `bun run build` |
|
||||
| Link `lh`/`lobe`/`lobehub` into your shell | `bun run cli:link` |
|
||||
| Remove the global link | `bun run cli:unlink` |
|
||||
|
||||
- `bun run build` only generates `dist/index.js`.
|
||||
- To make `lh` available in your shell, run `bun run cli:link`.
|
||||
- After linking, if your shell still cannot find `lh`, run `rehash` in `zsh`.
|
||||
|
||||
## Custom Server URL
|
||||
|
||||
By default the CLI connects to `https://app.lobehub.com`. To point it at a different server (e.g. a local instance):
|
||||
|
||||
| Method | Command | Persistence |
|
||||
| -------------------- | --------------------------------------------------------------- | ----------------------------------- |
|
||||
| Environment variable | `LOBEHUB_SERVER=http://localhost:4000 bun run dev -- <command>` | Current command only |
|
||||
| Login flag | `lh login --server http://localhost:4000` | Saved to `~/.lobehub/settings.json` |
|
||||
|
||||
Priority: `LOBEHUB_SERVER` env var > `settings.json` > default official URL.
|
||||
|
||||
## Shell Completion
|
||||
|
||||
### Install completion for a linked CLI
|
||||
|
||||
| Shell | Command |
|
||||
| ------ | ------------------------------ |
|
||||
| `zsh` | `source <(lh completion zsh)` |
|
||||
| `bash` | `source <(lh completion bash)` |
|
||||
|
||||
### Use completion during local development
|
||||
|
||||
| Shell | Command |
|
||||
| ------ | -------------------------------------------- |
|
||||
| `zsh` | `source <(bun src/index.ts completion zsh)` |
|
||||
| `bash` | `source <(bun src/index.ts completion bash)` |
|
||||
|
||||
- Completion is context-aware. For example, `lh agent <Tab>` shows agent subcommands instead of top-level commands.
|
||||
- If you update completion logic locally, re-run the corresponding `source <(...)` command to reload it in the current shell session.
|
||||
- Completion only registers shell functions. It does not install the `lh` binary by itself.
|
||||
|
||||
## Quick Check
|
||||
|
||||
```bash
|
||||
which lh
|
||||
lh --help
|
||||
lh agent <TAB>
|
||||
```
|
||||
@@ -0,0 +1,166 @@
|
||||
.\" Code generated by `npm run man:generate`; DO NOT EDIT.
|
||||
.\" Manual command details come from the Commander command tree.
|
||||
.TH LH 1 "" "@lobehub/cli 0.0.3" "User Commands"
|
||||
.SH NAME
|
||||
lh \- LobeHub CLI \- manage and connect to LobeHub services
|
||||
.SH SYNOPSIS
|
||||
.B lh
|
||||
[\fIOPTION\fR]...
|
||||
[\fICOMMAND\fR]
|
||||
.br
|
||||
.B lobe
|
||||
[\fIOPTION\fR]...
|
||||
[\fICOMMAND\fR]
|
||||
.br
|
||||
.B lobehub
|
||||
[\fIOPTION\fR]...
|
||||
[\fICOMMAND\fR]
|
||||
.SH DESCRIPTION
|
||||
lh is the command\-line interface for LobeHub. It provides authentication, device gateway connectivity, content generation, resource search, and management commands for agents, files, models, providers, plugins, knowledge bases, threads, topics, and related resources.
|
||||
.PP
|
||||
For command-specific manuals, use the built-in manual command:
|
||||
.PP
|
||||
.RS
|
||||
.B lh man
|
||||
[\fICOMMAND\fR]...
|
||||
.RE
|
||||
.SH COMMANDS
|
||||
.TP
|
||||
.B login
|
||||
Log in to LobeHub via browser (Device Code Flow) or configure API key server
|
||||
.TP
|
||||
.B logout
|
||||
Log out and remove stored credentials
|
||||
.TP
|
||||
.B completion
|
||||
Output shell completion script
|
||||
.TP
|
||||
.B man
|
||||
Show a manual page for the CLI or a subcommand
|
||||
.TP
|
||||
.B connect
|
||||
Connect to the device gateway and listen for tool calls
|
||||
.TP
|
||||
.B device
|
||||
Manage connected devices
|
||||
.TP
|
||||
.B status
|
||||
Check if gateway connection can be established
|
||||
.TP
|
||||
.B doc
|
||||
Manage documents
|
||||
.TP
|
||||
.B search
|
||||
Search across local resources or the web
|
||||
.TP
|
||||
.B kb
|
||||
Manage knowledge bases, folders, documents, and files
|
||||
.TP
|
||||
.B memory
|
||||
Manage user memories
|
||||
.TP
|
||||
.B agent
|
||||
Manage agents
|
||||
.TP
|
||||
.B agent\-group
|
||||
Manage agent groups
|
||||
.TP
|
||||
.B bot
|
||||
Manage bot integrations
|
||||
.TP
|
||||
.B cron
|
||||
Manage agent cron jobs
|
||||
.TP
|
||||
.B generate
|
||||
Generate content (text, image, video, speech) Alias: gen.
|
||||
.TP
|
||||
.B file
|
||||
Manage files
|
||||
.TP
|
||||
.B skill
|
||||
Manage agent skills
|
||||
.TP
|
||||
.B session\-group
|
||||
Manage agent session groups
|
||||
.TP
|
||||
.B task
|
||||
Manage agent tasks
|
||||
.TP
|
||||
.B thread
|
||||
Manage message threads
|
||||
.TP
|
||||
.B topic
|
||||
Manage conversation topics
|
||||
.TP
|
||||
.B message
|
||||
Manage messages
|
||||
.TP
|
||||
.B model
|
||||
Manage AI models
|
||||
.TP
|
||||
.B provider
|
||||
Manage AI providers
|
||||
.TP
|
||||
.B plugin
|
||||
Manage plugins
|
||||
.TP
|
||||
.B user
|
||||
Manage user account and settings
|
||||
.TP
|
||||
.B whoami
|
||||
Display current user information
|
||||
.TP
|
||||
.B usage
|
||||
View usage statistics
|
||||
.TP
|
||||
.B eval
|
||||
Manage evaluation workflows
|
||||
.TP
|
||||
.B migrate
|
||||
Migrate data from external tools (OpenClaw, ChatGPT, Claude, etc.)
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
.B \-V, \-\-version
|
||||
output the version number
|
||||
.TP
|
||||
.B \-h, \-\-help
|
||||
display help for command
|
||||
.SH FILES
|
||||
.TP
|
||||
.I ~/.lobehub/credentials.json
|
||||
Encrypted access and refresh tokens.
|
||||
.TP
|
||||
.I ~/.lobehub/settings.json
|
||||
CLI settings such as server and gateway URLs.
|
||||
.TP
|
||||
.I ~/.lobehub/daemon.pid
|
||||
Background daemon PID file.
|
||||
.TP
|
||||
.I ~/.lobehub/daemon.status
|
||||
Background daemon status metadata.
|
||||
.TP
|
||||
.I ~/.lobehub/daemon.log
|
||||
Background daemon log output.
|
||||
.PP
|
||||
The base directory can be overridden with the
|
||||
.B LOBEHUB_CLI_HOME
|
||||
environment variable.
|
||||
.SH EXAMPLES
|
||||
.TP
|
||||
.B lh login
|
||||
Start interactive login in the browser.
|
||||
.TP
|
||||
.B lh connect \-\-daemon
|
||||
Start the device gateway connection in the background.
|
||||
.TP
|
||||
.B lh search \-q "gpt\-5"
|
||||
Search local resources for a query.
|
||||
.TP
|
||||
.B lh generate text "Write release notes"
|
||||
Generate text from a prompt.
|
||||
.TP
|
||||
.B lh man generate
|
||||
Show the built\-in manual for the generate command group.
|
||||
.SH SEE ALSO
|
||||
.BR lobe (1),
|
||||
.BR lobehub (1)
|
||||
@@ -0,0 +1 @@
|
||||
.so man1/lh.1
|
||||
@@ -0,0 +1 @@
|
||||
.so man1/lh.1
|
||||
+19
-13
@@ -1,43 +1,49 @@
|
||||
{
|
||||
"name": "@lobehub/cli",
|
||||
"version": "0.0.1-canary.14",
|
||||
"version": "0.0.3",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"lh": "./dist/index.js",
|
||||
"lobe": "./dist/index.js",
|
||||
"lobehub": "./dist/index.js"
|
||||
},
|
||||
"man": [
|
||||
"./man/man1/lh.1",
|
||||
"./man/man1/lobe.1",
|
||||
"./man/man1/lobehub.1"
|
||||
],
|
||||
"files": [
|
||||
"dist"
|
||||
"dist",
|
||||
"man"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "npx tsup",
|
||||
"build": "tsdown",
|
||||
"cli:link": "bun link",
|
||||
"cli:unlink": "bun unlink",
|
||||
"dev": "LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts",
|
||||
"prepublishOnly": "npm run build",
|
||||
"man:generate": "bun src/man/generate.ts",
|
||||
"prepublishOnly": "npm run build && npm run man:generate",
|
||||
"test": "bunx vitest run --config vitest.config.mts --silent='passed-only'",
|
||||
"test:coverage": "bunx vitest run --config vitest.config.mts --coverage",
|
||||
"type-check": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"devDependencies": {
|
||||
"@lobechat/device-gateway-client": "workspace:*",
|
||||
"@lobechat/local-file-shell": "workspace:*",
|
||||
"@trpc/client": "^11.8.1",
|
||||
"@types/node": "^22.13.5",
|
||||
"@types/ws": "^8.18.1",
|
||||
"commander": "^13.1.0",
|
||||
"debug": "^4.4.0",
|
||||
"diff": "^8.0.3",
|
||||
"fast-glob": "^3.3.3",
|
||||
"ignore": "^7.0.5",
|
||||
"picocolors": "^1.1.1",
|
||||
"superjson": "^2.2.6",
|
||||
"tsdown": "^0.21.4",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.18.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lobechat/device-gateway-client": "workspace:*",
|
||||
"@lobechat/local-file-shell": "workspace:*",
|
||||
"@types/node": "^22.13.5",
|
||||
"@types/ws": "^8.18.1",
|
||||
"tsup": "^8.4.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org"
|
||||
|
||||
+30
-14
@@ -5,8 +5,8 @@ import type { LambdaRouter } from '@/server/routers/lambda';
|
||||
import type { ToolsRouter } from '@/server/routers/tools';
|
||||
|
||||
import { getValidToken } from '../auth/refresh';
|
||||
import { OFFICIAL_SERVER_URL } from '../constants/urls';
|
||||
import { loadSettings } from '../settings';
|
||||
import { CLI_API_KEY_ENV } from '../constants/auth';
|
||||
import { resolveServerUrl } from '../settings';
|
||||
import { log } from '../utils/logger';
|
||||
|
||||
export type TrpcClient = ReturnType<typeof createTRPCClient<LambdaRouter>>;
|
||||
@@ -19,31 +19,48 @@ async function getAuthAndServer() {
|
||||
// LOBEHUB_JWT + LOBEHUB_SERVER env vars (used by server-side sandbox execution)
|
||||
const envJwt = process.env.LOBEHUB_JWT;
|
||||
if (envJwt) {
|
||||
const serverUrl = process.env.LOBEHUB_SERVER || OFFICIAL_SERVER_URL;
|
||||
return { accessToken: envJwt, serverUrl: serverUrl.replace(/\/$/, '') };
|
||||
const serverUrl = resolveServerUrl();
|
||||
|
||||
return {
|
||||
headers: { 'Oidc-Auth': envJwt },
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
const envApiKey = process.env[CLI_API_KEY_ENV];
|
||||
if (envApiKey) {
|
||||
const serverUrl = resolveServerUrl();
|
||||
|
||||
return {
|
||||
headers: { 'X-API-Key': envApiKey },
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await getValidToken();
|
||||
if (!result) {
|
||||
log.error("No authentication found. Run 'lh login' first.");
|
||||
log.error(
|
||||
`No authentication found. Run 'lh login' (or 'npx -y @lobehub/cli login') first, or set ${CLI_API_KEY_ENV}.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const accessToken = result.credentials.accessToken;
|
||||
const serverUrl = loadSettings()?.serverUrl || OFFICIAL_SERVER_URL;
|
||||
const serverUrl = resolveServerUrl();
|
||||
|
||||
return { accessToken, serverUrl: serverUrl.replace(/\/$/, '') };
|
||||
return {
|
||||
headers: { 'Oidc-Auth': result.credentials.accessToken },
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getTrpcClient(): Promise<TrpcClient> {
|
||||
if (_client) return _client;
|
||||
|
||||
const { accessToken, serverUrl } = await getAuthAndServer();
|
||||
|
||||
const { headers, serverUrl } = await getAuthAndServer();
|
||||
_client = createTRPCClient<LambdaRouter>({
|
||||
links: [
|
||||
httpLink({
|
||||
headers: { 'Oidc-Auth': accessToken },
|
||||
headers,
|
||||
transformer: superjson,
|
||||
url: `${serverUrl}/trpc/lambda`,
|
||||
}),
|
||||
@@ -56,12 +73,11 @@ export async function getTrpcClient(): Promise<TrpcClient> {
|
||||
export async function getToolsTrpcClient(): Promise<ToolsTrpcClient> {
|
||||
if (_toolsClient) return _toolsClient;
|
||||
|
||||
const { accessToken, serverUrl } = await getAuthAndServer();
|
||||
|
||||
const { headers, serverUrl } = await getAuthAndServer();
|
||||
_toolsClient = createTRPCClient<ToolsRouter>({
|
||||
links: [
|
||||
httpLink({
|
||||
headers: { 'Oidc-Auth': accessToken },
|
||||
headers,
|
||||
transformer: superjson,
|
||||
url: `${serverUrl}/trpc/tools`,
|
||||
}),
|
||||
|
||||
+48
-26
@@ -1,31 +1,11 @@
|
||||
import { getValidToken } from '../auth/refresh';
|
||||
import { OFFICIAL_SERVER_URL } from '../constants/urls';
|
||||
import { loadSettings } from '../settings';
|
||||
import { CLI_API_KEY_ENV } from '../constants/auth';
|
||||
import { resolveServerUrl } from '../settings';
|
||||
import { log } from '../utils/logger';
|
||||
|
||||
// Must match the server's SECRET_XOR_KEY (src/envs/auth.ts)
|
||||
const SECRET_XOR_KEY = 'LobeHub · LobeHub';
|
||||
|
||||
/**
|
||||
* XOR-obfuscate a payload and encode as Base64.
|
||||
* The /webapi/* routes require `X-lobe-chat-auth` with this encoding.
|
||||
*/
|
||||
function obfuscatePayloadWithXOR(payload: Record<string, any>): string {
|
||||
const jsonString = JSON.stringify(payload);
|
||||
const dataBytes = new TextEncoder().encode(jsonString);
|
||||
const keyBytes = new TextEncoder().encode(SECRET_XOR_KEY);
|
||||
|
||||
const result = new Uint8Array(dataBytes.length);
|
||||
for (let i = 0; i < dataBytes.length; i++) {
|
||||
result[i] = dataBytes[i] ^ keyBytes[i % keyBytes.length];
|
||||
}
|
||||
|
||||
return btoa(String.fromCharCode(...result));
|
||||
}
|
||||
|
||||
export interface AuthInfo {
|
||||
accessToken: string;
|
||||
/** Headers required for /webapi/* endpoints (includes both X-lobe-chat-auth and Oidc-Auth) */
|
||||
/** Headers required for /webapi/* endpoints (Oidc-Auth for authentication) */
|
||||
headers: Record<string, string>;
|
||||
serverUrl: string;
|
||||
}
|
||||
@@ -33,20 +13,62 @@ export interface AuthInfo {
|
||||
export async function getAuthInfo(): Promise<AuthInfo> {
|
||||
const result = await getValidToken();
|
||||
if (!result) {
|
||||
if (process.env[CLI_API_KEY_ENV]) {
|
||||
log.error(
|
||||
`API key auth from ${CLI_API_KEY_ENV} is not supported for /webapi/* routes. Run OIDC login instead.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
log.error("No authentication found. Run 'lh login' first.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const accessToken = result!.credentials.accessToken;
|
||||
const serverUrl = loadSettings()?.serverUrl || OFFICIAL_SERVER_URL;
|
||||
const serverUrl = resolveServerUrl();
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Oidc-Auth': accessToken,
|
||||
'X-lobe-chat-auth': obfuscatePayloadWithXOR({}),
|
||||
},
|
||||
serverUrl: serverUrl.replace(/\/$/, ''),
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAgentStreamAuthInfo(): Promise<Pick<AuthInfo, 'headers' | 'serverUrl'>> {
|
||||
const serverUrl = resolveServerUrl();
|
||||
|
||||
const envJwt = process.env.LOBEHUB_JWT;
|
||||
if (envJwt) {
|
||||
return {
|
||||
headers: { 'Oidc-Auth': envJwt },
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
const envApiKey = process.env[CLI_API_KEY_ENV];
|
||||
if (envApiKey) {
|
||||
return {
|
||||
headers: { 'X-API-Key': envApiKey },
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await getValidToken();
|
||||
if (!result) {
|
||||
log.error(`No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV}.`);
|
||||
process.exit(1);
|
||||
|
||||
return {
|
||||
headers: {},
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
headers: { 'Oidc-Auth': result.credentials.accessToken },
|
||||
serverUrl,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { normalizeUrl, resolveServerUrl } from '../settings';
|
||||
|
||||
interface CurrentUserResponse {
|
||||
data?: {
|
||||
id?: string;
|
||||
userId?: string;
|
||||
};
|
||||
error?: string;
|
||||
message?: string;
|
||||
success?: boolean;
|
||||
}
|
||||
|
||||
export async function getUserIdFromApiKey(apiKey: string, serverUrl?: string): Promise<string> {
|
||||
const normalizedServerUrl = normalizeUrl(serverUrl) || resolveServerUrl();
|
||||
|
||||
const response = await fetch(`${normalizedServerUrl}/api/v1/users/me`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
});
|
||||
|
||||
let body: CurrentUserResponse | undefined;
|
||||
try {
|
||||
body = (await response.json()) as CurrentUserResponse;
|
||||
} catch {
|
||||
throw new Error(`Failed to parse response from ${normalizedServerUrl}/api/v1/users/me.`);
|
||||
}
|
||||
|
||||
if (!response.ok || body?.success === false) {
|
||||
throw new Error(
|
||||
body?.error || body?.message || `Request failed with status ${response.status}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const userId = body?.data?.id || body?.data?.userId;
|
||||
if (!userId) {
|
||||
throw new Error('Current user response did not include a user id.');
|
||||
}
|
||||
|
||||
return userId;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { OFFICIAL_SERVER_URL } from '../constants/urls';
|
||||
import { loadSettings } from '../settings';
|
||||
import { resolveServerUrl } from '../settings';
|
||||
import { loadCredentials, saveCredentials, type StoredCredentials } from './credentials';
|
||||
|
||||
const CLIENT_ID = 'lobehub-cli';
|
||||
@@ -20,7 +19,7 @@ export async function getValidToken(): Promise<{ credentials: StoredCredentials
|
||||
// Token expired — try refresh
|
||||
if (!credentials.refreshToken) return null;
|
||||
|
||||
const serverUrl = loadSettings()?.serverUrl || OFFICIAL_SERVER_URL;
|
||||
const serverUrl = resolveServerUrl();
|
||||
const refreshed = await refreshAccessToken(serverUrl, credentials.refreshToken);
|
||||
if (!refreshed) return null;
|
||||
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { getUserIdFromApiKey } from './apiKey';
|
||||
import { getValidToken } from './refresh';
|
||||
import { resolveToken } from './resolveToken';
|
||||
|
||||
vi.mock('./apiKey', () => ({
|
||||
getUserIdFromApiKey: vi.fn(),
|
||||
}));
|
||||
vi.mock('./refresh', () => ({
|
||||
getValidToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../settings', () => ({
|
||||
loadSettings: vi.fn().mockReturnValue({ serverUrl: 'https://app.lobehub.com' }),
|
||||
resolveServerUrl: vi.fn(() =>
|
||||
(process.env.LOBEHUB_SERVER || 'https://app.lobehub.com').replace(/\/$/, ''),
|
||||
),
|
||||
}));
|
||||
vi.mock('../utils/logger', () => ({
|
||||
log: {
|
||||
debug: vi.fn(),
|
||||
@@ -25,14 +34,23 @@ function makeJwt(sub: string): string {
|
||||
|
||||
describe('resolveToken', () => {
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>;
|
||||
const originalApiKey = process.env.LOBEHUB_CLI_API_KEY;
|
||||
const originalJwt = process.env.LOBEHUB_JWT;
|
||||
const originalServer = process.env.LOBEHUB_SERVER;
|
||||
|
||||
beforeEach(() => {
|
||||
exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw new Error('process.exit');
|
||||
});
|
||||
delete process.env.LOBEHUB_CLI_API_KEY;
|
||||
delete process.env.LOBEHUB_JWT;
|
||||
delete process.env.LOBEHUB_SERVER;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env.LOBEHUB_CLI_API_KEY = originalApiKey;
|
||||
process.env.LOBEHUB_JWT = originalJwt;
|
||||
process.env.LOBEHUB_SERVER = originalServer;
|
||||
exitSpy.mockRestore();
|
||||
});
|
||||
|
||||
@@ -42,7 +60,12 @@ describe('resolveToken', () => {
|
||||
|
||||
const result = await resolveToken({ token });
|
||||
|
||||
expect(result).toEqual({ token, userId: 'user-123' });
|
||||
expect(result).toEqual({
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
token,
|
||||
tokenType: 'jwt',
|
||||
userId: 'user-123',
|
||||
});
|
||||
});
|
||||
|
||||
it('should exit if JWT has no sub claim', async () => {
|
||||
@@ -67,7 +90,12 @@ describe('resolveToken', () => {
|
||||
userId: 'user-456',
|
||||
});
|
||||
|
||||
expect(result).toEqual({ token: 'svc-token', userId: 'user-456' });
|
||||
expect(result).toEqual({
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
token: 'svc-token',
|
||||
tokenType: 'serviceToken',
|
||||
userId: 'user-456',
|
||||
});
|
||||
});
|
||||
|
||||
it('should exit if --user-id is not provided', async () => {
|
||||
@@ -76,6 +104,37 @@ describe('resolveToken', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('with environment api key', () => {
|
||||
it('should return API key from environment', async () => {
|
||||
process.env.LOBEHUB_CLI_API_KEY = 'sk-lh-test';
|
||||
vi.mocked(getUserIdFromApiKey).mockResolvedValue('user-789');
|
||||
|
||||
const result = await resolveToken({});
|
||||
|
||||
expect(getUserIdFromApiKey).toHaveBeenCalledWith('sk-lh-test', 'https://app.lobehub.com');
|
||||
expect(result).toEqual({
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
token: 'sk-lh-test',
|
||||
tokenType: 'apiKey',
|
||||
userId: 'user-789',
|
||||
});
|
||||
});
|
||||
|
||||
it('should prefer LOBEHUB_SERVER when validating the API key', async () => {
|
||||
process.env.LOBEHUB_CLI_API_KEY = 'sk-lh-test';
|
||||
process.env.LOBEHUB_SERVER = 'https://self-hosted.example.com/';
|
||||
vi.mocked(getUserIdFromApiKey).mockResolvedValue('user-789');
|
||||
|
||||
const result = await resolveToken({});
|
||||
|
||||
expect(getUserIdFromApiKey).toHaveBeenCalledWith(
|
||||
'sk-lh-test',
|
||||
'https://self-hosted.example.com',
|
||||
);
|
||||
expect(result.serverUrl).toBe('https://self-hosted.example.com');
|
||||
});
|
||||
});
|
||||
|
||||
describe('with stored credentials', () => {
|
||||
it('should return stored credentials token', async () => {
|
||||
const token = makeJwt('stored-user');
|
||||
@@ -87,7 +146,12 @@ describe('resolveToken', () => {
|
||||
|
||||
const result = await resolveToken({});
|
||||
|
||||
expect(result).toEqual({ token, userId: 'stored-user' });
|
||||
expect(result).toEqual({
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
token,
|
||||
tokenType: 'jwt',
|
||||
userId: 'stored-user',
|
||||
});
|
||||
});
|
||||
|
||||
it('should exit if stored token has no sub', async () => {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { CLI_API_KEY_ENV } from '../constants/auth';
|
||||
import { resolveServerUrl } from '../settings';
|
||||
import { log } from '../utils/logger';
|
||||
import { getUserIdFromApiKey } from './apiKey';
|
||||
import { getValidToken } from './refresh';
|
||||
|
||||
interface ResolveTokenOptions {
|
||||
@@ -8,7 +11,9 @@ interface ResolveTokenOptions {
|
||||
}
|
||||
|
||||
interface ResolvedAuth {
|
||||
serverUrl: string;
|
||||
token: string;
|
||||
tokenType: 'apiKey' | 'jwt' | 'serviceToken';
|
||||
userId: string;
|
||||
}
|
||||
|
||||
@@ -25,20 +30,21 @@ function parseJwtSub(token: string): string | undefined {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve an access token from explicit options or stored credentials.
|
||||
* Resolve an access token from explicit options, environment variables, or stored credentials.
|
||||
* Exits the process if no token can be resolved.
|
||||
*/
|
||||
export async function resolveToken(options: ResolveTokenOptions): Promise<ResolvedAuth> {
|
||||
// LOBEHUB_JWT env var takes highest priority (used by server-side sandbox execution)
|
||||
const envJwt = process.env.LOBEHUB_JWT;
|
||||
if (envJwt) {
|
||||
const serverUrl = resolveServerUrl();
|
||||
const userId = parseJwtSub(envJwt);
|
||||
if (!userId) {
|
||||
log.error('Could not extract userId from LOBEHUB_JWT.');
|
||||
process.exit(1);
|
||||
}
|
||||
log.debug('Using LOBEHUB_JWT from environment');
|
||||
return { token: envJwt, userId };
|
||||
return { serverUrl, token: envJwt, tokenType: 'jwt', userId };
|
||||
}
|
||||
|
||||
// Explicit token takes priority
|
||||
@@ -48,7 +54,7 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv
|
||||
log.error('Could not extract userId from token. Provide --user-id explicitly.');
|
||||
process.exit(1);
|
||||
}
|
||||
return { token: options.token, userId };
|
||||
return { serverUrl: resolveServerUrl(), token: options.token, tokenType: 'jwt', userId };
|
||||
}
|
||||
|
||||
if (options.serviceToken) {
|
||||
@@ -56,22 +62,46 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv
|
||||
log.error('--user-id is required when using --service-token');
|
||||
process.exit(1);
|
||||
}
|
||||
return { token: options.serviceToken, userId: options.userId };
|
||||
return {
|
||||
serverUrl: resolveServerUrl(),
|
||||
token: options.serviceToken,
|
||||
tokenType: 'serviceToken',
|
||||
userId: options.userId,
|
||||
};
|
||||
}
|
||||
|
||||
const envApiKey = process.env[CLI_API_KEY_ENV];
|
||||
if (envApiKey) {
|
||||
try {
|
||||
const serverUrl = resolveServerUrl();
|
||||
const userId = await getUserIdFromApiKey(envApiKey, serverUrl);
|
||||
log.debug(`Using ${CLI_API_KEY_ENV} from environment`);
|
||||
return { serverUrl, token: envApiKey, tokenType: 'apiKey', userId };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
log.error(`Failed to validate ${CLI_API_KEY_ENV}: ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Try stored credentials
|
||||
const result = await getValidToken();
|
||||
if (result) {
|
||||
log.debug('Using stored credentials');
|
||||
const token = result.credentials.accessToken;
|
||||
const userId = parseJwtSub(token);
|
||||
const { credentials } = result;
|
||||
const serverUrl = resolveServerUrl();
|
||||
|
||||
const userId = parseJwtSub(credentials.accessToken);
|
||||
if (!userId) {
|
||||
log.error("Stored token is invalid. Run 'lh login' again.");
|
||||
process.exit(1);
|
||||
}
|
||||
return { token, userId };
|
||||
|
||||
return { serverUrl, token: credentials.accessToken, tokenType: 'jwt', userId };
|
||||
}
|
||||
|
||||
log.error("No authentication found. Run 'lh login' first, or provide --token.");
|
||||
log.error(
|
||||
`No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV}, or provide --token.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ const { mockTrpcClient } = vi.hoisted(() => ({
|
||||
execAgent: { mutate: vi.fn() },
|
||||
getOperationStatus: { query: vi.fn() },
|
||||
},
|
||||
device: {
|
||||
listDevices: { query: vi.fn() },
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -38,13 +41,18 @@ const { mockStreamAgentEvents } = vi.hoisted(() => ({
|
||||
mockStreamAgentEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockGetAuthInfo } = vi.hoisted(() => ({
|
||||
mockGetAuthInfo: vi.fn(),
|
||||
const { mockGetAgentStreamAuthInfo } = vi.hoisted(() => ({
|
||||
mockGetAgentStreamAuthInfo: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockResolveLocalDeviceId } = vi.hoisted(() => ({
|
||||
mockResolveLocalDeviceId: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
|
||||
vi.mock('../api/http', () => ({ getAuthInfo: mockGetAuthInfo }));
|
||||
vi.mock('../api/http', () => ({ getAgentStreamAuthInfo: mockGetAgentStreamAuthInfo }));
|
||||
vi.mock('../utils/agentStream', () => ({ streamAgentEvents: mockStreamAgentEvents }));
|
||||
vi.mock('../utils/device', () => ({ resolveLocalDeviceId: mockResolveLocalDeviceId }));
|
||||
vi.mock('../utils/logger', () => ({
|
||||
log: { debug: vi.fn(), error: vi.fn(), heartbeat: vi.fn(), info: vi.fn(), warn: vi.fn() },
|
||||
setVerbose: vi.fn(),
|
||||
@@ -58,12 +66,12 @@ describe('agent command', () => {
|
||||
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
|
||||
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
|
||||
mockGetAuthInfo.mockResolvedValue({
|
||||
accessToken: 'test-token',
|
||||
headers: { 'Content-Type': 'application/json', 'Oidc-Auth': 'test-token' },
|
||||
mockGetAgentStreamAuthInfo.mockResolvedValue({
|
||||
headers: { 'Oidc-Auth': 'test-token' },
|
||||
serverUrl: 'https://example.com',
|
||||
});
|
||||
mockStreamAgentEvents.mockResolvedValue(undefined);
|
||||
mockResolveLocalDeviceId.mockReset();
|
||||
for (const method of Object.values(mockTrpcClient.agent)) {
|
||||
for (const fn of Object.values(method)) {
|
||||
(fn as ReturnType<typeof vi.fn>).mockReset();
|
||||
@@ -74,6 +82,11 @@ describe('agent command', () => {
|
||||
(fn as ReturnType<typeof vi.fn>).mockReset();
|
||||
}
|
||||
}
|
||||
for (const method of Object.values(mockTrpcClient.device)) {
|
||||
for (const fn of Object.values(method)) {
|
||||
(fn as ReturnType<typeof vi.fn>).mockReset();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -297,7 +310,6 @@ describe('agent command', () => {
|
||||
expect.objectContaining({ json: undefined, verbose: undefined }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should support --slug option', async () => {
|
||||
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
|
||||
operationId: 'op-456',
|
||||
@@ -384,6 +396,186 @@ describe('agent command', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should pass --device local as deviceId', async () => {
|
||||
mockResolveLocalDeviceId.mockReturnValue('local-device-1');
|
||||
mockTrpcClient.device.listDevices.query.mockResolvedValue([
|
||||
{ deviceId: 'local-device-1', online: true },
|
||||
]);
|
||||
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
|
||||
operationId: 'op-device',
|
||||
success: true,
|
||||
});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'agent',
|
||||
'run',
|
||||
'--agent-id',
|
||||
'a1',
|
||||
'--prompt',
|
||||
'Hi',
|
||||
'--device',
|
||||
'local',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ agentId: 'a1', deviceId: 'local-device-1', prompt: 'Hi' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should pass --topic-id and --device local together', async () => {
|
||||
mockResolveLocalDeviceId.mockReturnValue('local-device-1');
|
||||
mockTrpcClient.device.listDevices.query.mockResolvedValue([
|
||||
{ deviceId: 'local-device-1', online: true },
|
||||
]);
|
||||
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
|
||||
operationId: 'op-topic-device',
|
||||
success: true,
|
||||
});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'agent',
|
||||
'run',
|
||||
'--agent-id',
|
||||
'a1',
|
||||
'--prompt',
|
||||
'Hi',
|
||||
'--topic-id',
|
||||
't1',
|
||||
'--device',
|
||||
'local',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ appContext: { topicId: 't1' }, deviceId: 'local-device-1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should pass explicit --device id as deviceId', async () => {
|
||||
mockTrpcClient.device.listDevices.query.mockResolvedValue([
|
||||
{ deviceId: 'device-remote-1', online: true },
|
||||
]);
|
||||
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
|
||||
operationId: 'op-explicit-device',
|
||||
success: true,
|
||||
});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'agent',
|
||||
'run',
|
||||
'--agent-id',
|
||||
'a1',
|
||||
'--prompt',
|
||||
'Hi',
|
||||
'--device',
|
||||
'device-remote-1',
|
||||
]);
|
||||
|
||||
expect(mockResolveLocalDeviceId).not.toHaveBeenCalled();
|
||||
expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ agentId: 'a1', deviceId: 'device-remote-1', prompt: 'Hi' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should exit when explicit device is not found', async () => {
|
||||
mockTrpcClient.device.listDevices.query.mockResolvedValue([
|
||||
{ deviceId: 'other-device', online: true },
|
||||
]);
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'agent',
|
||||
'run',
|
||||
'--agent-id',
|
||||
'a1',
|
||||
'--prompt',
|
||||
'Hi',
|
||||
'--device',
|
||||
'device-remote-1',
|
||||
]);
|
||||
|
||||
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('was not found'));
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should exit when local device cannot be resolved', async () => {
|
||||
mockResolveLocalDeviceId.mockReturnValue(undefined);
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'agent',
|
||||
'run',
|
||||
'--agent-id',
|
||||
'a1',
|
||||
'--prompt',
|
||||
'Hi',
|
||||
'--device',
|
||||
'local',
|
||||
]);
|
||||
|
||||
expect(log.error).toHaveBeenCalledWith(expect.stringContaining("Run 'lh connect' first"));
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should exit when local device is offline', async () => {
|
||||
mockResolveLocalDeviceId.mockReturnValue('local-device-1');
|
||||
mockTrpcClient.device.listDevices.query.mockResolvedValue([
|
||||
{ deviceId: 'local-device-1', online: false },
|
||||
]);
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'agent',
|
||||
'run',
|
||||
'--agent-id',
|
||||
'a1',
|
||||
'--prompt',
|
||||
'Hi',
|
||||
'--device',
|
||||
'local',
|
||||
]);
|
||||
|
||||
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('is not online'));
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should exit when explicit device is offline', async () => {
|
||||
mockTrpcClient.device.listDevices.query.mockResolvedValue([
|
||||
{ deviceId: 'device-remote-1', online: false },
|
||||
]);
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'agent',
|
||||
'run',
|
||||
'--agent-id',
|
||||
'a1',
|
||||
'--prompt',
|
||||
'Hi',
|
||||
'--device',
|
||||
'device-remote-1',
|
||||
]);
|
||||
|
||||
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Bring it online'));
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should pass --json to stream options', async () => {
|
||||
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
|
||||
operationId: 'op-j',
|
||||
|
||||
@@ -4,8 +4,14 @@ import type { Command } from 'commander';
|
||||
import pc from 'picocolors';
|
||||
|
||||
import { getTrpcClient } from '../api/client';
|
||||
import { getAuthInfo } from '../api/http';
|
||||
import { replayAgentEvents, streamAgentEvents } from '../utils/agentStream';
|
||||
import { getAgentStreamAuthInfo } from '../api/http';
|
||||
import { resolveAgentGatewayUrl } from '../settings';
|
||||
import {
|
||||
replayAgentEvents,
|
||||
streamAgentEvents,
|
||||
streamAgentEventsViaWebSocket,
|
||||
} from '../utils/agentStream';
|
||||
import { resolveLocalDeviceId } from '../utils/device';
|
||||
import { confirm, outputJson, printTable, truncate } from '../utils/format';
|
||||
import { log, setVerbose } from '../utils/logger';
|
||||
|
||||
@@ -248,17 +254,24 @@ export function registerAgentCommand(program: Command) {
|
||||
.option('-p, --prompt <text>', 'User prompt')
|
||||
.option('-t, --topic-id <id>', 'Reuse an existing topic')
|
||||
.option('--no-auto-start', 'Do not auto-start the agent')
|
||||
.option(
|
||||
'--device <target>',
|
||||
'Target device ID, or use "local" for the current connected device',
|
||||
)
|
||||
.option('--json', 'Output full JSON event stream')
|
||||
.option('-v, --verbose', 'Show detailed tool call info')
|
||||
.option('--replay <file>', 'Replay events from a saved JSON file (offline)')
|
||||
.option('--sse', 'Force SSE stream instead of WebSocket gateway')
|
||||
.action(
|
||||
async (options: {
|
||||
agentId?: string;
|
||||
autoStart?: boolean;
|
||||
device?: string;
|
||||
json?: boolean;
|
||||
prompt?: string;
|
||||
replay?: string;
|
||||
slug?: string;
|
||||
sse?: boolean;
|
||||
topicId?: string;
|
||||
verbose?: boolean;
|
||||
}) => {
|
||||
@@ -285,9 +298,45 @@ export function registerAgentCommand(program: Command) {
|
||||
|
||||
const client = await getTrpcClient();
|
||||
|
||||
let deviceId: string | undefined;
|
||||
if (options.device !== undefined) {
|
||||
if (options.device === 'local') {
|
||||
deviceId = resolveLocalDeviceId();
|
||||
if (!deviceId) {
|
||||
log.error(
|
||||
"No local device found. Run 'lh connect' first, then retry with --device local.",
|
||||
);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
deviceId = options.device;
|
||||
}
|
||||
|
||||
const devices = await client.device.listDevices.query();
|
||||
const matchedDevice = devices.find(
|
||||
(device: { deviceId?: string; online?: boolean }) => device.deviceId === deviceId,
|
||||
);
|
||||
if (!matchedDevice) {
|
||||
log.error(`Device "${deviceId}" was not found. Check 'lh device list' and try again.`);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
if (!matchedDevice.online) {
|
||||
log.error(
|
||||
options.device === 'local'
|
||||
? `Local device "${deviceId}" is not online. Reconnect with 'lh connect' and try again.`
|
||||
: `Device "${deviceId}" is not online. Bring it online and try again.`,
|
||||
);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Exec agent to get operationId
|
||||
const input: Record<string, any> = { prompt: options.prompt };
|
||||
if (options.agentId) input.agentId = options.agentId;
|
||||
if (deviceId) input.deviceId = deviceId;
|
||||
if (options.slug) input.slug = options.slug;
|
||||
if (options.topicId) input.appContext = { topicId: options.topicId };
|
||||
if (options.autoStart === false) input.autoStart = false;
|
||||
@@ -305,14 +354,26 @@ export function registerAgentCommand(program: Command) {
|
||||
log.info(`Operation: ${pc.dim(operationId)} · Topic: ${pc.dim(r.topicId || 'n/a')}`);
|
||||
}
|
||||
|
||||
// 2. Connect to SSE stream
|
||||
const { serverUrl, headers } = await getAuthInfo();
|
||||
const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
|
||||
// 2. Connect to stream (WebSocket via Gateway, or fallback to SSE)
|
||||
const { serverUrl, headers } = await getAgentStreamAuthInfo();
|
||||
const agentGatewayUrl = options.sse ? undefined : resolveAgentGatewayUrl();
|
||||
|
||||
await streamAgentEvents(streamUrl, headers, {
|
||||
json: options.json,
|
||||
verbose: options.verbose,
|
||||
});
|
||||
if (agentGatewayUrl) {
|
||||
const token = headers['Oidc-Auth'] || headers['X-API-Key'] || '';
|
||||
await streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: agentGatewayUrl,
|
||||
json: options.json,
|
||||
operationId,
|
||||
token,
|
||||
verbose: options.verbose,
|
||||
});
|
||||
} else {
|
||||
const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
|
||||
await streamAgentEvents(streamUrl, headers, {
|
||||
json: options.json,
|
||||
verbose: options.verbose,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
+246
-96
@@ -1,37 +1,130 @@
|
||||
import type { Command } from 'commander';
|
||||
import pc from 'picocolors';
|
||||
|
||||
import type { TrpcClient } from '../api/client';
|
||||
import { getTrpcClient } from '../api/client';
|
||||
import { confirm, outputJson, printTable } from '../utils/format';
|
||||
import { confirm, outputJson, printBoxTable, printTable, timeAgo } from '../utils/format';
|
||||
import { log } from '../utils/logger';
|
||||
import { registerBotMessageCommands } from './botMessage';
|
||||
|
||||
const SUPPORTED_PLATFORMS = ['discord', 'slack', 'telegram', 'lark', 'feishu'];
|
||||
// ── Helpers ──────────────────────────────────────────────
|
||||
|
||||
const PLATFORM_CREDENTIAL_FIELDS: Record<string, string[]> = {
|
||||
discord: ['botToken', 'publicKey'],
|
||||
feishu: ['appSecret'],
|
||||
lark: ['appSecret'],
|
||||
slack: ['botToken', 'signingSecret'],
|
||||
telegram: ['botToken'],
|
||||
function maskValue(val: string): string {
|
||||
if (val.length > 8) return val.slice(0, 4) + '****' + val.slice(-4);
|
||||
return '****';
|
||||
}
|
||||
|
||||
function camelToFlag(name: string): string {
|
||||
return '--' + name.replaceAll(/([A-Z])/g, '-$1').toLowerCase();
|
||||
}
|
||||
|
||||
/** Extract credential field definitions from a platform schema. */
|
||||
function getCredentialFields(platformDef: any): any[] {
|
||||
const credSchema = (platformDef.schema ?? []).find(
|
||||
(f: any) => f.key === 'credentials' && f.properties,
|
||||
);
|
||||
return credSchema?.properties ?? [];
|
||||
}
|
||||
|
||||
/** Extract credential values from CLI options based on platform schema. */
|
||||
function extractCredentials(
|
||||
platformDef: any,
|
||||
options: Record<string, any>,
|
||||
): { credentials: Record<string, string>; missing: any[] } {
|
||||
const fields = getCredentialFields(platformDef);
|
||||
const credentials: Record<string, string> = {};
|
||||
|
||||
for (const field of fields) {
|
||||
const value = options[field.key];
|
||||
if (typeof value === 'string') {
|
||||
credentials[field.key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const missing = fields.filter((f: any) => f.required && !credentials[f.key]);
|
||||
return { credentials, missing };
|
||||
}
|
||||
|
||||
/** Find a bot by ID from the user's bot list. */
|
||||
async function findBot(client: TrpcClient, botId: string) {
|
||||
const bots = await client.agentBotProvider.list.query();
|
||||
const bot = (bots as any[]).find((b: any) => b.id === botId);
|
||||
if (!bot) {
|
||||
log.error(`Bot integration not found: ${botId}`);
|
||||
process.exit(1);
|
||||
}
|
||||
return bot;
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, (s: string) => string> = {
|
||||
connected: pc.green,
|
||||
disconnected: pc.dim,
|
||||
failed: pc.red,
|
||||
queued: pc.yellow,
|
||||
starting: pc.yellow,
|
||||
unknown: pc.dim,
|
||||
};
|
||||
|
||||
function parseCredentials(
|
||||
platform: string,
|
||||
options: Record<string, string | undefined>,
|
||||
): Record<string, string> {
|
||||
const creds: Record<string, string> = {};
|
||||
|
||||
if (options.botToken) creds.botToken = options.botToken;
|
||||
if (options.publicKey) creds.publicKey = options.publicKey;
|
||||
if (options.signingSecret) creds.signingSecret = options.signingSecret;
|
||||
if (options.appSecret) creds.appSecret = options.appSecret;
|
||||
|
||||
return creds;
|
||||
/** Validate a platform ID and return its definition. */
|
||||
async function resolvePlatform(client: TrpcClient, platformId: string) {
|
||||
const platforms = await client.agentBotProvider.listPlatforms.query();
|
||||
const def = (platforms as any[]).find((p: any) => p.id === platformId);
|
||||
if (!def) {
|
||||
const ids = (platforms as any[]).map((p: any) => p.id).join(', ');
|
||||
log.error(`Invalid platform "${platformId}". Must be one of: ${ids}`);
|
||||
log.info('Run `lh bot platforms` to see required credentials for each platform.');
|
||||
process.exit(1);
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
// ── Command Registration ─────────────────────────────────
|
||||
|
||||
export function registerBotCommand(program: Command) {
|
||||
const bot = program.command('bot').description('Manage bot integrations');
|
||||
|
||||
// Register message subcommand group
|
||||
registerBotMessageCommands(bot);
|
||||
|
||||
// ── platforms ───────────────────────────────────────────
|
||||
|
||||
bot
|
||||
.command('platforms')
|
||||
.description('List supported platforms and their required credentials')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(async (options: { json?: boolean }) => {
|
||||
const client = await getTrpcClient();
|
||||
const platforms = await client.agentBotProvider.listPlatforms.query();
|
||||
|
||||
if (options.json) {
|
||||
outputJson(platforms);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(pc.bold('Supported platforms:\n'));
|
||||
|
||||
for (const p of platforms as any[]) {
|
||||
console.log(` ${pc.bold(pc.cyan(p.id))}`);
|
||||
if (p.name) console.log(` Name: ${p.name}`);
|
||||
|
||||
const fields = getCredentialFields(p);
|
||||
const required = fields.filter((f: any) => f.required);
|
||||
const optional = fields.filter((f: any) => !f.required);
|
||||
|
||||
if (required.length > 0) {
|
||||
console.log(
|
||||
` Required: ${required.map((f: any) => pc.yellow(camelToFlag(f.key))).join(', ')}`,
|
||||
);
|
||||
}
|
||||
if (optional.length > 0) {
|
||||
console.log(
|
||||
` Optional: ${optional.map((f: any) => pc.dim(camelToFlag(f.key))).join(', ')}`,
|
||||
);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
});
|
||||
|
||||
// ── list ──────────────────────────────────────────────
|
||||
|
||||
bot
|
||||
@@ -61,15 +154,20 @@ export function registerBotCommand(program: Command) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = items.map((b: any) => [
|
||||
b.id || '',
|
||||
b.platform || '',
|
||||
b.applicationId || '',
|
||||
b.agentId || '',
|
||||
b.enabled ? pc.green('enabled') : pc.dim('disabled'),
|
||||
]);
|
||||
const rows = items.map((b: any) => {
|
||||
const status = b.enabled ? (b.runtimeStatus ?? 'disconnected') : 'disabled';
|
||||
const colorFn = STATUS_COLORS[status] ?? pc.dim;
|
||||
return [
|
||||
b.id || '',
|
||||
b.platform || '',
|
||||
b.applicationId || '',
|
||||
b.agentId || '',
|
||||
colorFn(status),
|
||||
b.updatedAt ? timeAgo(b.updatedAt) : pc.dim('-'),
|
||||
];
|
||||
});
|
||||
|
||||
printTable(rows, ['ID', 'PLATFORM', 'APP ID', 'AGENT', 'STATUS']);
|
||||
printTable(rows, ['ID', 'PLATFORM', 'APP ID', 'AGENT', 'STATUS', 'UPDATED']);
|
||||
});
|
||||
|
||||
// ── view ──────────────────────────────────────────────
|
||||
@@ -77,44 +175,62 @@ export function registerBotCommand(program: Command) {
|
||||
bot
|
||||
.command('view <botId>')
|
||||
.description('View bot integration details')
|
||||
.requiredOption('-a, --agent <agentId>', 'Agent ID')
|
||||
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
|
||||
.action(async (botId: string, options: { agent: string; json?: string | boolean }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.agentBotProvider.getByAgentId.query({
|
||||
agentId: options.agent,
|
||||
});
|
||||
const items = Array.isArray(result) ? result : [];
|
||||
const item = items.find((b: any) => b.id === botId);
|
||||
.option('--show-credentials', 'Show full credential values (unmasked)')
|
||||
.action(
|
||||
async (botId: string, options: { json?: string | boolean; showCredentials?: boolean }) => {
|
||||
const client = await getTrpcClient();
|
||||
const b = await findBot(client, botId);
|
||||
|
||||
if (!item) {
|
||||
log.error(`Bot integration not found: ${botId}`);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.json !== undefined) {
|
||||
const fields = typeof options.json === 'string' ? options.json : undefined;
|
||||
outputJson(item, fields);
|
||||
return;
|
||||
}
|
||||
|
||||
const b = item as any;
|
||||
console.log(pc.bold(`${b.platform} bot`));
|
||||
console.log(pc.dim(`ID: ${b.id}`));
|
||||
console.log(`Application ID: ${b.applicationId}`);
|
||||
console.log(`Status: ${b.enabled ? pc.green('enabled') : pc.dim('disabled')}`);
|
||||
|
||||
if (b.credentials && typeof b.credentials === 'object') {
|
||||
console.log();
|
||||
console.log(pc.bold('Credentials:'));
|
||||
for (const [key, value] of Object.entries(b.credentials)) {
|
||||
const val = String(value);
|
||||
const masked = val.length > 8 ? val.slice(0, 4) + '****' + val.slice(-4) : '****';
|
||||
console.log(` ${key}: ${masked}`);
|
||||
if (options.json !== undefined) {
|
||||
const fields = typeof options.json === 'string' ? options.json : undefined;
|
||||
outputJson(b, fields);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const status = b.enabled ? (b.runtimeStatus ?? 'disconnected') : 'disabled';
|
||||
const statusColorFn = STATUS_COLORS[status] ?? pc.dim;
|
||||
|
||||
const credentialLines: string[] = [];
|
||||
if (b.credentials && typeof b.credentials === 'object') {
|
||||
for (const [key, value] of Object.entries(b.credentials)) {
|
||||
const val = String(value);
|
||||
const display = options.showCredentials ? val : maskValue(val);
|
||||
credentialLines.push(`${pc.dim(key)}: ${display}`);
|
||||
}
|
||||
}
|
||||
|
||||
const settingsLines: string[] = [];
|
||||
if (b.settings && typeof b.settings === 'object') {
|
||||
for (const [key, value] of Object.entries(b.settings)) {
|
||||
settingsLines.push(`${pc.dim(key)}: ${JSON.stringify(value)}`);
|
||||
}
|
||||
}
|
||||
|
||||
printBoxTable(
|
||||
[
|
||||
{ header: 'Field', key: 'field' },
|
||||
{ header: 'Value', key: 'value' },
|
||||
],
|
||||
[
|
||||
{ field: 'ID', value: b.id || '' },
|
||||
{ field: 'Platform', value: pc.cyan(b.platform || '') },
|
||||
{ field: 'Application ID', value: b.applicationId || '' },
|
||||
{ field: 'Agent ID', value: b.agentId || '' },
|
||||
{ field: 'Status', value: statusColorFn(status) },
|
||||
...(credentialLines.length > 0
|
||||
? [{ field: 'Credentials', value: credentialLines }]
|
||||
: []),
|
||||
...(settingsLines.length > 0 ? [{ field: 'Settings', value: settingsLines }] : []),
|
||||
...(b.createdAt
|
||||
? [{ field: 'Created', value: new Date(b.createdAt).toLocaleString() }]
|
||||
: []),
|
||||
...(b.updatedAt ? [{ field: 'Updated', value: timeAgo(b.updatedAt) }] : []),
|
||||
],
|
||||
`${b.platform} bot`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// ── add ───────────────────────────────────────────────
|
||||
|
||||
@@ -122,46 +238,58 @@ export function registerBotCommand(program: Command) {
|
||||
.command('add')
|
||||
.description('Add a bot integration to an agent')
|
||||
.requiredOption('-a, --agent <agentId>', 'Agent ID')
|
||||
.requiredOption('--platform <platform>', `Platform: ${SUPPORTED_PLATFORMS.join(', ')}`)
|
||||
.requiredOption('--platform <platform>', 'Platform (run `lh bot platforms` to see options)')
|
||||
.requiredOption('--app-id <appId>', 'Application ID for webhook routing')
|
||||
.option('--bot-token <token>', 'Bot token')
|
||||
.option('--bot-token <token>', 'Bot token (Discord, Slack, Telegram)')
|
||||
.option('--bot-id <id>', 'Bot ID (WeChat)')
|
||||
.option('--public-key <key>', 'Public key (Discord)')
|
||||
.option('--signing-secret <secret>', 'Signing secret (Slack)')
|
||||
.option('--app-secret <secret>', 'App secret (Lark/Feishu)')
|
||||
.option('--app-secret <secret>', 'App secret (Lark, Feishu, QQ)')
|
||||
.option('--secret-token <token>', 'Secret token (Telegram)')
|
||||
.option('--webhook-proxy-url <url>', 'Webhook proxy URL (Telegram)')
|
||||
.option('--encrypt-key <key>', 'Encrypt key (Feishu)')
|
||||
.option('--verification-token <token>', 'Verification token (Feishu)')
|
||||
.option('--json', 'Output created bot as JSON')
|
||||
.action(
|
||||
async (options: {
|
||||
agent: string;
|
||||
appId: string;
|
||||
appSecret?: string;
|
||||
botId?: string;
|
||||
botToken?: string;
|
||||
encryptKey?: string;
|
||||
json?: boolean;
|
||||
platform: string;
|
||||
publicKey?: string;
|
||||
secretToken?: string;
|
||||
signingSecret?: string;
|
||||
verificationToken?: string;
|
||||
webhookProxyUrl?: string;
|
||||
}) => {
|
||||
if (!SUPPORTED_PLATFORMS.includes(options.platform)) {
|
||||
log.error(`Invalid platform. Must be one of: ${SUPPORTED_PLATFORMS.join(', ')}`);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
const client = await getTrpcClient();
|
||||
const platformDef = await resolvePlatform(client, options.platform);
|
||||
|
||||
const credentials = parseCredentials(options.platform, options);
|
||||
const requiredFields = PLATFORM_CREDENTIAL_FIELDS[options.platform] || [];
|
||||
const missing = requiredFields.filter((f) => !credentials[f]);
|
||||
const { credentials, missing } = extractCredentials(platformDef, options);
|
||||
if (missing.length > 0) {
|
||||
log.error(
|
||||
`Missing required credentials for ${options.platform}: ${missing.map((f) => '--' + f.replaceAll(/([A-Z])/g, '-$1').toLowerCase()).join(', ')}`,
|
||||
`Missing required credentials for ${options.platform}: ${missing.map((f: any) => camelToFlag(f.key)).join(', ')}`,
|
||||
);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.agentBotProvider.create.mutate({
|
||||
agentId: options.agent,
|
||||
applicationId: options.appId,
|
||||
credentials,
|
||||
platform: options.platform,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const r = result as any;
|
||||
console.log(
|
||||
`${pc.green('✓')} Added ${pc.bold(options.platform)} bot ${pc.bold(r.id || '')}`,
|
||||
@@ -175,9 +303,14 @@ export function registerBotCommand(program: Command) {
|
||||
.command('update <botId>')
|
||||
.description('Update a bot integration')
|
||||
.option('--bot-token <token>', 'New bot token')
|
||||
.option('--bot-id <id>', 'New bot ID (WeChat)')
|
||||
.option('--public-key <key>', 'New public key')
|
||||
.option('--signing-secret <secret>', 'New signing secret')
|
||||
.option('--app-secret <secret>', 'New app secret')
|
||||
.option('--secret-token <token>', 'New secret token')
|
||||
.option('--webhook-proxy-url <url>', 'New webhook proxy URL')
|
||||
.option('--encrypt-key <key>', 'New encrypt key')
|
||||
.option('--verification-token <token>', 'New verification token')
|
||||
.option('--app-id <appId>', 'New application ID')
|
||||
.option('--platform <platform>', 'New platform')
|
||||
.action(
|
||||
@@ -186,20 +319,25 @@ export function registerBotCommand(program: Command) {
|
||||
options: {
|
||||
appId?: string;
|
||||
appSecret?: string;
|
||||
botId?: string;
|
||||
botToken?: string;
|
||||
encryptKey?: string;
|
||||
platform?: string;
|
||||
publicKey?: string;
|
||||
secretToken?: string;
|
||||
signingSecret?: string;
|
||||
verificationToken?: string;
|
||||
webhookProxyUrl?: string;
|
||||
},
|
||||
) => {
|
||||
const client = await getTrpcClient();
|
||||
const input: Record<string, any> = { id: botId };
|
||||
|
||||
const credentials: Record<string, string> = {};
|
||||
if (options.botToken) credentials.botToken = options.botToken;
|
||||
if (options.publicKey) credentials.publicKey = options.publicKey;
|
||||
if (options.signingSecret) credentials.signingSecret = options.signingSecret;
|
||||
if (options.appSecret) credentials.appSecret = options.appSecret;
|
||||
const existing = await findBot(client, botId);
|
||||
const platform = options.platform ?? existing.platform;
|
||||
const platformDef = await resolvePlatform(client, platform);
|
||||
|
||||
const { credentials } = extractCredentials(platformDef, options);
|
||||
if (Object.keys(credentials).length > 0) input.credentials = credentials;
|
||||
if (options.appId) input.applicationId = options.appId;
|
||||
if (options.platform) input.platform = options.platform;
|
||||
@@ -210,7 +348,6 @@ export function registerBotCommand(program: Command) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = await getTrpcClient();
|
||||
await client.agentBotProvider.update.mutate(input as any);
|
||||
console.log(`${pc.green('✓')} Updated bot ${pc.bold(botId)}`);
|
||||
},
|
||||
@@ -256,28 +393,41 @@ export function registerBotCommand(program: Command) {
|
||||
console.log(`${pc.green('✓')} Disabled bot ${pc.bold(botId)}`);
|
||||
});
|
||||
|
||||
// ── test ───────────────────────────────────────────────
|
||||
|
||||
bot
|
||||
.command('test <botId>')
|
||||
.description('Test bot credentials against the platform API')
|
||||
.action(async (botId: string) => {
|
||||
const client = await getTrpcClient();
|
||||
const b = await findBot(client, botId);
|
||||
|
||||
log.status(`Testing ${b.platform} credentials for ${b.applicationId}...`);
|
||||
|
||||
try {
|
||||
await client.agentBotProvider.testConnection.mutate({
|
||||
applicationId: b.applicationId,
|
||||
platform: b.platform,
|
||||
});
|
||||
console.log(`${pc.green('✓')} Credentials are valid for ${pc.bold(b.platform)} bot`);
|
||||
} catch (err: any) {
|
||||
const message = err?.message || 'Connection test failed';
|
||||
log.error(`Credential test failed: ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
// ── connect ───────────────────────────────────────────
|
||||
|
||||
bot
|
||||
.command('connect <botId>')
|
||||
.description('Connect and start a bot')
|
||||
.requiredOption('-a, --agent <agentId>', 'Agent ID')
|
||||
.action(async (botId: string, options: { agent: string }) => {
|
||||
// First fetch the bot to get platform and applicationId
|
||||
.action(async (botId: string) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.agentBotProvider.getByAgentId.query({
|
||||
agentId: options.agent,
|
||||
});
|
||||
const items = Array.isArray(result) ? result : [];
|
||||
const item = items.find((b: any) => b.id === botId);
|
||||
const b = await findBot(client, botId);
|
||||
|
||||
if (!item) {
|
||||
log.error(`Bot integration not found: ${botId}`);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
log.status(`Connecting ${b.platform} bot ${b.applicationId}...`);
|
||||
|
||||
const b = item as any;
|
||||
const connectResult = await client.agentBotProvider.connectBot.mutate({
|
||||
applicationId: b.applicationId,
|
||||
platform: b.platform,
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
import { DEFAULT_BOT_HISTORY_LIMIT } from '@lobechat/const';
|
||||
import type { Command } from 'commander';
|
||||
import pc from 'picocolors';
|
||||
|
||||
import { getTrpcClient } from '../api/client';
|
||||
import { confirm, outputJson, printTable, truncate } from '../utils/format';
|
||||
import { log } from '../utils/logger';
|
||||
|
||||
export function registerBotMessageCommands(bot: Command) {
|
||||
const message = bot
|
||||
.command('message')
|
||||
.description('Send and manage messages on connected platforms');
|
||||
|
||||
// ── send ────────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('send <botId>')
|
||||
.description('Send a message to a channel')
|
||||
.requiredOption('--target <channelId>', 'Target channel / conversation ID')
|
||||
.requiredOption('--message <text>', 'Message content')
|
||||
.option('--reply-to <messageId>', 'Reply to a specific message')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(
|
||||
async (
|
||||
botId: string,
|
||||
options: { json?: boolean; message: string; replyTo?: string; target: string },
|
||||
) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.sendMessage.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
content: options.message,
|
||||
replyTo: options.replyTo,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const r = result as any;
|
||||
console.log(
|
||||
`${pc.green('✓')} Message sent${r.messageId ? ` (${pc.dim(r.messageId)})` : ''}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// ── read ────────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('read <botId>')
|
||||
.description('Read messages from a channel')
|
||||
.requiredOption('--target <channelId>', 'Target channel / conversation ID')
|
||||
.option('--limit <n>', 'Max messages to fetch', String(DEFAULT_BOT_HISTORY_LIMIT))
|
||||
.option('--before <messageId>', 'Read messages before this ID')
|
||||
.option('--after <messageId>', 'Read messages after this ID')
|
||||
.option('--start-time <timestamp>', 'Start time as Unix seconds (Feishu/Lark)')
|
||||
.option('--end-time <timestamp>', 'End time as Unix seconds (Feishu/Lark)')
|
||||
.option('--cursor <token>', 'Pagination cursor from a previous response (Feishu/Lark)')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(
|
||||
async (
|
||||
botId: string,
|
||||
options: {
|
||||
after?: string;
|
||||
before?: string;
|
||||
cursor?: string;
|
||||
endTime?: string;
|
||||
json?: boolean;
|
||||
limit?: string;
|
||||
startTime?: string;
|
||||
target: string;
|
||||
},
|
||||
) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.readMessages.query({
|
||||
after: options.after,
|
||||
before: options.before,
|
||||
botId,
|
||||
channelId: options.target,
|
||||
cursor: options.cursor,
|
||||
endTime: options.endTime,
|
||||
limit: options.limit ? Number.parseInt(options.limit, 10) : undefined,
|
||||
startTime: options.startTime,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const messages = (result as any).messages ?? [];
|
||||
if (messages.length === 0) {
|
||||
console.log('No messages found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = messages.map((m: any) => [
|
||||
m.id || '',
|
||||
m.author?.name || '',
|
||||
truncate(m.content || '', 60),
|
||||
m.timestamp || '',
|
||||
]);
|
||||
|
||||
printTable(rows, ['ID', 'AUTHOR', 'CONTENT', 'TIME']);
|
||||
|
||||
const r = result as any;
|
||||
if (r.hasMore && r.nextCursor) {
|
||||
console.log(
|
||||
`\nMore messages available. Use ${pc.dim(`--cursor ${r.nextCursor}`)} to fetch next page.`,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ── edit ────────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('edit <botId>')
|
||||
.description('Edit a message')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--message-id <id>', 'Message ID to edit')
|
||||
.requiredOption('--message <text>', 'New message content')
|
||||
.action(
|
||||
async (botId: string, options: { message: string; messageId: string; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
await client.botMessage.editMessage.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
content: options.message,
|
||||
messageId: options.messageId,
|
||||
});
|
||||
|
||||
console.log(`${pc.green('✓')} Message ${pc.bold(options.messageId)} edited`);
|
||||
},
|
||||
);
|
||||
|
||||
// ── delete ──────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('delete <botId>')
|
||||
.description('Delete a message')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--message-id <id>', 'Message ID to delete')
|
||||
.option('--yes', 'Skip confirmation prompt')
|
||||
.action(
|
||||
async (botId: string, options: { messageId: string; target: string; yes?: boolean }) => {
|
||||
if (!options.yes) {
|
||||
const confirmed = await confirm('Are you sure you want to delete this message?');
|
||||
if (!confirmed) {
|
||||
console.log('Cancelled.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const client = await getTrpcClient();
|
||||
await client.botMessage.deleteMessage.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
messageId: options.messageId,
|
||||
});
|
||||
|
||||
console.log(`${pc.green('✓')} Message ${pc.bold(options.messageId)} deleted`);
|
||||
},
|
||||
);
|
||||
|
||||
// ── search ──────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('search <botId>')
|
||||
.description('Search messages in a channel')
|
||||
.requiredOption('--target <channelId>', 'Channel ID to search in')
|
||||
.requiredOption('--query <text>', 'Search query')
|
||||
.option('--author-id <id>', 'Filter by author ID')
|
||||
.option('--limit <n>', 'Max results')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(
|
||||
async (
|
||||
botId: string,
|
||||
options: {
|
||||
authorId?: string;
|
||||
json?: boolean;
|
||||
limit?: string;
|
||||
query: string;
|
||||
target: string;
|
||||
},
|
||||
) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.searchMessages.query({
|
||||
authorId: options.authorId,
|
||||
botId,
|
||||
channelId: options.target,
|
||||
limit: options.limit ? Number.parseInt(options.limit, 10) : undefined,
|
||||
query: options.query,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const messages = (result as any).messages ?? [];
|
||||
if (messages.length === 0) {
|
||||
console.log('No messages found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = messages.map((m: any) => [
|
||||
m.id || '',
|
||||
m.author?.name || '',
|
||||
truncate(m.content || '', 60),
|
||||
]);
|
||||
|
||||
printTable(rows, ['ID', 'AUTHOR', 'CONTENT']);
|
||||
},
|
||||
);
|
||||
|
||||
// ── react ───────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('react <botId>')
|
||||
.description('Add an emoji reaction to a message')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--message-id <id>', 'Message ID to react to')
|
||||
.requiredOption('--emoji <emoji>', 'Emoji to react with')
|
||||
.action(
|
||||
async (botId: string, options: { emoji: string; messageId: string; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
await client.botMessage.reactToMessage.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
emoji: options.emoji,
|
||||
messageId: options.messageId,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`${pc.green('✓')} Reacted with ${options.emoji} to message ${pc.bold(options.messageId)}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// ── reactions ───────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('reactions <botId>')
|
||||
.description('List reactions on a message')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--message-id <id>', 'Message ID')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(
|
||||
async (botId: string, options: { json?: boolean; messageId: string; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.getReactions.query({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
messageId: options.messageId,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const reactions = (result as any).reactions ?? [];
|
||||
if (reactions.length === 0) {
|
||||
console.log('No reactions found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = reactions.map((r: any) => [r.emoji || '', String(r.count || 0)]);
|
||||
printTable(rows, ['EMOJI', 'COUNT']);
|
||||
},
|
||||
);
|
||||
|
||||
// ── pin ─────────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('pin <botId>')
|
||||
.description('Pin a message')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--message-id <id>', 'Message ID to pin')
|
||||
.action(async (botId: string, options: { messageId: string; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
await client.botMessage.pinMessage.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
messageId: options.messageId,
|
||||
});
|
||||
|
||||
console.log(`${pc.green('✓')} Pinned message ${pc.bold(options.messageId)}`);
|
||||
});
|
||||
|
||||
// ── unpin ───────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('unpin <botId>')
|
||||
.description('Unpin a message')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--message-id <id>', 'Message ID to unpin')
|
||||
.action(async (botId: string, options: { messageId: string; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
await client.botMessage.unpinMessage.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
messageId: options.messageId,
|
||||
});
|
||||
|
||||
console.log(`${pc.green('✓')} Unpinned message ${pc.bold(options.messageId)}`);
|
||||
});
|
||||
|
||||
// ── pins ────────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('pins <botId>')
|
||||
.description('List pinned messages')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(async (botId: string, options: { json?: boolean; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.listPins.query({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const messages = (result as any).messages ?? [];
|
||||
if (messages.length === 0) {
|
||||
console.log('No pinned messages.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = messages.map((m: any) => [
|
||||
m.id || '',
|
||||
m.author?.name || '',
|
||||
truncate(m.content || '', 60),
|
||||
]);
|
||||
|
||||
printTable(rows, ['ID', 'AUTHOR', 'CONTENT']);
|
||||
});
|
||||
|
||||
// ── poll ────────────────────────────────────────────────
|
||||
|
||||
message
|
||||
.command('poll <botId>')
|
||||
.description('Create a poll')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--poll-question <text>', 'Poll question')
|
||||
.requiredOption('--poll-option <option>', 'Poll option (repeatable)', collectOptions, [])
|
||||
.option('--poll-multi', 'Allow multiple answers')
|
||||
.option('--poll-duration-hours <n>', 'Poll duration in hours')
|
||||
.action(
|
||||
async (
|
||||
botId: string,
|
||||
options: {
|
||||
pollDurationHours?: string;
|
||||
pollMulti?: boolean;
|
||||
pollOption: string[];
|
||||
pollQuestion: string;
|
||||
target: string;
|
||||
},
|
||||
) => {
|
||||
if (options.pollOption.length < 2) {
|
||||
log.error('At least 2 poll options are required.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.createPoll.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
duration: options.pollDurationHours
|
||||
? Number.parseInt(options.pollDurationHours, 10)
|
||||
: undefined,
|
||||
multipleAnswers: options.pollMulti,
|
||||
options: options.pollOption,
|
||||
question: options.pollQuestion,
|
||||
});
|
||||
|
||||
const r = result as any;
|
||||
console.log(`${pc.green('✓')} Poll created${r.pollId ? ` (${pc.dim(r.pollId)})` : ''}`);
|
||||
},
|
||||
);
|
||||
|
||||
// ── thread (subcommand group) ───────────────────────────
|
||||
|
||||
const thread = message.command('thread').description('Manage threads');
|
||||
|
||||
thread
|
||||
.command('create <botId>')
|
||||
.description('Create a new thread')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.requiredOption('--thread-name <name>', 'Thread name')
|
||||
.option('--message <text>', 'Initial message content')
|
||||
.option('--message-id <id>', 'Create thread from a message')
|
||||
.action(
|
||||
async (
|
||||
botId: string,
|
||||
options: { message?: string; messageId?: string; target: string; threadName: string },
|
||||
) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.createThread.mutate({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
content: options.message,
|
||||
messageId: options.messageId,
|
||||
name: options.threadName,
|
||||
});
|
||||
|
||||
const r = result as any;
|
||||
console.log(
|
||||
`${pc.green('✓')} Thread created${r.threadId ? ` (${pc.dim(r.threadId)})` : ''}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
thread
|
||||
.command('list <botId>')
|
||||
.description('List threads in a channel')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(async (botId: string, options: { json?: boolean; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.listThreads.query({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const threads = (result as any).threads ?? [];
|
||||
if (threads.length === 0) {
|
||||
console.log('No threads found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = threads.map((t: any) => [
|
||||
t.id || '',
|
||||
t.name || '',
|
||||
String(t.messageCount ?? ''),
|
||||
]);
|
||||
|
||||
printTable(rows, ['ID', 'NAME', 'MESSAGES']);
|
||||
});
|
||||
|
||||
thread
|
||||
.command('reply <botId>')
|
||||
.description('Reply to a thread')
|
||||
.requiredOption('--thread-id <id>', 'Thread ID')
|
||||
.requiredOption('--message <text>', 'Reply content')
|
||||
.action(async (botId: string, options: { message: string; threadId: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.replyToThread.mutate({
|
||||
botId,
|
||||
content: options.message,
|
||||
threadId: options.threadId,
|
||||
});
|
||||
|
||||
const r = result as any;
|
||||
console.log(`${pc.green('✓')} Reply sent${r.messageId ? ` (${pc.dim(r.messageId)})` : ''}`);
|
||||
});
|
||||
|
||||
// ── channel (subcommand group) ──────────────────────────
|
||||
|
||||
const channel = message.command('channel').description('Manage channels');
|
||||
|
||||
channel
|
||||
.command('list <botId>')
|
||||
.description('List channels')
|
||||
.option('--server-id <id>', 'Server / workspace ID')
|
||||
.option('--filter <type>', 'Filter by type')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(
|
||||
async (botId: string, options: { filter?: string; json?: boolean; serverId?: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.listChannels.query({
|
||||
botId,
|
||||
filter: options.filter,
|
||||
serverId: options.serverId,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const channels = (result as any).channels ?? [];
|
||||
if (channels.length === 0) {
|
||||
console.log('No channels found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = channels.map((c: any) => [c.id || '', c.name || '', c.type || '']);
|
||||
printTable(rows, ['ID', 'NAME', 'TYPE']);
|
||||
},
|
||||
);
|
||||
|
||||
channel
|
||||
.command('info <botId>')
|
||||
.description('Get channel details')
|
||||
.requiredOption('--target <channelId>', 'Channel ID')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(async (botId: string, options: { json?: boolean; target: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.getChannelInfo.query({
|
||||
botId,
|
||||
channelId: options.target,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const r = result as any;
|
||||
console.log(`Channel: ${pc.bold(r.name || options.target)}`);
|
||||
if (r.type) console.log(` Type: ${r.type}`);
|
||||
if (r.memberCount != null) console.log(` Members: ${r.memberCount}`);
|
||||
if (r.description) console.log(` Description: ${r.description}`);
|
||||
});
|
||||
|
||||
// ── member ──────────────────────────────────────────────
|
||||
|
||||
const member = message.command('member').description('Member information');
|
||||
|
||||
member
|
||||
.command('info <botId>')
|
||||
.description('Get member details')
|
||||
.requiredOption('--member-id <id>', 'Member / user ID')
|
||||
.option('--server-id <id>', 'Server / workspace ID')
|
||||
.option('--json', 'Output JSON')
|
||||
.action(
|
||||
async (botId: string, options: { json?: boolean; memberId: string; serverId?: string }) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = await client.botMessage.getMemberInfo.query({
|
||||
botId,
|
||||
memberId: options.memberId,
|
||||
serverId: options.serverId,
|
||||
});
|
||||
|
||||
if (options.json) {
|
||||
outputJson(result);
|
||||
return;
|
||||
}
|
||||
|
||||
const r = result as any;
|
||||
console.log(`Member: ${pc.bold(r.displayName || r.username || options.memberId)}`);
|
||||
if (r.status) console.log(` Status: ${r.status}`);
|
||||
if (r.roles?.length) console.log(` Roles: ${r.roles.join(', ')}`);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────
|
||||
|
||||
function collectOptions(value: string, previous: string[]): string[] {
|
||||
return [...previous, value];
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { Command } from 'commander';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { registerCompletionCommand } from './completion';
|
||||
|
||||
describe('completion command', () => {
|
||||
let consoleSpy: ReturnType<typeof vi.spyOn>;
|
||||
const originalShell = process.env.SHELL;
|
||||
|
||||
beforeEach(() => {
|
||||
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleSpy.mockRestore();
|
||||
delete process.env.LOBEHUB_COMP_CWORD;
|
||||
process.env.SHELL = originalShell;
|
||||
});
|
||||
|
||||
function createProgram() {
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
|
||||
program
|
||||
.command('agent')
|
||||
.description('Agent commands')
|
||||
.command('list')
|
||||
.description('List agents');
|
||||
program.command('generate').alias('gen').description('Generate content');
|
||||
program.command('usage').description('Usage').option('--month <YYYY-MM>', 'Month to query');
|
||||
program.command('internal', { hidden: true });
|
||||
|
||||
registerCompletionCommand(program);
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
it('should output zsh completion script by default', async () => {
|
||||
process.env.SHELL = '/bin/zsh';
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'completion']);
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('compdef _lobehub_completion'));
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('lh lobe lobehub'));
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"${(@)words[@]:1}"'));
|
||||
});
|
||||
|
||||
it('should output bash completion script when requested', async () => {
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'completion', 'bash']);
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('complete -o nosort'));
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('__complete'));
|
||||
});
|
||||
|
||||
it('should suggest root commands and aliases', async () => {
|
||||
process.env.LOBEHUB_COMP_CWORD = '0';
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', '__complete', 'g']);
|
||||
|
||||
expect(consoleSpy.mock.calls.map(([value]) => value)).toEqual(['gen', 'generate']);
|
||||
});
|
||||
|
||||
it('should suggest nested subcommands in the current command context', async () => {
|
||||
process.env.LOBEHUB_COMP_CWORD = '1';
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', '__complete', 'agent']);
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith('list');
|
||||
});
|
||||
|
||||
it('should suggest command options after leaf commands', async () => {
|
||||
process.env.LOBEHUB_COMP_CWORD = '1';
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', '__complete', 'usage']);
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith('--month');
|
||||
});
|
||||
|
||||
it('should not suggest commands while completing an option value', async () => {
|
||||
process.env.LOBEHUB_COMP_CWORD = '2';
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', '__complete', 'usage', '--month']);
|
||||
|
||||
expect(consoleSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not expose hidden commands', async () => {
|
||||
process.env.LOBEHUB_COMP_CWORD = '0';
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', '__complete']);
|
||||
|
||||
expect(consoleSpy.mock.calls.map(([value]) => value)).not.toContain('internal');
|
||||
expect(consoleSpy.mock.calls.map(([value]) => value)).not.toContain('__complete');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Command } from 'commander';
|
||||
|
||||
import {
|
||||
getCompletionCandidates,
|
||||
parseCompletionWordIndex,
|
||||
renderCompletionScript,
|
||||
resolveCompletionShell,
|
||||
} from '../utils/completion';
|
||||
|
||||
export function registerCompletionCommand(program: Command) {
|
||||
program
|
||||
.command('completion [shell]')
|
||||
.description('Output shell completion script')
|
||||
.action((shell?: string) => {
|
||||
console.log(renderCompletionScript(resolveCompletionShell(shell)));
|
||||
});
|
||||
|
||||
program
|
||||
.command('__complete', { hidden: true })
|
||||
.allowUnknownOption()
|
||||
.argument('[words...]')
|
||||
.action((words: string[] = []) => {
|
||||
const currentWordIndex = parseCompletionWordIndex(process.env.LOBEHUB_COMP_CWORD, words);
|
||||
const candidates = getCompletionCandidates(program, words, currentWordIndex);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
console.log(candidate);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2,10 +2,16 @@ import { Command } from 'commander';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../auth/resolveToken', () => ({
|
||||
resolveToken: vi.fn().mockResolvedValue({ token: 'test-token', userId: 'test-user' }),
|
||||
resolveToken: vi.fn().mockResolvedValue({
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
token: 'test-token',
|
||||
tokenType: 'jwt',
|
||||
userId: 'test-user',
|
||||
}),
|
||||
}));
|
||||
vi.mock('../settings', () => ({
|
||||
loadSettings: vi.fn().mockReturnValue(null),
|
||||
normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),
|
||||
saveSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -90,7 +96,7 @@ vi.mock('@lobechat/device-gateway-client', () => ({
|
||||
// eslint-disable-next-line import-x/first
|
||||
import { resolveToken } from '../auth/resolveToken';
|
||||
// eslint-disable-next-line import-x/first
|
||||
import { spawnDaemon, stopDaemon } from '../daemon/manager';
|
||||
import { removeStatus, spawnDaemon, stopDaemon, writeStatus } from '../daemon/manager';
|
||||
// eslint-disable-next-line import-x/first
|
||||
import { loadSettings, saveSettings } from '../settings';
|
||||
// eslint-disable-next-line import-x/first
|
||||
@@ -124,6 +130,36 @@ describe('connect command', () => {
|
||||
return program;
|
||||
}
|
||||
|
||||
it('should persist deviceId in status for foreground connections', async () => {
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'connect']);
|
||||
|
||||
expect(writeStatus).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ connectionStatus: 'connecting', deviceId: 'mock-device-id' }),
|
||||
);
|
||||
|
||||
clientEventHandlers.connected?.();
|
||||
|
||||
expect(writeStatus).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ connectionStatus: 'connected', deviceId: 'mock-device-id' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should persist deviceId in status for daemon child connections', async () => {
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'connect', '--daemon-child']);
|
||||
|
||||
expect(writeStatus).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ connectionStatus: 'connecting', deviceId: 'mock-device-id' }),
|
||||
);
|
||||
|
||||
clientEventHandlers.connected?.();
|
||||
|
||||
expect(writeStatus).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ connectionStatus: 'connected', deviceId: 'mock-device-id' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should connect to gateway', async () => {
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'connect']);
|
||||
@@ -161,6 +197,12 @@ describe('connect command', () => {
|
||||
serverUrl: 'https://self-hosted.example.com',
|
||||
});
|
||||
});
|
||||
it('should pass the resolved serverUrl to GatewayClient', async () => {
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'connect']);
|
||||
|
||||
expect(clientOptions.serverUrl).toBe('https://app.lobehub.com');
|
||||
});
|
||||
|
||||
it('should handle tool call requests', async () => {
|
||||
const program = createProgram();
|
||||
@@ -208,7 +250,12 @@ describe('connect command', () => {
|
||||
});
|
||||
|
||||
it('should handle auth_expired', async () => {
|
||||
vi.mocked(resolveToken).mockResolvedValueOnce({ token: 'new-tok', userId: 'user' });
|
||||
vi.mocked(resolveToken).mockResolvedValueOnce({
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
token: 'new-tok',
|
||||
tokenType: 'jwt',
|
||||
userId: 'user',
|
||||
});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'connect']);
|
||||
@@ -220,6 +267,24 @@ describe('connect command', () => {
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should ignore auth_expired for api key auth', async () => {
|
||||
vi.mocked(resolveToken).mockResolvedValueOnce({
|
||||
serverUrl: 'https://self-hosted.example.com',
|
||||
token: 'test-api-key',
|
||||
tokenType: 'apiKey',
|
||||
userId: 'user',
|
||||
});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'connect']);
|
||||
|
||||
await clientEventHandlers['auth_expired']?.();
|
||||
|
||||
expect(log.error).not.toHaveBeenCalled();
|
||||
expect(cleanupAllProcesses).not.toHaveBeenCalled();
|
||||
expect(exitSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle error event', async () => {
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'connect']);
|
||||
@@ -253,6 +318,7 @@ describe('connect command', () => {
|
||||
}
|
||||
|
||||
expect(cleanupAllProcesses).toHaveBeenCalled();
|
||||
expect(removeStatus).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle auth_expired when refresh fails', async () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { GatewayClient } from '@lobechat/device-gateway-client';
|
||||
import type { Command } from 'commander';
|
||||
|
||||
import { resolveToken } from '../auth/resolveToken';
|
||||
import { CLI_API_KEY_ENV } from '../constants/auth';
|
||||
import { OFFICIAL_GATEWAY_URL } from '../constants/urls';
|
||||
import {
|
||||
appendLog,
|
||||
@@ -23,7 +24,7 @@ import {
|
||||
stopDaemon,
|
||||
writeStatus,
|
||||
} from '../daemon/manager';
|
||||
import { loadSettings, saveSettings } from '../settings';
|
||||
import { loadSettings, normalizeUrl, saveSettings } from '../settings';
|
||||
import { executeToolCall } from '../tools';
|
||||
import { cleanupAllProcesses } from '../tools/shell';
|
||||
import { log, setVerbose } from '../utils/logger';
|
||||
@@ -172,9 +173,9 @@ function buildDaemonArgs(options: ConnectOptions): string[] {
|
||||
}
|
||||
|
||||
async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
|
||||
const auth = await resolveToken(options);
|
||||
let auth = await resolveToken(options);
|
||||
const settings = loadSettings();
|
||||
const gatewayUrl = options.gateway?.replace(/\/$/, '') || settings?.gatewayUrl;
|
||||
const gatewayUrl = normalizeUrl(options.gateway) || settings?.gatewayUrl;
|
||||
|
||||
if (!gatewayUrl && settings?.serverUrl) {
|
||||
log.error(
|
||||
@@ -194,7 +195,9 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
|
||||
deviceId: options.deviceId,
|
||||
gatewayUrl: resolvedGatewayUrl,
|
||||
logger: isDaemonChild ? createDaemonLogger() : log,
|
||||
serverUrl: auth.serverUrl,
|
||||
token: auth.token,
|
||||
tokenType: auth.tokenType,
|
||||
userId: auth.userId,
|
||||
});
|
||||
|
||||
@@ -214,20 +217,19 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
|
||||
info(` Hostname : ${os.hostname()}`);
|
||||
info(` Platform : ${process.platform}`);
|
||||
info(` Gateway : ${resolvedGatewayUrl}`);
|
||||
info(` Auth : jwt`);
|
||||
info(` Auth : ${auth.tokenType}`);
|
||||
info(` Mode : ${isDaemonChild ? 'daemon' : 'foreground'}`);
|
||||
info('───────────────────');
|
||||
|
||||
// Update status file for daemon mode
|
||||
// Update local connection status so other CLI commands can resolve the current device
|
||||
const updateStatus = (connectionStatus: string) => {
|
||||
if (isDaemonChild) {
|
||||
writeStatus({
|
||||
connectionStatus,
|
||||
gatewayUrl: resolvedGatewayUrl,
|
||||
pid: process.pid,
|
||||
startedAt: startedAt.toISOString(),
|
||||
});
|
||||
}
|
||||
writeStatus({
|
||||
connectionStatus,
|
||||
deviceId: client.currentDeviceId,
|
||||
gatewayUrl: resolvedGatewayUrl,
|
||||
pid: process.pid,
|
||||
startedAt: startedAt.toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
const startedAt = new Date();
|
||||
@@ -285,20 +287,37 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
|
||||
// Handle auth failed
|
||||
client.on('auth_failed', (reason) => {
|
||||
error(`Authentication failed: ${reason}`);
|
||||
error("Run 'lh login' to re-authenticate.");
|
||||
error(
|
||||
`Run 'lh login', or set ${CLI_API_KEY_ENV} and run 'lh login --server <url>' to configure API key authentication.`,
|
||||
);
|
||||
cleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Handle auth expired
|
||||
// Handle auth expired — refresh token and reconnect automatically
|
||||
client.on('auth_expired', async () => {
|
||||
error('Authentication expired. Attempting to refresh...');
|
||||
const refreshed = await resolveToken({});
|
||||
if (refreshed) {
|
||||
info('Token refreshed. Please reconnect.');
|
||||
} else {
|
||||
error("Could not refresh token. Run 'lh login' to re-authenticate.");
|
||||
if (auth.tokenType === 'apiKey') {
|
||||
// API keys don't expire; ignore stale auth_expired signals
|
||||
return;
|
||||
}
|
||||
|
||||
info('Authentication expired. Attempting to refresh token...');
|
||||
|
||||
try {
|
||||
const refreshed = await resolveToken({});
|
||||
if (refreshed) {
|
||||
info('Token refreshed successfully. Reconnecting...');
|
||||
client.updateToken(refreshed.token);
|
||||
// Update cached auth so subsequent refreshes use the latest token
|
||||
auth = refreshed;
|
||||
await client.reconnect();
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// refresh failed — fall through
|
||||
}
|
||||
|
||||
error("Could not refresh token. Run 'lh login' to re-authenticate.");
|
||||
cleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -313,8 +332,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
|
||||
info('Shutting down...');
|
||||
cleanupAllProcesses();
|
||||
client.disconnect();
|
||||
removeStatus();
|
||||
if (isDaemonChild) {
|
||||
removeStatus();
|
||||
removePid();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -61,7 +61,6 @@ describe('generate command', () => {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Oidc-Auth': 'test-token',
|
||||
'X-lobe-chat-auth': 'test-xor-token',
|
||||
},
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
});
|
||||
|
||||
@@ -3,11 +3,15 @@ import fs from 'node:fs';
|
||||
import { Command } from 'commander';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { getUserIdFromApiKey } from '../auth/apiKey';
|
||||
import { saveCredentials } from '../auth/credentials';
|
||||
import { loadSettings, saveSettings } from '../settings';
|
||||
import { log } from '../utils/logger';
|
||||
import { registerLoginCommand, resolveCommandExecutable } from './login';
|
||||
|
||||
vi.mock('../auth/apiKey', () => ({
|
||||
getUserIdFromApiKey: vi.fn(),
|
||||
}));
|
||||
vi.mock('../auth/credentials', () => ({
|
||||
saveCredentials: vi.fn(),
|
||||
}));
|
||||
@@ -37,6 +41,7 @@ vi.mock('node:child_process', () => ({
|
||||
|
||||
describe('login command', () => {
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>;
|
||||
const originalApiKey = process.env.LOBEHUB_CLI_API_KEY;
|
||||
const originalPath = process.env.PATH;
|
||||
const originalPathext = process.env.PATHEXT;
|
||||
const originalSystemRoot = process.env.SystemRoot;
|
||||
@@ -46,11 +51,13 @@ describe('login command', () => {
|
||||
vi.stubGlobal('fetch', vi.fn());
|
||||
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
|
||||
vi.mocked(loadSettings).mockReturnValue(null);
|
||||
delete process.env.LOBEHUB_CLI_API_KEY;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
exitSpy.mockRestore();
|
||||
process.env.LOBEHUB_CLI_API_KEY = originalApiKey;
|
||||
process.env.PATH = originalPath;
|
||||
process.env.PATHEXT = originalPathext;
|
||||
process.env.SystemRoot = originalSystemRoot;
|
||||
@@ -102,8 +109,12 @@ describe('login command', () => {
|
||||
} as any;
|
||||
}
|
||||
|
||||
async function runLogin(program: Command, args: string[] = []) {
|
||||
return program.parseAsync(['node', 'test', 'login', ...args]);
|
||||
}
|
||||
|
||||
async function runLoginAndAdvanceTimers(program: Command, args: string[] = []) {
|
||||
const parsePromise = program.parseAsync(['node', 'test', 'login', ...args]);
|
||||
const parsePromise = runLogin(program, args);
|
||||
// Advance timers to let sleep resolve in the polling loop
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
@@ -130,6 +141,19 @@ describe('login command', () => {
|
||||
expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Login successful'));
|
||||
});
|
||||
|
||||
it('should use environment api key without storing credentials', async () => {
|
||||
process.env.LOBEHUB_CLI_API_KEY = 'sk-lh-env-test';
|
||||
vi.mocked(getUserIdFromApiKey).mockResolvedValue('user-123');
|
||||
|
||||
const program = createProgram();
|
||||
await runLogin(program);
|
||||
|
||||
expect(getUserIdFromApiKey).toHaveBeenCalledWith('sk-lh-env-test', 'https://app.lobehub.com');
|
||||
expect(saveCredentials).not.toHaveBeenCalled();
|
||||
expect(saveSettings).toHaveBeenCalledWith({ serverUrl: 'https://app.lobehub.com' });
|
||||
expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Login successful'));
|
||||
});
|
||||
|
||||
it('should persist custom server into settings', async () => {
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(deviceAuthResponse())
|
||||
@@ -159,6 +183,23 @@ describe('login command', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should preserve existing gateway for environment api key on the same server', async () => {
|
||||
process.env.LOBEHUB_CLI_API_KEY = 'sk-lh-env-test';
|
||||
vi.mocked(getUserIdFromApiKey).mockResolvedValue('user-123');
|
||||
vi.mocked(loadSettings).mockReturnValueOnce({
|
||||
gatewayUrl: 'https://gateway.example.com',
|
||||
serverUrl: 'https://test.com',
|
||||
});
|
||||
|
||||
const program = createProgram();
|
||||
await runLogin(program, ['--server', 'https://test.com/']);
|
||||
|
||||
expect(saveSettings).toHaveBeenCalledWith({
|
||||
gatewayUrl: 'https://gateway.example.com',
|
||||
serverUrl: 'https://test.com',
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear existing gateway when logging into a different server', async () => {
|
||||
vi.mocked(loadSettings).mockReturnValueOnce({
|
||||
gatewayUrl: 'https://gateway.example.com',
|
||||
|
||||
@@ -4,9 +4,11 @@ import path from 'node:path';
|
||||
|
||||
import type { Command } from 'commander';
|
||||
|
||||
import { getUserIdFromApiKey } from '../auth/apiKey';
|
||||
import { saveCredentials } from '../auth/credentials';
|
||||
import { CLI_API_KEY_ENV } from '../constants/auth';
|
||||
import { OFFICIAL_SERVER_URL } from '../constants/urls';
|
||||
import { loadSettings, saveSettings } from '../settings';
|
||||
import { loadSettings, normalizeUrl, saveSettings } from '../settings';
|
||||
import { log } from '../utils/logger';
|
||||
|
||||
const CLIENT_ID = 'lobehub-cli';
|
||||
@@ -51,13 +53,43 @@ async function parseJsonResponse<T>(res: Response, endpoint: string): Promise<T>
|
||||
export function registerLoginCommand(program: Command) {
|
||||
program
|
||||
.command('login')
|
||||
.description('Log in to LobeHub via browser (Device Code Flow)')
|
||||
.description('Log in to LobeHub via browser (Device Code Flow) or configure API key server')
|
||||
.option('--server <url>', 'LobeHub server URL', OFFICIAL_SERVER_URL)
|
||||
.action(async (options: LoginOptions) => {
|
||||
const serverUrl = options.server.replace(/\/$/, '');
|
||||
const serverUrl = normalizeUrl(options.server) || OFFICIAL_SERVER_URL;
|
||||
|
||||
log.info('Starting login...');
|
||||
|
||||
const apiKey = process.env[CLI_API_KEY_ENV];
|
||||
if (apiKey) {
|
||||
try {
|
||||
await getUserIdFromApiKey(apiKey, serverUrl);
|
||||
|
||||
const existingSettings = loadSettings();
|
||||
const shouldPreserveGateway = existingSettings?.serverUrl === serverUrl;
|
||||
|
||||
saveSettings(
|
||||
shouldPreserveGateway
|
||||
? {
|
||||
gatewayUrl: existingSettings.gatewayUrl,
|
||||
serverUrl,
|
||||
}
|
||||
: {
|
||||
// Gateway auth is tied to the login server's token issuer/JWKS.
|
||||
// When server changes, clear old gateway to avoid stale cross-environment config.
|
||||
serverUrl,
|
||||
},
|
||||
);
|
||||
log.info('Login successful! Credentials saved.');
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
log.error(`API key validation failed: ${message}`);
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Step 1: Request device code
|
||||
let deviceAuth: DeviceAuthResponse;
|
||||
try {
|
||||
@@ -164,6 +196,7 @@ export function registerLoginCommand(program: Command) {
|
||||
: undefined,
|
||||
refreshToken: body.refresh_token,
|
||||
});
|
||||
|
||||
const existingSettings = loadSettings();
|
||||
const shouldPreserveGateway = existingSettings?.serverUrl === serverUrl;
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Command } from 'commander';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { registerManCommand } from './man';
|
||||
|
||||
describe('man command', () => {
|
||||
let consoleSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
function createProgram() {
|
||||
const program = new Command();
|
||||
|
||||
program.name('lh').description('Sample CLI').version('1.0.0');
|
||||
|
||||
const generate = program
|
||||
.command('generate')
|
||||
.alias('gen')
|
||||
.description('Generate content')
|
||||
.option('-m, --model <model>', 'Model to use');
|
||||
|
||||
generate
|
||||
.command('text <prompt>')
|
||||
.description('Generate text from a prompt')
|
||||
.option('--json', 'Output raw JSON');
|
||||
|
||||
program.command('login').description('Log in to LobeHub');
|
||||
|
||||
registerManCommand(program);
|
||||
program.exitOverride();
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
it('renders a manual page for the root command', async () => {
|
||||
const program = createProgram();
|
||||
|
||||
await program.parseAsync(['node', 'test', 'man']);
|
||||
|
||||
const output = consoleSpy.mock.calls.at(0)?.[0];
|
||||
|
||||
expect(output).toContain('LH(1)');
|
||||
expect(output).toContain('NAME\n lh - Sample CLI');
|
||||
expect(output).toContain('ALIASES\n lobe, lobehub');
|
||||
expect(output).toContain('SYNOPSIS\n lh [options] [command]');
|
||||
expect(output).toContain('generate|gen [options] [command]');
|
||||
expect(output).toContain('man [options] [command...]');
|
||||
});
|
||||
|
||||
it('renders a manual page for a command with subcommands', async () => {
|
||||
const program = createProgram();
|
||||
|
||||
await program.parseAsync(['node', 'test', 'man', 'generate']);
|
||||
|
||||
const output = consoleSpy.mock.calls.at(0)?.[0];
|
||||
|
||||
expect(output).toContain('LH-GENERATE(1)');
|
||||
expect(output).toContain('NAME\n lh generate - Generate content');
|
||||
expect(output).toContain('ALIASES\n gen');
|
||||
expect(output).toContain('SYNOPSIS\n lh generate [options] [command]');
|
||||
expect(output).toContain('text [options] <prompt>');
|
||||
expect(output).toContain('-m, --model <model>');
|
||||
});
|
||||
|
||||
it('renders arguments for a leaf command', async () => {
|
||||
const program = createProgram();
|
||||
|
||||
await program.parseAsync(['node', 'test', 'man', 'generate', 'text']);
|
||||
|
||||
const output = consoleSpy.mock.calls.at(0)?.[0];
|
||||
|
||||
expect(output).toContain('LH-GENERATE-TEXT(1)');
|
||||
expect(output).toContain('NAME\n lh generate text - Generate text from a prompt');
|
||||
expect(output).toContain('ARGUMENTS');
|
||||
expect(output).toContain('<prompt>');
|
||||
expect(output).toContain('Required argument');
|
||||
expect(output).toContain('SEE ALSO');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { Argument, Command } from 'commander';
|
||||
|
||||
const ROOT_ALIASES = ['lobe', 'lobehub'];
|
||||
const HELP_COMMAND_NAME = 'help';
|
||||
|
||||
interface DefinitionItem {
|
||||
description: string;
|
||||
term: string;
|
||||
}
|
||||
|
||||
interface ResolutionResult {
|
||||
command?: Command;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function registerManCommand(program: Command) {
|
||||
program
|
||||
.command('man [command...]')
|
||||
.description('Show a manual page for the CLI or a subcommand')
|
||||
.action((commandPath: string[] | undefined) => {
|
||||
const segments = commandPath ?? [];
|
||||
const resolution = resolveCommandPath(program, segments);
|
||||
|
||||
if (!resolution.command) {
|
||||
program.error(resolution.error || 'Unknown command path.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(renderManualPage(program, resolution.command));
|
||||
});
|
||||
}
|
||||
|
||||
function resolveCommandPath(root: Command, segments: string[]): ResolutionResult {
|
||||
let current = root;
|
||||
|
||||
for (const segment of segments) {
|
||||
const next = getVisibleCommands(current).find(
|
||||
(command) => command.name() === segment || command.aliases().includes(segment),
|
||||
);
|
||||
|
||||
if (!next) {
|
||||
const currentPath = buildCommandPath(current).join(' ');
|
||||
const available = getVisibleCommands(current)
|
||||
.map((command) => command.name())
|
||||
.join(', ');
|
||||
|
||||
return {
|
||||
error: `Unknown command "${segment}" under "${currentPath}". Available: ${available || 'none'}.`,
|
||||
};
|
||||
}
|
||||
|
||||
current = next;
|
||||
}
|
||||
|
||||
return { command: current };
|
||||
}
|
||||
|
||||
function renderManualPage(root: Command, command: Command) {
|
||||
const sections = [
|
||||
formatManualHeader(command),
|
||||
formatNameSection(command),
|
||||
formatSynopsisSection(root, command),
|
||||
formatAliasesSection(command),
|
||||
formatDescriptionSection(command),
|
||||
formatArgumentsSection(command),
|
||||
formatCommandsSection(command),
|
||||
formatOptionsSection(command),
|
||||
formatSeeAlsoSection(root, command),
|
||||
].filter(Boolean);
|
||||
|
||||
return sections.join('\n\n');
|
||||
}
|
||||
|
||||
function formatManualHeader(command: Command) {
|
||||
return `${buildCommandPath(command).join('-').toUpperCase()}(1)`;
|
||||
}
|
||||
|
||||
function formatNameSection(command: Command) {
|
||||
return ['NAME', ` ${buildCommandPath(command).join(' ')} - ${command.description()}`].join('\n');
|
||||
}
|
||||
|
||||
function formatSynopsisSection(root: Command, command: Command) {
|
||||
return ['SYNOPSIS', ` ${buildSynopsis(root, command)}`].join('\n');
|
||||
}
|
||||
|
||||
function formatAliasesSection(command: Command) {
|
||||
const aliases = command.parent ? command.aliases() : ROOT_ALIASES;
|
||||
|
||||
if (aliases.length === 0) return '';
|
||||
|
||||
return ['ALIASES', ` ${aliases.join(', ')}`].join('\n');
|
||||
}
|
||||
|
||||
function formatDescriptionSection(command: Command) {
|
||||
const description = command.description() || 'No description available.';
|
||||
|
||||
return ['DESCRIPTION', ` ${description}`].join('\n');
|
||||
}
|
||||
|
||||
function formatArgumentsSection(command: Command) {
|
||||
if (command.registeredArguments.length === 0) return '';
|
||||
|
||||
const items = command.registeredArguments.map((argument) => ({
|
||||
description: describeArgument(argument),
|
||||
term: formatArgumentTerm(argument),
|
||||
}));
|
||||
|
||||
return ['ARGUMENTS', ...formatDefinitionList(items)].join('\n');
|
||||
}
|
||||
|
||||
function formatCommandsSection(command: Command) {
|
||||
const help = command.createHelp();
|
||||
const items = getVisibleCommands(command).map((subcommand) => ({
|
||||
description: help.subcommandDescription(subcommand),
|
||||
term: buildSubcommandTerm(subcommand),
|
||||
}));
|
||||
|
||||
if (items.length === 0) return '';
|
||||
|
||||
return ['COMMANDS', ...formatDefinitionList(items)].join('\n');
|
||||
}
|
||||
|
||||
function formatOptionsSection(command: Command) {
|
||||
const help = command.createHelp();
|
||||
const items = help.visibleOptions(command).map((option) => ({
|
||||
description: help.optionDescription(option),
|
||||
term: help.optionTerm(option),
|
||||
}));
|
||||
|
||||
if (items.length === 0) return '';
|
||||
|
||||
return ['OPTIONS', ...formatDefinitionList(items)].join('\n');
|
||||
}
|
||||
|
||||
function formatSeeAlsoSection(root: Command, command: Command) {
|
||||
const items = new Set<string>();
|
||||
const currentPath = buildCommandPath(command);
|
||||
|
||||
items.add(`${currentPath.join(' ')} --help`);
|
||||
|
||||
const parent = command.parent;
|
||||
if (parent) {
|
||||
const parentPath = buildCommandPath(parent).slice(1).join(' ');
|
||||
items.add(parentPath ? `lh man ${parentPath}` : 'lh man');
|
||||
}
|
||||
|
||||
for (const subcommand of getVisibleCommands(command).slice(0, 5)) {
|
||||
items.add(`lh man ${buildCommandPath(subcommand).slice(1).join(' ')}`);
|
||||
}
|
||||
|
||||
return ['SEE ALSO', ...Array.from(items).map((item) => ` ${item}`)].join('\n');
|
||||
}
|
||||
|
||||
function getVisibleCommands(command: Command) {
|
||||
const help = command.createHelp();
|
||||
|
||||
return help
|
||||
.visibleCommands(command)
|
||||
.filter((subcommand) => subcommand.name() !== HELP_COMMAND_NAME);
|
||||
}
|
||||
|
||||
function buildSynopsis(root: Command, command: Command) {
|
||||
const path = buildCommandPath(command);
|
||||
|
||||
if (command === root) {
|
||||
return `${path[0]} ${command.usage()}`.trim();
|
||||
}
|
||||
|
||||
return `${path.join(' ')} ${command.usage()}`.trim();
|
||||
}
|
||||
|
||||
function buildCommandPath(command: Command): string[] {
|
||||
const path: string[] = [];
|
||||
let current: Command | null = command;
|
||||
|
||||
while (current) {
|
||||
path.unshift(current.name());
|
||||
current = current.parent || null;
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
function buildSubcommandTerm(command: Command) {
|
||||
const name = [command.name(), ...command.aliases()].join('|');
|
||||
const usage = command.usage();
|
||||
|
||||
return usage ? `${name} ${usage}` : name;
|
||||
}
|
||||
|
||||
function formatDefinitionList(items: DefinitionItem[]) {
|
||||
const width = Math.max(...items.map((item) => item.term.length));
|
||||
|
||||
return items.map((item) => ` ${item.term.padEnd(width)} ${item.description}`);
|
||||
}
|
||||
|
||||
function formatArgumentTerm(argument: Argument) {
|
||||
const name = argument.name();
|
||||
|
||||
if (argument.required) {
|
||||
return argument.variadic ? `<${name}...>` : `<${name}>`;
|
||||
}
|
||||
|
||||
return argument.variadic ? `[${name}...]` : `[${name}]`;
|
||||
}
|
||||
|
||||
function describeArgument(argument: Argument) {
|
||||
const required = argument.required ? 'Required' : 'Optional';
|
||||
const variadic = argument.variadic ? 'variadic ' : '';
|
||||
|
||||
return `${required} ${variadic}argument`;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { Command } from 'commander';
|
||||
|
||||
import { registerOpenClawMigration } from './openclaw';
|
||||
|
||||
export function registerMigrateCommand(program: Command) {
|
||||
const migrate = program
|
||||
.command('migrate')
|
||||
.description('Migrate data from external tools (OpenClaw, ChatGPT, Claude, etc.)');
|
||||
|
||||
registerOpenClawMigration(migrate);
|
||||
}
|
||||
@@ -0,0 +1,588 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { Command } from 'commander';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// ── Mocks ──────────────────────────────────────────────
|
||||
|
||||
const { mockTrpcClient } = vi.hoisted(() => ({
|
||||
mockTrpcClient: {
|
||||
agent: {
|
||||
createAgent: { mutate: vi.fn() },
|
||||
getBuiltinAgent: { query: vi.fn() },
|
||||
},
|
||||
agentDocument: {
|
||||
upsertDocument: { mutate: vi.fn() },
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
|
||||
getTrpcClient: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockConfirm } = vi.hoisted(() => ({
|
||||
mockConfirm: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
getTrpcClient: mockGetTrpcClient,
|
||||
}));
|
||||
|
||||
vi.mock('../../settings', () => ({
|
||||
resolveServerUrl: () => 'https://app.lobehub.com',
|
||||
}));
|
||||
|
||||
vi.mock('../../utils/format', async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>();
|
||||
return { ...actual, confirm: mockConfirm };
|
||||
});
|
||||
|
||||
vi.mock('../../utils/logger', () => ({
|
||||
log: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
setVerbose: vi.fn(),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line import-x/first
|
||||
import { log } from '../../utils/logger';
|
||||
// eslint-disable-next-line import-x/first
|
||||
import { registerOpenClawMigration } from './openclaw';
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────
|
||||
|
||||
let tmpDir: string;
|
||||
|
||||
function createProgram() {
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
const migrate = program.command('migrate');
|
||||
registerOpenClawMigration(migrate);
|
||||
return program;
|
||||
}
|
||||
|
||||
function writeFile(relativePath: string, content: string) {
|
||||
const fullPath = path.join(tmpDir, relativePath);
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
fs.writeFileSync(fullPath, content);
|
||||
}
|
||||
|
||||
// ── Setup / teardown ───────────────────────────────────
|
||||
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>;
|
||||
let consoleSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openclaw-test-'));
|
||||
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {
|
||||
throw new Error('process.exit');
|
||||
}) as any);
|
||||
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
|
||||
mockConfirm.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
exitSpy.mockRestore();
|
||||
consoleSpy.mockRestore();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// ── Tests ──────────────────────────────────────────────
|
||||
|
||||
describe('migrate openclaw', () => {
|
||||
// ── Profile parsing ────────────────────────────────
|
||||
|
||||
describe('agent profile from workspace', () => {
|
||||
it('should read name, description, and emoji from IDENTITY.md', async () => {
|
||||
writeFile(
|
||||
'IDENTITY.md',
|
||||
['# IDENTITY.md', '- **Name:** 龙虾', '- **Creature:** AI 助手', '- **Emoji:** 🦞'].join(
|
||||
'\n',
|
||||
),
|
||||
);
|
||||
writeFile('hello.md', 'hello');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith({
|
||||
config: {
|
||||
avatar: '🦞',
|
||||
description: 'AI 助手',
|
||||
title: '龙虾',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter out placeholder emoji like (待定)', async () => {
|
||||
writeFile(
|
||||
'IDENTITY.md',
|
||||
['# IDENTITY.md', '- **Name:** TestBot', '- **Emoji:**', ' _(待定)_'].join('\n'),
|
||||
);
|
||||
writeFile('hello.md', 'hello');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith({
|
||||
config: {
|
||||
avatar: undefined,
|
||||
description: undefined,
|
||||
title: 'TestBot',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should fall back to "OpenClaw" when no identity files exist', async () => {
|
||||
writeFile('doc.md', 'content');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith({
|
||||
config: {
|
||||
avatar: undefined,
|
||||
description: undefined,
|
||||
title: 'OpenClaw',
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── File filtering ─────────────────────────────────
|
||||
|
||||
describe('file collection and filtering', () => {
|
||||
it('should exclude common directories like node_modules and .git', async () => {
|
||||
writeFile('README.md', 'readme');
|
||||
writeFile('node_modules/pkg/index.js', 'module');
|
||||
writeFile('.git/config', 'git');
|
||||
writeFile('.idea/workspace.xml', 'ide');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filename: 'README.md' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should exclude files matching glob patterns like *.pyc and *.log', async () => {
|
||||
writeFile('main.py', 'print("hi")');
|
||||
writeFile('main.pyc', 'bytecode');
|
||||
writeFile('app.log', 'log data');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filename: 'main.py' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should respect workspace .gitignore', async () => {
|
||||
writeFile('.gitignore', 'secret.txt\ndata/\n');
|
||||
writeFile('README.md', 'readme');
|
||||
writeFile('secret.txt', 'password');
|
||||
writeFile('data/dump.sql', 'sql');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
const filenames = mockTrpcClient.agentDocument.upsertDocument.mutate.mock.calls.map(
|
||||
(c: any[]) => c[0].filename,
|
||||
);
|
||||
expect(filenames).toContain('README.md');
|
||||
expect(filenames).not.toContain('secret.txt');
|
||||
expect(filenames).not.toContain('data/dump.sql');
|
||||
});
|
||||
|
||||
it('should skip binary files during import', async () => {
|
||||
writeFile('readme.md', 'text content');
|
||||
// Write a file with null bytes (binary)
|
||||
const binPath = path.join(tmpDir, 'image.dat');
|
||||
fs.writeFileSync(binPath, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0x00, 0x01]));
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
// Only the text file should be upserted
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filename: 'readme.md' }),
|
||||
);
|
||||
// Binary file should show as skipped in output
|
||||
const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
|
||||
expect(allOutput).toContain('skipped');
|
||||
});
|
||||
|
||||
it('should exclude database files by extension', async () => {
|
||||
writeFile('data.md', 'notes');
|
||||
writeFile('local.sqlite', 'fake-sqlite');
|
||||
writeFile('app.db', 'fake-db');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filename: 'data.md' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should collect files in subdirectories', async () => {
|
||||
writeFile('docs/guide.md', 'guide');
|
||||
writeFile('docs/api.md', 'api');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
const filenames = mockTrpcClient.agentDocument.upsertDocument.mutate.mock.calls
|
||||
.map((c: any[]) => c[0].filename)
|
||||
.sort();
|
||||
expect(filenames).toEqual(['docs/api.md', 'docs/guide.md']);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Dry run ────────────────────────────────────────
|
||||
|
||||
describe('--dry-run', () => {
|
||||
it('should list files without calling API', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--dry-run',
|
||||
]);
|
||||
|
||||
expect(mockGetTrpcClient).not.toHaveBeenCalled();
|
||||
expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).not.toHaveBeenCalled();
|
||||
expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Dry run'));
|
||||
});
|
||||
});
|
||||
|
||||
// ── Agent resolution ───────────────────────────────
|
||||
|
||||
describe('agent resolution', () => {
|
||||
it('should use --agent-id directly when provided', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--agent-id',
|
||||
'agt_existing',
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ agentId: 'agt_existing' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should resolve agent by --slug', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
mockTrpcClient.agent.getBuiltinAgent.query.mockResolvedValue({ id: 'agt_inbox' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--slug',
|
||||
'inbox',
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agent.getBuiltinAgent.query).toHaveBeenCalledWith({ slug: 'inbox' });
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ agentId: 'agt_inbox' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should create a new agent by default', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_new' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledTimes(1);
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ agentId: 'agt_new' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Confirmation ───────────────────────────────────
|
||||
|
||||
describe('confirmation', () => {
|
||||
it('should cancel when user declines', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
mockConfirm.mockResolvedValue(false);
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync(['node', 'test', 'migrate', 'openclaw', '--source', tmpDir]);
|
||||
|
||||
expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();
|
||||
expect(consoleSpy).toHaveBeenCalledWith('Cancelled.');
|
||||
});
|
||||
|
||||
it('should skip confirmation with --yes', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Error handling ─────────────────────────────────
|
||||
|
||||
describe('error handling', () => {
|
||||
it('should exit when source path does not exist', async () => {
|
||||
const program = createProgram();
|
||||
await program
|
||||
.parseAsync(['node', 'test', 'migrate', 'openclaw', '--source', '/nonexistent/path'])
|
||||
.catch(() => {}); // process.exit throws
|
||||
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
|
||||
});
|
||||
|
||||
it('should report failed files without aborting', async () => {
|
||||
writeFile('a.md', 'ok');
|
||||
writeFile('b.md', 'fail');
|
||||
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
// Files are iterated in readdir order; mock first success then failure
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate
|
||||
.mockResolvedValueOnce({})
|
||||
.mockRejectedValueOnce(new Error('upload error'));
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(2);
|
||||
const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
|
||||
expect(allOutput).toContain('1 imported');
|
||||
expect(allOutput).toContain('1 failed');
|
||||
});
|
||||
|
||||
it('should show no files message for empty workspace', async () => {
|
||||
// Only excluded items
|
||||
writeFile('.git/config', 'git');
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--dry-run',
|
||||
]);
|
||||
|
||||
expect(log.info).toHaveBeenCalledWith('No files found in workspace.');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Output ─────────────────────────────────────────
|
||||
|
||||
describe('output', () => {
|
||||
it('should print agent URL on completion', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_abc123' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
|
||||
expect(allOutput).toContain('https://app.lobehub.com/agent/agt_abc123');
|
||||
});
|
||||
|
||||
it('should show friendly completion message on success', async () => {
|
||||
writeFile('file.md', 'content');
|
||||
mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
|
||||
mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
|
||||
|
||||
const program = createProgram();
|
||||
await program.parseAsync([
|
||||
'node',
|
||||
'test',
|
||||
'migrate',
|
||||
'openclaw',
|
||||
'--source',
|
||||
tmpDir,
|
||||
'--yes',
|
||||
]);
|
||||
|
||||
const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
|
||||
expect(allOutput).toContain('Migration complete');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,466 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import type { Command } from 'commander';
|
||||
import ignore from 'ignore';
|
||||
import pc from 'picocolors';
|
||||
|
||||
import type { TrpcClient } from '../../api/client';
|
||||
import { getTrpcClient } from '../../api/client';
|
||||
import { resolveServerUrl } from '../../settings';
|
||||
import { confirm } from '../../utils/format';
|
||||
import { log } from '../../utils/logger';
|
||||
|
||||
const DEFAULT_AGENT_NAME = 'OpenClaw';
|
||||
|
||||
// Files to look for agent identity (tried in order)
|
||||
const IDENTITY_FILES = ['IDENTITY.md', 'SOUL.md'];
|
||||
|
||||
// Default ignore rules (gitignore syntax) applied when no .gitignore is found
|
||||
const DEFAULT_IGNORE_RULES = [
|
||||
// VCS
|
||||
'.git',
|
||||
'.svn',
|
||||
'.hg',
|
||||
|
||||
// OpenClaw internal
|
||||
'.openclaw',
|
||||
|
||||
// OS artifacts
|
||||
'.DS_Store',
|
||||
'Thumbs.db',
|
||||
'desktop.ini',
|
||||
|
||||
// IDE / editor
|
||||
'.idea',
|
||||
'.vscode',
|
||||
'.fleet',
|
||||
'.cursor',
|
||||
'.zed',
|
||||
'*.swp',
|
||||
'*.swo',
|
||||
'*~',
|
||||
|
||||
// Dependencies
|
||||
'node_modules',
|
||||
'.pnp',
|
||||
'.yarn',
|
||||
'bower_components',
|
||||
'vendor',
|
||||
'jspm_packages',
|
||||
|
||||
// Python
|
||||
'.venv',
|
||||
'venv',
|
||||
'env',
|
||||
'__pycache__',
|
||||
'*.pyc',
|
||||
'*.pyo',
|
||||
'.mypy_cache',
|
||||
'.ruff_cache',
|
||||
'.pytest_cache',
|
||||
'.tox',
|
||||
'.eggs',
|
||||
'*.egg-info',
|
||||
|
||||
// Ruby
|
||||
'.bundle',
|
||||
|
||||
// Rust
|
||||
'target',
|
||||
|
||||
// Go
|
||||
'go.sum',
|
||||
|
||||
// Java / JVM
|
||||
'.gradle',
|
||||
'.m2',
|
||||
|
||||
// .NET
|
||||
'bin',
|
||||
'obj',
|
||||
'packages',
|
||||
|
||||
// Build / cache / output
|
||||
'.cache',
|
||||
'.parcel-cache',
|
||||
'.next',
|
||||
'.nuxt',
|
||||
'.turbo',
|
||||
'.output',
|
||||
'dist',
|
||||
'build',
|
||||
'out',
|
||||
'.sass-cache',
|
||||
|
||||
// Env / secrets
|
||||
'.env',
|
||||
'.env.*',
|
||||
|
||||
// Test / coverage
|
||||
'coverage',
|
||||
'.nyc_output',
|
||||
|
||||
// Infra
|
||||
'.terraform',
|
||||
|
||||
// Temp
|
||||
'tmp',
|
||||
'.tmp',
|
||||
|
||||
// Logs
|
||||
'*.log',
|
||||
'logs',
|
||||
|
||||
// Databases
|
||||
'*.sqlite',
|
||||
'*.sqlite3',
|
||||
'*.db',
|
||||
'*.db-shm',
|
||||
'*.db-wal',
|
||||
'*.ldb',
|
||||
'*.mdb',
|
||||
'*.accdb',
|
||||
|
||||
// Archives / binaries
|
||||
'*.zip',
|
||||
'*.tar',
|
||||
'*.tar.gz',
|
||||
'*.tgz',
|
||||
'*.gz',
|
||||
'*.bz2',
|
||||
'*.xz',
|
||||
'*.rar',
|
||||
'*.7z',
|
||||
'*.jar',
|
||||
'*.war',
|
||||
'*.dll',
|
||||
'*.so',
|
||||
'*.dylib',
|
||||
'*.exe',
|
||||
'*.bin',
|
||||
'*.o',
|
||||
'*.a',
|
||||
'*.lib',
|
||||
'*.class',
|
||||
|
||||
// Images / media / fonts
|
||||
'*.png',
|
||||
'*.jpg',
|
||||
'*.jpeg',
|
||||
'*.gif',
|
||||
'*.bmp',
|
||||
'*.ico',
|
||||
'*.webp',
|
||||
'*.svg',
|
||||
'*.mp3',
|
||||
'*.mp4',
|
||||
'*.wav',
|
||||
'*.avi',
|
||||
'*.mov',
|
||||
'*.mkv',
|
||||
'*.flac',
|
||||
'*.ogg',
|
||||
'*.pdf',
|
||||
'*.woff',
|
||||
'*.woff2',
|
||||
'*.ttf',
|
||||
'*.otf',
|
||||
'*.eot',
|
||||
|
||||
// Lock files
|
||||
'package-lock.json',
|
||||
'yarn.lock',
|
||||
'pnpm-lock.yaml',
|
||||
'Gemfile.lock',
|
||||
'Cargo.lock',
|
||||
'poetry.lock',
|
||||
'composer.lock',
|
||||
];
|
||||
|
||||
interface AgentProfile {
|
||||
avatar?: string;
|
||||
description?: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to extract the agent name, description, and avatar emoji from
|
||||
* IDENTITY.md or SOUL.md. Falls back to "OpenClaw" if neither file
|
||||
* exists or parsing fails.
|
||||
*/
|
||||
function readAgentProfile(workspacePath: string): AgentProfile {
|
||||
for (const filename of IDENTITY_FILES) {
|
||||
const filePath = path.join(workspacePath, filename);
|
||||
if (!fs.existsSync(filePath)) continue;
|
||||
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
|
||||
// Try to extract **Name:** value
|
||||
const nameMatch = content.match(/\*{0,2}Name:?\*{0,2}\s*(.+)/i);
|
||||
const title = nameMatch ? nameMatch[1].trim() : DEFAULT_AGENT_NAME;
|
||||
|
||||
// Try to extract **Creature:** or **Vibe:** or **Description:** as description
|
||||
const descMatch = content.match(/\*{0,2}(?:Creature|Vibe|Description):?\*{0,2}\s*(.+)/i);
|
||||
const description = descMatch ? descMatch[1].trim() : undefined;
|
||||
|
||||
// Try to extract **Emoji:** value (single emoji)
|
||||
const emojiMatch = content.match(/\*{0,2}Emoji:?\*{0,2}\s*(.+)/i);
|
||||
const rawAvatar = emojiMatch ? emojiMatch[1].trim() : undefined;
|
||||
// Filter out placeholder text like (待定), _(待定)_, (TBD), N/A, etc.
|
||||
const isPlaceholder =
|
||||
rawAvatar && /^[_*((].*[))_*]$|^(?:tbd|todo|n\/?a|none|待定|未定)$/i.test(rawAvatar);
|
||||
const avatar = rawAvatar && !isPlaceholder ? rawAvatar : undefined;
|
||||
|
||||
return { avatar, description, title };
|
||||
}
|
||||
|
||||
return { title: DEFAULT_AGENT_NAME };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an ignore filter for the workspace. Uses .gitignore if present,
|
||||
* otherwise falls back to a comprehensive default rule set.
|
||||
*/
|
||||
function buildIgnoreFilter(workspacePath: string) {
|
||||
const ig = ignore();
|
||||
|
||||
const gitignorePath = path.join(workspacePath, '.gitignore');
|
||||
if (fs.existsSync(gitignorePath)) {
|
||||
ig.add(fs.readFileSync(gitignorePath, 'utf8'));
|
||||
}
|
||||
|
||||
// Always apply default rules on top
|
||||
ig.add(DEFAULT_IGNORE_RULES);
|
||||
|
||||
return ig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively collect all files under `dir`, filtered by ignore rules.
|
||||
* Returns paths relative to `baseDir`.
|
||||
*/
|
||||
function collectFiles(dir: string, baseDir: string, ig: ReturnType<typeof ignore>): string[] {
|
||||
const results: string[] = [];
|
||||
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const relativePath = path.relative(baseDir, path.join(dir, entry.name));
|
||||
|
||||
// Directories need a trailing slash for ignore to match correctly
|
||||
const testPath = entry.isDirectory() ? `${relativePath}/` : relativePath;
|
||||
if (ig.ignores(testPath)) continue;
|
||||
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
results.push(...collectFiles(fullPath, baseDir, ig));
|
||||
} else if (entry.isFile()) {
|
||||
results.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick check: read the first 8KB and look for null bytes.
|
||||
* If found, the file is likely binary and should be skipped.
|
||||
*/
|
||||
function isBinaryFile(filePath: string): boolean {
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(8192);
|
||||
const bytesRead = fs.readSync(fd, buf, 0, 8192, 0);
|
||||
for (let i = 0; i < bytesRead; i++) {
|
||||
if (buf[i] === 0) return true;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function formatAgentLabel(profile: AgentProfile): string {
|
||||
return profile.avatar ? `${profile.avatar} ${profile.title}` : profile.title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the target agent ID.
|
||||
* Priority: --agent-id > --slug > create new agent from workspace profile.
|
||||
*/
|
||||
async function resolveAgentId(
|
||||
client: TrpcClient,
|
||||
opts: { agentId?: string; slug?: string },
|
||||
profile: AgentProfile,
|
||||
): Promise<string> {
|
||||
if (opts.agentId) return opts.agentId;
|
||||
|
||||
if (opts.slug) {
|
||||
const agent = await client.agent.getBuiltinAgent.query({ slug: opts.slug });
|
||||
if (!agent) {
|
||||
log.error(`Agent not found for slug: ${opts.slug}`);
|
||||
process.exit(1);
|
||||
}
|
||||
return agent.id;
|
||||
}
|
||||
|
||||
const label = formatAgentLabel(profile);
|
||||
log.info(`Creating new agent ${pc.bold(label)}...`);
|
||||
const result = await client.agent.createAgent.mutate({
|
||||
config: {
|
||||
avatar: profile.avatar,
|
||||
description: profile.description,
|
||||
title: profile.title,
|
||||
},
|
||||
});
|
||||
|
||||
const id = result.agentId;
|
||||
if (!id) {
|
||||
log.error('Failed to create agent — no agentId returned.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`${pc.green('✓')} Agent created: ${pc.bold(label)}`);
|
||||
return id;
|
||||
}
|
||||
|
||||
export function registerOpenClawMigration(migrate: Command) {
|
||||
migrate
|
||||
.command('openclaw')
|
||||
.description('Import OpenClaw workspace files as agent documents')
|
||||
.option(
|
||||
'--source <path>',
|
||||
'Path to OpenClaw workspace',
|
||||
path.join(os.homedir(), '.openclaw', 'workspace'),
|
||||
)
|
||||
.option('--agent-id <id>', 'Import into an existing agent by ID')
|
||||
.option('--slug <slug>', 'Import into an existing agent by slug (e.g. "inbox")')
|
||||
.option('--dry-run', 'Preview files without importing')
|
||||
.option('--yes', 'Skip confirmation prompt')
|
||||
.action(
|
||||
async (options: {
|
||||
agentId?: string;
|
||||
dryRun?: boolean;
|
||||
slug?: string;
|
||||
source: string;
|
||||
yes?: boolean;
|
||||
}) => {
|
||||
// Check auth early so users don't scan files only to find out they're not logged in
|
||||
if (!options.dryRun) {
|
||||
await getTrpcClient();
|
||||
}
|
||||
|
||||
const workspacePath = path.resolve(options.source);
|
||||
|
||||
// Validate source directory
|
||||
if (!fs.existsSync(workspacePath)) {
|
||||
log.error(`OpenClaw workspace not found: ${workspacePath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!fs.statSync(workspacePath).isDirectory()) {
|
||||
log.error(`Not a directory: ${workspacePath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Read agent profile from workspace identity files
|
||||
const profile = readAgentProfile(workspacePath);
|
||||
const label = formatAgentLabel(profile);
|
||||
|
||||
// Collect files (respects .gitignore + default rules)
|
||||
const ig = buildIgnoreFilter(workspacePath);
|
||||
const files = collectFiles(workspacePath, workspacePath, ig);
|
||||
|
||||
if (files.length === 0) {
|
||||
log.info('No files found in workspace.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Found ${pc.bold(String(files.length))} file(s) in ${pc.dim(workspacePath)}:\n`,
|
||||
);
|
||||
for (const f of files) {
|
||||
console.log(` ${pc.dim('•')} ${f}`);
|
||||
}
|
||||
console.log();
|
||||
|
||||
if (options.dryRun) {
|
||||
log.info('Dry run — no changes made.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Confirm
|
||||
if (!options.yes) {
|
||||
const target = options.agentId
|
||||
? `agent ${pc.bold(options.agentId)}`
|
||||
: options.slug
|
||||
? `agent slug "${pc.bold(options.slug)}"`
|
||||
: `a new ${pc.bold(label)} agent`;
|
||||
const confirmed = await confirm(
|
||||
`Import ${files.length} file(s) as agent documents into ${target}?`,
|
||||
);
|
||||
if (!confirmed) {
|
||||
console.log('Cancelled.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const client = await getTrpcClient();
|
||||
|
||||
// Create or reuse agent
|
||||
const agentId = await resolveAgentId(client, options, profile);
|
||||
|
||||
console.log(`\nImporting to ${pc.bold(label)}...\n`);
|
||||
|
||||
let success = 0;
|
||||
let failed = 0;
|
||||
|
||||
let skipped = 0;
|
||||
|
||||
for (const relativePath of files) {
|
||||
const fullPath = path.join(workspacePath, relativePath);
|
||||
|
||||
try {
|
||||
// Skip binary files that slipped through the extension filter
|
||||
if (isBinaryFile(fullPath)) {
|
||||
console.log(` ${pc.dim('○')} ${relativePath} ${pc.dim('(binary, skipped)')}`);
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(fullPath, 'utf8');
|
||||
const stat = fs.statSync(fullPath);
|
||||
|
||||
await client.agentDocument.upsertDocument.mutate({
|
||||
agentId,
|
||||
content,
|
||||
createdAt: stat.birthtime,
|
||||
filename: relativePath,
|
||||
updatedAt: stat.mtime,
|
||||
});
|
||||
console.log(` ${pc.green('✓')} ${relativePath}`);
|
||||
success++;
|
||||
} catch (err: any) {
|
||||
console.log(` ${pc.red('✗')} ${relativePath} — ${err.message || err}`);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
const agentUrl = `${resolveServerUrl()}/agent/${agentId}`;
|
||||
const skippedInfo = skipped > 0 ? `, ${skipped} skipped` : '';
|
||||
console.log();
|
||||
if (failed === 0) {
|
||||
console.log(
|
||||
`${pc.green('✓')} Migration complete! ${pc.bold(String(success))} file(s) imported to ${pc.bold(label)}.${skippedInfo}`,
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
`${pc.yellow('⚠')} Migration finished with issues: ${pc.bold(String(success))} imported, ${pc.red(String(failed))} failed${skippedInfo}.`,
|
||||
);
|
||||
}
|
||||
console.log(`\n ${pc.dim('→')} ${pc.underline(agentUrl)}`);
|
||||
console.log();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -3,10 +3,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// Mock resolveToken
|
||||
vi.mock('../auth/resolveToken', () => ({
|
||||
resolveToken: vi.fn().mockResolvedValue({ token: 'test-token', userId: 'test-user' }),
|
||||
resolveToken: vi.fn().mockResolvedValue({
|
||||
serverUrl: 'https://app.lobehub.com',
|
||||
token: 'test-token',
|
||||
tokenType: 'jwt',
|
||||
userId: 'test-user',
|
||||
}),
|
||||
}));
|
||||
vi.mock('../settings', () => ({
|
||||
loadSettings: vi.fn().mockReturnValue(null),
|
||||
normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),
|
||||
saveSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -115,6 +121,16 @@ describe('status command', () => {
|
||||
serverUrl: 'https://self-hosted.example.com',
|
||||
});
|
||||
});
|
||||
it('should pass the resolved serverUrl to GatewayClient', async () => {
|
||||
const program = createProgram();
|
||||
const parsePromise = program.parseAsync(['node', 'test', 'status']);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
clientEventHandlers['connected']?.();
|
||||
|
||||
await parsePromise;
|
||||
expect(clientOptions.serverUrl).toBe('https://app.lobehub.com');
|
||||
});
|
||||
|
||||
it('should log CONNECTED on successful connection', async () => {
|
||||
const program = createProgram();
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Command } from 'commander';
|
||||
|
||||
import { resolveToken } from '../auth/resolveToken';
|
||||
import { OFFICIAL_GATEWAY_URL } from '../constants/urls';
|
||||
import { loadSettings, saveSettings } from '../settings';
|
||||
import { loadSettings, normalizeUrl, saveSettings } from '../settings';
|
||||
import { log, setVerbose } from '../utils/logger';
|
||||
|
||||
interface StatusOptions {
|
||||
@@ -30,7 +30,7 @@ export function registerStatusCommand(program: Command) {
|
||||
|
||||
const auth = await resolveToken(options);
|
||||
const settings = loadSettings();
|
||||
const gatewayUrl = options.gateway?.replace(/\/$/, '') || settings?.gatewayUrl;
|
||||
const gatewayUrl = normalizeUrl(options.gateway) || settings?.gatewayUrl;
|
||||
|
||||
if (!gatewayUrl && settings?.serverUrl) {
|
||||
log.error(
|
||||
@@ -50,7 +50,9 @@ export function registerStatusCommand(program: Command) {
|
||||
autoReconnect: false,
|
||||
gatewayUrl: gatewayUrl || OFFICIAL_GATEWAY_URL,
|
||||
logger: log,
|
||||
serverUrl: auth.serverUrl,
|
||||
token: auth.token,
|
||||
tokenType: auth.tokenType,
|
||||
userId: auth.userId,
|
||||
});
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@ import type { Command } from 'commander';
|
||||
import pc from 'picocolors';
|
||||
|
||||
import { getTrpcClient } from '../../api/client';
|
||||
import type { KanbanColumn } from '../../utils/format';
|
||||
import {
|
||||
confirm,
|
||||
displayWidth,
|
||||
outputJson,
|
||||
printKanban,
|
||||
printTable,
|
||||
timeAgo,
|
||||
truncate,
|
||||
@@ -37,10 +39,12 @@ export function registerTaskCommand(program: Command) {
|
||||
.option('-L, --limit <n>', 'Page size', '50')
|
||||
.option('--offset <n>', 'Offset', '0')
|
||||
.option('--tree', 'Display as tree structure')
|
||||
.option('--board', 'Display as kanban board grouped by status')
|
||||
.option('--json [fields]', 'Output JSON')
|
||||
.action(
|
||||
async (options: {
|
||||
agent?: string;
|
||||
board?: boolean;
|
||||
json?: string | boolean;
|
||||
limit?: string;
|
||||
offset?: string;
|
||||
@@ -59,8 +63,8 @@ export function registerTaskCommand(program: Command) {
|
||||
if (options.limit) input.limit = Number.parseInt(options.limit, 10);
|
||||
if (options.offset) input.offset = Number.parseInt(options.offset, 10);
|
||||
|
||||
// For tree mode, fetch all tasks (no pagination limit)
|
||||
if (options.tree) {
|
||||
// For tree/board mode, fetch all tasks (no pagination limit)
|
||||
if (options.tree || options.board) {
|
||||
input.limit = 100;
|
||||
delete input.offset;
|
||||
}
|
||||
@@ -77,6 +81,58 @@ export function registerTaskCommand(program: Command) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.board) {
|
||||
// Kanban board grouped by status
|
||||
const statusOrder = [
|
||||
'backlog',
|
||||
'blocked',
|
||||
'running',
|
||||
'paused',
|
||||
'completed',
|
||||
'failed',
|
||||
'timeout',
|
||||
'canceled',
|
||||
];
|
||||
|
||||
const statusColors: Record<string, (s: string) => string> = {
|
||||
backlog: pc.dim,
|
||||
blocked: pc.red,
|
||||
canceled: pc.dim,
|
||||
completed: pc.green,
|
||||
failed: pc.red,
|
||||
paused: pc.yellow,
|
||||
running: pc.blue,
|
||||
timeout: pc.red,
|
||||
};
|
||||
|
||||
// Group tasks by status
|
||||
const grouped = new Map<string, any[]>();
|
||||
for (const t of result.data) {
|
||||
const status = t.status || 'backlog';
|
||||
const list = grouped.get(status) || [];
|
||||
list.push(t);
|
||||
grouped.set(status, list);
|
||||
}
|
||||
|
||||
const kanbanColumns: KanbanColumn[] = statusOrder
|
||||
.filter((s) => grouped.has(s))
|
||||
.map((status) => ({
|
||||
color: statusColors[status],
|
||||
items: grouped.get(status)!.map((t: any) => ({
|
||||
badge: pc.dim(t.identifier),
|
||||
meta: t.assigneeAgentId ? `agent: ${t.assigneeAgentId}` : undefined,
|
||||
title: t.name || t.instruction,
|
||||
})),
|
||||
title: status.toUpperCase(),
|
||||
}));
|
||||
|
||||
console.log();
|
||||
printKanban(kanbanColumns);
|
||||
console.log();
|
||||
log.info(`Total: ${result.total}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.tree) {
|
||||
// Build tree display
|
||||
const taskMap = new Map<string, any>();
|
||||
@@ -139,11 +195,72 @@ export function registerTaskCommand(program: Command) {
|
||||
|
||||
task
|
||||
.command('view <id>')
|
||||
.description('View task details (by ID or identifier like TASK-1)')
|
||||
.description('View task details (by ID or identifier like T-1)')
|
||||
.option('--json [fields]', 'Output JSON')
|
||||
.action(async (id: string, options: { json?: string | boolean }) => {
|
||||
const client = await getTrpcClient();
|
||||
|
||||
// ── Auto-detect by id prefix ──
|
||||
|
||||
// docs_ → show document content
|
||||
if (id.startsWith('docs_')) {
|
||||
const doc = await client.document.getDocumentDetail.query({ id });
|
||||
|
||||
if (options.json !== undefined) {
|
||||
outputJson(doc, options.json);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!doc) {
|
||||
log.error('Document not found.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n📄 ${pc.bold(doc.title || 'Untitled')} ${pc.dim(doc.id)}`);
|
||||
if (doc.fileType) console.log(`${pc.dim('Type:')} ${doc.fileType}`);
|
||||
if (doc.totalCharCount) console.log(`${pc.dim('Size:')} ${doc.totalCharCount} chars`);
|
||||
console.log(`${pc.dim('Updated:')} ${timeAgo(doc.updatedAt)}`);
|
||||
console.log();
|
||||
if (doc.content) {
|
||||
console.log(doc.content);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// tpc_ → show topic messages
|
||||
if (id.startsWith('tpc_')) {
|
||||
const messages = await client.message.getMessages.query({ topicId: id });
|
||||
const items = Array.isArray(messages) ? messages : [];
|
||||
|
||||
if (options.json !== undefined) {
|
||||
outputJson(items, options.json);
|
||||
return;
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
log.info('No messages in this topic.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log();
|
||||
for (const msg of items) {
|
||||
const role =
|
||||
msg.role === 'assistant'
|
||||
? pc.green('Assistant')
|
||||
: msg.role === 'user'
|
||||
? pc.blue('User')
|
||||
: pc.dim(msg.role);
|
||||
|
||||
console.log(`${pc.bold(role)} ${pc.dim(timeAgo(msg.createdAt))}`);
|
||||
if (msg.content) {
|
||||
console.log(msg.content);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Default: task detail
|
||||
const result = await client.task.detail.query({ id });
|
||||
|
||||
if (options.json !== undefined) {
|
||||
@@ -179,23 +296,34 @@ export function registerTaskCommand(program: Command) {
|
||||
}
|
||||
if (t.error) console.log(`${pc.red('Error:')} ${t.error}`);
|
||||
|
||||
// ── Subtasks ──
|
||||
// ── Subtasks (nested tree) ──
|
||||
if (t.subtasks && t.subtasks.length > 0) {
|
||||
// Build lookup: which subtasks are completed
|
||||
const completedIdentifiers = new Set(
|
||||
t.subtasks.filter((s) => s.status === 'completed').map((s) => s.identifier),
|
||||
);
|
||||
// Build lookup: which subtasks are completed (flatten tree)
|
||||
const collectCompleted = (nodes: typeof t.subtasks, set: Set<string>): Set<string> => {
|
||||
for (const s of nodes!) {
|
||||
if (s.status === 'completed') set.add(s.identifier);
|
||||
if (s.children) collectCompleted(s.children, set);
|
||||
}
|
||||
return set;
|
||||
};
|
||||
const completedIdentifiers = collectCompleted(t.subtasks, new Set());
|
||||
|
||||
const renderSubtasks = (nodes: typeof t.subtasks, indent: string) => {
|
||||
for (const s of nodes!) {
|
||||
const depInfo = s.blockedBy ? pc.dim(` ← blocks: ${s.blockedBy}`) : '';
|
||||
const isBlocked = s.blockedBy && !completedIdentifiers.has(s.blockedBy);
|
||||
const displayStatus = s.status === 'backlog' && isBlocked ? 'blocked' : s.status;
|
||||
console.log(
|
||||
`${indent}${pc.dim(s.identifier)} ${statusBadge(displayStatus)} ${s.name || '(unnamed)'}${depInfo}`,
|
||||
);
|
||||
if (s.children && s.children.length > 0) {
|
||||
renderSubtasks(s.children, indent + ' ');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
console.log(`\n${pc.bold('Subtasks:')}`);
|
||||
for (const s of t.subtasks) {
|
||||
const depInfo = s.blockedBy ? pc.dim(` ← blocks: ${s.blockedBy}`) : '';
|
||||
// Show 'blocked' instead of 'backlog' if task has unresolved dependencies
|
||||
const isBlocked = s.blockedBy && !completedIdentifiers.has(s.blockedBy);
|
||||
const displayStatus = s.status === 'backlog' && isBlocked ? 'blocked' : s.status;
|
||||
console.log(
|
||||
` ${pc.dim(s.identifier)} ${statusBadge(displayStatus)} ${s.name || '(unnamed)'}${depInfo}`,
|
||||
);
|
||||
}
|
||||
renderSubtasks(t.subtasks, ' ');
|
||||
}
|
||||
|
||||
// ── Dependencies ──
|
||||
@@ -279,83 +407,74 @@ export function registerTaskCommand(program: Command) {
|
||||
const LEFT_COL = 56;
|
||||
const FROM_WIDTH = 10;
|
||||
|
||||
const renderNodes = (list: typeof nodes, indent: string) => {
|
||||
const renderNodes = (list: typeof nodes, indent: string, isChild: boolean) => {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const node = list[i];
|
||||
const isFolder = node.fileType === 'custom/folder';
|
||||
const isLast = i === list.length - 1;
|
||||
const icon = isFolder ? '📁' : '📄';
|
||||
const prefix = `${indent}${icon} `;
|
||||
const connector = isChild ? (isLast ? '└── ' : '├── ') : '';
|
||||
const prefix = `${indent}${connector}${icon} `;
|
||||
const titleStr = truncate(node.title || 'Untitled', LEFT_COL - displayWidth(prefix));
|
||||
const titlePad = ' '.repeat(
|
||||
Math.max(1, LEFT_COL - displayWidth(prefix) - displayWidth(titleStr)),
|
||||
);
|
||||
|
||||
const fromStr = node.sourceTaskIdentifier ? `← ${node.sourceTaskIdentifier}` : '';
|
||||
const fromPad = fromStr
|
||||
? ' '.repeat(Math.max(1, FROM_WIDTH - fromStr.length + 1))
|
||||
: '';
|
||||
const fromPad = ' '.repeat(Math.max(1, FROM_WIDTH - fromStr.length + 1));
|
||||
const size =
|
||||
!isFolder && node.size ? formatSize(node.size).padStart(6) + ' chars' : '';
|
||||
!isFolder && node.size
|
||||
? formatSize(node.size).padStart(6) + ' chars'
|
||||
: ''.padStart(12);
|
||||
|
||||
const ago = node.createdAt ? ` ${timeAgo(node.createdAt)}` : '';
|
||||
|
||||
console.log(
|
||||
`${prefix}${titleStr}${titlePad}${pc.dim(`(${node.documentId})`)} ${fromStr}${fromPad}${pc.dim(size)}`,
|
||||
`${prefix}${titleStr}${titlePad}${pc.dim(`(${node.documentId})`)} ${fromStr}${fromPad}${pc.dim(size)}${pc.dim(ago)}`,
|
||||
);
|
||||
|
||||
if (node.children && node.children.length > 0) {
|
||||
const childIndent = indent + (isLast ? ' ' : ' ');
|
||||
renderNodes(node.children, childIndent);
|
||||
const childIndent = isChild ? indent + (isLast ? ' ' : '│ ') : indent;
|
||||
renderNodes(node.children, childIndent, true);
|
||||
}
|
||||
}
|
||||
};
|
||||
renderNodes(nodes, ' ');
|
||||
renderNodes(nodes, ' ', false);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Activities ──
|
||||
// ── Activities (already sorted desc by service) ──
|
||||
{
|
||||
const tl = t.timeline;
|
||||
const activities: { text: string; time: string }[] = [];
|
||||
|
||||
for (const tp of tl?.topics || []) {
|
||||
const sBadge = statusBadge(tp.status || 'running');
|
||||
activities.push({
|
||||
text: ` 💬 ${pc.dim((tp.time || '').padStart(7))} Topic #${tp.seq || '?'} ${tp.title || 'Untitled'} ${sBadge} ${pc.dim(tp.id || '')}`,
|
||||
time: tp.time || '',
|
||||
});
|
||||
}
|
||||
|
||||
for (const b of tl?.briefs || []) {
|
||||
const icon = briefIcon(b.type);
|
||||
const pri =
|
||||
b.priority === 'urgent'
|
||||
? pc.red(' [urgent]')
|
||||
: b.priority === 'normal'
|
||||
? pc.yellow(' [normal]')
|
||||
: '';
|
||||
const resolved = b.resolvedAction ? pc.green(` ✏️ ${b.resolvedAction}`) : '';
|
||||
const typeLabel = pc.dim(`[${b.type}]`);
|
||||
activities.push({
|
||||
text: ` ${icon} ${pc.dim((b.time || '').padStart(7))} Brief ${typeLabel} ${b.title}${pri}${resolved} ${pc.dim(b.id || '')}`,
|
||||
time: b.time || '',
|
||||
});
|
||||
}
|
||||
|
||||
for (const c of tl?.comments || []) {
|
||||
const author = c.agentId ? `🤖 ${c.agentId}` : '👤 user';
|
||||
activities.push({
|
||||
text: ` 💭 ${pc.dim((c.time || '').padStart(7))} ${pc.cyan(author)} ${c.content}`,
|
||||
time: c.time || '',
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`\n${pc.bold('Activities:')}`);
|
||||
if (activities.length === 0) {
|
||||
const acts = t.activities || [];
|
||||
if (acts.length === 0) {
|
||||
console.log(` ${pc.dim('No activities yet.')}`);
|
||||
} else {
|
||||
// Activities are already sorted by the service
|
||||
for (const act of activities) {
|
||||
console.log(act.text);
|
||||
for (const act of acts) {
|
||||
const ago = act.time ? timeAgo(act.time) : '';
|
||||
const idSuffix = act.id ? ` ${pc.dim(act.id)}` : '';
|
||||
if (act.type === 'topic') {
|
||||
const sBadge = statusBadge(act.status || 'running');
|
||||
console.log(
|
||||
` 💬 ${pc.dim(ago.padStart(7))} Topic #${act.seq || '?'} ${act.title || 'Untitled'} ${sBadge}${idSuffix}`,
|
||||
);
|
||||
} else if (act.type === 'brief') {
|
||||
const icon = briefIcon(act.briefType || '');
|
||||
const pri =
|
||||
act.priority === 'urgent'
|
||||
? pc.red(' [urgent]')
|
||||
: act.priority === 'normal'
|
||||
? pc.yellow(' [normal]')
|
||||
: '';
|
||||
const resolved = act.resolvedAction ? pc.green(` ✏️ ${act.resolvedAction}`) : '';
|
||||
const typeLabel = pc.dim(`[${act.briefType}]`);
|
||||
console.log(
|
||||
` ${icon} ${pc.dim(ago.padStart(7))} Brief ${typeLabel} ${act.title}${pri}${resolved}${idSuffix}`,
|
||||
);
|
||||
} else if (act.type === 'comment') {
|
||||
const author = act.agentId ? `🤖 ${act.agentId}` : '👤 user';
|
||||
console.log(` 💭 ${pc.dim(ago.padStart(7))} ${pc.cyan(author)} ${act.content}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -373,7 +492,7 @@ export function registerTaskCommand(program: Command) {
|
||||
.option('--agent <id>', 'Assign to agent')
|
||||
.option('--parent <id>', 'Parent task ID')
|
||||
.option('--priority <n>', 'Priority (0=none, 1=urgent, 2=high, 3=normal, 4=low)', '0')
|
||||
.option('--prefix <prefix>', 'Identifier prefix', 'TASK')
|
||||
.option('--prefix <prefix>', 'Identifier prefix', 'T')
|
||||
.option('--json [fields]', 'Output JSON')
|
||||
.action(
|
||||
async (options: {
|
||||
@@ -419,6 +538,10 @@ export function registerTaskCommand(program: Command) {
|
||||
.option('--heartbeat-interval <n>', 'Heartbeat interval in seconds')
|
||||
.option('--heartbeat-timeout <n>', 'Heartbeat timeout in seconds (0 to disable)')
|
||||
.option('--description <text>', 'Task description')
|
||||
.option(
|
||||
'--status <status>',
|
||||
'Set status (backlog, running, paused, completed, failed, canceled)',
|
||||
)
|
||||
.option('--json [fields]', 'Output JSON')
|
||||
.action(
|
||||
async (
|
||||
@@ -432,10 +555,23 @@ export function registerTaskCommand(program: Command) {
|
||||
json?: string | boolean;
|
||||
name?: string;
|
||||
priority?: string;
|
||||
status?: string;
|
||||
},
|
||||
) => {
|
||||
const client = await getTrpcClient();
|
||||
|
||||
// Handle --status separately (uses updateStatus API)
|
||||
if (options.status) {
|
||||
const valid = ['backlog', 'running', 'paused', 'completed', 'failed', 'canceled'];
|
||||
if (!valid.includes(options.status)) {
|
||||
log.error(`Invalid status "${options.status}". Must be one of: ${valid.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
const result = await client.task.updateStatus.mutate({ id, status: options.status });
|
||||
log.info(`${pc.bold(result.data.identifier)} → ${options.status}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const input: Record<string, any> = { id };
|
||||
if (options.name) input.name = options.name;
|
||||
if (options.instruction) input.instruction = options.instruction;
|
||||
|
||||
@@ -258,7 +258,7 @@ export function registerLifecycleCommands(task: Command) {
|
||||
|
||||
task
|
||||
.command('sort <id> <identifiers...>')
|
||||
.description('Reorder subtasks (e.g. lh task sort TASK-1 TASK-2 TASK-4 TASK-3)')
|
||||
.description('Reorder subtasks (e.g. lh task sort T-1 T-2 T-4 T-3)')
|
||||
.action(async (id: string, identifiers: string[]) => {
|
||||
const client = await getTrpcClient();
|
||||
const result = (await client.task.reorderSubtasks.mutate({
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const CLI_API_KEY_ENV = 'LOBEHUB_CLI_API_KEY';
|
||||
@@ -1,2 +1,3 @@
|
||||
export const OFFICIAL_AGENT_GATEWAY_URL = 'https://agent-gateway.lobehub.com';
|
||||
export const OFFICIAL_SERVER_URL = 'https://app.lobehub.com';
|
||||
export const OFFICIAL_GATEWAY_URL = 'https://device-gateway.lobehub.com';
|
||||
|
||||
@@ -23,6 +23,7 @@ function getLogFilePath() {
|
||||
|
||||
export interface DaemonStatus {
|
||||
connectionStatus: string;
|
||||
deviceId?: string;
|
||||
gatewayUrl: string;
|
||||
pid: number;
|
||||
startedAt: string;
|
||||
|
||||
+2
-100
@@ -1,101 +1,3 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { createProgram } from './program';
|
||||
|
||||
import { Command } from 'commander';
|
||||
|
||||
import { registerAgentCommand } from './commands/agent';
|
||||
import { registerAgentGroupCommand } from './commands/agent-group';
|
||||
import { registerBotCommand } from './commands/bot';
|
||||
import { registerBriefCommand } from './commands/brief';
|
||||
import { registerConfigCommand } from './commands/config';
|
||||
import { registerConnectCommand } from './commands/connect';
|
||||
import { registerCronCommand } from './commands/cron';
|
||||
import { registerDeviceCommand } from './commands/device';
|
||||
import { registerDocCommand } from './commands/doc';
|
||||
import { registerEvalCommand } from './commands/eval';
|
||||
import { registerFileCommand } from './commands/file';
|
||||
import { registerGenerateCommand } from './commands/generate';
|
||||
import { registerKbCommand } from './commands/kb';
|
||||
import { registerLoginCommand } from './commands/login';
|
||||
import { registerLogoutCommand } from './commands/logout';
|
||||
import { registerMemoryCommand } from './commands/memory';
|
||||
import { registerMessageCommand } from './commands/message';
|
||||
import { registerModelCommand } from './commands/model';
|
||||
import { registerPluginCommand } from './commands/plugin';
|
||||
import { registerProviderCommand } from './commands/provider';
|
||||
import { registerSearchCommand } from './commands/search';
|
||||
import { registerSessionGroupCommand } from './commands/session-group';
|
||||
import { registerSkillCommand } from './commands/skill';
|
||||
import { registerStatusCommand } from './commands/status';
|
||||
import { registerTaskCommand } from './commands/task';
|
||||
import { registerThreadCommand } from './commands/thread';
|
||||
import { registerTopicCommand } from './commands/topic';
|
||||
import { registerUserCommand } from './commands/user';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version } = require('../package.json');
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name('lh')
|
||||
.description('LobeHub CLI - manage and connect to LobeHub services')
|
||||
.version(version);
|
||||
|
||||
registerLoginCommand(program);
|
||||
registerLogoutCommand(program);
|
||||
registerConnectCommand(program);
|
||||
registerDeviceCommand(program);
|
||||
registerStatusCommand(program);
|
||||
registerDocCommand(program);
|
||||
registerSearchCommand(program);
|
||||
registerKbCommand(program);
|
||||
registerMemoryCommand(program);
|
||||
registerAgentCommand(program);
|
||||
registerAgentGroupCommand(program);
|
||||
registerBotCommand(program);
|
||||
registerBriefCommand(program);
|
||||
registerCronCommand(program);
|
||||
registerGenerateCommand(program);
|
||||
registerFileCommand(program);
|
||||
registerSkillCommand(program);
|
||||
registerSessionGroupCommand(program);
|
||||
registerTaskCommand(program);
|
||||
registerThreadCommand(program);
|
||||
registerTopicCommand(program);
|
||||
registerMessageCommand(program);
|
||||
registerModelCommand(program);
|
||||
registerProviderCommand(program);
|
||||
registerPluginCommand(program);
|
||||
registerUserCommand(program);
|
||||
registerConfigCommand(program);
|
||||
registerEvalCommand(program);
|
||||
|
||||
// Global error handler for clean TRPC error output
|
||||
process.on('uncaughtException', (error: any) => {
|
||||
if (error?.name === 'TRPCClientError' || error?.constructor?.name?.includes('TRPCClientError')) {
|
||||
const message = error.message || 'Unknown error';
|
||||
const code = error.data?.code || error.shape?.data?.code || '';
|
||||
const path = error.data?.path || error.shape?.data?.path || '';
|
||||
console.error(`\x1B[31mError${path ? ` [${path}]` : ''}: ${message}\x1B[0m`);
|
||||
if (code) console.error(`\x1B[2mCode: ${code}\x1B[0m`);
|
||||
process.exit(1);
|
||||
}
|
||||
// Re-throw non-TRPC errors
|
||||
console.error(error?.message || error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (error: any) => {
|
||||
if (error?.name === 'TRPCClientError' || error?.constructor?.name?.includes('TRPCClientError')) {
|
||||
const message = error.message || 'Unknown error';
|
||||
const code = error.data?.code || error.shape?.data?.code || '';
|
||||
const path = error.data?.path || error.shape?.data?.path || '';
|
||||
console.error(`\x1B[31mError${path ? ` [${path}]` : ''}: ${message}\x1B[0m`);
|
||||
if (code) console.error(`\x1B[2mCode: ${code}\x1B[0m`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.error(error?.message || error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
program.parse();
|
||||
createProgram().parse();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { cliVersion, createProgram } from '../program';
|
||||
import { generateAliasManPage, generateRootManPage } from './roff';
|
||||
|
||||
const outputDir = fileURLToPath(new URL('../../man/man1/', import.meta.url));
|
||||
|
||||
await mkdir(outputDir, { recursive: true });
|
||||
|
||||
const program = createProgram();
|
||||
|
||||
await Promise.all([
|
||||
writeFile(`${outputDir}lh.1`, generateRootManPage(program, cliVersion)),
|
||||
writeFile(`${outputDir}lobe.1`, generateAliasManPage('lh')),
|
||||
writeFile(`${outputDir}lobehub.1`, generateAliasManPage('lh')),
|
||||
]);
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Command } from 'commander';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { generateAliasManPage, generateRootManPage } from './roff';
|
||||
|
||||
describe('roff manual generator', () => {
|
||||
it('renders a root man page from the command tree', () => {
|
||||
const program = new Command();
|
||||
|
||||
program.name('lh').description('Sample CLI').version('1.0.0');
|
||||
|
||||
program.command('generate').alias('gen').description('Generate content');
|
||||
program.command('login').description('Log in');
|
||||
|
||||
const output = generateRootManPage(program, '1.2.3');
|
||||
|
||||
expect(output).toContain('.TH LH 1 "" "@lobehub/cli 1.2.3" "User Commands"');
|
||||
expect(output).toContain('.SH COMMANDS');
|
||||
expect(output).toContain('.B generate');
|
||||
expect(output).toContain('Generate content Alias: gen.');
|
||||
expect(output).toContain('.B login');
|
||||
expect(output).toContain('.SH OPTIONS');
|
||||
});
|
||||
|
||||
it('renders alias man pages as so links', () => {
|
||||
expect(generateAliasManPage('lh')).toBe('.so man1/lh.1\n');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import type { Command } from 'commander';
|
||||
|
||||
const ROOT_ALIASES = ['lobe', 'lobehub'];
|
||||
const HELP_COMMAND_NAME = 'help';
|
||||
|
||||
interface RoffDefinition {
|
||||
description: string;
|
||||
term: string;
|
||||
}
|
||||
|
||||
const FILE_ENTRIES = [
|
||||
{
|
||||
description: 'Encrypted access and refresh tokens.',
|
||||
path: '~/.lobehub/credentials.json',
|
||||
},
|
||||
{
|
||||
description: 'CLI settings such as server and gateway URLs.',
|
||||
path: '~/.lobehub/settings.json',
|
||||
},
|
||||
{
|
||||
description: 'Background daemon PID file.',
|
||||
path: '~/.lobehub/daemon.pid',
|
||||
},
|
||||
{
|
||||
description: 'Background daemon status metadata.',
|
||||
path: '~/.lobehub/daemon.status',
|
||||
},
|
||||
{
|
||||
description: 'Background daemon log output.',
|
||||
path: '~/.lobehub/daemon.log',
|
||||
},
|
||||
] as const;
|
||||
|
||||
const EXAMPLES = [
|
||||
{
|
||||
command: 'lh login',
|
||||
description: 'Start interactive login in the browser.',
|
||||
},
|
||||
{
|
||||
command: 'lh connect --daemon',
|
||||
description: 'Start the device gateway connection in the background.',
|
||||
},
|
||||
{
|
||||
command: 'lh search -q "gpt-5"',
|
||||
description: 'Search local resources for a query.',
|
||||
},
|
||||
{
|
||||
command: 'lh generate text "Write release notes"',
|
||||
description: 'Generate text from a prompt.',
|
||||
},
|
||||
{
|
||||
command: 'lh man generate',
|
||||
description: 'Show the built-in manual for the generate command group.',
|
||||
},
|
||||
] as const;
|
||||
|
||||
export function generateRootManPage(program: Command, version: string) {
|
||||
const help = program.createHelp();
|
||||
const commands = getVisibleCommands(program).map((command) => ({
|
||||
description: formatCommandDescription(help.subcommandDescription(command), command.aliases()),
|
||||
term: command.name(),
|
||||
}));
|
||||
const options = help.visibleOptions(program).map((option) => ({
|
||||
description: help.optionDescription(option),
|
||||
term: help.optionTerm(option),
|
||||
}));
|
||||
|
||||
const lines = [
|
||||
'.\\" Code generated by `npm run man:generate`; DO NOT EDIT.',
|
||||
'.\\" Manual command details come from the Commander command tree.',
|
||||
`.TH LH 1 "" "${escapeRoff(`@lobehub/cli ${version}`)}" "User Commands"`,
|
||||
'.SH NAME',
|
||||
`lh \\- ${escapeRoff(program.description() || 'LobeHub CLI')}`,
|
||||
'.SH SYNOPSIS',
|
||||
...formatSynopsisLines(),
|
||||
'.SH DESCRIPTION',
|
||||
escapeRoff(
|
||||
`${program.name()} is the command-line interface for LobeHub. It provides authentication, device gateway connectivity, content generation, resource search, and management commands for agents, files, models, providers, plugins, knowledge bases, threads, topics, and related resources.`,
|
||||
),
|
||||
'.PP',
|
||||
'For command-specific manuals, use the built-in manual command:',
|
||||
'.PP',
|
||||
'.RS',
|
||||
'.B lh man',
|
||||
'[\\fICOMMAND\\fR]...',
|
||||
'.RE',
|
||||
'.SH COMMANDS',
|
||||
...formatDefinitionSection(commands, 'B'),
|
||||
'.SH OPTIONS',
|
||||
...formatDefinitionSection(options, 'B'),
|
||||
'.SH FILES',
|
||||
...FILE_ENTRIES.flatMap((entry) => [
|
||||
'.TP',
|
||||
`.I ${escapeRoff(entry.path)}`,
|
||||
escapeRoff(entry.description),
|
||||
]),
|
||||
'.PP',
|
||||
'The base directory can be overridden with the',
|
||||
'.B LOBEHUB_CLI_HOME',
|
||||
'environment variable.',
|
||||
'.SH EXAMPLES',
|
||||
...EXAMPLES.flatMap((example) => [
|
||||
'.TP',
|
||||
`.B ${escapeRoff(example.command)}`,
|
||||
escapeRoff(example.description),
|
||||
]),
|
||||
'.SH SEE ALSO',
|
||||
'.BR lobe (1),',
|
||||
'.BR lobehub (1)',
|
||||
];
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export function generateAliasManPage(target: string) {
|
||||
return `.so man1/${target}.1\n`;
|
||||
}
|
||||
|
||||
function formatSynopsisLines() {
|
||||
return ['lh', ...ROOT_ALIASES]
|
||||
.flatMap((binary) => [`.B ${binary}`, '[\\fIOPTION\\fR]...', '[\\fICOMMAND\\fR]', '.br'])
|
||||
.slice(0, -1);
|
||||
}
|
||||
|
||||
function getVisibleCommands(command: Command) {
|
||||
return command
|
||||
.createHelp()
|
||||
.visibleCommands(command)
|
||||
.filter((subcommand) => subcommand.name() !== HELP_COMMAND_NAME);
|
||||
}
|
||||
|
||||
function formatCommandDescription(description: string, aliases: string[]) {
|
||||
if (aliases.length === 0) return description;
|
||||
|
||||
return `${description} Alias: ${aliases.join(', ')}.`;
|
||||
}
|
||||
|
||||
function formatDefinitionSection(items: RoffDefinition[], macro: 'B' | 'I') {
|
||||
return items.flatMap((item) => [
|
||||
'.TP',
|
||||
`.${macro} ${escapeRoff(item.term)}`,
|
||||
escapeRoff(item.description),
|
||||
]);
|
||||
}
|
||||
|
||||
function escapeRoff(value: string) {
|
||||
return value.replaceAll('\\', '\\\\').replaceAll('-', '\\-');
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
import { Command } from 'commander';
|
||||
|
||||
import { registerAgentCommand } from './commands/agent';
|
||||
import { registerAgentGroupCommand } from './commands/agent-group';
|
||||
import { registerBotCommand } from './commands/bot';
|
||||
import { registerCompletionCommand } from './commands/completion';
|
||||
import { registerConfigCommand } from './commands/config';
|
||||
import { registerConnectCommand } from './commands/connect';
|
||||
import { registerCronCommand } from './commands/cron';
|
||||
import { registerDeviceCommand } from './commands/device';
|
||||
import { registerDocCommand } from './commands/doc';
|
||||
import { registerEvalCommand } from './commands/eval';
|
||||
import { registerFileCommand } from './commands/file';
|
||||
import { registerGenerateCommand } from './commands/generate';
|
||||
import { registerKbCommand } from './commands/kb';
|
||||
import { registerLoginCommand } from './commands/login';
|
||||
import { registerLogoutCommand } from './commands/logout';
|
||||
import { registerManCommand } from './commands/man';
|
||||
import { registerMemoryCommand } from './commands/memory';
|
||||
import { registerMessageCommand } from './commands/message';
|
||||
import { registerMigrateCommand } from './commands/migrate';
|
||||
import { registerModelCommand } from './commands/model';
|
||||
import { registerPluginCommand } from './commands/plugin';
|
||||
import { registerProviderCommand } from './commands/provider';
|
||||
import { registerSearchCommand } from './commands/search';
|
||||
import { registerSessionGroupCommand } from './commands/session-group';
|
||||
import { registerSkillCommand } from './commands/skill';
|
||||
import { registerStatusCommand } from './commands/status';
|
||||
import { registerTaskCommand } from './commands/task';
|
||||
import { registerThreadCommand } from './commands/thread';
|
||||
import { registerTopicCommand } from './commands/topic';
|
||||
import { registerUserCommand } from './commands/user';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version } = require('../package.json');
|
||||
|
||||
export function createProgram() {
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name('lh')
|
||||
.description('LobeHub CLI - manage and connect to LobeHub services')
|
||||
.version(version);
|
||||
|
||||
registerLoginCommand(program);
|
||||
registerLogoutCommand(program);
|
||||
registerCompletionCommand(program);
|
||||
registerManCommand(program);
|
||||
registerConnectCommand(program);
|
||||
registerDeviceCommand(program);
|
||||
registerStatusCommand(program);
|
||||
registerDocCommand(program);
|
||||
registerSearchCommand(program);
|
||||
registerKbCommand(program);
|
||||
registerMemoryCommand(program);
|
||||
registerAgentCommand(program);
|
||||
registerAgentGroupCommand(program);
|
||||
registerBotCommand(program);
|
||||
registerCronCommand(program);
|
||||
registerGenerateCommand(program);
|
||||
registerFileCommand(program);
|
||||
registerSkillCommand(program);
|
||||
registerSessionGroupCommand(program);
|
||||
registerTaskCommand(program);
|
||||
registerThreadCommand(program);
|
||||
registerTopicCommand(program);
|
||||
registerMessageCommand(program);
|
||||
registerModelCommand(program);
|
||||
registerProviderCommand(program);
|
||||
registerPluginCommand(program);
|
||||
registerUserCommand(program);
|
||||
registerConfigCommand(program);
|
||||
registerEvalCommand(program);
|
||||
registerMigrateCommand(program);
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
export { version as cliVersion };
|
||||
@@ -5,18 +5,19 @@ import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { log } from '../utils/logger';
|
||||
import { loadSettings, saveSettings } from './index';
|
||||
import { loadSettings, normalizeUrl, resolveServerUrl, saveSettings } from './index';
|
||||
|
||||
const tmpDir = path.join(os.tmpdir(), 'lobehub-cli-test-settings');
|
||||
const settingsDir = path.join(tmpDir, '.lobehub');
|
||||
const settingsFile = path.join(settingsDir, 'settings.json');
|
||||
const originalServer = process.env.LOBEHUB_SERVER;
|
||||
|
||||
vi.mock('node:os', async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, any>>();
|
||||
return {
|
||||
...actual,
|
||||
default: {
|
||||
...actual['default'],
|
||||
...actual.default,
|
||||
homedir: () => path.join(os.tmpdir(), 'lobehub-cli-test-settings'),
|
||||
},
|
||||
};
|
||||
@@ -31,10 +32,12 @@ vi.mock('../utils/logger', () => ({
|
||||
describe('settings', () => {
|
||||
beforeEach(() => {
|
||||
fs.mkdirSync(tmpDir, { recursive: true });
|
||||
delete process.env.LOBEHUB_SERVER;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { force: true, recursive: true });
|
||||
process.env.LOBEHUB_SERVER = originalServer;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -64,4 +67,28 @@ describe('settings', () => {
|
||||
expect(loadSettings()).toBeNull();
|
||||
expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('Please delete this file'));
|
||||
});
|
||||
|
||||
it('should normalize trailing slashes', () => {
|
||||
expect(normalizeUrl('https://self-hosted.example.com/')).toBe(
|
||||
'https://self-hosted.example.com',
|
||||
);
|
||||
expect(normalizeUrl(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should prefer LOBEHUB_SERVER over settings', () => {
|
||||
saveSettings({ serverUrl: 'https://settings.example.com/' });
|
||||
process.env.LOBEHUB_SERVER = 'https://env.example.com/';
|
||||
|
||||
expect(resolveServerUrl()).toBe('https://env.example.com');
|
||||
});
|
||||
|
||||
it('should fall back to settings then official server', () => {
|
||||
saveSettings({ serverUrl: 'https://settings.example.com/' });
|
||||
|
||||
expect(resolveServerUrl()).toBe('https://settings.example.com');
|
||||
|
||||
fs.unlinkSync(settingsFile);
|
||||
|
||||
expect(resolveServerUrl()).toBe('https://app.lobehub.com');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,10 +2,11 @@ import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { OFFICIAL_SERVER_URL } from '../constants/urls';
|
||||
import { OFFICIAL_AGENT_GATEWAY_URL, OFFICIAL_SERVER_URL } from '../constants/urls';
|
||||
import { log } from '../utils/logger';
|
||||
|
||||
export interface StoredSettings {
|
||||
agentGatewayUrl?: string;
|
||||
gatewayUrl?: string;
|
||||
serverUrl?: string;
|
||||
}
|
||||
@@ -14,19 +15,35 @@ 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 {
|
||||
export function normalizeUrl(url: string | undefined): string | undefined {
|
||||
return url ? url.replace(/\/$/, '') : undefined;
|
||||
}
|
||||
|
||||
export function resolveServerUrl(): string {
|
||||
const envServerUrl = normalizeUrl(process.env.LOBEHUB_SERVER);
|
||||
const settingsServerUrl = normalizeUrl(loadSettings()?.serverUrl);
|
||||
|
||||
return envServerUrl || settingsServerUrl || OFFICIAL_SERVER_URL;
|
||||
}
|
||||
|
||||
export function resolveAgentGatewayUrl(): string | undefined {
|
||||
const envUrl = normalizeUrl(process.env.AGENT_GATEWAY_URL);
|
||||
const settingsUrl = normalizeUrl(loadSettings()?.agentGatewayUrl);
|
||||
|
||||
return envUrl || settingsUrl || OFFICIAL_AGENT_GATEWAY_URL;
|
||||
}
|
||||
|
||||
export function saveSettings(settings: StoredSettings): void {
|
||||
const serverUrl = normalizeUrl(settings.serverUrl);
|
||||
const agentGatewayUrl = normalizeUrl(settings.agentGatewayUrl);
|
||||
const gatewayUrl = normalizeUrl(settings.gatewayUrl);
|
||||
const serverUrl = normalizeUrl(settings.serverUrl);
|
||||
const normalized: StoredSettings = {
|
||||
agentGatewayUrl: agentGatewayUrl === OFFICIAL_AGENT_GATEWAY_URL ? undefined : agentGatewayUrl,
|
||||
gatewayUrl,
|
||||
serverUrl: serverUrl === OFFICIAL_SERVER_URL ? undefined : serverUrl,
|
||||
};
|
||||
|
||||
if (!normalized.serverUrl && !normalized.gatewayUrl) {
|
||||
if (!normalized.serverUrl && !normalized.gatewayUrl && !normalized.agentGatewayUrl) {
|
||||
try {
|
||||
fs.unlinkSync(SETTINGS_FILE);
|
||||
} catch {}
|
||||
@@ -43,14 +60,16 @@ export function loadSettings(): StoredSettings | null {
|
||||
try {
|
||||
const data = fs.readFileSync(SETTINGS_FILE, 'utf8');
|
||||
const parsed = JSON.parse(data) as StoredSettings;
|
||||
const agentGatewayUrl = normalizeUrl(parsed.agentGatewayUrl);
|
||||
const gatewayUrl = normalizeUrl(parsed.gatewayUrl);
|
||||
const serverUrl = normalizeUrl(parsed.serverUrl);
|
||||
const normalized: StoredSettings = {
|
||||
agentGatewayUrl: agentGatewayUrl === OFFICIAL_AGENT_GATEWAY_URL ? undefined : agentGatewayUrl,
|
||||
gatewayUrl,
|
||||
serverUrl: serverUrl === OFFICIAL_SERVER_URL ? undefined : serverUrl,
|
||||
};
|
||||
|
||||
if (!normalized.serverUrl && !normalized.gatewayUrl) return null;
|
||||
if (!normalized.serverUrl && !normalized.gatewayUrl && !normalized.agentGatewayUrl) return null;
|
||||
|
||||
return normalized;
|
||||
} catch {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { streamAgentEvents } from './agentStream';
|
||||
import { streamAgentEvents, streamAgentEventsViaWebSocket } from './agentStream';
|
||||
|
||||
vi.mock('./logger', () => ({
|
||||
log: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
heartbeat: vi.fn(),
|
||||
info: vi.fn(),
|
||||
@@ -193,3 +194,391 @@ describe('streamAgentEvents', () => {
|
||||
exitSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
// ── WebSocket stream tests ──────────────────────────────
|
||||
|
||||
let capturedWs: MockWebSocket | undefined;
|
||||
|
||||
class MockWebSocket {
|
||||
static OPEN = 1;
|
||||
static CONNECTING = 0;
|
||||
static CLOSED = 3;
|
||||
|
||||
readyState = MockWebSocket.CONNECTING;
|
||||
onopen: ((ev: any) => void) | null = null;
|
||||
onmessage: ((ev: any) => void) | null = null;
|
||||
onerror: ((ev: any) => void) | null = null;
|
||||
onclose: ((ev: any) => void) | null = null;
|
||||
|
||||
sent: string[] = [];
|
||||
private autoAuthSuccess = true;
|
||||
|
||||
constructor(
|
||||
public url: string,
|
||||
autoAuth = true,
|
||||
) {
|
||||
this.autoAuthSuccess = autoAuth;
|
||||
capturedWs = this; // eslint-disable-line @typescript-eslint/no-this-alias
|
||||
// Trigger onopen on next microtask (after handlers are assigned)
|
||||
queueMicrotask(() => {
|
||||
this.readyState = MockWebSocket.OPEN;
|
||||
this.onopen?.({ type: 'open' });
|
||||
});
|
||||
}
|
||||
|
||||
send(data: string) {
|
||||
this.sent.push(data);
|
||||
const msg = JSON.parse(data);
|
||||
|
||||
if (msg.type === 'auth' && this.autoAuthSuccess) {
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({ data: JSON.stringify({ type: 'auth_success' }) });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
this.readyState = MockWebSocket.CLOSED;
|
||||
// Async like real WebSocket — fires after current microtask
|
||||
queueMicrotask(() => this.onclose?.({ code: 1000, reason: '' }));
|
||||
}
|
||||
|
||||
simulateMessage(msg: Record<string, unknown>) {
|
||||
this.onmessage?.({ data: JSON.stringify(msg) });
|
||||
}
|
||||
}
|
||||
|
||||
describe('streamAgentEventsViaWebSocket', () => {
|
||||
let stdoutSpy: ReturnType<typeof vi.spyOn>;
|
||||
let consoleSpy: ReturnType<typeof vi.spyOn>;
|
||||
const originalWebSocket = globalThis.WebSocket;
|
||||
|
||||
beforeEach(() => {
|
||||
capturedWs = undefined;
|
||||
stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
|
||||
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
(globalThis as any).WebSocket = MockWebSocket;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
stdoutSpy.mockRestore();
|
||||
consoleSpy.mockRestore();
|
||||
globalThis.WebSocket = originalWebSocket;
|
||||
});
|
||||
|
||||
/** Wait for microtasks + short delay so WS open/auth cycle completes */
|
||||
const flush = () => new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
it('should connect, authenticate, and send resume', async () => {
|
||||
const promise = streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://gw.test.com',
|
||||
operationId: 'op-1',
|
||||
token: 'test-token',
|
||||
});
|
||||
|
||||
await flush();
|
||||
|
||||
const ws = capturedWs!;
|
||||
expect(ws.sent.map((s) => JSON.parse(s))).toEqual([
|
||||
{ token: 'test-token', type: 'auth' },
|
||||
{ lastEventId: '', type: 'resume' },
|
||||
]);
|
||||
|
||||
ws.simulateMessage({ id: '1', type: 'session_complete' });
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('should render agent_event messages using existing renderEvent', async () => {
|
||||
const promise = streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://gw.test.com',
|
||||
operationId: 'op-1',
|
||||
token: 'test-token',
|
||||
});
|
||||
|
||||
await flush();
|
||||
const ws = capturedWs!;
|
||||
|
||||
ws.simulateMessage({
|
||||
event: { data: null, operationId: 'op-1', stepIndex: 0, timestamp: 1, type: 'step_start' },
|
||||
id: '1',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { chunkType: 'text', content: 'Hello WS!' },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 2,
|
||||
type: 'stream_chunk',
|
||||
},
|
||||
id: '2',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { stepCount: 1 },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 3,
|
||||
type: 'agent_runtime_end',
|
||||
},
|
||||
id: '3',
|
||||
type: 'agent_event',
|
||||
});
|
||||
|
||||
await promise;
|
||||
expect(stdoutSpy).toHaveBeenCalledWith('Hello WS!');
|
||||
});
|
||||
|
||||
it('should output JSON when json option is set', async () => {
|
||||
const promise = streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://gw.test.com',
|
||||
json: true,
|
||||
operationId: 'op-1',
|
||||
token: 'test-token',
|
||||
});
|
||||
|
||||
await flush();
|
||||
const ws = capturedWs!;
|
||||
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: null,
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 1,
|
||||
type: 'agent_runtime_init',
|
||||
},
|
||||
id: '1',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { stepCount: 1 },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 2,
|
||||
type: 'agent_runtime_end',
|
||||
},
|
||||
id: '2',
|
||||
type: 'agent_event',
|
||||
});
|
||||
|
||||
await promise;
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"agent_runtime_init"'));
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"agent_runtime_end"'));
|
||||
});
|
||||
|
||||
it('should reject on auth failure', async () => {
|
||||
// Override mock to return auth_failed instead of auth_success
|
||||
(globalThis as any).WebSocket = class extends MockWebSocket {
|
||||
constructor(url: string) {
|
||||
super(url, false); // disable auto auth_success
|
||||
capturedWs = this; // eslint-disable-line @typescript-eslint/no-this-alias
|
||||
}
|
||||
|
||||
override send(data: string) {
|
||||
this.sent.push(data);
|
||||
const msg = JSON.parse(data);
|
||||
if (msg.type === 'auth') {
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({
|
||||
data: JSON.stringify({ reason: 'invalid token', type: 'auth_failed' }),
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await expect(
|
||||
streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://gw.test.com',
|
||||
operationId: 'op-1',
|
||||
token: 'bad-token',
|
||||
}),
|
||||
).rejects.toThrow('Gateway auth failed');
|
||||
});
|
||||
|
||||
it('should resolve on session_complete', async () => {
|
||||
const promise = streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://gw.test.com',
|
||||
operationId: 'op-1',
|
||||
token: 'test-token',
|
||||
});
|
||||
|
||||
await flush();
|
||||
capturedWs!.simulateMessage({ id: '1', summary: 'All done', type: 'session_complete' });
|
||||
|
||||
await expect(promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('should ignore heartbeat_ack messages', async () => {
|
||||
const promise = streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://gw.test.com',
|
||||
operationId: 'op-1',
|
||||
token: 'test-token',
|
||||
});
|
||||
|
||||
await flush();
|
||||
const ws = capturedWs!;
|
||||
|
||||
ws.simulateMessage({ type: 'heartbeat_ack' });
|
||||
expect(stdoutSpy).not.toHaveBeenCalled();
|
||||
|
||||
ws.simulateMessage({ id: '1', type: 'session_complete' });
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('should construct correct WebSocket URL from HTTPS gateway URL', async () => {
|
||||
const promise = streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://agent-gateway.lobehub.com',
|
||||
operationId: 'op-123',
|
||||
token: 'tok',
|
||||
});
|
||||
|
||||
await flush();
|
||||
expect(capturedWs!.url).toBe('wss://agent-gateway.lobehub.com/ws?operationId=op-123');
|
||||
|
||||
capturedWs!.simulateMessage({ id: '1', type: 'session_complete' });
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('should render a multi-step agent run with tool calls', async () => {
|
||||
const promise = streamAgentEventsViaWebSocket({
|
||||
gatewayUrl: 'https://gw.test.com',
|
||||
operationId: 'op-1',
|
||||
token: 'tok',
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
await flush();
|
||||
const ws = capturedWs!;
|
||||
const { log } = await import('./logger');
|
||||
|
||||
// Step 1: thinking + text + tool call
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: null,
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 1,
|
||||
type: 'agent_runtime_init',
|
||||
},
|
||||
id: '1',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: { data: null, operationId: 'op-1', stepIndex: 0, timestamp: 2, type: 'step_start' },
|
||||
id: '2',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { chunkType: 'reasoning', reasoning: 'Let me search...' },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 3,
|
||||
type: 'stream_chunk',
|
||||
},
|
||||
id: '3',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { chunkType: 'text', content: 'Searching for news.' },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 4,
|
||||
type: 'stream_chunk',
|
||||
},
|
||||
id: '4',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { toolCalling: { apiName: 'search', id: 'tc-1' } },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 5,
|
||||
type: 'tool_start',
|
||||
},
|
||||
id: '5',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: { data: null, operationId: 'op-1', stepIndex: 0, timestamp: 6, type: 'stream_end' },
|
||||
id: '6',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { stepIndex: 0 },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 0,
|
||||
timestamp: 7,
|
||||
type: 'step_complete',
|
||||
},
|
||||
id: '7',
|
||||
type: 'agent_event',
|
||||
});
|
||||
|
||||
// Step 2: tool result + final text
|
||||
ws.simulateMessage({
|
||||
event: { data: null, operationId: 'op-1', stepIndex: 1, timestamp: 8, type: 'step_start' },
|
||||
id: '8',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: {
|
||||
isSuccess: true,
|
||||
payload: { toolCalling: { id: 'tc-1' } },
|
||||
result: { content: 'Results...' },
|
||||
},
|
||||
operationId: 'op-1',
|
||||
stepIndex: 1,
|
||||
timestamp: 9,
|
||||
type: 'tool_end',
|
||||
},
|
||||
id: '9',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { chunkType: 'text', content: 'Here are the results.' },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 1,
|
||||
timestamp: 10,
|
||||
type: 'stream_chunk',
|
||||
},
|
||||
id: '10',
|
||||
type: 'agent_event',
|
||||
});
|
||||
ws.simulateMessage({
|
||||
event: {
|
||||
data: { cost: { total: 0.05 }, stepCount: 2, usage: { total_tokens: 500 } },
|
||||
operationId: 'op-1',
|
||||
stepIndex: 1,
|
||||
timestamp: 11,
|
||||
type: 'agent_runtime_end',
|
||||
},
|
||||
id: '11',
|
||||
type: 'agent_event',
|
||||
});
|
||||
|
||||
await promise;
|
||||
|
||||
// Verify reasoning was rendered (dim)
|
||||
expect(stdoutSpy).toHaveBeenCalledWith(expect.stringContaining('Let me search...'));
|
||||
// Verify text chunks
|
||||
expect(stdoutSpy).toHaveBeenCalledWith('Searching for news.');
|
||||
expect(stdoutSpy).toHaveBeenCalledWith('Here are the results.');
|
||||
// Verify tool call was logged
|
||||
expect(log.toolCall).toHaveBeenCalledWith('search', 'tc-1', undefined);
|
||||
// Verify tool result was logged
|
||||
expect(log.toolResult).toHaveBeenCalled();
|
||||
// Verify finish line
|
||||
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Agent finished'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import pc from 'picocolors';
|
||||
import urlJoin from 'url-join';
|
||||
|
||||
import { log } from './logger';
|
||||
|
||||
@@ -16,6 +17,12 @@ interface StreamOptions {
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
interface WebSocketStreamOptions extends StreamOptions {
|
||||
gatewayUrl: string;
|
||||
operationId: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the agent SSE stream and render events to the terminal.
|
||||
* Resolves when the stream ends (agent_runtime_end or connection close).
|
||||
@@ -152,6 +159,126 @@ export function replayAgentEvents(events: AgentStreamEvent[], options: StreamOpt
|
||||
}
|
||||
}
|
||||
|
||||
const HEARTBEAT_INTERVAL = 30_000;
|
||||
|
||||
/**
|
||||
* Connect to the Agent Gateway via WebSocket and render events to the terminal.
|
||||
* Resolves when the session completes or the connection closes.
|
||||
*/
|
||||
export async function streamAgentEventsViaWebSocket(
|
||||
options: WebSocketStreamOptions,
|
||||
): Promise<void> {
|
||||
const { gatewayUrl, operationId, token, ...streamOpts } = options;
|
||||
const wsUrl = urlJoin(
|
||||
gatewayUrl.replace(/^http/, 'ws'),
|
||||
`/ws?operationId=${encodeURIComponent(operationId)}`,
|
||||
);
|
||||
|
||||
log.debug(`Connecting to gateway: ${wsUrl}`);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
const jsonEvents: AgentStreamEvent[] = [];
|
||||
const ctx = createRenderContext();
|
||||
let lastEventId = '';
|
||||
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let jsonPrinted = false;
|
||||
|
||||
const cleanup = () => {
|
||||
if (heartbeatTimer) clearInterval(heartbeatTimer);
|
||||
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
|
||||
ws.close();
|
||||
}
|
||||
};
|
||||
|
||||
ws.onopen = () => {
|
||||
ws.send(JSON.stringify({ token, type: 'auth' }));
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const msg = JSON.parse(event.data as string);
|
||||
|
||||
if (msg.type === 'auth_success') {
|
||||
log.debug('Gateway authenticated');
|
||||
// Request all buffered events (covers events pushed before WS connected)
|
||||
ws.send(JSON.stringify({ lastEventId: '', type: 'resume' }));
|
||||
heartbeatTimer = setInterval(() => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'heartbeat' }));
|
||||
}
|
||||
}, HEARTBEAT_INTERVAL);
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'auth_failed') {
|
||||
cleanup();
|
||||
reject(new Error(`Gateway auth failed: ${msg.reason}`));
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'heartbeat_ack') return;
|
||||
|
||||
if (msg.type === 'agent_event') {
|
||||
const agentEvent: AgentStreamEvent = msg.event;
|
||||
if (msg.id) lastEventId = msg.id;
|
||||
|
||||
if (streamOpts.json) {
|
||||
jsonEvents.push(agentEvent);
|
||||
} else {
|
||||
renderEvent(agentEvent, ctx, streamOpts);
|
||||
}
|
||||
|
||||
if (agentEvent.type === 'agent_runtime_end') {
|
||||
if (streamOpts.json && !jsonPrinted) {
|
||||
jsonPrinted = true;
|
||||
console.log(JSON.stringify(jsonEvents, null, 2));
|
||||
} else if (!streamOpts.json) {
|
||||
renderEnd(agentEvent);
|
||||
}
|
||||
cleanup();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
if (agentEvent.type === 'error') {
|
||||
if (streamOpts.json && !jsonPrinted) {
|
||||
jsonPrinted = true;
|
||||
console.log(JSON.stringify(jsonEvents, null, 2));
|
||||
}
|
||||
log.error(
|
||||
`Agent error: ${agentEvent.data?.message || agentEvent.data?.error || 'Unknown error'}`,
|
||||
);
|
||||
cleanup();
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.type === 'session_complete') {
|
||||
if (streamOpts.json && jsonEvents.length > 0 && !jsonPrinted) {
|
||||
jsonPrinted = true;
|
||||
console.log(JSON.stringify(jsonEvents, null, 2));
|
||||
}
|
||||
cleanup();
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = (err) => {
|
||||
cleanup();
|
||||
reject(err);
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
if (heartbeatTimer) clearInterval(heartbeatTimer);
|
||||
if (streamOpts.json && jsonEvents.length > 0 && !jsonPrinted) {
|
||||
jsonPrinted = true;
|
||||
console.log(JSON.stringify(jsonEvents, null, 2));
|
||||
}
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ── Render helpers ──────────────────────────────────────
|
||||
|
||||
interface RenderContext {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { Command, Option } from 'commander';
|
||||
import { InvalidArgumentError } from 'commander';
|
||||
|
||||
const CLI_BIN_NAMES = ['lh', 'lobe', 'lobehub'] as const;
|
||||
const SUPPORTED_SHELLS = ['bash', 'zsh'] as const;
|
||||
|
||||
type SupportedShell = (typeof SUPPORTED_SHELLS)[number];
|
||||
|
||||
interface HiddenCommand extends Command {
|
||||
_hidden?: boolean;
|
||||
}
|
||||
|
||||
interface HiddenOption extends Option {
|
||||
hidden: boolean;
|
||||
}
|
||||
|
||||
function isVisibleCommand(command: Command) {
|
||||
return !(command as HiddenCommand)._hidden;
|
||||
}
|
||||
|
||||
function isVisibleOption(option: Option) {
|
||||
return !(option as HiddenOption).hidden;
|
||||
}
|
||||
|
||||
function listCommandTokens(command: Command) {
|
||||
return [command.name(), ...command.aliases()].filter(Boolean);
|
||||
}
|
||||
|
||||
function listOptionTokens(command: Command) {
|
||||
return command.options
|
||||
.filter(isVisibleOption)
|
||||
.flatMap((option) => [option.short, option.long].filter(Boolean) as string[]);
|
||||
}
|
||||
|
||||
function findSubcommand(command: Command, token: string) {
|
||||
return command.commands.find(
|
||||
(subcommand) => isVisibleCommand(subcommand) && listCommandTokens(subcommand).includes(token),
|
||||
);
|
||||
}
|
||||
|
||||
function findOption(command: Command, token: string) {
|
||||
return command.options.find(
|
||||
(option) =>
|
||||
isVisibleOption(option) && (option.short === token || option.long === token || false),
|
||||
);
|
||||
}
|
||||
|
||||
function filterCandidates(candidates: string[], currentWord: string) {
|
||||
const unique = [...new Set(candidates)];
|
||||
|
||||
if (!currentWord) return unique.sort();
|
||||
|
||||
return unique.filter((candidate) => candidate.startsWith(currentWord)).sort();
|
||||
}
|
||||
|
||||
function resolveCommandContext(program: Command, completedWords: string[]) {
|
||||
let command = program;
|
||||
let expectsOptionValue = false;
|
||||
|
||||
for (const token of completedWords) {
|
||||
if (expectsOptionValue) {
|
||||
expectsOptionValue = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!token) continue;
|
||||
|
||||
if (token.startsWith('-')) {
|
||||
const option = findOption(command, token);
|
||||
|
||||
expectsOptionValue = Boolean(
|
||||
option && (option.required || option.optional || option.variadic),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const subcommand = findSubcommand(command, token);
|
||||
if (subcommand) {
|
||||
command = subcommand;
|
||||
}
|
||||
}
|
||||
|
||||
return { command, expectsOptionValue };
|
||||
}
|
||||
|
||||
export function getCompletionCandidates(
|
||||
program: Command,
|
||||
words: string[],
|
||||
currentWordIndex = words.length,
|
||||
) {
|
||||
const safeCurrentWordIndex = Math.min(Math.max(currentWordIndex, 0), words.length);
|
||||
const completedWords = words.slice(0, safeCurrentWordIndex);
|
||||
const currentWord = safeCurrentWordIndex < words.length ? words[safeCurrentWordIndex] || '' : '';
|
||||
const { command, expectsOptionValue } = resolveCommandContext(program, completedWords);
|
||||
|
||||
if (expectsOptionValue) return [];
|
||||
|
||||
const commandCandidates = currentWord.startsWith('-')
|
||||
? []
|
||||
: command.commands
|
||||
.filter(isVisibleCommand)
|
||||
.flatMap((subcommand) => listCommandTokens(subcommand));
|
||||
|
||||
if (commandCandidates.length > 0) {
|
||||
return filterCandidates(commandCandidates, currentWord);
|
||||
}
|
||||
|
||||
return filterCandidates(listOptionTokens(command), currentWord);
|
||||
}
|
||||
|
||||
export function parseCompletionWordIndex(rawValue: string | undefined, words: string[]) {
|
||||
const parsedValue = rawValue ? Number.parseInt(rawValue, 10) : Number.NaN;
|
||||
|
||||
if (Number.isNaN(parsedValue)) return words.length;
|
||||
|
||||
return Math.min(Math.max(parsedValue, 0), words.length);
|
||||
}
|
||||
|
||||
export function resolveCompletionShell(shell?: string): SupportedShell {
|
||||
const fallbackShell = process.env.SHELL?.split('/').pop() || 'zsh';
|
||||
const resolvedShell = (shell || fallbackShell).toLowerCase();
|
||||
|
||||
if ((SUPPORTED_SHELLS as readonly string[]).includes(resolvedShell)) {
|
||||
return resolvedShell as SupportedShell;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentError(
|
||||
`Unsupported shell "${resolvedShell}". Supported shells: ${SUPPORTED_SHELLS.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function renderCompletionScript(shell: SupportedShell) {
|
||||
if (shell === 'bash') {
|
||||
return [
|
||||
'# shellcheck shell=bash',
|
||||
'_lobehub_completion() {',
|
||||
" local IFS=$'\\n'",
|
||||
' local current_index=$((COMP_CWORD - 1))',
|
||||
' local completions',
|
||||
' completions=$(LOBEHUB_COMP_CWORD="$current_index" "${COMP_WORDS[0]}" __complete "${COMP_WORDS[@]:1}")',
|
||||
' COMPREPLY=($(printf \'%s\\n\' "$completions"))',
|
||||
'}',
|
||||
`complete -o nosort -F _lobehub_completion ${CLI_BIN_NAMES.join(' ')}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
return [
|
||||
`#compdef ${CLI_BIN_NAMES.join(' ')}`,
|
||||
'_lobehub_completion() {',
|
||||
' local -a completions',
|
||||
' local current_index=$((CURRENT - 2))',
|
||||
' completions=("${(@f)$(LOBEHUB_COMP_CWORD="$current_index" "$words[1]" __complete "${(@)words[@]:1}")}")',
|
||||
" _describe 'values' completions",
|
||||
'}',
|
||||
`compdef _lobehub_completion ${CLI_BIN_NAMES.join(' ')}`,
|
||||
].join('\n');
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { readStatus } from '../daemon/manager';
|
||||
|
||||
export function resolveLocalDeviceId(): string | undefined {
|
||||
return readStatus()?.deviceId;
|
||||
}
|
||||
@@ -387,6 +387,102 @@ export function printCalendarHeatmap(
|
||||
console.log();
|
||||
}
|
||||
|
||||
// ── Kanban Board ─────────────────────────────────────
|
||||
|
||||
export interface KanbanColumn {
|
||||
color?: (s: string) => string;
|
||||
items: KanbanCard[];
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface KanbanCard {
|
||||
badge?: string;
|
||||
meta?: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a kanban board with side-by-side columns.
|
||||
* Adapts column width to terminal width automatically.
|
||||
*/
|
||||
export function printKanban(columns: KanbanColumn[]) {
|
||||
// Filter out empty columns
|
||||
const cols = columns.filter((c) => c.items.length > 0);
|
||||
if (cols.length === 0) return;
|
||||
|
||||
const termWidth = process.stdout.columns || 100;
|
||||
// Each column gets equal width, with 1-char gap between
|
||||
const colWidth = Math.max(20, Math.floor((termWidth - (cols.length - 1)) / cols.length));
|
||||
const innerWidth = colWidth - 4; // 2 chars border + 2 padding
|
||||
|
||||
const maxRows = Math.max(...cols.map((c) => c.items.length));
|
||||
|
||||
// ── Header ──
|
||||
const topBorder = cols
|
||||
.map((c) => {
|
||||
const titleStr = ` ${c.title} (${c.items.length}) `;
|
||||
const color = c.color || pc.white;
|
||||
const remaining = colWidth - 2 - displayWidth(titleStr);
|
||||
const left = Math.floor(remaining / 2);
|
||||
const right = remaining - left;
|
||||
return color(
|
||||
'┌' + '─'.repeat(Math.max(0, left)) + titleStr + '─'.repeat(Math.max(0, right)) + '┐',
|
||||
);
|
||||
})
|
||||
.join(' ');
|
||||
console.log(topBorder);
|
||||
|
||||
// ── Rows ──
|
||||
for (let row = 0; row < maxRows; row++) {
|
||||
const line = cols
|
||||
.map((c) => {
|
||||
const color = c.color || pc.white;
|
||||
const item = c.items[row];
|
||||
if (!item) {
|
||||
return color('│') + ' '.repeat(colWidth - 2) + color('│');
|
||||
}
|
||||
|
||||
const badge = item.badge ? item.badge + ' ' : '';
|
||||
const badgeWidth = displayWidth(badge);
|
||||
const titleMaxWidth = innerWidth - badgeWidth;
|
||||
const title = truncate(item.title, titleMaxWidth);
|
||||
const titleWidth = displayWidth(title);
|
||||
const pad = ' '.repeat(Math.max(0, colWidth - 2 - badgeWidth - titleWidth - 2));
|
||||
return color('│') + ' ' + badge + title + pad + ' ' + color('│');
|
||||
})
|
||||
.join(' ');
|
||||
console.log(line);
|
||||
|
||||
// Print meta line if any card in this row has meta
|
||||
const hasMeta = cols.some((c) => c.items[row]?.meta);
|
||||
if (hasMeta) {
|
||||
const metaLine = cols
|
||||
.map((c) => {
|
||||
const color = c.color || pc.white;
|
||||
const item = c.items[row];
|
||||
if (!item?.meta) {
|
||||
return color('│') + ' '.repeat(colWidth - 2) + color('│');
|
||||
}
|
||||
const meta = truncate(item.meta, innerWidth);
|
||||
const metaWidth = displayWidth(meta);
|
||||
const pad = ' '.repeat(Math.max(0, colWidth - 2 - metaWidth - 2));
|
||||
return color('│') + ' ' + pc.dim(meta) + pad + ' ' + color('│');
|
||||
})
|
||||
.join(' ');
|
||||
console.log(metaLine);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Bottom border ──
|
||||
const bottomBorder = cols
|
||||
.map((c) => {
|
||||
const color = c.color || pc.white;
|
||||
return color('└' + '─'.repeat(colWidth - 2) + '┘');
|
||||
})
|
||||
.join(' ');
|
||||
console.log(bottomBorder);
|
||||
}
|
||||
|
||||
export function confirm(message: string): Promise<boolean> {
|
||||
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
||||
return new Promise((resolve) => {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
banner: { js: '#!/usr/bin/env node' },
|
||||
clean: true,
|
||||
deps: {
|
||||
neverBundle: ['@napi-rs/canvas'],
|
||||
},
|
||||
entry: ['src/index.ts'],
|
||||
fixedExtension: false,
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'node18',
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import { defineConfig } from 'tsup';
|
||||
|
||||
export default defineConfig({
|
||||
banner: { js: '#!/usr/bin/env node' },
|
||||
clean: true,
|
||||
entry: ['src/index.ts'],
|
||||
external: ['@napi-rs/canvas', 'fast-glob', 'diff', 'debug'],
|
||||
format: ['esm'],
|
||||
noExternal: [
|
||||
'@lobechat/device-gateway-client',
|
||||
'@lobechat/local-file-shell',
|
||||
'@lobechat/file-loaders',
|
||||
'@trpc/client',
|
||||
'superjson',
|
||||
],
|
||||
platform: 'node',
|
||||
target: 'node18',
|
||||
});
|
||||
@@ -52,8 +52,9 @@ export default defineConfig({
|
||||
minify: !isDev,
|
||||
outDir: 'dist/main',
|
||||
rollupOptions: {
|
||||
// Native modules must be externalized to work correctly
|
||||
external: getExternalDependencies(),
|
||||
// Native modules must be externalized to work correctly.
|
||||
// bufferutil and utf-8-validate are optional peer deps of ws that may not be installed.
|
||||
external: [...getExternalDependencies(), 'bufferutil', 'utf-8-validate'],
|
||||
output: {
|
||||
// Prevent debug package from being bundled into index.js to avoid side-effect pollution
|
||||
manualChunks(id) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user