Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(im): 新增 Lark 机器人接入 (#1133)

DavidShenXD8d6952e0579c
diff --git a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
index 716940db39..f9b9224fa4 100644
--- a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
+++ b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
@@ -34,7 +34,8 @@ vi.mock('../../ownerScopedStorage', () => ({
import type { FeishuIM } from '@cindy/im';
import { buildFeishuAdapter } from '../adapter';
-const fakeIm = {} as unknown as FeishuIM;
+const getService = vi.fn<() => 'feishu' | 'lark'>(() => 'feishu');
+const fakeIm = { getService } as unknown as FeishuIM;
const CONFIG = {
agentKind: 'claude-code' as const,
defaultModel: 'claude-opus-4-7',
@@ -77,7 +78,15 @@ describe('feishu ImChannelAdapter characterization', () => {
it('会话落「对话」分组(workspaceKind=dialogue) + oneshot 起名前缀 [飞书·DM]', () => {
expect(adapter.sessions.workspaceKind).toBe('dialogue');
- expect(adapter.sessions.generatedTitlePrefix).toBe('[飞书·DM] ');
+ expect(adapter.sessions.generatedTitlePrefix).toBeTypeOf('function');
+ expect((adapter.sessions.generatedTitlePrefix as () => string)()).toBe('[飞书·DM] ');
+ });
+
+ it('Lark 凭据使用独立的 Lark 会话标题', () => {
+ getService.mockReturnValueOnce('lark');
+ expect(adapter.sessions.defaultTitle('ou_1234567890')).toBe('[Lark·DM] 567890');
+ getService.mockReturnValueOnce('lark');
+ expect((adapter.sessions.generatedTitlePrefix as () => string)()).toBe('[Lark·DM] ');
});
it('workingDir = userData/im-working-dir/{botAppId}(同 bot 共享)', () => {
diff --git a/apps/desktop/src/main/im/feishu/adapter.ts b/apps/desktop/src/main/im/feishu/adapter.ts
index 65259cc9b1..e6791e1c52 100644
--- a/apps/desktop/src/main/im/feishu/adapter.ts
+++ b/apps/desktop/src/main/im/feishu/adapter.ts
@@ -37,6 +37,7 @@ export function buildFeishuAdapter(
feishuIm: FeishuIM,
config: ImOrchestratorConfig,
): ImChannelAdapter {
+ const conversationPrefix = () => (feishuIm.getService() === 'lark' ? '[Lark·DM] ' : '[飞书·DM] ');
return {
channel: 'feishu',
im: feishuIm,
@@ -53,10 +54,10 @@ export function buildFeishuAdapter(
* `feishu_{botAppId}_{openId}` — long but human-readable, easy to grep。
*/
sessionIdFor: (botAppId, openId) => `feishu_${botAppId}_${openId}`,
- defaultTitle: (openId) => `[飞书·DM] ${openId.slice(-6)}`,
+ defaultTitle: (openId) => `${conversationPrefix()}${openId.slice(-6)}`,
// 首条消息(含每次 /new 后的首条)oneshot 起名的前缀 —— 与 hook Slack 的
// `[Slack·DM]` 同款视觉, 在「对话」分组里一眼认出渠道
- generatedTitlePrefix: '[飞书·DM] ',
+ generatedTitlePrefix: conversationPrefix,
// 飞书 bot 私聊会话进侧边栏「对话」分组; workingDir 是 app 托管的
// im-working-dir, 不该以它聚成假项目组
workspaceKind: 'dialogue',
diff --git a/apps/desktop/src/main/im/feishu/uiText.ts b/apps/desktop/src/main/im/feishu/uiText.ts
index a8e24f91b4..c68dbf67d1 100644
--- a/apps/desktop/src/main/im/feishu/uiText.ts
+++ b/apps/desktop/src/main/im/feishu/uiText.ts
@@ -133,7 +133,8 @@ export const ui = {
resolved: (label: string) => `✅ 权限模式切到 ${label} 了`,
failed: (reason: string) => `❌ 权限模式没切过去:${reason}`,
fullAccessConfirmTitle: '⚠️ 确认开启 Full access?',
- fullAccessConfirmBody: 'Full access 会关闭工作区沙箱并跳过常规审批。Cindy 可以修改工作区外的文件、执行联网命令且不再询问;内置高风险操作仍会要求确认。',
+ fullAccessConfirmBody:
+ 'Full access 会关闭工作区沙箱并跳过常规审批。Cindy 可以修改工作区外的文件、执行联网命令且不再询问;内置高风险操作仍会要求确认。',
btnConfirmFullAccess: '开启 Full access',
btnCancelFullAccess: '保留当前权限',
fullAccessCancelled: '已取消,保留当前权限',
@@ -181,7 +182,7 @@ export const ui = {
(sessionTitle: string) =>
`⏳ 正在让你接管 **${sessionTitle}**…\n_📦 加载存档元数据_ · _🔌 接通 agent 通道_ · _🧠 复盘上回合战况_\n_三两秒就好,咖啡别一口闷完_`,
(sessionTitle: string) =>
- `🎮 登入 **${sessionTitle}** 中…\n_早期版本里,等不及的玩家会狂点飞书图标,但其实并没有用_`,
+ `🎮 登入 **${sessionTitle}** 中…\n_早期版本里,等不及的玩家会狂点聊天工具图标,但其实并没有用_`,
(sessionTitle: string) =>
`⌛ **${sessionTitle}** 加载中… 99%\n_这条进度条是真的——Haiku 正在翻你们上回合聊了啥_`,
(sessionTitle: string) =>
@@ -191,9 +192,9 @@ export const ui = {
// 这个是给 agent 的指令(不是给用户看的), 让 agent 用一段简短话回顾现状 +
// 问用户下一步意图。fanout listener 会把 agent 输出推到飞书卡片。
sessionAttachedOneshotPrompts: [
- '我刚通过飞书远程上号了——简单同步下战况:上回合咋样、当前在哪一步,然后问我下一步咋走。',
+ '我刚通过 IM 远程上号了——简单同步下战况:上回合咋样、当前在哪一步,然后问我下一步咋走。',
'我接力了——一句话过下进度,告诉我现在到哪、刚做了啥,再问我要不要继续推进或者换方向。',
- 'Hi 我从飞书接手了——快速 brief 一下当前形势、最新结果是啥,最后问我下一步指令。',
+ 'Hi 我从 IM 接手了——快速 brief 一下当前形势、最新结果是啥,最后问我下一步指令。',
'切到我了——简单复盘下,告诉我现在是什么阶段,然后问我要不要继续干。',
],
// ── /ctr new: 新建空白 session 接管成功后 ──
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index a05bed7771..4dda807b97 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -402,10 +402,7 @@ export function createTurnRunner(
* agent switch 主动 close 的旧 Session。只有对象身份和 close reason 都匹配才
* 忽略;同一业务 sessionId 下的用户关闭或新引擎关闭必须照常清缓存。
*/
- const agentSwitchCloseSuppressed = new Map<
- string,
- { expectedSession: MakerSession }
- >();
+ const agentSwitchCloseSuppressed = new Map<string, { expectedSession: MakerSession }>();
type MakerInstance = ReturnType<typeof getMaker>;
let subscribedMaker: MakerInstance | null = null;
let unsubscribeMakerEvents: (() => void) | null = null;
@@ -417,10 +414,7 @@ export function createTurnRunner(
unsubscribeMakerEvents = maker.on((event) => {
if (event.type !== 'session:closed') return;
const suppression = agentSwitchCloseSuppressed.get(event.sessionId);
- if (
- suppression?.expectedSession === event.session &&
- event.reason === 'agent-switch'
- ) return;
+ if (suppression?.expectedSession === event.session && event.reason === 'agent-switch') return;
forgetClosedSession(event.sessionId, 'maker session closed');
});
}
@@ -1404,8 +1398,9 @@ export function createTurnRunner(
headerCardId: string | null,
): Promise<void> {
const threadUiPack = adapter.ui.thread;
- const prefix = adapter.sessions.generatedTitlePrefix;
- if (prefix === undefined && !(adapter.threadScoped && threadUiPack)) return;
+ const configuredPrefix = adapter.sessions.generatedTitlePrefix;
+ if (configuredPrefix === undefined && !(adapter.threadScoped && threadUiPack)) return;
+ const prefix = typeof configuredPrefix === 'function' ? configuredPrefix() : configuredPrefix;
try {
const title = await generateAndPersistFbotTitle(sessionId, text, prefix);
if (!title || !headerCardId || !threadUiPack) return;
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index 4a3533d9fe..a0f35902db 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -85,7 +85,7 @@ export interface ImSessionNamespace {
* 缺省时 threadScoped 渠道回落 FBot 前缀, 非 threadScoped 渠道不起名
* (保持 defaultTitle)。接管 session 一律沿用 FBot 前缀, 不走这里。
*/
- generatedTitlePrefix?: string;
+ generatedTitlePrefix?: string | (() => string);
}
/**
@@ -133,10 +133,7 @@ export interface ImChannelAdapter {
* Text-only channels can still resolve agent interactions without rich cards.
* The callback owns channel-specific correlation and parsing.
*/
- handleTextInteraction?(
- userId: string,
- request: InteractionRequest,
- ): Promise<InteractionDecision>;
+ handleTextInteraction?(userId: string, request: InteractionRequest): Promise<InteractionDecision>;
/** Durable channels may promote task-scoped attachments after message persistence succeeds. */
onUserMessagePersisted?(args: {
sessionId: string;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 2226abaca8..c38fcceb81 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1461,16 +1461,21 @@ contextBridge.exposeInMainWorld('electronAPI', {
ownerOpenId: string | null;
error?: string;
lifecycleAnnouncement: boolean;
+ service: 'feishu' | 'lark';
}> => ipcRenderer.invoke('feishuBot:get-state'),
- save: (payload: { appId: string; appSecret: string }): Promise<{
+ save: (payload: {
+ appId: string;
+ appSecret: string;
+ service: 'feishu' | 'lark';
+ }): Promise<{
verdict: 'connected' | 'conflict' | 'error' | 'pending';
}> => ipcRenderer.invoke('feishuBot:save', payload),
- reconnect: (): Promise<{ verdict: 'connected' | 'conflict' | 'error' }> =>
- ipcRenderer.invoke('feishuBot:reconnect'),
+ reconnect: (): Promise<{ verdict: 'connected' | 'conflict' | 'error' }> => ipcRenderer.invoke('feishuBot:reconnect'),
clear: (): Promise<{ ok: true }> => ipcRenderer.invoke('feishuBot:clear'),
- setLifecycleAnnouncement: (enabled: boolean): Promise<{ ok: true }> =>
- ipcRenderer.invoke('feishuBot:set-lifecycle-announcement', { enabled }),
- registrationBegin: (): Promise<{
+ setLifecycleAnnouncement: (enabled: boolean): Promise<{ ok: true }> => ipcRenderer.invoke('feishuBot:set-lifecycle-announcement', { enabled }),
+ registrationBegin: (
+ service: 'feishu' | 'lark',
+ ): Promise<{
ok: boolean;
deviceCode?: string;
userCode?: string;
@@ -1478,9 +1483,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
expiresIn?: number;
interval?: number;
error?: string;
- }> => ipcRenderer.invoke('feishuBot:registration-begin'),
- registrationCancel: (): Promise<{ ok: true }> =>
- ipcRenderer.invoke('feishuBot:registration-cancel'),
+ }> => ipcRenderer.invoke('feishuBot:registration-begin', { service }),
+ registrationCancel: (): Promise<{ ok: true }> => ipcRenderer.invoke('feishuBot:registration-cancel'),
onStatusChange: fanOutFeishuBotStatusChange,
onConflict: fanOutFeishuBotConflict,
onRegistrationStatus: fanOutFeishuBotRegistrationStatus,
@@ -5195,9 +5199,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
updateDriver: (opts?: { joinOnly?: boolean }): Promise<ComputerDriverInstallResult> =>
ipcRenderer.invoke('maker:computer:update-driver', opts),
onUpdateProgress: fanOutComputerDriverUpdateProgress,
+
},
},
// ── 剪贴板历史快捷面板 ────────────────────────────────────────────
-
});
diff --git a/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx b/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx
index b08d2d8d5a..2e54f67d09 100644
--- a/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx
+++ b/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx
@@ -8,7 +8,7 @@
* 注入这个组件。
*
* 视觉对标 UpdateNoticeDialog(Radix AlertDialog)。两个 action:
- * - "创建我的 App":跳到飞书开放平台新建独立 App
+ * - "创建我的 App":跳到当前 IM 服务的开放平台新建独立 App
* - "忽略":仅关闭,bot 状态保持 conflict
*/
@@ -21,6 +21,7 @@ import { cn } from '@/lib/utils';
interface FeishuConflictDialogProps {
open: boolean;
appId: string | null;
+ service: 'feishu' | 'lark';
onDismiss: () => void;
onCreateOwnApp: () => void;
}
@@ -28,10 +29,12 @@ interface FeishuConflictDialogProps {
export function FeishuConflictDialog({
open,
appId,
+ service,
onDismiss,
onCreateOwnApp,
}: FeishuConflictDialogProps) {
const { t } = useTranslation();
+ const serviceName = t(`settings.feishuBot.services.${service}`);
return (
<AlertDialog.Root open={open} onOpenChange={(next) => !next && onDismiss()}>
<AlertDialog.Portal>
@@ -66,7 +69,7 @@ export function FeishuConflictDialog({
<AlertTriangle size={20} style={{ color: 'var(--status-bar-accent)' }} />
</div>
<AlertDialog.Title className="text-16 font-medium text-[var(--settings-section-title)]">
- {t('imBot.conflictDialog.title')}
+ {t('imBot.conflictDialog.title', { service: serviceName })}
</AlertDialog.Title>
</div>
@@ -90,7 +93,7 @@ export function FeishuConflictDialog({
<br />
{t('imBot.conflictDialog.suggestion1')}
<br />
- {t('imBot.conflictDialog.suggestion2')}
+ {t('imBot.conflictDialog.suggestion2', { service: serviceName })}
</AlertDialog.Description>
{/* Actions */}
diff --git a/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx b/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx
index 0e01b36a6c..959197307b 100644
--- a/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx
+++ b/apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx
@@ -12,16 +12,25 @@ import { useCallback, useEffect, useState } from 'react';
import { FeishuConflictDialog } from './FeishuConflictDialog';
-const FEISHU_OPEN_PLATFORM_URL = 'https://open.feishu.cn/app?lang=zh-CN';
+const OPEN_PLATFORM_URLS = {
+ feishu: 'https://open.feishu.cn/app?lang=zh-CN',
+ lark: 'https://open.larksuite.com/app',
+} as const;
export function FeishuConflictDialogHost() {
const [open, setOpen] = useState(false);
const [appId, setAppId] = useState<string | null>(null);
+ const [service, setService] = useState<'feishu' | 'lark'>('feishu');
useEffect(() => {
const unsub = window.electronAPI.feishuBot.onConflict((payload) => {
setAppId(payload.appId);
- setOpen(true);
+ setService('feishu');
+ void window.electronAPI.feishuBot
+ .getState()
+ .then((state) => setService(state.service ?? 'feishu'))
+ .catch(() => undefined)
+ .finally(() => setOpen(true));
});
return unsub;
}, []);
@@ -32,13 +41,14 @@ export function FeishuConflictDialogHost() {
const handleCreateOwnApp = useCallback(() => {
setOpen(false);
- window.electronAPI.openExternal?.(FEISHU_OPEN_PLATFORM_URL);
- }, []);
+ window.electronAPI.openExternal?.(OPEN_PLATFORM_URLS[service]);
+ }, [service]);
return (
<FeishuConflictDialog
open={open}
appId={appId}
+ service={service}
onDismiss={handleDismiss}
onCreateOwnApp={handleCreateOwnApp}
/>
diff --git a/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx b/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx
index e034b76839..06da62e77d 100644
--- a/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx
@@ -1,9 +1,9 @@
-import { useCallback, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Eye, EyeOff, Trash2, Check, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
-import { useFeishuBot, type FeishuBotStatus } from '@/hooks/useFeishuBot';
+import { useFeishuBot, type FeishuBotService, type FeishuBotStatus } from '@/hooks/useFeishuBot';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
@@ -12,7 +12,12 @@ import { ImChannelSettingsCard, useImChannelSettingsSummary } from './ImChannelS
import { ImDefaultSettingsSection } from './ImDefaultSettingsSection';
import { FeishuBotNotificationSection } from './FeishuBotNotificationSection';
-const FEISHU_LAUNCHER_URL = 'https://open.feishu.cn/page/launcher?from=backend_oneclick';
+const APP_LAUNCHER_URL: Record<FeishuBotService, string> = {
+ feishu: 'https://open.feishu.cn/page/launcher?from=backend_oneclick',
+ lark: 'https://open.larksuite.com/page/launcher?from=backend_oneclick',
+};
+const FEISHU_SERVICES = ['feishu', 'lark'] as const;
+const FEISHU_ONLY = ['feishu'] as const;
const statusKey: Record<FeishuBotStatus, string> = {
idle: 'settings.feishuBot.status.needsConfig',
@@ -51,11 +56,15 @@ function maskTail(value: string): string {
export function FeishuBotSection({
expanded,
onToggle,
+ showLark,
}: {
expanded: boolean;
onToggle: () => void;
+ showLark: boolean;
}) {
const {
+ service,
+ setService,
appId,
setAppId,
appSecret,
@@ -78,8 +87,20 @@ export function FeishuBotSection({
const { confirm } = useConfirmDialog();
const { t } = useTranslation();
- const canSave = appId.trim().length > 0 && appSecret.trim().length > 0 && !isSaving;
const showSavedCredentialsCard = shouldShowSavedCredentialsCard(hasSavedCreds);
+ // 已保存的 Lark 凭证仍允许查看和清除,身份限制只影响新的配置入口。
+ const configurableService = showLark || hasSavedCreds ? service : 'feishu';
+ const canSave =
+ service === configurableService &&
+ appId.trim().length > 0 &&
+ appSecret.trim().length > 0 &&
+ !isSaving;
+
+ useEffect(() => {
+ if (!showLark && !hasSavedCreds && service === 'lark') {
+ setService('feishu');
+ }
+ }, [hasSavedCreds, service, setService, showLark]);
const handleClearClick = useCallback(async () => {
const confirmed = await confirm({
@@ -93,8 +114,8 @@ export function FeishuBotSection({
}, [confirm, clear, t]);
const openLauncher = useCallback(() => {
- window.electronAPI.openExternal?.(FEISHU_LAUNCHER_URL);
- }, []);
+ window.electronAPI.openExternal?.(APP_LAUNCHER_URL[configurableService]);
+ }, [configurableService]);
return (
<ImChannelSettingsCard
@@ -136,6 +157,7 @@ export function FeishuBotSection({
{showSavedCredentialsCard ? (
<SavedCredentialsCard
appId={appId}
+ service={service}
ownerOpenId={ownerOpenId}
status={status}
isClearing={isClearing}
@@ -145,6 +167,9 @@ export function FeishuBotSection({
/>
) : (
<ManualConfig
+ service={configurableService}
+ setService={setService}
+ showLark={showLark}
appId={appId}
setAppId={setAppId}
appSecret={appSecret}
@@ -171,6 +196,7 @@ export function FeishuBotSection({
function SavedCredentialsCard(props: {
appId: string;
+ service: FeishuBotService;
ownerOpenId: string | null;
status: FeishuBotStatus;
isClearing: boolean;
@@ -179,6 +205,7 @@ function SavedCredentialsCard(props: {
onClear: () => void;
}) {
const { t } = useTranslation();
+ const serviceName = t(`settings.feishuBot.services.${props.service}`);
return (
<div
className={cn(
@@ -206,16 +233,23 @@ function SavedCredentialsCard(props: {
props.status === 'connected'
? 'settings.feishuBot.connected.heading'
: 'settings.feishuBot.saved.heading',
+ { service: serviceName },
)}
</div>
- <Tip text={t('settings.feishuBot.connected.reconnect')} side="top" delay={200}>
+ <Tip
+ text={t('settings.feishuBot.connected.reconnect', { service: serviceName })}
+ side="top"
+ delay={200}
+ >
{/* Keep the trigger hoverable while the inner button is disabled. */}
<span className="inline-flex shrink-0">
<button
type="button"
onClick={() => void props.onReconnect()}
disabled={props.isReconnecting || props.isClearing}
- aria-label={t('settings.feishuBot.connected.reconnect')}
+ aria-label={t('settings.feishuBot.connected.reconnect', {
+ service: serviceName,
+ })}
className={cn(
'inline-flex h-7 w-7 select-none items-center justify-center rounded-full',
'text-[var(--settings-section-desc)] transition-colors',
@@ -240,6 +274,10 @@ function SavedCredentialsCard(props: {
</div>
</div>
<div className="grid gap-2 text-12 text-[var(--settings-section-desc)]">
+ <div className="flex justify-between gap-4">
+ <span>{t('settings.feishuBot.connected.serviceLabel')}</span>
+ <span className="font-medium text-[var(--settings-section-title)]">{serviceName}</span>
+ </div>
<div className="flex justify-between gap-4">
<span>{t('settings.feishuBot.connected.appIdLabel')}</span>
<span className="font-medium text-[var(--settings-section-title)]">
@@ -276,6 +314,9 @@ function SavedCredentialsCard(props: {
}
function ManualConfig(props: {
+ service: FeishuBotService;
+ setService: (service: FeishuBotService) => void;
+ showLark: boolean;
appId: string;
setAppId: (v: string) => void;
appSecret: string;
@@ -292,6 +333,45 @@ function ManualConfig(props: {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-3">
+ <fieldset className="flex flex-col gap-2">
+ <legend
+ className="text-12 font-medium text-[var(--settings-section-desc)]"
+ style={{ letterSpacing: '0.12px' }}
+ >
+ {t('settings.feishuBot.serviceLabel')}
+ </legend>
+ <div
+ className={cn(
+ 'grid gap-1 rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] p-1',
+ props.showLark ? 'grid-cols-2' : 'grid-cols-1',
+ )}
+ role="radiogroup"
+ aria-label={t('settings.feishuBot.serviceAria')}
+ >
+ {(props.showLark ? FEISHU_SERVICES : FEISHU_ONLY).map((service) => {
+ const selected = props.service === service;
+ return (
+ <button
+ key={service}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={() => props.setService(service)}
+ className={cn(
+ 'h-[34px] rounded-full text-12 font-medium transition-colors',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ selected
+ ? 'bg-[var(--surface-chip)] text-[var(--settings-section-title)]'
+ : 'text-[var(--settings-section-desc)] hover:text-[var(--settings-section-title)]',
+ )}
+ >
+ {t(`settings.feishuBot.services.${service}`)}
+ </button>
+ );
+ })}
+ </div>
+ </fieldset>
+
<label
className="text-12 font-medium text-[var(--settings-section-desc)]"
style={{ letterSpacing: '0.12px' }}
@@ -370,7 +450,9 @@ function ManualConfig(props: {
onClick={props.onOpenLauncher}
className="cursor-pointer bg-transparent p-0 font-medium text-[var(--settings-source-link)] underline decoration-[var(--settings-source-link)] decoration-1 underline-offset-2"
>
- {t('settings.feishuBot.createLink')}
+ {t('settings.feishuBot.createLink', {
+ service: t(`settings.feishuBot.services.${props.service}`),
+ })}
</button>
<span>{t('settings.feishuBot.createLinkSuffix')}</span>
</p>
diff --git a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx b/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
index e37619b357..25f67b447b 100644
--- a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
@@ -34,6 +34,7 @@ import { WechatBotSection } from './WechatBotSection';
import {
showCindyGroup,
showDiscordBot,
+ showLarkBot,
showTelegramBot,
type ImBotIdentity,
} from './imBotVisibility';
@@ -61,12 +62,14 @@ export function isImBotSettingsGroup(value: string | null): value is ImBotSettin
return value === 'cindy' || value === 'personal';
}
-/** 个人栏内容 —— 用户自配凭证的机器人(国区个人账号无 Discord/Telegram)。 */
+/** 个人栏内容 —— 用户自配凭证的机器人(国区个人账号无 Discord/Lark/Telegram)。 */
function PersonalGroupContent({
showDiscord,
+ showLark,
showTelegram,
}: {
showDiscord: boolean;
+ showLark: boolean;
showTelegram: boolean;
}) {
const [expandedChannel, setExpandedChannel] = useState<
@@ -80,7 +83,11 @@ function PersonalGroupContent({
return (
<div className="flex flex-col gap-3">
<WechatBotSection expanded={expandedChannel === 'wechat'} onToggle={() => toggle('wechat')} />
- <FeishuBotSection expanded={expandedChannel === 'feishu'} onToggle={() => toggle('feishu')} />
+ <FeishuBotSection
+ expanded={expandedChannel === 'feishu'}
+ onToggle={() => toggle('feishu')}
+ showLark={showLark}
+ />
<DingTalkBotSection
expanded={expandedChannel === 'dingtalk'}
onToggle={() => toggle('dingtalk')}
@@ -117,6 +124,7 @@ export function ImBotSection({
};
const cindyGroupAvailable = showCindyGroup(identity);
const discordVisible = showDiscordBot(identity);
+ const larkVisible = showLarkBot(identity);
const telegramVisible = showTelegramBot(identity);
const availableGroups = cindyGroupAvailable
? IM_BOT_SETTINGS_GROUPS
@@ -189,7 +197,11 @@ export function ImBotSection({
{effectiveGroup === 'cindy' ? (
<HookConnectionsSection />
) : (
- <PersonalGroupContent showDiscord={discordVisible} showTelegram={telegramVisible} />
+ <PersonalGroupContent
+ showDiscord={discordVisible}
+ showLark={larkVisible}
+ showTelegram={telegramVisible}
+ />
)}
</div>
</div>
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/imBotVisibility.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/imBotVisibility.test.ts
index cdc416f4b2..390961f8a5 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/imBotVisibility.test.ts
+++ b/apps/desktop/src/renderer/components/settings/__tests__/imBotVisibility.test.ts
@@ -1,13 +1,14 @@
// imBotVisibility —— 「IM 机器人」分栏/渠道可见性规则:
-// - 国区构建(cn/dev)+ 个人账号 cloud 登录:无 Cindy 分栏、无 Discord
+// - 国区构建(cn/dev)+ 个人账号 cloud 登录:无 Cindy 分栏、无 Discord/Lark
// - 企业账号 / global 构建:全量
-// - 本地模式:无 Cindy 分栏(既有规则),Discord 保留
+// - 国区本地模式 / 未登录:Lark 隐藏;global 仍显示
import { describe, expect, it } from 'vitest';
import {
isCnPersonalIdentity,
showCindyGroup,
showDiscordBot,
+ showLarkBot,
type ImBotIdentity,
} from '../imBotVisibility';
@@ -16,17 +17,19 @@ function identity(overrides: Partial<ImBotIdentity>): ImBotIdentity {
}
describe('imBotVisibility', () => {
- it('hides both the Cindy group and Discord for cn-build personal cloud accounts', () => {
+ it('hides the Cindy group, Discord, and Lark for cn-build personal cloud accounts', () => {
const cnPersonal = identity({});
expect(isCnPersonalIdentity(cnPersonal)).toBe(true);
expect(showCindyGroup(cnPersonal)).toBe(false);
expect(showDiscordBot(cnPersonal)).toBe(false);
+ expect(showLarkBot(cnPersonal)).toBe(false);
});
it('treats the dev region as cn for the personal-account rule', () => {
const devPersonal = identity({ region: 'dev' });
expect(showCindyGroup(devPersonal)).toBe(false);
expect(showDiscordBot(devPersonal)).toBe(false);
+ expect(showLarkBot(devPersonal)).toBe(false);
});
it('keeps everything for cn-build org accounts', () => {
@@ -34,22 +37,39 @@ describe('imBotVisibility', () => {
expect(isCnPersonalIdentity(cnOrg)).toBe(false);
expect(showCindyGroup(cnOrg)).toBe(true);
expect(showDiscordBot(cnOrg)).toBe(true);
+ expect(showLarkBot(cnOrg)).toBe(true);
});
it('keeps everything for global-build personal accounts', () => {
const globalPersonal = identity({ region: 'global' });
expect(showCindyGroup(globalPersonal)).toBe(true);
expect(showDiscordBot(globalPersonal)).toBe(true);
+ expect(showLarkBot(globalPersonal)).toBe(true);
});
- it('keeps the existing local-mode rule: no Cindy group, Discord stays', () => {
+ it('hides Lark for cn local mode while keeping the existing Discord rule', () => {
const cnLocal = identity({ mode: 'local', membershipKind: null });
expect(isCnPersonalIdentity(cnLocal)).toBe(false);
expect(showCindyGroup(cnLocal)).toBe(false);
expect(showDiscordBot(cnLocal)).toBe(true);
+ expect(showLarkBot(cnLocal)).toBe(false);
+
+ const devLocal = identity({ region: 'dev', mode: 'local', membershipKind: null });
+ expect(showLarkBot(devLocal)).toBe(false);
const globalLocal = identity({ region: 'global', mode: 'local', membershipKind: null });
expect(showCindyGroup(globalLocal)).toBe(false);
expect(showDiscordBot(globalLocal)).toBe(true);
+ expect(showLarkBot(globalLocal)).toBe(true);
+ });
+
+ it('hides Lark when signed out in cn/dev and keeps it visible in global', () => {
+ expect(showLarkBot(identity({ mode: 'signed-out', membershipKind: null }))).toBe(false);
+ expect(showLarkBot(identity({ region: 'dev', mode: 'signed-out', membershipKind: null }))).toBe(
+ false,
+ );
+ expect(
+ showLarkBot(identity({ region: 'global', mode: 'signed-out', membershipKind: null })),
+ ).toBe(true);
});
});
diff --git a/apps/desktop/src/renderer/components/settings/imBotVisibility.ts b/apps/desktop/src/renderer/components/settings/imBotVisibility.ts
index 30ebaeb4b4..dc172a3eb2 100644
--- a/apps/desktop/src/renderer/components/settings/imBotVisibility.ts
+++ b/apps/desktop/src/renderer/components/settings/imBotVisibility.ts
@@ -40,6 +40,13 @@ export function showDiscordBot(identity: ImBotIdentity): boolean {
return !isCnPersonalIdentity(identity);
}
+/** Lark 在国区只对已登录的云端企业账号开放;global 不受登录模式限制。 */
+export function showLarkBot(identity: ImBotIdentity): boolean {
+ return (
+ identity.region === 'global' || (identity.mode === 'cloud' && identity.membershipKind === 'org')
+ );
+}
+
/** 个人分栏是否提供 Telegram 机器人配置 — 可见性规则与 Discord 同组。 */
export function showTelegramBot(identity: ImBotIdentity): boolean {
return !isCnPersonalIdentity(identity);
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts
index 74b7f427f0..75877532a6 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts
@@ -45,6 +45,7 @@ type FeishuState = {
hasSecret: boolean;
ownerOpenId: string | null;
lifecycleAnnouncement: boolean;
+ service?: 'feishu' | 'lark';
};
function installFeishuApi() {
@@ -124,6 +125,36 @@ describe('useFeishuBot', () => {
expect(second.result.current.ownerOpenId).toBe('ou_new_owner');
});
+ it('hydrates and saves the selected Lark service', async () => {
+ const { api } = installFeishuApi();
+ api.getState.mockResolvedValueOnce({
+ status: 'idle',
+ appId: null,
+ appSecret: null,
+ hasSecret: false,
+ ownerOpenId: null,
+ lifecycleAnnouncement: true,
+ service: 'lark',
+ });
+ api.save.mockResolvedValueOnce({ verdict: 'connected' });
+ const hook = renderHook(() => useFeishuBot());
+
+ await waitFor(() => expect(hook.result.current.service).toBe('lark'));
+ act(() => {
+ hook.result.current.setAppId('cli_1234567890');
+ hook.result.current.setAppSecret('sec_test');
+ });
+ await act(async () => {
+ await hook.result.current.save();
+ });
+
+ expect(api.save).toHaveBeenCalledWith({
+ appId: 'cli_1234567890',
+ appSecret: 'sec_test',
+ service: 'lark',
+ });
+ });
+
it('does not let an older getState response overwrite a newer owner push', async () => {
let resolveState!: (state: {
status: 'connected';
@@ -187,9 +218,7 @@ describe('useFeishuBot', () => {
const hook = renderHook(() => useFeishuBot());
- await waitFor(() =>
- expect(hook.result.current.ownerOpenId).toBe('ou_mount_race_owner'),
- );
+ await waitFor(() => expect(hook.result.current.ownerOpenId).toBe('ou_mount_race_owner'));
});
it('does not let an older reload overwrite a newer registration reload', async () => {
diff --git a/apps/desktop/src/renderer/hooks/useFeishuBot.ts b/apps/desktop/src/renderer/hooks/useFeishuBot.ts
index 5265406db2..67944340e4 100644
--- a/apps/desktop/src/renderer/hooks/useFeishuBot.ts
+++ b/apps/desktop/src/renderer/hooks/useFeishuBot.ts
@@ -24,14 +24,13 @@ import { setFeishuNotificationsEnabled } from '@/hooks/useFeishuNotificationSett
const log = createLogger('useFeishuBot');
export type FeishuBotStatus =
- | 'idle'
- | 'testing'
- | 'connected'
- | 'reconnecting'
- | 'conflict'
- | 'error';
+ 'idle' | 'testing' | 'connected' | 'reconnecting' | 'conflict' | 'error';
+
+export type FeishuBotService = 'feishu' | 'lark';
export interface UseFeishuBotReturn {
+ service: FeishuBotService;
+ setService: (service: FeishuBotService) => void;
/** 当前 input 框里的 appId(可能未保存) */
appId: string;
setAppId: (v: string) => void;
@@ -70,6 +69,7 @@ const APP_ID_PATTERN = /^cli_[A-Za-z0-9]{10,30}$/;
// Module-level cache so re-mounting (e.g. switching settings tabs) doesn't
// flash the default `idle` state for one frame before IPC getState() resolves.
interface FeishuBotCache {
+ service: FeishuBotService;
appId: string;
appSecret: string;
status: FeishuBotStatus;
@@ -82,13 +82,22 @@ let cachedState: FeishuBotCache | null = null;
export function useFeishuBot(): UseFeishuBotReturn {
const { t } = useTranslation();
+ const [service, setServiceState] = useState<FeishuBotService>(
+ () => cachedState?.service ?? 'feishu',
+ );
const [appId, setAppIdState] = useState(() => cachedState?.appId ?? '');
const [appSecret, setAppSecret] = useState(() => cachedState?.appSecret ?? '');
const [status, setStatus] = useState<FeishuBotStatus>(() => cachedState?.status ?? 'idle');
- const [errorMessage, setErrorMessage] = useState<string | null>(() => cachedState?.errorMessage ?? null);
+ const [errorMessage, setErrorMessage] = useState<string | null>(
+ () => cachedState?.errorMessage ?? null,
+ );
const [hasSavedCreds, setHasSavedCreds] = useState(() => cachedState?.hasSavedCreds ?? false);
- const [ownerOpenId, setOwnerOpenId] = useState<string | null>(() => cachedState?.ownerOpenId ?? null);
- const [lifecycleAnnouncement, setLifecycleAnnouncementState] = useState(() => cachedState?.lifecycleAnnouncement ?? true);
+ const [ownerOpenId, setOwnerOpenId] = useState<string | null>(
+ () => cachedState?.ownerOpenId ?? null,
+ );
+ const [lifecycleAnnouncement, setLifecycleAnnouncementState] = useState(
+ () => cachedState?.lifecycleAnnouncement ?? true,
+ );
const [validationError, setValidationError] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
@@ -116,6 +125,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
if (reloadRequestVersion !== reloadRequestVersionRef.current) return;
const nextAppId = state.appId ?? '';
const nextAppSecret = state.appSecret ?? '';
+ const nextService: FeishuBotService = state.service === 'lark' ? 'lark' : 'feishu';
const newerStatusPush =
statusPushVersionRef.current !== statusPushVersion ? latestStatusPushRef.current : null;
const nextStatus = newerStatusPush?.status ?? state.status;
@@ -124,6 +134,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
: (state.error ?? null);
const nextOwnerOpenId = newerStatusPush ? newerStatusPush.ownerOpenId : state.ownerOpenId;
setStatus(nextStatus);
+ setServiceState(nextService);
setHasSavedCreds(state.hasSecret);
setOwnerOpenId(nextOwnerOpenId);
setErrorMessage(nextErrorMessage);
@@ -135,6 +146,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
setAppSecret(state.appSecret);
}
cachedState = {
+ service: nextService,
appId: nextAppId || cachedState?.appId || '',
appSecret: nextAppSecret || cachedState?.appSecret || '',
status: nextStatus,
@@ -208,11 +220,14 @@ export function useFeishuBot(): UseFeishuBotReturn {
}, [reloadState]);
// ── setters with validation ──────────────────────────────────────────────
- const setAppId = useCallback((v: string) => {
- setAppIdState(v);
- setValidationError(null);
- if (saveSuccess) setSaveSuccess(false);
- }, [saveSuccess]);
+ const setAppId = useCallback(
+ (v: string) => {
+ setAppIdState(v);
+ setValidationError(null);
+ if (saveSuccess) setSaveSuccess(false);
+ },
+ [saveSuccess],
+ );
// ── actions ──────────────────────────────────────────────────────────────
const save = useCallback(async () => {
@@ -236,6 +251,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
const { verdict } = await window.electronAPI.feishuBot.save({
appId: trimmedAppId,
appSecret: trimmedSecret,
+ service,
});
// A non-connected verdict can still coexist with persisted credentials.
@@ -250,6 +266,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
setHasSavedCreds(true);
setSaveSuccess(true);
cachedState = {
+ service,
appId: trimmedAppId,
appSecret: trimmedSecret,
status: 'connected',
@@ -283,7 +300,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
} finally {
setIsSaving(false);
}
- }, [appId, appSecret, isSaving, reloadState, t]);
+ }, [appId, appSecret, isSaving, reloadState, service, t]);
const clear = useCallback(async () => {
if (isClearing) return;
@@ -297,6 +314,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
setStatus('idle');
setErrorMessage(null);
cachedState = {
+ service,
appId: '',
appSecret: '',
status: 'idle',
@@ -319,7 +337,7 @@ export function useFeishuBot(): UseFeishuBotReturn {
} finally {
setIsClearing(false);
}
- }, [isClearing, t]);
+ }, [isClearing, service, t]);
const reconnect = useCallback(async () => {
if (isReconnecting) return false;
@@ -362,7 +380,18 @@ export function useFeishuBot(): UseFeishuBotReturn {
});
}, []);
+ const setService = useCallback(
+ (nextService: FeishuBotService) => {
+ setServiceState(nextService);
+ setValidationError(null);
+ if (saveSuccess) setSaveSuccess(false);
+ },
+ [saveSuccess],
+ );
+
return {
+ service,
+ setService,
appId,
setAppId,
appSecret,
diff --git a/apps/desktop/src/renderer/hooks/useFeishuBotRegistration.ts b/apps/desktop/src/renderer/hooks/useFeishuBotRegistration.ts
index de071c26b2..9072a01ae3 100644
--- a/apps/desktop/src/renderer/hooks/useFeishuBotRegistration.ts
+++ b/apps/desktop/src/renderer/hooks/useFeishuBotRegistration.ts
@@ -26,13 +26,7 @@ function getQrColors(): { dark: string; light: string } {
}
export type FeishuBotRegistrationPhase =
- | 'idle'
- | 'starting'
- | 'qr'
- | 'success'
- | 'expired'
- | 'cancelled'
- | 'error';
+ 'idle' | 'starting' | 'qr' | 'success' | 'expired' | 'cancelled' | 'error';
interface UseFeishuBotRegistrationReturn {
phase: FeishuBotRegistrationPhase;
@@ -46,7 +40,9 @@ interface UseFeishuBotRegistrationReturn {
cancelRegistration: () => Promise<void>;
}
-export function useFeishuBotRegistration(): UseFeishuBotRegistrationReturn {
+export function useFeishuBotRegistration(
+ service: 'feishu' | 'lark' = 'feishu',
+): UseFeishuBotRegistrationReturn {
const { t } = useTranslation();
const [phase, setPhase] = useState<FeishuBotRegistrationPhase>('idle');
const [verificationUrl, setVerificationUrl] = useState<string | null>(null);
@@ -113,7 +109,7 @@ export function useFeishuBotRegistration(): UseFeishuBotRegistrationReturn {
setQrDataUrl(null);
try {
- const result = await window.electronAPI.feishuBot.registrationBegin();
+ const result = await window.electronAPI.feishuBot.registrationBegin(service);
if (!result.ok || !result.verificationUrl || !result.expiresIn) {
setPhase('error');
setErrorMessage(result.error ?? t('logic.errors.registrationFailed'));
@@ -138,7 +134,7 @@ export function useFeishuBotRegistration(): UseFeishuBotRegistrationReturn {
setPhase('error');
setErrorMessage(msg);
}
- }, [phase, t]);
+ }, [phase, service, t]);
const cancelRegistration = useCallback(async () => {
await window.electronAPI.feishuBot.registrationCancel();
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 077936dab1..dd4eb739b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -464,9 +464,9 @@
"sessionDoneLabel": "Show desktop notification when a session finishes",
"sessionDoneHint": "Only shown while the window is unfocused, to avoid foreground interruption.",
"sessionDoneAria": "Toggle session-done desktop notifications",
- "feishuLabel": "Send a FeiShu DM when a session finishes or needs reply",
- "feishuHint": "Sends a private message via the linked FeiShu bot; only when the window is unfocused.",
- "feishuDisabledHint": "First set up the bot in \"FeiShu Bot\" and DM it once to complete binding.",
+ "feishuLabel": "Send a Feishu / Lark DM when a session finishes or needs a reply",
+ "feishuHint": "Sends a private message via the linked Feishu or Lark bot; only when the window is unfocused.",
+ "feishuDisabledHint": "First set up the bot in \"Feishu / Lark Bot\" and DM it once to complete binding.",
"feishuAria": "Toggle session-done FeiShu notifications"
},
"windowBehavior": {
@@ -1581,9 +1581,15 @@
"saveFailed": "Failed to save Git safety setting"
},
"feishuBot": {
- "title": "Feishu Bot",
- "description": "Connect to {{appName}} via Feishu Bot to work anywhere, anytime.",
- "statusAria": "FeiShu Bot status: {{status}}",
+ "title": "Feishu / Lark Bot",
+ "description": "Connect to {{appName}} via a Feishu or Lark bot to work anywhere, anytime.",
+ "statusAria": "Feishu / Lark Bot status: {{status}}",
+ "serviceLabel": "Service",
+ "serviceAria": "Select an IM service",
+ "services": {
+ "feishu": "Feishu",
+ "lark": "Lark"
+ },
"status": {
"needsConfig": "Needs configuration",
"connecting": "Connecting…",
@@ -1593,16 +1599,17 @@
"error": "Connection failed"
},
"connected": {
- "heading": "Feishu Bot connected",
+ "heading": "{{service}} Bot connected",
"note": "Bound to the current scanning user; private messages from other people are silently ignored.",
+ "serviceLabel": "Service",
"appIdLabel": "App ID",
"ownerLabel": "Owner",
"ownerWaiting": "Waiting for first private-message bind",
- "reconnect": "Reconnect Feishu Bot",
+ "reconnect": "Reconnect {{service}} Bot",
"clear": "Unbind"
},
"saved": {
- "heading": "Feishu Bot is bound",
+ "heading": "{{service}} Bot is bound",
"connectingNote": "Bot credentials are saved. Establishing the connection now.",
"reconnectingNote": "Bot credentials are saved. Restoring the connection now.",
"conflictNote": "Bot credentials are saved, but this App ID is currently in use on another device.",
@@ -1615,11 +1622,11 @@
"appSecretPlaceholder": "sec_xxxxxxxxxxxxxxxxxx",
"showSecret": "Show secret",
"hideSecret": "Hide secret",
- "createLink": "Click here to create ↗",
+ "createLink": "Create on {{service}} Open Platform ↗",
"createLinkSuffix": ", then fill in the credentials",
- "clearAria": "Unbind Feishu Bot",
+ "clearAria": "Unbind IM bot",
"clearConfirm": {
- "title": "Unbind Feishu Bot?",
+ "title": "Unbind IM bot?",
"description": "Unbinding will close the WebSocket connection and remove the locally stored App ID / App Secret / owner openId. To re-enable, you'll need to recreate or re-enter the credentials.",
"confirm": "Unbind",
"cancel": "Cancel"
@@ -4368,12 +4375,12 @@
},
"imBot": {
"conflictDialog": {
- "title": "This Feishu Bot App is already in use",
+ "title": "This {{service}} Bot App is already in use",
"bodyPrefix": "The current App",
"bodyMain": "is already running a long-lived connection on another device — likely a colleague using the same App ID. An App can only bind to one device at a time, so this client has automatically disconnected to avoid contention.",
"suggestionsHeading": "Two suggested approaches:",
"suggestion1": "1. Coordinate with the other user to use it at different times. Have them clear the credential on their device, then reconnect here.",
- "suggestion2": "2. Create your own dedicated App on the Feishu Open Platform so you and your colleague each have your own.",
+ "suggestion2": "2. Create your own dedicated App on the {{service}} Open Platform so you and your colleague each have your own.",
"dismiss": "Dismiss",
"createOwnApp": "Create my App ↗"
}
@@ -7625,16 +7632,16 @@
"toasts": {
"googleConnected": "Google connected",
"codexConnected": "ChatGPT account connected",
- "feishuBotConnected": "FeiShu bot connected",
- "feishuBotReconnected": "Feishu bot reconnected",
- "feishuBotReconnectFailed": "Reconnect failed. Check the Feishu configuration and try again",
+ "feishuBotConnected": "IM bot connected",
+ "feishuBotReconnected": "IM bot reconnected",
+ "feishuBotReconnectFailed": "Reconnect failed. Check the IM bot configuration and try again",
"feishuBotConflict": "This App is already in use — a colleague may be using the same App ID",
"feishuBotConnectFailed": "Connection failed, check App ID / Secret",
"feishuBotSaveFailed": "Save failed: {{message}}",
- "feishuBotCleared": "FeiShu bot credentials cleared",
+ "feishuBotCleared": "IM bot credentials cleared",
"feishuBotClearFailed": "Clear failed: {{message}}",
- "feishuBotCreatedConnected": "FeiShu bot created and connected",
- "feishuBotCreatedCheck": "FeiShu bot created, please check connection status",
+ "feishuBotCreatedConnected": "IM bot created and connected",
+ "feishuBotCreatedCheck": "IM bot created. Check the connection status",
"discordBotConnected": "Discord bot configuration saved",
"discordBotConnectFailed": "Discord bot connection failed; check the token and permissions",
"discordBotSaveFailed": "Save failed: {{message}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 9f259a7008..98956ff75e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -464,9 +464,9 @@
"sessionDoneLabel": "セッション完了時にデスクトップ通知を表示",
"sessionDoneHint": "ウィンドウが非アクティブの場合のみ表示し、フォアグラウンドでの中断を防ぎます。",
"sessionDoneAria": "セッション完了時のデスクトップ通知を切り替え",
- "feishuLabel": "セッション完了または返信が必要な時に Feishu メッセージを送信",
- "feishuHint": "連携済みの Feishu ボットからプライベートメッセージを送信します。ウィンドウが非アクティブの場合のみ送信。",
- "feishuDisabledHint": "先に「Feishu ボット」で設定し、ボットに 1 度メッセージを送ってバインドを完了してください。",
+ "feishuLabel": "セッション完了または返信が必要な時に Feishu / Lark メッセージを送信",
+ "feishuHint": "連携済みの Feishu または Lark ボットからプライベートメッセージを送信します。ウィンドウが非アクティブの場合のみ送信。",
+ "feishuDisabledHint": "先に「Feishu / Lark ボット」で設定し、ボットに 1 度メッセージを送ってバインドを完了してください。",
"feishuAria": "セッション完了時の Feishu 通知を切り替え"
},
"windowBehavior": {
@@ -1580,9 +1580,15 @@
"saveFailed": "Git セーフティ設定の保存に失敗しました"
},
"feishuBot": {
- "title": "Feishu ボット",
- "description": "Feishu ボット経由で {{appName}} に接続し、いつでもどこでも作業できます。",
- "statusAria": "Feishu ボットの状態: {{status}}",
+ "title": "Feishu / Lark ボット",
+ "description": "Feishu または Lark ボット経由で {{appName}} に接続し、いつでもどこでも作業できます。",
+ "statusAria": "Feishu / Lark ボットの状態: {{status}}",
+ "serviceLabel": "サービス",
+ "serviceAria": "IM サービスを選択",
+ "services": {
+ "feishu": "Feishu",
+ "lark": "Lark"
+ },
"status": {
"needsConfig": "設定が必要",
"connecting": "接続中…",
@@ -1592,16 +1598,17 @@
"error": "接続失敗"
},
"connected": {
- "heading": "Feishu ボットは接続済み",
+ "heading": "{{service}} ボットは接続済み",
"note": "現在の QR コードスキャンユーザーにバインドされています。他の人からのプライベートメッセージは自動的に無視されます。",
+ "serviceLabel": "サービス",
"appIdLabel": "App ID",
"ownerLabel": "Owner",
"ownerWaiting": "初回プライベートメッセージのバインドを待機中",
- "reconnect": "Feishu ボットを再接続",
+ "reconnect": "{{service}} ボットを再接続",
"clear": "連携解除"
},
"saved": {
- "heading": "Feishu ボットは連携済み",
+ "heading": "{{service}} ボットは連携済み",
"connectingNote": "ボットの認証情報は保存されています。接続しています。",
"reconnectingNote": "ボットの認証情報は保存されています。接続を復旧しています。",
"conflictNote": "ボットの認証情報は保存されていますが、この App ID は別のデバイスで使用中です。",
@@ -1614,11 +1621,11 @@
"appSecretPlaceholder": "sec_xxxxxxxxxxxxxxxxxx",
"showSecret": "シークレットを表示",
"hideSecret": "シークレットを非表示",
- "createLink": "クリックして作成 ↗",
+ "createLink": "{{service}} オープンプラットフォームで作成 ↗",
"createLinkSuffix": "、作成後にここに入力します",
- "clearAria": "Feishu ボットの連携を解除",
+ "clearAria": "IM ボットの連携を解除",
"clearConfirm": {
- "title": "Feishu ボットの連携を解除しますか?",
+ "title": "IM ボットの連携を解除しますか?",
"description": "連携を解除すると WebSocket 接続が切れ、ローカルに保存された App ID / App Secret / オーナー openId が削除されます。再度使うには、再作成または再入力が必要です。",
"confirm": "連携解除",
"cancel": "キャンセル"
@@ -4367,12 +4374,12 @@
},
"imBot": {
"conflictDialog": {
- "title": "この Feishu Bot App は既に使用中です",
+ "title": "この {{service}} Bot App は既に使用中です",
"bodyPrefix": "現在の App",
"bodyMain": "は別の端末で既にロングコネクションを開始しています。同僚が同じ App ID を使用している可能性があります。一つの App は一台にしか接続できないため、競合を避けるために本機では自動的に切断しました。",
"suggestionsHeading": "対処方法は 2 つあります:",
"suggestion1": "1. 相手と相談して時間をずらして使用し、相手側で先に資格情報をクリアしてから本機で再接続する。",
- "suggestion2": "2. Feishu オープンプラットフォームで自分専用の App を別途作成し、同僚と分けて使用する。",
+ "suggestion2": "2. {{service}} オープンプラットフォームで自分専用の App を別途作成し、同僚と分けて使用する。",
"dismiss": "閉じる",
"createOwnApp": "自分の App を作成 ↗"
}
@@ -7614,16 +7621,16 @@
"toasts": {
"googleConnected": "Google に接続しました",
"codexConnected": "ChatGPT アカウントに接続しました",
- "feishuBotConnected": "Feishu ボットに接続しました",
- "feishuBotReconnected": "Feishu ボットを再接続しました",
- "feishuBotReconnectFailed": "再接続に失敗しました。Feishu の設定を確認して再試行してください",
+ "feishuBotConnected": "IM ボットに接続しました",
+ "feishuBotReconnected": "IM ボットを再接続しました",
+ "feishuBotReconnectFailed": "再接続に失敗しました。IM ボットの設定を確認して再試行してください",
"feishuBotConflict": "この App は既に使用されています。同僚が同じ App ID を使用している可能性があります",
"feishuBotConnectFailed": "接続に失敗しました。App ID / Secret を確認してください",
"feishuBotSaveFailed": "保存に失敗しました:{{message}}",
- "feishuBotCleared": "Feishu ボットの認証情報を削除しました",
+ "feishuBotCleared": "IM ボットの認証情報を削除しました",
"feishuBotClearFailed": "削除に失敗しました:{{message}}",
- "feishuBotCreatedConnected": "Feishu ボットを作成し接続しました",
- "feishuBotCreatedCheck": "Feishu ボットを作成しました。接続状態をご確認ください",
+ "feishuBotCreatedConnected": "IM ボットを作成し接続しました",
+ "feishuBotCreatedCheck": "IM ボットを作成しました。接続状態をご確認ください",
"discordBotConnected": "Discord ボット設定を保存しました",
"discordBotConnectFailed": "Discord ボットの接続に失敗しました。Token と権限を確認してください",
"discordBotSaveFailed": "保存に失敗しました:{{message}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a65386f036..15358043dc 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -464,9 +464,9 @@
"sessionDoneLabel": "세션 완료 시 데스크톱 알림 표시",
"sessionDoneHint": "창이 비활성 상태일 때만 표시되어 포그라운드 방해를 방지합니다.",
"sessionDoneAria": "세션 완료 데스크톱 알림 전환",
- "feishuLabel": "세션 완료 또는 응답 필요 시 Feishu 메시지 전송",
- "feishuHint": "연동된 Feishu 봇을 통해 개인 메시지를 보냅니다. 창이 비활성 상태일 때만 전송됩니다.",
- "feishuDisabledHint": "먼저 \"Feishu 봇\"에서 봇을 설정하고 한 번 메시지를 보내 바인딩을 완료하세요.",
+ "feishuLabel": "세션 완료 또는 응답 필요 시 Feishu / Lark 메시지 전송",
+ "feishuHint": "연동된 Feishu 또는 Lark 봇을 통해 개인 메시지를 보냅니다. 창이 비활성 상태일 때만 전송됩니다.",
+ "feishuDisabledHint": "먼저 \"Feishu / Lark 봇\"에서 봇을 설정하고 한 번 메시지를 보내 바인딩을 완료하세요.",
"feishuAria": "세션 완료 Feishu 알림 전환"
},
"windowBehavior": {
@@ -1580,9 +1580,15 @@
"saveFailed": "Git 안전 설정 저장에 실패했습니다"
},
"feishuBot": {
- "title": "Feishu 봇",
- "description": "Feishu 봇을 통해 언제 어디서나 {{appName}}에 연결하여 작업하세요.",
- "statusAria": "Feishu 봇 상태: {{status}}",
+ "title": "Feishu / Lark 봇",
+ "description": "Feishu 또는 Lark 봇을 통해 언제 어디서나 {{appName}}에 연결하여 작업하세요.",
+ "statusAria": "Feishu / Lark 봇 상태: {{status}}",
+ "serviceLabel": "서비스",
+ "serviceAria": "IM 서비스 선택",
+ "services": {
+ "feishu": "Feishu",
+ "lark": "Lark"
+ },
"status": {
"needsConfig": "구성 필요",
"connecting": "연결 중…",
@@ -1592,16 +1598,17 @@
"error": "연결 실패"
},
"connected": {
- "heading": "Feishu 봇이 연결됨",
+ "heading": "{{service}} 봇이 연결됨",
"note": "현재 QR 스캔 사용자에 바인딩되어 있으며, 다른 사람의 개인 메시지는 자동으로 무시됩니다.",
+ "serviceLabel": "서비스",
"appIdLabel": "App ID",
"ownerLabel": "Owner",
"ownerWaiting": "첫 개인 메시지 바인딩 대기 중",
- "reconnect": "Feishu 봇 다시 연결",
+ "reconnect": "{{service}} 봇 다시 연결",
"clear": "연동 해제"
},
"saved": {
- "heading": "Feishu 봇이 연동됨",
+ "heading": "{{service}} 봇이 연동됨",
"connectingNote": "봇 자격 증명이 저장되어 있습니다. 연결하는 중입니다.",
"reconnectingNote": "봇 자격 증명이 저장되어 있습니다. 연결을 복구하는 중입니다.",
"conflictNote": "봇 자격 증명이 저장되어 있지만 이 App ID는 다른 기기에서 사용 중입니다.",
@@ -1614,11 +1621,11 @@
"appSecretPlaceholder": "sec_xxxxxxxxxxxxxxxxxx",
"showSecret": "시크릿 표시",
"hideSecret": "시크릿 숨기기",
- "createLink": "여기를 클릭해 생성 ↗",
+ "createLink": "{{service}} 오픈 플랫폼에서 생성 ↗",
"createLinkSuffix": ", 생성 후 자격 증명을 입력하세요",
- "clearAria": "Feishu 봇 연동 해제",
+ "clearAria": "IM 봇 연동 해제",
"clearConfirm": {
- "title": "Feishu 봇 연동을 해제하시겠습니까?",
+ "title": "IM 봇 연동을 해제하시겠습니까?",
"description": "연동을 해제하면 WebSocket 연결이 끊기고, 로컬에 저장된 App ID / App Secret / 소유자 openId가 삭제됩니다. 다시 사용하려면 재생성하거나 자격 증명을 다시 입력해야 합니다.",
"confirm": "연동 해제",
"cancel": "취소"
@@ -4367,12 +4374,12 @@
},
"imBot": {
"conflictDialog": {
- "title": "이 Feishu Bot App은 이미 사용 중입니다",
+ "title": "이 {{service}} Bot App은 이미 사용 중입니다",
"bodyPrefix": "현재 App",
"bodyMain": "은 다른 기기에서 이미 장시간 연결을 시작했습니다. 동료가 동일한 App ID를 사용 중일 수 있습니다. 하나의 App은 한 기기에만 바인딩될 수 있으므로 충돌을 피하기 위해 본 기기에서 자동으로 연결이 해제되었습니다.",
"suggestionsHeading": "두 가지 처리 방법:",
"suggestion1": "1. 상대방과 협의해 시간대를 분리해 사용하고, 상대방이 자신의 기기에서 인증 정보를 먼저 지운 뒤 본 기기에서 재연결합니다.",
- "suggestion2": "2. Feishu 오픈 플랫폼에서 자신만의 별도 App을 만들어 동료와 각자 사용합니다.",
+ "suggestion2": "2. {{service}} 오픈 플랫폼에서 자신만의 별도 App을 만들어 동료와 각자 사용합니다.",
"dismiss": "무시",
"createOwnApp": "내 App 만들기 ↗"
}
@@ -7614,16 +7621,16 @@
"toasts": {
"googleConnected": "Google에 연결됨",
"codexConnected": "ChatGPT 계정 연결됨",
- "feishuBotConnected": "Feishu 봇에 연결됨",
- "feishuBotReconnected": "Feishu 봇이 다시 연결됨",
- "feishuBotReconnectFailed": "다시 연결하지 못했습니다. Feishu 구성을 확인한 후 다시 시도하세요",
+ "feishuBotConnected": "IM 봇에 연결됨",
+ "feishuBotReconnected": "IM 봇이 다시 연결됨",
+ "feishuBotReconnectFailed": "다시 연결하지 못했습니다. IM 봇 구성을 확인한 후 다시 시도하세요",
"feishuBotConflict": "이 App은 이미 사용 중입니다. 동료가 같은 App ID를 사용하고 있을 수 있습니다",
"feishuBotConnectFailed": "연결 실패. App ID / Secret을 확인하세요",
"feishuBotSaveFailed": "저장 실패: {{message}}",
- "feishuBotCleared": "Feishu 봇 자격 증명이 삭제됨",
+ "feishuBotCleared": "IM 봇 자격 증명이 삭제됨",
"feishuBotClearFailed": "삭제 실패: {{message}}",
- "feishuBotCreatedConnected": "Feishu 봇이 생성되어 연결됨",
- "feishuBotCreatedCheck": "Feishu 봇이 생성됨. 연결 상태를 확인하세요",
+ "feishuBotCreatedConnected": "IM 봇이 생성되어 연결됨",
+ "feishuBotCreatedCheck": "IM 봇이 생성됨. 연결 상태를 확인하세요",
"discordBotConnected": "Discord 봇 구성이 저장됨",
"discordBotConnectFailed": "Discord 봇 연결 실패. Token과 권한을 확인하세요",
"discordBotSaveFailed": "저장 실패: {{message}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index eea09612d1..6db415732b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -464,9 +464,9 @@
"sessionDoneLabel": "对话完成时弹出系统通知",
"sessionDoneHint": "仅在窗口失焦时弹出,避免前台打扰。",
"sessionDoneAria": "切换对话完成的系统通知",
- "feishuLabel": "对话完成或需要回复时发送飞书消息",
- "feishuHint": "通过已绑定的飞书机器人,向你私聊发送一条消息;仅在窗口失焦时发送。",
- "feishuDisabledHint": "需要先在「飞书机器人」中配置 bot 并向它发送一条消息以完成绑定。",
+ "feishuLabel": "对话完成或需要回复时发送飞书 / Lark 消息",
+ "feishuHint": "通过已绑定的飞书或 Lark 机器人,向你私聊发送一条消息;仅在窗口失焦时发送。",
+ "feishuDisabledHint": "需要先在「飞书 / Lark 机器人」中配置 bot 并向它发送一条消息以完成绑定。",
"feishuAria": "切换对话完成的飞书通知"
},
"windowBehavior": {
@@ -1580,9 +1580,15 @@
"saveFailed": "保存 Git 安全设置失败"
},
"feishuBot": {
- "title": "飞书机器人",
- "description": "通过飞书机器人随时随地连接 {{appName}} 进行工作。",
- "statusAria": "飞书机器人状态:{{status}}",
+ "title": "飞书 / Lark 机器人",
+ "description": "通过飞书或 Lark 机器人随时随地连接 {{appName}} 进行工作。",
+ "statusAria": "飞书 / Lark 机器人状态:{{status}}",
+ "serviceLabel": "服务",
+ "serviceAria": "选择 IM 服务",
+ "services": {
+ "feishu": "飞书",
+ "lark": "Lark"
+ },
"status": {
"needsConfig": "需要配置",
"connecting": "连接中…",
@@ -1592,16 +1598,17 @@
"error": "连接失败"
},
"connected": {
- "heading": "飞书机器人已连接",
+ "heading": "{{service}} 机器人已连接",
"note": "已绑定当前扫码用户,其他人私聊会被自动忽略。",
+ "serviceLabel": "服务",
"appIdLabel": "App ID",
"ownerLabel": "Owner",
"ownerWaiting": "等待首次私聊绑定",
- "reconnect": "重新连接飞书机器人",
+ "reconnect": "重新连接 {{service}} 机器人",
"clear": "解绑"
},
"saved": {
- "heading": "飞书机器人已绑定",
+ "heading": "{{service}} 机器人已绑定",
"connectingNote": "已保存机器人凭证,正在建立连接。",
"reconnectingNote": "已保存机器人凭证,正在恢复连接。",
"conflictNote": "已保存机器人凭证,但该 App ID 当前被其他设备占用。",
@@ -1614,11 +1621,11 @@
"appSecretPlaceholder": "sec_xxxxxxxxxxxxxxxxxx",
"showSecret": "显示密钥",
"hideSecret": "隐藏密钥",
- "createLink": "点击链接创建 ↗",
+ "createLink": "前往 {{service}} 开放平台创建 ↗",
"createLinkSuffix": ",创建完成后填入",
- "clearAria": "解绑飞书机器人",
+ "clearAria": "解绑 IM 机器人",
"clearConfirm": {
- "title": "解绑飞书机器人?",
+ "title": "解绑 IM 机器人?",
"description": "解绑后将断开 WebSocket 连接,并删除本机保存的 App ID / App Secret / 主人 openId。如需重新使用,需要重新创建或重新填写凭证。",
"confirm": "解绑",
"cancel": "取消"
@@ -4367,12 +4374,12 @@
},
"imBot": {
"conflictDialog": {
- "title": "该飞书机器人 App 已被占用",
+ "title": "该 {{service}} 机器人 App 已被占用",
"bodyPrefix": "当前 App",
"bodyMain": "已经在另一台设备上启动了长连接,可能是同事在使用同一个 App ID。一个 App 只能绑定一台设备,本机已自动断开以避免互相抢占。",
"suggestionsHeading": "建议两种处理方式:",
"suggestion1": "1. 与对方协商错峰使用,让对方先在其设备上清除该凭证后,本机再重新连接;",
- "suggestion2": "2. 到飞书开放平台为自己另建一个独立 App,与同事各用各的。",
+ "suggestion2": "2. 到 {{service}} 开放平台为自己另建一个独立 App,与同事各用各的。",
"dismiss": "关闭",
"createOwnApp": "创建我的 App ↗"
}
@@ -7614,16 +7621,16 @@
"toasts": {
"googleConnected": "Google 已连接",
"codexConnected": "ChatGPT 账号已连接",
- "feishuBotConnected": "飞书机器人已连接",
- "feishuBotReconnected": "飞书机器人已重新连接",
- "feishuBotReconnectFailed": "重新连接失败,请检查飞书配置后重试",
+ "feishuBotConnected": "IM 机器人已连接",
+ "feishuBotReconnected": "IM 机器人已重新连接",
+ "feishuBotReconnectFailed": "重新连接失败,请检查 IM 机器人配置后重试",
"feishuBotConflict": "该 App 已被占用,可能是同事在用同一个 App ID",
"feishuBotConnectFailed": "连接失败,请检查 App ID / Secret",
"feishuBotSaveFailed": "保存失败:{{message}}",
- "feishuBotCleared": "已清除飞书机器人凭证",
+ "feishuBotCleared": "已清除 IM 机器人凭证",
"feishuBotClearFailed": "清除失败:{{message}}",
- "feishuBotCreatedConnected": "飞书机器人已创建并连接",
- "feishuBotCreatedCheck": "飞书机器人已创建,请检查连接状态",
+ "feishuBotCreatedConnected": "IM 机器人已创建并连接",
+ "feishuBotCreatedCheck": "IM 机器人已创建,请检查连接状态",
"discordBotConnected": "Discord 机器人配置已保存",
"discordBotConnectFailed": "Discord 机器人连接失败,请检查 Token 和权限",
"discordBotSaveFailed": "保存失败:{{message}}",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 9ebe710bbb..bada6cc6d3 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1710,8 +1710,9 @@ interface ElectronAPI {
ownerOpenId: string | null;
error?: string;
lifecycleAnnouncement: boolean;
+ service: 'feishu' | 'lark';
}>;
- save: (payload: { appId: string; appSecret: string }) => Promise<{
+ save: (payload: { appId: string; appSecret: string; service: 'feishu' | 'lark' }) => Promise<{
verdict: 'connected' | 'conflict' | 'error' | 'pending';
}>;
reconnect: () => Promise<{
@@ -1719,7 +1720,7 @@ interface ElectronAPI {
}>;
clear: () => Promise<{ ok: true }>;
setLifecycleAnnouncement: (enabled: boolean) => Promise<{ ok: true }>;
- registrationBegin: () => Promise<FeishuBotRegistrationBeginResult>;
+ registrationBegin: (service: 'feishu' | 'lark') => Promise<FeishuBotRegistrationBeginResult>;
registrationCancel: () => Promise<{ ok: true }>;
onStatusChange: (
callback: (update: {
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 97efce65cf..632e641c03 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -160,6 +160,10 @@ OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入
钉钉机器人连接的产品名称,沿用官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。
+### Lark
+
+Lark 国际版 IM 服务的官方品牌名,四语统一保留原品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。
+
### Black Cat
灵动岛角色皮肤名(设置页「图标皮肤」列表)。角色本体是黑猫形象,四语先采用直译并登记为待讨论,避免后续界面出现「ブラックキャット / 블랙캣」等音译与直译混用。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 86bcd5d4e6..77e37696e2 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -76,6 +76,17 @@
},
"note": "个人微信连接的产品名称,沿用微信官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。"
},
+ {
+ "id": "lark",
+ "status": "proposed",
+ "en": "Lark",
+ "translations": {
+ "zh-CN": "Lark",
+ "ja": "Lark",
+ "ko": "Lark"
+ },
+ "note": "Lark 国际版 IM 服务的官方品牌名,四语统一保留原品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。"
+ },
{
"id": "personal-wechat",
"status": "proposed",
diff --git a/packages/lizi-im/src/feishu/__tests__/appRegistration.test.ts b/packages/lizi-im/src/feishu/__tests__/appRegistration.test.ts
new file mode 100644
index 0000000000..9a925004ae
--- /dev/null
+++ b/packages/lizi-im/src/feishu/__tests__/appRegistration.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ FEISHU_ACCOUNTS_BASE_URL,
+ pollAppRegistration,
+ requestAppRegistration,
+} from '../appRegistration.js';
+
+describe('app registration service routing', () => {
+ it('bootstraps on Feishu while using the selected verification host', async () => {
+ const post = vi.fn(async () => ({
+ status: 200,
+ body: {
+ device_code: 'device-code',
+ user_code: 'user-code',
+ expires_in: 300,
+ interval: 5,
+ },
+ }));
+
+ const result = await requestAppRegistration(post, 'lark');
+
+ expect(post).toHaveBeenCalledWith(
+ `${FEISHU_ACCOUNTS_BASE_URL}/oauth/v1/app/registration`,
+ expect.any(URLSearchParams),
+ );
+ expect(result.verificationUrl).toContain('open.larksuite.com');
+ });
+
+ it('preserves tenant brand discovery on authorization-pending responses', async () => {
+ const post = vi.fn(async () => ({
+ status: 400,
+ body: {
+ error: 'authorization_pending',
+ user_info: { tenant_brand: 'lark' },
+ },
+ }));
+
+ await expect(
+ pollAppRegistration(post, 'feishu', 'device-code', 5),
+ ).resolves.toEqual({
+ status: 'pending',
+ tenantBrand: 'lark',
+ });
+ });
+
+ it('keeps polling when a successful response has no complete credentials yet', async () => {
+ const post = vi.fn(async () => ({
+ status: 200,
+ body: {
+ user_info: { tenant_brand: 'lark' },
+ },
+ }));
+
+ await expect(
+ pollAppRegistration(post, 'feishu', 'device-code', 5),
+ ).resolves.toEqual({
+ status: 'pending',
+ tenantBrand: 'lark',
+ });
+ });
+});
diff --git a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
index 17adf7907e..30078b73fc 100644
--- a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
@@ -9,7 +9,12 @@ const mocks = vi.hoisted(() => ({
() => 'idle' | 'testing' | 'connected' | 'reconnecting' | 'conflict' | 'error'
>(() => 'idle'),
readCredentials: vi.fn(
- () => null as { appId: string; appSecret: string } | null,
+ () =>
+ null as {
+ appId: string;
+ appSecret: string;
+ service: 'feishu' | 'lark';
+ } | null,
),
writeCredentials: vi.fn(() => true),
writeOwnerOpenId: vi.fn(() => true),
@@ -136,13 +141,170 @@ afterEach(() => {
});
describe('Feishu IPC account scope', () => {
+ it('starts app registration with the selected verification service', async () => {
+ mocks.requestRegistration.mockResolvedValue({
+ deviceCode: 'device-code',
+ userCode: 'user-code',
+ verificationUrl: 'https://example.test',
+ interval: 60,
+ expiresIn: 60,
+ });
+ const begin = handlers.get('feishuBot:registration-begin');
+
+ await expect(Promise.resolve(begin?.({ service: 'lark' }))).resolves.toMatchObject({
+ ok: true,
+ });
+
+ expect(mocks.requestRegistration).toHaveBeenCalledWith(host.httpPostForm, 'lark');
+ cancelAppRegistration();
+ });
+
+ it('switches to Lark immediately when Feishu reports the tenant while pending', async () => {
+ vi.useFakeTimers();
+ mocks.requestRegistration.mockResolvedValue({
+ deviceCode: 'device-code',
+ userCode: 'user-code',
+ verificationUrl: 'https://open.larksuite.com/page/cli',
+ interval: 1,
+ expiresIn: 600,
+ });
+ mocks.pollRegistration
+ .mockResolvedValueOnce({
+ status: 'pending',
+ tenantBrand: 'lark',
+ })
+ .mockResolvedValueOnce({
+ status: 'pending',
+ })
+ .mockResolvedValueOnce({
+ status: 'success',
+ result: {
+ clientId: 'cli_lark',
+ clientSecret: 'lark-secret',
+ tenantBrand: null,
+ ownerOpenId: 'ou_lark_owner',
+ },
+ });
+
+ const begin = handlers.get('feishuBot:registration-begin');
+ await expect(
+ Promise.resolve(begin?.({ service: 'lark' })),
+ ).resolves.toMatchObject({
+ ok: true,
+ });
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(mocks.pollRegistration).toHaveBeenNthCalledWith(
+ 1,
+ host.httpPostForm,
+ 'feishu',
+ 'device-code',
+ 1,
+ );
+ expect(mocks.pollRegistration).toHaveBeenNthCalledWith(
+ 2,
+ host.httpPostForm,
+ 'lark',
+ 'device-code',
+ 1,
+ );
+ expect(mocks.writeCredentials).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(mocks.pollRegistration).toHaveBeenNthCalledWith(
+ 3,
+ host.httpPostForm,
+ 'lark',
+ 'device-code',
+ 1,
+ );
+ expect(mocks.writeCredentials).toHaveBeenCalledWith({
+ appId: 'cli_lark',
+ appSecret: 'lark-secret',
+ service: 'lark',
+ });
+ });
+
+ it('keeps polling Lark when the first cross-domain poll is still pending', async () => {
+ vi.useFakeTimers();
+ mocks.requestRegistration.mockResolvedValue({
+ deviceCode: 'device-code',
+ userCode: 'user-code',
+ verificationUrl: 'https://open.larksuite.com/page/cli',
+ interval: 1,
+ expiresIn: 600,
+ });
+ mocks.pollRegistration
+ .mockResolvedValueOnce({
+ status: 'success',
+ result: {
+ clientId: 'cli_lark',
+ clientSecret: '',
+ tenantBrand: 'lark',
+ ownerOpenId: 'ou_lark_owner',
+ },
+ })
+ .mockResolvedValueOnce({ status: 'pending' })
+ .mockResolvedValueOnce({
+ status: 'success',
+ result: {
+ clientId: 'cli_lark',
+ clientSecret: 'lark-secret',
+ tenantBrand: 'lark',
+ ownerOpenId: 'ou_lark_owner',
+ },
+ });
+
+ const begin = handlers.get('feishuBot:registration-begin');
+ await expect(
+ Promise.resolve(begin?.({ service: 'lark' })),
+ ).resolves.toMatchObject({
+ ok: true,
+ });
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(mocks.pollRegistration).toHaveBeenNthCalledWith(
+ 1,
+ host.httpPostForm,
+ 'feishu',
+ 'device-code',
+ 1,
+ );
+ expect(mocks.pollRegistration).toHaveBeenNthCalledWith(
+ 2,
+ host.httpPostForm,
+ 'lark',
+ 'device-code',
+ 1,
+ );
+ expect(mocks.writeCredentials).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(mocks.pollRegistration).toHaveBeenNthCalledWith(
+ 3,
+ host.httpPostForm,
+ 'lark',
+ 'device-code',
+ 1,
+ );
+ expect(mocks.writeCredentials).toHaveBeenCalledWith({
+ appId: 'cli_lark',
+ appSecret: 'lark-secret',
+ service: 'lark',
+ });
+ });
+
it('does not reconnect when credential save loses its account generation', async () => {
const gate = deferred<void>();
operationGate = gate.promise;
const save = handlers.get('feishuBot:save');
expect(save).toBeDefined();
- const saving = Promise.resolve(save?.({ appId: 'cli_test', appSecret: 'secret' }));
+ const saving = Promise.resolve(
+ save?.({ appId: 'cli_test', appSecret: 'secret', service: 'feishu' }),
+ );
await vi.waitFor(() => expect(accountRun).toHaveBeenCalledWith(accountToken));
active = false;
@@ -176,7 +338,7 @@ describe('Feishu IPC account scope', () => {
mocks.pollRegistration.mockReturnValue(poll.promise);
const begin = handlers.get('feishuBot:registration-begin');
- await expect(Promise.resolve(begin?.())).resolves.toMatchObject({
+ await expect(Promise.resolve(begin?.({ service: 'feishu' }))).resolves.toMatchObject({
ok: true,
});
await vi.advanceTimersByTimeAsync(1000);
@@ -201,7 +363,11 @@ describe('Feishu IPC account scope', () => {
});
describe('Feishu credential connection semantics', () => {
- const credentials = { appId: 'cli_test', appSecret: 'secret' };
+ const credentials = {
+ appId: 'cli_test',
+ appSecret: 'secret',
+ service: 'feishu' as const,
+ };
it('delegates owner clearing to stop before the idle status is broadcast', async () => {
await clearAndDisconnect();
@@ -232,7 +398,7 @@ describe('Feishu credential connection semantics', () => {
mocks.getCurrentStatus.mockReturnValue('connected');
await expect(
- saveAndConnect(credentials.appId, credentials.appSecret, {
+ saveAndConnect(credentials.appId, credentials.appSecret, credentials.service, {
replacementOwnerOpenId: 'ou_registered_owner',
}),
).resolves.toEqual({ verdict: 'connected' });
@@ -249,7 +415,7 @@ describe('Feishu credential connection semantics', () => {
mocks.writeOwnerOpenId.mockReturnValue(false);
await expect(
- saveAndConnect(credentials.appId, credentials.appSecret, {
+ saveAndConnect(credentials.appId, credentials.appSecret, credentials.service, {
replacementOwnerOpenId: 'ou_registered_owner',
}),
).rejects.toThrow('[OWNER_PERSIST_FAILED]');
@@ -297,7 +463,9 @@ describe('Feishu credential connection semantics', () => {
it('suppresses lifecycle announcements for an explicit manual reconnect', async () => {
mocks.readCredentials.mockReturnValue(credentials);
- await expect(reconnectSavedCredentials()).resolves.toEqual({ verdict: 'connected' });
+ await expect(reconnectSavedCredentials()).resolves.toEqual({
+ verdict: 'connected',
+ });
expect(mocks.stop).toHaveBeenCalledWith({
announceOffline: false,
@@ -321,7 +489,33 @@ describe('Feishu credential connection semantics', () => {
clearOwnerBeforeIdle: true,
});
expect(mocks.start).toHaveBeenCalledWith(
- { appId: 'cli_other', appSecret: 'other-secret' },
+ { appId: 'cli_other', appSecret: 'other-secret', service: 'feishu' },
+ { reason: 'credentials-replaced' },
+ );
+ });
+
+ it('treats switching between Feishu and Lark as a new owner boundary', async () => {
+ mocks.readCredentials.mockReturnValue(credentials);
+
+ await expect(saveAndConnect(credentials.appId, credentials.appSecret, 'lark')).resolves.toEqual(
+ { verdict: 'connected' },
+ );
+
+ expect(mocks.writeCredentials).toHaveBeenCalledWith({
+ appId: credentials.appId,
+ appSecret: credentials.appSecret,
+ service: 'lark',
+ });
+ expect(mocks.stop).toHaveBeenCalledWith({
+ reason: 'credentials-replaced',
+ clearOwnerBeforeIdle: true,
+ });
+ expect(mocks.start).toHaveBeenCalledWith(
+ {
+ appId: credentials.appId,
+ appSecret: credentials.appSecret,
+ service: 'lark',
+ },
{ reason: 'credentials-replaced' },
);
});
@@ -330,7 +524,7 @@ describe('Feishu credential connection semantics', () => {
mocks.readCredentials.mockReturnValue(credentials);
await expect(
- saveAndConnect('cli_registered', 'registered-secret', {
+ saveAndConnect('cli_registered', 'registered-secret', 'feishu', {
replacementOwnerOpenId: 'ou_registered_owner',
}),
).resolves.toEqual({ verdict: 'connected' });
@@ -351,7 +545,7 @@ describe('Feishu credential connection semantics', () => {
mocks.writeOwnerOpenId.mockReturnValue(false);
await expect(
- saveAndConnect('cli_registered', 'registered-secret', {
+ saveAndConnect('cli_registered', 'registered-secret', 'feishu', {
replacementOwnerOpenId: 'ou_registered_owner',
}),
).rejects.toThrow('[OWNER_PERSIST_FAILED]');
diff --git a/packages/lizi-im/src/feishu/__tests__/serviceRouting.test.ts b/packages/lizi-im/src/feishu/__tests__/serviceRouting.test.ts
new file mode 100644
index 0000000000..dc21080864
--- /dev/null
+++ b/packages/lizi-im/src/feishu/__tests__/serviceRouting.test.ts
@@ -0,0 +1,43 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+const constructedDomains: unknown[] = [];
+
+vi.doMock('@larksuiteoapi/node-sdk', () => ({
+ Client: class {
+ readonly im = {};
+
+ constructor(options: { domain?: unknown }) {
+ constructedDomains.push(options.domain);
+ }
+ },
+ Domain: {
+ Feishu: 'feishu-domain',
+ Lark: 'lark-domain',
+ },
+}));
+
+let outbound: typeof import('../outbound.js');
+
+beforeAll(async () => {
+ outbound = await import('../outbound.js');
+});
+
+afterAll(() => {
+ outbound.unbindClient();
+ vi.doUnmock('@larksuiteoapi/node-sdk');
+});
+
+describe('outbound IM service routing', () => {
+ it.each([
+ ['feishu', 'feishu-domain'],
+ ['lark', 'lark-domain'],
+ ] as const)('uses the %s API domain', (service, expectedDomain) => {
+ outbound.bindClient({
+ appId: 'cli_service_test',
+ appSecret: 'secret',
+ service,
+ });
+
+ expect(constructedDomains.at(-1)).toBe(expectedDomain);
+ });
+});
diff --git a/packages/lizi-im/src/feishu/__tests__/storageService.test.ts b/packages/lizi-im/src/feishu/__tests__/storageService.test.ts
new file mode 100644
index 0000000000..ce45e95d24
--- /dev/null
+++ b/packages/lizi-im/src/feishu/__tests__/storageService.test.ts
@@ -0,0 +1,92 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const values = new Map<string, string>();
+let failNextKey: string | null = null;
+
+const secrets = {
+ isAvailable: () => true,
+ read: (key: string) => values.get(key) ?? null,
+ write: (key: string, value: string) => {
+ if (failNextKey === key) {
+ failNextKey = null;
+ return false;
+ }
+ values.set(key, value);
+ return true;
+ },
+ remove: (key: string) => {
+ values.delete(key);
+ },
+};
+
+vi.doMock('../moduleScope.js', () => ({
+ getHost: () => ({ secrets }),
+ getLog: () => ({
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ }),
+}));
+
+let storage: typeof import('../storage.js');
+
+beforeAll(async () => {
+ storage = await import('../storage.js');
+});
+
+beforeEach(() => {
+ values.clear();
+ failNextKey = null;
+});
+
+describe('IM service credential storage', () => {
+ it('defaults legacy credentials without a service key to Feishu', () => {
+ values.set('feishu_bot_app_id', 'cli_legacy');
+ values.set('feishu_bot_app_secret', 'legacy-secret');
+
+ expect(storage.readCredentials()).toEqual({
+ appId: 'cli_legacy',
+ appSecret: 'legacy-secret',
+ service: 'feishu',
+ });
+ });
+
+ it('persists Lark as part of the credential set', () => {
+ expect(
+ storage.writeCredentials({
+ appId: 'cli_lark',
+ appSecret: 'lark-secret',
+ service: 'lark',
+ }),
+ ).toBe(true);
+
+ expect(storage.readCredentials()).toEqual({
+ appId: 'cli_lark',
+ appSecret: 'lark-secret',
+ service: 'lark',
+ });
+ });
+
+ it('restores the previous credential set when a write fails', () => {
+ values.set('feishu_bot_app_id', 'cli_previous');
+ values.set('feishu_bot_app_secret', 'previous-secret');
+ values.set('feishu_bot_service', 'feishu');
+ failNextKey = 'feishu_bot_app_secret';
+
+ expect(
+ storage.writeCredentials({
+ appId: 'cli_replacement',
+ appSecret: 'replacement-secret',
+ service: 'lark',
+ }),
+ ).toBe(false);
+ expect(storage.readCredentials()).toEqual({
+ appId: 'cli_previous',
+ appSecret: 'previous-secret',
+ service: 'feishu',
+ });
+ });
+});
diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts
index 5d2b05ae71..db44737246 100644
--- a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts
@@ -1,13 +1,4 @@
-import {
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from 'vitest';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { feishuEvents } from '../events.js';
import { messages as transportMessages } from '../messages.js';
@@ -19,6 +10,7 @@ interface CapturingLogger {
interface MockSdkOptions {
logger: CapturingLogger;
+ domain?: string;
onReady?: () => void;
onError?: (error: Error) => void;
}
@@ -65,6 +57,7 @@ vi.doMock('@larksuiteoapi/node-sdk', () => ({
}
},
LoggerLevel: { info: 'info' },
+ Domain: { Feishu: 'feishu-domain', Lark: 'lark-domain' },
}));
vi.doMock('../outbound.js', () => ({
@@ -94,6 +87,7 @@ let wsClient: typeof import('../wsClient.js');
const credentials = {
appId: 'cli_conflict_test',
appSecret: 'secret',
+ service: 'feishu' as const,
};
function latestClient() {
@@ -138,13 +132,13 @@ describe('Feishu WebSocket conflict handling', () => {
feishuEvents.on('conflict', onConflict);
try {
- const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ const connecting = wsClient.start(credentials, {
+ announceLifecycle: false,
+ });
const sdkClient = latestClient();
sdkClient.options.onError?.(
- new Error(
- 'pullConnectConfig failed: code=1000040350, msg=exceed_conn_limit',
- ),
+ new Error('pullConnectConfig failed: code=1000040350, msg=exceed_conn_limit'),
);
sdkClient.options.onReady?.();
expect(wsClient.getCurrentStatus()).not.toBe('connected');
@@ -164,7 +158,9 @@ describe('Feishu WebSocket conflict handling', () => {
feishuEvents.on('conflict', onConflict);
try {
- const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ const connecting = wsClient.start(credentials, {
+ announceLifecycle: false,
+ });
const sdkClient = latestClient();
sdkClient.options.onReady?.();
@@ -183,7 +179,9 @@ describe('Feishu WebSocket conflict handling', () => {
});
it('keeps SDK error-log parsing as a conflict fallback', async () => {
- const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ const connecting = wsClient.start(credentials, {
+ announceLifecycle: false,
+ });
const sdkClient = latestClient();
sdkClient.logger.error('[ws]', 'code: 1000040350, exceed_conn_limit');
@@ -202,7 +200,9 @@ describe('Feishu owner binding updates', () => {
feishuEvents.on('status', onStatus);
try {
- const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ const connecting = wsClient.start(credentials, {
+ announceLifecycle: false,
+ });
latestClient().options.onReady?.();
await expect(connecting).resolves.toBe('connected');
@@ -224,7 +224,9 @@ describe('Feishu owner binding updates', () => {
const onStatus = vi.fn();
try {
- const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ const connecting = wsClient.start(credentials, {
+ announceLifecycle: false,
+ });
latestClient().options.onReady?.();
await expect(connecting).resolves.toBe('connected');
feishuEvents.on('status', onStatus);
@@ -259,7 +261,9 @@ describe('Feishu owner binding updates', () => {
mocks.clearOwner.mockImplementationOnce(() => {
mocks.firstAllowed.mockReturnValue(null);
});
- const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ const connecting = wsClient.start(credentials, {
+ announceLifecycle: false,
+ });
latestClient().options.onReady?.();
await expect(connecting).resolves.toBe('connected');
const onStatus = vi.fn();
@@ -291,7 +295,9 @@ describe('Feishu owner binding updates', () => {
});
mocks.sendText.mockResolvedValue({ messageId: 'om_lifecycle' });
- const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ const connecting = wsClient.start(credentials, {
+ announceLifecycle: false,
+ });
latestClient().options.onReady?.();
await expect(connecting).resolves.toBe('connected');
await wsClient.stop({
@@ -306,6 +312,7 @@ describe('Feishu owner binding updates', () => {
const replacementCredentials = {
appId: 'cli_replacement',
appSecret: 'replacement-secret',
+ service: 'feishu' as const,
};
const replacementConnecting = wsClient.start(replacementCredentials, {
announceLifecycle: false,
@@ -330,3 +337,17 @@ describe('Feishu owner binding updates', () => {
);
});
});
+
+describe('IM service routing', () => {
+ it('selects the Lark SDK domain for Lark credentials', async () => {
+ const connecting = wsClient.start(
+ { ...credentials, service: 'lark' },
+ { announceLifecycle: false },
+ );
+ const sdkClient = latestClient();
+
+ expect(sdkClient.options.domain).toBe('lark-domain');
+ sdkClient.options.onReady?.();
+ await expect(connecting).resolves.toBe('connected');
+ });
+});
diff --git a/packages/lizi-im/src/feishu/appRegistration.ts b/packages/lizi-im/src/feishu/appRegistration.ts
index c24d250a29..d894e3ac0e 100644
--- a/packages/lizi-im/src/feishu/appRegistration.ts
+++ b/packages/lizi-im/src/feishu/appRegistration.ts
@@ -17,15 +17,23 @@ export interface AppRegistrationSuccessResult {
tenantBrand: LarkBrand | null;
}
+interface AppRegistrationBrandDiscovery {
+ /** Brand reported before credentials are complete (including pending responses). */
+ tenantBrand?: LarkBrand;
+}
+
export type AppRegistrationPollResult =
- | { status: 'pending' }
- | { status: 'slow_down'; interval: number }
+ | ({ status: 'pending' } & AppRegistrationBrandDiscovery)
+ | ({ status: 'slow_down'; interval: number } & AppRegistrationBrandDiscovery)
| { status: 'success'; result: AppRegistrationSuccessResult }
- | { status: 'expired'; message: string }
- | { status: 'denied'; message: string }
- | { status: 'error'; message: string };
+ | ({ status: 'expired'; message: string } & AppRegistrationBrandDiscovery)
+ | ({ status: 'denied'; message: string } & AppRegistrationBrandDiscovery)
+ | ({ status: 'error'; message: string } & AppRegistrationBrandDiscovery);
-type HttpPostForm = (url: string, form: URLSearchParams) => Promise<{ status: number; body: unknown }>;
+type HttpPostForm = (
+ url: string,
+ form: URLSearchParams,
+) => Promise<{ status: number; body: unknown }>;
const log = makeScopedLogger('appRegistration');
@@ -47,7 +55,11 @@ function registrationEndpoint(brand: LarkBrand): string {
return `${accountsBase(brand)}/oauth/v1/app/registration`;
}
-export function buildVerificationUrl(brand: LarkBrand, userCode: string, appVersion?: string): string {
+export function buildVerificationUrl(
+ brand: LarkBrand,
+ userCode: string,
+ appVersion?: string,
+): string {
const url = new URL('/page/cli', openBase(brand));
url.searchParams.set('user_code', userCode);
if (appVersion) {
@@ -74,11 +86,16 @@ export async function requestAppRegistration(
// 对照实现: lark-cli 同样不在此处订阅, 在 consume preflight 时报错让用户去 console
// (https://github.com/larksuite/cli/blob/main/internal/auth/app_registration.go).
+ // Device-code registration always bootstraps on Feishu. `brand` only picks
+ // the user-facing verification host; polling discovers the issuing tenant
+ // and switches to Lark when required.
const res = await httpPostForm(registrationEndpoint('feishu'), form);
const data = asRecord(res.body);
const apiError = getString(data, 'error');
if (res.status >= 400 || apiError) {
- throw new Error(getString(data, 'error_description') || apiError || 'app registration begin failed');
+ throw new Error(
+ getString(data, 'error_description') || apiError || 'app registration begin failed',
+ );
}
const deviceCode = getString(data, 'device_code');
@@ -111,10 +128,11 @@ export async function pollAppRegistration(
const res = await httpPostForm(registrationEndpoint(brand), form);
const data = asRecord(res.body);
const err = getString(data, 'error');
+ const userInfo = asRecord(data.user_info);
+ const tenantBrand = normalizeBrand(getString(userInfo, 'tenant_brand'));
+ const brandDiscovery = tenantBrand ? { tenantBrand } : {};
if (!err && getString(data, 'client_id')) {
- const userInfo = asRecord(data.user_info);
- const tenantBrand = normalizeBrand(getString(userInfo, 'tenant_brand'));
return {
status: 'success',
result: {
@@ -126,27 +144,33 @@ export async function pollAppRegistration(
};
}
+ if (!err && res.status < 400) {
+ return { status: 'pending', ...brandDiscovery };
+ }
+
switch (err) {
case 'authorization_pending':
- return { status: 'pending' };
+ return { status: 'pending', ...brandDiscovery };
case 'slow_down':
- return { status: 'slow_down', interval: Math.min(interval + 5, 60) };
+ return { status: 'slow_down', interval: Math.min(interval + 5, 60), ...brandDiscovery };
case 'access_denied':
return {
status: 'denied',
message: getString(data, 'error_description') || 'Authorization denied by user',
+ ...brandDiscovery,
};
case 'expired_token':
case 'invalid_grant':
return {
status: 'expired',
message: getString(data, 'error_description') || 'Device code expired, please try again',
+ ...brandDiscovery,
};
}
const msg = getString(data, 'error_description') || err || `HTTP ${res.status}`;
log.warn(`[feishu/appRegistration] poll failed brand=${brand}: ${msg}`);
- return { status: 'error', message: msg };
+ return { status: 'error', message: msg, ...brandDiscovery };
}
function normalizeBrand(value: string): LarkBrand | null {
diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.ts
index fb2178077e..1056397377 100644
--- a/packages/lizi-im/src/feishu/index.ts
+++ b/packages/lizi-im/src/feishu/index.ts
@@ -124,10 +124,7 @@ export class FeishuIM extends BaseIM implements ChannelIM {
return outbound.sendInteractive(openId, { body: markdown, buttons: [] });
}
- startStreamingText(
- openId: string,
- initial?: string,
- ): Promise<StreamingTextHandle> {
+ startStreamingText(openId: string, initial?: string): Promise<StreamingTextHandle> {
return streamingText.start(openId, initial);
}
@@ -139,10 +136,7 @@ export class FeishuIM extends BaseIM implements ChannelIM {
return streamingText.patchMarkdown(messageId, markdown);
}
- sendInteractiveCard(
- openId: string,
- spec: InteractiveCardSpec,
- ): Promise<{ messageId: string }> {
+ sendInteractiveCard(openId: string, spec: InteractiveCardSpec): Promise<{ messageId: string }> {
return outbound.sendInteractive(openId, spec);
}
@@ -150,11 +144,7 @@ export class FeishuIM extends BaseIM implements ChannelIM {
return outbound.updateInteractive(messageId, spec);
}
- sendFile(
- openId: string,
- absPath: string,
- displayName?: string,
- ): Promise<SendFileResult> {
+ sendFile(openId: string, absPath: string, displayName?: string): Promise<SendFileResult> {
return outbound.sendFile(openId, absPath, displayName);
}
@@ -209,6 +199,11 @@ export class FeishuIM extends BaseIM implements ChannelIM {
getOwnerOpenId(): string | null {
return ownerGuard.firstAllowed();
}
+
+ /** Active Open Platform service; legacy credentials default to Feishu. */
+ getService(): 'feishu' | 'lark' {
+ return storage.readCredentials()?.service ?? 'feishu';
+ }
}
export function createFeishuIM(host: IMHost): FeishuIM {
diff --git a/packages/lizi-im/src/feishu/internal-types.ts b/packages/lizi-im/src/feishu/internal-types.ts
index 908e473993..aac1e71e4d 100644
--- a/packages/lizi-im/src/feishu/internal-types.ts
+++ b/packages/lizi-im/src/feishu/internal-types.ts
@@ -7,12 +7,7 @@
*/
export type FeishuConnectionStatus =
- | 'idle'
- | 'testing'
- | 'connected'
- | 'reconnecting'
- | 'conflict'
- | 'error';
+ 'idle' | 'testing' | 'connected' | 'reconnecting' | 'conflict' | 'error';
export interface FeishuStatusUpdate {
status: FeishuConnectionStatus;
@@ -22,9 +17,7 @@ export interface FeishuStatusUpdate {
}
export type ConnectVerdict =
- | { kind: 'connected' }
- | { kind: 'conflict' }
- | { kind: 'error'; message: string };
+ { kind: 'connected' } | { kind: 'conflict' } | { kind: 'error'; message: string };
/**
* Public state surfaced to the renderer through `feishuBot:get-state` —
@@ -43,9 +36,13 @@ export interface FeishuPublicState {
ownerOpenId: string | null;
error?: string;
lifecycleAnnouncement: boolean;
+ service: FeishuService;
}
+export type FeishuService = 'feishu' | 'lark';
+
export interface BotCredentials {
appId: string;
appSecret: string;
+ service: FeishuService;
}
diff --git a/packages/lizi-im/src/feishu/ipc.ts b/packages/lizi-im/src/feishu/ipc.ts
index 038307acad..92c4792de6 100644
--- a/packages/lizi-im/src/feishu/ipc.ts
+++ b/packages/lizi-im/src/feishu/ipc.ts
@@ -23,6 +23,7 @@ import {
pollAppRegistration,
requestAppRegistration,
type AppRegistrationPollResult,
+ type LarkBrand,
} from './appRegistration.js';
import type { FeishuPublicState } from './internal-types.js';
@@ -73,20 +74,23 @@ export function registerFeishuIpc(): void {
host.ipc.handle('feishuBot:get-state', async () => getPublicState());
host.ipc.handle('feishuBot:save', async (payload) => {
- const p = payload as { appId?: unknown; appSecret?: unknown } | undefined;
+ const p = payload as { appId?: unknown; appSecret?: unknown; service?: unknown } | undefined;
if (
!p ||
typeof p.appId !== 'string' ||
typeof p.appSecret !== 'string' ||
+ (p.service !== 'feishu' && p.service !== 'lark') ||
p.appId.length === 0 ||
p.appSecret.length === 0
) {
- throw new Error('[INVALID_PAYLOAD] appId and appSecret required');
+ throw new Error('[INVALID_PAYLOAD] appId, appSecret and service required');
}
const appId = p.appId.trim();
const appSecret = p.appSecret.trim();
const accountScope = captureAccountScope();
- return runInAccountScope(accountScope, () => saveAndConnect(appId, appSecret));
+ return runInAccountScope(accountScope, () =>
+ saveAndConnect(appId, appSecret, p.service as LarkBrand),
+ );
});
host.ipc.handle('feishuBot:clear', async () => {
@@ -102,7 +106,12 @@ export function registerFeishuIpc(): void {
return { ok: true };
});
- host.ipc.handle('feishuBot:registration-begin', async () => {
+ host.ipc.handle('feishuBot:registration-begin', async (payload) => {
+ const p = payload as { service?: unknown } | undefined;
+ if (p?.service !== 'feishu' && p?.service !== 'lark') {
+ return { ok: false, error: '[INVALID_PAYLOAD] service required' };
+ }
+ const service = p.service;
registrationRunId++;
const runId = registrationRunId;
const accountScope = captureAccountScope();
@@ -110,7 +119,7 @@ export function registerFeishuIpc(): void {
return { ok: false, error: '[IM_NOT_READY] IM account is not active' };
}
try {
- const begin = await requestAppRegistration(host.httpPostForm, 'feishu');
+ const begin = await requestAppRegistration(host.httpPostForm, service);
if (runId !== registrationRunId || !isAccountScopeCurrent(accountScope)) {
return {
ok: false,
@@ -165,6 +174,7 @@ export function getPublicState(): FeishuPublicState {
hasSecret: creds != null,
ownerOpenId: storage.readOwnerOpenId(),
lifecycleAnnouncement: storage.readLifecycleAnnouncement(),
+ service: creds?.service ?? 'feishu',
};
}
@@ -176,10 +186,12 @@ interface SaveAndConnectOptions {
export async function saveAndConnect(
appId: string,
appSecret: string,
+ service: LarkBrand = 'feishu',
options: SaveAndConnectOptions = {},
): Promise<{ verdict: 'connected' | 'conflict' | 'error' | 'pending' }> {
const saved = storage.readCredentials();
- const credentialsUnchanged = saved?.appId === appId && saved.appSecret === appSecret;
+ const credentialsUnchanged =
+ saved?.appId === appId && saved.appSecret === appSecret && saved.service === service;
if (credentialsUnchanged && options.replacementOwnerOpenId) {
persistReplacementOwner(options.replacementOwnerOpenId);
}
@@ -190,31 +202,32 @@ export async function saveAndConnect(
return { verdict: 'connected' };
}
if (status === 'testing' || status === 'reconnecting') {
- getLog().info(
- `[feishu/ipc] saveAndConnect skipped: same credentials already ${status}`,
- );
+ getLog().info(`[feishu/ipc] saveAndConnect skipped: same credentials already ${status}`);
return { verdict: 'pending' };
}
return reconnectSavedCredentials();
}
- const ok = storage.writeCredentials({ appId, appSecret });
+ const ok = storage.writeCredentials({ appId, appSecret, service });
if (!ok) return { verdict: 'error' };
await wsClient.stop({
reason: 'credentials-replaced',
- clearOwnerBeforeIdle: saved?.appId !== appId,
+ clearOwnerBeforeIdle: saved?.appId !== appId || saved.service !== service,
});
if (options.replacementOwnerOpenId) {
persistReplacementOwner(options.replacementOwnerOpenId);
}
- const verdict = await wsClient.start({ appId, appSecret }, { reason: 'credentials-replaced' });
+ const verdict = await wsClient.start(
+ { appId, appSecret, service },
+ { reason: 'credentials-replaced' },
+ );
return { verdict };
}
function persistReplacementOwner(ownerOpenId: string): void {
const ownerWritten = storage.writeOwnerOpenId(ownerOpenId);
if (!ownerWritten) {
- throw new Error('[OWNER_PERSIST_FAILED] Failed to persist Feishu owner');
+ throw new Error('[OWNER_PERSIST_FAILED] Failed to persist IM bot owner');
}
ownerGuard.loadFromDisk();
}
@@ -225,7 +238,7 @@ export async function reconnectSavedCredentials(): Promise<{
}> {
const creds = storage.readCredentials();
if (!creds) {
- throw new Error('[NO_CREDENTIALS] Feishu bot credentials are not configured');
+ throw new Error('[NO_CREDENTIALS] IM bot credentials are not configured');
}
await wsClient.stop({ announceOffline: false, reason: 'manual-reconnect' });
const verdict = await wsClient.start(creds, {
@@ -246,18 +259,28 @@ async function pollRegistrationInBackground(
const log = getLog();
const deadline = Date.now() + expiresIn * 1000;
let currentInterval = Math.max(interval, 1);
+ let pollBrand: LarkBrand = 'feishu';
+ let pollWithoutDelay = false;
while (
Date.now() < deadline &&
runId === registrationRunId &&
isAccountScopeCurrent(accountScope)
) {
- await delay(currentInterval * 1000);
- if (runId !== registrationRunId || !isAccountScopeCurrent(accountScope)) return;
+ if (!pollWithoutDelay) {
+ await delay(currentInterval * 1000);
+ if (runId !== registrationRunId || !isAccountScopeCurrent(accountScope)) return;
+ }
+ pollWithoutDelay = false;
let result: AppRegistrationPollResult;
try {
- result = await pollAppRegistration(host.httpPostForm, 'feishu', deviceCode, currentInterval);
+ result = await pollAppRegistration(
+ host.httpPostForm,
+ pollBrand,
+ deviceCode,
+ currentInterval,
+ );
} catch (err) {
if (runId !== registrationRunId || !isAccountScopeCurrent(accountScope)) return;
const error = err instanceof Error ? err.message : String(err);
@@ -269,6 +292,14 @@ async function pollRegistrationInBackground(
}
if (runId !== registrationRunId || !isAccountScopeCurrent(accountScope)) return;
+ const discoveredBrand =
+ result.status === 'success' ? result.result.tenantBrand : result.tenantBrand;
+ if (pollBrand === 'feishu' && discoveredBrand === 'lark') {
+ pollBrand = 'lark';
+ pollWithoutDelay = true;
+ continue;
+ }
+
if (result.status === 'pending') {
host.ipc.broadcast('feishuBot:registration-status', {
status: 'pending',
@@ -285,31 +316,25 @@ async function pollRegistrationInBackground(
}
if (result.status === 'success') {
- let success = result.result;
- if (success.tenantBrand === 'lark' && !success.clientSecret) {
- const larkResult = await pollAppRegistration(
- host.httpPostForm,
- 'lark',
- deviceCode,
- currentInterval,
- );
- if (larkResult.status === 'success') success = larkResult.result;
- }
-
+ const success = result.result;
if (!success.clientId || !success.clientSecret) {
host.ipc.broadcast('feishuBot:registration-status', {
- status: 'error',
- error: 'app registration succeeded but missing client_id or client_secret',
+ status: 'pending',
});
- return;
+ continue;
}
let verdict: 'connected' | 'conflict' | 'error' | 'pending';
try {
({ verdict } = await runInAccountScope(accountScope, async () => {
- return saveAndConnect(success.clientId, success.clientSecret, {
- replacementOwnerOpenId: success.ownerOpenId,
- });
+ return saveAndConnect(
+ success.clientId,
+ success.clientSecret,
+ success.tenantBrand ?? pollBrand,
+ {
+ replacementOwnerOpenId: success.ownerOpenId,
+ },
+ );
}));
} catch (err) {
if (!isAccountScopeCurrent(accountScope)) return;
diff --git a/packages/lizi-im/src/feishu/messages.ts b/packages/lizi-im/src/feishu/messages.ts
index 45a3aa88a0..25db577fa6 100644
--- a/packages/lizi-im/src/feishu/messages.ts
+++ b/packages/lizi-im/src/feishu/messages.ts
@@ -9,7 +9,7 @@
export const messages = {
lifecycle: {
online: '🟢 已上线,可以开聊啦~',
- offline: '🔴 Cindy 已离线,暂时无法通过飞书继续聊天。',
+ offline: '🔴 Cindy 已离线,暂时无法通过当前 IM 继续聊天。',
offlineNotice: '🔔 我之前离线过一段时间,期间的消息可能没有收到哦~',
},
ownerBinding: {
diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.ts
index 7305ad6df1..d3e237d6c7 100644
--- a/packages/lizi-im/src/feishu/outbound.ts
+++ b/packages/lizi-im/src/feishu/outbound.ts
@@ -23,10 +23,7 @@ import * as Lark from '@larksuiteoapi/node-sdk';
import { getLog } from './moduleScope.js';
import { buildInteractiveCardV1 } from './cards.js';
-import type {
- InteractiveCardSpec,
- SendFileResult,
-} from '../types.js';
+import type { InteractiveCardSpec, SendFileResult } from '../types.js';
import type { BotCredentials } from './internal-types.js';
/** 30 MB per file — feishu's upper limit for `im.file.create`. */
@@ -39,7 +36,11 @@ let creds: BotCredentials | null = null;
export function bindClient(c: BotCredentials): void {
creds = c;
- client = new Lark.Client({ appId: c.appId, appSecret: c.appSecret });
+ client = new Lark.Client({
+ appId: c.appId,
+ appSecret: c.appSecret,
+ domain: c.service === 'lark' ? Lark.Domain.Lark : Lark.Domain.Feishu,
+ });
}
export function unbindClient(): void {
@@ -56,16 +57,14 @@ export function getBoundCreds(): BotCredentials | null {
}
function ensureClient(): Lark.Client {
- if (!client) throw new Error('[feishu/outbound] Lark.Client not bound — feishu connection not established');
+ if (!client)
+ throw new Error('[feishu/outbound] Lark.Client not bound — feishu connection not established');
return client;
}
// ── basic text ────────────────────────────────────────────────────────────────
-export async function sendText(
- openId: string,
- text: string,
-): Promise<{ messageId: string }> {
+export async function sendText(openId: string, text: string): Promise<{ messageId: string }> {
const res = await ensureClient().im.v1.message.create({
params: { receive_id_type: 'open_id' },
data: {
@@ -87,10 +86,7 @@ export async function sendText(
* - 飞书规则:只有原始添加者(此处是 bot 自己)能删除该 reaction,所以
* reaction_id 必须配对持有,跨进程/重启不可恢复 → 调用方负责短期持有。
*/
-export async function addReaction(
- messageId: string,
- emojiType: string,
-): Promise<string | null> {
+export async function addReaction(messageId: string, emojiType: string): Promise<string | null> {
const log = getLog();
try {
const res = await ensureClient().im.v1.messageReaction.create({
@@ -109,10 +105,7 @@ export async function addReaction(
* 撤销之前 addReaction 返回的 reaction_id 对应的表情。
* 失败 swallow,因为这是 ack 的清理动作,不应影响 turn 结束流程。
*/
-export async function removeReaction(
- messageId: string,
- reactionId: string,
-): Promise<void> {
+export async function removeReaction(messageId: string, reactionId: string): Promise<void> {
const log = getLog();
try {
await ensureClient().im.v1.messageReaction.delete({
@@ -157,10 +150,7 @@ export async function updateInteractive(
// ── raw card patch (used by streamingText for v2 markdown patching) ───────────
-export async function patchCardRaw(
- messageId: string,
- cardJson: unknown,
-): Promise<void> {
+export async function patchCardRaw(messageId: string, cardJson: unknown): Promise<void> {
await ensureClient().im.v1.message.patch({
path: { message_id: messageId },
data: { content: JSON.stringify(cardJson) },
@@ -283,9 +273,7 @@ export async function uploadImage(absPath: string): Promise<string | null> {
}
const stat = fs.statSync(absPath);
if (stat.size === 0 || stat.size > FEISHU_IMAGE_MAX_BYTES) {
- log.warn(
- `[feishu/outbound] uploadImage size ineligible ${stat.size} for ${absPath}`,
- );
+ log.warn(`[feishu/outbound] uploadImage size ineligible ${stat.size} for ${absPath}`);
return null;
}
const res = await ensureClient().im.v1.image.create({
diff --git a/packages/lizi-im/src/feishu/storage.ts b/packages/lizi-im/src/feishu/storage.ts
index 95b53ea5ec..9281f4a837 100644
--- a/packages/lizi-im/src/feishu/storage.ts
+++ b/packages/lizi-im/src/feishu/storage.ts
@@ -16,10 +16,11 @@
*/
import { getHost, getLog } from './moduleScope.js';
-import type { BotCredentials } from './internal-types.js';
+import type { BotCredentials, FeishuService } from './internal-types.js';
const KEY_APP_ID = 'feishu_bot_app_id';
const KEY_APP_SECRET = 'feishu_bot_app_secret';
+const KEY_SERVICE = 'feishu_bot_service';
const KEY_OWNER_OPEN_ID = 'feishu_bot_owner_open_id';
const KEY_LIFECYCLE_ANNOUNCEMENT = 'feishu_bot_lifecycle_announcement';
@@ -34,7 +35,11 @@ export function readCredentials(): BotCredentials | null {
const appId = secrets.read(KEY_APP_ID);
const appSecret = secrets.read(KEY_APP_SECRET);
if (!appId || !appSecret) return null;
- return { appId, appSecret };
+ return {
+ appId,
+ appSecret,
+ service: normalizeService(secrets.read(KEY_SERVICE)),
+ };
}
export function writeCredentials(creds: BotCredentials): boolean {
@@ -44,15 +49,23 @@ export function writeCredentials(creds: BotCredentials): boolean {
log.warn('[feishu/storage] secrets unavailable; refuse to write');
return false;
}
- const ok1 = secrets.write(KEY_APP_ID, creds.appId);
- if (!ok1) return false;
- const ok2 = secrets.write(KEY_APP_SECRET, creds.appSecret);
- if (!ok2) {
- secrets.remove(KEY_APP_ID);
+ const previous = {
+ appId: secrets.read(KEY_APP_ID),
+ appSecret: secrets.read(KEY_APP_SECRET),
+ service: secrets.read(KEY_SERVICE),
+ };
+ if (
+ !secrets.write(KEY_SERVICE, creds.service) ||
+ !secrets.write(KEY_APP_ID, creds.appId) ||
+ !secrets.write(KEY_APP_SECRET, creds.appSecret)
+ ) {
+ restoreSecret(KEY_SERVICE, previous.service);
+ restoreSecret(KEY_APP_ID, previous.appId);
+ restoreSecret(KEY_APP_SECRET, previous.appSecret);
return false;
}
log.info(
- `[feishu/storage] wrote credentials appId=${maskTail(creds.appId)} appSecret=${maskTail(creds.appSecret)}`,
+ `[feishu/storage] wrote credentials service=${creds.service} appId=${maskTail(creds.appId)} appSecret=${maskTail(creds.appSecret)}`,
);
return true;
}
@@ -61,6 +74,7 @@ export function clearAll(): void {
const secrets = getHost().secrets;
secrets.remove(KEY_APP_ID);
secrets.remove(KEY_APP_SECRET);
+ secrets.remove(KEY_SERVICE);
secrets.remove(KEY_OWNER_OPEN_ID);
}
@@ -103,3 +117,15 @@ export function writeLifecycleAnnouncement(enabled: boolean): void {
secrets.write(KEY_LIFECYCLE_ANNOUNCEMENT, String(enabled));
}
+function normalizeService(value: string | null): FeishuService {
+ return value === 'lark' ? 'lark' : 'feishu';
+}
+
+function restoreSecret(key: string, value: string | null): void {
+ const secrets = getHost().secrets;
+ if (value === null) {
+ secrets.remove(key);
+ return;
+ }
+ secrets.write(key, value);
+}
diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.ts
index 71044fb2af..050f7e416e 100644
--- a/packages/lizi-im/src/feishu/wsClient.ts
+++ b/packages/lizi-im/src/feishu/wsClient.ts
@@ -40,10 +40,7 @@ import { downloadAttachments } from './attachmentDownloader.js';
import { parseCardAction } from './cardActionParser.js';
import { getLog } from './moduleScope.js';
import { messages as transportMessages } from './messages.js';
-import type {
- BotCredentials,
- FeishuConnectionStatus,
-} from './internal-types.js';
+import type { BotCredentials, FeishuConnectionStatus } from './internal-types.js';
// ── module state ──────────────────────────────────────────────────────────────
@@ -106,21 +103,11 @@ function isConflictSignal(message: string): boolean {
}
function isActiveConnection(generation: number, appId: string): boolean {
- return (
- acceptingInbound &&
- lifecycleGeneration === generation &&
- currentBotAppId === appId
- );
+ return acceptingInbound && lifecycleGeneration === generation && currentBotAppId === appId;
}
-async function transitionToConflict(
- generation: number,
- appId: string,
-): Promise<void> {
- if (
- conflictTransitionGeneration === generation ||
- !isActiveConnection(generation, appId)
- ) {
+async function transitionToConflict(generation: number, appId: string): Promise<void> {
+ if (conflictTransitionGeneration === generation || !isActiveConnection(generation, appId)) {
return;
}
@@ -141,10 +128,7 @@ function handleReadySignal(
): void {
if (!isActiveConnection(generation, appId)) return;
activeDetector.markReady();
- if (
- activeDetector.getVerdict()?.kind === 'connected' &&
- currentStatus !== 'connected'
- ) {
+ if (activeDetector.getVerdict()?.kind === 'connected' && currentStatus !== 'connected') {
setStatus('connected');
}
}
@@ -156,10 +140,7 @@ function handleReconnectingSignal(
): void {
if (!isActiveConnection(generation, appId)) return;
activeDetector.markReconnecting();
- if (
- activeDetector.getVerdict()?.kind !== 'conflict' &&
- currentStatus === 'connected'
- ) {
+ if (activeDetector.getVerdict()?.kind !== 'conflict' && currentStatus === 'connected') {
setStatus('reconnecting');
}
}
@@ -171,10 +152,7 @@ function handleReconnectedSignal(
): void {
if (!isActiveConnection(generation, appId)) return;
activeDetector.markReconnected();
- if (
- activeDetector.getVerdict()?.kind === 'connected' &&
- currentStatus !== 'connected'
- ) {
+ if (activeDetector.getVerdict()?.kind === 'connected' && currentStatus !== 'connected') {
setStatus('connected');
}
}
@@ -187,10 +165,7 @@ function handleErrorSignal(
): void {
if (!isActiveConnection(generation, appId)) return;
if (isConflictSignal(error.message)) {
- if (
- !activeDetector.markConflict() &&
- activeDetector.getVerdict()?.kind !== 'conflict'
- ) {
+ if (!activeDetector.markConflict() && activeDetector.getVerdict()?.kind !== 'conflict') {
void transitionToConflict(generation, appId);
}
return;
@@ -218,9 +193,7 @@ function makeCapturingLogger(
trace: () => {},
debug: () => {},
info: (...args: unknown[]) => {
- const msg = args
- .map((a) => (typeof a === 'string' ? a : JSON.stringify(a)))
- .join(' ');
+ const msg = args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');
log.debug('[feishu/sdk-info]', msg);
if (!isActiveConnection(generation, appId)) return;
if (msg.includes('ws client ready')) {
@@ -231,28 +204,19 @@ function makeCapturingLogger(
handleReconnectingSignal(activeDetector, generation, appId);
} else if (msg.includes('unable to connect to the server')) {
activeDetector.markError(new Error('unable to connect after retries'));
- setStatus('error', '连接失败:飞书服务无法访问,请检查网络');
+ setStatus('error', '连接失败:IM 服务无法访问,请检查网络');
}
},
warn: (...args: unknown[]) => {
- const msg = args
- .map((a) => (typeof a === 'string' ? a : JSON.stringify(a)))
- .join(' ');
+ const msg = args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');
log.warn('[feishu/sdk-warn]', msg);
},
error: (...args: unknown[]) => {
- const msg = args
- .map((a) => (typeof a === 'string' ? a : JSON.stringify(a)))
- .join(' ');
+ const msg = args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');
log.error('[feishu/sdk-error]', msg);
if (!isActiveConnection(generation, appId)) return;
if (isConflictSignal(msg)) {
- handleErrorSignal(
- new Error(FEISHU_CONFLICT_ERROR),
- activeDetector,
- generation,
- appId,
- );
+ handleErrorSignal(new Error(FEISHU_CONFLICT_ERROR), activeDetector, generation, appId);
return;
}
if (msg.includes('code: 514')) {
@@ -285,12 +249,16 @@ export async function start(
currentBotAppId = creds.appId;
setStatus('testing');
- const startDetector = new ConflictDetector({ readyTimeoutMs: 8000, reconnectThreshold: 2 });
+ const startDetector = new ConflictDetector({
+ readyTimeoutMs: 8000,
+ reconnectThreshold: 2,
+ });
detector = startDetector;
client = new Lark.WSClient({
appId: creds.appId,
appSecret: creds.appSecret,
+ domain: creds.service === 'lark' ? Lark.Domain.Lark : Lark.Domain.Feishu,
loggerLevel: Lark.LoggerLevel.info,
autoReconnect: true,
logger: makeCapturingLogger(startDetector, startedGeneration, creds.appId),
@@ -463,9 +431,7 @@ async function announceLifecycle(phase: 'online' | 'offline'): Promise<void> {
}
const text =
- phase === 'online'
- ? transportMessages.lifecycle.online
- : transportMessages.lifecycle.offline;
+ phase === 'online' ? transportMessages.lifecycle.online : transportMessages.lifecycle.offline;
try {
log.info(`[feishu/wsClient] announceLifecycle ${phase}: sending to ...${owner.slice(-8)}`);
const res = await outbound.sendText(owner, text);
@@ -496,10 +462,7 @@ interface RawMessageEvent {
};
}
-async function handleIncomingMessage(
- botAppId: string,
- data: RawMessageEvent,
-): Promise<void> {
+async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): Promise<void> {
const log = getLog();
if (!acceptingInbound) {
log.info('[feishu/wsClient] drop inbound message while connection is stopping');
@@ -514,9 +477,7 @@ async function handleIncomingMessage(
// p2p only
if (data.message.chat_type !== 'p2p') {
- log.info(
- `[feishu/wsClient] drop non-p2p chat_type=${data.message.chat_type}`,
- );
+ log.info(`[feishu/wsClient] drop non-p2p chat_type=${data.message.chat_type}`);
return;
}
@@ -635,7 +596,5 @@ async function handleCardAction(data: unknown): Promise<unknown> {
// gives the user instant "click registered" feedback even before the
// orchestrator finishes patching the card. Generic wording — orchestrator's
// updateInteractiveCard authoritatively replaces the card body.
- return parsedOk
- ? { toast: { type: 'success', content: '已收到您的选择' } }
- : {};
+ return parsedOk ? { toast: { type: 'success', content: '已收到您的选择' } } : {};
}
diff --git a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts
index 336b17a359..18fd42591e 100644
--- a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts
@@ -2,7 +2,7 @@
* cindy_feishuBotMcpServer.ts
* ---------------------------------------------------------------------------
* In-process MCP server for the feishu bot channel. Attached to every session
- * (no source gate) so users can say "跑完通过飞书通知我" from a desktop chat
+ * (no source gate) so users can say "跑完通过飞书或 Lark 通知我" from a desktop chat
* and have the agent push results into the bot DM.
*
* 架构对齐 art MCP server:
@@ -22,10 +22,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { jsonObjectArg } from './json-object-arg.js';
-import {
- FeishuBotToolRegistry,
- type FeishuBotToolResult,
-} from './cindy_feishuBotToolRegistry';
+import { FeishuBotToolRegistry, type FeishuBotToolResult } from './cindy_feishuBotToolRegistry';
import type { FeishuBotMcpHostDeps } from './types.js';
import descListTools from './prompts/cindy_feishu_bot/tools/list_tools.md?raw';
@@ -50,10 +47,10 @@ type FeishuBotToolDescriptions = { [K in keyof typeof D]: string };
* (organic SlackIM 渠道及其 lizi_slack_bot 已于 2026-07-17 随老 relay 退役。)
*/
export const SLACK_HOOK_SESSION_CHANNEL_NOTE =
- '\n\n⚠️ 当前是 Slack 会话:文字回复直接输出即可(会自动回贴到当前 Slack thread,无需工具);把文件发给用户是在最终回复文本里写 `[文件名](xdt-file:///绝对路径)`(文件须位于当前工作目录内),图片直接引用其地址 `![说明](cindy-media://… 或 xdt-image://…)`,系统自动作为 Slack 附件发回,不要用本工具;仅当用户明确说「发飞书 / 飞书通知我」时才走飞书通道。';
+ '\n\n⚠️ 当前是 Slack 会话:文字回复直接输出即可(会自动回贴到当前 Slack thread,无需工具);把文件发给用户是在最终回复文本里写 `[文件名](xdt-file:///绝对路径)`(文件须位于当前工作目录内),图片直接引用其地址 `![说明](cindy-media://… 或 xdt-image://…)`,系统自动作为 Slack 附件发回,不要用本工具;仅当用户明确说「发飞书或 Lark / 通过飞书或 Lark 通知我」时才走该 IM 通道。';
export const TELEGRAM_HOOK_SESSION_CHANNEL_NOTE =
- '\n\n⚠️ 当前是 Telegram 会话:文字回复直接输出即可(会自动回贴到当前 Telegram 对话或回复链,无需工具);把文件发给用户是在最终回复文本里写 `[文件名](xdt-file:///绝对路径)`(文件须位于当前工作目录内),图片直接引用其地址 `![说明](cindy-media://… 或 xdt-image://…)`,系统自动作为 Telegram 附件发回,不要用本工具;仅当用户明确说「发飞书 / 飞书通知我」时才走飞书通道。';
+ '\n\n⚠️ 当前是 Telegram 会话:文字回复直接输出即可(会自动回贴到当前 Telegram 对话或回复链,无需工具);把文件发给用户是在最终回复文本里写 `[文件名](xdt-file:///绝对路径)`(文件须位于当前工作目录内),图片直接引用其地址 `![说明](cindy-media://… 或 xdt-image://…)`,系统自动作为 Telegram 附件发回,不要用本工具;仅当用户明确说「发飞书或 Lark / 通过飞书或 Lark 通知我」时才走该 IM 通道。';
const NOTE_BY_SOURCE: Record<string, string> = {
'slack-hook': SLACK_HOOK_SESSION_CHANNEL_NOTE,
@@ -143,9 +140,7 @@ function registerSendFileToUser(
absPath: z
.string()
.min(1)
- .describe(
- '本地绝对路径(必填)。Windows 反斜杠或正斜杠都行;Unix 必须 / 开头',
- ),
+ .describe('本地绝对路径(必填)。Windows 反斜杠或正斜杠都行;Unix 必须 / 开头'),
displayName: z
.string()
.optional()
@@ -158,18 +153,13 @@ function registerSendFileToUser(
{
ok: false,
errorCode: 'NO_CHAT_CONTEXT',
- error:
- `既没有当前飞书 session 的 chatId,bot 也没有绑定过 owner(用户从未私聊过 bot)。请让用户先在飞书里私聊自己配置的那个机器人一次完成绑定,再重试。`,
+ error: `既没有当前飞书 / Lark session 的 chatId,bot 也没有绑定过 owner(用户从未私聊过 bot)。请让用户先在已配置的 IM 服务里私聊机器人一次完成绑定,再重试。`,
},
true,
);
}
- const result = await deps.sendFile(
- chatId,
- absPath,
- displayName,
- );
+ const result = await deps.sendFile(chatId, absPath, displayName);
if (!result.ok) {
const codeMap: Record<string, string> = {
@@ -220,7 +210,7 @@ function registerSendMessageToUser(
.min(1)
.max(FEISHU_MESSAGE_MAX_CHARS)
.describe(
- `markdown 正文(必填,${FEISHU_MESSAGE_MAX_CHARS} 字符上限)。飞书 lark_md 支持 **bold** / _italic_ / \`code\` / 链接 / 列表 / > 引用 / # 标题。`,
+ `markdown 正文(必填,${FEISHU_MESSAGE_MAX_CHARS} 字符上限)。飞书 / Lark lark_md 支持 **bold** / _italic_ / \`code\` / 链接 / 列表 / > 引用 / # 标题。`,
),
},
handler: async ({ text }) => {
@@ -230,8 +220,7 @@ function registerSendMessageToUser(
{
ok: false,
errorCode: 'NO_CHAT_CONTEXT',
- error:
- `既没有当前飞书 session 的 chatId,bot 也没有绑定过 owner(用户从未私聊过 bot)。请让用户先在飞书里私聊自己配置的那个机器人一次完成绑定,再重试。`,
+ error: `既没有当前飞书 / Lark session 的 chatId,bot 也没有绑定过 owner(用户从未私聊过 bot)。请让用户先在已配置的 IM 服务里私聊机器人一次完成绑定,再重试。`,
},
true,
);
@@ -290,10 +279,7 @@ function registerListToolsEntry(
'list_tools',
d.list_tools,
{
- category: z
- .enum(CATEGORY_ENUM)
- .optional()
- .describe('工具类目。不传时返回所有类目概览。'),
+ category: z.enum(CATEGORY_ENUM).optional().describe('工具类目。不传时返回所有类目概览。'),
},
async ({ category }) => {
if (category) {
@@ -316,9 +302,7 @@ function registerListToolsEntry(
description: t.description,
...(t.rules && t.rules.length > 0 ? { rules: t.rules } : {}),
})),
- ...(Object.keys(bundledRules).length > 0
- ? { rules: bundledRules }
- : {}),
+ ...(Object.keys(bundledRules).length > 0 ? { rules: bundledRules } : {}),
hint: '调用具体工具用 call_tool({name, args})。每个 tool 的 rules 数组列出它必须遵守的共享规则键,完整规则在顶层 rules 字段。',
}),
},
@@ -357,9 +341,7 @@ function registerCallToolEntry(
'call_tool',
d.call_tool,
{
- name: z
- .string()
- .describe('工具名,从 list_tools 获取(如 send_file_to_user)'),
+ name: z.string().describe('工具名,从 list_tools 获取(如 send_file_to_user)'),
args: jsonObjectArg('工具参数(JSON 对象)。不确定 schema 时可先传 {} 触发错误反馈。'),
},
async ({ name, args }) => registry.call(name, args),
diff --git a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/call_tool.md b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/call_tool.md
index 4b7f8f68de..fc2ca03bf4 100644
--- a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/call_tool.md
+++ b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/call_tool.md
@@ -1 +1 @@
-调用一个具体的 cindy_feishu_bot 工具(参数会经过 zod 校验)。先用 list_tools 获取工具名;参数错误时会返回该工具的 JSON Schema 用于自我修正。常见 errorCode: UNKNOWN_TOOL / INVALID_ARGS / NO_CHAT_CONTEXT(当前不是飞书 bot session 上下文,工具不可用) / FILE_NOT_FOUND / FILE_EMPTY / FILE_TOO_LARGE / UPLOAD_FAILED / SEND_FAILED。
+调用一个具体的 cindy_feishu_bot 工具(参数会经过 zod 校验)。先用 list_tools 获取工具名;参数错误时会返回该工具的 JSON Schema 用于自我修正。常见 errorCode: UNKNOWN_TOOL / INVALID_ARGS / NO_CHAT_CONTEXT(当前没有飞书 / Lark bot session,且 bot 也未绑定 owner,工具不可用) / FILE_NOT_FOUND / FILE_EMPTY / FILE_TOO_LARGE / UPLOAD_FAILED / SEND_FAILED。
diff --git a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/list_tools.md b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/list_tools.md
index f71f365cdd..14943df43e 100644
--- a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/list_tools.md
+++ b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/list_tools.md
@@ -1 +1 @@
-探索 cindy_feishu_bot 可用工具(渐进式发现入口)。不传 category → 返回所有类目+每个类目工具数量。传 category → 返回该类目下所有工具的名称和简介,以及该类目下涉及的共享规则(rules 字段,markdown 内容,只在第一次拉取该类目时读一遍即可)。类目: bot(把消息/文件/图片直接推给当前飞书用户)。获取工具名后用 call_tool({name, args}) 执行;参数错误会返回完整 JSON Schema。
+探索 cindy_feishu_bot 可用工具(渐进式发现入口)。不传 category → 返回所有类目+每个类目工具数量。传 category → 返回该类目下所有工具的名称和简介,以及该类目下涉及的共享规则(rules 字段,markdown 内容,只在第一次拉取该类目时读一遍即可)。类目: bot(把消息/文件/图片直接推给当前飞书或 Lark 用户)。获取工具名后用 call_tool({name, args}) 执行;参数错误会返回完整 JSON Schema。
diff --git a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_file_to_user.md b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_file_to_user.md
index 08bc7e7856..e29051527d 100644
--- a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_file_to_user.md
+++ b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_file_to_user.md
@@ -1,26 +1,30 @@
-通过飞书 bot 把本地文件推送给当前用户(bot 归属人)。chatId 由 session 上下文自动注入,**不要也不能**作为参数传 —— 你只关心"发什么"。
+通过已配置的飞书 / Lark bot 把本地文件推送给当前用户(bot 归属人)。chatId 由 session 上下文自动注入,**不要也不能**作为参数传 —— 你只关心"发什么"。
-**接收人语义**(与 send_message_to_user 一致):优先发到当前 session 归属的飞书聊天(在飞书里私聊 bot 触发的 session);若当前不是飞书 session(桌面端 chat 里 agent 被要求"把这个截图 / 报告发飞书给我"),自动回落到 bot 首次被私聊时 TOFU 记录的 owner。两条路径最终都发到你在飞书里私聊 bot 的对话里,不会跑到其他任何人。
+**接收人语义**(与 send_message_to_user 一致):优先发到当前 session 归属的 IM 聊天(在飞书或 Lark 里私聊 bot 触发的 session);若当前不是该 IM session(桌面端 chat 里 agent 被要求"把这个截图 / 报告发飞书或 Lark 给我"),自动回落到 bot 首次被私聊时 TOFU 记录的 owner。两条路径最终都发到用户私聊 bot 的对话里,不会跑到其他任何人。
用途:
-- **跨 session 文件推送**:用户在桌面端说"把这份文档 / 这张图发飞书给我" —— 用这个,文件立刻出现在飞书 DM。
-- **飞书 session 内直接发送**:用户让你"出张图发我看看"、"把日志文件传过来" —— 任何需要把磁盘上的文件本体送到用户手机/PC 飞书客户端的场景。
-- **不要**用这个工具发卡片正文里的内联说明,正文用流式输出就好;这个工具是发独立的 file/image 消息(用户在飞书会看到"📎 文件名"或图片预览,可以直接下载/转发)。
-- 用户没明确说"发飞书给我"或类似意图时,不要自作主张主动推送文件到用户飞书。
+
+- **跨 session 文件推送**:用户在桌面端说"把这份文档 / 这张图发飞书或 Lark 给我" —— 用这个,文件立刻出现在对应 IM 的 DM。
+- **IM session 内直接发送**:用户让你"出张图发我看看"、"把日志文件传过来" —— 任何需要把磁盘上的文件本体送到用户手机/PC 客户端的场景。
+- **不要**用这个工具发卡片正文里的内联说明,正文用流式输出就好;这个工具是发独立的 file/image 消息(用户会看到"📎 文件名"或图片预览,可以直接下载/转发)。
+- 用户没明确说"发飞书 / Lark 给我"或类似意图时,不要自作主张主动推送文件。
参数:
+
- `absPath` (必填):本地绝对路径。Windows 用正斜杠或反斜杠都行;Unix 用 `/...`。
- `displayName` (可选):发送给用户看到的文件名,默认用 `path.basename(absPath)`。
行为:
+
- 图片(`.png .jpg .jpeg .gif .webp .bmp`)且 ≤ 10MB → 自动以 `msg_type:'image'` 发出,用户在聊天里直接预览,无需下载。
-- 其他文件或超过图片上限的图 → 以 `msg_type:'file'` 发出,飞书会显示文件名+下载按钮。
-- 单文件硬上限 30MB(飞书侧限制),超出返回 `FILE_TOO_LARGE`,改 `errorCode` 让你知道是规格问题不是网络问题。
+- 其他文件或超过图片上限的图 → 以 `msg_type:'file'` 发出,客户端会显示文件名+下载按钮。
+- 单文件硬上限 30MB(平台侧限制),超出返回 `FILE_TOO_LARGE`,改 `errorCode` 让你知道是规格问题不是网络问题。
错误码:
-- `NO_CHAT_CONTEXT` —— 既不在飞书 session,bot 又没有绑定过 owner(用户从未私聊过 bot)。告诉用户先在飞书里私聊自己配置的那个机器人一次完成绑定,再重试。不要自己重试。
+
+- `NO_CHAT_CONTEXT` —— 既不在飞书 / Lark session,bot 又没有绑定过 owner(用户从未私聊过 bot)。告诉用户先在已配置的 IM 服务里私聊机器人一次完成绑定,再重试。不要自己重试。
- `FILE_NOT_FOUND` —— absPath 不存在,检查路径
-- `FILE_EMPTY` —— 0 字节文件,飞书拒收
+- `FILE_EMPTY` —— 0 字节文件,平台拒收
- `FILE_TOO_LARGE` —— 超过 30MB
- `UPLOAD_FAILED` / `SEND_FAILED` —— 网络/权限/SDK 错误,返回 raw 错误信息
diff --git a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_message_to_user.md b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_message_to_user.md
index 38ddfe8772..6c78c41bda 100644
--- a/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_message_to_user.md
+++ b/packages/lizi-mcps/src/prompts/cindy_feishu_bot/tools/send_message_to_user.md
@@ -1,28 +1,33 @@
-通过飞书 bot 给当前用户(bot 归属人)发一条 markdown 消息。chatId 由 session 上下文自动注入,**不要也不能**作为参数传 —— 你只关心"发什么"。
+通过已配置的飞书 / Lark bot 给当前用户(bot 归属人)发一条 markdown 消息。chatId 由 session 上下文自动注入,**不要也不能**作为参数传 —— 你只关心"发什么"。
-**接收人语义**:优先发到当前 session 归属的飞书聊天(在飞书里私聊 bot 触发的 session);若当前不是飞书 session(例如桌面端 chat 里 agent 被要求跑长任务并通过飞书通知用户),自动回落到 bot 首次被私聊时 TOFU 记录的 owner —— 也就是"这台机器上登录使用 bot 的那个人"。两条路径最终都发到你在飞书里私聊 bot 的对话里,不会跑到其他任何人。
+**接收人语义**:优先发到当前 session 归属的 IM 聊天(在飞书或 Lark 里私聊 bot 触发的 session);若当前不是该 IM session(例如桌面端 chat 里 agent 被要求跑长任务并通过飞书或 Lark 通知用户),自动回落到 bot 首次被私聊时 TOFU 记录的 owner —— 也就是"这台机器上登录使用 bot 的那个人"。两条路径最终都发到用户私聊 bot 的对话里,不会跑到其他任何人。
用途:
-- **跨 session 通知**:用户在桌面端说"跑完之后通过飞书通知我" —— 用这个,收尾时发一条汇总到飞书 DM。
+
+- **跨 session 通知**:用户在桌面端说"跑完之后通过飞书或 Lark 通知我" —— 用这个,收尾时发一条汇总到对应 IM 的 DM。
- **长任务进度汇报**:关键节点给用户"喘口气"式提示("已经跑完 3/10 步,估计还有 5 分钟")。
- **中间结果推送**:重要链接 / 检查项 / 阶段性产出,不必等最终一次性 dump。
**不适合的场景**:
-- 在**飞书 session** 里发最终回复不用这个工具 —— agent 收尾会话走原生流式通道自动回到飞书,再用这个工具发一遍等于让用户收两条几乎一样的消息。
+
+- 在**飞书 / Lark session** 里发最终回复不用这个工具 —— agent 收尾会话走原生流式通道自动回到当前 IM,再用这个工具发一遍等于让用户收两条几乎一样的消息。
- 短确认(比如"收到"、"好的")—— 没意义的噪音,不发就是不发。
- 不要用它做 UI 交互(问用户选择、确认)—— 那个走另外的通路。
- 用户没明确说"通知我"或类似意图时,不要自作主张主动发消息骚扰用户。
参数:
-- `text` (必填):markdown 正文。飞书 lark_md 语法支持 `**bold**` / `_italic_` / `` `code` `` / 链接 / 有序 / 无序列表 / `>` 引用 / `#` 标题。URL 直接写飞书会自动识别成链接。长度硬上限 30000 字符,超出时 schema 校验失败返回 `INVALID_ARGS`(含 `validation_errors`)。空字符串或纯空白返回 `EMPTY_TEXT`。
+
+- `text` (必填):markdown 正文。飞书 / Lark lark_md 语法支持 `**bold**` / `_italic_` / `` `code` `` / 链接 / 有序 / 无序列表 / `>` 引用 / `#` 标题。URL 会自动识别成链接。长度硬上限 30000 字符,超出时 schema 校验失败返回 `INVALID_ARGS`(含 `validation_errors`)。空字符串或纯空白返回 `EMPTY_TEXT`。
行为:
+
- 一次性发送,不流式(想流式请等最终 assistant 回复走原生通道)。
-- 底层走 feishu `im.v1.messages.create` 的 `interactive` 卡片消息,一张 body-only 极简卡片,视觉上跟纯文本消息接近但 markdown 会渲染。
+- 底层走 OpenAPI `im.v1.messages.create` 的 `interactive` 卡片消息,一张 body-only 极简卡片,视觉上跟纯文本消息接近但 markdown 会渲染。
- 发送成功返回 `{ ok: true, messageId }`,`messageId` 可用于后续引用(目前无 reply-to 工具,预留)。
错误码:
-- `NO_CHAT_CONTEXT` —— 既不在飞书 session,bot 又没有绑定过 owner(用户从未私聊过 bot)。**告诉用户**:"我目前无法通过飞书通知你,请先在飞书里私聊你配置的那个机器人发一条消息完成绑定,之后再让我重试。" 不要自己重试。
+
+- `NO_CHAT_CONTEXT` —— 既不在飞书 / Lark session,bot 又没有绑定过 owner(用户从未私聊过 bot)。**告诉用户**:"我目前无法通过飞书或 Lark 通知你,请先在已配置的 IM 服务里私聊机器人发一条消息完成绑定,之后再让我重试。" 不要自己重试。
- `EMPTY_TEXT` —— text 为空或纯空白,不发
- `INVALID_ARGS` —— schema 校验失败(含 `validation_errors`);最常见原因是 text 超过 30000 字符,截断后重试
- `SEND_FAILED` —— 网络 / 权限 / SDK 错误,返回 raw 错误信息;可视具体错误决定是否重试(rate-limit 类等一秒再试;auth 类不要重试)
diff --git a/packages/wechat-ilink/src/transport.ts b/packages/wechat-ilink/src/transport.ts
index f5dcaf2337..356f168afd 100644
--- a/packages/wechat-ilink/src/transport.ts
+++ b/packages/wechat-ilink/src/transport.ts
@@ -231,9 +231,8 @@ export class TencentIlinkTransport implements WechatTransport {
ref: {
kind: request.kind,
encryptedQuery,
- // iLink's sendmessage media.aes_key uses base64(hex-text), matching
- // the official WorkBuddy client. The upload request above still uses
- // the raw AES key as a hex string.
+ // iLink's sendmessage media.aes_key uses base64(hex-text), while the
+ // upload request above still uses the raw AES key as a hex string.
aesKeyBase64: Buffer.from(prepared.aesKeyHex).toString("base64"),
byteLength: request.bytes.byteLength,
encryptedByteLength: prepared.ciphertext.byteLength,