Compare commits

...

156 Commits

Author SHA1 Message Date
ONLY-yours 8e96924774 fix: merge canayr 2026-04-01 17:27:58 +08:00
Arvin Xu 60a59e89f6 🛠 chore(fetch-sse): preserve legacy body.message and body.name keys for compatibility (#13469)
Restores the original body.message / body.name fields that downstream error
handlers rely on. The previous PR renamed them to errorMessage / errorName
which broke existing error renderers.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 15:04:37 +08:00
Arvin Xu 7fd6d67fe3 🐛 fix(model-runtime): add toolConfig for Gemini 3+ combined tools (#13465)
* 🐛 fix(model-runtime): add toolConfig for Gemini 3+ combined tools

When Gemini 3+ models combine built-in tools (googleSearch/urlContext)
with functionDeclarations, the API requires
toolConfig.includeServerSideToolInvocations to be set to true.

Without this flag, requests return 400: "Please enable
tool_config.include_server_side_tool_invocations to use Built-in tools
with Function calling."

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  test(google): fix incomplete grounding metadata test

The test defined grounding response data but never used it as mock
input and had no assertions. Rewrote to properly feed grounding chunks
through the stream and verify the output contains grounding events
with citations and search queries.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix(test): use type assertion for grounding test data

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 15:03:23 +08:00
Arvin Xu 453db9f165 🔨 chore(fetch-sse): enrich error context with provider, model, and network diagnostics (#13468)
 feat(fetch-sse): enrich error context with provider, model, and network diagnostics

When a fetch error occurs (e.g. TypeError: Failed to fetch), the error body now
includes provider, model, apiMode, fetchOnClient, elapsedMs, networkStatus, and
traceId to help diagnose issues instead of only showing a useless minified stack.

Fixes LOBE-6594

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 14:58:14 +08:00
LiJian 19f90e3d9a ♻️ refactor: change the klavis github tools into lobehub skill & add vercel skills (#13442)
* refactor: change the klavis github tools into lobehub skill & add the vercel skill

* fix: slove the test & topicid parse
2026-04-01 14:48:16 +08:00
Arvin Xu fee0fe5699 🔨 chore: add disableTools option to execAgent (#13454)
*  feat: add disableTools option to execAgent for eval/benchmark scenarios

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: short-circuit tool discovery when disableTools is set

Move all tool-related fetches (plugin DB query, LobeHub/Klavis manifest
fetches, device list probing, model-bank import) inside the disableTools
guard so they are fully skipped in eval/benchmark runs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  test: add unit tests for disableTools short-circuit behavior

Verify that when disableTools=true, all expensive tool discovery
(plugin query, manifest fetches, ToolsEngine creation) is skipped.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: hoist variables referenced outside disableTools guard

Move lobehubSkillManifests, klavisManifests, agentPlugins, and
LOBE_DEFAULT_MODEL_LIST declarations outside the else block since
they are also used by agent management context and skill engine.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 14:28:59 +08:00
Arvin Xu 88246e5719 🔨 chore: support per-task model/provider override via task.config (#13466)
*  feat: support per-task model/provider override via task.config

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: extract agent execution types into dedicated agentExecution module

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  test: add unit tests for execAgent model/provider override

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 14:25:24 +08:00
Innei aaefe6c0d2 👷 chore(ci): unify CI package manager from bun to pnpm (#13464)
* 👷 chore(ci): unify CI package manager from bun to pnpm

Replace bun with pnpm across all GitHub Actions workflows to ensure
lockfile consistency with pnpm-lock.yaml as single source of truth.

* 👷 chore(ci): replace bun run with pnpm run in package.json scripts

Fix build failure in CI where bun is not installed. Replace bun run
references in root and e2e package.json scripts with pnpm run.

* 👷 chore(e2e): replace bunx with npx in e2e server startup

* 👷 chore(ci): create unified setup-env action, use pnpm install + bun run

- Add .github/actions/setup-env composite action (pnpm + bun + node)
- Refactor desktop-build-setup to use setup-env internally
- All workflows: pnpm install for deps, bun run for scripts
- Revert package.json/e2e scripts back to bun run
- Remove all direct pnpm/action-setup and oven-sh/setup-bun from workflows

* 🐛 fix(test): inline lexical ESM deps for vitest under pnpm

pnpm's strict node_modules layout causes vitest ESM resolution to fail
for lexical's named exports. Add lexical and @lexical/* to inline deps.
2026-04-01 14:08:37 +08:00
Arvin Xu cbc9bfccaa 💄 style: show live elapsed timer during tool execution (#13437)
*  feat: show live elapsed timer during tool execution

Display a real-time elapsed timer on tool call inspector while the tool is executing.
The timer automatically hides once execution completes.

Fixes LOBE-6331

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: stop execution timer for rejected tool calls and reset elapsed on restart

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:34:54 +08:00
Rylan Cai 3e056ad37a 🔧 chore:(web-browsing): OOM debug logs (#13452)
* 🔧 add oom debug logging for web browsing search

* wip: trim

* 🔧 minimize web browsing oom debug logs

* ♻️ revert incidental crawl error check change

* 🔧 refine web browsing oom tracing

* 🔧 polish oom memory logs

* ♻️ inline crawler impl fallback in caller

* 🐛 guard memory snapshot behind debug enablement
2026-04-01 00:22:48 +08:00
Innei 46bac5b540 🐛 fix(utils): auto-reload on chunk load error (#13450)
🐛 fix: auto-reload on chunk load error instead of showing toast

When a chunk fails to load the old version is already unusable,
so reload the page automatically. Uses sessionStorage guard to
prevent infinite reload loops.

Fixes LOBE-6572
2026-03-31 23:56:20 +08:00
Innei 57ed8f8541 ♻️ refactor(tool): decouple topic-reference executor from app TRPC client (#13451)
♻️ refactor(tool): inject topic reference runtime in app layer

Move topic-reference executor to runtime injection so package code no longer imports app-level TRPC client aliases. Keep the TRPC call in store executor wiring for clear package/app boundaries.

Made-with: Cursor
2026-03-31 23:27:42 +08:00
LobeHub Bot 132893549a test: add unit tests for TaskService (#13432)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 22:14:50 +08:00
sxjeru d717d5da20 🐛 fix: update payload handling for OpenRouter image models (#10622)
*  feat: add imageAspectRatio support and update payload handling for image models

*  feat: enhance image model handling and support imageAspectRatio configuration

*  feat: add support for new image model "Nano Banana 2" and enhance image configuration handling

*  feat: add 'thinkingLevel4' to extendParams and improve image configuration handling

*  feat: add new AI models including DeepSeek V3.2 and Ministral 3 series, enhancing model capabilities and configurations

*  feat: update context window tokens and add new models in AIChatModelCard

*  feat: update Mistral model IDs and add new models; change AiHubMix base URL to API endpoint
2026-03-31 22:12:52 +08:00
Innei 58fa4f869d feat(chat): intervention fallback UI, GTD default tools, intervention guard order (#13447)
*  Improve intervention fallback UI; add GTD to default tools; defer unknown-tool guard

- Fallback intervention: show tool/action titles, collapsible parameters with i18n
- Register GTD manifest in defaultToolIds for shared tool list
- Run unknown-tool intervention only after per-tool resolver (auto-run skips early)
- TodoProgress: horizontal margin and top corner radii

Made-with: Cursor

* 🌐 chore(i18n): sync default keys and locale JSON across namespaces

Align knowledgeBase, labs, memory, notification, portal, thread, models, and chat bundles with default sources.

Made-with: Cursor
2026-03-31 22:07:58 +08:00
Rdmclin2 32e36e330a 🔨 chore: optimize message tool (#13444)
* chore: adjust electron testing to local testing

* chore: comprehence discord docs

* chore: add common capture window

* chore: default enable message tool in bot conversation

* fix: discord readMessages error

* chore: optimize readMessages prompt

* chore: optimize limit description

* chore: optimize limit size

* chore: remove limit parameter for discord

* chore: add threadRecover  Patch

* chore: optimize system role and bot context

* fix: avoid overide user config message tool

* chore: add default timeout
2026-03-31 21:28:18 +08:00
Innei ee8cab8305 🐛 fix: set context before replaceMessages in StoreUpdater layout effect (#13421)
🐛 fix: set context before replaceMessages in layout effect

replaceMessages calls onMessagesChange(messages, get().context) internally.
Without updating context first, it writes new topic's messages to the old
topic's key in ChatStore, corrupting cached data.
2026-03-31 20:47:33 +08:00
Innei 393653e20c ⬆️ chore: bump Lexical to 0.42 and align editor imports (#13440)
* ⬆️ chore: bump Lexical to 0.42 and align editor imports

- Bump lexical and @lexical/utils; pin lexical in pnpm overrides
- Return serialized nodes from ActionTag/ReferTopic XML readers (no INodeHelper require)
- Drop IEditorPlugin implements; import MenuRenderProps and IEditor from @lobehub/editor barrel

Made-with: Cursor

*  chore: add lexical dependency version 0.42.0 to package.json

Signed-off-by: Innei <tukon479@gmail.com>

*  test: enhance MCPClient Stdio Transport tests with local stdio entry

- Updated the test configuration to use a local stdio entry instead of `npx`, improving test reliability in CI environments.
- Added necessary imports for path resolution to support the new configuration.

Signed-off-by: Innei <tukon479@gmail.com>

---------

Signed-off-by: Innei <tukon479@gmail.com>
2026-03-31 20:45:32 +08:00
Hardy 560f598789 🐛 fix(glmCodingPlan): update default URL and add GLM-5.1 model (#13405)
*  feat(glmCodingPlan): update default URL and add GLM-5.1 model

- Change default URL to open.bigmodel.cn/api/coding/paas/v4
- Add GLM-5.1 model with 200K context window, 128K max output, reasoning support

* 🐛 fix: update test baseline URL for GLM Coding Plan provider
2026-03-31 18:42:40 +08:00
LobeHub Bot 993dfe1bb0 🌐 chore: translate non-English comments to English in packages (#13427)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 18:11:39 +08:00
Arvin Xu 967302269e 🐛 fix: support multiple artifacts rendering in the same message (#13436)
* 🐛 fix: support multiple artifacts rendering in the same message

When a message contains multiple `<lobeArtifact>` tags, only the first one
rendered correctly. The rest stayed in loading state or showed incorrect content.

Root causes:
- processWithArtifact used non-global regex, only removing newlines from first artifact
- artifactCode selector only extracted first artifact's content
- isArtifactTagClosed returned true if ANY artifact was closed
- Render onClick compared only messageId, closing portal instead of switching

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  test: add comprehensive tests for multiple artifacts rendering

- rehypePlugin: test multiple artifact tags in same tree (both p-wrapped and raw)
- action: test openArtifact switching between artifacts (same message, different messages)
- selectors: test artifactCode/isArtifactTagClosed with identifier edge cases
  (non-existent identifier, unclosed artifact, both closed)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: resolve type error in rehypePlugin test

Cast tree.children elements to any when accessing tagName property
to fix TS2339 error in the raw node test case.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: escape regex special characters in artifact identifier

Artifact identifiers interpolated directly into `new RegExp()` could cause
SyntaxError or incorrect matching when containing regex metacharacters
like (, [, +, etc. Now escapes identifiers before building regex patterns.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 17:21:15 +08:00
ONLY-yours 4b9ddc4fc2 ♻️ refactor: align skill collection types with API schema
- Update SkillCollectionItem type: coverUrl → cover, description → summary
- Add pagination fields to SkillCollectionDetail: currentPage, pageSize, totalCount, totalPages
- Update Hero, CollectionsSection, EditorsPick, MoreCollections components to use correct field names

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-31 16:49:09 +08:00
Arvin Xu 674c849254 feat: support client-side function tool execution in Response API (#13414)
*  feat: support client-side function tool execution in Response API

Implement LOBE-6543: when the Response API receives tools with type='function',
inject them into the LLM and pause execution when the LLM calls them, allowing
the client to provide results via function_call_output input items.

Key changes:
- Add 'client' to ToolSource type
- Inject function tools into LLM via execAgent with source='client' in sourceMap
- Pause agent loop (interrupt) when LLM calls a client function tool
- Handle function_call_output resume flow via previous_response_id
- Add response.function_call_arguments.done streaming event
- Emit response.incomplete when interrupted for client tool execution
- Use original function name for client tools instead of identifier/apiName
- Simplify response ID to use topicId directly (includes LOBE-6536 fix)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: remove MessageModel import, use prompt-based resume flow

MessageModel is not exported from @lobechat/database package.
Replace direct DB writes with prompt-based approach for tool result resume.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: use separator-safe client function identifier and add client to ToolSource

CLIENT_FN_IDENTIFIER `__fn__` caused ambiguous splits with PLUGIN_SCHEMA_SEPARATOR `____`,
breaking tool name resolution. Renamed to `lobe-client-fn` and added `client` to the
ToolSource union in @lobechat/types to match context-engine's definition.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 16:24:39 +08:00
ONLY-yours f0b16a5565 fix: merge canary 2026-03-31 15:58:33 +08:00
René Wang f327e377a6 feat: update changelog (#13430)
* feat: Update changelog

* fix: changelog images missing
2026-03-31 14:58:04 +08:00
Rylan Cai e7be5b1928 🔧 chore: adjust eval qstash runtime retries (#13364)
* 🔧 tune eval qstash runtime retries

* 🔧 smooth eval qstash retry delay

* 🔧 persist eval qstash retry telemetry

* ♻️ trim hook types formatting noise

* 🗑️ remove eval retry telemetry passthrough

* 🚚 restore hook event spacing
2026-03-31 14:12:11 +08:00
Arvin Xu b54a41968d 🐛 fix(model-runtime): allow Gemini 3+ to combine search tools with function declarations (#13429)
* 🐛 fix(model-runtime): allow Gemini 3+ models to combine search tools with function declarations

Gemini 3+ models support urlContext, googleSearch, and functionDeclarations coexisting in the tools array. Previously, enabling search/urlContext would exclude function declarations (MCP tools/skills), causing them to silently fail.

Fixes LOBE-6450

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix(model-runtime): restore hasToolCalls guard for pre-Gemini 3 multi-turn tool sessions

Restores the hasToolCalls check for pre-Gemini 3 models so that when
tool_calls exist in message history, functionDeclarations are prioritized
over search tools to maintain multi-turn tool-calling sessions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 12:34:48 +08:00
Zhijie He f39f5e9fd6 🐛 fix: fix lmstudio api key field has been hidden (#12678)
fix: fix lmstudio api key field has been hidden

env: support api key env
2026-03-31 12:17:16 +08:00
Rylan Cai 7be18092d3 ♻️ refactor: Agent Runtime stability improvement (#13257)
*  feat: add tool error kind classification and runtime retry dispatch

*  feat: add llm retry loop and stream reset event

* 🚑 stop retrying unknown tool execution errors

* ♻️ reduce runtime executor diff noise

* ♻️ restore runtime executor context comments

* ♻️ compress runtime executor retry diff

*  add llm retry backoff

* ♻️ tighten llm error classification kinds

* ♻️ tighten retry test assertions

* 🐛 stop llm retry after operation interruption

*  fix runtime executor retry stream test

* 🐛 stop retries after operation interruption

* 🐛 stop retrying provider invalid_request llm errors

* wip: reset

*  sync runAgent test with canary expectations
2026-03-31 11:18:30 +08:00
sxjeru c60c02bcfe 🐛 fix: correct extend params reasoning payloads and persist cleared model settings & add MiniMax M2.7 (#12760)
* fix: 允许单独传递 thinking.budget_tokens 参数

* fix: 添加 normalizeExtendParamsValue 函数并更新 ExtendParamsSelect 组件逻辑

* add new GPT-5.4 mini and nano models to AIChatModelCard array

* 🐛 fix: update DEFAULT_MINI_MODEL to gpt-5.4-mini

* 🐛 fix: update model references to gpt-5.4-mini in tests and snapshots

* 🐛 fix: 移除 MiniMax-M2.1 模型的定义

* feat: 添加 MiniMax M2.7 和高速度模型,更新现有模型定价和描述

* typo

* feat: 添加 MiniMax M2.7 和 MiMo V2 系列模型,更新模型能力和定价

* fix test

*  feat: update NVIDIA chat models with new entries and enhanced descriptions

* feat: 添加 Qwen3.5 Omni Plus 和 Qwen3.5 Omni Flash 模型,更新模型能力和定价
feat: 更新响应 API 模型,添加 gpt-5.4-mini 和 gpt-5.4-nano
2026-03-31 11:01:32 +08:00
Zhijie He ec3443d1db 💄 style: add qwen3.5-omni series (#13422)
style: add qwen3.5-omni series
2026-03-31 10:05:29 +08:00
Arvin Xu e76ab1f990 💄 style: mount DynamicFavicon for agent operation favicon switching (#13416)
*  feat: mount DynamicFavicon to enable favicon state switching during agent operations

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: add favicon link tags to SPA HTML templates and handle missing links in updateFaviconDOM

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 09:25:18 +08:00
Innei c59c066330 🐛 fix(intervention): resolve InterventionBar context errors, rendering, and topic transition issues (#13420)
* 🐛 fix: resolve InterventionBar context errors and rendering issues

- Replace useMessageAggregationContext with prop drilling for assistantGroupId,
  fixing crash when ApprovalActions renders outside MessageAggregationContext
- Filter out tmp_ message IDs from pending interventions to prevent
  disabled buttons during message creation
- Portal ApprovalActions outside scroll container in InterventionBar
  so buttons are always accessible for long content
- Clear stale displayMessages synchronously on topic change to prevent
  old interventions from persisting during transitions

* 🐛 fix: use useLayoutEffect to clear stale interventions on topic switch

Replace render-phase side effect with useLayoutEffect to properly clear
displayMessages before browser paint when context changes, preventing
old topic interventions from flashing during transitions.

* 🐛 fix: synchronously reset store on context change to prevent stale data flash

Use React's "setState during render" pattern instead of useLayoutEffect.
When contextKey changes, React bails out and re-renders StoreUpdater
before rendering sibling components (ChatList/ChatInput), ensuring they
read fresh store state with no visible flash of old topic data.

* 🐛 fix: remount store on context change to eliminate stale data flash

Add key={contextKey} to zustand Provider so the store is recreated on
topic switch. Seed the new store with initialMessages in createStore to
render correct data on first mount — no intermediate skeleton or stale
flash. Remove render-phase reset hack from StoreUpdater as it's no
longer needed.

* 🐛 fix: revert Provider key approach, use useLayoutEffect for context reset

Provider key={contextKey} caused ChatHydration to remount and reset
activeTopicId from URL query, preventing topic switches entirely.

Reverted to stable Provider. Instead, use useLayoutEffect in StoreUpdater
to atomically reset displayMessages + messagesInit when contextKey changes.
This fires after commit but before paint, and React processes store updates
from layout effects synchronously, ensuring subscribers re-render with
correct state before the browser paints.
2026-03-31 02:57:56 +08:00
Innei 7097167613 🐛 fix(editor): add ReactMentionPlugin to ChatInput for mention node rendering (#13415)
🐛 fix: add ReactMentionPlugin to ChatInput so mention nodes render

The ChatInput editor plugins did not include ReactMentionPlugin, causing
mention nodes inserted via @ to be invisible. Move the plugin into
CHAT_INPUT_EMBED_PLUGINS so all ChatInput instances (including Home)
render mention nodes, and remove the now-duplicate entry from EditorCanvas.

Fixes LOBE-6270
2026-03-31 01:53:29 +08:00
Arvin Xu 2c2795e73a 🐛 fix: cli gateway auto reconnect (#13418)
* ♻️ refactor: move Marketplace below Resources in sidebar

Move the Marketplace (Community) nav item from topNavItems to bottomMenuItems,
positioning it below Resources in the sidebar navigation.

Closes LOBE-6320

* 🐛 fix(cli): auto-reconnect on auth expiry instead of exit

- Add `updateToken()` and `reconnect()` methods to GatewayClient
- On `auth_expired`, refresh JWT then reconnect automatically (no more process.exit)
- Add heartbeat ack timeout detection: force reconnect after 3 missed acks
- Reset missed heartbeat counter on `heartbeat_ack` receipt
- Add comprehensive tests for updateToken, reconnect, and missed heartbeat scenarios

Closes connection drop issue when JWT expires after long-running sessions.
2026-03-31 01:16:17 +08:00
Rdmclin2 965fc929e1 feat: add unified messaging tool for cross-platform communication (#13296)
*  feat: add cross-platform message tool for AI bot channel operations

Implement a unified message tool (`lobe-message`) that provides AI with
messaging capabilities across Discord, Telegram, Slack, Google Chat,
and IRC through a single interface with platform-specific extensions.

Core APIs: sendMessage, readMessages, editMessage, deleteMessage,
searchMessages, reactToMessage, getReactions, pin/unpin management,
channel/member info, thread operations, and polls.

Architecture follows the established builtin-tool pattern:
- Package: @lobechat/builtin-tool-message (manifest, types, executor,
  ExecutionRuntime, client components)
- Registry: registered in builtin-tools (renders, inspectors,
  interventions, streamings)
- Server runtime: stub service ready for platform adapter integration

https://claude.ai/code/session_011sHc6R7V4cSYKere9RY1QM

* feat: implement platform specific message service

* chore: add wechat platform

* chore: update wechat api service

* chore: update protocol implementation

* chore: optimize  platform api test

* fix: lark domain error

* feat: support bot message cli

* chore: refactor adapter to service

* chore: optimize bot status fetch

* fix: bot status

* fix: channel nav ignore

* feat: message tool support bot manage

* feat: add lobe-message runtime

* feat: support direct message

* feat: add history limit

* chore: update const limit

* feat: optimize  server id message history limit

* chore: optimize system role & inject platform environment info

* chore: update  readMessages vibe

* fix: form body width 50%

* chore: optimize tool prompt

* chore: update i18n files

* chore: optimize read message system role and update bot message lh

* updage readMessage api rate limit

* chore: comatible for readMessages

* fix: feishu readMessage implementation error

* fix: test case

* chore: update i18n files

* fix: lint error

* chore: add timeout for conversaction case

* fix: message test case

* fix: vite gzip error

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 00:26:32 +08:00
Innei 491aba4dbd ♻️ refactor(store): class-based Zustand actions with flattenActions (#13383)
♻️ refactor(store): migrate slices to class actions with flattenActions

- Video store: generationConfig/Topic/Batch/createVideo as *ActionImpl; aggregate with flattenActions
- Eval store: benchmark/dataset/run/testCase as classes; top-level flattenActions
- Tool agentSkills: AgentSkillsActionImpl + Pick typing
- groupProfile: flattenActions around ActionImpl instead of spreading instance
- agentGroup: wrap chatGroupAction with flattenActions for consistent aggregation

Made-with: Cursor
2026-03-30 23:46:35 +08:00
Innei 6402656ec7 feat: use skill-specific icons in slash menu instead of generic wrench icon (#13401)
*  feat: use skill-specific icons in slash menu instead of generic wrench icon

Each skill/tool in the slash menu now displays its own avatar (emoji or image URL)
instead of the generic 🔧 wrench icon for all items.

https://claude.ai/code/session_01KbUecMiAUDHvFtEULkSDvr

* ♻️ refactor: use SkillsIcon as default slash menu skill icon

https://claude.ai/code/session_01KbUecMiAUDHvFtEULkSDvr

*  feat: enhance slash action item rendering and mention menu styles

- Updated `useSlashActionItems.ts` to improve icon rendering for URLs, now supporting blob and data-URI images.
- Modified `MenuItem.tsx` to conditionally apply additional styles for items with extra categories.
- Added new style for `itemWithCategoryExtra` in `style.ts` to enhance layout consistency.

These changes aim to improve the visual presentation and functionality of the chat input components.

Signed-off-by: Innei <tukon479@gmail.com>

* 🐛 fix(mention-menu): satisfy cx ClassNamesArg types in MenuItem

Made-with: Cursor

---------

Signed-off-by: Innei <tukon479@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-30 22:36:12 +08:00
Innei f6314cc673 ♻️ refactor: serve Vite SPA static assets under /_spa (#13409)
Made-with: Cursor
2026-03-30 21:54:20 +08:00
Yizhuo cded932f1a 📝 docs: update telegram channel guide & remove wip description (#13226)
*  docs: add screenshots to Telegram channel guide

* 📝 docs: Remove "feature in development" callout and developer mode requirement from channels documentation.

* docs: Migrate Telegram channel images to local assets and update CDN cache.

* docs: Add screenshots to channel setup guides for various platforms.

* chore: Update documentation image paths from GitHub user attachments to local blog assets.

---------

Co-authored-by: Rdmclin2 <rdmclin2@gmail.com>
2026-03-30 21:42:29 +08:00
Innei e7c496352f 🐛 fix: defer scroll-to-user-message until spacer is mounted (#13378)
* 🐛 fix: defer scroll-to-user-message until spacer is mounted

The scroll that pins a user message to the top of the viewport was
racing with the conversation spacer mount. When the spacer hadn't
rendered yet, there wasn't enough scrollable height, so the scroll
had no effect.

Now `useScrollToUserMessage` accepts a `spacerActive` flag and
defers the scroll until the spacer is mounted, guaranteeing the
fill height is available before scrolling.

https://claude.ai/code/session_016GDASpf7Rh5yN7BJTdXYwT

* 🐛 fix: always scroll immediately, re-scroll when spacer mounts

The previous fix deferred scrolling entirely until spacerActive was
true. This regressed the no-spacer case (content fills viewport,
spacer height = 0, mounted stays false) — the scroll never fired.

Now the hook always scrolls immediately on message send (preserving
original behavior), and additionally fires a follow-up scroll when
spacerActive transitions to true. This covers both cases:
- Content fills viewport: immediate scroll works, no spacer needed
- Content is short: immediate scroll may under-scroll, but the
  follow-up scroll after spacer mounts corrects the position

https://claude.ai/code/session_016GDASpf7Rh5yN7BJTdXYwT

* 🐛 fix(conversation): shrink bottom spacer on scroll-up when idle

- Track scroll delta to reduce spacer height while not streaming
- Disable height transition during scroll-shrink for immediate feedback
- Reset reduction on new user/assistant pair and generation state changes

Made-with: Cursor

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-30 21:31:35 +08:00
Arvin Xu 296c6f3cb3 🔧 refactor: simplify response ID to use topicId directly (#13410)
Remove resp_ prefix and random suffix encoding from response IDs.
Response ID now equals topicId directly, simplifying multi-turn
conversation support via previous_response_id.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 21:31:09 +08:00
LiJian 53d0ee9ca5 🐛 fix: should use env.APP_URL to replace online url (#13408)
* fix: should use env.APP_URL to replace online url

* fix: fixed the double / path problem
2026-03-30 20:37:44 +08:00
Arvin Xu 689d5a51e8 feat(openapi): support hosted builtin tools in Response API (#13406)
*  feat(openapi): support hosted builtin tools in Response API

Allow declaring builtin tools via { type: 'lobe-xxx' } syntax in the
tools array of POST /api/v1/responses. Hosted tool identifiers are
extracted and passed as additionalPluginIds to execAgent, where the
existing ToolsEngine handles manifest resolution automatically.

LOBE-6535

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  feat(openapi): stream tool calls and results in Response API

Add full streaming support for tool execution events in the Response
API. Previously only text deltas were streamed; tool calls and results
were only visible in the final response.completed event.

Now emits:
- response.output_item.added (function_call) when LLM invokes a tool
- response.function_call_arguments.delta for tool arguments
- response.output_item.done (function_call) when tool call is complete
- response.output_item.added/done (function_call_output) when tool
  execution finishes with results
- Proper text message lifecycle (added/delta/done) across multi-step
  agent loops

LOBE-6535

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix(openapi): handle nullable tools param in extractHostedToolIds

The tools field from CreateResponseRequest uses .nullish() in zod,
so it can be null. Accept null in the parameter type.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 20:37:07 +08:00
Arvin Xu 23eab8769b 🐛 fix: add unread completion notification for group topic orchestration (#13407)
* 🐛 fix: add unread completion notification for group topic orchestration

Group orchestration was missing markUnreadCompleted() call after completion,
and group topic NavItem lacked the unread completion indicator UI.

Fixes LOBE-4878

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 💄 style: extract neon dot inline styles to createStaticStyles

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: add test screenshot 01.jpg for LOBE-4878

* docs: add test screenshot 02.jpg for LOBE-4878

* docs: add test screenshot 03.jpg for LOBE-4878

* 🔥 chore: remove temporary test screenshots

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 💄 style: change unread neon dot color from green to blue (colorInfo)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: replace remaining successColor references with infoColor in group topic item

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 20:33:31 +08:00
Innei 0e57fd9955 feat(onboarding): agent web onboarding, feature toggle, and lifecycle sync (#13139)
*  feat(onboarding): add agent-guided web onboarding flow

Made-with: Cursor

* Update onboarding prompts

Co-authored-by: Codex <noreply@openai.com>

* 🐛 fix web onboarding builtin tool flow

*  feat(onboarding): enhance agent onboarding flow with new dimensions and refined rules

- Updated onboarding structure to include new nodes: agentIdentity, userIdentity, workStyle, workContext, and painPoints.
- Revised system role instructions to emphasize a conversational approach and concise interactions.
- Adjusted manifest and type definitions to reflect the new onboarding schema.
- Implemented tests to ensure proper functionality of the onboarding context and flow.

This update aims to improve user experience during onboarding by making it more engaging and structured.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): enhance onboarding experience with localized welcome messages and interaction hints

- Added localized welcome messages for onboarding in English and Chinese.
- Refactored system role handling to support dynamic interaction hints based on user locale.
- Updated onboarding context to include interaction hints for improved user engagement.
- Implemented tests to validate the new interaction hint functionality.

This update aims to create a more personalized and engaging onboarding experience for users across different languages.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): overhaul onboarding flow with new question structure and refined interaction rules

- Replaced existing interaction hints with a focused question structure to enhance user engagement.
- Updated system role instructions to clarify onboarding protocols and improve conversational flow.
- Refactored type definitions and manifest to align with the new onboarding schema.
- Removed deprecated interaction hint components and tests to streamline the codebase.

This update aims to create a more structured and engaging onboarding experience for users, ensuring clarity and efficiency in interactions.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): introduce builtin agent onboarding package with structured roles and prompts

- Added a new package for agent onboarding, including a package.json configuration and initial TypeScript files.
- Implemented system role templates and tool prompts to guide the onboarding process.
- Established a client interface for rendering questions and handling user interactions.
- Updated dependencies in related packages to integrate the new onboarding functionality.

This update aims to enhance the onboarding experience by providing a structured approach for agents, ensuring clarity and efficiency in user interactions.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): enhance agent onboarding with new question renderer and refined interaction logic

- Introduced a new `QuestionRendererView` component to streamline the rendering of onboarding questions.
- Refactored the `QuestionRenderer` to utilize a runtime hook for improved state management and separation of concerns.
- Updated the onboarding context to fallback to stored questions when the current question is empty, enhancing user experience.
- Simplified the onboarding API by removing unnecessary read token requirements from various endpoints.
- Added tests to validate the new question rendering logic and ensure proper functionality.

This update aims to create a more efficient and user-friendly onboarding experience by improving the question handling and rendering process.

Signed-off-by: Innei <tukon479@gmail.com>

* Add dev history view for onboarding

* remove: prosetting

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): inline response language step in agent conversation

- Add ResponseLanguageInlineStep and wire into Conversation flow
- Extend agent onboarding context and update ResponseLanguageStep route
- Add tests and onboarding agent document design spec

Made-with: Cursor

*  feat(onboarding): enhance onboarding flow with inbox integration and schema refactor

- Updated onboarding process to migrate conversation topics to the inbox upon completion, ensuring users can revisit their onboarding discussions.
- Introduced a new schema-driven normalizer and node handler registry to streamline onboarding data handling, reducing code duplication and improving maintainability.
- Added comprehensive tests for new document builders and onboarding service methods to ensure functionality and reliability.
- Refactored existing components to support the new onboarding structure and improve user experience.

This update aims to create a more cohesive onboarding experience by integrating user identity data into the inbox and simplifying the underlying code structure.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(agent-documents): add listDocuments, readDocumentByFilename, upsertDocumentByFilename APIs

*  feat(onboarding): add generic user interaction builtin tool

*  feat(onboarding): wire generic tool interaction semantics

Register user-interaction tool in builtin-tools registry with manifest,
intervention components, client executor, and server runtime. Extend
BuiltinInterventionProps with interactionMode and onInteractionAction
to support custom (non-approval) interaction UIs. Add submit/skip/cancel
actions to conversation store with full operation lifecycle management.

* 🔧 fix: add builtin-tool-user-interaction to root workspace dependencies

* ♻️ refactor(onboarding): remove onboarding-owned question persistence

Drop askUserQuestion from the web-onboarding tool and remove
questionSurface from persisted state. Question presentation is now
delegated to the generic lobe-user-interaction tool.

* ♻️ refactor(onboarding): switch UI to generic interaction tool

Enable UserInteraction and AgentDocuments tools in web-onboarding and
inbox agent configs. Remove obsolete inline question renderers
(QuestionRenderer, QuestionRendererView, questionRendererRuntime,
questionRendererSchema, ResponseLanguageInlineStep) and simplify
Conversation component to only render summary CTA.

* 🔥 refactor(onboarding): remove identity doc and rewrite soul sync

* 🐛 fix(user-interaction): add humanIntervention to manifest and implement form UI

* 🐛 fix(onboarding): create user message on interaction submit instead of re-executing tool

* ♻️ refactor(onboarding): rebuild generic interaction flow

Align agent/tool roles and onboarding UI/runtime around the generic interaction rebuild.

Made-with: Cursor

*  feat(onboarding): implement onboarding document and persona management

Introduce a new onboarding document structure that separates agent identity and user persona data. Replace existing `readSoulDocument` and `updateSoulDocument` APIs with `readDocument` and `updateDocument` to handle both SOUL.md and user persona documents. Update related services, client executors, and localization keys to reflect these changes. Ensure document updates are driven by the agent, allowing for incremental updates and improved content management.

Signed-off-by: Innei <tukon479@gmail.com>

* refactor

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(workflow): introduce unified tool call collapse UI and supporting components

Add a new workflow collapse feature that groups tool calls and reasoning into a single collapsible unit, enhancing the user interface for tool call progress. This includes the creation of several components: `WorkflowCollapse`, `WorkflowSummary`, `WorkflowExpandedList`, `WorkflowToolLine`, and `WorkflowReasoningLine`. Update the design specifications and implementation plans to reflect this new structure, aiming for a more cohesive and user-friendly experience.

Signed-off-by: Innei <tukon479@gmail.com>

* feat(types): add discovery pacing types and constant

* feat(onboarding): add countTopicUserMessages and pacing gate to derivePhase

* feat(onboarding): capture discovery baseline and return pacing data in getState

*  feat(onboarding): add pacing hints to discovery phase tool result

* test(onboarding): add discovery pacing gate tests

* ♻️ refactor(onboarding): soften discovery pacing gate and add early exit exception

- MIN_DISCOVERY_USER_MESSAGES lowered from 4 to 2 (hard floor)
- RECOMMENDED_DISCOVERY_USER_MESSAGES = 4 (advisory hint)
- Tool protocol rule 2 now has explicit early exit exception
- Pacing hint text changed from imperative to advisory

*  feat(onboarding): update .gitignore and remove outdated onboarding plans

- Added `docs/superpowers` to .gitignore to exclude documentation files from version control.
- Deleted several outdated onboarding implementation plans, including those for onboarding inbox integration, generic interaction rebuild, and user question simplification, to streamline project documentation.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): refine agent onboarding, streaming, and AskUserQuestion

Made-with: Cursor

*  feat(store): add pending interventions selector

* 🐛 fix(store): handle standalone tool messages and structural children traversal in pending interventions selector

*  feat(conversation): create InterventionBar component

Add InterventionBar UI component with tab bar for multiple pending
interventions, reusing the existing Intervention detail component.

* 🐛 fix(conversation): use stable toolCallId for active tab state and add min-height: 0

Track active intervention by toolCallId instead of array index to prevent
stale selection when interventions are resolved. Add min-height: 0 to
scrollable content for correct overflow in flex column layout.

* feat(chatinput): show InterventionBar when pending interventions exist

* feat(tool): collapse inline intervention to one-line summary with scroll-to-bottom

* feat(i18n): add intervention bar translation keys

* 🐛 fix(chatinput): prevent infinite render loop from pendingInterventions selector

* 🐛 fix(chatinput): use equality function for pendingInterventions to break render loop

* refactor(tool): remove CollapsedIntervention, return null for pending inline

* feat(i18n): add form.other translation key

* feat(tool): add styles for select field with Other option

* feat(tool): add SelectFieldInput with Other option row

* feat(tool): wire SelectFieldInput and update validation in AskUserQuestion

* fix(tool): add keyboard handler to Other row, fix label flex

* refactor(tool): restore Select dropdown, add Other toggle row below

* refactor(tool): change Other to form-level escape hatch, restore antd Select

* refactor(tool): replace checkbox toggle with minimal text link escape hatch

* feat(tool): use lucide icons, auto-focus on escape toggle, createStaticStyles

* refactor(onboarding): update onboarding model references and improve styling in ModeSwitch component

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): add greeting entry animation keyframes and card styles

*  feat(onboarding): add LogoThree and entry animations to greeting card

*  feat(onboarding): add View Transition morph from greeting to conversation

* refactor(onboarding): simplify ModeSwitch component by removing segmentedGlass styling

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(onboarding): increase maximum onboarding steps to 5 and add ProSettingsStep component

Signed-off-by: Innei <tukon479@gmail.com>

*  feat: enhance user interaction question handling with validation schema

- Introduced Zod validation for askUserQuestion arguments to ensure correct structure.
- Updated test to reflect new question format with fields.
- Added error handling in AskUserQuestion component to log submission errors.

This improves the robustness of user interactions by enforcing schema validation and enhancing error reporting.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat: enhance agent metadata handling and onboarding synchronization

- Updated `useAgentMeta` to prioritize custom titles from the database, falling back to the default Lobe AI title if none exists.
- Integrated `refreshBuiltinAgent` into the onboarding process to ensure the latest agent data is reflected during user interactions.
- Adjusted the `InboxItem` component to display the correct agent title and avatar based on the updated metadata.
- Refactored optimistic update actions to improve message handling and synchronization across components.

This improves the user experience by ensuring that the most relevant agent information is displayed and updated in real-time during onboarding and conversation flows.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat: enhance conversation lifecycle and onboarding agent synchronization

- Updated `ConversationLifecycleActionImpl` to include additional context parameters (agentId, groupId, threadId, topicId) when updating message plugins for aborted interactions.
- Integrated `refreshBuiltinAgent` for the inbox during the onboarding process to ensure the latest agent data is synchronized.

These changes improve the handling of conversation lifecycle events and ensure that onboarding reflects the most current agent information, enhancing user experience during interactions.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat: implement agent onboarding feature toggle and enhance ModeSwitch component

- Introduced `AGENT_ONBOARDING_ENABLED` configuration to control the visibility of the agent onboarding options.
- Updated `ModeSwitch` component to conditionally render onboarding options based on the feature toggle.
- Enhanced tests for `ModeSwitch` to cover scenarios for both enabled and disabled states of agent onboarding.
- Refactored `AgentOnboardingRoute` to navigate to the classic onboarding if the agent onboarding feature is disabled.

These changes improve the onboarding experience by allowing dynamic control over the agent onboarding feature, ensuring that users only see relevant options based on the configuration.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat: update agent onboarding feature toggle to include development mode

- Modified `AGENT_ONBOARDING_ENABLED` to also activate in development mode using `isDev`.
- This change allows for easier testing and development of the agent onboarding feature without needing to alter production configurations.

Signed-off-by: Innei <tukon479@gmail.com>

* Prevent welcome message when onboard

* 🐛 fix: satisfy ToolExecutionContext and updateMessageTools typings

Made-with: Cursor

* 🐛 fix: update tests for custom builtin agent title and discovery phase constants

* 🐛 fix: use custom inbox agent title and avatar in InboxWelcome

* 🧹 chore(onboarding): remove HistoryPanel unit test

Made-with: Cursor

* 🐛 fix: add missing onboarding/agent and onboarding/classic routes to desktop config

*  test: fix failing tests for onboarding container, document helpers, and executor

*  test: mock LogoThree to prevent Spline runtime fetch errors in CI

---------

Signed-off-by: Innei <tukon479@gmail.com>
Co-authored-by: Codex <noreply@openai.com>
2026-03-30 20:28:54 +08:00
LobeHub Bot 2f5a31fc99 test: add unit tests for LocalTaskScheduler (#13398)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-30 18:53:03 +08:00
Arvin Xu 143a15fdb9 💄 style: show interrupted hint when AI generation is stopped (#13397)
*  feat: show interrupted hint when AI generation is stopped

Display "Interrupted · What should I do instead?" text below the message
when user stops AI generation, replacing the infinite dotting animation.

Fixes LOBE-4462
Fixes LOBE-5726

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  feat: add edit button to queued messages tray

Allow users to edit queued messages by clicking the pencil icon,
which removes the message from the queue and restores its content
to the input editor.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 📝 chore: move record-electron-demo.sh to electron-testing skill

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: derive isInterrupted from latest runtime operation only

Previously isInterrupted used .some() to check if any cancelled AI
runtime operation existed for a message. In stop-then-retry flows,
the old cancelled op persisted alongside the new completed one,
causing the interrupted hint to reappear after the retry finished.

Now only the latest AI runtime operation is checked, so completed
retries correctly clear the interrupted state.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: read group interruption from active block ID

For assistant groups, continuation runs attach cancelled operations to
lastBlockId (contentId) rather than the group root. Check isInterrupted
on both the group root and the active block so the interrupted hint
is shown correctly for stopped group continuations.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  test: update test to expect cancelled status after user stop

The test for resolving aborted tools after cancellation now correctly
expects 'cancelled' status, since completeOperation preserves the
user's intentional cancellation rather than overwriting it.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 18:46:46 +08:00
LiJian 9c08fa5cdf 🐛 fix: add the creds tools into execAgentRuntime (#13399)
fix: add the creds tools into execAgentRuntime
2026-03-30 17:20:37 +08:00
Hardy 59d8d878a2 🐛 fix: use Anthropic SDK for Kimi Coding Plan provider (#13345)
🐛 fix: use Anthropic SDK for Kimi Coding Plan provider

- Switch from OpenAI SDK to Anthropic SDK for Kimi Coding Plan
- Update baseURL from `/coding/v1` to `/coding` (Anthropic-compatible endpoint)
- Update model IDs: `kimi-k2.5` → `k2p5`, remove `kimi-k2`
- Fix max_tokens resolution to use KimiCodingPlan model list
- Rewrite tests for Anthropic SDK compatibility
2026-03-30 16:53:28 +08:00
WindSpiritSR 0439a29189 🔨 chore(docker): replace dev/prod pgsql docker image with paradedb (#13373)
🐛 fix(docker): replace dev/prod pgsql docker image with paradedb

Signed-off-by: WindSpiritSR <simon343riley@gmail.com>
2026-03-30 16:52:00 +08:00
LobeHub Bot 4a63ea3dcc 🌐 chore: translate non-English comments to English in src/routes (#13395)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-30 16:50:45 +08:00
YuTengjing 91b2653c71 🐛 fix: check error value in social sign-in result (#13392) 2026-03-30 11:38:48 +08:00
René Wang 8c8e7dd992 Update team assignments and feature responsibilities (#13393) 2026-03-30 10:44:25 +08:00
Arvin Xu a9cd2f7301 ♻️ refactor: remove DefaultAgentForm UI from settings pages (#13342)
🔥 refactor: remove DefaultAgentForm UI from settings pages

Remove the user-facing Default Agent configuration form from both
the agent settings page and the service-model settings page.
The underlying store action and selectors are preserved for
programmatic use (e.g. onboarding).

Fixes LOBE-1125

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 10:18:31 +08:00
YuTengjing b6c66dbdd7 feat: add businessElement and getFetchOptions plumbing to signin page (#13382)
*  feat: add businessElement and getFetchOptions plumbing to signin page

Add extension points to the signin flow so cloud overrides can inject
custom UI elements and modify fetch options for social sign-in requests.

- Add businessElement slot to SignInEmailStep component
- Pass getFetchOptions to signIn.social() and signIn.oauth2() calls
- Add businessElement and getFetchOptions defaults to useBusinessSignin

* 🐛 fix: resolve TS error on signIn.social result type with fetchOptions
2026-03-29 23:15:16 +08:00
Rylan Cai 5e1738ad4b ♻️ refactor(context engine): tool message normalization (#13359)
* ♻️ normalize tool call messages in context engine

* ♻️ prune tool message normalization implementation

* ♻️ prune tool message normalization diff

* ♻️ simplify tool message normalization diff

* ♻️ restore tool message reorder logging

* ♻️ restore reorder tool message shape

* ♻️ restore tool message reorder comment

* ♻️ prune tool message normalization diff

* ♻️ restore tool message reorder shape

* 🐛 fix(context-engine): keep empty tool content in reorder
2026-03-29 23:04:02 +08:00
Arvin Xu 4dc3c4ea1d 💄 style: move Marketplace below Resources in sidebar (#13381)
♻️ refactor: move Marketplace below Resources in sidebar

Move the Marketplace (Community) nav item from topNavItems to bottomMenuItems,
positioning it below Resources in the sidebar navigation.

Closes LOBE-6320
2026-03-29 22:32:30 +08:00
Arvin Xu bc9ae6b4e5 feat: support message queue (#13343)
*  feat: add message queue for agent runtime (soft interrupt)

Implement per-context message queue that allows users to send messages
while the agent is executing. Messages are queued and consumed via two
paths: injected at step boundaries during execution (Path A), or
triggering a new sendMessage after completion (Path B).

- Add QueuedMessage type and queuedMessages state in operation store
- Add enqueue/drain/remove/clear actions and selectors
- Modify sendMessage to enqueue when execAgentRuntime is running
- Add queue checkpoint in step loop (streamingExecutor)
- Add Path B: drain remaining queue after completion → new sendMessage
- Keep input enabled during agent execution (remove isInputLoading guard)
- Add QueueTray component showing "N Queued" above ChatInput
- Add electron-testing skill for agent-browser CLI automation

Fixes LOBE-6001

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: Path B deferred execution to avoid recursive internal_execAgentRuntime

Use setTimeout(0) to break out of the current execution context when
triggering a new agent runtime for queued messages after completion.
Direct recursive calls caused issues with zustand state batching.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: remove premature Path A drain, fix Path B with fresh store ref

Path A (step checkpoint injection) was draining the queue before the
last LLM step, leaving nothing for Path B. For agents without tool
calls, this meant queued messages were consumed but never acted upon.

Fix: remove Path A for now (will be re-added for tool-call scenarios),
and use useChatStore.getState() in Path B setTimeout to get a fresh
store reference instead of a stale closure capture.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 📝 docs: update electron-testing skill with real-world patterns

Based on lessons learned during message queue testing:
- Must cd to apps/desktop before npx electron-vite dev
- Use polling loop for startup detection
- snapshot -i -C required for contenteditable (chat input)
- Use sleep + screenshot instead of agent-browser wait for long ops
- Access store via window.__LOBE_STORES.chat()
- Add error interceptor and store inspection patterns
- Document all gotchas (HMR, daemon blocking, fill vs type)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  feat: add Path A - early handoff to Path B at tool completion

When tools finish and queue has messages, break the step loop early
and let Path B create user message + start new operation. The new
LLM call sees full context including tool results + new user message.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: Path B use sendMessage for proper message creation

Use sendMessage instead of optimisticCreateMessage + internal_execAgentRuntime.
sendMessage handles the full lifecycle correctly: creates user message
on server, creates assistant message placeholder, and triggers
internal_execAgentRuntime — ensuring both messages are visible in UI.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 💄 style: redesign QueueTray to Codex-style card layout

Each queued message shows as a card with icon, text preview,
and delete button. Uses antd CSS variables for consistent theming.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 💄 style: connect QueueTray with ChatInput as unified container

QueueTray and ChatInput now share a connected border:
- QueueTray has top-rounded corners, no bottom border
- ChatInput gets bottom-only rounded corners when queue has items
- Uses cssVar for proper theme token styling
- Zero gap between tray and input

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: move queue check logic into GeneralChatAgent

Move the "finish early when queue has messages" decision from
streamingExecutor into GeneralChatAgent.runner(). The agent now
checks stepContext.hasQueuedMessages at tools_batch_result phase
and returns finish instruction, which is architecturally cleaner.

- Add hasQueuedMessages to RuntimeStepContext and computeStepContext
- GeneralChatAgent returns finish when tools complete + queue non-empty
- Remove Path A/B labels from comments
- streamingExecutor just passes hasQueuedMessages via stepContext

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: forward queued files in sendMessage and drain only on success

- Forward merged file attachments when replaying queued messages
  (sendMessage now receives files from merged queue)
- Move drainQueuedMessages inside the status==='done' branch so
  queued messages are preserved on error/interrupted states
- Add queued_message_interrupt to FinishReason enum
- Add hasQueuedMessages check to tool_result and tasks_batch_result
  phases in GeneralChatAgent (not just tools_batch_result)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: use full operationContext for context key indexing

- operationsByContext index now uses messageMapKey(context) with full
  context (including threadId, scope, etc.) instead of stripped key
- Fixes key mismatch where thread/scoped contexts couldn't find
  running operations, causing overlapping generations
- Move mergeQueuedMessages from services/messageQueue.ts into
  operation/types.ts alongside QueuedMessage type
- Delete services/messageQueue.ts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 22:08:15 +08:00
YuTengjing 70091935ba 🔥 refactor(auth): remove NextAuth dead code from auth middleware (#13370)
* 🔥 refactor(auth): remove NextAuth dead code from auth middleware

* chore: shorter cookie cache duration
2026-03-29 21:17:45 +08:00
YuTengjing 50e373ad1c 🐛 fix(i18n): add missing credits.packages.charged key (#13369) 2026-03-29 02:09:57 +08:00
YuTengjing 966f943175 🐛 fix(auth): throw Unauthorized when no valid auth method found (#13368) 2026-03-29 01:56:40 +08:00
Rdmclin2 c7c2b56f3b feat: support bot manage (#13365)
* feat: support platform manage

* feat: auto connect when import config

* fix: lint error
2026-03-29 01:52:59 +08:00
Innei 841c1d2ef2 ♻️ refactor(styles): migrate remaining createStyles to createStaticStyles (#13358)
- Replace antd-style createStyles hooks with createStaticStyles and cssVar tokens
- Update MentionMenu, reactions, eval bench UI, OAuth device flow, DeviceGateway, GTD plan UI
- ModelSelect: use popupMatchSelectWidth for numeric popupWidth; narrow prop to number

Made-with: Cursor
2026-03-28 21:57:15 +08:00
Innei 26449e522a feat(resource): add select all hint and improve resource explorer selection (#13134)
*  feat(resource): add select all hint and improve resource explorer selection

Made-with: Cursor

* ♻️ refactor(resource): flatten store actions and improve type imports

Made-with: Cursor

* ♻️ refactor resource explorer list view

* refactor: engine

Signed-off-by: Innei <tukon479@gmail.com>

*  feat: checkpoint current workspace updates

* ♻️ refine resource explorer fetch ownership

* 🐛 fix: resolve resource manager ci regressions

* 🐛 fix(lambda): delete page-backed knowledge items by document id

* 🐛 fix(lambda): include knowledge-base files in remove-all

* 🐛 fix(resource): preserve cross-page select-all exclusions

* 🐛 fix(resource): retain off-screen optimistic resources

* 🐛 fix(resource): hide moved root items from current query

* 🐛 fix(resource): reset explorer selection on query change

* 🐛 fix(resource): fix select-all batchChunking and optimistic replace visibility

- batchChunking: pass through server-resolved IDs not in local resourceMap
  when selectAllState is 'all', letting server filter unsupported types
- replaceLocalResource: keep replacement visible if the optimistic item was
  already in the list, avoiding slug-vs-UUID mismatch in visibility check

* 🐛 fix(resource): reset selectAllState after batch operations and preserve off-screen optimistic items

- Reset selectAllState to 'none' after delete, removeFromKnowledgeBase,
  and batchChunking to prevent stale 'all' state causing unintended
  re-selection of remaining items
- Preserve off-screen optimistic resources in clearCurrentQueryResources
  so background uploads from other folders survive delete-all-by-query

* 🐛 fix: satisfy import-x/first in resource action test

Made-with: Cursor

* 🎨 lint: sort imports in ResourceExplorer

Made-with: Cursor

* 🐛 fix: widen searchQuery type in useResetSelectionOnQueryChange test

Made-with: Cursor

---------

Signed-off-by: Innei <tukon479@gmail.com>
2026-03-28 11:51:23 +08:00
Rdmclin2 f4c4ba7db5 🐛 fix: bot callback error (#13349)
* fix: not edit message id

* fix: error edit message

* chore: merge config & default

* chore: remove typing var

* fix: agent setting problem

* fix: test case error
2026-03-28 00:53:53 +08:00
LiJian 83f8f0319c 🐛 fix: slove the list connection always use require auth & should have trust client auth (#13344)
fix: slove the list connection always use require auth & should have trust client check
2026-03-27 21:14:03 +08:00
YuTengjing 197a0cc8f1 🌐 chore: sync i18n locale translations (#13340) 2026-03-27 18:59:54 +08:00
LiJian 6b4046eb17 🐛 fix: add the user github oauth in community home page profiles (#13222)
* fix: add the user github oauth in community home page profiles

* fix: change the oauth from social Profiles into skill connector way

* feat: add the claims user mcp and skills in community profiles

* fix: improve some claim model and skills/mcp
2026-03-27 18:04:17 +08:00
Innei 9e27bef8fa 🐛 fix(settings): remove system tools full-page loading (#13338) 2026-03-27 17:28:23 +08:00
lobehubbot aaff9af3b7 Merge remote-tracking branch 'origin/main' into canary 2026-03-27 08:05:35 +00:00
LiJian feb50e7007 🚀 release: 20260327 (#13330)
# 🚀 release: 20260326

This release includes **91 commits**. Key updates are below.


- **Agent can now execute background tasks** — Agents can perform
long-running operations without blocking your conversation.
[#13289](https://github.com/lobehub/lobe-chat/pull/13289)
- **Better error messages** — Redesigned error UI across chat and image
generation with clearer explanations and recovery options.
[#13302](https://github.com/lobehub/lobe-chat/pull/13302)
- **Smoother topic switching** — No more full page reloads when
switching topics while an agent is responding.
[#13309](https://github.com/lobehub/lobe-chat/pull/13309)
- **Faster image uploads** — Large images are now automatically
compressed to 1920px before upload, reducing wait times.
[#13224](https://github.com/lobehub/lobe-chat/pull/13224)
- **Improved knowledge base** — Documents are now properly parsed before
chunking, improving retrieval accuracy.
[#13221](https://github.com/lobehub/lobe-chat/pull/13221)

### Bot Platform

- **WeChat Bot support** — You can now connect LobeChat to WeChat, in
addition to Discord.
[#13191](https://github.com/lobehub/lobe-chat/pull/13191)
- **Richer bot responses** — Bots now support custom markdown rendering
and context injection.
[#13294](https://github.com/lobehub/lobe-chat/pull/13294)
- **New bot commands** — Added `/new` to start fresh conversations and
`/stop` to halt generation.
[#13194](https://github.com/lobehub/lobe-chat/pull/13194)
- **Discord stability fixes** — Fixed thread creation issues and Redis
connection drops.
[#13228](https://github.com/lobehub/lobe-chat/pull/13228)
[#13205](https://github.com/lobehub/lobe-chat/pull/13205)

### Models & Providers

- **GLM-5** is now available in the LobeHub model list.
[#13189](https://github.com/lobehub/lobe-chat/pull/13189)
- **Coding Plan providers** — Added support for code planning assistant
providers. [#13203](https://github.com/lobehub/lobe-chat/pull/13203)
- **Tencent Hunyuan 3.0 ImageGen** — New image generation model from
Tencent. [#13166](https://github.com/lobehub/lobe-chat/pull/13166)
- **Gemini content handling** — Better handling when Gemini blocks
content due to safety filters.
[#13270](https://github.com/lobehub/lobe-chat/pull/13270)
- **Claude token limits fixed** — Corrected max window tokens for
Anthropic Claude models.
[#13206](https://github.com/lobehub/lobe-chat/pull/13206)

### Skills & Tools

- **Auto credential injection** — Skills can now automatically request
and use required credentials.
[#13124](https://github.com/lobehub/lobe-chat/pull/13124)
- **Smarter tool permissions** — Built-in tools skip confirmation for
safe paths like `/tmp`.
[#13232](https://github.com/lobehub/lobe-chat/pull/13232)
- **Model switcher improvements** — Quick access to provider settings
and visual highlight for default model.
[#13220](https://github.com/lobehub/lobe-chat/pull/13220)

### Memory

- **Bulk delete memories** — You can now delete all memory entries at
once. [#13161](https://github.com/lobehub/lobe-chat/pull/13161)
- **Per-agent memory control** — Memory injection now respects
individual agent settings.
[#13265](https://github.com/lobehub/lobe-chat/pull/13265)

### Desktop App

- **Gateway connection** — Desktop app can now connect to LobeHub
Gateway for enhanced features.
[#13234](https://github.com/lobehub/lobe-chat/pull/13234)
- **Connection status indicator** — See gateway connection status in the
titlebar. [#13260](https://github.com/lobehub/lobe-chat/pull/13260)
- **Settings persistence** — Gateway toggle state now persists across
app restarts. [#13300](https://github.com/lobehub/lobe-chat/pull/13300)

### CLI

- **API key authentication** — CLI now supports API key auth for
programmatic access.
[#13190](https://github.com/lobehub/lobe-chat/pull/13190)
- **Shell completion** — Tab completion for bash/zsh/fish shells.
[#13164](https://github.com/lobehub/lobe-chat/pull/13164)
- **Man pages** — Built-in manual pages for CLI commands.
[#13200](https://github.com/lobehub/lobe-chat/pull/13200)

### Security

- **XSS protection** — Sanitized search result image titles to prevent
script injection.
[#13303](https://github.com/lobehub/lobe-chat/pull/13303)
- **Workflow hardening** — Fixed potential shell injection in release
automation. [#13319](https://github.com/lobehub/lobe-chat/pull/13319)
- **Dependency update** — Updated nodemailer to address security
advisory. [#13326](https://github.com/lobehub/lobe-chat/pull/13326)

### Bug Fixes

- Fixed skill page not redirecting correctly after import.
[#13255](https://github.com/lobehub/lobe-chat/pull/13255)
[#13261](https://github.com/lobehub/lobe-chat/pull/13261)
- Fixed token counting in group chats.
[#13247](https://github.com/lobehub/lobe-chat/pull/13247)
- Fixed editor not resetting when switching to empty pages.
[#13229](https://github.com/lobehub/lobe-chat/pull/13229)
- Fixed manual tool toggle not working.
[#13218](https://github.com/lobehub/lobe-chat/pull/13218)
- Fixed Search1API response parsing.
[#13207](https://github.com/lobehub/lobe-chat/pull/13207)
[#13208](https://github.com/lobehub/lobe-chat/pull/13208)
- Fixed mobile topic menus rendering issues.
[#12477](https://github.com/lobehub/lobe-chat/pull/12477)
- Fixed history count calculation for accurate context.
[#13051](https://github.com/lobehub/lobe-chat/pull/13051)
- Added missing Turkish translations.
[#13196](https://github.com/lobehub/lobe-chat/pull/13196)

### Credits

Huge thanks to these contributors:

@bakiburakogun @hardy-one @Zhouguanyang @sxjeru @hezhijie0327 @arvinxx
@cy948 @CanisMinor @Innei @LiJian @lobehubbot @Neko @rdmclin2
@rivertwilight @tjx666
2026-03-27 16:04:56 +08:00
ONLY-yours 97987229a8 feat: skills collection list & detail connect pages init 2026-03-27 15:45:41 +08:00
Zhijie He dc9adf8f10 🐛 fix: fix some features for Github Copilot (ResponseAPI / Vision, etc) (#13279)
* 🐛 fix(github-copilot): switch codex models to responses api

* ♻️ refactor(github-copilot): simplify responses api routing

style: update model list

style: update model list

🐛 fix: align github copilot payload mapping and tests

style: update model list

style: update model list

* chore: add debug stream support

* refactor: use anthropic sdk for claude

* fix: fix ci error

* fix: fix github copilot reasoning_text chunk

* style: update Raptor mini base config, same as gpt-5-mini

style: update Raptor mini base config, same as gpt-5-mini

style: update Raptor mini base config, same as gpt-5-mini

* style: update model contextWindowTokens

* style: set default reasoning.summary to detailed, default as vscode
2026-03-27 15:13:28 +08:00
Innei 3d592ca70d ♻️ refactor: add generic SafeBoundary error boundary with tiered fallback (#13321)
Introduce a unified SafeBoundary component (silent/alert variants) to
replace scattered custom ErrorBoundary class components. Automatically
wraps Inspector, ContentBlock sub-components, MessageItem, and
EditorCanvas to prevent individual component crashes from propagating
to the entire app.
2026-03-27 15:10:00 +08:00
LobeHub Bot 8d0ac45476 🌐 chore: translate non-English comments to English in packages/openapi (#13329)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 14:15:46 +08:00
Rdmclin2 953033355b 🔨 chore: optimize bot platform ux (#13262)
* chore: remove typing interval

* chore: optimize wechat media problem

* chore: add webhook helpers

* chore: update telegram docs

* chore: extract wechat credentials to custom render form

* feat: support wechat file upload

* feat: support concurrency mode and debounceMs

* chore: add locales

* chore: support visible then

* chore: support auto disapear save result info

* chore: default debounce mode

* chore: optimize doc position

* chore: adjust ack message logic

* fix: aes throw
2026-03-27 13:28:52 +08:00
sxjeru 48b5927024 💄 style: enhance handling of blocked content on Gemini (#13270)
*  feat: improve error messages for Google AI block reasons and enhance handling of blocked content

*  feat: add error localization for Google provider in createAgentExecutors
2026-03-27 10:51:01 +08:00
renovate[bot] 6e86912e7f Update dependency nodemailer to ^7.0.13 [SECURITY] (#13326)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-03-27 10:34:22 +08:00
Arvin Xu 4576059f4f ♻️ refactor: implement SkillResolver, BaseSystemRoleProvider, and agent document injection pipeline (#13315)
* ♻️ refactor: implement SkillResolver to replace ad-hoc skill assembly

Introduces a two-layer skill resolution architecture mirroring ToolsEngine + ToolResolver:

- SkillEngine (assembly layer): accepts raw skills + enableChecker, outputs OperationSkillSet
- SkillResolver (resolution layer): merges operation + step delta + accumulated activations

Key changes:
- Add SkillResolver, OperationSkillSet, StepSkillDelta, ActivatedStepSkill types
- Enhance SkillEngine with enableChecker and generate() method
- Wire SkillResolver into RuntimeExecutors call_llm
- Replace manual skillMetas assembly in aiAgent with SkillEngine.generate()
- Update client-side skillEngineering to use SkillEngine + enableChecker
- Add activatedStepSkills to AgentState for step-level skill accumulation

Fixes: agent-browser content injected into non-desktop scenarios (Discord bot)
due to missing filterBuiltinSkills call in aiAgent

LOBE-6410

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: extract agent-templates to standalone package and inject documents server-side

- Create @lobechat/agent-templates package with types, templates, and registry
- Move DocumentLoadPosition, DocumentLoadFormat, DocumentLoadRule, etc. to new package
- Move claw templates (AGENTS, BOOTSTRAP, IDENTITY, SOUL) with .md file imports
- Add BOOTSTRAP.md as new onboarding template (priority 1, system-append)
- Fix template positions: AGENTS→before-system, IDENTITY/SOUL→system-append
- Update database package to re-export from @lobechat/agent-templates
- Migrate all consumers to import directly from @lobechat/agent-templates
- Add agent documents injection in server-side RuntimeExecutors (was missing)
- Support -p CLI flag in devStartupSequence for port configuration

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: correct import statement for non-type exports from agent-templates

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 📦 build: add @lobechat/agent-templates to root dependencies

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: remove template proxy files from database package

Stop re-exporting template/templates from database — consumers import
directly from @lobechat/agent-templates. Keep types.ts re-exports for
internal database code only.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: create BaseSystemRoleProvider to unify system message append pattern

All providers that append to the system message now inherit from
BaseSystemRoleProvider and only implement buildSystemRoleContent().
The base class handles find-or-create and join logic.

Migrated providers:
- EvalContextSystemInjector
- BotPlatformContextInjector
- SystemDateProvider
- ToolSystemRoleProvider
- HistorySummaryProvider
- SkillContextProvider

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: restore metadata tracking in BaseSystemRoleProvider via onInjected hook

Add onInjected() callback to BaseSystemRoleProvider so subclasses can
update pipeline metadata after successful injection. Also add raw-md
plugin to context-engine vitest config for .md imports.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  feat: add enabled field to AgentDocumentInjector config

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: add enabled field to all providers, remove spread conditionals in MessagesEngine

All providers now accept an `enabled` config field. MessagesEngine
pipeline is a flat array with no spread conditionals — each provider
is always instantiated and uses `enabled` to skip internally.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 💄 style: clean up MessagesEngine pipeline comments

Remove numbered prefixes, keep descriptive comments for each provider.
Only phase headers use separator blocks.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: reorganize MessagesEngine pipeline phases by injection target

Phase 1: History Truncation
Phase 2: System Message Assembly (all BaseSystemRoleProvider)
Phase 3: Context Injection (before first user message, BaseFirstUserContentProvider)
Phase 4: User Message Augmentation (last user message injections)
Phase 5: Message Transformation (flatten, template, variables)
Phase 6: Content Processing & Cleanup (multimodal, tool calls, cleanup)

Moved SkillContext, ToolSystemRole, HistorySummary from Phase 3 to
Phase 2 since they append to system message, not user context.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 💄 style: split Phase 6 into Content Processing (6) and Cleanup (7)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: split AgentDocumentInjector into three position-based injectors

- AgentDocumentSystemInjector (Phase 2): before-system, system-append, system-replace
- AgentDocumentContextInjector (Phase 3): before-first-user
- AgentDocumentMessageInjector (Phase 4): after-first-user, context-end

Shared utilities (filterByRules, formatDocument, sortByPriority) extracted
to AgentDocumentInjector/shared.ts. Old monolithic injector removed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: split AgentDocumentSystemInjector into three separate injectors

- AgentDocumentBeforeSystemInjector: prepends as separate system message (before-system)
- AgentDocumentSystemAppendInjector: appends to system message (system-append)
- AgentDocumentSystemReplaceInjector: replaces entire system message (system-replace)

Each has distinct semantics and correct pipeline placement:
- BeforeSystem → before SystemRoleInjector
- SystemAppend → after HistorySummary (end of Phase 2)
- SystemReplace → last in Phase 2 (destructive)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

*  feat: auto-enable agent-documents tool when agent has documents

- Add AgentDocumentsManifest to defaultToolIds
- Add hasAgentDocuments rule in server createServerAgentToolsEngine
- Query agent documents in AiAgentService.execAgent to determine flag
- Pattern matches KnowledgeBase auto-enable via enableChecker rules

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🔨 chore: add agent documents status to execAgent operation log

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* update content

* fix tests

* 🐛 fix: add raw-md plugin to database vitest configs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 10:10:06 +08:00
Arvin Xu 9e9ba3e6c3 🐛 fix: prevent first assistant message re-animation on assistantGroup transition (#13320)
* 🐛 fix: prevent first assistant message re-animation on assistantGroup transition

When tool calls arrive during streaming, the message transitions from
assistant to assistantGroup, causing a full React remount. The first
content block's text was re-animating because isGenerating was still
true. Pass isFirstBlock prop through the render chain to disable
animation for the first block, since its text is guaranteed complete
by the time the group forms.

Fixes LOBE-6414

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: remove redundant isToolSingleLine animation check

isFirstBlock already covers the first block case, and subsequent blocks
should not have animation disabled just because they are single-line
with tools — they may still be streaming.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 01:41:17 +08:00
Innei 46602be0b3 🐛 fix(workflow): prevent shell injection in auto-tag release (#13319) 2026-03-27 01:18:35 +08:00
YuTengjing 14b278fba8 💄 style: add payment upgrade i18n keys and update microcopy (#13317) 2026-03-27 00:51:28 +08:00
Arvin Xu 53c5708c9f 🔨 chore: improve start up scripts (#13318)
update scripts
2026-03-27 00:49:23 +08:00
YuTengjing edc8920703 🔨 chore: temporarily disable notification triggers (#13314) 2026-03-26 23:35:04 +08:00
Arvin Xu 926de076d9 🐛 fix: sanitize search grounding image titles to prevent XSS (#13303)
* 🐛 fix: sanitize search grounding image titles to prevent XSS

Replace dangerouslySetInnerHTML with stripHtml() for image result titles
in SearchGrounding and ImageSearchRef components to prevent stored XSS
attacks via malicious search result data.

Ref: GHSA-m5qx-g8hx-5f2p

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🔒 fix: remove SystemJS plugin renderer to eliminate arbitrary JS execution risk

The old plugin render system (ui.mode === 'module') that used SystemJS
to dynamically load and execute JS from untrusted URLs has been fully
retired. Remove SystemJsRender and systemjs dependency entirely.

Ref: GHSA-46v7-wvmj-6vf7

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Revert "🔒 fix: remove SystemJS plugin renderer to eliminate arbitrary JS execution risk"

This reverts commit 99a7603a72.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 22:38:49 +08:00
Innei 9b7beca85e 💄 style(conversation): align user rich text line height with LexicalRenderer (#13312)
💄 style(conversation): set LexicalRenderer line height in user rich text

Made-with: Cursor
2026-03-26 21:58:24 +08:00
Arvin Xu 0724d8ca60 🐛 fix: prevent full page reload when switching topics during agent execution (#13309)
Move `e.preventDefault()` before the `disabled || loading` early return
in NavItem's onClick handler. Previously, when a NavItem was in disabled
or loading state, the early return skipped `preventDefault()`, allowing
the underlying `<a>` tag's default navigation to trigger a full browser
page load instead of SPA routing.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 21:30:08 +08:00
YuTengjing 9f36fe95ac feat: add notification system (temporarily disabled) (#13301) 2026-03-26 21:16:38 +08:00
Arvin Xu 3f148005e4 ♻️ refactor: remove langchain dependency, use direct document loaders (#13304)
* ♻️ refactor: remove langchain dependency, use direct document loaders

Replace langchain and @langchain/community with self-implemented text
splitters and direct usage of underlying libraries (pdf-parse, d3-dsv,
mammoth, officeparser, epub2). This eliminates unnecessary dependency
bloat and addresses CVE-2026-26019 in @langchain/community.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: add missing @types/html-to-text and @types/pdf-parse

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 21:13:55 +08:00
Arvin Xu 4e60d87514 🔒 refactor: remove deprecated SystemJS plugin renderer (#13305)
🔒 fix: remove SystemJS plugin renderer to eliminate arbitrary JS execution risk

The old plugin render system (ui.mode === 'module') that used SystemJS
to dynamically load and execute JS from untrusted URLs has been fully
retired. Remove SystemJsRender and systemjs dependency entirely.

Ref: GHSA-46v7-wvmj-6vf7

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 20:41:06 +08:00
YuTengjing d2a16d0714 feat: improve error UI and error handling across chat and image generation (#13302) 2026-03-26 20:09:06 +08:00
Arvin Xu 0f04463708 🐛 fix(desktop): persist gateway toggle state across app restarts (#13300)
🐛 fix: persist gateway toggle state across app restarts

The gateway auto-connect logic only checked if the user was logged in,
ignoring whether they had manually disabled the toggle. Added a
`gatewayEnabled` flag to the Electron store that is set on
connect/disconnect and checked before auto-connecting on startup.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 19:31:42 +08:00
Arvin Xu 093fa7bcae feat: support agent tasks system (#13289)
*  feat: agent task system — CLI, review rubrics, workspace, comments, brief tool split

support import md

Major changes:
- Split task CLI into modular files (task/, lifecycle, topic, doc, review, checkpoint, dep)
- Split builtin-tool-task into task + brief tools (conditional injection)
- Task review uses EvalBenchmarkRubric from @lobechat/eval-rubric
- Task workspace: documents auto-pin via Notebook, tree view with folders
- Task comments system (task_comments table)
- Task topics: dedicated TaskTopicModel with userId, handoff fields, review results
- Heartbeat timeout auto-detection in detail API
- Run idempotency (reject duplicate runs) + error rollback
- Topic cancel/delete by topicId only (no taskId needed)
- Integration tests for task router (13 tests)
- interruptOperation fix (string param, not object)
- Global TRPC error handler in CLI

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

task document workflow

task handoff loop

🗃️ chore: consolidate task system migrations into single 0095

Merged 7 separate migrations (0095-0101) into one:
- tasks, briefs, task_comments, task_dependencies, task_documents, task_topics tables
- All fields including sort_order, resolved_action/comment, review fields
- Idempotent CREATE TABLE IF NOT EXISTS, DROP/ADD CONSTRAINT, CREATE INDEX IF NOT EXISTS

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

fix interruptOperation

topic auto review workflow

topic handoff workflow

finish run topic and brief workflow

support task tool

improve task schema

update

 feat: add onComplete hook to task.run for completion callbacks

When agent execution completes, the hook:
- Updates task heartbeat
- Creates a result Brief (on success) with assistant content summary
- Creates an error Brief (on failure) with error message
- Supports both local (handler) and production (webhook) modes

Uses the new Agent Runtime Hooks system instead of raw stepCallbacks.

LOBE-6160 LOBE-6208

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add Review system — LLM-as-Judge automated review

Task review uses an independent LLM call to evaluate topic output
quality against configurable criteria with pass/fail thresholds.

- TaskReviewService: structured LLM review via generateObject,
  auto-resolves model/provider from user's system agent defaults
- Model: getReviewConfig, updateReviewConfig on TaskModel
- Router: getReview, updateReview, runReview procedures
- CLI: `task review set/view/run` commands
- Auto-creates Brief with review results

LOBE-6165

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add TaskScheduler, multi-topic execution, and handoff context

- TaskScheduler: interface + Local implementation (setTimeout-based),
  following QueueService dual-mode pattern
- Multi-topic execution: `task run --topics N --delay S` runs N topics
  in sequence with optional delay between them
- Handoff context: buildTaskPrompt() queries previous topics by
  metadata.taskId and injects handoff summaries into the next topic's
  prompt (sliding window: latest full, older summaries only)
- Heartbeat auto-update between topics

LOBE-6161

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add Heartbeat watchdog + heartbeat CLI

Watchdog scans running tasks with expired heartbeats, marks them as
failed, and creates urgent error Briefs. Heartbeat CLI allows manual
heartbeat reporting for testing.

- Model: refactored to use Drizzle operators (isNull, isNotNull, ne)
  instead of raw SQL where possible; fixed findStuckTasks to skip
  tasks without heartbeat data
- Router: heartbeat (manual report), watchdog (scan + fail + brief)
- Router: updateSchema now includes heartbeatInterval, heartbeatTimeout
- CLI: `task heartbeat <id>`, `task watchdog`, `task edit` with
  --heartbeat-timeout, --heartbeat-interval, --description

LOBE-6161

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

♻️ refactor: move CheckpointConfig to @lobechat/types

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add task run — trigger agent execution for tasks

Task.run creates a topic, triggers AiAgentService.execAgent with task
context, and streams results via SSE. Supports both agentId and slug.

- Service: added taskId to ExecAgentParams, included in topic metadata
- Router: task.run procedure — resolves agent, builds prompt, calls execAgent,
  updates topic count and heartbeat
- CLI: `task run <id>` command with SSE streaming, --prompt, --verbose

LOBE-6160

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add Checkpoint system for task review gates

Checkpoint allows configuring pause points in task execution flow.
Supports beforeIds (pause before subtask starts) and afterIds (pause
after subtask completes) on parent tasks.

- Model: CheckpointConfig type, getCheckpointConfig, updateCheckpointConfig,
  shouldPauseBeforeStart, shouldPauseAfterComplete
- Router: getCheckpoint, updateCheckpoint procedures; integrated with
  updateStatus for automatic checkpoint triggering
- CLI: `task checkpoint view/set` commands with --before, --after,
  --topic-before, --topic-after, --on-agent-request options
- Tests: 3 new checkpoint tests (37 total)

LOBE-6162

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add dependency unlocking on task completion

When a task completes, automatically check and unlock blocked tasks
whose dependencies are all satisfied (backlog → running). Also notify
when all subtasks of a parent are completed.

- Model: getUnlockedTasks, areAllSubtasksCompleted (Drizzle, no raw SQL)
- Router: updateStatus hook triggers unlocking on completion
- CLI: shows unlocked tasks and parent completion notification
- Tests: 3 new tests (34 total)

LOBE-6164

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add Brief system — schema, model, router, CLI

Brief is a universal Agent-to-User reporting mechanism, not limited to
Tasks. CronJobs, Agents, and future systems can all produce Briefs.

- Schema: briefs table with polymorphic source (taskId, cronJobId, agentId)
- Model: BriefModel with CRUD, listUnresolved (Daily Brief), markRead, resolve
- Router: TRPC brief router with taskId identifier resolution
- CLI: `lh brief` command (list/view/read/resolve)
- Tests: 11 model tests
- Migration: 0096_add_briefs_table.sql

LOBE-6163

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

 feat: add Task system — schema, model, router, CLI

Implement the foundational Task system for managing long-running,
multi-topic agent tasks with subtask trees and dependency chains.

- Schema: tasks, task_dependencies, task_documents tables
- Model: TaskModel with CRUD, tree queries, heartbeat, dependencies, document pinning
- Router: TRPC task router with identifier/id resolution
- CLI: `lh task` command (list/view/create/edit/delete/start/pause/resume/complete/cancel/tree/dep)
- Tests: 31 model tests
- Migration: 0095_add_task_tables.sql

LOBE-6036 LOBE-6054

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* update

* 🐛 fix: update brief model import path and add raw-md vitest plugin

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: eslint import sort in vitest config

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: brief ID validation, auto-review retry, and continueTopicId operationId

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: task integration tests — create test agent for FK, fix children spread

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: task integration tests — correct identifier prefix and agent ID

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: remove unused toolsActivatorRuntime import

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: create real topic in task integration tests to satisfy FK constraint

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: type errors in task prompt tests, handoff schema, and activity mapping

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: create real agent/topic/brief records in database model tests for FK constraints

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 17:43:51 +08:00
ONLY-yours 4aa6dcd01a refactor: change the skills to new vision 2026-03-26 17:38:15 +08:00
lobehubbot ac8a9ec0f8 🔖 chore(release): release version v2.1.46 [skip ci] 2026-03-26 09:07:05 +00:00
lobehubbot aa48b856fb Merge remote-tracking branch 'origin/main' into canary 2026-03-26 09:05:30 +00:00
YuTengjing b4d27c7232 🗃️ db: add notification tables (#13295)
🗃️ db: add notification tables migration (UUID, with indexes)
2026-03-26 17:04:47 +08:00
Rdmclin2 dd192eda3e feat: bot support custom markdown render and context injection (#13294)
* feat: support  bot mardown format

* feat: support custom markdownRender and bot context inject

* feat: support custom PORT

* feat: telegram support html render

* feat: slack support markdown render

* chore: feishu and lark don't handle markdown for now
2026-03-26 16:52:35 +08:00
huangkairan c6b0f868ef 🐛 fix: skill page redirect & activeTab handling in Details component (#13255) 2026-03-26 15:39:43 +08:00
Arvin Xu 3bea920193 🔁 chore: sync main branch to canary (#13286)
## Summary
- Sync main branch (v2.1.44 + v2.1.45 releases, agent task system DB
schema) into canary
- Resolved Body.tsx merge conflict by keeping canary version
2026-03-26 15:03:02 +08:00
arvinxx ca16a40a44 Merge remote-tracking branch 'origin/main' into sync/main-to-canary-20260326-v2
# Conflicts:
#	src/routes/(main)/agent/channel/detail/Body.tsx
2026-03-26 15:01:04 +08:00
lobehubbot 59e19310fe 🔖 chore(release): release version v2.1.45 [skip ci] 2026-03-26 05:58:23 +00:00
Arvin Xu b005a9c73b 👷 build: add agent task system database schema (#13280)
* 🗃️ chore: add agent task system database schema

Add 6 new tables for the Agent Task System:
- tasks: core task with tree structure, heartbeat, scheduling
- task_dependencies: inter-task dependency graph (blocks/relates)
- task_documents: MVP workspace document pinning
- task_topics: topic tracking with handoff (jsonb) and review results
- task_comments: user/agent comments with author tracking (text id: cmt_)
- briefs: unresolved notification system (text id: brf_)

All sub-tables include userId FK for row-level user isolation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🗃️ chore: add self-referential FK on tasks.parentTaskId (ON DELETE SET NULL)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: use foreignKey() for self-referential parentTaskId to avoid TS circular inference

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🗃️ chore: add FK on task_topics.topic_id → topics.id (ON DELETE SET NULL)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: resolve pre-existing TS type-check errors

- Fix i18next defaultValue type (string | null → string)
- Fix i18next options type mismatches
- Fix fieldTags.webhook possibly undefined

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🗃️ chore: add FK on tasks.currentTopicId → topics.id (ON DELETE SET NULL)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🗃️ chore: add FK constraints for assignee, author, topic, and parent fields

- tasks.assigneeUserId → users.id (ON DELETE SET NULL)
- tasks.assigneeAgentId → agents.id (ON DELETE SET NULL)
- tasks.parentTaskId → tasks.id (ON DELETE SET NULL)
- tasks.currentTopicId → topics.id (ON DELETE SET NULL)
- task_comments.authorUserId → users.id (ON DELETE SET NULL)
- task_comments.authorAgentId → agents.id (ON DELETE SET NULL)
- task_topics.topicId → topics.id (ON DELETE SET NULL)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🗃️ chore: change task_topics.topicId FK to ON DELETE CASCADE

Topic deleted → task_topic mapping row removed (not just nulled).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: use inline .references() for currentTopicId FK

No circular inference issue — only parentTaskId (self-ref) needs foreignKey().

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🗃️ chore: add FK on task_comments.briefId and topicId (ON DELETE SET NULL)

- task_comments.briefId → briefs.id (SET NULL)
- task_comments.topicId → topics.id (SET NULL)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: merge briefs table into task.ts to fix circular dependency

brief.ts imported task.ts (briefs.taskId FK) and task.ts imported
brief.ts (taskComments.briefId FK), causing circular dependency error.
Merged briefs into task.ts since briefs are part of the task system.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🗃️ chore: add FK on tasks.createdByAgentId → agents.id (ON DELETE SET NULL)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 13:56:01 +08:00
Rdmclin2 2c657670fe 🐛 fix: skill import url and github address problem (#13261)
* chore: optimize github import placeholder and hint

* fix: support import a github hosted skill.md url

* fix:  reimport skill problem

* fix: github zip url file correctly resovled

* fix:  empty content

* fix: test case

* fix: regex lint
2026-03-26 11:28:31 +08:00
Rylan Cai 4dd271c968 feat(cli): support api key auth in cli (#13190)
*  support cli api key auth

* 🔒 reject invalid x-api-key without fallback auth

* ♻️ clean up cli api key auth diff

* ♻️ clean up cli auth command diff

* ♻️ clean up remaining cli auth diff

* ♻️ split stored auth token fields

* ♻️ trim connect auth surface

* ♻️ drop redundant jwt user id carry-over

* ♻️ trim auth test wording diff

* 🐛 fix api key model imports

* 🐛 fix api key util subpath import

* 🔐 chore(cli): use env-only api key auth

* ♻️ refactor(cli): simplify auth credential flow

*  feat: simplify cli api key login flow

* 🐛 fix(cli): prefer jwt for webapi auth

* ♻️ refactor(cli): trim auth http diff

* 🐛 fix(cli): skip api key auth expiry handling

* 🐛 fix(cli): restore non-jwt expiry handling

* ♻️ refactor(cli): trim connect auth expired diff

* ♻️ refactor(cli): trim login comment diff

* ♻️ refactor(cli): trim resolve token comment diff

* ♻️ refactor(cli): restore connect expiry flow

* ♻️ refactor(cli): trim login api key message

* 🐛 fix(cli): support api key gateway auth

* ♻️ refactor(cli): restore resolve token comment

* ♻️ refactor(cli): trim test-only auth diffs

* ♻️ refactor(cli): restore resolve token comments

*  test(cli): add api key expiry coverage

* 🐛 fix cli auth server resolution and gateway auth

* ♻️ prune auth fix diff noise

* ♻️ unify cli server url precedence

* ♻️ simplify device gateway auth tests

*  add gateway auth edge case coverage

*  remove low-value gateway auth test

* 🐛 fix api key context test mock typing
2026-03-26 10:11:38 +08:00
Arvin Xu b76db6bcbd 🐛 fix(memory): respect agent-level memory toggle when injecting memories (#13265)
* 🐛 fix(memory): respect agent-level memory toggle when injecting memories

When the user disables the memory toggle in ChatInput (which writes to
agent-level chatConfig.memory.enabled), the actual message-sending path
in chat/index.ts was only checking the user-level memoryEnabled setting,
completely ignoring the agent-level override.

This aligns the injection logic with useMemoryEnabled hook:
agent-level config takes priority, falls back to user-level setting.

Also fix pre-commit hook to use bunx instead of npx to ensure the
correct ESLint version (v10) is used in monorepo context.

Adds regression tests verifying all three priority scenarios.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update pre-commit

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 01:51:56 +08:00
Innei 84674b1e10 feat(builtin-tool-local-system): skip intervention for safe paths like /tmp (#13232)
*  feat(builtin-tool-local-system): skip intervention for safe paths like /tmp

Add SAFE_PATH_PREFIXES whitelist to bypass user confirmation for
file operations targeting ephemeral directories (/tmp, /var/tmp).

* Fix intervention audit tests

* Move fs checks into Electron
2026-03-26 01:38:36 +08:00
LobeHub Bot 1cb13d9f93 test: add unit tests for mcpStore selectors (#13240)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 01:19:27 +08:00
Arvin Xu 169f11b63b feat(desktop): add device gateway status indicator in titlebar (#13260)
* support desktop gateway

* support device mode

*  feat(desktop): add device gateway status indicator in titlebar

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

*  test(desktop): update getDeviceInfo test to include name and description fields

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ✏️ chore(i18n): update gateway status copy to reference Gateway instead of cloud

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ✏️ chore(i18n): translate Gateway to 网关 in zh-CN

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ✏️ chore(i18n): simplify description placeholder to Optional

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ✏️ chore(desktop): use fixed title 'Connect to Gateway' in device popover

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 01:14:08 +08:00
Arvin Xu 2c7a3f934d 🐛 fix: use display messages for token counting in group chats (#13247)
* 🐛 fix: use partial-json fallback in ToolArgumentsRepairer to recover incomplete args

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: use display messages for token counting in group chats

The TokenTag component used dbMessageSelectors.activeDbMessages which
generates a key without groupId, causing empty results in group chats.
This made the Context Details token tag invisible for group agents.

Switch to using the messageString prop (from mainAIChatsMessageString)
which correctly includes groupId in its key generation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 00:59:45 +08:00
YuTengjing a1e91ab30d test: add tests for topic updatedTime grouping (#13249) 2026-03-25 19:46:40 +08:00
Rdmclin2 4a7c89ec25 fix: discord not create thread & wechat media and connect optimize (#13228)
* fix: avoid subscribe whole channel

* chore: add start message whatever

* chore: remove typing interval

* feat: support typing keep alive

* fix: wechat redis client

* feat: add common gateway

* chore: use persistent to replace websocket

* chore: add wechat tip

* fix: add queue Handoff Succeeded stop typing

* feat: optimize connect status display and wechat connect infomation

* chore: wechat maximum 2048

* feat: support wechat files type

* feat: support wechat image upload

* feat: support wechat image resolve

* fix: lint error

* fix: lint error

* fix: postProcessUrl test case

* chore: moke file service

* chore: add page test case timeout
2026-03-25 18:43:45 +08:00
Neko 684a186e3b 🐛 fix(agent-runtime): missing agentId in context (#13250)
Authored-by-agent: Codex <267193182+codex@users.noreply.github.com>
2026-03-25 18:41:14 +08:00
Rdmclin2 e8a948cfaf style: replace plugin icon with skill icon (#13252)
chore: replace plugin icon  with skill icon
2026-03-25 18:21:36 +08:00
YuTengjing 11daf645e9 💄 style: unlock downgrade restrictions i18n and copy improvements (#13241)
* 💬 chore: add i18n keys for unlocking downgrade restrictions

Add subscription i18n keys:
- plans.downgradeWillCancel: warning shown when action cancels pending downgrade
- plans.pendingDowngrade: button text for pending downgrade target
- Update plans.downgradeTip to reflect cancellation context

LOBE-6155

* 🐛 fix: close model switch panel on clicking multi-provider item in generation mode

* 🌐 i18n: add cancel downgrade schedule translations

* 💄 style: simplify menu and tab labels for billing, credits, and usage

* 💄 style: rename switch success to downgrade and update copy

* 🌐 i18n: add switchDowngradeTarget translation key

* 🌐 i18n: sync translations for downgrade schedule keys
2026-03-25 16:44:49 +08:00
Rdmclin2 a4a03eadc4 chore: remove like github star footer (#13246) 2026-03-25 16:29:04 +08:00
Innei 04ddb992d1 🐛 fix(desktop): add missing Stats and Creds tabs to Electron componentMap (#13243) 2026-03-25 16:27:37 +08:00
LobeHub Bot 991de25b97 🌐 chore: translate non-English comments to English in packages/openapi (#13184)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 15:42:28 +08:00
Arvin Xu 056f390abc 🐛 fix: use partial-json fallback in ToolArgumentsRepairer to recover incomplete args (#13239)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 13:50:34 +08:00
Rdmclin2 9b9949befa chore: remove runtime config in agent builder and doc writer (#13238) 2026-03-25 12:54:35 +08:00
LobeHub Bot 366b02bb46 test: add unit tests for topicReference serverRuntime (#13055)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 12:31:45 +08:00
Hardy ad2087cf65 feat: add Coding Plan providers support (#13203)
*  feat: add Aliyun Bailian Coding Plan provider

- Add new AI provider for Bailian Coding Plan (coding.dashscope.aliyuncs.com/v1)
- Support 8 coding-optimized models: Qwen3.5 Plus, Qwen3 Coder Plus/Next, Qwen3 Max, GLM-5/4.7, Kimi K2.5, MiniMax M2.5
- Reuse QwenAIStream for stream processing
- Static model list (Coding Plan does not support API model fetching)
- Add i18n translations for provider description

*  feat: add MiniMax Coding Plan provider

- Add new AI provider for MiniMax Token Plan (api.minimax.io/v1)
- Support 6 models: MiniMax-M2.7, M2.7-highspeed, M2.5, M2.5-highspeed, M2.1, M2
- Static model list (Coding Plan does not support API model fetching)
- Add i18n translations for provider description

*  feat: add GLM Coding Plan provider

- Add new AI provider for GLM Coding Plan (api.z.ai/api/paas/v4)
- Support 6 models: GLM-5, GLM-5-Turbo, GLM-4.7, GLM-4.6, GLM-4.5, GLM-4.5-Air
- Static model list (Coding Plan does not support API model fetching)
- Add i18n translations for provider description

*  feat: add Kimi Code Plan provider

- Add new AI provider for Kimi Code Plan (api.moonshot.ai/v1)
- Support 3 models: Kimi K2.5, Kimi K2, Kimi K2 Thinking
- Static model list (Coding Plan does not support API model fetching)
- Add i18n translations for provider description

*  feat: add Volcengine Coding Plan provider

- Add new AI provider for Volcengine Coding Plan (ark.cn-beijing.volces.com/api/coding/v3)
- Support 5 models: Doubao-Seed-Code, Doubao-Seed-Code-2.0, GLM-4.7, DeepSeek-V3.2, Kimi-K2.5
- Static model list (Coding Plan does not support API model fetching)
- Add i18n translations for provider description

*  feat: update coding plan providers default enabled models and configurations

*  feat: add reasoningBudgetToken32k and reasoningBudgetToken80k slider variants

- Add ReasoningTokenSlider32k component (max 32*1024)
- Add ReasoningTokenSlider80k component (max 80*1024)
- Add reasoningBudgetToken32k and reasoningBudgetToken80k to ExtendParamsType
- Update ControlsForm to render appropriate slider based on extendParams
- Update ExtendParamsSelect with new options and previews
- Fix ReasoningTokenSlider max value to use 64*Kibi (65536) instead of 64000

* 🔧 fix: support reasoningBudgetToken32k/80k in ControlsForm and modelParamsResolver

- Add reasoningBudgetToken32k and reasoningBudgetToken80k fields to chatConfig type and schema
- Update ControlsForm to use correct name matching for 32k/80k sliders
- Add processing logic for 32k/80k params in modelParamsResolver
- Add i18n translations for extendParams hints

* 🎨 style: use linear marks for reasoning token sliders (32k/80k)

- Switch from log2 scale to linear scale for equal mark spacing
- Add minWidth/maxWidth constraints to limit slider length
- Fix 64k and 80k marks being too close together

* 🎨 fix: use equal-spaced index for reasoning token sliders (32k/80k)

- Slider uses index [0,1,2,3,...] for equal mark spacing
- Map index to token values via MARK_TOKENS array
- Add minWidth/maxWidth to limit slider length when marks increase

*  feat: add reasoningBudgetToken32k for GLM-5 and GLM-4.7 in Bailian Coding Plan

* 🔧 fix: update coding plan API endpoints and model configurations

- minimaxCodingPlan: change API URL to api.minimaxi.com (China site)
- kimiCodingPlan: change API URL to api.kimi.com/coding/v1
- volcengineCodingPlan: update doubao-seed models with correct deploymentName, pricing
- volcengineCodingPlan: add minimax-m2.5 model
- bailianCodingPlan & volcengineCodingPlan: remove unsupported extendParams from minimax-m2.5

*  feat: add Coding Plan tag to provider cards with i18n support

* ♻️ refactor: set showModelFetcher to false for Bailian Coding Plan

- Coding Plan does not support fetching model list via API
- Set both modelList.showModelFetcher and settings.showModelFetcher to false

* 🔧 fix: correct Coding Plan exports case in package.json

*  feat: update coding plan models with releasedAt and remove pricing

* 🔧 fix: remove unsupported reasoning abilities from MiniMax Coding Plan models

* 🐛 fix(modelParamsResolver): fix reasoningBudgetToken32k/80k not being read when enableReasoning is present

- Add nested logic to check which budget field (32k/80k/generic) the model supports when enableReasoning is true
- Move reasoningBudgetToken32k/80k else-if branches before reasoningBudgetToken to ensure correct field is read
- Fix GLM-5/GLM-4.7 models sending wrong budget_tokens value to API
2026-03-25 11:53:16 +08:00
LobeHub Bot 0689dd68a3 🌐 chore: translate non-English comments to English in routes and layout (#13210)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 11:52:28 +08:00
LobeHub Bot 75ea33153f 🌐 chore: translate non-English comments to English in packages/agent-runtime (#13236)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 11:51:28 +08:00
YuTengjing dbff1e0668 🐛 fix: default topic display mode to byUpdatedTime and fix nanoBanana2 resolution enum (#13235) 2026-03-25 11:17:41 +08:00
LobeHub Bot afefe217db test: add unit tests for eval-dataset-parser (#13197)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 10:55:58 +08:00
Arvin Xu fed8b39957 feat: desktop support connect to gateway (#13234)
* support desktop gateway

* support device mode

* support desktop

* fix tests

* improve

* fix tests

* fix tests

* fix case
2026-03-25 10:43:15 +08:00
Rdmclin2 f853537695 Add /new and /stop slash commands for bot message management (#13194)
*  feat(bot): implement /new and /stop slash commands

Add Chat SDK slash command handlers for bot integrations:
- /new: resets conversation state so the next message starts a fresh topic
- /stop: cancels any active agent execution on the current thread

https://claude.ai/code/session_01MDofskrz64tRjh2T6xzGBL

* feat: support telegram text type  commands

* fix: stop commands

* feat: register discord slash commands

* feat: add chat adapter patch

* feat: add interuption action

* chore: add agent thread interuption signal

* chore: optimize interruption result

* fix: /stop command message edit

* chore: create a message when interrupted

* chore: add bot test case

* chore: fix test case

* chore: fix test case and remove duplicate completion

* fix: lint error

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-25 00:31:01 +08:00
Baki Burak Öğün 0cdaf117cb 🌐 fix(locale): translate missing Turkish (tr-TR) strings (#13196)
fix(locale): translate missing Turkish (tr-TR) strings in setting.json

- Translate agentCronJobs.clearTopics, clearTopicsFailed, confirmClearTopics
- Translate agentCronJobs.confirmDeleteCronJob, deleteCronJob, deleteFailed

Co-authored-by: bakiburakogun <bakiburakogun@users.noreply.github.com>
2026-03-25 00:11:55 +08:00
Innei ada555789d 🐛 fix(editor): reset editor state when switching to empty page (#13229)
Fixes LOBE-6321
2026-03-24 21:37:08 +08:00
Arvin Xu 007d2dc554 🐛 fix: compress uploaded images to max 1920px before sending to API (#13224)
* 🐛 fix: compress uploaded images to max 1920px before sending to API

Anthropic API rejects images exceeding 2000px in multi-image requests.
Compress images during upload to stay within limits while preserving
original aspect ratio and format (no webp conversion).

Fixes LOBE-6315

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: skip canvas compression for GIF and SVG images

Canvas serialization flattens animated GIFs and rasterizes SVGs.
Restrict compression to safe raster formats: JPEG, PNG, WebP.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: always compress images to PNG to avoid MIME mismatch

canvas.toDataURL with original file type can produce content that
doesn't match the declared MIME type, causing Anthropic API errors.
Always output PNG which is universally supported and consistent.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* 🐛 fix: progressively shrink images to stay under 5MB API limit

If compressed PNG still exceeds 5MB, progressively reduce dimensions
by 20% until it fits. Also triggers compression for small-dimension
images that exceed 5MB file size.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ♻️ refactor: extract compressImageFile to utils and add comprehensive tests

Move compressImageFile, COMPRESSIBLE_IMAGE_TYPES, and constants to
@lobechat/utils/compressImage for reusability and testability.
Add tests for: dimension compression, file size limit, format filtering,
error handling, and progressive shrinking.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:23:58 +08:00
Innei 995d5ea354 🐛 fix(conversation): preserve mention runtime context (#13223)
* 🐛 fix(conversation): preserve mention context on retry

* 🐛 fix(runtime): preserve initial payload for mention context

*  feat(store): expose Zustand stores on window.__LOBE_STORES in dev

Made-with: Cursor
2026-03-24 19:50:26 +08:00
Arvin Xu 72ba8c8923 🐛 fix: add document parsing to knowledge base chunking pipeline (#13221)
* 🐛 fix: add document parsing to knowledge base chunking pipeline

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix plugin title

* update

* 🐛 fix: add missing findByFileId mock in document service tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 19:49:26 +08:00
YuTengjing 6f65b1e65e feat: improve model switch panel with provider settings shortcut and default highlight (#13220) 2026-03-24 16:30:38 +08:00
YuTengjing 383caceb77 ♻️ refactor: rename getBusinessMenuItems to useBusinessMenuItems hook (#13219) 2026-03-24 15:58:29 +08:00
Rdmclin2 b4862f2942 🐛 fix: manual tool disabled (#13218)
fix: manual tool disabled
2026-03-24 15:24:18 +08:00
YuTengjing d1affa8e44 🌐 feat(i18n): add userPanel.upgradePlan i18n key (#13213) 2026-03-24 15:20:34 +08:00
Innei 6e3053fcb3 feat(cli): add generated man pages (#13200) 2026-03-24 14:46:56 +08:00
Innei b845ba4476 🔨 chore(vite): support direct markdown imports (#13216)
 feat(vite): support markdown imports
2026-03-24 14:33:57 +08:00
LiJian 7c00650be5 ♻️ refactor: add the user creds modules & skill should auto inject the need creds (#13124)
* feat: add the user creds modules & skill should auto inject the need creds

* feat: add the builtin creds tools

* fix: add some prompt in creds & codesandbox

* fix: open this settings/creds in community plan

* fix: refacoter the settings/creds the ui

* feat: improve the tools inject system Role

* feat: change the settings/creds mananger ui

* fix: add the creds upload Files api

* feat: should call back the files creds url
2026-03-24 14:28:23 +08:00
Innei 5bc015a746 🐛 fix: move nodrag from TabBar container to individual TabItems (#13211) 2026-03-24 11:33:00 +08:00
Arvin Xu 6757e10ec2 🐛 fix: map unsupported time_range values for Search1API (#13208)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 09:22:04 +08:00
Arvin Xu 48428594c3 🐛 fix: correct Search1API response parsing to match actual API format (#13207)
* 🐛 fix: correct Search1API response parsing to match actual API format

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix tests

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 02:18:28 +08:00
Innei 6a45414b46 🐛 fix(electron): reserve titlebar control space (#13204)
* 🐛 fix(electron): reserve titlebar control space

* 🐛 fix(electron): update titlebar padding for Windows control space
2026-03-23 23:29:55 +08:00
Arvin Xu 0f53490633 🐛 fix: fix anthropic claude model max window tokens (#13206)
* fix anthropic max tokens

* fix anthropic max tokens

* clean

* fix tests
2026-03-23 23:01:31 +08:00
Rdmclin2 66fba60194 fix: add discord redisClient lost problem (#13205) 2026-03-23 21:13:03 +08:00
YuTengjing fadaeef8d3 feat: add GLM-5 model support to LobeHub provider (#13189) 2026-03-23 17:46:32 +08:00
CanisMinor 3c5249eae7 📝 docs: fix agent usage typo (#13198)
docs: fix agent usage
2026-03-23 14:14:58 +08:00
Innei 9eca3d2ec0 ♻️ refactor(store): replace dynamic imports with static imports in actions (#13159)
Made-with: Cursor
2026-03-23 14:11:04 +08:00
Innei 4e89a00d2a feat(cli): add shell completion and migrate to tsdown (#13164)
* 👷 build(cli): migrate bundler from tsup to tsdown

Made-with: Cursor

* 🔧 chore(cli): update package.json and tsdown.config.ts dependencies

- Moved several dependencies from "dependencies" to "devDependencies" in package.json.
- Updated the bundling configuration in tsdown.config.ts to simplify the bundling process.

Signed-off-by: Innei <tukon479@gmail.com>

* 🔧 chore(cli): reorganize package.json and tsdown.config.ts

- Moved "fast-glob" from "dependencies" to "devDependencies" in package.json for better clarity.
- Removed the "onlyBundle" option from tsdown.config.ts to streamline the configuration.

Signed-off-by: Innei <tukon479@gmail.com>

*  feat(cli): add shell completion support

---------

Signed-off-by: Innei <tukon479@gmail.com>
2026-03-23 14:10:39 +08:00
LobeHub Bot 89a0211adf 🌐 chore: translate non-English comments to English in plugindevmodal and image-config (#13169)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 13:29:46 +08:00
Rdmclin2 ecde45b4ce feat: support wechat bot (#13191)
* feat: support weixin channel

* chore: rename to wechat

* chore: refact wechat adapter with ilink spec

* feat: add qrcode generate and refresh

* chore: update wechat docs

* fix: qrcode

* chore: remove developer mode restrict

* fix: wechat link error

* chore: add thread typing

* chore: support skip progressMessageId

* fix: discord eye reaction

* chore: resolve CodeQL regex rule

* test: add chat adapter wechat test case

* chore: wechat refresh like discord

* fix: perist token and add typing action

* chore: bot cli support weixin

* fix: database test case
2026-03-23 12:52:11 +08:00
LiJian 1df02300bc 🐛 fix: add the lost desktop community skill page (#13170)
fix: add the lost desktop community skill page
2026-03-23 10:48:47 +08:00
Rdmclin2 637ef4a84e 🔨 chore: remove default calculator (#13162)
* chore: remove calculator from RECOMMENDED_SKILLS

* chore: add default uninstalled builtin list

* fix: ensure uninstall tool loaded

* fix: lint error
2026-03-22 23:15:59 +08:00
lobehubbot b53abaa3b2 🔖 chore(release): release version v2.1.44 [skip ci] 2026-03-20 10:39:27 +00:00
1790 changed files with 131376 additions and 13961 deletions
+69 -4
View File
@@ -200,20 +200,85 @@ The base directory (`~/.lobehub/`) can be overridden with the `LOBEHUB_CLI_HOME`
## Development
### Running in Dev Mode
Dev mode uses `LOBEHUB_CLI_HOME=.lobehub-dev` to isolate credentials from the global `~/.lobehub/` directory, so dev and production configs never conflict.
```bash
# Run directly (dev mode, uses ~/.lobehub-dev for credentials)
# Run a command in dev mode (from apps/cli/)
cd apps/cli && bun run dev -- <command>
# Build
# This is equivalent to:
LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts <command>
```
### Connecting to Local Dev Server
To test CLI against a local dev server (e.g. `localhost:3011`):
**Step 1: Start the local server**
```bash
# From cloud repo root
bun run dev
# Server starts on http://localhost:3011 (or configured port)
```
**Step 2: Login to local server via Device Code Flow**
```bash
cd apps/cli && bun run dev -- login --server http://localhost:3011
```
This will:
1. Call `POST http://localhost:3011/oidc/device/auth` to get a device code
2. Print a URL like `http://localhost:3011/oidc/device?user_code=XXXX-YYYY`
3. Open the URL in your browser — log in and authorize
4. Save credentials to `apps/cli/.lobehub-dev/credentials.json`
5. Save server URL to `apps/cli/.lobehub-dev/settings.json`
After login, all subsequent `bun run dev -- <command>` calls will use the local server.
**Step 3: Run commands against local server**
```bash
cd apps/cli && bun run dev -- task list
cd apps/cli && bun run dev -- task create -i "Test task" -n "My Task"
cd apps/cli && bun run dev -- agent list
```
**Troubleshooting:**
- If login returns `invalid_grant`, make sure the local OIDC provider is properly configured (check `OIDC_*` env vars in `.env`)
- If you get `UNAUTHORIZED` on API calls, your token may have expired — run `bun run dev -- login --server http://localhost:3011` again
- Dev credentials are stored in `apps/cli/.lobehub-dev/` (gitignored), not in `~/.lobehub/`
### Switching Between Local and Production
```bash
# Dev mode (local server) — uses .lobehub-dev/
cd apps/cli && bun run dev -- <command>
# Production (app.lobehub.com) — uses ~/.lobehub/
lh <command>
```
The two environments are completely isolated by different credential directories.
### Build & Test
```bash
# Build CLI
cd apps/cli && bun run build
# Test (unit tests)
# Unit tests
cd apps/cli && bun run test
# E2E tests (requires authenticated CLI)
cd apps/cli && bunx vitest run e2e/kb.e2e.test.ts
# Link globally for testing
# Link globally for testing (installs lh/lobe/lobehub commands)
cd apps/cli && bun run cli:link
```
+4
View File
@@ -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?
+2 -6
View File
@@ -101,10 +101,6 @@ DROP TABLE "old_table";
CREATE INDEX "users_email_idx" ON "users" ("email");
```
## Step 4: Regenerate Client After SQL Edits
## Step 4: Update Journal Tag
After modifying the generated SQL (e.g., adding `IF NOT EXISTS`), regenerate the client:
```bash
bun run db:generate:client
```
After renaming the migration SQL file in Step 2, update the `tag` field in `packages/database/migrations/meta/_journal.json` to match the new filename (without `.sql` extension).
+935
View File
@@ -0,0 +1,935 @@
---
name: local-testing
description: >
Local app and bot testing. Uses agent-browser CLI for Electron/web app UI testing,
and osascript (AppleScript) for controlling native macOS apps (WeChat, Discord, Telegram, Slack, Lark/飞书, QQ)
to test bots. Triggers on 'local test', 'test in electron', 'test desktop', 'test bot',
'bot test', 'test in discord', 'test in telegram', 'test in slack', 'test in weixin',
'test in wechat', 'test in lark', 'test in feishu', 'test in qq',
'manual test', 'osascript', or UI/bot verification tasks.
---
# Local App & Bot Testing
Two approaches for local testing on macOS:
| Approach | Tool | Best For |
| --------------------------- | ------------------- | ---------------------------------------------------- |
| **agent-browser + CDP** | `agent-browser` CLI | Electron apps, web apps (DOM access, JS eval) |
| **osascript (AppleScript)** | `osascript -e` | Native macOS apps (WeChat, Discord, Telegram, Slack) |
---
# Part 1: agent-browser (Electron / Web Apps)
Use `agent-browser` to automate Chromium-based apps via Chrome DevTools Protocol.
## Prerequisites
- `agent-browser` CLI installed globally (`agent-browser --version`)
## Core Workflow
### 1. Snapshot → Find Elements
```bash
agent-browser --cdp -i < PORT > snapshot # Interactive elements only
agent-browser --cdp -i -C < PORT > snapshot # Include contenteditable elements
```
Returns element refs like `@e1`, `@e2`. **Refs are ephemeral** — re-snapshot after any page change.
### 2. Interact
```bash
agent-browser --cdp @e5 < PORT > click
agent-browser --cdp @e3 "text" < PORT > type # Character by character (contenteditable)
agent-browser --cdp @e3 "text" < PORT > fill # Bulk fill (regular inputs)
agent-browser --cdp Enter < PORT > press
agent-browser --cdp down 500 < PORT > scroll
```
### 3. Wait
```bash
agent-browser --cdp 2000 < PORT > wait # Wait ms
agent-browser --cdp --load networkidle < PORT > wait # Wait for network
```
For waits >30s, use `sleep N` in bash instead — `agent-browser wait` blocks the daemon.
### 4. Screenshot & Verify
```bash
agent-browser --cdp < PORT > screenshot # Save to ~/.agent-browser/tmp/screenshots/
agent-browser --cdp text @e1 < PORT > get # Get element text
agent-browser --cdp url < PORT > get # Get current URL
```
Read screenshots with the `Read` tool for visual verification.
### 5. Evaluate JavaScript
```bash
agent-browser --cdp "document.title" < PORT > eval
```
For multi-line JS, use `--stdin`:
```bash
agent-browser --cdp --stdin < PORT > eval << 'EVALEOF'
(function() {
return JSON.stringify({ title: document.title, url: location.href });
})()
EVALEOF
```
## Electron (LobeHub Desktop)
### Setup
```bash
# 1. Kill existing instances
pkill -f "Electron" 2> /dev/null
pkill -f "electron-vite" 2> /dev/null
pkill -f "agent-browser" 2> /dev/null
sleep 3
# 2. Start Electron with CDP (MUST cd to apps/desktop first)
cd apps/desktop && ELECTRON_ENABLE_LOGGING=1 npx electron-vite dev -- --remote-debugging-port=9222 > /tmp/electron-dev.log 2>&1 &
# 3. Wait for startup
for i in $(seq 1 12); do
sleep 5
if strings /tmp/electron-dev.log 2> /dev/null | grep -q "starting electron"; then
echo "ready"
break
fi
done
# 4. Wait for renderer, then connect
sleep 15 && agent-browser --cdp 9222 wait 3000
```
**Critical:** `npx electron-vite dev` MUST run from `apps/desktop/` directory, not project root.
### LobeHub-Specific Patterns
#### Access Zustand Store State
```bash
agent-browser --cdp 9222 eval --stdin << 'EVALEOF'
(function() {
var chat = window.__LOBE_STORES.chat();
var ops = Object.values(chat.operations);
return JSON.stringify({
ops: ops.map(function(o) { return { type: o.type, status: o.status }; }),
activeAgent: chat.activeAgentId,
activeTopic: chat.activeTopicId,
});
})()
EVALEOF
```
#### Find and Use the Chat Input
```bash
# The chat input is contenteditable — must use -C flag
agent-browser --cdp 9222 snapshot -i -C 2>&1 | grep "editable"
agent-browser --cdp 9222 click @e48
agent-browser --cdp 9222 type @e48 "Hello world"
agent-browser --cdp 9222 press Enter
```
#### Wait for Agent to Complete
```bash
agent-browser --cdp 9222 eval --stdin << 'EVALEOF'
(function() {
var chat = window.__LOBE_STORES.chat();
var ops = Object.values(chat.operations);
var running = ops.filter(function(o) { return o.status === 'running'; });
return running.length === 0 ? 'done' : 'running: ' + running.length;
})()
EVALEOF
```
#### Install Error Interceptor
```bash
agent-browser --cdp 9222 eval --stdin << 'EVALEOF'
(function() {
window.__CAPTURED_ERRORS = [];
var orig = console.error;
console.error = function() {
var msg = Array.from(arguments).map(function(a) {
if (a instanceof Error) return a.message;
return typeof a === 'object' ? JSON.stringify(a) : String(a);
}).join(' ');
window.__CAPTURED_ERRORS.push(msg);
orig.apply(console, arguments);
};
return 'installed';
})()
EVALEOF
# Later, check captured errors:
agent-browser --cdp 9222 eval "JSON.stringify(window.__CAPTURED_ERRORS)"
```
## Chrome / Web Apps
```bash
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
--remote-debugging-port=9222 \
--user-data-dir=/tmp/chrome-test-profile \
"<URL>" &
sleep 5
agent-browser --cdp 9222 snapshot -i
```
---
# Part 2: osascript (Native macOS App Bot Testing)
Use AppleScript via `osascript` to control native macOS desktop apps for bot testing. This works with any app that supports macOS Accessibility, without needing CDP or Chromium.
## Core osascript Patterns
### Activate an App
```bash
osascript -e 'tell application "Discord" to activate'
```
### Type Text
```bash
# Type character by character (reliable, but slow for long text)
osascript -e 'tell application "System Events" to keystroke "Hello world"'
# Press Enter
osascript -e 'tell application "System Events" to key code 36'
# Press Tab
osascript -e 'tell application "System Events" to key code 48'
# Press Escape
osascript -e 'tell application "System Events" to key code 53'
```
### Paste from Clipboard (fast, for long text)
```bash
# Set clipboard and paste — much faster than keystroke for long messages
osascript -e 'set the clipboard to "Your long message here"'
osascript -e 'tell application "System Events" to keystroke "v" using command down'
```
Or in one shot:
```bash
osascript -e '
set the clipboard to "Your long message here"
tell application "System Events" to keystroke "v" using command down
'
```
### Keyboard Shortcuts
```bash
# Cmd+K (quick switcher in Discord/Slack)
osascript -e 'tell application "System Events" to keystroke "k" using command down'
# Cmd+F (search)
osascript -e 'tell application "System Events" to keystroke "f" using command down'
# Cmd+N (new message/chat)
osascript -e 'tell application "System Events" to keystroke "n" using command down'
# Cmd+Shift+K (example: multi-modifier)
osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}'
```
### Click at Position
```bash
# Click at absolute screen coordinates
osascript -e '
tell application "System Events"
click at {500, 300}
end tell
'
```
### Get Window Info
```bash
# Get window position and size
osascript -e '
tell application "System Events"
tell process "Discord"
get {position, size} of window 1
end tell
end tell
'
```
### Screenshot
```bash
# Full screen
screencapture /tmp/screenshot.png
# Interactive region select
screencapture -i /tmp/screenshot.png
# Specific window (by window ID from CGWindowList)
screencapture -l < WINDOW_ID > /tmp/screenshot.png
```
To get window ID for a specific app:
```bash
osascript -e '
tell application "System Events"
tell process "Discord"
get id of window 1
end tell
end tell
'
```
### Read Accessibility Elements
```bash
# Get all UI elements of the frontmost window (can be slow/large)
osascript -e '
tell application "System Events"
tell process "Discord"
entire contents of window 1
end tell
end tell
'
# Get a specific element's value
osascript -e '
tell application "System Events"
tell process "Discord"
get value of text field 1 of window 1
end tell
end tell
'
```
> **Warning:** `entire contents` can be extremely slow on complex UIs. Prefer screenshots + `Read` tool for visual verification.
### Read Screen Text via Clipboard
For reading the latest message or response from an app:
```bash
# Select all text in the focused area and copy
osascript -e '
tell application "System Events"
keystroke "a" using command down
keystroke "c" using command down
end tell
'
sleep 0.5
# Read clipboard
pbpaste
```
---
## Client: Discord
**App name:** `Discord` | **Process name:** `Discord`
### Activate & Navigate
```bash
# Activate Discord
osascript -e 'tell application "Discord" to activate'
sleep 1
# Open Quick Switcher (Cmd+K) to navigate to a channel
osascript -e 'tell application "System Events" to keystroke "k" using command down'
sleep 0.5
osascript -e 'tell application "System Events" to keystroke "bot-testing"'
sleep 1
osascript -e 'tell application "System Events" to key code 36' # Enter
sleep 2
```
### Send Message to Bot
```bash
# The message input is focused after navigating to a channel
# Type a message
osascript -e 'tell application "System Events" to keystroke "/hello"'
sleep 0.5
osascript -e 'tell application "System Events" to key code 36' # Enter
```
### Send Long Message (via clipboard)
```bash
osascript -e '
tell application "Discord" to activate
delay 0.5
set the clipboard to "Write a 3000 word essay about space exploration"
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36 -- Enter
end tell
'
```
### Verify Bot Response
```bash
# Wait for bot to respond, then screenshot
sleep 10
screencapture /tmp/discord-bot-response.png
# Read with the Read tool for visual verification
```
### Full Bot Test Example
```bash
#!/usr/bin/env bash
# test-discord-bot.sh — Send message and verify bot response
# 1. Activate Discord and navigate to channel
osascript -e '
tell application "Discord" to activate
delay 1
-- Quick Switcher
tell application "System Events" to keystroke "k" using command down
delay 0.5
tell application "System Events" to keystroke "bot-testing"
delay 1
tell application "System Events" to key code 36
delay 2
'
# 2. Send test message
osascript -e '
set the clipboard to "!ping"
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36
end tell
'
# 3. Wait for response and capture
sleep 5
screencapture /tmp/discord-test-result.png
echo "Screenshot saved to /tmp/discord-test-result.png"
```
---
## Client: Slack
**App name:** `Slack` | **Process name:** `Slack`
### Activate & Navigate
```bash
# Activate Slack
osascript -e 'tell application "Slack" to activate'
sleep 1
# Quick Switcher (Cmd+K)
osascript -e 'tell application "System Events" to keystroke "k" using command down'
sleep 0.5
osascript -e 'tell application "System Events" to keystroke "bot-testing"'
sleep 1
osascript -e 'tell application "System Events" to key code 36' # Enter
sleep 2
```
### Send Message to Bot
```bash
# Direct message input (focused after channel nav)
osascript -e 'tell application "System Events" to keystroke "@mybot hello"'
sleep 0.3
osascript -e 'tell application "System Events" to key code 36'
```
### Send Long Message
```bash
osascript -e '
tell application "Slack" to activate
delay 0.5
set the clipboard to "A long test message for the bot..."
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36
end tell
'
```
### Slash Command Test
```bash
osascript -e '
tell application "Slack" to activate
delay 0.5
tell application "System Events"
keystroke "/ask What is the meaning of life?"
delay 0.5
key code 36
end tell
'
```
### Verify Response
```bash
sleep 10
screencapture /tmp/slack-bot-response.png
```
---
## Client: Telegram
**App name:** `Telegram` | **Process name:** `Telegram`
### Activate & Navigate
```bash
# Activate Telegram
osascript -e 'tell application "Telegram" to activate'
sleep 1
# Search for a bot (Cmd+F or click search)
osascript -e '
tell application "System Events"
keystroke "f" using command down
delay 0.5
keystroke "MyTestBot"
delay 1
key code 36 -- Enter to select
end tell
'
sleep 2
```
### Send Message to Bot
```bash
# After navigating to bot chat, input is focused
osascript -e '
tell application "System Events"
keystroke "/start"
delay 0.3
key code 36
end tell
'
```
### Send Long Message
```bash
osascript -e '
tell application "Telegram" to activate
delay 0.5
set the clipboard to "Tell me about quantum computing in detail"
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36
end tell
'
```
### Verify Response
```bash
sleep 10
screencapture /tmp/telegram-bot-response.png
```
### Telegram Bot API (programmatic alternative)
For sending messages directly to the bot's chat without UI:
```bash
# Send message as the bot (for testing webhooks/responses)
curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
-d "chat_id=$CHAT_ID&text=test message"
# Get recent updates
curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates?limit=5" | jq .
```
---
## Client: WeChat / 微信
**App name:** `微信` or `WeChat` | **Process name:** `WeChat`
### Activate & Navigate
```bash
# Activate WeChat
osascript -e 'tell application "微信" to activate'
sleep 1
# Search for a contact/bot (Cmd+F)
osascript -e '
tell application "System Events"
keystroke "f" using command down
delay 0.5
keystroke "TestBot"
delay 1
key code 36 -- Enter to select
end tell
'
sleep 2
```
### Send Message
```bash
# After navigating to a chat, the input is focused
osascript -e '
tell application "System Events"
keystroke "Hello bot!"
delay 0.3
key code 36
end tell
'
```
### Send Long Message (clipboard)
```bash
osascript -e '
tell application "微信" to activate
delay 0.5
set the clipboard to "Please help me with this task..."
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36
end tell
'
```
### Verify Response
```bash
sleep 10
screencapture /tmp/wechat-bot-response.png
```
### WeChat-Specific Notes
- WeChat macOS app name can be `微信` or `WeChat` depending on system language. Try both:
```bash
osascript -e 'tell application "微信" to activate' 2> /dev/null \
|| osascript -e 'tell application "WeChat" to activate'
```
- WeChat uses **Enter** to send (not Cmd+Enter by default, but configurable)
- For multi-line messages without sending, use **Shift+Enter**:
```bash
osascript -e 'tell application "System Events" to key code 36 using shift down'
```
---
## Client: Lark / 飞书
**App name:** `Lark` or `飞书` | **Process name:** `Lark` or `飞书`
### Activate & Navigate
```bash
# Activate Lark (auto-detects Lark or 飞书)
osascript -e 'tell application "Lark" to activate' 2> /dev/null \
|| osascript -e 'tell application "飞书" to activate'
sleep 1
# Quick Switcher / Search (Cmd+K)
osascript -e 'tell application "System Events" to keystroke "k" using command down'
sleep 0.5
osascript -e '
set the clipboard to "bot-testing"
tell application "System Events"
keystroke "v" using command down
delay 1.5
key code 36 -- Enter
end tell
'
sleep 2
```
### Send Message to Bot
```bash
osascript -e '
set the clipboard to "@MyBot help me with this task"
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36 -- Enter
end tell
'
```
### Verify Response
```bash
sleep 10
screencapture /tmp/lark-bot-response.png
```
### Lark-Specific Notes
- App name varies: `Lark` (international) vs `飞书` (China mainland) — the script auto-detects
- Uses `Cmd+K` for quick search (same as Discord/Slack)
- Enter sends message by default
---
## Client: QQ
**App name:** `QQ` | **Process name:** `QQ`
### Activate & Navigate
```bash
osascript -e 'tell application "QQ" to activate'
sleep 1
# Search for contact/group (Cmd+F)
osascript -e '
tell application "System Events"
keystroke "f" using command down
delay 0.8
end tell
'
osascript -e '
set the clipboard to "bot-testing"
tell application "System Events"
keystroke "v" using command down
delay 1.5
key code 36 -- Enter
end tell
'
sleep 2
```
### Send Message to Bot
```bash
osascript -e '
set the clipboard to "Hello bot!"
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36 -- Enter
end tell
'
```
### Verify Response
```bash
sleep 10
screencapture /tmp/qq-bot-response.png
```
### QQ-Specific Notes
- Enter sends message by default; Shift+Enter for newlines
- Uses `Cmd+F` for search
- Always use clipboard paste for CJK characters
---
## Common Bot Testing Workflow (osascript)
Regardless of platform, the pattern is:
```bash
APP_NAME="Discord" # or "Slack", "Telegram", "微信"
CHANNEL="bot-testing"
MESSAGE="Hello bot!"
WAIT_SECONDS=10
# 1. Activate
osascript -e "tell application \"$APP_NAME\" to activate"
sleep 1
# 2. Navigate to channel/chat (via Quick Switcher or Search)
osascript -e 'tell application "System Events" to keystroke "k" using command down'
sleep 0.5
osascript -e "tell application \"System Events\" to keystroke \"$CHANNEL\""
sleep 1
osascript -e 'tell application "System Events" to key code 36'
sleep 2
# 3. Send message
osascript -e "set the clipboard to \"$MESSAGE\""
osascript -e '
tell application "System Events"
keystroke "v" using command down
delay 0.3
key code 36
end tell
'
# 4. Wait for bot response
sleep "$WAIT_SECONDS"
# 5. Screenshot for verification
screencapture /tmp/"${APP_NAME,,}"-bot-test.png
echo "Result saved to /tmp/${APP_NAME,,}-bot-test.png"
```
### Tips
- **Use clipboard paste** (`Cmd+V`) for messages containing special characters or long text — `keystroke` can mangle non-ASCII
- **Add `delay`** between actions — apps need time to process UI events
- **Screenshot for verification** — use `screencapture` + `Read` tool for visual checks
- **Use a dedicated test channel/chat** — avoid polluting real conversations
- **Check app name** — some apps have different names in different locales (e.g., `微信` vs `WeChat`)
- **Accessibility permissions required** — System Events automation requires granting Accessibility access in System Preferences > Privacy & Security > Accessibility
---
# Scripts
Ready-to-use scripts in `.agents/skills/local-testing/scripts/`:
| Script | Usage |
| ------------------------- | --------------------------------------------- |
| `capture-app-window.sh` | Capture screenshot of a specific app window |
| `record-electron-demo.sh` | Record Electron app demo with ffmpeg |
| `test-discord-bot.sh` | Send message to Discord bot via osascript |
| `test-slack-bot.sh` | Send message to Slack bot via osascript |
| `test-telegram-bot.sh` | Send message to Telegram bot via osascript |
| `test-wechat-bot.sh` | Send message to WeChat bot via osascript |
| `test-lark-bot.sh` | Send message to Lark / 飞书 bot via osascript |
| `test-qq-bot.sh` | Send message to QQ bot via osascript |
### Window Screenshot Utility
`capture-app-window.sh` captures a screenshot of a specific app window using `screencapture -l <windowID>`. It uses Swift + CGWindowList to find the window by process name, so screenshots work correctly even when the window is on an external monitor or behind other windows.
```bash
# Standalone usage
./.agents/skills/local-testing/scripts/capture-app-window.sh "Discord" /tmp/discord.png
./.agents/skills/local-testing/scripts/capture-app-window.sh "Slack" /tmp/slack.png
./.agents/skills/local-testing/scripts/capture-app-window.sh "WeChat" /tmp/wechat.png
```
All bot test scripts use this utility automatically for their screenshots.
### Bot Test Scripts
All bot test scripts share the same interface:
```bash
./scripts/test-<platform>-bot.sh <channel_or_contact> <message> [wait_seconds] [screenshot_path]
```
Examples:
```bash
# Discord — test a bot in #bot-testing channel
./.agents/skills/local-testing/scripts/test-discord-bot.sh "bot-testing" "!ping"
./.agents/skills/local-testing/scripts/test-discord-bot.sh "bot-testing" "/ask Tell me a joke" 30
# Slack — test a bot in #bot-testing channel
./.agents/skills/local-testing/scripts/test-slack-bot.sh "bot-testing" "@mybot hello"
./.agents/skills/local-testing/scripts/test-slack-bot.sh "bot-testing" "/ask What is 2+2?" 20
# Telegram — test a bot by username
./.agents/skills/local-testing/scripts/test-telegram-bot.sh "MyTestBot" "/start"
./.agents/skills/local-testing/scripts/test-telegram-bot.sh "GPTBot" "Hello" 60
# WeChat — test a bot or send to a contact
./.agents/skills/local-testing/scripts/test-wechat-bot.sh "文件传输助手" "test message" 5
./.agents/skills/local-testing/scripts/test-wechat-bot.sh "MyBot" "Tell me a joke" 30
# Lark/飞书 — test a bot in a group chat
./.agents/skills/local-testing/scripts/test-lark-bot.sh "bot-testing" "@MyBot hello"
./.agents/skills/local-testing/scripts/test-lark-bot.sh "bot-testing" "Help me with this" 30
# QQ — test a bot in a group or direct chat
./.agents/skills/local-testing/scripts/test-qq-bot.sh "bot-testing" "Hello bot" 15
./.agents/skills/local-testing/scripts/test-qq-bot.sh "MyBot" "/help" 10
```
Each script: activates the app, navigates to the channel/contact, pastes the message via clipboard, sends, waits, and takes a screenshot. Use the `Read` tool on the screenshot for visual verification.
---
# Screen Recording
Record automated demos by combining `ffmpeg` screen capture with `agent-browser` automation. The script `.agents/skills/local-testing/scripts/record-electron-demo.sh` handles the full lifecycle for Electron.
### Usage
```bash
# Run the built-in demo (queue-edit feature)
./.agents/skills/local-testing/scripts/record-electron-demo.sh
# Run a custom automation script
./.agents/skills/local-testing/scripts/record-electron-demo.sh ./my-demo.sh /tmp/my-demo.mp4
```
The script automatically:
1. Starts Electron with CDP and waits for SPA to load
2. Detects window position, screen, and Retina scale via Swift/CGWindowList
3. Records only the Electron window region using `ffmpeg -f avfoundation` with crop
4. Runs the demo (built-in or custom script receiving CDP port as `$1`)
5. Stops recording and cleans up
---
# Gotchas
### agent-browser
- **Daemon can get stuck** — if commands hang, `pkill -f agent-browser` to reset
- **`agent-browser wait` blocks the daemon** — for waits >30s, use bash `sleep`
- **HMR invalidates everything** — after code changes, refs break. Re-snapshot or restart
- **`snapshot -i` doesn't find contenteditable** — use `snapshot -i -C` for rich text editors
- **`fill` doesn't work on contenteditable** — use `type` for chat inputs
- **Screenshots go to `~/.agent-browser/tmp/screenshots/`** — read them with the `Read` tool
### Electron-specific
- **`npx electron-vite dev` must run from `apps/desktop/`** — running from project root fails silently
- **Don't resize the Electron window after load** — resizing triggers full SPA reload
- **Store is at `window.__LOBE_STORES`** not `window.__ZUSTAND_STORES__`
### osascript
- **Accessibility permission required** — first run will prompt for access; grant it in System Preferences > Privacy & Security > Accessibility for Terminal / iTerm / Claude Code
- **`keystroke` is slow for long text** — always use clipboard paste (`Cmd+V`) for messages over \~20 characters
- **`keystroke` can mangle non-ASCII** — use clipboard paste for Chinese, emoji, or special characters
- **`key code 36` is Enter** — this is the hardware key code, works regardless of keyboard layout
- **`entire contents` is extremely slow** — avoid for complex UIs; use screenshots instead
- **App name varies by locale** — `微信` vs `WeChat`, `企业微信` vs `WeCom`; handle both
- **WeChat Enter sends immediately** — use `Shift+Enter` for newlines within a message
- **Rate limiting** — don't send messages too fast; platforms may throttle or flag automated input
- **Lark / 飞书 app name varies** — `Lark` (international) vs `飞书` (China mainland); scripts auto-detect
- **QQ uses `Cmd+F` for search** — not `Cmd+K` like Discord/Slack/Lark
- **Bot response times vary** — AI-powered bots may take 10-60s; use generous sleep values
+54
View File
@@ -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
@@ -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 ==="
+64
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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"
+79
View File
@@ -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
View File
@@ -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"
+22 -6
View File
@@ -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
+18 -3
View File
@@ -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.
---
+123
View File
@@ -0,0 +1,123 @@
---
name: trpc-router
description: TRPC router development guide. Use when creating or modifying TRPC routers (src/server/routers/**), adding procedures, or working with server-side API endpoints. Triggers on TRPC router creation, procedure implementation, or API endpoint tasks.
---
# TRPC Router Guide
## File Location
- Routers: `src/server/routers/lambda/<domain>.ts`
- Helpers: `src/server/routers/lambda/_helpers/`
- Schemas: `src/server/routers/lambda/_schema/`
## Router Structure
### Imports
```typescript
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { SomeModel } from '@/database/models/some';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
```
### Middleware: Inject Models into ctx
**Always use middleware to inject models into `ctx`** instead of creating `new Model(ctx.serverDB, ctx.userId)` inside every procedure.
```typescript
const domainProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
return opts.next({
ctx: {
fooModel: new FooModel(ctx.serverDB, ctx.userId),
barModel: new BarModel(ctx.serverDB, ctx.userId),
},
});
});
```
Then use `ctx.fooModel` in procedures:
```typescript
// Good
const model = ctx.fooModel;
// Bad - don't create models inside procedures
const model = new FooModel(ctx.serverDB, ctx.userId);
```
**Exception**: When a model needs a different `userId` (e.g., watchdog iterating over multiple users' tasks), create it inline.
### Procedure Pattern
```typescript
export const fooRouter = router({
// Query
find: domainProcedure.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {
try {
const item = await ctx.fooModel.findById(input.id);
if (!item) throw new TRPCError({ code: 'NOT_FOUND', message: 'Not found' });
return { data: item, success: true };
} catch (error) {
if (error instanceof TRPCError) throw error;
console.error('[foo:find]', error);
throw new TRPCError({
cause: error,
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to find item',
});
}
}),
// Mutation
create: domainProcedure.input(createSchema).mutation(async ({ input, ctx }) => {
try {
const item = await ctx.fooModel.create(input);
return { data: item, message: 'Created', success: true };
} catch (error) {
if (error instanceof TRPCError) throw error;
console.error('[foo:create]', error);
throw new TRPCError({
cause: error,
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to create',
});
}
}),
});
```
### Aggregated Detail Endpoint
For views that need multiple related data, create a single `detail` procedure that fetches everything in parallel:
```typescript
detail: domainProcedure.input(idInput).query(async ({ input, ctx }) => {
const item = await resolveOrThrow(ctx.fooModel, input.id);
const [children, related] = await Promise.all([
ctx.fooModel.findChildren(item.id),
ctx.barModel.findByFooId(item.id),
]);
return {
data: { ...item, children, related },
success: true,
};
}),
```
This avoids the CLI or frontend making N sequential requests.
## Conventions
- Return shape: `{ data, success: true }` for queries, `{ data?, message, success: true }` for mutations
- Error handling: re-throw `TRPCError`, wrap others with `console.error` + new `TRPCError`
- Input validation: use `zod` schemas, define at file top
- Router name: `export const fooRouter = router({ ... })`
- Procedure names: alphabetical order within the router object
- Log prefix: `[domain:procedure]` format, e.g. `[task:create]`
+4 -4
View File
@@ -6,7 +6,7 @@
- **@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
- **@Innei**: Knowledge base, files (KB-related), group chat
- **@nekomeowww**: Memory, backend, deployment, DevOps
- **@sudongyuer**: Mobile app (React Native)
- **@sxjeru**: Model providers and configuration
@@ -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,7 +57,7 @@ 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:subscription` | @tcmonster | Subscription and billing |
@@ -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
+29
View File
@@ -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 }}
+4 -6
View File
@@ -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
+8 -15
View File
@@ -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
+3 -12
View File
@@ -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
+3 -3
View File
@@ -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: |
+1 -1
View File
@@ -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)"
+4 -6
View File
@@ -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
+6 -24
View File
@@ -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 }}
@@ -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 }}
@@ -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
+7 -36
View File
@@ -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
+5 -19
View File
@@ -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
+5 -17
View File
@@ -133,19 +133,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
@@ -247,16 +241,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
+5 -17
View File
@@ -128,19 +128,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
@@ -242,16 +236,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
+2 -8
View File
@@ -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
+3 -11
View File
@@ -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
+4 -6
View File
@@ -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
View File
@@ -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
View File
@@ -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
+3 -1
View File
@@ -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)
+58
View File
@@ -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">
[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#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">
[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#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>
+1
View File
@@ -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.
+1 -1
View File
@@ -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
+55
View File
@@ -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>
```
+160
View File
@@ -0,0 +1,160 @@
.\" 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.1\-canary.14" "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 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
.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)
+1
View File
@@ -0,0 +1 @@
.so man1/lh.1
+1
View File
@@ -0,0 +1 @@
.so man1/lh.1
+18 -13
View File
@@ -1,43 +1,48 @@
{
"name": "@lobehub/cli",
"version": "0.0.1-canary.12",
"version": "0.0.1-canary.14",
"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",
"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"
+28 -14
View File
@@ -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,46 @@ 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' 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 +71,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`,
}),
+11 -4
View File
@@ -1,6 +1,6 @@
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)
@@ -33,12 +33,19 @@ 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,
@@ -47,6 +54,6 @@ export async function getAuthInfo(): Promise<AuthInfo> {
'Oidc-Auth': accessToken,
'X-lobe-chat-auth': obfuscatePayloadWithXOR({}),
},
serverUrl: serverUrl.replace(/\/$/, ''),
serverUrl,
};
}
+41
View File
@@ -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;
}
+2 -3
View File
@@ -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;
+68 -4
View File
@@ -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 () => {
+38 -8
View File
@@ -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);
}
+246 -96
View File
@@ -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,
+564
View File
@@ -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];
}
+211
View File
@@ -0,0 +1,211 @@
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
export function registerBriefCommand(program: Command) {
const brief = program.command('brief').description('Manage briefs (Agent reports)');
// ── list ──────────────────────────────────────────────
brief
.command('list')
.description('List briefs')
.option('--unresolved', 'Only show unresolved briefs (default)')
.option('--all', 'Show all briefs')
.option('--type <type>', 'Filter by type (decision/result/insight/error)')
.option('-L, --limit <n>', 'Page size', '50')
.option('--json [fields]', 'Output JSON')
.action(
async (options: {
all?: boolean;
json?: string | boolean;
limit?: string;
type?: string;
unresolved?: boolean;
}) => {
const client = await getTrpcClient();
let items: any[];
if (options.all) {
const input: Record<string, any> = {};
if (options.type) input.type = options.type;
if (options.limit) input.limit = Number.parseInt(options.limit, 10);
const result = await client.brief.list.query(input as any);
items = result.data;
} else {
const result = await client.brief.listUnresolved.query();
items = result.data;
}
if (options.json !== undefined) {
outputJson(items, typeof options.json === 'string' ? options.json : undefined);
return;
}
if (!items || items.length === 0) {
log.info('No briefs found.');
return;
}
const rows = items.map((b: any) => [
typeBadge(b.type, b.priority),
truncate(b.title, 40),
truncate(b.summary, 50),
b.taskId ? pc.dim(b.taskId) : b.cronJobId ? pc.dim(b.cronJobId) : '-',
b.resolvedAt ? pc.green('resolved') : b.readAt ? pc.dim('read') : 'new',
timeAgo(b.createdAt),
]);
printTable(rows, ['TYPE', 'TITLE', 'SUMMARY', 'SOURCE', 'STATUS', 'CREATED']);
},
);
// ── view ──────────────────────────────────────────────
brief
.command('view <id>')
.description('View brief details (auto marks as read)')
.option('--json [fields]', 'Output JSON')
.action(async (id: string, options: { json?: string | boolean }) => {
const client = await getTrpcClient();
const result = await client.brief.find.query({ id });
const b = result.data;
if (options.json !== undefined) {
outputJson(b, typeof options.json === 'string' ? options.json : undefined);
return;
}
if (!b) {
log.error('Brief not found.');
return;
}
// Auto mark as read
if (!b.readAt) {
await client.brief.markRead.mutate({ id });
}
const resolvedLabel = b.resolvedAt
? (() => {
const actions = (b.actions as any[]) || [];
const matched = actions.find((a: any) => a.key === (b as any).resolvedAction);
return pc.green(` ${matched?.label || '✓ resolved'}`);
})()
: '';
console.log(`\n${typeBadge(b.type, b.priority)} ${pc.bold(b.title)}${resolvedLabel}`);
console.log(`${pc.dim('Type:')} ${b.type} ${pc.dim('Created:')} ${timeAgo(b.createdAt)}`);
if (b.agentId) console.log(`${pc.dim('Agent:')} ${b.agentId}`);
if (b.taskId) console.log(`${pc.dim('Task:')} ${b.taskId}`);
if (b.cronJobId) console.log(`${pc.dim('CronJob:')} ${b.cronJobId}`);
if (b.topicId) console.log(`${pc.dim('Topic:')} ${b.topicId}`);
console.log(`\n${b.summary}`);
if (b.artifacts && (b.artifacts as string[]).length > 0) {
console.log(`\n${pc.dim('Artifacts:')}`);
for (const a of b.artifacts as string[]) {
console.log(` 📎 ${a}`);
}
}
console.log();
if (!b.resolvedAt) {
const actions = (b.actions as any[]) || [];
if (actions.length > 0) {
console.log('Actions:');
for (const a of actions) {
const cmd =
a.type === 'comment'
? `lh brief resolve ${b.id} --action ${a.key} -m "内容"`
: `lh brief resolve ${b.id} --action ${a.key}`;
console.log(` ${a.label} ${pc.dim(cmd)}`);
}
} else {
console.log(pc.dim('Actions:'));
console.log(pc.dim(` lh brief resolve ${b.id} # 确认通过`));
console.log(pc.dim(` lh brief resolve ${b.id} --reply "修改意见" # 反馈修改`));
}
} else if ((b as any).resolvedComment) {
console.log(`${pc.dim('Comment:')} ${(b as any).resolvedComment}`);
}
});
// ── resolve ──────────────────────────────────────────────
brief
.command('resolve <id>')
.description('Resolve a brief (approve, reply, or custom action)')
.option('--action <key>', 'Execute a specific action (e.g. approve, feedback)')
.option('--reply <text>', 'Reply with feedback')
.option('-m, --message <text>', 'Message for comment-type actions')
.action(async (id: string, options: { action?: string; message?: string; reply?: string }) => {
const client = await getTrpcClient();
const actionKey = options.action || (options.reply ? 'feedback' : 'approve');
const actionMessage = options.message || options.reply;
const briefResult = await client.brief.find.query({ id });
const b = briefResult.data;
// For comment-type actions, add comment to task
if (actionMessage && b?.taskId) {
await client.task.addComment.mutate({
briefId: id,
content: actionMessage,
id: b.taskId,
});
}
await client.brief.resolve.mutate({
action: actionKey,
comment: actionMessage,
id,
});
const actions = (b?.actions as any[]) || [];
const matchedAction = actions.find((a: any) => a.key === actionKey);
const label = matchedAction?.label || actionKey;
log.info(`${label} — Brief ${pc.dim(id)} resolved.`);
});
// ── delete ──────────────────────────────────────────────
brief
.command('delete <id>')
.description('Delete a brief')
.action(async (id: string) => {
const client = await getTrpcClient();
await client.brief.delete.mutate({ id });
log.info(`Brief ${pc.dim(id)} deleted.`);
});
}
function typeBadge(type: string, priority?: string): string {
if (priority === 'urgent') {
return pc.red('🔴');
}
switch (type) {
case 'decision': {
return pc.yellow('🟡');
}
case 'result': {
return pc.green('✅');
}
case 'insight': {
return '💬';
}
case 'error': {
return pc.red('❌');
}
default: {
return '·';
}
}
}
+102
View File
@@ -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');
});
});
+30
View File
@@ -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);
}
});
}
+37 -2
View File
@@ -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(),
}));
@@ -161,6 +167,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 +220,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 +237,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']);
+32 -12
View File
@@ -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,7 +217,7 @@ 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('───────────────────');
@@ -285,20 +288,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);
});
+42 -1
View File
@@ -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',
+36 -3
View File
@@ -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;
+85
View File
@@ -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');
});
});
+212
View File
@@ -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`;
}
+17 -1
View File
@@ -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();
+4 -2
View File
@@ -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,
});
+95
View File
@@ -0,0 +1,95 @@
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { log } from '../../utils/logger';
export function registerCheckpointCommands(task: Command) {
// ── checkpoint ──────────────────────────────────────────────
const cp = task.command('checkpoint').description('Manage task checkpoints');
cp.command('view <id>')
.description('View checkpoint config for a task')
.action(async (id: string) => {
const client = await getTrpcClient();
const result = await client.task.getCheckpoint.query({ id });
const c = result.data as any;
console.log(`\n${pc.bold('Checkpoint config:')}`);
console.log(` onAgentRequest: ${c.onAgentRequest ?? pc.dim('not set (default: true)')}`);
if (c.topic) {
console.log(` topic.before: ${c.topic.before ?? false}`);
console.log(` topic.after: ${c.topic.after ?? false}`);
}
if (c.tasks?.beforeIds?.length > 0) {
console.log(` tasks.beforeIds: ${c.tasks.beforeIds.join(', ')}`);
}
if (c.tasks?.afterIds?.length > 0) {
console.log(` tasks.afterIds: ${c.tasks.afterIds.join(', ')}`);
}
if (
!c.topic &&
!c.tasks?.beforeIds?.length &&
!c.tasks?.afterIds?.length &&
c.onAgentRequest === undefined
) {
console.log(` ${pc.dim('(no checkpoints configured)')}`);
}
console.log();
});
cp.command('set <id>')
.description('Configure checkpoints')
.option('--on-agent-request <bool>', 'Allow agent to request review (true/false)')
.option('--topic-before <bool>', 'Pause before each topic (true/false)')
.option('--topic-after <bool>', 'Pause after each topic (true/false)')
.option('--before <ids>', 'Pause before these subtask identifiers (comma-separated)')
.option('--after <ids>', 'Pause after these subtask identifiers (comma-separated)')
.action(
async (
id: string,
options: {
after?: string;
before?: string;
onAgentRequest?: string;
topicAfter?: string;
topicBefore?: string;
},
) => {
const client = await getTrpcClient();
// Get current config first
const current = (await client.task.getCheckpoint.query({ id })).data as any;
const checkpoint: any = { ...current };
if (options.onAgentRequest !== undefined) {
checkpoint.onAgentRequest = options.onAgentRequest === 'true';
}
if (options.topicBefore !== undefined || options.topicAfter !== undefined) {
checkpoint.topic = { ...checkpoint.topic };
if (options.topicBefore !== undefined)
checkpoint.topic.before = options.topicBefore === 'true';
if (options.topicAfter !== undefined)
checkpoint.topic.after = options.topicAfter === 'true';
}
if (options.before !== undefined) {
checkpoint.tasks = { ...checkpoint.tasks };
checkpoint.tasks.beforeIds = options.before
.split(',')
.map((s: string) => s.trim())
.filter(Boolean);
}
if (options.after !== undefined) {
checkpoint.tasks = { ...checkpoint.tasks };
checkpoint.tasks.afterIds = options.after
.split(',')
.map((s: string) => s.trim())
.filter(Boolean);
}
await client.task.updateCheckpoint.mutate({ checkpoint, id });
log.info('Checkpoint updated.');
},
);
}
+56
View File
@@ -0,0 +1,56 @@
import type { Command } from 'commander';
import { getTrpcClient } from '../../api/client';
import { outputJson, printTable, timeAgo } from '../../utils/format';
import { log } from '../../utils/logger';
export function registerDepCommands(task: Command) {
// ── dep ──────────────────────────────────────────────
const dep = task.command('dep').description('Manage task dependencies');
dep
.command('add <taskId> <dependsOnId>')
.description('Add dependency (taskId blocks on dependsOnId)')
.option('--type <type>', 'Dependency type (blocks/relates)', 'blocks')
.action(async (taskId: string, dependsOnId: string, options: { type?: string }) => {
const client = await getTrpcClient();
await client.task.addDependency.mutate({
dependsOnId,
taskId,
type: (options.type || 'blocks') as any,
});
log.info(`Dependency added: ${taskId} ${options.type || 'blocks'} on ${dependsOnId}`);
});
dep
.command('rm <taskId> <dependsOnId>')
.description('Remove dependency')
.action(async (taskId: string, dependsOnId: string) => {
const client = await getTrpcClient();
await client.task.removeDependency.mutate({ dependsOnId, taskId });
log.info(`Dependency removed.`);
});
dep
.command('list <taskId>')
.description('List dependencies for a task')
.option('--json [fields]', 'Output JSON')
.action(async (taskId: string, options: { json?: string | boolean }) => {
const client = await getTrpcClient();
const result = await client.task.getDependencies.query({ id: taskId });
if (options.json !== undefined) {
outputJson(result.data, options.json);
return;
}
if (!result.data || result.data.length === 0) {
log.info('No dependencies.');
return;
}
const rows = result.data.map((d: any) => [d.type, d.dependsOnId, timeAgo(d.createdAt)]);
printTable(rows, ['TYPE', 'DEPENDS ON', 'CREATED']);
});
}
+102
View File
@@ -0,0 +1,102 @@
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { log } from '../../utils/logger';
export function registerDocCommands(task: Command) {
// ── doc ──────────────────────────────────────────────
const dc = task.command('doc').description('Manage task workspace documents');
dc.command('create <id>')
.description('Create a document and pin it to the task')
.requiredOption('-t, --title <title>', 'Document title')
.option('-b, --body <content>', 'Document content')
.option('--parent <docId>', 'Parent document/folder ID')
.option('--folder', 'Create as folder')
.action(
async (
id: string,
options: { body?: string; folder?: boolean; parent?: string; title: string },
) => {
const client = await getTrpcClient();
// Create document
const fileType = options.folder ? 'custom/folder' : undefined;
const content = options.body || '';
const result = await client.document.createDocument.mutate({
content,
editorData: options.folder ? undefined : JSON.stringify({ content, type: 'doc' }),
fileType,
parentId: options.parent,
title: options.title,
});
// Pin to task
await client.task.pinDocument.mutate({
documentId: result.id,
pinnedBy: 'user',
taskId: id,
});
const icon = options.folder ? '📁' : '📄';
log.info(`${icon} Created & pinned: ${pc.bold(options.title)} ${pc.dim(result.id)}`);
},
);
dc.command('pin <id> <documentId>')
.description('Pin an existing document to a task')
.action(async (id: string, documentId: string) => {
const client = await getTrpcClient();
await client.task.pinDocument.mutate({ documentId, pinnedBy: 'user', taskId: id });
log.info(`Pinned ${pc.dim(documentId)} to ${pc.bold(id)}.`);
});
dc.command('unpin <id> <documentId>')
.description('Unpin a document from a task')
.action(async (id: string, documentId: string) => {
const client = await getTrpcClient();
await client.task.unpinDocument.mutate({ documentId, taskId: id });
log.info(`Unpinned ${pc.dim(documentId)} from ${pc.bold(id)}.`);
});
dc.command('mv <id> <documentId> <folder>')
.description('Move a document into a folder (auto-creates folder if not found)')
.action(async (id: string, documentId: string, folder: string) => {
const client = await getTrpcClient();
// Check if folder is a document ID or a folder name
let folderId = folder;
if (!folder.startsWith('docs_')) {
// folder is a name, find or create it
const detail = await client.task.detail.query({ id });
const folders = detail.data.workspace || [];
// Search for existing folder by name
const existingFolder = folders.find((f) => f.title === folder);
if (existingFolder) {
folderId = existingFolder.documentId;
} else {
// Create folder and pin to task
const result = await client.document.createDocument.mutate({
content: '',
fileType: 'custom/folder',
title: folder,
});
await client.task.pinDocument.mutate({
documentId: result.id,
pinnedBy: 'user',
taskId: id,
});
folderId = result.id;
log.info(`📁 Created folder: ${pc.bold(folder)} ${pc.dim(folderId)}`);
}
}
// Move document into folder
await client.document.updateDocument.mutate({ id: documentId, parentId: folderId });
log.info(`Moved ${pc.dim(documentId)} → 📁 ${pc.bold(folder)}`);
});
}
+74
View File
@@ -0,0 +1,74 @@
import pc from 'picocolors';
export function statusBadge(status: string): string {
const pad = (s: string) => s.padEnd(9);
switch (status) {
case 'backlog': {
return pc.dim(`${pad('backlog')}`);
}
case 'blocked': {
return pc.red(`${pad('blocked')}`);
}
case 'running': {
return pc.blue(`${pad('running')}`);
}
case 'paused': {
return pc.yellow(`${pad('paused')}`);
}
case 'completed': {
return pc.green(`${pad('completed')}`);
}
case 'failed': {
return pc.red(`${pad('failed')}`);
}
case 'timeout': {
return pc.red(`${pad('timeout')}`);
}
case 'canceled': {
return pc.dim(`${pad('canceled')}`);
}
default: {
return status;
}
}
}
export function briefIcon(type: string): string {
switch (type) {
case 'decision': {
return '📋';
}
case 'result': {
return '✅';
}
case 'insight': {
return '💡';
}
case 'error': {
return '❌';
}
default: {
return '📌';
}
}
}
export function priorityLabel(priority: number | null | undefined): string {
switch (priority) {
case 1: {
return pc.red('urgent');
}
case 2: {
return pc.yellow('high');
}
case 3: {
return 'normal';
}
case 4: {
return pc.dim('low');
}
default: {
return pc.dim('-');
}
}
}
+624
View File
@@ -0,0 +1,624 @@
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import {
confirm,
displayWidth,
outputJson,
printTable,
timeAgo,
truncate,
} from '../../utils/format';
import { log } from '../../utils/logger';
import { registerCheckpointCommands } from './checkpoint';
import { registerDepCommands } from './dep';
import { registerDocCommands } from './doc';
import { briefIcon, priorityLabel, statusBadge } from './helpers';
import { registerLifecycleCommands } from './lifecycle';
import { registerReviewCommands } from './review';
import { registerTopicCommands } from './topic';
export function registerTaskCommand(program: Command) {
const task = program.command('task').description('Manage agent tasks');
// ── list ──────────────────────────────────────────────
task
.command('list')
.description('List tasks')
.option(
'--status <status>',
'Filter by status (pending/running/paused/completed/failed/canceled)',
)
.option('--root', 'Only show root tasks (no parent)')
.option('--parent <id>', 'Filter by parent task ID')
.option('--agent <id>', 'Filter by assignee agent ID')
.option('-L, --limit <n>', 'Page size', '50')
.option('--offset <n>', 'Offset', '0')
.option('--tree', 'Display as tree structure')
.option('--json [fields]', 'Output JSON')
.action(
async (options: {
agent?: string;
json?: string | boolean;
limit?: string;
offset?: string;
parent?: string;
root?: boolean;
status?: string;
tree?: boolean;
}) => {
const client = await getTrpcClient();
const input: Record<string, any> = {};
if (options.status) input.status = options.status;
if (options.root) input.parentTaskId = null;
if (options.parent) input.parentTaskId = options.parent;
if (options.agent) input.assigneeAgentId = options.agent;
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) {
input.limit = 100;
delete input.offset;
}
const result = await client.task.list.query(input as any);
if (options.json !== undefined) {
outputJson(result.data, options.json);
return;
}
if (!result.data || result.data.length === 0) {
log.info('No tasks found.');
return;
}
if (options.tree) {
// Build tree display
const taskMap = new Map<string, any>();
for (const t of result.data) taskMap.set(t.id, t);
const roots = result.data.filter((t: any) => !t.parentTaskId);
const children = new Map<string, any[]>();
for (const t of result.data) {
if (t.parentTaskId) {
const list = children.get(t.parentTaskId) || [];
list.push(t);
children.set(t.parentTaskId, list);
}
}
// Sort children by sortOrder first, then seq
for (const [, list] of children) {
list.sort(
(a: any, b: any) =>
(a.sortOrder ?? 0) - (b.sortOrder ?? 0) || (a.seq ?? 0) - (b.seq ?? 0),
);
}
const printNode = (t: any, prefix: string, isLast: boolean, isRoot: boolean) => {
const connector = isRoot ? '' : isLast ? '└── ' : '├── ';
const name = truncate(t.name || t.instruction, 40);
console.log(
`${prefix}${connector}${pc.dim(t.identifier)} ${statusBadge(t.status)} ${name}`,
);
const childList = children.get(t.id) || [];
const newPrefix = isRoot ? '' : prefix + (isLast ? ' ' : '│ ');
childList.forEach((child: any, i: number) => {
printNode(child, newPrefix, i === childList.length - 1, false);
});
};
for (const root of roots) {
printNode(root, '', true, true);
}
log.info(`Total: ${result.total}`);
return;
}
const rows = result.data.map((t: any) => [
pc.dim(t.identifier),
truncate(t.name || t.instruction, 40),
statusBadge(t.status),
priorityLabel(t.priority),
t.assigneeAgentId ? pc.dim(t.assigneeAgentId) : '-',
t.parentTaskId ? pc.dim('↳ subtask') : '',
timeAgo(t.createdAt),
]);
printTable(rows, ['ID', 'NAME', 'STATUS', 'PRI', 'AGENT', 'TYPE', 'CREATED']);
log.info(`Total: ${result.total}`);
},
);
// ── view ──────────────────────────────────────────────
task
.command('view <id>')
.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) {
outputJson(result.data, options.json);
return;
}
const t = result.data;
// ── Header ──
console.log(`\n${pc.bold(t.identifier)} ${t.name || ''}`);
console.log(
`${pc.dim('Status:')} ${statusBadge(t.status)} ${pc.dim('Priority:')} ${priorityLabel(t.priority)}`,
);
console.log(`${pc.dim('Instruction:')} ${t.instruction}`);
if (t.description) console.log(`${pc.dim('Description:')} ${t.description}`);
if (t.agentId) console.log(`${pc.dim('Agent:')} ${t.agentId}`);
if (t.userId) console.log(`${pc.dim('User:')} ${t.userId}`);
if (t.parent) {
console.log(`${pc.dim('Parent:')} ${t.parent.identifier} ${t.parent.name || ''}`);
}
const topicInfo = t.topicCount ? `${t.topicCount}` : '0';
const createdInfo = t.createdAt ? timeAgo(t.createdAt) : '-';
console.log(`${pc.dim('Topics:')} ${topicInfo} ${pc.dim('Created:')} ${createdInfo}`);
if (t.heartbeat?.timeout && t.heartbeat.lastAt) {
const hb = timeAgo(t.heartbeat.lastAt);
const interval = t.heartbeat.interval ? `${t.heartbeat.interval}s` : '-';
const elapsed = (Date.now() - new Date(t.heartbeat.lastAt).getTime()) / 1000;
const isStuck = t.status === 'running' && elapsed > t.heartbeat.timeout;
console.log(
`${pc.dim('Heartbeat:')} ${isStuck ? pc.red(hb) : hb} ${pc.dim('interval:')} ${interval} ${pc.dim('timeout:')} ${t.heartbeat.timeout}s${isStuck ? pc.red(' ⚠ TIMEOUT') : ''}`,
);
}
if (t.error) console.log(`${pc.red('Error:')} ${t.error}`);
// ── Subtasks ──
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),
);
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}`,
);
}
}
// ── Dependencies ──
if (t.dependencies && t.dependencies.length > 0) {
console.log(`\n${pc.bold('Dependencies:')}`);
for (const d of t.dependencies) {
const depName = d.name ? ` ${d.name}` : '';
console.log(` ${pc.dim(d.type || 'blocks')}: ${d.dependsOn}${depName}`);
}
}
// ── Checkpoint ──
{
const cp = t.checkpoint || {};
console.log(`\n${pc.bold('Checkpoint:')}`);
const hasConfig =
cp.onAgentRequest !== undefined ||
cp.topic?.before ||
cp.topic?.after ||
cp.tasks?.beforeIds?.length ||
cp.tasks?.afterIds?.length;
if (hasConfig) {
if (cp.onAgentRequest !== undefined)
console.log(` onAgentRequest: ${cp.onAgentRequest}`);
if (cp.topic?.before) console.log(` topic.before: ${cp.topic.before}`);
if (cp.topic?.after) console.log(` topic.after: ${cp.topic.after}`);
if (cp.tasks?.beforeIds?.length)
console.log(` tasks.before: ${cp.tasks.beforeIds.join(', ')}`);
if (cp.tasks?.afterIds?.length)
console.log(` tasks.after: ${cp.tasks.afterIds.join(', ')}`);
} else {
console.log(` ${pc.dim('(not configured, default: onAgentRequest=true)')}`);
}
}
// ── Review ──
{
const rv = t.review as any;
console.log(`\n${pc.bold('Review:')}`);
if (rv && rv.enabled) {
console.log(
` judge: ${rv.judge?.model || 'default'}${rv.judge?.provider ? ` (${rv.judge.provider})` : ''}`,
);
console.log(` maxIterations: ${rv.maxIterations} autoRetry: ${rv.autoRetry}`);
if (rv.rubrics?.length > 0) {
for (let i = 0; i < rv.rubrics.length; i++) {
const rb = rv.rubrics[i];
const threshold = rb.threshold ? `${Math.round(rb.threshold * 100)}%` : '';
const typeTag = pc.dim(`[${rb.type}]`);
let configInfo = '';
if (rb.type === 'llm-rubric') configInfo = rb.config?.criteria || '';
else if (rb.type === 'contains' || rb.type === 'equals')
configInfo = `value="${rb.config?.value}"`;
else if (rb.type === 'regex') configInfo = `pattern="${rb.config?.pattern}"`;
console.log(` ${i + 1}. ${rb.name} ${typeTag}${threshold} ${pc.dim(configInfo)}`);
}
}
} else {
console.log(` ${pc.dim('(not configured)')}`);
}
}
// ── Workspace ──
{
const nodes = t.workspace || [];
if (nodes.length === 0) {
console.log(`\n${pc.bold('Workspace:')}`);
console.log(` ${pc.dim('No documents yet.')}`);
} else {
const countNodes = (list: typeof nodes): number =>
list.reduce((sum, n) => sum + 1 + (n.children ? countNodes(n.children) : 0), 0);
console.log(`\n${pc.bold(`Workspace (${countNodes(nodes)}):`)}`);
const formatSize = (chars: number | null | undefined) => {
if (!chars) return '';
if (chars >= 10_000) return `${(chars / 1000).toFixed(1)}k`;
return `${chars}`;
};
const LEFT_COL = 56;
const FROM_WIDTH = 10;
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 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 = ' '.repeat(Math.max(1, FROM_WIDTH - fromStr.length + 1));
const size =
!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)}${pc.dim(ago)}`,
);
if (node.children && node.children.length > 0) {
const childIndent = isChild ? indent + (isLast ? ' ' : '│ ') : indent;
renderNodes(node.children, childIndent, true);
}
}
};
renderNodes(nodes, ' ', false);
}
}
// ── Activities (already sorted desc by service) ──
{
console.log(`\n${pc.bold('Activities:')}`);
const acts = t.activities || [];
if (acts.length === 0) {
console.log(` ${pc.dim('No activities yet.')}`);
} else {
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}`);
}
}
}
}
console.log();
});
// ── create ──────────────────────────────────────────────
task
.command('create')
.description('Create a new task')
.requiredOption('-i, --instruction <text>', 'Task instruction')
.option('-n, --name <name>', 'Task name')
.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', 'T')
.option('--json [fields]', 'Output JSON')
.action(
async (options: {
agent?: string;
instruction: string;
json?: string | boolean;
name?: string;
parent?: string;
prefix?: string;
priority?: string;
}) => {
const client = await getTrpcClient();
const input: Record<string, any> = {
instruction: options.instruction,
};
if (options.name) input.name = options.name;
if (options.agent) input.assigneeAgentId = options.agent;
if (options.parent) input.parentTaskId = options.parent;
if (options.priority) input.priority = Number.parseInt(options.priority, 10);
if (options.prefix) input.identifierPrefix = options.prefix;
const result = await client.task.create.mutate(input as any);
if (options.json !== undefined) {
outputJson(result.data, options.json);
return;
}
log.info(`Task created: ${pc.bold(result.data.identifier)} ${result.data.name || ''}`);
},
);
// ── edit ──────────────────────────────────────────────
task
.command('edit <id>')
.description('Update a task')
.option('-n, --name <name>', 'Task name')
.option('-i, --instruction <text>', 'Task instruction')
.option('--agent <id>', 'Assign to agent')
.option('--priority <n>', 'Priority (0-4)')
.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 (
id: string,
options: {
agent?: string;
description?: string;
heartbeatInterval?: string;
heartbeatTimeout?: string;
instruction?: string;
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;
if (options.description) input.description = options.description;
if (options.agent) input.assigneeAgentId = options.agent;
if (options.priority) input.priority = Number.parseInt(options.priority, 10);
if (options.heartbeatInterval)
input.heartbeatInterval = Number.parseInt(options.heartbeatInterval, 10);
if (options.heartbeatTimeout !== undefined) {
const val = Number.parseInt(options.heartbeatTimeout, 10);
input.heartbeatTimeout = val === 0 ? null : val;
}
const result = await client.task.update.mutate(input as any);
if (options.json !== undefined) {
outputJson(result.data, typeof options.json === 'string' ? options.json : undefined);
return;
}
log.info(`Task updated: ${pc.bold(result.data.identifier)}`);
},
);
// ── delete ──────────────────────────────────────────────
task
.command('delete <id>')
.description('Delete a task')
.option('-y, --yes', 'Skip confirmation')
.action(async (id: string, options: { yes?: boolean }) => {
if (!options.yes) {
const ok = await confirm(`Delete task ${pc.bold(id)}?`);
if (!ok) return;
}
const client = await getTrpcClient();
await client.task.delete.mutate({ id });
log.info(`Task ${pc.bold(id)} deleted.`);
});
// ── clear ──────────────────────────────────────────────
task
.command('clear')
.description('Delete all tasks')
.option('-y, --yes', 'Skip confirmation')
.action(async (options: { yes?: boolean }) => {
if (!options.yes) {
const ok = await confirm(`Delete ${pc.red('ALL')} tasks? This cannot be undone.`);
if (!ok) return;
}
const client = await getTrpcClient();
const result = (await client.task.clearAll.mutate()) as any;
log.info(`${result.count} task(s) deleted.`);
});
// ── tree ──────────────────────────────────────────────
task
.command('tree <id>')
.description('Show task tree (subtasks + dependencies)')
.option('--json [fields]', 'Output JSON')
.action(async (id: string, options: { json?: string | boolean }) => {
const client = await getTrpcClient();
const result = await client.task.getTaskTree.query({ id });
if (options.json !== undefined) {
outputJson(result.data, options.json);
return;
}
if (!result.data || result.data.length === 0) {
log.info('No tasks found.');
return;
}
// Build tree display (raw SQL returns snake_case)
const taskMap = new Map<string, any>();
for (const t of result.data) taskMap.set(t.id, t);
const printNode = (taskId: string, indent: number) => {
const t = taskMap.get(taskId);
if (!t) return;
const prefix = indent === 0 ? '' : ' '.repeat(indent) + '├── ';
const name = t.name || t.identifier || '';
const status = t.status || 'pending';
const identifier = t.identifier || t.id;
console.log(`${prefix}${pc.dim(identifier)} ${statusBadge(status)} ${name}`);
// Print children (handle both camelCase and snake_case)
for (const child of result.data) {
const childParent = child.parentTaskId || child.parent_task_id;
if (childParent === taskId) {
printNode(child.id, indent + 1);
}
}
};
// Find root - resolve identifier first
const resolved = await client.task.find.query({ id });
const rootId = resolved.data.id;
const root = result.data.find((t: any) => t.id === rootId);
if (root) printNode(root.id, 0);
else log.info('Root task not found in tree.');
});
// Register subcommand groups
registerLifecycleCommands(task);
registerCheckpointCommands(task);
registerReviewCommands(task);
registerDepCommands(task);
registerTopicCommands(task);
registerDocCommands(task);
}
+303
View File
@@ -0,0 +1,303 @@
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { getAuthInfo } from '../../api/http';
import { streamAgentEvents } from '../../utils/agentStream';
import { log } from '../../utils/logger';
export function registerLifecycleCommands(task: Command) {
// ── start ──────────────────────────────────────────────
task
.command('start <id>')
.description('Start a task (pending → running)')
.option('--no-run', 'Only update status, do not trigger agent execution')
.option('-p, --prompt <text>', 'Additional context for the agent')
.option('-f, --follow', 'Follow agent output in real-time (default: run in background)')
.option('--json', 'Output full JSON event stream')
.option('-v, --verbose', 'Show detailed tool call info')
.action(
async (
id: string,
options: {
follow?: boolean;
json?: boolean;
prompt?: string;
run?: boolean;
verbose?: boolean;
},
) => {
const client = await getTrpcClient();
// Check if already running
const taskDetail = await client.task.find.query({ id });
if (taskDetail.data.status === 'running') {
log.info(`Task ${pc.bold(taskDetail.data.identifier)} is already running.`);
return;
}
const statusResult = await client.task.updateStatus.mutate({ id, status: 'running' });
log.info(`Task ${pc.bold(statusResult.data.identifier)} started.`);
// Auto-run unless --no-run
if (options.run === false) return;
// Default agent to inbox if not assigned
if (!taskDetail.data.assigneeAgentId) {
await client.task.update.mutate({ assigneeAgentId: 'inbox', id });
log.info(`Assigned default agent: ${pc.dim('inbox')}`);
}
const result = (await client.task.run.mutate({
id,
...(options.prompt && { prompt: options.prompt }),
})) as any;
if (!result.success) {
log.error(`Failed to run task: ${result.error || result.message || 'Unknown error'}`);
process.exit(1);
}
log.info(
`Operation: ${pc.dim(result.operationId)} · Topic: ${pc.dim(result.topicId || 'n/a')}`,
);
if (!options.follow) {
log.info(
`Agent running in background. Use ${pc.dim(`lh task view ${id}`)} to check status.`,
);
return;
}
const { serverUrl, headers } = await getAuthInfo();
const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(result.operationId)}`;
await streamAgentEvents(streamUrl, headers, {
json: options.json,
verbose: options.verbose,
});
// Send heartbeat after completion
try {
await client.task.heartbeat.mutate({ id });
} catch {
// ignore heartbeat errors
}
},
);
// ── run ──────────────────────────────────────────────
task
.command('run <id>')
.description('Run a task — trigger agent execution')
.option('-p, --prompt <text>', 'Additional context for the agent')
.option('-c, --continue <topicId>', 'Continue running on an existing topic')
.option('-f, --follow', 'Follow agent output in real-time (default: run in background)')
.option('--topics <n>', 'Run N topics in sequence (default: 1, implies --follow)', '1')
.option('--delay <s>', 'Delay between topics in seconds', '0')
.option('--json', 'Output full JSON event stream')
.option('-v, --verbose', 'Show detailed tool call info')
.action(
async (
id: string,
options: {
continue?: string;
delay?: string;
follow?: boolean;
json?: boolean;
prompt?: string;
topics?: string;
verbose?: boolean;
},
) => {
const topicCount = Number.parseInt(options.topics || '1', 10);
const delaySec = Number.parseInt(options.delay || '0', 10);
// --topics > 1 implies --follow
const shouldFollow = options.follow || topicCount > 1;
for (let i = 0; i < topicCount; i++) {
if (i > 0) {
log.info(`\n${'─'.repeat(60)}`);
log.info(`Topic ${i + 1}/${topicCount}`);
if (delaySec > 0) {
log.info(`Waiting ${delaySec}s before next topic...`);
await new Promise((r) => setTimeout(r, delaySec * 1000));
}
}
const client = await getTrpcClient();
// Auto-assign inbox agent on first topic if not assigned
if (i === 0) {
const taskDetail = await client.task.find.query({ id });
if (!taskDetail.data.assigneeAgentId) {
await client.task.update.mutate({ assigneeAgentId: 'inbox', id });
log.info(`Assigned default agent: ${pc.dim('inbox')}`);
}
}
// Only pass extra prompt and continue on first topic
const result = (await client.task.run.mutate({
id,
...(i === 0 && options.prompt && { prompt: options.prompt }),
...(i === 0 && options.continue && { continueTopicId: options.continue }),
})) as any;
if (!result.success) {
log.error(`Failed to run task: ${result.error || result.message || 'Unknown error'}`);
process.exit(1);
}
const operationId = result.operationId;
if (i === 0) {
log.info(`Task ${pc.bold(result.taskIdentifier)} running`);
}
log.info(`Operation: ${pc.dim(operationId)} · Topic: ${pc.dim(result.topicId || 'n/a')}`);
if (!shouldFollow) {
log.info(
`Agent running in background. Use ${pc.dim(`lh task view ${id}`)} to check status.`,
);
return;
}
// Connect to SSE stream and wait for completion
const { serverUrl, headers } = await getAuthInfo();
const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
await streamAgentEvents(streamUrl, headers, {
json: options.json,
verbose: options.verbose,
});
// Update heartbeat after each topic
try {
await client.task.heartbeat.mutate({ id });
} catch {
// ignore heartbeat errors
}
}
},
);
// ── comment ──────────────────────────────────────────────
task
.command('comment <id>')
.description('Add a comment to a task')
.requiredOption('-m, --message <text>', 'Comment content')
.action(async (id: string, options: { message: string }) => {
const client = await getTrpcClient();
await client.task.addComment.mutate({ content: options.message, id });
log.info('Comment added.');
});
// ── pause ──────────────────────────────────────────────
task
.command('pause <id>')
.description('Pause a running task')
.action(async (id: string) => {
const client = await getTrpcClient();
const result = await client.task.updateStatus.mutate({ id, status: 'paused' });
log.info(`Task ${pc.bold(result.data.identifier)} paused.`);
});
// ── resume ──────────────────────────────────────────────
task
.command('resume <id>')
.description('Resume a paused task')
.action(async (id: string) => {
const client = await getTrpcClient();
const result = await client.task.updateStatus.mutate({ id, status: 'running' });
log.info(`Task ${pc.bold(result.data.identifier)} resumed.`);
});
// ── complete ──────────────────────────────────────────────
task
.command('complete <id>')
.description('Mark a task as completed')
.action(async (id: string) => {
const client = await getTrpcClient();
const result = (await client.task.updateStatus.mutate({ id, status: 'completed' })) as any;
log.info(`Task ${pc.bold(result.data.identifier)} completed.`);
if (result.unlocked?.length > 0) {
log.info(`Unlocked: ${result.unlocked.map((id: string) => pc.bold(id)).join(', ')}`);
}
if (result.paused?.length > 0) {
log.info(
`Paused (checkpoint): ${result.paused.map((id: string) => pc.yellow(id)).join(', ')}`,
);
}
if (result.checkpointTriggered) {
log.info(`${pc.yellow('Checkpoint triggered')} — parent task paused for review.`);
}
if (result.allSubtasksDone) {
log.info(`All subtasks of parent task completed.`);
}
});
// ── cancel ──────────────────────────────────────────────
task
.command('cancel <id>')
.description('Cancel a task')
.action(async (id: string) => {
const client = await getTrpcClient();
const result = await client.task.updateStatus.mutate({ id, status: 'canceled' });
log.info(`Task ${pc.bold(result.data.identifier)} canceled.`);
});
// ── sort ──────────────────────────────────────────────
task
.command('sort <id> <identifiers...>')
.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({
id,
order: identifiers,
})) as any;
log.info('Subtasks reordered:');
for (const item of result.data) {
console.log(` ${pc.dim(`#${item.sortOrder}`)} ${item.identifier}`);
}
});
// ── heartbeat ──────────────────────────────────────────────
task
.command('heartbeat <id>')
.description('Manually send heartbeat for a running task')
.action(async (id: string) => {
const client = await getTrpcClient();
await client.task.heartbeat.mutate({ id });
log.info(`Heartbeat sent for ${pc.bold(id)}.`);
});
// ── watchdog ──────────────────────────────────────────────
task
.command('watchdog')
.description('Run watchdog check — detect and fail stuck tasks')
.action(async () => {
const client = await getTrpcClient();
const result = (await client.task.watchdog.mutate()) as any;
if (result.failed?.length > 0) {
log.info(
`${pc.red('Stuck tasks failed:')} ${result.failed.map((id: string) => pc.bold(id)).join(', ')}`,
);
} else {
log.info('No stuck tasks found.');
}
});
}
+306
View File
@@ -0,0 +1,306 @@
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { printTable, truncate } from '../../utils/format';
import { log } from '../../utils/logger';
export function registerReviewCommands(task: Command) {
// ── review ──────────────────────────────────────────────
const rv = task.command('review').description('Manage task review (LLM-as-Judge)');
rv.command('view <id>')
.description('View review config for a task')
.action(async (id: string) => {
const client = await getTrpcClient();
const result = await client.task.getReview.query({ id });
const r = result.data as any;
if (!r || !r.enabled) {
log.info('Review not configured for this task.');
return;
}
console.log(`\n${pc.bold('Review config:')}`);
console.log(` enabled: ${r.enabled}`);
if (r.judge?.model)
console.log(` judge: ${r.judge.model}${r.judge.provider ? ` (${r.judge.provider})` : ''}`);
console.log(` maxIterations: ${r.maxIterations}`);
console.log(` autoRetry: ${r.autoRetry}`);
if (r.rubrics?.length > 0) {
console.log(` rubrics:`);
for (let i = 0; i < r.rubrics.length; i++) {
const rb = r.rubrics[i];
const threshold = rb.threshold ? `${Math.round(rb.threshold * 100)}%` : '';
const typeTag = pc.dim(`[${rb.type}]`);
let configInfo = '';
if (rb.type === 'llm-rubric') configInfo = rb.config?.criteria || '';
else if (rb.type === 'contains' || rb.type === 'equals')
configInfo = `value="${rb.config?.value}"`;
else if (rb.type === 'regex') configInfo = `pattern="${rb.config?.pattern}"`;
console.log(` ${i + 1}. ${rb.name} ${typeTag}${threshold} ${pc.dim(configInfo)}`);
}
} else {
console.log(` rubrics: ${pc.dim('(none)')}`);
}
console.log();
});
rv.command('set <id>')
.description('Enable review and configure judge settings')
.option('--model <model>', 'Judge model')
.option('--provider <provider>', 'Judge provider')
.option('--max-iterations <n>', 'Max review iterations', '3')
.option('--no-auto-retry', 'Disable auto retry on failure')
.option('--recursive', 'Apply to all subtasks as well')
.action(
async (
id: string,
options: {
autoRetry?: boolean;
maxIterations?: string;
model?: string;
provider?: string;
recursive?: boolean;
},
) => {
const client = await getTrpcClient();
// Read current review config to preserve rubrics
const current = (await client.task.getReview.query({ id })).data as any;
const existingRubrics = current?.rubrics || [];
const review = {
autoRetry: options.autoRetry !== false,
enabled: true,
judge: {
...(options.model && { model: options.model }),
...(options.provider && { provider: options.provider }),
},
maxIterations: Number.parseInt(options.maxIterations || '3', 10),
rubrics: existingRubrics,
};
await client.task.updateReview.mutate({ id, review });
if (options.recursive) {
const subtasks = await client.task.getSubtasks.query({ id });
for (const s of subtasks.data || []) {
const subCurrent = (await client.task.getReview.query({ id: s.id })).data as any;
await client.task.updateReview.mutate({
id: s.id,
review: { ...review, rubrics: subCurrent?.rubrics || existingRubrics },
});
}
log.info(
`Review enabled for ${pc.bold(id)} + ${(subtasks.data || []).length} subtask(s).`,
);
} else {
log.info('Review enabled.');
}
},
);
// ── review criteria ──────────────────────────────────────
const rc = rv.command('criteria').description('Manage review rubrics');
rc.command('list <id>')
.description('List review rubrics for a task')
.action(async (id: string) => {
const client = await getTrpcClient();
const result = await client.task.getReview.query({ id });
const r = result.data as any;
const rubrics = r?.rubrics || [];
if (rubrics.length === 0) {
log.info('No rubrics configured.');
return;
}
const rows = rubrics.map((r: any, i: number) => {
const config = r.config || {};
const configStr =
r.type === 'llm-rubric'
? config.criteria || ''
: r.type === 'contains' || r.type === 'equals'
? `value: "${config.value}"`
: r.type === 'regex'
? `pattern: "${config.pattern}"`
: JSON.stringify(config);
return [
String(i + 1),
r.name,
r.type,
r.threshold ? `${Math.round(r.threshold * 100)}%` : '-',
String(r.weight ?? 1),
truncate(configStr, 40),
];
});
printTable(rows, ['#', 'NAME', 'TYPE', 'THRESHOLD', 'WEIGHT', 'CONFIG']);
});
rc.command('add <id>')
.description('Add a review rubric')
.requiredOption('-n, --name <name>', 'Rubric name (e.g. "内容准确性")')
.option('--type <type>', 'Rubric type (default: llm-rubric)', 'llm-rubric')
.option('-t, --threshold <n>', 'Pass threshold 0-100 (converted to 0-1)')
.option('-d, --description <text>', 'Criteria description (for llm-rubric type)')
.option('--value <value>', 'Expected value (for contains/equals type)')
.option('--pattern <pattern>', 'Regex pattern (for regex type)')
.option('-w, --weight <n>', 'Weight for scoring (default: 1)')
.option('--recursive', 'Add to all subtasks as well')
.action(
async (
id: string,
options: {
description?: string;
name: string;
pattern?: string;
recursive?: boolean;
threshold?: string;
type: string;
value?: string;
weight?: string;
},
) => {
const client = await getTrpcClient();
// Build rubric config based on type
const buildConfig = (): Record<string, any> | null => {
switch (options.type) {
case 'llm-rubric': {
return { criteria: options.description || options.name };
}
case 'contains':
case 'equals':
case 'starts-with':
case 'ends-with': {
if (!options.value) {
log.error(`--value is required for type "${options.type}"`);
return null;
}
return { value: options.value };
}
case 'regex': {
if (!options.pattern) {
log.error('--pattern is required for type "regex"');
return null;
}
return { pattern: options.pattern };
}
default: {
return { criteria: options.description || options.name };
}
}
};
const config = buildConfig();
if (!config) return;
const rubric: Record<string, any> = {
config,
id: `rubric-${Date.now()}`,
name: options.name,
type: options.type,
weight: options.weight ? Number.parseFloat(options.weight) : 1,
};
if (options.threshold) {
rubric.threshold = Number.parseInt(options.threshold, 10) / 100;
}
const addToTask = async (taskId: string) => {
const current = (await client.task.getReview.query({ id: taskId })).data as any;
const rubrics = current?.rubrics || [];
// Replace if same name exists, otherwise append
const filtered = rubrics.filter((r: any) => r.name !== options.name);
filtered.push(rubric);
await client.task.updateReview.mutate({
id: taskId,
review: {
autoRetry: current?.autoRetry ?? true,
enabled: current?.enabled ?? true,
judge: current?.judge ?? {},
maxIterations: current?.maxIterations ?? 3,
rubrics: filtered,
},
});
};
await addToTask(id);
if (options.recursive) {
const subtasks = await client.task.getSubtasks.query({ id });
for (const s of subtasks.data || []) {
await addToTask(s.id);
}
log.info(
`Rubric "${options.name}" [${options.type}] added to ${pc.bold(id)} + ${(subtasks.data || []).length} subtask(s).`,
);
} else {
log.info(`Rubric "${options.name}" [${options.type}] added.`);
}
},
);
rc.command('rm <id>')
.description('Remove a review rubric')
.requiredOption('-n, --name <name>', 'Rubric name to remove')
.option('--recursive', 'Remove from all subtasks as well')
.action(async (id: string, options: { name: string; recursive?: boolean }) => {
const client = await getTrpcClient();
const removeFromTask = async (taskId: string) => {
const current = (await client.task.getReview.query({ id: taskId })).data as any;
if (!current) return;
const rubrics = (current.rubrics || []).filter((r: any) => r.name !== options.name);
await client.task.updateReview.mutate({
id: taskId,
review: { ...current, rubrics },
});
};
await removeFromTask(id);
if (options.recursive) {
const subtasks = await client.task.getSubtasks.query({ id });
for (const s of subtasks.data || []) {
await removeFromTask(s.id);
}
log.info(
`Rubric "${options.name}" removed from ${pc.bold(id)} + ${(subtasks.data || []).length} subtask(s).`,
);
} else {
log.info(`Rubric "${options.name}" removed.`);
}
});
rv.command('run <id>')
.description('Manually run review on content')
.requiredOption('--content <text>', 'Content to review')
.action(async (id: string, options: { content: string }) => {
const client = await getTrpcClient();
const result = (await client.task.runReview.mutate({
content: options.content,
id,
})) as any;
const r = result.data;
console.log(
`\n${r.passed ? pc.green('✓ Review passed') : pc.red('✗ Review failed')} (${r.overallScore}%)`,
);
for (const s of r.rubricResults || []) {
const icon = s.passed ? pc.green('✓') : pc.red('✗');
const pct = Math.round(s.score * 100);
console.log(` ${icon} ${s.rubricId}: ${pct}%${s.reason ? `${s.reason}` : ''}`);
}
console.log();
});
}
+117
View File
@@ -0,0 +1,117 @@
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../../utils/format';
import { log } from '../../utils/logger';
import { statusBadge } from './helpers';
export function registerTopicCommands(task: Command) {
// ── topic ──────────────────────────────────────────────
const tp = task.command('topic').description('Manage task topics');
tp.command('list <id>')
.description('List topics for a task')
.option('--json [fields]', 'Output JSON')
.action(async (id: string, options: { json?: string | boolean }) => {
const client = await getTrpcClient();
const result = await client.task.getTopics.query({ id });
if (options.json !== undefined) {
outputJson(result.data, options.json);
return;
}
if (!result.data || result.data.length === 0) {
log.info('No topics found for this task.');
return;
}
const rows = result.data.map((t: any) => [
`#${t.seq}`,
t.id,
statusBadge(t.status || 'running'),
truncate(t.title || 'Untitled', 40),
t.operationId ? pc.dim(truncate(t.operationId, 20)) : '-',
timeAgo(t.createdAt),
]);
printTable(rows, ['SEQ', 'TOPIC ID', 'STATUS', 'TITLE', 'OPERATION', 'CREATED']);
});
tp.command('view <id> <topicId>')
.description('View messages of a topic (topicId can be a seq number like "1")')
.option('--json [fields]', 'Output JSON')
.action(async (id: string, topicId: string, options: { json?: string | boolean }) => {
const client = await getTrpcClient();
let resolvedTopicId = topicId;
// If it's a number, treat as seq index
const seqNum = Number.parseInt(topicId, 10);
if (!Number.isNaN(seqNum) && String(seqNum) === topicId) {
const topicsResult = await client.task.getTopics.query({ id });
const match = (topicsResult.data || []).find((t: any) => t.seq === seqNum);
if (!match) {
log.error(`Topic #${seqNum} not found for this task.`);
return;
}
resolvedTopicId = match.id;
log.info(
`Topic #${seqNum}: ${pc.bold(match.title || 'Untitled')} ${pc.dim(resolvedTopicId)}`,
);
}
const messages = await client.message.getMessages.query({ topicId: resolvedTopicId });
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();
}
});
tp.command('cancel <topicId>')
.description('Cancel a running topic and pause the task')
.action(async (topicId: string) => {
const client = await getTrpcClient();
await client.task.cancelTopic.mutate({ topicId });
log.info(`Topic ${pc.bold(topicId)} canceled. Task paused.`);
});
tp.command('delete <topicId>')
.description('Delete a topic and its messages')
.option('-y, --yes', 'Skip confirmation')
.action(async (topicId: string, options: { yes?: boolean }) => {
if (!options.yes) {
const ok = await confirm(`Delete topic ${pc.bold(topicId)} and all its messages?`);
if (!ok) return;
}
const client = await getTrpcClient();
await client.task.deleteTopic.mutate({ topicId });
log.info(`Topic ${pc.bold(topicId)} deleted.`);
});
}
+1
View File
@@ -0,0 +1 @@
export const CLI_API_KEY_ENV = 'LOBEHUB_CLI_API_KEY';
+2 -68
View File
@@ -1,69 +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 { 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 { 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);
registerCronCommand(program);
registerGenerateCommand(program);
registerFileCommand(program);
registerSkillCommand(program);
registerSessionGroupCommand(program);
registerThreadCommand(program);
registerTopicCommand(program);
registerMessageCommand(program);
registerModelCommand(program);
registerProviderCommand(program);
registerPluginCommand(program);
registerUserCommand(program);
registerConfigCommand(program);
registerEvalCommand(program);
program.parse();
createProgram().parse();
+17
View File
@@ -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')),
]);
+28
View File
@@ -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');
});
});
+148
View File
@@ -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('-', '\\-');
}
+77
View File
@@ -0,0 +1,77 @@
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 { 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 { 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);
registerThreadCommand(program);
registerTopicCommand(program);
registerMessageCommand(program);
registerModelCommand(program);
registerProviderCommand(program);
registerPluginCommand(program);
registerUserCommand(program);
registerConfigCommand(program);
registerEvalCommand(program);
return program;
}
export { version as cliVersion };
+29 -2
View File
@@ -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');
});
});
+8 -1
View File
@@ -14,10 +14,17 @@ 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 saveSettings(settings: StoredSettings): void {
const serverUrl = normalizeUrl(settings.serverUrl);
const gatewayUrl = normalizeUrl(settings.gatewayUrl);
+157
View File
@@ -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');
}
+1 -1
View File
@@ -87,7 +87,7 @@ function stripAnsi(s: string): string {
* Calculate the display width of a string in the terminal.
* CJK characters and fullwidth symbols occupy 2 columns.
*/
function displayWidth(s: string): number {
export function displayWidth(s: string): number {
const plain = stripAnsi(s);
let width = 0;
for (const char of plain) {
+14
View File
@@ -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',
});
-18
View File
@@ -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',
});
+3 -2
View File
@@ -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) {
+2 -1
View File
@@ -50,6 +50,7 @@
"@electron-toolkit/tsconfig": "^2.0.0",
"@electron-toolkit/utils": "^4.0.0",
"@lobechat/desktop-bridge": "workspace:*",
"@lobechat/device-gateway-client": "workspace:*",
"@lobechat/electron-client-ipc": "workspace:*",
"@lobechat/electron-server-ipc": "workspace:*",
"@lobechat/file-loaders": "workspace:*",
@@ -66,7 +67,7 @@
"consola": "^3.4.2",
"cookie": "^1.1.1",
"cross-env": "^10.1.0",
"diff": "^8.0.2",
"diff": "^8.0.4",
"electron": "41.0.2",
"electron-builder": "^26.8.1",
"electron-devtools-installer": "4.0.0",
+1
View File
@@ -3,5 +3,6 @@ packages:
- '../../packages/electron-client-ipc'
- '../../packages/file-loaders'
- '../../packages/desktop-bridge'
- '../../packages/device-gateway-client'
- '../../packages/local-file-shell'
- '.'
+5
View File
@@ -28,6 +28,11 @@ export const defaultProxySettings: NetworkProxySettings = {
export const STORE_DEFAULTS: ElectronMainStore = {
dataSyncConfig: { storageMode: 'cloud' },
encryptedTokens: {},
gatewayDeviceDescription: '',
gatewayDeviceId: '',
gatewayDeviceName: '',
gatewayEnabled: true,
gatewayUrl: 'https://device-gateway.lobehub.com',
locale: 'auto',
networkProxy: defaultProxySettings,
shortcuts: DEFAULT_SHORTCUTS_CONFIG,
+19 -2
View File
@@ -9,6 +9,7 @@ import type {
} from '@lobechat/electron-client-ipc';
import { BrowserWindow, shell } from 'electron';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import { appendVercelCookie } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
@@ -43,14 +44,14 @@ export default class AuthCtr extends ControllerModule {
/**
* Polling related parameters
*/
private pollingInterval: NodeJS.Timeout | null = null;
private cachedRemoteUrl: string | null = null;
/**
* Auto-refresh timer
*/
private autoRefreshTimer: NodeJS.Timeout | null = null;
/**
@@ -531,6 +532,9 @@ export default class AuthCtr extends ControllerModule {
// Start auto-refresh timer
this.startAutoRefresh();
// Connect to device gateway after successful login
this.connectGateway();
return { success: true };
} catch (error) {
logger.error('Exchanging authorization code failed:', error);
@@ -538,6 +542,19 @@ export default class AuthCtr extends ControllerModule {
}
}
/**
* Connect to device gateway (fire-and-forget)
*/
private connectGateway() {
const gatewaySrv = this.app.getService(GatewayConnectionService);
if (gatewaySrv) {
logger.info('Triggering gateway connection after login');
gatewaySrv.connect().catch((error) => {
logger.error('Gateway connection after login failed:', error);
});
}
}
/**
* Broadcast token refreshed event
*/
@@ -0,0 +1,139 @@
import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import { ControllerModule, IpcMethod } from './index';
import LocalFileCtr from './LocalFileCtr';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
import ShellCommandCtr from './ShellCommandCtr';
/**
* GatewayConnectionCtr
*
* Thin IPC layer that delegates to GatewayConnectionService.
*/
export default class GatewayConnectionCtr extends ControllerModule {
static override readonly groupName = 'gatewayConnection';
// ─── Service Accessor ───
private get service() {
return this.app.getService(GatewayConnectionService);
}
private get remoteServerConfigCtr() {
return this.app.getController(RemoteServerConfigCtr);
}
private get localFileCtr() {
return this.app.getController(LocalFileCtr);
}
private get shellCommandCtr() {
return this.app.getController(ShellCommandCtr);
}
// ─── Lifecycle ───
afterAppReady() {
const srv = this.service;
srv.loadOrCreateDeviceId();
// Wire up token provider and refresher
srv.setTokenProvider(() => this.remoteServerConfigCtr.getAccessToken());
srv.setTokenRefresher(() => this.remoteServerConfigCtr.refreshAccessToken());
// Wire up tool call handler
srv.setToolCallHandler((apiName, args) => this.executeToolCall(apiName, args));
// Auto-connect if already logged in
this.tryAutoConnect();
}
// ─── IPC Methods (Renderer → Main) ───
@IpcMethod()
async connect(): Promise<{ error?: string; success: boolean }> {
this.app.storeManager.set('gatewayEnabled', true);
return this.service.connect();
}
@IpcMethod()
async disconnect(): Promise<{ success: boolean }> {
this.app.storeManager.set('gatewayEnabled', false);
return this.service.disconnect();
}
@IpcMethod()
async getConnectionStatus(): Promise<{ status: GatewayConnectionStatus }> {
return { status: this.service.getStatus() };
}
@IpcMethod()
async getDeviceInfo(): Promise<{
description: string;
deviceId: string;
hostname: string;
name: string;
platform: string;
}> {
return this.service.getDeviceInfo();
}
@IpcMethod()
async setDeviceName(params: { name: string }): Promise<{ success: boolean }> {
this.service.setDeviceName(params.name);
return { success: true };
}
@IpcMethod()
async setDeviceDescription(params: { description: string }): Promise<{ success: boolean }> {
this.service.setDeviceDescription(params.description);
return { success: true };
}
// ─── Auto Connect ───
private async tryAutoConnect() {
const gatewayEnabled = this.app.storeManager.get('gatewayEnabled');
if (!gatewayEnabled) return;
const isConfigured = await this.remoteServerConfigCtr.isRemoteServerConfigured();
if (!isConfigured) return;
const token = await this.remoteServerConfigCtr.getAccessToken();
if (!token) return;
await this.service.connect();
}
// ─── Tool Call Routing ───
private async executeToolCall(apiName: string, args: any): Promise<unknown> {
const methodMap: Record<string, () => Promise<unknown>> = {
editLocalFile: () => this.localFileCtr.handleEditFile(args),
globLocalFiles: () => this.localFileCtr.handleGlobFiles(args),
grepContent: () => this.localFileCtr.handleGrepContent(args),
listLocalFiles: () => this.localFileCtr.listLocalFiles(args),
moveLocalFiles: () => this.localFileCtr.handleMoveFiles(args),
readLocalFile: () => this.localFileCtr.readFile(args),
renameLocalFile: () => this.localFileCtr.handleRenameFile(args),
searchLocalFiles: () => this.localFileCtr.handleLocalFilesSearch(args),
writeLocalFile: () => this.localFileCtr.handleWriteFile(args),
getCommandOutput: () => this.shellCommandCtr.handleGetCommandOutput(args),
killCommand: () => this.shellCommandCtr.handleKillCommand(args),
runCommand: () => this.shellCommandCtr.handleRunCommand(args),
};
const handler = methodMap[apiName];
if (!handler) {
throw new Error(
`Tool "${apiName}" is not available on this device. It may not be supported in the current desktop version. Please skip this tool and try alternative approaches.`,
);
}
return handler();
}
}
@@ -1,8 +1,10 @@
import { constants } from 'node:fs';
import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { access, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import {
type AuditSafePathsParams,
type AuditSafePathsResult,
type EditLocalFileParams,
type EditLocalFileResult,
type GlobFilesParams,
@@ -52,6 +54,72 @@ import { ControllerModule, IpcMethod } from './index';
// Create logger
const logger = createLogger('controllers:LocalFileCtr');
const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;
const normalizeAbsolutePath = (inputPath: string): string =>
path.normalize(path.isAbsolute(inputPath) ? inputPath : `/${inputPath}`);
const resolvePathWithScope = (inputPath: string, scope: string): string =>
path.isAbsolute(inputPath) ? inputPath : path.join(scope, inputPath);
const isWithinSafePathPrefixes = (targetPath: string, prefixes: readonly string[]): boolean =>
prefixes.some((prefix) => targetPath === prefix || targetPath.startsWith(`${prefix}${path.sep}`));
const resolveNearestExistingRealPath = async (targetPath: string): Promise<string | undefined> => {
let currentPath = targetPath;
while (true) {
try {
await access(currentPath, constants.F_OK);
return normalizeAbsolutePath(await realpath(currentPath));
} catch {
const parentPath = path.dirname(currentPath);
if (parentPath === currentPath) return undefined;
currentPath = parentPath;
}
}
};
const resolveSafePathRealPrefixes = async (): Promise<string[]> => {
const prefixes = new Set<string>(SAFE_PATH_PREFIXES);
for (const safePrefix of SAFE_PATH_PREFIXES) {
try {
prefixes.add(normalizeAbsolutePath(await realpath(safePrefix)));
} catch {
// Keep the lexical prefix if the platform does not expose this directory.
}
}
return [...prefixes];
};
const areAllPathsSafeOnDisk = async (
paths: string[],
resolveAgainstScope: string,
): Promise<boolean> => {
if (paths.length === 0) return false;
const safeRealPrefixes = await resolveSafePathRealPrefixes();
for (const currentPath of paths) {
const normalizedPath = normalizeAbsolutePath(
resolvePathWithScope(currentPath, resolveAgainstScope),
);
if (!isWithinSafePathPrefixes(normalizedPath, SAFE_PATH_PREFIXES)) {
return false;
}
const realPath = await resolveNearestExistingRealPath(normalizedPath);
if (!realPath || !isWithinSafePathPrefixes(realPath, safeRealPrefixes)) {
return false;
}
}
return true;
};
export default class LocalFileCtr extends ControllerModule {
static override readonly groupName = 'localSystem';
private get searchService() {
@@ -240,6 +308,18 @@ export default class LocalFileCtr extends ControllerModule {
return writeLocalFile({ content, path: filePath });
}
@IpcMethod()
async auditSafePaths({
paths,
resolveAgainstScope,
}: AuditSafePathsParams): Promise<AuditSafePathsResult> {
logger.debug('Auditing safe paths', { count: paths.length, resolveAgainstScope });
return {
allSafe: await areAllPathsSafeOnDisk(paths, resolveAgainstScope),
};
}
@IpcMethod()
async handlePrepareSkillDirectory({
forceRefresh,
@@ -6,6 +6,7 @@ import retry from 'async-retry';
import { safeStorage, session as electronSession } from 'electron';
import { OFFICIAL_CLOUD_SERVER } from '@/const/env';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import { appendVercelCookie } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
@@ -319,6 +320,13 @@ export default class RemoteServerConfigCtr extends ControllerModule {
// Also clear from persistent storage
logger.debug(`Deleting tokens from store key: ${this.encryptedTokensKey}`);
this.app.storeManager.delete(this.encryptedTokensKey);
// Disconnect gateway when tokens are cleared (logout / token refresh failure)
const gatewaySrv = this.app.getService(GatewayConnectionService);
if (gatewaySrv) {
logger.debug('Disconnecting gateway due to token clear');
await gatewaySrv.disconnect();
}
}
/**
@@ -1,4 +1,3 @@
import type { DataSyncConfig } from '@lobechat/electron-client-ipc';
import { BrowserWindow, shell } from 'electron';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -100,6 +99,7 @@ const mockApp = {
}
return null;
}),
getService: vi.fn(() => null),
} as unknown as App;
describe('AuthCtr', () => {
@@ -0,0 +1,606 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import GatewayConnectionCtr from '../GatewayConnectionCtr';
import LocalFileCtr from '../LocalFileCtr';
import RemoteServerConfigCtr from '../RemoteServerConfigCtr';
import ShellCommandCtr from '../ShellCommandCtr';
// ─── Mocks ───
const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {
const { EventEmitter } = require('node:events');
// Must be defined inside vi.hoisted so it's available when vi.mock factories run
class _MockGatewayClient extends EventEmitter {
static lastInstance: _MockGatewayClient | null = null;
static lastOptions: any = null;
connectionStatus = 'disconnected' as string;
currentDeviceId: string;
connect = vi.fn(async () => {
this.connectionStatus = 'connecting';
this.emit('status_changed', 'connecting');
});
disconnect = vi.fn(async () => {
this.connectionStatus = 'disconnected';
});
sendToolCallResponse = vi.fn();
constructor(options: any) {
super();
this.currentDeviceId = options.deviceId || 'mock-device-id';
_MockGatewayClient.lastInstance = this;
_MockGatewayClient.lastOptions = options;
}
// Test helpers
simulateConnected() {
this.connectionStatus = 'connected';
this.emit('status_changed', 'connected');
this.emit('connected');
}
simulateStatusChanged(status: string) {
this.connectionStatus = status;
this.emit('status_changed', status);
}
simulateToolCallRequest(apiName: string, args: object, requestId = 'req-1') {
this.emit('tool_call_request', {
requestId,
toolCall: {
apiName,
arguments: JSON.stringify(args),
identifier: 'test-tool',
},
type: 'tool_call_request',
});
}
simulateAuthExpired() {
this.emit('auth_expired');
}
simulateError(message: string) {
this.emit('error', new Error(message));
}
simulateReconnecting(delay: number) {
this.connectionStatus = 'reconnecting';
this.emit('status_changed', 'reconnecting');
this.emit('reconnecting', delay);
}
}
return {
MockGatewayClient: _MockGatewayClient,
ipcMainHandleMock: vi.fn(),
};
});
vi.mock('electron', () => ({
app: {
getPath: vi.fn((name: string) => `/mock/${name}`),
},
ipcMain: { handle: ipcMainHandleMock },
}));
vi.mock('@/utils/logger', () => ({
createLogger: () => ({
debug: vi.fn(),
error: vi.fn(),
info: vi.fn(),
verbose: vi.fn(),
warn: vi.fn(),
}),
}));
vi.mock('electron-is', () => ({
macOS: vi.fn(() => false),
windows: vi.fn(() => false),
linux: vi.fn(() => false),
}));
vi.mock('@/const/env', () => ({
OFFICIAL_CLOUD_SERVER: 'https://lobehub-cloud.com',
isMac: false,
isWindows: false,
isLinux: false,
isDev: false,
}));
vi.mock('node:crypto', () => ({
randomUUID: vi.fn(() => 'mock-device-uuid'),
}));
vi.mock('node:os', () => ({
default: { hostname: vi.fn(() => 'mock-hostname') },
}));
vi.mock('@lobechat/device-gateway-client', () => ({
GatewayClient: MockGatewayClient,
}));
// ─── Mock Controllers ───
const mockLocalFileCtr = {
handleEditFile: vi.fn().mockResolvedValue({ success: true }),
handleGlobFiles: vi.fn().mockResolvedValue({ files: [] }),
handleGrepContent: vi.fn().mockResolvedValue({ matches: [] }),
handleLocalFilesSearch: vi.fn().mockResolvedValue([]),
handleMoveFiles: vi.fn().mockResolvedValue([]),
handleRenameFile: vi.fn().mockResolvedValue({ newPath: '/mock/renamed.txt', success: true }),
handleWriteFile: vi.fn().mockResolvedValue({ success: true }),
listLocalFiles: vi.fn().mockResolvedValue([]),
readFile: vi.fn().mockResolvedValue({
charCount: 12,
content: 'file content',
createdTime: new Date('2024-01-01'),
filename: 'test.txt',
fileType: '.txt',
lineCount: 1,
loc: [1, 1] as [number, number],
modifiedTime: new Date('2024-01-01'),
totalCharCount: 12,
totalLineCount: 1,
}),
} as unknown as LocalFileCtr;
const mockShellCommandCtr = {
handleGetCommandOutput: vi.fn().mockResolvedValue({ output: '' }),
handleKillCommand: vi.fn().mockResolvedValue({ success: true }),
handleRunCommand: vi.fn().mockResolvedValue({ success: true, stdout: '' }),
} as unknown as ShellCommandCtr;
const mockRemoteServerConfigCtr = {
getAccessToken: vi.fn().mockResolvedValue('mock-access-token'),
isRemoteServerConfigured: vi.fn().mockResolvedValue(true),
refreshAccessToken: vi.fn().mockResolvedValue({ success: true }),
} as unknown as RemoteServerConfigCtr;
const mockBroadcast = vi.fn();
const mockStoreGet = vi.fn();
const mockStoreSet = vi.fn();
const mockApp = {
browserManager: { broadcastToAllWindows: mockBroadcast },
getController: vi.fn((Cls) => {
if (Cls === RemoteServerConfigCtr) return mockRemoteServerConfigCtr;
if (Cls === LocalFileCtr) return mockLocalFileCtr;
if (Cls === ShellCommandCtr) return mockShellCommandCtr;
return null;
}),
getService: vi.fn((Cls) => {
if (Cls === GatewayConnectionService) return mockGatewayConnectionSrv;
return null;
}),
storeManager: { get: mockStoreGet, set: mockStoreSet },
} as unknown as App;
// Lazily initialized — created in beforeEach so it uses the current mockApp
let mockGatewayConnectionSrv: GatewayConnectionService;
// ─── Test Suite ───
describe('GatewayConnectionCtr', () => {
let ctr: GatewayConnectionCtr;
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
MockGatewayClient.lastInstance = null;
MockGatewayClient.lastOptions = null;
mockStoreGet.mockImplementation((key: string) => {
if (key === 'gatewayEnabled') return true;
return undefined;
});
mockGatewayConnectionSrv = new GatewayConnectionService(mockApp);
ctr = new GatewayConnectionCtr(mockApp);
});
afterEach(() => {
ctr.disconnect();
vi.useRealTimers();
});
// ─── Connection ───
describe('connect', () => {
it('should create GatewayClient with correct options', async () => {
mockStoreGet.mockImplementation((key: string) => {
if (key === 'gatewayEnabled') return true;
if (key === 'gatewayDeviceId') return 'stored-device-id';
if (key === 'gatewayUrl') return undefined;
return undefined;
});
ctr = new GatewayConnectionCtr(mockApp);
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const options = MockGatewayClient.lastOptions;
expect(options).not.toBeNull();
expect(options.token).toBe('mock-access-token');
expect(options.deviceId).toBe('stored-device-id');
expect(options.gatewayUrl).toBe('https://device-gateway.lobehub.com');
expect(options.logger).toBeDefined();
});
it('should use custom gateway URL from store when set', async () => {
mockStoreGet.mockImplementation((key: string) => {
if (key === 'gatewayEnabled') return true;
if (key === 'gatewayUrl') return 'http://localhost:8787';
return undefined;
});
ctr = new GatewayConnectionCtr(mockApp);
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastOptions.gatewayUrl).toBe('http://localhost:8787');
});
it('should return success:false when no access token', async () => {
// Prevent auto-connect, then set up providers manually
vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValueOnce(null);
const result = await ctr.connect();
expect(result).toEqual({ error: 'No access token available', success: false });
expect(MockGatewayClient.lastInstance).toBeNull();
});
it('should persist gatewayEnabled=true on connect', async () => {
vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
mockStoreSet.mockClear();
await ctr.connect();
expect(mockStoreSet).toHaveBeenCalledWith('gatewayEnabled', true);
});
it('should no-op when already connected', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const firstClient = MockGatewayClient.lastInstance;
firstClient!.simulateConnected();
const result = await ctr.connect();
expect(result).toEqual({ success: true });
// No new client created
expect(MockGatewayClient.lastInstance).toBe(firstClient);
});
it('should broadcast status changes: disconnected → connecting → connected', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {
status: 'connecting',
});
MockGatewayClient.lastInstance!.simulateConnected();
expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {
status: 'connected',
});
});
});
// ─── Disconnect ───
describe('disconnect', () => {
it('should disconnect client and set status to disconnected', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
mockBroadcast.mockClear();
await ctr.disconnect();
expect(client.disconnect).toHaveBeenCalled();
expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {
status: 'disconnected',
});
});
it('should persist gatewayEnabled=false on disconnect', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
MockGatewayClient.lastInstance!.simulateConnected();
mockStoreSet.mockClear();
await ctr.disconnect();
expect(mockStoreSet).toHaveBeenCalledWith('gatewayEnabled', false);
});
it('should not trigger reconnect after intentional disconnect', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
await ctr.disconnect();
mockBroadcast.mockClear();
// Advance timers — no reconnect should happen
await vi.advanceTimersByTimeAsync(60_000);
expect(mockBroadcast).not.toHaveBeenCalledWith('gatewayConnectionStatusChanged', {
status: 'reconnecting',
});
});
});
// ─── Auto-Connect ───
describe('afterAppReady (auto-connect)', () => {
it('should auto-connect when server is configured and token exists', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).not.toBeNull();
expect(MockGatewayClient.lastInstance!.connect).toHaveBeenCalled();
});
it('should skip auto-connect when gatewayEnabled is false', async () => {
mockStoreGet.mockImplementation((key: string) => {
if (key === 'gatewayEnabled') return false;
return undefined;
});
ctr = new GatewayConnectionCtr(mockApp);
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).toBeNull();
});
it('should skip auto-connect when remote server not configured', async () => {
vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).toBeNull();
});
it('should skip auto-connect when no access token', async () => {
vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValueOnce(null);
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).toBeNull();
});
it('should create device ID on first launch and persist it', () => {
mockStoreGet.mockReturnValue(undefined);
ctr.afterAppReady();
expect(mockStoreSet).toHaveBeenCalledWith('gatewayDeviceId', 'mock-device-uuid');
});
it('should reuse persisted device ID', () => {
mockStoreGet.mockImplementation((key: string) => {
if (key === 'gatewayEnabled') return true;
if (key === 'gatewayDeviceId') return 'existing-id';
return undefined;
});
ctr = new GatewayConnectionCtr(mockApp);
ctr.afterAppReady();
expect(mockStoreSet).not.toHaveBeenCalledWith('gatewayDeviceId', expect.anything());
});
});
// ─── Reconnection ───
describe('reconnection', () => {
it('should broadcast reconnecting status when client emits reconnecting', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
mockBroadcast.mockClear();
client.simulateReconnecting(1000);
expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {
status: 'reconnecting',
});
});
});
// ─── Tool Call Routing ───
describe('tool call routing', () => {
async function connectAndOpen() {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
return client;
}
it.each([
['readLocalFile', 'readFile', mockLocalFileCtr],
['listLocalFiles', 'listLocalFiles', mockLocalFileCtr],
['moveLocalFiles', 'handleMoveFiles', mockLocalFileCtr],
['renameLocalFile', 'handleRenameFile', mockLocalFileCtr],
['searchLocalFiles', 'handleLocalFilesSearch', mockLocalFileCtr],
['writeLocalFile', 'handleWriteFile', mockLocalFileCtr],
['editLocalFile', 'handleEditFile', mockLocalFileCtr],
['globLocalFiles', 'handleGlobFiles', mockLocalFileCtr],
['grepContent', 'handleGrepContent', mockLocalFileCtr],
['runCommand', 'handleRunCommand', mockShellCommandCtr],
['getCommandOutput', 'handleGetCommandOutput', mockShellCommandCtr],
['killCommand', 'handleKillCommand', mockShellCommandCtr],
] as const)('should route %s to %s', async (apiName, methodName, controller) => {
const client = await connectAndOpen();
const args = { test: 'arg' };
client.simulateToolCallRequest(apiName, args);
await vi.advanceTimersByTimeAsync(0);
expect((controller as any)[methodName]).toHaveBeenCalledWith(args);
});
it('should send tool_call_response with success result', async () => {
vi.mocked(mockLocalFileCtr.readFile).mockResolvedValueOnce({
charCount: 5,
content: 'hello',
createdTime: new Date('2024-01-01'),
filename: 'a.txt',
fileType: '.txt',
lineCount: 1,
loc: [1, 1] as [number, number],
modifiedTime: new Date('2024-01-01'),
totalCharCount: 5,
totalLineCount: 1,
});
const client = await connectAndOpen();
client.simulateToolCallRequest('readLocalFile', { path: '/a.txt' }, 'req-42');
await vi.advanceTimersByTimeAsync(0);
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-42',
result: {
content: JSON.stringify({
charCount: 5,
content: 'hello',
createdTime: new Date('2024-01-01'),
filename: 'a.txt',
fileType: '.txt',
lineCount: 1,
loc: [1, 1],
modifiedTime: new Date('2024-01-01'),
totalCharCount: 5,
totalLineCount: 1,
}),
success: true,
},
});
});
it('should send tool_call_response with error on failure', async () => {
vi.mocked(mockLocalFileCtr.readFile).mockRejectedValueOnce(new Error('File not found'));
const client = await connectAndOpen();
client.simulateToolCallRequest('readLocalFile', { path: '/missing' }, 'req-err');
await vi.advanceTimersByTimeAsync(0);
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-err',
result: {
content: 'File not found',
error: 'File not found',
success: false,
},
});
});
it('should send error for unknown apiName', async () => {
const client = await connectAndOpen();
client.simulateToolCallRequest('unknownApi', {}, 'req-unknown');
await vi.advanceTimersByTimeAsync(0);
const errorMsg =
'Tool "unknownApi" is not available on this device. It may not be supported in the current desktop version. Please skip this tool and try alternative approaches.';
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-unknown',
result: {
content: errorMsg,
error: errorMsg,
success: false,
},
});
});
});
// ─── Auth Expired ───
describe('auth_expired handling', () => {
it('should refresh token and reconnect on auth_expired', async () => {
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const client1 = MockGatewayClient.lastInstance!;
client1.simulateConnected();
client1.simulateAuthExpired();
await vi.advanceTimersByTimeAsync(0);
expect(mockRemoteServerConfigCtr.refreshAccessToken).toHaveBeenCalled();
// Should have created a new GatewayClient for reconnection
expect(MockGatewayClient.lastInstance).not.toBe(client1);
expect(MockGatewayClient.lastInstance!.connect).toHaveBeenCalled();
});
it('should set status to disconnected when token refresh fails', async () => {
vi.mocked(mockRemoteServerConfigCtr.refreshAccessToken).mockResolvedValueOnce({
error: 'invalid_grant',
success: false,
});
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
mockBroadcast.mockClear();
client.simulateAuthExpired();
await vi.advanceTimersByTimeAsync(0);
expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {
status: 'disconnected',
});
});
});
// ─── IPC Methods ───
describe('getConnectionStatus', () => {
it('should return current status', async () => {
expect(await ctr.getConnectionStatus()).toEqual({ status: 'disconnected' });
ctr.afterAppReady();
await vi.advanceTimersByTimeAsync(0);
expect(await ctr.getConnectionStatus()).toEqual({ status: 'connecting' });
MockGatewayClient.lastInstance!.simulateConnected();
expect(await ctr.getConnectionStatus()).toEqual({ status: 'connected' });
});
});
describe('getDeviceInfo', () => {
it('should return device information', async () => {
mockStoreGet.mockImplementation((key: string) => {
if (key === 'gatewayEnabled') return true;
if (key === 'gatewayDeviceId') return 'my-device';
return undefined;
});
ctr = new GatewayConnectionCtr(mockApp);
ctr.afterAppReady();
const info = await ctr.getDeviceInfo();
expect(info).toEqual({
description: '',
deviceId: 'my-device',
hostname: 'mock-hostname',
name: 'mock-hostname',
platform: process.platform,
});
});
});
});
@@ -45,6 +45,7 @@ vi.mock('node:fs/promises', () => ({
mkdir: vi.fn(),
readFile: vi.fn(),
readdir: vi.fn(),
realpath: vi.fn(),
rename: vi.fn(),
rm: vi.fn(),
stat: vi.fn(),
@@ -301,6 +302,46 @@ describe('LocalFileCtr', () => {
});
});
describe('auditSafePaths', () => {
it('should treat real temporary paths as safe', async () => {
vi.mocked(mockFsPromises.access).mockResolvedValue(undefined);
vi.mocked(mockFsPromises.realpath).mockImplementation(async (targetPath: string) => {
if (targetPath === '/tmp') return '/private/tmp';
if (targetPath === '/var/tmp') return '/private/var/tmp';
if (targetPath === '/tmp/out') return '/private/tmp/out';
return targetPath;
});
const result = await localFileCtr.auditSafePaths({
paths: ['/tmp/out'],
resolveAgainstScope: '/Users/me/project',
});
expect(result).toEqual({ allSafe: true });
});
it('should reject safe-path candidates whose real target escapes the temporary roots', async () => {
vi.mocked(mockFsPromises.access).mockImplementation(async (targetPath: string) => {
if (targetPath === '/tmp/out/config') {
throw new Error('ENOENT');
}
});
vi.mocked(mockFsPromises.realpath).mockImplementation(async (targetPath: string) => {
if (targetPath === '/tmp') return '/private/tmp';
if (targetPath === '/var/tmp') return '/private/var/tmp';
if (targetPath === '/tmp/out') return '/Users/me/.ssh';
return targetPath;
});
const result = await localFileCtr.auditSafePaths({
paths: ['/tmp/out/config'],
resolveAgainstScope: '/Users/me/project',
});
expect(result).toEqual({ allSafe: false });
});
});
describe('handlePrepareSkillDirectory', () => {
it('should download and extract a skill zip into a local cache directory', async () => {
const zipped = zipSync({
@@ -47,8 +47,14 @@ const mockBrowserManager = {
broadcastToAllWindows: vi.fn(),
};
const mockGatewayConnectionSrv = {
disconnect: vi.fn().mockResolvedValue({ success: true }),
};
const mockApp = {
browserManager: mockBrowserManager,
getController: vi.fn(),
getService: vi.fn().mockReturnValue(mockGatewayConnectionSrv),
storeManager: mockStoreManager,
} as unknown as App;
@@ -294,6 +300,13 @@ describe('RemoteServerConfigCtr', () => {
const accessToken = await controller.getAccessToken();
expect(accessToken).toBeNull();
});
it('should disconnect gateway when tokens are cleared', async () => {
await controller.saveTokens('access', 'refresh', 3600);
await controller.clearTokens();
expect(mockGatewayConnectionSrv.disconnect).toHaveBeenCalled();
});
});
describe('getTokenExpiresAt', () => {
@@ -3,6 +3,7 @@ import type { CreateServicesResult, IpcServiceConstructor, MergeIpcService } fro
import AuthCtr from './AuthCtr';
import BrowserWindowsCtr from './BrowserWindowsCtr';
import DevtoolsCtr from './DevtoolsCtr';
import GatewayConnectionCtr from './GatewayConnectionCtr';
import LocalFileCtr from './LocalFileCtr';
import McpCtr from './McpCtr';
import McpInstallCtr from './McpInstallCtr';
@@ -23,6 +24,7 @@ export const controllerIpcConstructors = [
AuthCtr,
BrowserWindowsCtr,
DevtoolsCtr,
GatewayConnectionCtr,
LocalFileCtr,
McpCtr,
McpInstallCtr,
@@ -0,0 +1,317 @@
import { randomUUID } from 'node:crypto';
import os from 'node:os';
import type {
SystemInfoRequestMessage,
ToolCallRequestMessage,
} from '@lobechat/device-gateway-client';
import { GatewayClient } from '@lobechat/device-gateway-client';
import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
import { app } from 'electron';
import { createLogger } from '@/utils/logger';
import { ServiceModule } from './index';
const logger = createLogger('services:GatewayConnectionSrv');
const DEFAULT_GATEWAY_URL = 'https://device-gateway.lobehub.com';
interface ToolCallHandler {
(apiName: string, args: any): Promise<unknown>;
}
/**
* GatewayConnectionService
*
* Core business logic for managing WebSocket connection to the cloud device-gateway.
* Extracted from GatewayConnectionCtr so other controllers can reuse connect/disconnect.
*/
export default class GatewayConnectionService extends ServiceModule {
private client: GatewayClient | null = null;
private status: GatewayConnectionStatus = 'disconnected';
private deviceId: string | null = null;
private tokenProvider: (() => Promise<string | null>) | null = null;
private tokenRefresher: (() => Promise<{ error?: string; success: boolean }>) | null = null;
private toolCallHandler: ToolCallHandler | null = null;
// ─── Configuration ───
/**
* Set token provider function (to decouple from RemoteServerConfigCtr)
*/
setTokenProvider(provider: () => Promise<string | null>) {
this.tokenProvider = provider;
}
/**
* Set token refresher function (for auth_expired handling)
*/
setTokenRefresher(refresher: () => Promise<{ error?: string; success: boolean }>) {
this.tokenRefresher = refresher;
}
/**
* Set tool call handler (to route tool calls to LocalFileCtr/ShellCommandCtr)
*/
setToolCallHandler(handler: ToolCallHandler) {
this.toolCallHandler = handler;
}
// ─── Device ID ───
loadOrCreateDeviceId() {
const stored = this.app.storeManager.get('gatewayDeviceId') as string | undefined;
if (stored) {
this.deviceId = stored;
} else {
this.deviceId = randomUUID();
this.app.storeManager.set('gatewayDeviceId', this.deviceId);
}
logger.debug(`Device ID: ${this.deviceId}`);
}
getDeviceId(): string {
return this.deviceId || 'unknown';
}
// ─── Connection Status ───
getStatus(): GatewayConnectionStatus {
return this.status;
}
getDeviceInfo() {
return {
description: this.getDeviceDescription(),
deviceId: this.getDeviceId(),
hostname: os.hostname(),
name: this.getDeviceName(),
platform: process.platform,
};
}
// ─── Device Name & Description ───
getDeviceName(): string {
return (this.app.storeManager.get('gatewayDeviceName') as string) || os.hostname();
}
setDeviceName(name: string) {
this.app.storeManager.set('gatewayDeviceName', name);
}
getDeviceDescription(): string {
return (this.app.storeManager.get('gatewayDeviceDescription') as string) || '';
}
setDeviceDescription(description: string) {
this.app.storeManager.set('gatewayDeviceDescription', description);
}
// ─── Connection Logic ───
async connect(): Promise<{ error?: string; success: boolean }> {
if (this.status === 'connected' || this.status === 'connecting') {
return { success: true };
}
return this.doConnect();
}
async disconnect(): Promise<{ success: boolean }> {
if (this.client) {
await this.client.disconnect();
this.client = null;
}
this.setStatus('disconnected');
return { success: true };
}
private async doConnect(): Promise<{ error?: string; success: boolean }> {
// Clean up any existing client
if (this.client) {
await this.client.disconnect();
this.client = null;
}
if (!this.tokenProvider) {
logger.warn('Cannot connect: no token provider configured');
return { error: 'No token provider configured', success: false };
}
const token = await this.tokenProvider();
if (!token) {
logger.warn('Cannot connect: no access token');
return { error: 'No access token available', success: false };
}
const gatewayUrl = this.getGatewayUrl();
const userId = this.extractUserIdFromToken(token);
logger.info(`Connecting to device gateway: ${gatewayUrl}, userId: ${userId || 'unknown'}`);
const client = new GatewayClient({
deviceId: this.getDeviceId(),
gatewayUrl,
logger,
token,
userId: userId || undefined,
});
this.setupClientEvents(client);
this.client = client;
await client.connect();
return { success: true };
}
private setupClientEvents(client: GatewayClient) {
client.on('status_changed', (status) => {
this.setStatus(status);
});
client.on('tool_call_request', (request) => {
this.handleToolCallRequest(request, client);
});
client.on('system_info_request', (request) => {
this.handleSystemInfoRequest(client, request);
});
client.on('auth_expired', () => {
logger.warn('Received auth_expired, will reconnect with refreshed token');
this.handleAuthExpired();
});
client.on('error', (error) => {
logger.error('WebSocket error:', error.message);
});
}
// ─── Auth Expired Handling ───
private async handleAuthExpired() {
// Disconnect the current client
if (this.client) {
await this.client.disconnect();
this.client = null;
}
if (!this.tokenRefresher) {
logger.error('No token refresher configured, cannot handle auth_expired');
this.setStatus('disconnected');
return;
}
logger.info('Attempting token refresh before reconnect');
const result = await this.tokenRefresher();
if (result.success) {
logger.info('Token refreshed, reconnecting');
await this.doConnect();
} else {
logger.error('Token refresh failed:', result.error);
this.setStatus('disconnected');
}
}
// ─── System Info ───
private handleSystemInfoRequest(client: GatewayClient, request: SystemInfoRequestMessage) {
logger.info(`Received system_info_request: requestId=${request.requestId}`);
client.sendSystemInfoResponse({
requestId: request.requestId,
result: {
success: true,
systemInfo: {
arch: os.arch(),
desktopPath: app.getPath('desktop'),
documentsPath: app.getPath('documents'),
downloadsPath: app.getPath('downloads'),
homePath: app.getPath('home'),
musicPath: app.getPath('music'),
picturesPath: app.getPath('pictures'),
userDataPath: app.getPath('userData'),
videosPath: app.getPath('videos'),
workingDirectory: process.cwd(),
},
},
});
}
// ─── Tool Call Routing ───
private handleToolCallRequest = async (
request: ToolCallRequestMessage,
client: GatewayClient,
) => {
const { requestId, toolCall } = request;
const { apiName, arguments: argsStr } = toolCall;
logger.info(`Received tool call: apiName=${apiName}, requestId=${requestId}`);
try {
if (!this.toolCallHandler) {
throw new Error('No tool call handler configured');
}
const args = JSON.parse(argsStr);
const result = await this.toolCallHandler(apiName, args);
client.sendToolCallResponse({
requestId,
result: {
content: typeof result === 'string' ? result : JSON.stringify(result),
success: true,
},
});
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`Tool call failed: apiName=${apiName}, error=${errorMsg}`);
client.sendToolCallResponse({
requestId,
result: {
content: errorMsg,
error: errorMsg,
success: false,
},
});
}
};
// ─── Status Broadcasting ───
private setStatus(status: GatewayConnectionStatus) {
if (this.status === status) return;
logger.info(`Connection status: ${this.status}${status}`);
this.status = status;
this.app.browserManager.broadcastToAllWindows('gatewayConnectionStatusChanged', { status });
}
// ─── Gateway URL ───
private getGatewayUrl(): string {
return this.app.storeManager.get('gatewayUrl') || DEFAULT_GATEWAY_URL;
}
// ─── Token Helpers ───
/**
* Extract userId (sub claim) from JWT without verification.
* The token will be verified server-side; we just need the userId for routing.
*/
private extractUserIdFromToken(token: string): string | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf-8'));
return payload.sub || null;
} catch {
logger.warn('Failed to extract userId from JWT token');
return null;
}
}
}
+5
View File
@@ -12,6 +12,11 @@ export interface ElectronMainStore {
lastRefreshAt?: number;
refreshToken?: string;
};
gatewayDeviceDescription: string;
gatewayDeviceId: string;
gatewayDeviceName: string;
gatewayEnabled: boolean;
gatewayUrl: string;
locale: string;
networkProxy: NetworkProxySettings;
shortcuts: Record<string, string>;
+17 -16
View File
@@ -1,7 +1,7 @@
import { DurableObject } from 'cloudflare:workers';
import { Hono } from 'hono';
import { verifyDesktopToken } from './auth';
import { resolveSocketAuth, verifyApiKeyToken, verifyDesktopToken } from './auth';
import type { DeviceAttachment, Env } from './types';
const AUTH_TIMEOUT = 10_000; // 10s to authenticate after connect
@@ -58,24 +58,25 @@ export class DeviceGatewayDO extends DurableObject<Env> {
if (att.authenticated) return; // Already authenticated, ignore
try {
const token = data.token as string;
if (!token) throw new Error('Missing token');
const token = data.token as string | undefined;
const tokenType = data.tokenType as 'apiKey' | 'jwt' | 'serviceToken' | undefined;
const serverUrl = data.serverUrl as string | undefined;
const storedUserId = await this.ctx.storage.get<string>('_userId');
let verifiedUserId: string;
if (token === this.env.SERVICE_TOKEN) {
// Service token auth (for CLI debugging)
const storedUserId = await this.ctx.storage.get<string>('_userId');
if (!storedUserId) throw new Error('Missing userId');
verifiedUserId = storedUserId;
} else {
// JWT auth (normal desktop flow)
const result = await verifyDesktopToken(this.env, token);
verifiedUserId = result.userId;
}
const verifiedUserId = await resolveSocketAuth({
serverUrl,
serviceToken: this.env.SERVICE_TOKEN,
storedUserId,
token,
tokenType,
verifyApiKey: verifyApiKeyToken,
verifyJwt: async (jwt) => {
const result = await verifyDesktopToken(this.env, jwt);
return { userId: result.userId };
},
});
// Verify userId matches the DO routing
const storedUserId = await this.ctx.storage.get<string>('_userId');
if (storedUserId && verifiedUserId !== storedUserId) {
throw new Error('userId mismatch');
}

Some files were not shown because too many files have changed in this diff Show More