Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(lark): address review findings and improve setup UX

cyh2848538108b6
diff --git a/.worktrees/vibe/feature/slack-i18n b/.worktrees/vibe/feature/slack-i18n
new file mode 160000
index 000000000..ee193f59c
--- /dev/null
+++ b/.worktrees/vibe/feature/slack-i18n
@@ -0,0 +1 @@
+Subproject commit ee193f59c6a70d49da948a11d14da96b408da120
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index a027471a5..ce1337237 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -76,6 +76,8 @@ class FeishuBot(BaseIMClient):
self._stop_event: Optional[asyncio.Event] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._recent_event_ids: Dict[str, float] = {}
+ self._cached_token: Optional[str] = None
+ self._token_expires_at: Optional[float] = None
# ------------------------------------------------------------------
# Lifecycle / injection
@@ -133,17 +135,24 @@ class FeishuBot(BaseIMClient):
)
async def _get_tenant_token(self) -> Optional[str]:
- """Get tenant access token for raw HTTP calls."""
+ """Get tenant access token for raw HTTP calls (non-blocking)."""
+ # Return cached token if still valid (expires after ~2h, refresh at 1h50m)
+ if self._cached_token and self._token_expires_at and time.time() < self._token_expires_at:
+ return self._cached_token
try:
- import urllib.request
-
url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
- data = json.dumps({"app_id": self.config.app_id, "app_secret": self.config.app_secret}).encode()
- req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
- with urllib.request.urlopen(req, timeout=10) as resp:
- result = json.loads(resp.read().decode())
- if result.get("code") == 0:
- return result.get("tenant_access_token")
+ payload = json.dumps({"app_id": self.config.app_id, "app_secret": self.config.app_secret})
+ timeout = aiohttp.ClientTimeout(total=10)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.post(url, data=payload, headers={"Content-Type": "application/json"}) as resp:
+ result = await resp.json()
+ if result.get("code") == 0:
+ token = result.get("tenant_access_token")
+ expire = result.get("expire", 7200)
+ self._cached_token = token
+ # Refresh 10 minutes before expiry
+ self._token_expires_at = time.time() + max(expire - 600, 60)
+ return token
except Exception as exc:
logger.error("Failed to get tenant_access_token: %s", exc)
return None
@@ -155,15 +164,14 @@ class FeishuBot(BaseIMClient):
if not token:
return
url = "https://open.feishu.cn/open-apis/bot/v3/info"
- req_obj = __import__("urllib.request", fromlist=["Request"]).Request(
- url, headers={"Authorization": f"Bearer {token}"}
- )
- with __import__("urllib.request", fromlist=["urlopen"]).urlopen(req_obj, timeout=10) as resp:
- result = json.loads(resp.read().decode())
- if result.get("code") == 0:
- bot = result.get("bot", {})
- self._bot_open_id = bot.get("open_id")
- logger.info("Feishu bot info: open_id=%s", self._bot_open_id)
+ timeout = aiohttp.ClientTimeout(total=10)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.get(url, headers={"Authorization": f"Bearer {token}"}) as resp:
+ result = await resp.json()
+ if result.get("code") == 0:
+ bot = result.get("bot", {})
+ self._bot_open_id = bot.get("open_id")
+ logger.info("Feishu bot info: open_id=%s", self._bot_open_id)
except Exception as exc:
logger.warning("Failed to fetch bot info: %s", exc)
@@ -246,7 +254,10 @@ class FeishuBot(BaseIMClient):
# If replying in thread, use reply API
if root_id:
- return await self._reply_message(root_id, text)
+ message_id = await self._reply_message(root_id, text)
+ if self.settings_manager:
+ self.settings_manager.mark_thread_active(context.user_id, context.channel_id, root_id)
+ return message_id
response = await self._lark_client.im.v1.message.acreate(request)
if not response.success():
@@ -346,7 +357,10 @@ class FeishuBot(BaseIMClient):
# Thread reply
root_id = context.thread_id
if root_id:
- return await self._reply_message_with_card(root_id, card_json)
+ message_id = await self._reply_message_with_card(root_id, card_json)
+ if self.settings_manager:
+ self.settings_manager.mark_thread_active(context.user_id, context.channel_id, root_id)
+ return message_id
request = (
CreateMessageRequest.builder()
@@ -696,23 +710,32 @@ class FeishuBot(BaseIMClient):
if msg_type == "file":
file_key = msg_content.get("file_key", "")
file_name = msg_content.get("file_name", "unknown")
+ url = (
+ f"https://open.feishu.cn/open-apis/im/v1/messages/{message_id}/resources/{file_key}?type=file"
+ if message_id and file_key
+ else None
+ )
attachments.append(
FileAttachment(
name=file_name,
mimetype="application/octet-stream",
- url=None,
+ url=url,
size=msg_content.get("file_size"),
)
)
- # Store download info in platform_specific later
elif msg_type == "image":
image_key = msg_content.get("image_key", "")
+ url = (
+ f"https://open.feishu.cn/open-apis/im/v1/messages/{message_id}/resources/{image_key}?type=image"
+ if message_id and image_key
+ else None
+ )
attachments.append(
FileAttachment(
name=f"{image_key}.png",
mimetype="image/png",
- url=None,
+ url=url,
size=None,
)
)
@@ -720,11 +743,16 @@ class FeishuBot(BaseIMClient):
elif msg_type == "media":
file_key = msg_content.get("file_key", "")
file_name = msg_content.get("file_name", "unknown")
+ url = (
+ f"https://open.feishu.cn/open-apis/im/v1/messages/{message_id}/resources/{file_key}?type=file"
+ if message_id and file_key
+ else None
+ )
attachments.append(
FileAttachment(
name=file_name,
mimetype=msg_content.get("mime_type", "application/octet-stream"),
- url=None,
+ url=url,
size=None,
)
)
@@ -882,7 +910,9 @@ class FeishuBot(BaseIMClient):
if not user_id:
return
- # Require-mention logic
+ # Require-mention logic (bypass for p2p/DM chats)
+ chat_type = message.get("chat_type", "")
+ is_p2p = chat_type == "p2p"
is_thread_reply = bool(root_id)
effective_require_mention = self.config.require_mention
if self.settings_manager:
@@ -890,7 +920,7 @@ class FeishuBot(BaseIMClient):
chat_id, global_default=self.config.require_mention
)
- if effective_require_mention:
+ if effective_require_mention and not is_p2p:
if not is_thread_reply:
if not bot_mentioned:
logger.debug("Ignoring non-mention message in channel")
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 8ce92d06a..aae52c4a6 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -93,7 +93,11 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const platform = config.platform || data.platform || 'slack';
const botToken = platform === 'discord'
? (config.discord?.bot_token || data.discord?.bot_token || '')
- : (config.slack?.bot_token || config.slackBotToken || '');
+ : platform === 'lark'
+ ? '' // Lark uses app_id + app_secret, not bot_token
+ : (config.slack?.bot_token || config.slackBotToken || '');
+ const larkAppId = config.lark?.app_id || data.lark?.app_id || '';
+ const larkAppSecret = config.lark?.app_secret || data.lark?.app_secret || '';
useEffect(() => {
if (platform !== 'discord') return;
@@ -117,7 +121,11 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
};
const loadChannels = async (all?: boolean) => {
- if (!botToken) return;
+ if (platform === 'lark') {
+ if (!larkAppId || !larkAppSecret) return;
+ } else if (!botToken) {
+ return;
+ }
const isAll = all ?? browseAll;
if (isAll) {
setLoadingAll(true);
@@ -125,7 +133,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
setLoading(true);
}
try {
- if (platform === 'discord') {
+ if (platform === 'lark') {
+ const result = await api.larkChats(larkAppId, larkAppSecret);
+ if (result.ok) {
+ setChannels(result.channels || []);
+ }
+ } else if (platform === 'discord') {
if (!selectedGuild) {
setLoading(false);
return;
@@ -195,6 +208,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
};
useEffect(() => {
+ if (platform === 'lark') {
+ if (larkAppId && larkAppSecret) {
+ loadChannels();
+ }
+ return;
+ }
if (!botToken) return;
if (platform === 'discord') {
loadGuilds();
@@ -204,7 +223,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
} else {
loadChannels();
}
- }, [botToken, platform, selectedGuild]);
+ }, [botToken, platform, selectedGuild, larkAppId, larkAppSecret]);
useEffect(() => {
if (config.agents?.claude?.enabled) {
@@ -355,7 +374,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
>
<RefreshCw size={14} className={loading ? 'animate-spin' : ''} /> {t('channelList.refreshList')}
</button>
- {!browseAll && (
+ {!browseAll && platform !== 'lark' && (
<button
onClick={() => loadChannels(true)}
disabled={loadingAll}
@@ -374,7 +393,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{t('channelList.cantFindChannel')}
</span>
<span className="absolute bottom-full left-0 mb-2 px-3 py-2 bg-text text-bg text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 w-64 whitespace-normal">
- {platform === 'discord' ? t('channelList.discordInviteBotHint') : t('channelList.inviteBotHint')}
+ {platform === 'discord' ? t('channelList.discordInviteBotHint') : platform === 'lark' ? t('channelList.larkInviteBotHint') : t('channelList.inviteBotHint')}
</span>
</span>
{channels.length === 0 && !loading && (
@@ -407,7 +426,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</div>
<div className="flex-1 overflow-y-auto border border-border rounded-xl divide-y divide-border bg-panel shadow-sm">
- {!loading && channels.length === 0 && !botToken && (
+ {!loading && channels.length === 0 && !botToken && platform !== 'lark' && (
<div className="p-8 text-center text-muted">
{t('channelList.addTokenFirst')}
</div>
@@ -510,7 +529,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<option value="">
{t('common.default')} ({platform === 'discord'
? (config.discord?.require_mention ? t('common.enabled') : t('common.disabled'))
- : (config.slack?.require_mention ? t('common.enabled') : t('common.disabled'))})
+ : platform === 'lark'
+ ? (config.lark?.require_mention ? t('common.enabled') : t('common.disabled'))
+ : (config.slack?.require_mention ? t('common.enabled') : t('common.disabled'))})
</option>
<option value="true">{t('channelList.requireMentionOn')}</option>
<option value="false">{t('channelList.requireMentionOff')}</option>
diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsx
index a70fcedc5..59c2ad750 100644
--- a/ui/src/components/steps/LarkConfig.tsx
+++ b/ui/src/components/steps/LarkConfig.tsx
@@ -1,9 +1,26 @@
import React, { useEffect, useMemo, useState } from 'react';
-import { Shield, RefreshCw, Check, MessageSquare, KeyRound, Plus, ExternalLink, ChevronDown, ChevronUp, Send, BookOpen } from 'lucide-react';
+import { Shield, RefreshCw, Check, MessageSquare, KeyRound, Plus, ExternalLink, ChevronDown, ChevronUp, Send, BookOpen, Copy, AlertTriangle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
+const LARK_PERMISSIONS_JSON = `{
+ "scopes": {
+ "tenant": [
+ "contact:user.base:readonly",
+ "im:chat",
+ "im:message",
+ "im:message.group_at_msg:readonly",
+ "im:message.p2p_msg:readonly",
+ "im:message.reactions:read",
+ "im:message.reactions:write_only",
+ "im:message:send_as_bot",
+ "im:resource"
+ ],
+ "user": []
+ }
+}`;
+
interface LarkConfigProps {
data: any;
onNext: (data: any) => void;
@@ -18,8 +35,8 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
const [checking, setChecking] = useState(false);
const [authResult, setAuthResult] = useState<any>(null);
const [chats, setChats] = useState<any[]>([]);
- const [selectedChat, setSelectedChat] = useState<string>(data.lark?.chat_id || '');
const [expandedSteps, setExpandedSteps] = useState<Record<number, boolean>>({ 1: true, 2: false, 3: false, 4: false, 5: false });
+ const [copiedJson, setCopiedJson] = useState(false);
useEffect(() => {
setAuthResult(null);
@@ -50,7 +67,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
try {
const result = await api.larkChats(appId, appSecret);
if (result.ok) {
- setChats(result.chats || []);
+ setChats(result.channels || []);
}
} catch {
// ignore
@@ -71,6 +88,16 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
window.open('https://open.feishu.cn/app', '_blank');
};
+ const copyPermissionsJson = async () => {
+ try {
+ await navigator.clipboard.writeText(LARK_PERMISSIONS_JSON);
+ setCopiedJson(true);
+ setTimeout(() => setCopiedJson(false), 2000);
+ } catch {
+ // fallback
+ }
+ };
+
const StepHeader: React.FC<{ step: number; title: string; icon: React.ReactNode; completed?: boolean }> = ({
step,
title,
@@ -145,40 +172,60 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
{expandedSteps[2] && (
<div className="p-4 space-y-4 border-t border-border">
<p className="text-sm text-muted">{t('larkConfig.step2Description')}</p>
- <ul className="space-y-1.5 text-sm text-muted pl-1">
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">1</code>
- {t('larkConfig.step2Item1')}
- </li>
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">2</code>
- {t('larkConfig.step2Item2')}
- </li>
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">3</code>
- {t('larkConfig.step2Item3')}
- </li>
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">4</code>
- {t('larkConfig.step2Item4')}
- </li>
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">5</code>
- {t('larkConfig.step2Item5')}
- </li>
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">6</code>
- {t('larkConfig.step2Item6')}
- </li>
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">7</code>
- {t('larkConfig.step2Item7')}
- </li>
- <li className="flex items-start gap-2">
- <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">8</code>
- {t('larkConfig.step2Item8')}
- </li>
- </ul>
+
+ {/* Batch import JSON */}
+ <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-blue-800">{t('larkConfig.step2BatchImport')}</span>
+ <button
+ onClick={copyPermissionsJson}
+ className="flex items-center gap-1.5 px-3 py-1 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded text-xs font-medium transition-colors"
+ >
+ {copiedJson ? <Check size={12} /> : <Copy size={12} />}
+ {copiedJson ? t('larkConfig.step2Copied') : t('larkConfig.step2CopyJson')}
+ </button>
+ </div>
+ <pre className="text-xs bg-white/70 rounded p-2 overflow-x-auto font-mono text-blue-900 whitespace-pre">{LARK_PERMISSIONS_JSON}</pre>
+ <p className="text-xs text-blue-700">{t('larkConfig.step2BatchImportHint')}</p>
+ </div>
+
+ <details className="text-sm text-muted">
+ <summary className="cursor-pointer font-medium text-text hover:text-accent transition-colors">{t('larkConfig.step2ManualList')}</summary>
+ <ul className="space-y-1.5 mt-2 pl-1">
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">1</code>
+ {t('larkConfig.step2Item1')}
+ </li>
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">2</code>
+ {t('larkConfig.step2Item2')}
+ </li>
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">3</code>
+ {t('larkConfig.step2Item3')}
+ </li>
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">4</code>
+ {t('larkConfig.step2Item4')}
+ </li>
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">5</code>
+ {t('larkConfig.step2Item5')}
+ </li>
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">6</code>
+ {t('larkConfig.step2Item6')}
+ </li>
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">7</code>
+ {t('larkConfig.step2Item7')}
+ </li>
+ <li className="flex items-start gap-2">
+ <code className="text-xs bg-neutral-100 px-1.5 py-0.5 rounded font-mono shrink-0">8</code>
+ {t('larkConfig.step2Item8')}
+ </li>
+ </ul>
+ </details>
</div>
)}
</div>
@@ -201,6 +248,14 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
<div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-800">
<strong>{t('slackConfig.important')}:</strong> {t('larkConfig.step3Tip')}
</div>
+ {/* Long connection FAQ */}
+ <div className="bg-neutral-50 border border-neutral-200 rounded-lg p-3 space-y-1.5">
+ <div className="flex items-center gap-2 text-sm font-medium text-text">
+ <AlertTriangle size={14} className="text-amber-500" />
+ {t('larkConfig.step3LongConnFaqTitle')}
+ </div>
+ <p className="text-xs text-muted">{t('larkConfig.step3LongConnFaqDesc')}</p>
+ </div>
</div>
)}
</div>
@@ -240,7 +295,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
<KeyRound size={16} className="text-accent" /> {t('larkConfig.appId')}
</label>
<input
- type="password"
+ type="text"
value={appId}
onChange={(e) => setAppId(e.target.value)}
placeholder={t('larkConfig.appIdPlaceholder')}
@@ -294,18 +349,20 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack })
{authResult?.ok && chats.length > 0 && (
<div className="space-y-2">
<label className="text-sm font-medium text-text flex items-center gap-2">
- <MessageSquare size={16} className="text-accent" /> {t('channelList.title')}
+ <MessageSquare size={16} className="text-accent" /> {t('larkConfig.chatListLabel')}
</label>
- <select
- value={selectedChat}
- onChange={(e) => setSelectedChat(e.target.value)}
- className="w-full bg-bg border border-border rounded-lg p-3 text-text focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent"
- >
- <option value="">{t('channelList.noChannelsLoaded')}</option>
- {chats.map((c: any) => (
- <option key={c.chat_id} value={c.chat_id}>{c.name}</option>
- ))}
- </select>
+ <p className="text-xs text-muted">{t('larkConfig.chatListHint')}</p>
+ <div className="bg-bg border border-border rounded-lg p-3 max-h-32 overflow-y-auto">
+ <ul className="space-y-1 text-sm text-text">
+ {chats.map((c: any) => (
+ <li key={c.id} className="flex items-center gap-2">
+ <Check size={12} className="text-success shrink-0" />
+ <span>{c.name}</span>
+ <span className="text-xs text-muted font-mono">({c.id})</span>
+ </li>
+ ))}
+ </ul>
+ </div>
</div>
)}
</div>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 8f5ce1c49..412176788 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -161,7 +161,16 @@
"appSecretHint": "Click to reveal and copy from Feishu Open Platform",
"validateCredentials": "Validate Credentials",
"credentialsValidated": "Credentials validated",
- "authFailed": "Validation failed"
+ "authFailed": "Validation failed",
+ "step2BatchImport": "Quick setup: Copy JSON and use \"Batch Import/Export Permissions\"",
+ "step2CopyJson": "Copy JSON",
+ "step2Copied": "Copied!",
+ "step2BatchImportHint": "In Permission Management, click \"Batch Import/Export Permissions\", paste this JSON, and confirm.",
+ "step2ManualList": "Or manually enable permissions one by one",
+ "step3LongConnFaqTitle": "Can't find \"Use Long Connection\"?",
+ "step3LongConnFaqDesc": "If you only see \"Send events to developer server\", your app may not have the Bot capability enabled. Go back to Step 1, enter your app → Add Capabilities → enable \"Bot\". After saving, return to Events & Callbacks and the \"Use Long Connection\" option will appear.",
+ "chatListLabel": "Bot's Chat Groups",
+ "chatListHint": "These are the groups the bot has joined. You can enable specific channels in the next step."
},
"slackConfig": {
"title": "Slack Configuration",
@@ -234,6 +243,7 @@
"cantFindChannel": "Can't find your channel?",
"inviteBotHint": "Invite the bot to your channel first:\n1. Open the channel, click ⚙️ Settings → Integrations → Add apps\n2. Or type /invite @YourBotName in the channel",
"discordInviteBotHint": "Add the bot to your guild and grant access to the channel.",
+ "larkInviteBotHint": "Add the bot to a group chat: Open the group → Settings → Bots → Add Bot.",
"guild": "Guild",
"guildPlaceholder": "Select a guild",
"discordText": "Text",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 63e96685b..c353fa372 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -161,7 +161,16 @@
"appSecretHint": "在飞书开放平台点击显示并复制",
"validateCredentials": "验证凭证",
"credentialsValidated": "凭证验证通过",
- "authFailed": "验证失败"
+ "authFailed": "验证失败",
+ "step2BatchImport": "快捷配置:复制 JSON 后使用「批量导入/导出权限」",
+ "step2CopyJson": "复制 JSON",
+ "step2Copied": "已复制!",
+ "step2BatchImportHint": "在权限管理页面,点击「批量导入/导出权限」,粘贴此 JSON 并确认即可。",
+ "step2ManualList": "或逐个手动开通权限",
+ "step3LongConnFaqTitle": "找不到「使用长连接接收事件」?",
+ "step3LongConnFaqDesc": "如果只看到「将事件发送至开发者服务器」,说明应用尚未开启机器人能力。请回到第 1 步,进入应用 → 添加应用能力 → 开启「机器人」。保存后再回到「事件与回调」页面,就会出现「使用长连接接收事件」选项。",
+ "chatListLabel": "机器人所在群组",
+ "chatListHint": "以下是机器人已加入的群组,你可以在下一步选择启用哪些频道。"
},
"slackConfig": {
"title": "Slack 配置",
@@ -234,6 +243,7 @@
"cantFindChannel": "找不到你想要的频道?",
"inviteBotHint": "请先将 Bot 邀请到频道:\n1. 打开频道,点击 ⚙️ 设置 → 集成 → 添加应用\n2. 或在频道中输入 /invite @你的Bot名称",
"discordInviteBotHint": "请确保机器人已加入服务器并具备访问频道的权限。",
+ "larkInviteBotHint": "将机器人添加到群聊:打开群 → 设置 → 群机器人 → 添加机器人。",
"guild": "服务器",
"guildPlaceholder": "选择服务器",
"discordText": "文本",
diff --git a/vibe/api.py b/vibe/api.py
index b431a3821..9e37d9d02 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -971,52 +971,64 @@ def codex_models() -> dict:
return {"ok": True, "models": uniq}
-def lark_auth_test(app_id: str, app_secret: str) -> dict:
- """Test Lark/Feishu app credentials by fetching tenant_access_token."""
+def _lark_tenant_token(app_id: str, app_secret: str) -> Optional[str]:
+ """Get Lark tenant access token (internal helper, not exposed to frontend)."""
import urllib.request
+ url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
+ data = json.dumps({"app_id": app_id, "app_secret": app_secret}).encode()
+ req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ result = json.loads(resp.read().decode())
+ if result.get("code") == 0:
+ return result.get("tenant_access_token")
+ return None
+
+
+def lark_auth_test(app_id: str, app_secret: str) -> dict:
+ """Test Lark/Feishu app credentials. Only returns ok/error, never exposes token."""
try:
- url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
- data = json.dumps({"app_id": app_id, "app_secret": app_secret}).encode()
- req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
- with urllib.request.urlopen(req, timeout=10) as resp:
- result = json.loads(resp.read().decode())
- if result.get("code") == 0:
- return {"ok": True, "response": result}
- return {"ok": False, "error": result.get("msg", "Unknown error")}
+ token = _lark_tenant_token(app_id, app_secret)
+ if not token:
+ return {"ok": False, "error": "Invalid credentials"}
+ return {"ok": True}
except Exception as exc:
return {"ok": False, "error": str(exc)}
def lark_list_chats(app_id: str, app_secret: str) -> dict:
- """List Lark/Feishu group chats the bot has joined."""
+ """List Lark/Feishu group chats the bot has joined (with pagination)."""
import urllib.request
try:
- # First get token
- token_result = lark_auth_test(app_id, app_secret)
- if not token_result.get("ok"):
- return token_result
- token = token_result["response"].get("tenant_access_token")
+ token = _lark_tenant_token(app_id, app_secret)
if not token:
return {"ok": False, "error": "Failed to get access token"}
- # List chats
- url = "https://open.feishu.cn/open-apis/im/v1/chats?page_size=100"
- req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"})
- with urllib.request.urlopen(req, timeout=10) as resp:
- result = json.loads(resp.read().decode())
- if result.get("code") == 0:
- items = result.get("data", {}).get("items", [])
- channels = [
- {
- "id": c.get("chat_id"),
- "name": c.get("name"),
- "is_private": c.get("chat_type") == "private",
- }
- for c in items
- ]
- return {"ok": True, "channels": channels}
- return {"ok": False, "error": result.get("msg", "Unknown error")}
+ channels = []
+ page_token = ""
+ while True:
+ url = "https://open.feishu.cn/open-apis/im/v1/chats?page_size=100"
+ if page_token:
+ url = f"{url}&page_token={page_token}"
+ req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"})
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ result = json.loads(resp.read().decode())
+ if result.get("code") != 0:
+ return {"ok": False, "error": result.get("msg", "Unknown error")}
+ data = result.get("data", {})
+ items = data.get("items", [])
+ channels.extend(
+ {
+ "id": c.get("chat_id"),
+ "name": c.get("name"),
+ "is_private": c.get("chat_type") == "private",
+ }
+ for c in items
+ )
+ page_token = data.get("page_token") or ""
+ if not data.get("has_more") or not page_token:
+ break
+ return {"ok": True, "channels": channels}
except Exception as exc:
return {"ok": False, "error": str(exc)}