🤖 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.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
feat(i18n): 服务端剩余文案(二):后台任务通知与 /tasks、需要你、准入、投递提醒、出站放弃原因、免打扰时间、重启提示
dyk986342d53dfdd8
diff --git a/src/core/access.ts b/src/core/access.tsindex 41218a1..053ffc8 100644--- a/src/core/access.ts+++ b/src/core/access.ts@@ -13,21 +13,22 @@ import type { InboundEvent } from "./types.js";import { eventText } from "./types.js";import type { AccessEntry, Store } from "../store/db.js";import { logger } from "../log.js";+import { t as tr } from "../i18n/index.js";const log = logger("access");/** 陌生人收到的那一句 */-export const REFUSAL_TEXT = "你还没有被允许使用这个机器人,已通知主人。主人同意后就可以直接对话了。";+export const refusalText = () => tr("access.refusal");/** 同一个陌生人多久最多回一次 */export const REFUSE_EVERY_MS = 3600_000;/** 每个机器人每小时最多给主人发几条使用请求通知(其余只在应用里显示) */export const NOTICE_LIMIT = 3;const NOTICE_WINDOW_MS = 3600_000;-export const APPROVED_TEXT = "主人已经同意了,现在可以直接和我对话。";+export const approvedText = () => tr("access.approved");export type AccessChannel = "weixin" | "feishu";export const ACCESS_CHANNELS: AccessChannel[] = ["weixin", "feishu"];-const CHANNEL_LABEL: Record<string, string> = { weixin: "微信", feishu: "飞书", web: "网页" };+const channelLabel = (c: string) => (c === "weixin" ? tr("access.chWeixin") : c === "feishu" ? tr("access.chFeishu") : c === "web" ? tr("access.chWeb") : c);/** 主动发一条通知(App 经渠道和出站队列发);发不出去(对方 24 小时内没说过话、渠道没开)返回 false */export type Notify = (to: { botId: string; channel: string; peerId: string }, text: string, id: string) => boolean;@@ -51,7 +52,7 @@ export function peerName(e: Pick<AccessEntry, "peerId" | "senderId" | "name">):}export function whoText(e: Pick<AccessEntry, "channel" | "peerId" | "senderId" | "name">): string {- return `${CHANNEL_LABEL[e.channel] ?? e.channel}用户 ${peerName(e)}`;+ return tr("access.who", { channel: channelLabel(e.channel), name: peerName(e) });}const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);@@ -128,7 +129,7 @@ export class AccessControl {}if (e.repliedAt && now - e.repliedAt < REFUSE_EVERY_MS) return { ok: false };this.store.updateAccess(e.id, { repliedAt: now });- return { ok: false, reply: REFUSAL_TEXT };+ return { ok: false, reply: refusalText() };}/**@@ -170,8 +171,8 @@ export class AccessControl {return;}const bot = this.store.getBot(e.botId);- const said = e.text ? `:「${clip(e.text, 60)}」` : "";- const text = `有人想使用机器人「${bot?.name ?? e.botId}」——${whoText(e)}${said}\n回复「同意 ${e.code}」允许,「拒绝 ${e.code}」拒绝;也可以在 AnyModelBot 的信息面板里处理。`;+ const said = e.text ? tr("access.said", { text: clip(e.text, 60) }) : "";+ const text = tr("access.ownerNotice", { bot: bot?.name ?? e.botId, who: whoText(e), said, code: e.code });let sent = false;for (const ch of ACCESS_CHANNELS) {const o = this.owner(e.botId, ch);@@ -201,7 +202,7 @@ export class AccessControl {if (!e) return { handled: false };const allow = !/^(拒绝|不同意|n|no)$/i.test(m[1]);this.decide(e.id, allow, `${ev.channel}:${ev.sender.id}`);- return { handled: true, ack: allow ? `✅ 已允许「${whoText(e)}」使用这个机器人` : `❌ 已拒绝「${whoText(e)}」` };+ return { handled: true, ack: tr(allow ? "access.allowedAck" : "access.deniedAck", { who: whoText(e) }) };}/** 允许或拒绝一个请求(被拒绝的也可以改成允许);允许时告诉对方一声 */@@ -211,7 +212,7 @@ export class AccessControl {const now = this.now();this.store.updateAccess(id, { status: allow ? "allowed" : "denied", code: "", decidedAt: now, decidedBy: by, updatedAt: now });log.info(`access ${allow ? "allowed" : "denied"}`, { bot: e.botId, channel: e.channel, peer: shortPeer(e.peerId), by });- if (allow) this.opts.notify?.({ botId: e.botId, channel: e.channel, peerId: e.peerId }, APPROVED_TEXT, `access:${id}:approved:${now}`);+ if (allow) this.opts.notify?.({ botId: e.botId, channel: e.channel, peerId: e.peerId }, approvedText(), `access:${id}:approved:${now}`);return this.store.getAccessById(id);}@@ -282,8 +283,8 @@ export class AccessControl {policyLine(botId: string): string {const v = this.view(botId);const allowed = v.entries.filter((e) => e.status === "allowed").length;- const owners = ACCESS_CHANNELS.map((ch) => `${CHANNEL_LABEL[ch]}主人${v.owners[ch] ? ` ${shortPeer(v.owners[ch]!.peerId)}` : "未设置"}`).join(",");- const req = v.requests.length ? `;${v.requests.length} 个使用请求待处理(回复「同意 编号」或在应用的信息面板里处理)` : "";- return `谁能使用:只有主人和允许名单里的人(${owners};已允许 ${allowed} 人)${req}`;+ const owners = ACCESS_CHANNELS.map((ch) => tr("access.ownerOf", { channel: channelLabel(ch), who: v.owners[ch] ? ` ${shortPeer(v.owners[ch]!.peerId)}` : tr("access.notSet") })).join(tr("access.listSep"));+ const req = v.requests.length ? tr("access.pendingRequests", { count: v.requests.length }) : "";+ return tr("access.policy", { owners, allowed, req });}}diff --git a/src/core/delivery.ts b/src/core/delivery.tsindex 9faae72..1c6788e 100644--- a/src/core/delivery.ts+++ b/src/core/delivery.ts@@ -22,6 +22,7 @@ import { DEFAULT_QUIET, fmtWhen, inQuiet, minuteOf, nextAt, quietEnd, quietStartimport { QUOTA_WINDOW_MS, WeixinQuota } from "../channels/weixin/quota.js";import { combineHeld, filterMarkdown } from "../channels/weixin/channel.js";import { logger } from "../log.js";+import { t as tr } from "../i18n/index.js";const log = logger("delivery");@@ -119,7 +120,7 @@ export interface AttentionItem {actions: Array<"retry" | "dismiss">;}-const CHANNEL_NAME: Record<string, string> = { weixin: "微信", feishu: "飞书" };+const channelName = (c: string) => (c === "weixin" ? tr("delivery.chWeixin") : c === "feishu" ? tr("delivery.chFeishu") : c);const ACK = /^(ok|okay|k|好|好的|好滴|嗯|嗯嗯|收到|行|可以)[\s!!。.~~]*$/i;const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();@@ -136,7 +137,7 @@ export function needsPerson(row: OutboxRow | undefined): boolean {export function digestText(items: Array<{ purpose: string; text: string }>): string {if (items.length === 1) return items[0].text;const all = (...k: string[]) => items.every((i) => k.includes(i.purpose));- const head = all("result", "failure") ? `${items.length} 个后台任务:` : all("rule", "reminder") ? `${items.length} 条提醒:` : `${items.length} 条消息:`;+ const head = tr(all("result", "failure") ? "delivery.digestTasks" : all("rule", "reminder") ? "delivery.digestReminders" : "delivery.digestMessages", { count: items.length });return [head, ...items.map((i) => `· ${oneLine(i.text)}`)].join("\n");}@@ -147,9 +148,9 @@ export function nudgeText(items: Upcoming[], now: number, tz: string): { text: sconst list = items.slice(0, 3).map((i) => (i.at ? `${fmtWhen(i.at, now, tz)} ` : "") + clip(oneLine(i.label), 20))- .join("、");- const tail = noun === "提醒" ? "回个「ok」我就能继续按时提醒你。" : "回个「ok」我就能继续发给你。";- return { text: `接下来还有 ${items.length} 条${noun}要发给你(${list}${items.length > 3 ? " 等" : ""})。${tail}`, noun };+ .join(tr("delivery.listSep"));+ const kind = noun === "提醒" ? "Reminders" : noun === "结果" ? "Results" : "Messages";+ return { text: tr(`delivery.nudge${kind}` as "delivery.nudgeMessages", { count: items.length, list, more: items.length > 3 ? tr("delivery.andMore") : "" }), noun };}/**@@ -445,7 +446,7 @@ export class Delivery {const last = this.store.lastSentOutbox(`${botId}:${channel}:${peerId}`);if (!last || last.purpose !== "nudge" || last.reason === "acked" || this.now() - last.sentAt > QUOTA_WINDOW_MS + NUDGE_BEFORE_MS) return undefined;this.store.updateOutbox(last.id, { reason: "acked" }, this.now());- return last.subject === "提醒" ? "好的,到时提醒你。" : "好的,到时发给你。";+ return last.subject === "提醒" ? tr("delivery.ackReminder") : tr("delivery.ackSend");}// ---------- 需要你 ----------@@ -490,11 +491,11 @@ export class Delivery {for (const [id, list] of groups) {const r0 = list[0];const held = r0.status === "held";- const ch = CHANNEL_NAME[r0.channel] ?? r0.channel;+ const ch = channelName(r0.channel);// 合成过的一条按里面的条数算;文件不单算const parts = list.flatMap((r) => [r, ...(r.body.digest || r.body.away ? this.store.mergedOutbox(r.id) : [])]).filter((r) => r.kind !== "file");const n = Math.max(1, parts.length);- const noun = parts.length && parts.every((r) => r.purpose === "result" || r.purpose === "failure") ? "条结果" : "条消息";+ const results = parts.length > 0 && parts.every((r) => r.purpose === "result" || r.purpose === "failure");items.push({id,kind: "delivery",@@ -503,10 +504,10 @@ export class Delivery {conversationId: r0.conversationId,channel: r0.channel,severity: held ? "warn" : "error",- title: held ? `${n} ${noun}未送达${ch}` : `${n} ${noun}没能发到${ch}`,- line: held ? `在${ch}里发条消息就能收到` : list.some((r) => r.status === "pending") ? "还在重试" : "",+ title: tr(held ? (results ? "delivery.heldResults" : "delivery.heldMessages") : results ? "delivery.failedResults" : "delivery.failedMessages", { count: n, channel: ch }),+ line: held ? tr("delivery.heldLine", { channel: ch }) : list.some((r) => r.status === "pending") ? tr("delivery.retrying") : "",since: Math.min(...list.map((r) => r.createdAt)),- messages: list.map((r) => ({ id: r.id, text: r.kind === "file" ? `[文件 ${r.body.name ?? ""}]` : (r.body.text ?? ""), at: r.createdAt, ref: r.ref })),+ messages: list.map((r) => ({ id: r.id, text: r.kind === "file" ? tr("delivery.fileItem", { name: r.body.name ?? "" }) : (r.body.text ?? ""), at: r.createdAt, ref: r.ref })),actions: held ? [] : list.some((r) => r.status === "gone") ? ["retry", "dismiss"] : ["retry"],});}diff --git a/src/core/outbox.ts b/src/core/outbox.tsindex e7ec804..76f615a 100644--- a/src/core/outbox.ts+++ b/src/core/outbox.ts@@ -16,6 +16,7 @@import crypto from "node:crypto";import type { OutboxBody, OutboxKind, OutboxPurpose, OutboxRow, Store } from "../store/db.js";import { logger } from "../log.js";+import { t as tr } from "../i18n/index.js";const log = logger("outbox");@@ -201,7 +202,7 @@ export class Outbox {this.started = true;this.stopped = false;try {- for (const st of ["held", "scheduled"] as const) for (const r of this.store.listOutbox({ status: st, limit: 500 })) if (r.expiresAt <= this.now()) this.gone(r, "等待太久,已不再发送");+ for (const st of ["held", "scheduled"] as const) for (const r of this.store.listOutbox({ status: st, limit: 500 })) if (r.expiresAt <= this.now()) this.gone(r, tr("delivery.goneTooLong"));this.store.pruneOutbox(this.now());// 重启了:等着退避的不用再等,马上试一次this.store.resumeOutbox(this.now());@@ -242,11 +243,11 @@ export class Outbox {release(botId: string, channel: string, peerId: string, combine?: (rows: OutboxRow[]) => HeldGroup[]): number {const conv = `${botId}:${channel}:${peerId}`;// 还没发出去的续期提醒:对方已经发消息了,不用再提醒- for (const r of this.store.pendingOutbox().filter((x) => x.conversationId === conv && x.purpose === "nudge")) if (!this.inflight.has(conv)) this.gone(r, "对方已经发消息了");+ for (const r of this.store.pendingOutbox().filter((x) => x.conversationId === conv && x.purpose === "nudge")) if (!this.inflight.has(conv)) this.gone(r, tr("delivery.goneReplied"));const waiting = this.store.waitingOutbox(conv);if (!waiting.length) return 0;const now = this.now();- const live = waiting.filter((r) => r.expiresAt > now || (this.gone(r, "等待太久,已不再发送"), false));+ const live = waiting.filter((r) => r.expiresAt > now || (this.gone(r, tr("delivery.goneTooLong")), false));this.apply(combine ? combine(live) : live.map((r): HeldGroup => ({ rows: [r] })), now, "inbound");if (live.length) log.info(`releasing ${live.length} waiting message(s)`, { bot: botId, channel });this.kick();@@ -284,7 +285,7 @@ export class Outbox {const byConv = new Map<string, OutboxRow[]>();for (const r of due) byConv.set(r.conversationId, [...(byConv.get(r.conversationId) ?? []), r]);for (const rows of byConv.values()) {- const live = rows.filter((r) => r.expiresAt > now || (this.gone(r, "等待太久,已不再发送"), false));+ const live = rows.filter((r) => r.expiresAt > now || (this.gone(r, tr("delivery.goneTooLong")), false));if (!live.length) continue;let plan: ReturnType<OutboxPlanner["promote"]> = live.map((r) => ({ rows: [r] }));try {@@ -324,7 +325,7 @@ export class Outbox {heads.add(row.conversationId);if (this.inflight.has(row.conversationId)) continue;if (row.expiresAt <= now) {- this.gone(row, row.error ? `一直没能发出去(${row.error})` : "等待太久,已不再发送");+ this.gone(row, row.error ? tr("delivery.goneKeptFailing", { error: row.error }) : tr("delivery.goneTooLong"));this.kick();continue;}@@ -373,7 +374,7 @@ export class Outbox {}const attempts = row.attempts + 1;const rejected = (e as { rejected?: boolean })?.rejected === true;- if ((rejected && attempts >= REJECTIONS_BEFORE_GONE) || now >= row.expiresAt) return this.gone(row, `发送失败:${msg}`);+ if ((rejected && attempts >= REJECTIONS_BEFORE_GONE) || now >= row.expiresAt) return this.gone(row, tr("delivery.goneFailed", { error: msg }));const delay = Math.min(max, base * 2 ** Math.min(attempts - 1, 16));log.warn("send failed, will retry", { id: row.id, channel: row.channel, attempts, inMs: delay, message: msg });this.store.updateOutbox(row.id, { attempts, error: msg, due: now + delay }, now);diff --git a/src/core/quiet.ts b/src/core/quiet.tsindex 246d763..254ca0b 100644--- a/src/core/quiet.ts+++ b/src/core/quiet.ts@@ -3,6 +3,7 @@* 跨午夜的时段也行。夏令时切换那天按本地钟面时间对齐。*/+import { t as tr } from "../i18n/index.js";export interface QuietHours {enabled: boolean;/** "22:00" */@@ -111,16 +112,15 @@ export function allowedAt(ts: number, q: QuietHours, tz: string): number {return quietEnd(ts, q, tz);}-const CN_WEEK = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];-/** 给用户看的时间:今天 21:30、今晚 22:00、明早 8:00、明天 15:00、周一 9:00、11月3日 9:00 */+/** 给用户看的时间(按当前语言):今天 21:30、今晚 22:00、明早 8:00、明天 15:00、周一 9:00、11月3日 9:00 */export function fmtWhen(at: number, now: number, tz: string): string {const a = localParts(at, tz);const m = Math.floor(a.minute);const hm = `${Math.floor(m / 60)}:${String(m % 60).padStart(2, "0")}`;const days = Math.round((startOfDay(at, tz) - startOfDay(now, tz)) / (DAY * MIN));- if (days <= 0) return `${m >= 18 * 60 ? "今晚" : "今天"} ${hm}`;- if (days === 1) return `${m < 12 * 60 ? "明早" : "明天"} ${hm}`;- if (days < 7) return `${CN_WEEK[a.weekday]} ${hm}`;- return `${a.mo}月${a.d}日 ${hm}`;+ if (days <= 0) return tr(m >= 18 * 60 ? "delivery.tonight" : "delivery.today", { hm });+ if (days === 1) return tr(m < 12 * 60 ? "delivery.tomorrowMorning" : "delivery.tomorrow", { hm });+ if (days < 7) return tr(`delivery.weekday${a.weekday}` as "delivery.weekday0", { hm });+ return tr("delivery.date", { month: tr(`delivery.month${a.mo}` as "delivery.month1"), d: a.d, hm });}diff --git a/src/core/recovery.ts b/src/core/recovery.tsindex c5560a7..a7549a7 100644--- a/src/core/recovery.ts+++ b/src/core/recovery.ts@@ -7,6 +7,7 @@* 发下一条消息时先说。*/import type { Store } from "../store/db.js";+import { t as tr } from "../i18n/index.js";const INFLIGHT = "inflight:";const NOTICE = "notice:";@@ -27,7 +28,7 @@ export function previewOf(text: string): string {/** 告诉用户的话 */export function interruptedText(preview: string): string {- return `上次的消息${preview ? `「${preview}」` : ""}因为应用重启没有处理完,请重新发送。`;+ return tr("delivery.recovered", { preview: preview ? tr("delivery.quoted", { text: preview }) : "" });}/** 开始处理一条消息(同一会话已有标记时保留最早那条) */diff --git a/src/i18n/messages/access.ts b/src/i18n/messages/access.tsnew file mode 100644index 0000000..6391b33--- /dev/null+++ b/src/i18n/messages/access.ts@@ -0,0 +1,38 @@+// access:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ refusal: "你还没有被允许使用这个机器人,已通知主人。主人同意后就可以直接对话了。",+ approved: "主人已经同意了,现在可以直接和我对话。",+ chWeixin: "微信",+ chFeishu: "飞书",+ chWeb: "网页",+ who: "{channel}用户 {name}",+ ownerNotice: "有人想使用机器人「{bot}」——{who}{said}\n回复「同意 {code}」允许,「拒绝 {code}」拒绝;也可以在 AnyModelBot 的信息面板里处理。",+ allowedAck: "✅ 已允许「{who}」使用这个机器人",+ deniedAck: "❌ 已拒绝「{who}」",+ ownerOf: "{channel}主人{who}",+ notSet: "未设置",+ listSep: ",",+ pendingRequests: ";{count} 个使用请求待处理(回复「同意 编号」或在应用的信息面板里处理)",+ policy: "谁能使用:只有主人和允许名单里的人({owners};已允许 {allowed} 人){req}",+ said: ":「{text}」",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ refusal: "You haven't been allowed to use this bot yet; the owner has been notified. Once they approve, you can chat right away.",+ approved: "The owner has approved you. You can chat with me now.",+ chWeixin: "WeChat",+ chFeishu: "Feishu",+ chWeb: "web",+ who: "{channel} user {name}",+ ownerNotice: "Someone wants to use the bot \"{bot}\": {who}{said}\nReply \"yes {code}\" to allow or \"no {code}\" to deny, or handle it in AnyModelBot's info panel.",+ allowedAck: "✅ Allowed \"{who}\" to use this bot",+ deniedAck: "❌ Denied \"{who}\"",+ ownerOf: "{channel} owner{who}",+ notSet: " not set",+ listSep: ", ",+ pendingRequests: "; {count} usage request(s) waiting (reply \"yes <code>\" or handle them in the app's info panel)",+ policy: "Who can use it: only the owners and people on the allow list ({owners}; {allowed} allowed){req}",+ said: ": \"{text}\"",+};diff --git a/src/i18n/messages/delivery.ts b/src/i18n/messages/delivery.tsnew file mode 100644index 0000000..92614ec--- /dev/null+++ b/src/i18n/messages/delivery.ts@@ -0,0 +1,106 @@+// delivery:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ chWeixin: "微信",+ chFeishu: "飞书",+ digestTasks: "{count} 个后台任务:",+ digestReminders: "{count} 条提醒:",+ digestMessages: "{count} 条消息:",+ listSep: "、",+ andMore: " 等",+ nudgeReminders: "接下来还有 {count} 条提醒要发给你({list}{more})。回个「ok」我就能继续按时提醒你。",+ nudgeResults: "接下来还有 {count} 条结果要发给你({list}{more})。回个「ok」我就能继续发给你。",+ nudgeMessages: "接下来还有 {count} 条消息要发给你({list}{more})。回个「ok」我就能继续发给你。",+ ackReminder: "好的,到时提醒你。",+ ackSend: "好的,到时发给你。",+ heldResults: { other: "{count} 条结果未送达{channel}" },+ heldMessages: { other: "{count} 条消息未送达{channel}" },+ failedResults: { other: "{count} 条结果没能发到{channel}" },+ failedMessages: { other: "{count} 条消息没能发到{channel}" },+ heldLine: "在{channel}里发条消息就能收到",+ retrying: "还在重试",+ fileItem: "[文件 {name}]",+ goneTooLong: "等待太久,已不再发送",+ goneReplied: "对方已经发消息了",+ goneKeptFailing: "一直没能发出去({error})",+ goneFailed: "发送失败:{error}",+ today: "今天 {hm}",+ tonight: "今晚 {hm}",+ tomorrowMorning: "明早 {hm}",+ tomorrow: "明天 {hm}",+ weekday0: "周日 {hm}",+ weekday1: "周一 {hm}",+ weekday2: "周二 {hm}",+ weekday3: "周三 {hm}",+ weekday4: "周四 {hm}",+ weekday5: "周五 {hm}",+ weekday6: "周六 {hm}",+ date: "{month}{d}日 {hm}",+ month1: "1月",+ month2: "2月",+ month3: "3月",+ month4: "4月",+ month5: "5月",+ month6: "6月",+ month7: "7月",+ month8: "8月",+ month9: "9月",+ month10: "10月",+ month11: "11月",+ month12: "12月",+ recovered: "上次的消息{preview}因为应用重启没有处理完,请重新发送。",+ quoted: "「{text}」",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ chWeixin: "WeChat",+ chFeishu: "Feishu",+ digestTasks: "{count} background tasks:",+ digestReminders: "{count} reminders:",+ digestMessages: "{count} messages:",+ listSep: ", ",+ andMore: " and more",+ nudgeReminders: "I have {count} more reminders for you ({list}{more}). Reply \"ok\" so I can keep reminding you on time.",+ nudgeResults: "I have {count} more results for you ({list}{more}). Reply \"ok\" so I can keep sending them.",+ nudgeMessages: "I have {count} more messages for you ({list}{more}). Reply \"ok\" so I can keep sending them.",+ ackReminder: "OK, I'll remind you then.",+ ackSend: "OK, I'll send it then.",+ heldResults: { one: "{count} result not delivered to {channel}", other: "{count} results not delivered to {channel}" },+ heldMessages: { one: "{count} message not delivered to {channel}", other: "{count} messages not delivered to {channel}" },+ failedResults: { one: "{count} result couldn't be sent to {channel}", other: "{count} results couldn't be sent to {channel}" },+ failedMessages: { one: "{count} message couldn't be sent to {channel}", other: "{count} messages couldn't be sent to {channel}" },+ heldLine: "Send a message in {channel} to receive them",+ retrying: "Still retrying",+ fileItem: "[file {name}]",+ goneTooLong: "Waited too long; no longer sending",+ goneReplied: "They've already sent a message",+ goneKeptFailing: "Kept failing to send ({error})",+ goneFailed: "Sending failed: {error}",+ today: "today {hm}",+ tonight: "tonight {hm}",+ tomorrowMorning: "tomorrow morning {hm}",+ tomorrow: "tomorrow {hm}",+ weekday0: "Sun {hm}",+ weekday1: "Mon {hm}",+ weekday2: "Tue {hm}",+ weekday3: "Wed {hm}",+ weekday4: "Thu {hm}",+ weekday5: "Fri {hm}",+ weekday6: "Sat {hm}",+ date: "{month} {d} {hm}",+ month1: "Jan",+ month2: "Feb",+ month3: "Mar",+ month4: "Apr",+ month5: "May",+ month6: "Jun",+ month7: "Jul",+ month8: "Aug",+ month9: "Sep",+ month10: "Oct",+ month11: "Nov",+ month12: "Dec",+ recovered: "Your last message{preview} wasn't finished because the app restarted. Please send it again.",+ quoted: " \"{text}\"",+};diff --git a/src/i18n/messages/index.ts b/src/i18n/messages/index.tsindex 50d3625..9ce4a67 100644--- a/src/i18n/messages/index.ts+++ b/src/i18n/messages/index.ts@@ -15,5 +15,7 @@ import * as cu from "./cu.js";import * as pwsh from "./pwsh.js";import * as activity from "./activity.js";import * as tasks from "./tasks.js";+import * as access from "./access.js";+import * as delivery from "./delivery.js";-export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh, activity, tasks };+export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh, activity, tasks, access, delivery };diff --git a/src/i18n/messages/tasks.ts b/src/i18n/messages/tasks.tsindex 95c6dd6..832b8b8 100644--- a/src/i18n/messages/tasks.ts+++ b/src/i18n/messages/tasks.ts@@ -11,6 +11,34 @@ export const zh = {stageReady: "已完成",stageQueued: "排队中",stageWorking: "进行中",+ recoverAppRestart: "应用重启",+ recoverAgentExit: "代理进程退出",+ stoppedNoFollowup: "「{title}」已停止,不能再追加;需要的话开个新任务。",+ stoppedShort: "「{title}」已停止",+ endStopped: "已停止",+ agentDidntStart: "代理没能启动",+ agentUnavailable: "代理不可用",+ modelKeptFailing: "模型一直出错",+ noResult: "没有给出结果",+ done: "「{title}」做好了。",+ notDone: "⚠️「{title}」没做完:{why}",+ withdrawAnswered: "已回答",+ withdrawHandled: "已处理",+ approvalTitle: "需批准(任务「{title}」)",+ questionTitle: "「{title}」想问你",+ continuing: "收到,「{title}」继续。",+ none: "没有后台任务。",+ latestSuffix: ":{text}",+ listHead: "后台任务:",+ stopHint: "发 /stop 编号 可停止。",+ noSuchIndex: "没有第 {n} 个后台任务,发 /tasks 查看。",+ alreadyStage: "「{title}」{stage}。",+ stoppedTask: "已停止后台任务「{title}」。",+ chWeixin: "微信",+ chFeishu: "飞书",+ chWeb: "对话",+ notifyTitle: "{name} 需要你",+ trayTitle: { other: "{product} · {count} 件事需要你" },} satisfies Catalog;export const en: Catalog<typeof zh> = {@@ -23,4 +51,32 @@ export const en: Catalog<typeof zh> = {stageReady: "Done",stageQueued: "Queued",stageWorking: "In progress",+ recoverAppRestart: "the app restarted",+ recoverAgentExit: "the agent process exited",+ stoppedNoFollowup: "\"{title}\" has stopped and can't take follow-ups; start a new task if you need to.",+ stoppedShort: "\"{title}\" has stopped",+ endStopped: "Stopped",+ agentDidntStart: "the agent didn't start",+ agentUnavailable: "the agent isn't available",+ modelKeptFailing: "the model kept failing",+ noResult: "no result",+ done: "\"{title}\" is done.",+ notDone: "⚠️ \"{title}\" didn't finish: {why}",+ withdrawAnswered: "answered",+ withdrawHandled: "handled",+ approvalTitle: "Approval needed (task \"{title}\")",+ questionTitle: "\"{title}\" has a question",+ continuing: "Got it, \"{title}\" carries on.",+ none: "No background tasks.",+ latestSuffix: ": {text}",+ listHead: "Background tasks:",+ stopHint: "Send /stop <number> to stop one.",+ noSuchIndex: "There's no background task {n}; send /tasks to see the list.",+ alreadyStage: "\"{title}\": {stage}.",+ stoppedTask: "Stopped the background task \"{title}\".",+ chWeixin: "WeChat",+ chFeishu: "Feishu",+ chWeb: "Chat",+ notifyTitle: "{name} needs you",+ trayTitle: { one: "{product} · {count} thing needs you", other: "{product} · {count} things need you" },};diff --git a/src/tasks/attention.ts b/src/tasks/attention.tsindex 3dd499a..ff00179 100644--- a/src/tasks/attention.ts+++ b/src/tasks/attention.ts@@ -11,6 +11,7 @@ import type { ApprovalRow, Store } from "../store/db.js";import { questionsOf, type QuestionItem } from "../agent/approvals.js";import type { AttentionItem as DeliveryItem } from "../core/delivery.js";import { logger } from "../log.js";+import { t as tr } from "../i18n/index.js";const log = logger("attention");@@ -164,7 +165,7 @@ export class Attention {}}-const CHANNEL: Record<string, string> = { weixin: "微信", feishu: "飞书", web: "对话" };+const channelLabel = (c: string) => (c === "weixin" ? tr("tasks.chWeixin") : c === "feishu" ? tr("tasks.chFeishu") : c === "web" ? tr("tasks.chWeb") : undefined);/*** 审批中心那一份:还在等的提问和审批(聊天回合里的、后台任务的)。任务的以任务名为题,聊天里的以渠道为题:@@ -181,8 +182,8 @@ export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[kind: r.kind,botId: r.botId,botName: store.getBot(r.botId)?.name ?? r.botId,- subject: task?.title ?? CHANNEL[channel] ?? "对话",- status: r.kind === "approval" ? "等你批准" : "等你回答",+ subject: task?.title ?? channelLabel(channel) ?? tr("tasks.chWeb"),+ status: r.kind === "approval" ? tr("tasks.stageApproval") : tr("tasks.stageAnswer"),line: line.length > 300 ? line.slice(0, 299) + "…" : line,since: r.createdAt,severity: "warn",@@ -232,10 +233,10 @@ export function botLine(it: AttentionItem): string {/** 系统通知:标题「小蓝 需要你」,正文「GPU 价格调研:报告用中文还是英文?」(设计第 6 节) */export function notificationOf(it: AttentionItem): { title: string; body: string } {const body = it.line ? `${it.subject}:${it.line}` : botLine(it);- return { title: `${it.botName} 需要你`, body: body.length > 120 ? body.slice(0, 119) + "…" : body };+ return { title: tr("tasks.notifyTitle", { name: it.botName }), body: body.length > 120 ? body.slice(0, 119) + "…" : body };}/** 托盘:有事时提示文字带上件数,没事时只有应用名(健康时什么都不加) */export function trayTitle(product: string, n: number): string {- return n > 0 ? `${product} · ${n} 件事需要你` : product;+ return n > 0 ? tr("tasks.trayTitle", { product, count: n }) : product;}diff --git a/src/tasks/service.ts b/src/tasks/service.tsindex ce34d47..3925afa 100644--- a/src/tasks/service.ts+++ b/src/tasks/service.ts@@ -32,6 +32,7 @@ import type { AttentionItem } from "./attention.js";import { logger } from "../log.js";import { DEFAULT_MAX_BACKGROUND, pickRuns, priorityOf } from "./slots.js";import { taskStage, type Stage } from "./stage.js";+import { t as tr } from "../i18n/index.js";const log = logger("tasks");@@ -213,7 +214,7 @@ export class TaskService {this.started = true;this.closing = false;this.unlisten ??= this.o.approvals?.listen((e) => this.onApproval(e));- this.recover(undefined, "应用重启");+ this.recover(undefined, tr("tasks.recoverAppRestart"));for (const r of this.store.listRuns({ states: ["ended"] })) {if (!r.taskId) continue;if (!r.delivery && (r.outcome === "done" || r.outcome === "failed")) {@@ -254,7 +255,7 @@ export class TaskService {if (this.closing || !this.started || this.dropped.has(botId)) return;if (!this.store.listRuns({ botId, states: ["running", "settling"] }).length) return;log.warn("agent process exited with background tasks running; recovering them", { bot: botId });- this.recover(botId, "代理进程退出");+ this.recover(botId, tr("tasks.recoverAgentExit"));this.pump();}@@ -343,7 +344,7 @@ export class TaskService {async message(taskId: string, text: string): Promise<{ how?: "steered" | "sent" | "queued" | "resumed" | "answered"; error?: string }> {const task = this.store.getTask(taskId);if (!task) return { error: "task not found" };- if (task.endReason === "stopped") return { error: `「${task.title}」已停止,不能再追加;需要的话开个新任务。` };+ if (task.endReason === "stopped") return { error: tr("tasks.stoppedNoFollowup", { title: task.title }) };// 任务在等用户回答:这句话就是回答(回答成为它的新输入,见 onApproval)const open = this.o.approvals?.pendingForTask(task.id).find((r) => r.kind === "question" && !r.blocking);if (open && this.o.approvals!.answerText(open.id, text.trim(), "followup")) return { how: "answered" };@@ -355,7 +356,7 @@ export class TaskService {async retry(taskId: string): Promise<{ how?: "steered" | "sent" | "queued" | "resumed"; error?: string }> {const task = this.store.getTask(taskId);if (!task) return { error: "task not found" };- if (task.endReason === "stopped") return { error: `「${task.title}」已停止` };+ if (task.endReason === "stopped") return { error: tr("tasks.stoppedShort", { title: task.title }) };const last = this.store.latestRun(task.id);const why = last?.report?.message || last?.error || "";const input = this.addInput(task.id, "followup", `[用户让你再试一次]${why ? `\n上次没做完:${clip(oneLine(why), 300)}` : ""}`, true);@@ -402,7 +403,7 @@ export class TaskService {for (const a of this.o.approvals?.pendingForTask(taskId) ?? []) this.o.approvals!.cancel(a.id, "stopped");const l = this.liveOf(taskId);if (l) {- l.activity.end("已停止");+ l.activity.end(tr("tasks.endStopped"));this.end(l, "stopped");await this.o.host.stop(l.botId, l.sessionId).catch((e) => log.warn("stopping the task session failed", { task: taskId, message: (e as Error).message.slice(0, 200) }));}@@ -539,7 +540,7 @@ export class TaskService {l.timer.unref?.();return;}- this.end(l, "failed", undefined, this.o.host.available ? "代理没能启动" : "代理不可用");+ this.end(l, "failed", undefined, this.o.host.available ? tr("tasks.agentDidntStart") : tr("tasks.agentUnavailable"));return;} finally {l.starting = false;@@ -675,7 +676,7 @@ export class TaskService {return;}if (l.turnError) log.warn("task failed after retries", { task: l.taskId, message: l.turnError.slice(0, 300) });- this.end(l, "failed", undefined, l.turnError ? "模型一直出错" : "没有给出结果");+ this.end(l, "failed", undefined, l.turnError ? tr("tasks.modelKeptFailing") : tr("tasks.noResult"));}/** 结束 run:存下步骤、结果;done / failed 发回会话;空出名额 */@@ -719,7 +720,7 @@ export class TaskService {return;}const msg = oneLine(report?.message ?? "");- const text = outcome === "done" ? clip(msg, MESSAGE_MAX) || `「${task.title}」做好了。` : `⚠️「${task.title}」没做完:${clip(msg || error || "没有给出结果", MESSAGE_MAX)}`;+ const text = outcome === "done" ? clip(msg, MESSAGE_MAX) || tr("tasks.done", { title: task.title }) : tr("tasks.notDone", { title: task.title, why: clip(msg || error || tr("tasks.noResult"), MESSAGE_MAX) });const files = outcome === "done" ? this.files(task, report?.files ?? []) : [];if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.delivery) this.post(conv, task, id, purpose, text, files);this.store.addMessage(conv.id, "assistant", files.length && conv.channel === "web" ? `${text}\n\n${files.map((f) => `- ${path.relative(this.o.host.workspace(task.botId), f)}`).join("\n")}` : text);@@ -875,7 +876,7 @@ export class TaskService {if (!task) return;if (e.type === "decided" && row.kind === "question" && !row.blocking && row.status === "answered" && task.endReason !== "stopped") this.answered(task, row);// 有了决定(在桌面上回答了、批了,任务停了):推给用户还没发出去的那条(排到早上、等微信窗口)不用再发了- if (e.type === "decided") this.o.delivery?.withdraw(askId(row), `已${row.status === "answered" ? "回答" : "处理"}`);+ if (e.type === "decided") this.o.delivery?.withdraw(askId(row), tr(row.status === "answered" ? "tasks.withdrawAnswered" : "tasks.withdrawHandled"));this.changed(task.id);// 等批准时让出的名额:有了决定,排队的可能要等它了if (e.type === "decided" && row.blocking) this.pump();@@ -913,7 +914,7 @@ export class TaskService {else {const replyTo = task.originRef || replyHandle(this.store, conv.id).messageId || "";const buttons = promptButtons(row);- const title = row.kind === "approval" ? `需批准(任务「${task.title}」)` : `「${task.title}」想问你`;+ const title = row.kind === "approval" ? tr("tasks.approvalTitle", { title: task.title }) : tr("tasks.questionTitle", { title: task.title });const body = row.kind === "approval" ? (row.detail ? "`" + row.detail.slice(0, 300) + "`" : row.tool) : (questionsOf(row)[0]?.question ?? row.detail);if (replyTo && buttons) delivery.push({ ...base, replyTo, card: actionCardSpec(title, body, buttons) });else delivery.push({ ...base, replyTo, kind: replyTo ? "text" : "notice" });@@ -932,7 +933,7 @@ export class TaskService {quotes: (row, quote) => !!row.taskId && quotes(this.store.getOutbox(askId(row))?.body.text ?? "", quote, questionsOf(row)[0]?.question ?? row.detail),answered: (row) => {const t = this.store.getTask(row.taskId);- return t ? `收到,「${t.title}」继续。` : undefined;+ return t ? tr("tasks.continuing", { title: t.title }) : undefined;},};}@@ -949,7 +950,7 @@ export class TaskService {const bot = this.store.getBot(t.botId);const conv = this.store.getConversation(t.conversationId);const r = run?.report ?? t.report;- const line = st.key === "failed" ? r?.message || run?.error || "没有给出结果" : r?.message || r?.summary.split("\n")[0] || "";+ const line = st.key === "failed" ? r?.message || run?.error || tr("tasks.noResult") : r?.message || r?.summary.split("\n")[0] || "";out.push({id: `task:${t.id}`,kind: "failed",@@ -1037,20 +1038,20 @@ export class TaskService {/** /tasks:这个会话的任务,带编号(/stop 编号 用同一个顺序) */listText(conversationId: string): string {const list = this.list({ conversationId, limit: 10, since: this.now() - 7 * 86400_000 });- if (!list.length) return "没有后台任务。";- const lines = list.map((t, i) => `${i + 1}. ${t.title} · ${t.stage.label}${t.latest ? `:${clip(t.latest, 40)}` : ""}`);+ if (!list.length) return tr("tasks.none");+ const lines = list.map((x, i) => `${i + 1}. ${x.title} · ${x.stage.label}${x.latest ? tr("tasks.latestSuffix", { text: clip(x.latest, 40) }) : ""}`);const working = list.findIndex((t) => t.stage.group === "working");- return ["后台任务:", ...lines, ...(working >= 0 ? ["发 /stop 编号 可停止。"] : [])].join("\n");+ return [tr("tasks.listHead"), ...lines, ...(working >= 0 ? [tr("tasks.stopHint")] : [])].join("\n");}/** /stop 编号:立即记为停止(停会话在后台进行),返回给用户的话 */stopByIndex(conversationId: string, n: number, by: string): string {const list = this.list({ conversationId, limit: 10, since: this.now() - 7 * 86400_000 });const t = list[n - 1];- if (!t) return `没有第 ${n} 个后台任务,发 /tasks 查看。`;- if (t.stage.group !== "working") return `「${t.title}」${t.stage.label}。`;+ if (!t) return tr("tasks.noSuchIndex", { n });+ if (t.stage.group !== "working") return tr("tasks.alreadyStage", { title: t.title, stage: t.stage.label });void this.stopTask(t.id, by);- return `已停止后台任务「${t.title}」。`;+ return tr("tasks.stoppedTask", { title: t.title });}/** 这个会话有没有正在进行的任务(/stop 不带编号时提示) */diff --git a/test/access.e2e.test.ts b/test/access.e2e.test.tsindex c7c885d..c04a617 100644--- a/test/access.e2e.test.ts+++ b/test/access.e2e.test.ts@@ -10,7 +10,7 @@ import path from "node:path";import { DatabaseSync } from "node:sqlite";import { App } from "../src/app.js";import { loadConfig } from "../src/config.js";-import { APPROVED_TEXT, REFUSAL_TEXT } from "../src/core/access.js";+import { approvedText, refusalText } from "../src/core/access.js";import { FakeFeishu, feishuEvent, mockIlink, mockOpenAI, until } from "./helpers.js";let llm: Awaited<ReturnType<typeof mockOpenAI>>;@@ -81,7 +81,7 @@ describe("微信:只有主人和允许的人", () => {const ownerMsgs = to(OWNER).length;ilink.push("[email protected]", "我是张三,想借用一下");await until(() => to("[email protected]").length >= 1 && to(OWNER).length > ownerMsgs, 8000);- expect(to("[email protected]")).toEqual([REFUSAL_TEXT]);+ expect(to("[email protected]")).toEqual([refusalText()]);const notice = to(OWNER).at(-1)!;expect(notice).toContain("我是张三");code = /同意 (\d{4})/.exec(notice)![1];@@ -102,7 +102,7 @@ describe("微信:只有主人和允许的人", () => {await until(() => to(OWNER).at(-1)!.startsWith("✅"), 8000);expect(to(OWNER).at(-1)).toMatch(/^✅ 已允许「微信用户 .+」使用这个机器人$/);await until(() => to("[email protected]").length >= 2, 8000);- expect(to("[email protected]")[1]).toBe(APPROVED_TEXT);+ expect(to("[email protected]")[1]).toBe(approvedText());ilink.push("[email protected]", "现在呢");await until(() => to("[email protected]").length >= 3, 8000);expect(to("[email protected]")[2]).toBe("[mock-a] 你说:现在呢");@@ -122,14 +122,14 @@ describe("微信:只有主人和允许的人", () => {expect((await api(`/bots/default/access/${wang.id}/approve`, { method: "POST", body: {} })).json.entry.status).toBe("allowed");expect((await api(`/bots/default/access/${wang.id}/approve`, { method: "POST", body: {} })).status).toBe(409);await until(() => to("[email protected]").length >= 2, 8000);- expect(to("[email protected]")).toEqual([REFUSAL_TEXT, APPROVED_TEXT]);+ expect(to("[email protected]")).toEqual([refusalText(), approvedText()]);const calls = llm.calls.length;ilink.push("[email protected]", "再试试");ilink.push("[email protected]", "我能用了吗");await until(() => to("[email protected]").length >= 3, 8000);await app.channels.get("default")!.weixin!.idle();- expect(to("[email protected]")).toEqual([REFUSAL_TEXT]);+ expect(to("[email protected]")).toEqual([refusalText()]);expect(llm.calls.length).toBe(calls + 1);expect((await api(`/bots/default/access/${wang.id}`, { method: "DELETE" })).status).toBe(200);@@ -137,7 +137,7 @@ describe("微信:只有主人和允许的人", () => {await until(async () => (await api("/bots/default/access")).json.requests.length === 1, 8000);await app.channels.get("default")!.weixin!.idle();expect(to("[email protected]")).toHaveLength(4);- expect(to("[email protected]")[3]).toBe(REFUSAL_TEXT);+ expect(to("[email protected]")[3]).toBe(refusalText());expect(llm.calls.length).toBe(calls + 1);});@@ -176,7 +176,7 @@ describe("飞书:第一个发消息的人成为主人", () => {const ownerWx = to(OWNER).length;feishu.onMessage!(feishuEvent("借用一下", { chatId: "oc_colleague", senderOpenId: "ou_colleague" }));await ch.idle();- expect(feishu.texts.at(-1)).toBe(REFUSAL_TEXT);+ expect(feishu.texts.at(-1)).toBe(refusalText());const notice = feishu.notices.at(-1)!;expect(notice.chatId).toBe("oc_boss");const code = /同意 (\d{4})/.exec(notice.text)![1];@@ -185,7 +185,7 @@ describe("飞书:第一个发消息的人成为主人", () => {feishu.onMessage!(feishuEvent(`允许 ${code}`, { chatId: "oc_boss", senderOpenId: "ou_boss" }));await ch.idle();expect(feishu.texts.at(-1)).toMatch(/^✅ 已允许「飞书用户 .+」使用这个机器人$/);- expect(feishu.notices.at(-1)).toMatchObject({ chatId: "oc_colleague", text: APPROVED_TEXT });+ expect(feishu.notices.at(-1)).toMatchObject({ chatId: "oc_colleague", text: approvedText() });feishu.onMessage!(feishuEvent("谢谢", { chatId: "oc_colleague", senderOpenId: "ou_colleague" }));await ch.idle();expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:谢谢");@@ -203,7 +203,7 @@ describe("飞书:第一个发消息的人成为主人", () => {// 原来的主人要重新申请;被允许的同事照常能用feishu.onMessage!(feishuEvent("我还是主人吗", { chatId: "oc_boss", senderOpenId: "ou_boss" }));await ch.idle();- expect(feishu.texts.at(-1)).toBe(REFUSAL_TEXT);+ expect(feishu.texts.at(-1)).toBe(refusalText());feishu.onMessage!(feishuEvent("我还能用吗", { chatId: "oc_colleague", senderOpenId: "ou_colleague" }));await ch.idle();expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:我还能用吗");diff --git a/test/access.unit.test.ts b/test/access.unit.test.tsindex 6e46f05..8ce5a54 100644--- a/test/access.unit.test.ts+++ b/test/access.unit.test.ts@@ -7,7 +7,7 @@ import os from "node:os";import path from "node:path";import { DatabaseSync } from "node:sqlite";import { Store } from "../src/store/db.js";-import { AccessControl, NOTICE_LIMIT, REFUSAL_TEXT, REFUSE_EVERY_MS } from "../src/core/access.js";+import { AccessControl, NOTICE_LIMIT, refusalText, REFUSE_EVERY_MS } from "../src/core/access.js";import { ApprovalCenter } from "../src/agent/approvals.js";import type { InboundEvent } from "../src/core/types.js";@@ -39,7 +39,7 @@ describe("AccessControl", () => {expect(access.admit(ev("web", "console", "hi"))).toEqual({ ok: true });expect(access.admit(ev("feishu", "oc_group", "hi", "group"))).toEqual({ ok: true });- expect(access.admit(ev("weixin", "[email protected]", "我是张三,想用一下"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ expect(access.admit(ev("weixin", "[email protected]", "我是张三,想用一下"))).toEqual({ ok: false, reply: refusalText() });const req = access.view("b").requests[0];expect(req).toMatchObject({ channel: "weixin", peerId: "[email protected]", status: "pending", text: "我是张三,想用一下", requests: 1 });expect(req.code).toMatch(/^\d{4}$/);@@ -54,7 +54,7 @@ describe("AccessControl", () => {expect(sent).toHaveLength(1);expect(store.getAccessById(req.id)!.requests).toBe(2);tick(REFUSE_EVERY_MS + 1);- expect(access.admit(ev("weixin", "[email protected]", "在吗"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ expect(access.admit(ev("weixin", "[email protected]", "在吗"))).toEqual({ ok: false, reply: refusalText() });expect(sent).toHaveLength(1);});@@ -93,7 +93,7 @@ describe("AccessControl", () => {tick(5 * 3600_000);expect(access.admit(ev("weixin", "[email protected]", "hi"))).toEqual({ ok: false });expect(access.remove(id)).toBe(true);- expect(access.admit(ev("weixin", "[email protected]", "hi again"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ expect(access.admit(ev("weixin", "[email protected]", "hi again"))).toEqual({ ok: false, reply: refusalText() });expect(access.view("b").requests[0].text).toBe("hi again");});@@ -109,7 +109,7 @@ describe("AccessControl", () => {expect(access.admit(ev("feishu", "oc_me", "再来一句"))).toEqual({ ok: true });// 第二个、不同的人:使用请求,飞书主人和微信主人都收到配对码- expect(access.admit(ev("feishu", "oc_colleague", "借用一下"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ expect(access.admit(ev("feishu", "oc_colleague", "借用一下"))).toEqual({ ok: false, reply: refusalText() });const req = access.view("b").requests[0];expect(req).toMatchObject({ peerId: "oc_colleague", status: "pending" });expect(sent.filter((s) => s.id.startsWith(`access:${req.id}`)).map((s) => [s.channel, s.peerId]).sort()).toEqual([["feishu", "oc_me"], ["weixin", "[email protected]"]]);@@ -136,7 +136,7 @@ describe("AccessControl", () => {// 下一个发消息的人成为主人;原来的主人要重新申请expect(access.admit(ev("feishu", "oc_me", "绑定"))).toEqual({ ok: true });expect(access.owner("b", "feishu")!.peerId).toBe("oc_me");- expect(access.admit(ev("feishu", "oc_wrong", "我还能用吗"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ expect(access.admit(ev("feishu", "oc_wrong", "我还能用吗"))).toEqual({ ok: false, reply: refusalText() });// 允许名单里的人在没有主人时也会认领(升级前就在用的人多半就是你自己)access.resetOwner("b", "feishu");access.allow("b", "feishu", "oc_old", "migration");@@ -151,7 +151,7 @@ describe("AccessControl", () => {expect(access.owner("b", "weixin")).toBeUndefined();expect(access.admit(ev("weixin", "[email protected]", "你好"))).toEqual({ ok: true });expect(access.owner("b", "weixin")).toMatchObject({ peerId: "[email protected]", via: "first-message" });- expect(access.admit(ev("weixin", "[email protected]", "hi"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ expect(access.admit(ev("weixin", "[email protected]", "hi"))).toEqual({ ok: false, reply: refusalText() });// 重新扫码拿到了扫码者(App 里登录成功时这样调用)access.resetOwner("b", "weixin", { keep: true });store.saveWeixinAccount({ botId: "b", botToken: "t", ilinkBotId: "[email protected]", baseUrl: "http://x", ownerUserId: "[email protected]" });