Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

feat(channels): 飞书聊天账号扫码一键添加

dyk9816db133712ad
diff --git a/src/agent/feishu-account.ts b/src/agent/feishu-account.ts
index c7af904..cbbc5b9 100644
--- a/src/agent/feishu-account.ts
+++ b/src/agent/feishu-account.ts
@@ -306,10 +306,25 @@ export class FeishuAccounts {
/** 开始添加:给了 App ID 和 Secret 就用已有的应用,否则一键创建 */
startFlow(app?: { appId: string; appSecret: string; brand?: FeishuBrand }): FeishuFlowView {
+ return this.launch(app ? "authorize" : "create-app", (flow) => this.runFlow(flow, app));
+ }
+
+ /** 飞书聊天账号:只扫码创建应用,不要用户授权(聊天用的是应用身份)。done 把应用连上,回账号的名字 */
+ startAppFlow(done: (app: { appId: string; appSecret: string; brand: FeishuBrand }) => Promise<string>): FeishuFlowView {
+ return this.launch("create-app", async (flow) => {
+ const app = await this.createApp(flow, flow.abort.signal);
+ flow.label = await done(app);
+ flow.url = "";
+ flow.qr = "";
+ flow.state = "done";
+ });
+ }
+
+ private launch(state: FeishuFlowState, run: (flow: Flow) => Promise<void>): FeishuFlowView {
for (const [k, f] of this.flows) if (f.state === "done" || f.state === "failed") this.flows.delete(k);
- const flow: Flow = { id: crypto.randomBytes(12).toString("hex"), state: app ? "authorize" : "create-app", url: "", qr: "", error: "", label: "", abort: new AbortController() };
+ const flow: Flow = { id: crypto.randomBytes(12).toString("hex"), state, url: "", qr: "", error: "", label: "", abort: new AbortController() };
this.flows.set(flow.id, flow);
- this.runFlow(flow, app).catch((e) => {
+ run(flow).catch((e) => {
if (flow.abort.signal.aborted) return;
flow.state = "failed";
flow.error = e instanceof ConnectionError ? e.message : "Feishu didn't complete the authorization. Try again.";
diff --git a/src/app.ts b/src/app.ts
index 71968bd..8946850 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -105,7 +105,7 @@ export function appVersion(): string {
export interface AppOptions {
/** 测试注入:替换飞书传输层 */
- feishuTransport?: (account: { id: string; feishuAppId: string; feishuAppSecret: string }) => FeishuTransport;
+ feishuTransport?: (account: { id: string; feishuAppId: string; feishuAppSecret: string; brand: "feishu" | "lark" }) => FeishuTransport;
/** 测试用:替换 Telegram、Slack、Discord 的传输层 */
messengerTransport?: (id: MessengerId, botId: string, credentials: Record<string, string>) => MessengerTransport;
/** 测试注入:替换 iLink 的 fetch */
@@ -863,7 +863,8 @@ export class App {
const { appId, appSecret } = fsAccount?.credentials ?? {};
if (fsAccount?.enabled && appId && appSecret && !ch.feishu) {
registerSecret(appSecret);
- const transport = this.opts.feishuTransport?.({ id: key, feishuAppId: appId, feishuAppSecret: appSecret }) ?? new LarkTransport(appId, appSecret);
+ const brand = fsAccount.credentials.brand === "lark" ? "lark" : "feishu";
+ const transport = this.opts.feishuTransport?.({ id: key, feishuAppId: appId, feishuAppSecret: appSecret, brand }) ?? new LarkTransport(appId, appSecret, brand);
ch.feishu = new FeishuChannel(key, transport, this.runtime, this.queue, this.config.feishu.throttleMs, this.outbox, this.store);
ch.feishu.delivery = this.delivery;
ch.feishu.route = route("feishu");
@@ -971,12 +972,14 @@ export class App {
}
/** 连接(或改凭据)飞书应用:Secret 留空沿用已保存的;App ID 留空就是移除。换了应用:单聊会话都是新的,连上后第一个发消息的人成为主人 */
- async connectFeishu(key: string, appId: string, appSecret: string): Promise<void> {
+ async connectFeishu(key: string, appId: string, appSecret: string, brand?: "feishu" | "lark"): Promise<void> {
if (!appId) return this.removeFeishu(key);
const cur = this.store.getChannelAccount(key, "feishu");
- if (appId !== cur?.credentials.appId) this.access.resetOwner(key, "feishu");
+ const same = appId === cur?.credentials.appId;
+ if (!same) this.access.resetOwner(key, "feishu");
const base = this.ensureChannelAccount(key, "feishu", t("app.feishu_account_name"));
- this.store.saveChannelAccount({ ...base, credentials: { appId, appSecret: appSecret || cur?.credentials.appSecret || "" } });
+ const lark = (brand ?? (same ? cur?.credentials.brand : undefined)) === "lark";
+ this.store.saveChannelAccount({ ...base, credentials: { appId, appSecret: appSecret || cur?.credentials.appSecret || "", ...(lark ? { brand: "lark" } : {}) } });
await this.stopFeishu(key);
await this.startBot(key);
}
diff --git a/src/web/server.ts b/src/web/server.ts
index 7b40fe0..f123170 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -553,6 +553,14 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
await app.connectFeishu(id, String(b.appId ?? "").trim(), String(b.appSecret ?? "").trim());
return send(res, 200, app.channelStatus(id));
}
+ // 一键添加:扫码创建应用(流程状态在 /connections/flows/:id),连上后账号才出现
+ if (sub === "feishu/one-click" && m === "POST") {
+ const flow = app.connections.feishu.startAppFlow(async (created) => {
+ await app.connectFeishu(id, created.appId, created.appSecret, created.brand);
+ return app.store.getChannelAccount(id, "feishu")?.label ?? "";
+ });
+ return send(res, 200, { flow });
+ }
if (sub === "feishu" && m === "DELETE") {
await app.removeChannelAccount(id, "feishu");
return send(res, 200, app.channelStatus(id));
diff --git a/test/channel-accounts.e2e.test.ts b/test/channel-accounts.e2e.test.ts
index 3fcbd8c..91d7bd6 100644
--- a/test/channel-accounts.e2e.test.ts
+++ b/test/channel-accounts.e2e.test.ts
@@ -19,6 +19,7 @@ let base: string;
/** 账号 key → 假 Telegram(检查凭据和真正连上用的是两个对象,留最后建的) */
const fakes = new Map<string, FakeMessenger>();
let secondBot = "";
+const feishuBrands: string[] = [];
async function api(p: string, init: { method?: string; body?: unknown } = {}) {
const res = await fetch(base + "/amb/api" + p, {
@@ -41,7 +42,10 @@ beforeAll(async () => {
const config = loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_AGENT: "off" } });
app = new App(config, {
printQrToTerminal: false,
- feishuTransport: () => new FakeFeishu(),
+ feishuTransport: (account) => {
+ feishuBrands.push(account.brand);
+ return new FakeFeishu();
+ },
messengerTransport: (id, key) => {
const f = new FakeMessenger(id);
fakes.set(key, f);
@@ -202,6 +206,22 @@ describe("删除机器人", () => {
});
});
+describe("飞书聊天账号", () => {
+ it("连上后账号才出现;Lark 用 Lark 的地址,改 Secret 不丢品牌,换应用才重置", async () => {
+ const key = "acct_lark";
+ await app.connectFeishu(key, "cli_lark", "lark-secret", "lark");
+ expect(app.store.getChannelAccount(key, "feishu")!.credentials).toEqual({ appId: "cli_lark", appSecret: "lark-secret", brand: "lark" });
+ expect(feishuBrands.at(-1)).toBe("lark");
+ await api(`/channel-accounts/${key}/feishu`, { method: "PUT", body: { appId: "cli_lark", appSecret: "new-secret" } });
+ expect(app.store.getChannelAccount(key, "feishu")!.credentials).toEqual({ appId: "cli_lark", appSecret: "new-secret", brand: "lark" });
+ await api(`/channel-accounts/${key}/feishu`, { method: "PUT", body: { appId: "cli_other", appSecret: "s" } });
+ expect(app.store.getChannelAccount(key, "feishu")!.credentials).toEqual({ appId: "cli_other", appSecret: "s" });
+ expect(feishuBrands.at(-1)).toBe("feishu");
+ expect((await api(`/channel-accounts/${key}/feishu`, { method: "DELETE" })).status).toBe(200);
+ expect(await account(key)).toBeUndefined();
+ });
+});
+
describe("升级:老数据变成全局账号", () => {
it("机器人上的飞书、微信、其他平台:key 沿用机器人 id,默认机器人是它自己,名字不撞车", async () => {
const bot = app.store.createBot({ id: "old-bot", name: "WORK", systemPrompt: "", feishuAppId: "cli_old", feishuAppSecret: "old-secret", weixinEnabled: false });
diff --git a/test/connections.unit.test.ts b/test/connections.unit.test.ts
index 101ffad..96c4599 100644
--- a/test/connections.unit.test.ts
+++ b/test/connections.unit.test.ts
@@ -651,6 +651,37 @@ describe("飞书账号:添加流程", () => {
expect((accounts.list("feishu")[0].auth as any).brand).toBe("lark");
});
+ it("聊天账号一键添加:只扫码创建应用,交给回调连上,不做用户授权", async () => {
+ const { feishu, accounts, calls } = flowWith([
+ { json: { device_code: "reg", user_code: "UC", interval: 0.01, expire_in: 60 } },
+ { json: { client_id: "cli_chat", client_secret: "sec_chat", user_info: { open_id: "ou", tenant_brand: "lark" } } },
+ { json: { client_id: "cli_chat", client_secret: "sec_chat", user_info: { open_id: "ou", tenant_brand: "lark" } } },
+ ]);
+ const got: unknown[] = [];
+ const flow = feishu.startAppFlow(async (app) => {
+ got.push(app);
+ return "飞书";
+ });
+ expect(flow.state).toBe("create-app");
+ const done = await settle(feishu, flow.id);
+ expect(done).toMatchObject({ state: "done", label: "飞书", url: "", qr: "" });
+ expect(got).toEqual([{ appId: "cli_chat", appSecret: "sec_chat", brand: "lark" }]);
+ expect(calls.some((c) => c.path.includes("device_authorization"))).toBe(false);
+ // 聊天账号不进数据账号的列表
+ expect(accounts.list()).toEqual([]);
+ });
+
+ it("聊天账号一键添加:回调失败时流程失败", async () => {
+ const { feishu } = flowWith([
+ { json: { device_code: "reg", user_code: "UC", interval: 0.01, expire_in: 60 } },
+ { json: { client_id: "c", client_secret: "s" } },
+ ]);
+ const flow = feishu.startAppFlow(async () => {
+ throw new ConnectionError("Couldn't connect.");
+ });
+ expect((await settle(feishu, flow.id)).error).toBe("Couldn't connect.");
+ });
+
it("取消:流程不再加账号", async () => {
const { feishu, accounts } = flowWith([{ json: { device_code: "d", verification_uri: "https://x", interval: 30, expires_in: 60 } }]);
const { id } = feishu.startFlow({ appId: "a", appSecret: "s" });
diff --git a/ui/locales/en/settings.js b/ui/locales/en/settings.js
index 39f8aff..0f019c6 100644
--- a/ui/locales/en/settings.js
+++ b/ui/locales/en/settings.js
@@ -53,6 +53,7 @@ export default {
feishuTitle: "Add a Feishu account",
feishuAppHint: "The app needs user permissions for reading messages. You'll scan a code to authorize next.",
next: "Next",
+ feishuChatStep: "Scan with Feishu to create your bot app. Then send it a message in Feishu to start chatting.",
feishuStepCreate: "Step 1: scan with Feishu to create your personal app",
feishuStepAuthorize: "Step 2: scan with Feishu to let it read your chats and messages",
qrAlt: "Feishu authorization QR code",
diff --git a/ui/locales/zh-CN/settings.js b/ui/locales/zh-CN/settings.js
index 96368d8..9279319 100644
--- a/ui/locales/zh-CN/settings.js
+++ b/ui/locales/zh-CN/settings.js
@@ -53,6 +53,7 @@ export default {
feishuTitle: "添加飞书账号",
feishuAppHint: "应用要开通读消息的用户权限。填完后再扫码授权。",
next: "下一步",
+ feishuChatStep: "用飞书扫码,创建你的机器人应用。完成后在飞书里给它发条消息就能聊。",
feishuStepCreate: "第 1 步:用飞书扫码,创建你的个人应用",
feishuStepAuthorize: "第 2 步:用飞书扫码,授权读取你的会话和消息",
qrAlt: "飞书授权二维码",
diff --git a/ui/screens/connections.js b/ui/screens/connections.js
index c9997f6..1f730e1 100644
--- a/ui/screens/connections.js
+++ b/ui/screens/connections.js
@@ -207,15 +207,12 @@ function NotionTokenSheet({ conn, onClose }) {
<//>`;
}
-/** 飞书:一键授权要扫两次(创建应用、授权读消息);用已有应用只扫第二次 */
-function FeishuSheet({ conn, mode, onClose }) {
- const [appId, setAppId] = useState("");
- const [appSecret, setAppSecret] = useState("");
+/** 飞书的扫码流程:开始之后轮询状态,完成时回调;关掉就取消 */
+function useFeishuFlow(onDone) {
const [flow, setFlow] = useState(null);
const [error, setError] = useState("");
const live = useRef(null);
const timer = useRef(null);
-
const poll = async () => {
if (!live.current) return;
try {
@@ -223,9 +220,7 @@ function FeishuSheet({ conn, mode, onClose }) {
setFlow(r.flow);
if (r.flow.state === "done") {
live.current = null;
- conn.setAccounts(r.accounts);
- saved();
- onClose();
+ onDone(r);
return;
}
if (r.flow.state === "failed") {
@@ -237,10 +232,11 @@ function FeishuSheet({ conn, mode, onClose }) {
}
timer.current = setTimeout(poll, POLL_MS);
};
- const start = async (body) => {
+ const start = async (path, body) => {
setError("");
+ setFlow(null);
try {
- const r = await api("/connections/feishu", { method: "POST", body });
+ const r = await api(path, { method: "POST", body });
live.current = r.flow.id;
setFlow(r.flow);
timer.current = setTimeout(poll, POLL_MS);
@@ -248,33 +244,73 @@ function FeishuSheet({ conn, mode, onClose }) {
setError(e.message || String(e));
}
};
- useEffect(() => {
- if (mode === "oneclick") start({});
- return () => {
+ useEffect(
+ () => () => {
clearTimeout(timer.current);
if (live.current) api(`/connections/flows/${live.current}`, { method: "DELETE" }).catch(() => {});
- };
- }, []);
+ },
+ [],
+ );
+ return { flow, error: flow && flow.state === "failed" ? flow.error : error, start };
+}
- const failedText = flow && flow.state === "failed" ? flow.error : error;
+/** 流程进行中:二维码、链接、等待 */
+function FlowSteps({ flow, text }) {
+ return html`<p>${text}</p>
+ ${flow.qr && html`<img class="panel-qr" src=${flow.qr} alt=${t("settings.connections.qrAlt")} />`}
+ ${flow.url && html`<p><a class="text" href=${flow.url} target="_blank" rel="noopener noreferrer">${t("settings.connections.openInBrowser")}</a></p>`}
+ <p class="hint"><${Spinner} /> ${t("settings.connections.waiting")}</p>`;
+}
+
+/** 飞书消息:一键授权要扫两次(创建应用、授权读消息);用已有应用只扫第二次 */
+function FeishuSheet({ conn, mode, onClose }) {
+ const [appId, setAppId] = useState("");
+ const [appSecret, setAppSecret] = useState("");
+ const { flow, error, start } = useFeishuFlow((r) => {
+ conn.setAccounts(r.accounts);
+ saved();
+ onClose();
+ });
+ const begin = (body) => start("/connections/feishu", body);
+ useEffect(() => {
+ if (mode === "oneclick") begin({});
+ }, []);
const steps = flow && (flow.state === "create-app" || flow.state === "authorize");
return html`<${Sheet} title=${t("settings.connections.feishuTitle")} onClose=${onClose}>
- ${mode === "app" && !flow && html`<form onSubmit=${(e) => { e.preventDefault(); start({ appId: appId.trim(), appSecret: appSecret.trim() }); }}>
+ ${mode === "app" && !flow && html`<form onSubmit=${(e) => { e.preventDefault(); begin({ appId: appId.trim(), appSecret: appSecret.trim() }); }}>
<p class="hint">${t("settings.connections.feishuAppHint")}</p>
<label class="set-field"><span class="k">App ID</span><input class="field mono" value=${appId} placeholder="cli_xxxxxxxx" onInput=${(e) => setAppId(e.target.value)} /></label>
<label class="set-field"><span class="k">App Secret</span><input class="field mono" type="password" autocomplete="off" value=${appSecret} onInput=${(e) => setAppSecret(e.target.value)} /></label>
<div class="actions"><button type="submit" class="btn primary" disabled=${!appId.trim() || !appSecret.trim()}>${t("settings.connections.next")}</button></div>
</form>`}
- ${steps && html`<p>${t(flow.state === "create-app" ? "settings.connections.feishuStepCreate" : "settings.connections.feishuStepAuthorize")}</p>
- ${flow.qr && html`<img class="panel-qr" src=${flow.qr} alt=${t("settings.connections.qrAlt")} />`}
- ${flow.url && html`<p><a class="text" href=${flow.url} target="_blank" rel="noopener noreferrer">${t("settings.connections.openInBrowser")}</a></p>`}
- <p class="hint"><${Spinner} /> ${t("settings.connections.waiting")}</p>`}
- ${!flow && mode === "oneclick" && !failedText && html`<p class="hint"><${Spinner} /></p>`}
- <${ErrorLine} text=${failedText} />
- ${failedText && html`<div class="actions"><button type="button" class="btn" onClick=${() => { setFlow(null); setError(""); if (mode === "oneclick") start({}); }}>${t("settings.connections.retry")}</button></div>`}
+ ${steps && html`<${FlowSteps} flow=${flow} text=${t(flow.state === "create-app" ? "settings.connections.feishuStepCreate" : "settings.connections.feishuStepAuthorize")} />`}
+ ${!flow && mode === "oneclick" && !error && html`<p class="hint"><${Spinner} /></p>`}
+ <${ErrorLine} text=${error} />
+ ${error && mode === "oneclick" && html`<div class="actions"><button type="button" class="btn" onClick=${() => begin({})}>${t("settings.connections.retry")}</button></div>`}
<//>`;
}
+/** 飞书聊天账号:默认扫码创建应用,也可以填已有的应用 */
+function FeishuChatConnect({ accountKey, st, reload }) {
+ const [manual, setManual] = useState(false);
+ const path = `/channel-accounts/${encodeURIComponent(accountKey)}/feishu/one-click`;
+ const { flow, error, start } = useFeishuFlow(() => {
+ saved();
+ reload();
+ });
+ useEffect(() => {
+ if (!manual) start(path, {});
+ }, [manual]);
+ if (manual) return html`<${CredentialConnect} accountKey=${accountKey} channel="feishu" st=${st} reload=${reload} />`;
+ return html`${flow && flow.state === "create-app" && flow.url && html`<${FlowSteps} flow=${flow} text=${t("settings.connections.feishuChatStep")} />`}
+ ${(!flow || !flow.url) && !error && html`<p class="hint"><${Spinner} /></p>`}
+ <${ErrorLine} text=${error} />
+ <div class="actions">
+ ${error && html`<button type="button" class="btn" onClick=${() => start(path, {})}>${t("settings.connections.retry")}</button>`}
+ <button type="button" class="text" onClick=${() => setManual(true)}>${t("settings.connections.feishuOther")}</button>
+ </div>`;
+}
+
function RenameSheet({ conn, account, onClose }) {
const [label, setLabel] = useState(account.label);
const submit = async (e) => {
@@ -468,9 +504,11 @@ function ChannelSheet({ conn, bots, channel, accountKey, onClose }) {
<${MenuButton} label=${t("settings.connections.defaultBot")} value=${account.defaultBot} width=${260} options=${(bots || []).map((b) => [b.id, b.name])} onChange=${(v) => put({ defaultBot: v })} />
<p class="hint">${t("settings.connections.defaultBotHint")}</p>
</div>`}
- ${key && (channel === "weixin"
+ ${key && st && (channel === "weixin"
? html`<${WeixinConnect} accountKey=${key} st=${st} reload=${reload} />`
- : html`<${CredentialConnect} key=${key} accountKey=${key} channel=${channel} st=${st} reload=${reload} />`)}
+ : channel === "feishu" && !st.account
+ ? html`<${FeishuChatConnect} accountKey=${key} st=${st} reload=${reload} />`
+ : html`<${CredentialConnect} key=${key} accountKey=${key} channel=${channel} st=${st} reload=${reload} />`)}
${account && html`<${AccessPanel} accountKey=${key} channel=${channel} onChanged=${conn.reloadChannels} />
<div class="actions"><button type="button" class="text danger" onClick=${remove}>${t("settings.connections.removeAccount")}</button></div>`}
<//>`;