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(telegram): 个人 bot 支持下线/上线与跨设备远程下线 (#1301)

Chris Zhang1eaffe78e7e9
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 6a19f101f1..e787c70d98 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -159,7 +159,8 @@ import { RendererBootGuard } from './renderer-boot-guard';
import yaml from 'js-yaml';
import matter from 'gray-matter';
import type { Maker } from '@cindy/maker-core';
-import { im, feishuIm, registerTelegramBotConfigIpc, startImOrchestrators, startImConnection, stopImConnection } from './im';
+import { im, feishuIm, telegramIm, registerTelegramBotConfigIpc, startImOrchestrators, startImConnection, stopImConnection } from './im';
+import { setTelegramRemoteSource } from './device-link/telegramRemoteControl';
import * as authManager from './authManager';
import { hasPersistedSessionHint } from './authSessionHint';
import { createAccountDeletionIpcHandlers } from './accountDeletionIpc';
@@ -5920,6 +5921,11 @@ app.on('ready', async () => {
// Telegram 个人 bot 行为/人格/群参与配置的 IPC(设置卡数据面),与 im.registerIpc
// 同期无条件注册;不能放 host.ts 模块顶层(mock electron 的单测收集期会炸)。
registerTelegramBotConfigIpc();
+ // 把 telegram transport 注入 device-link 的跨设备上下线执行器。用注入而非
+ // 静态 import: device-link 侧直接引 im/host 会把整个 IM 子系统拽进它的依赖链
+ // (host.ts 模块顶层就调 app.getPath / ipcMain.handle),而 main 进程又禁止运行时
+ // 动态 import(架构不变式 §2)——注入是唯一合规且不破坏单测收集的接法。
+ setTelegramRemoteSource(telegramIm);
// 挂业务 orchestrator: 订阅 feishuIm.onMessage / .onCardAction。orchestrator
// 必须在 createWindow 前挂好,避免 renderer 起来后第一波 IPC / event 找不到
// handler。FeishuBot 的 WS 长连接必须等当前用户 localDb ready 后再启动。
diff --git a/apps/desktop/src/main/device-link/__tests__/telegramRemoteControl.test.ts b/apps/desktop/src/main/device-link/__tests__/telegramRemoteControl.test.ts
new file mode 100644
index 0000000000..3a799da466
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/telegramRemoteControl.test.ts
@@ -0,0 +1,157 @@
+/**
+ * telegramRemoteControl.test.ts — 被控端跨设备上下线的执行契约。
+ * -------------------------------------------------------------------------------------
+ * 锁住三件事:
+ * 1. **状态投影不带凭证**:过网线的只有 kind / appId / reason。ownerUserId(Telegram
+ * 用户 id)与 botUsername(bot 身份)绝不出现 —— 控制端只需要判断"远端占的是不是
+ * 同一个 bot", appId 就够了。
+ * 2. set-online 只允许下线,并在副作用前重新核对探测时的 bot appId。
+ * 3. 参数解析防御:缺参 / 非法形状一律报错且不执行副作用。
+ * 只 mock im/host 与 logger:本模块的价值就在投影与转发, 不需要真 transport。
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+import type { IMStatus } from '@cindy/im';
+
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+
+const { readTelegramRemoteStatus, setTelegramRemoteOnline, setTelegramRemoteSource } = await import(
+ '../telegramRemoteControl'
+);
+
+const goOffline = vi.fn(async () => {});
+const goOnline = vi.fn(async () => true);
+const getStatus = vi.fn<() => IMStatus>();
+
+beforeEach(() => {
+ goOffline.mockClear();
+ goOnline.mockClear();
+ getStatus.mockReset();
+ setTelegramRemoteSource({ getStatus, goOffline, goOnline });
+});
+
+describe('telegram 远程状态投影', () => {
+ it('connected: 只带 kind + appId, 不泄漏任何凭证/身份字段', () => {
+ getStatus.mockReturnValue({ kind: 'connected', appId: '999' });
+ const projected = readTelegramRemoteStatus();
+ expect(projected).toEqual({ kind: 'connected', appId: '999', reason: null, code: null });
+ // 白名单式断言:未来给 IMStatus 加字段时, 不会悄悄漏到网线上。
+ expect(Object.keys(projected).sort()).toEqual(['appId', 'code', 'kind', 'reason']);
+ const serialized = JSON.stringify(projected);
+ expect(serialized).not.toMatch(/ownerUserId|botUsername|token|secret/i);
+ });
+
+ it('offline / conflict 同样带 appId(控制端据此判断是否同一个 bot)', () => {
+ getStatus.mockReturnValue({ kind: 'offline', appId: '999' });
+ expect(readTelegramRemoteStatus().appId).toBe('999');
+ getStatus.mockReturnValue({ kind: 'conflict', appId: '999' });
+ expect(readTelegramRemoteStatus().kind).toBe('conflict');
+ });
+
+ it('idle: 无 appId 时回 null 而不是 undefined(过 JSON 后形状稳定)', () => {
+ getStatus.mockReturnValue({ kind: 'idle' });
+ expect(readTelegramRemoteStatus()).toEqual({ kind: 'idle', appId: null, reason: null, code: null });
+ });
+
+ it('error: 带上 reason 供控制端显示"token 无效"这类原因', () => {
+ getStatus.mockReturnValue({ kind: 'error', reason: 'invalid token', code: 'invalid-token' });
+ expect(readTelegramRemoteStatus()).toEqual({
+ kind: 'error',
+ appId: null,
+ reason: 'invalid token',
+ code: 'invalid-token',
+ });
+ });
+
+ it('未注入 source: 状态按未配置;携带旧 expectedAppId 的下线被拒绝', async () => {
+ setTelegramRemoteSource(null);
+ expect(readTelegramRemoteStatus()).toEqual({ kind: 'idle', appId: null, reason: null, code: null });
+ await expect(
+ setTelegramRemoteOnline({ online: false, expectedAppId: '999' }),
+ ).rejects.toThrow(/PRECONDITION_FAILED/);
+ });
+
+ it('拒绝上线优先于一切 —— 未注入 source 时也不能被当成"成功"', async () => {
+ setTelegramRemoteSource(null);
+ await expect(
+ setTelegramRemoteOnline({ online: true, expectedAppId: '999' }),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ });
+});
+
+describe('telegram 远程上下线', () => {
+ it('{online:false} → goOffline', async () => {
+ getStatus.mockReturnValue({ kind: 'offline', appId: '999' });
+ const result = await setTelegramRemoteOnline({ online: false, expectedAppId: '999' });
+ expect(goOffline).toHaveBeenCalledTimes(1);
+ expect(goOnline).not.toHaveBeenCalled();
+ expect(result.kind).toBe('offline');
+ });
+
+ it('{online:true} 被硬拒绝 —— 远程不得撤销目标机自己选的下线', async () => {
+ getStatus.mockReturnValue({ kind: 'offline', appId: '999' });
+ // 控制端 UI 只发 false 是产品选择, 不是权限约束: deviceLink.invoke 通用入口
+ // 允许任意参数, 放开上线等于让别的设备把这台拽回 409 争抢。
+ await expect(
+ setTelegramRemoteOnline({ online: true, expectedAppId: '999' }),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ expect(goOnline).not.toHaveBeenCalled();
+ expect(goOffline).not.toHaveBeenCalled();
+ });
+
+ it('畸形 payload 一律报错, 不执行任何副作用(不猜意图)', async () => {
+ getStatus.mockReturnValue({ kind: 'connected', appId: '999' });
+ // 跨设备入口不做宽松解析: 把 {} / {offline:true} 这类笔误默默当成下线, 会让
+ // 目标机莫名其妙停止收消息, 而调用方永远发现不了自己发错了。
+ for (const bad of [
+ undefined,
+ null,
+ 'online',
+ 42,
+ [],
+ [{ online: false }],
+ {},
+ { online: 'false' },
+ { online: 0 },
+ { offline: true },
+ { online: false },
+ { online: false, expectedAppId: '' },
+ { online: false, expectedAppId: null },
+ { online: false, expectedAppId: 999 },
+ ]) {
+ goOffline.mockClear();
+ goOnline.mockClear();
+ await expect(
+ setTelegramRemoteOnline(bad),
+ `payload ${JSON.stringify(bad) ?? 'undefined'} 应被拒绝`,
+ ).rejects.toThrow(/INVALID_PARAMS/);
+ expect(goOffline).not.toHaveBeenCalled();
+ expect(goOnline).not.toHaveBeenCalled();
+ }
+ });
+
+ it('合法的 { online: false } 正常执行下线', async () => {
+ getStatus.mockReturnValue({ kind: 'offline', appId: '999' });
+ await expect(
+ setTelegramRemoteOnline({ online: false, expectedAppId: '999' }),
+ ).resolves.toMatchObject({
+ kind: 'offline',
+ });
+ expect(goOffline).toHaveBeenCalledTimes(1);
+ });
+
+ it('探测后目标端换绑 Bot: 旧 expectedAppId 被拒绝且不下线新 Bot', async () => {
+ getStatus.mockReturnValue({ kind: 'connected', appId: '999' });
+ const staleSnapshot = readTelegramRemoteStatus();
+ getStatus.mockReturnValue({ kind: 'connected', appId: '888' });
+
+ await expect(
+ setTelegramRemoteOnline({ online: false, expectedAppId: staleSnapshot.appId }),
+ ).rejects.toThrow(/PRECONDITION_FAILED/);
+
+ expect(goOffline).not.toHaveBeenCalled();
+ expect(getStatus()).toEqual({ kind: 'connected', appId: '888' });
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index a25a8f03eb..db5c29afe6 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -34,6 +34,8 @@ import {
DL_VOICE_DICTIONARY_LEARNING_CHANNEL,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
DL_VOICE_DICTIONARY_GET_CHANNEL,
+ DL_TELEGRAM_STATUS_CHANNEL,
+ DL_TELEGRAM_SET_ONLINE_CHANNEL,
DeviceLinkError,
parseFsWatchTopic,
type Envelope,
@@ -60,6 +62,7 @@ import { dispatchLocalInvoke } from './invoke-registry';
import { runDeviceLinkInvokeContext } from './invoke-context';
import { fetchLocalMediaToOss } from './mediaFetch';
import { transcribeRemoteVoiceInput } from './voiceTranscribe';
+import { readTelegramRemoteStatus, setTelegramRemoteOnline } from './telegramRemoteControl';
import { adviseAndRecordVoiceInputDictionaryLearning } from '../voice-input/index.js';
import { readDictionaryProjectionForMobile } from '../voice-input/dictionarySyncDriver.js';
import { setBroadcastTapListener } from './broadcast-tap';
@@ -1742,6 +1745,24 @@ export async function runInvoke(
}
}
+ // device-link:telegram:* 不是 ipcMain handler(IM 的 ipcMain 面统一挂了
+ // assertTrustedAppRendererEvent, 合成 event 必然不可信 —— 那道闸不该为远程下线
+ // 放宽), 故在此拦截。已过三道 gate, 等同受信本地访问。只切轮询、不碰凭证:
+ // 远程能让它停收消息, 但拿不走也删不掉绑定(解绑仍只能本机操作)。
+ if (payload.channel === DL_TELEGRAM_STATUS_CHANNEL) {
+ return { ok: true, result: readTelegramRemoteStatus() };
+ }
+ if (payload.channel === DL_TELEGRAM_SET_ONLINE_CHANNEL) {
+ try {
+ const result = await setTelegramRemoteOnline((payload.args ?? [])[0]);
+ return { ok: true, result };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ log.warn(`telegram:set-online failed from ${shortId(src)}: ${message}`);
+ return { ok: false, error: { code: 'IPC_ERROR', message } };
+ }
+ }
+
// Legacy device-link:voice:transcribe 不是 ipcMain handler:早期手机语音方案上传录音到 OSS 后,
// 被控端下载并用本机 voice-input batch ASR 配置转写。当前手机版主流程走 credential sync
// + 手机端实时 ASR/refine,此处仅保留协议兼容面。已过三道 gate,等同受信本地访问。
diff --git a/apps/desktop/src/main/device-link/telegramRemoteControl.ts b/apps/desktop/src/main/device-link/telegramRemoteControl.ts
new file mode 100644
index 0000000000..0ac594d9f4
--- /dev/null
+++ b/apps/desktop/src/main/device-link/telegramRemoteControl.ts
@@ -0,0 +1,137 @@
+/**
+ * telegramRemoteControl.ts — 被控端处理个人 Telegram bot 的跨设备上下线
+ * (device-link:telegram:status / device-link:telegram:set-online)。
+ * ---------------------------------------------------------------------------
+ * 个人 Telegram bot 是 BYO token 直连 Bot API 的 getUpdates 长轮询: 同一 token
+ * 同时只有一台设备能收消息(Telegram 侧 409 Conflict), 而两台设备之间没有任何
+ * 通信通道。换机器时想让另一端让位, 原本只能人肉去那台机器操作 —— 本模块就是
+ * 补这个缺口: 控制端点一下, 被控端自己 goOffline()。
+ *
+ * 为什么不复用 telegramBot:set-online 那条 ipcMain 通道: IM 的所有 IPC 在
+ * im/host.ts 的 host.ipc.handle 里统一包了 assertTrustedAppRendererEvent, 只认
+ * Electron 持有的真实 sender; 而 dispatchLocalInvoke 传的是合成 event
+ * (sender: undefined), 必然判定不可信。那道闸是有意拦着 IM 凭证/配置面的, 不该
+ * 为远程下线放宽, 所以这里与 media:fetch / voice:* 同款 —— 不是 ipcMain handler,
+ * 由 dispatch 在通用路由前拦截执行。
+ *
+ * 安全: 仅由 dispatch.executeInvoke 在三道 gate(remoteControlEnabled + 未撤销 +
+ * allowlist)之后调用, 调用方已是「同账号 + 显式 opt-in 被控 + 未撤销」的控制端。
+ * 边界刻意收窄:
+ * - **不碰凭证**: token / owner id 不读、不写、不外传; 解绑(清凭证)仍然只能
+ * 本机操作 —— 远程能做的只有"让它别收消息", 不能让它失去绑定。
+ * - 状态投影只回 kind + appId(bot 数字 id)。控制端拿 appId 与本机一比即可判断
+ * "远端占的是不是同一个 bot"(不同 bot 根本不冲突, 没必要让它下线), 这就够了;
+ * ownerUserId 是 Telegram 用户 id、botUsername 是 bot 身份, 都没有理由过网线。
+ */
+
+import type { IMErrorCode, IMStatus } from '@cindy/im';
+
+import { createLogger } from '../logger.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+const log = createLogger('device-link:telegram');
+
+/**
+ * 本模块需要的 telegram transport 能力(结构类型, 由 bootstrap 注入 telegramIm)。
+ */
+export interface TelegramRemoteSource {
+ getStatus(): IMStatus;
+ goOffline(): Promise<void>;
+ goOnline(): Promise<boolean>;
+}
+
+let source: TelegramRemoteSource | null = null;
+
+/**
+ * 由 bootstrap 在 IM 接线期注入 —— **刻意不静态 import im/host**:
+ * 1. 架构不变式禁止 main 进程运行时动态 import(), 依赖只能顶层静态引入或注入,
+ * 而这里必须选注入;
+ * 2. 直接静态 import 会把整个 IM host 拽进 device-link 的依赖链, 而 host.ts
+ * 模块顶层就调 app.getPath / ipcMain.handle —— dispatch 的单测在收集期会
+ * 直接炸(host.ts 顶部记着同款教训: 2026-07-30 device-link
+ * TEST_COLLECT_FAILED)。
+ * 未注入时两个入口都按"未配置"处理, 不抛错: 远程控制不该因为本机没装 IM 子系统
+ * 而报一个控制端看不懂的异常。
+ */
+export function setTelegramRemoteSource(next: TelegramRemoteSource | null): void {
+ source = next;
+}
+
+/** 过网线的最小状态投影(无凭证、无 owner id、无 bot 身份)。 */
+export interface TelegramRemoteStatus {
+ /** 与 @cindy/im 的 IMStatus.kind 同集合。 */
+ kind: 'idle' | 'connecting' | 'connected' | 'conflict' | 'offline' | 'error';
+ /** bot 数字 id;未绑定/未解析出时 null。控制端据此判断是否同一个 bot。 */
+ appId: string | null;
+ /** 仅 kind='error' 时可能非空 —— 原文只作诊断, 控制端展示走 code。 */
+ reason: string | null;
+ /** 稳定错误分类;控制端按它取本地化文案, 不直接显示 reason。 */
+ code: IMErrorCode | null;
+}
+
+const NOT_CONFIGURED: TelegramRemoteStatus = { kind: 'idle', appId: null, reason: null, code: null };
+
+/** 把 IMStatus 收敛成过网线的投影(多余字段一律不带)。 */
+function projectStatus(): TelegramRemoteStatus {
+ if (!source) return { ...NOT_CONFIGURED };
+ const status = source.getStatus();
+ return {
+ kind: status.kind,
+ appId: 'appId' in status ? status.appId : null,
+ reason: status.kind === 'error' ? status.reason : null,
+ code: status.kind === 'error' ? (status.code ?? null) : null,
+ };
+}
+
+/** device-link:telegram:status —— 只读快照。 */
+export function readTelegramRemoteStatus(): TelegramRemoteStatus {
+ return projectStatus();
+}
+
+/**
+ * device-link:telegram:set-online —— 让被控端下线。除本地开关的 `online:false`
+ * 外还必须带探测快照的 `expectedAppId`,供目标端在副作用前复核身份。
+ *
+ * 为什么在这里硬拒绝 `online:true`:`deviceLink.invoke` 是通用入口,控制端可以
+ * 自行构造参数 —— 控制端 UI 只发 `false` 是产品选择,不是权限约束。放开上线等于
+ * 让任一有控制权的设备**撤销目标机用户主动选择的下线状态**,把它重新拽回 409
+ * 争抢。远程能做的只有「让它别收消息」,上线是目标机本人的决定,只能本地操作。
+ */
+export async function setTelegramRemoteOnline(arg: unknown): Promise<TelegramRemoteStatus> {
+ // 形状先严格校验再谈语义: 缺字段 / null / 数组 / 字符串 / 字段类型不符
+ // 一律报错, 不做"猜意图"的宽松解析。这是跨设备入口, 把畸形 payload 默默当成
+ // 下线会让控制端的字段名笔误变成一次静默的真实副作用 —— 用户莫名其妙被下线,
+ // 而调用方永远发现不了自己发错了。
+ if (!arg || typeof arg !== 'object' || Array.isArray(arg)) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'expected an object payload { online: boolean, expectedAppId: string }',
+ );
+ }
+ const record = arg as Record<string, unknown>;
+ const online = record.online;
+ if (typeof online !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', '"online" must be a boolean');
+ }
+ const expectedAppId = record.expectedAppId;
+ if (typeof expectedAppId !== 'string' || !expectedAppId) {
+ throwIpcError('INVALID_PARAMS', '"expectedAppId" must be a non-empty string');
+ }
+ if (online) {
+ log.warn('remote set-online(true) rejected: bringing a device online is local-only');
+ throwIpcError('PERMISSION_DENIED', 'bringing a device online remotely is not allowed');
+ }
+
+ // 探测快照只决定按钮是否展示,不能授权稍后的副作用。解绑/换绑可能发生在
+ // probe 与 click 之间;这里在调用 goOffline 前重新取当前身份并精确比对。
+ // 比对与 goOffline 调用之间没有 await,避免新开一个 TOCTOU 窗口。
+ const activeSource = source;
+ const current = projectStatus();
+ if (!activeSource || current.appId !== expectedAppId) {
+ throwIpcError('PRECONDITION_FAILED', 'Telegram bot changed since the status probe');
+ }
+ await activeSource.goOffline();
+ const projected = projectStatus();
+ log.info(`remote set-online(false) -> ${projected.kind}`);
+ return projected;
+}
diff --git a/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts b/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts
index 336b7c097a..19f14f5e52 100644
--- a/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts
+++ b/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts
@@ -26,7 +26,11 @@ vi.mock('electron', () => ({
safeStorage: {
isEncryptionAvailable: () => true,
encryptString: (value: string) => Buffer.from(`encrypted:${value}`, 'utf-8'),
- decryptString: (value: Buffer) => value.toString('utf-8').replace(/^encrypted:/, ''),
+ decryptString: (value: Buffer) => {
+ const raw = value.toString('utf-8');
+ if (raw === 'corrupt') throw new Error('cannot decrypt');
+ return raw.replace(/^encrypted:/, '');
+ },
},
}));
@@ -103,6 +107,26 @@ describe('IM owner-scoped storage', () => {
});
});
+ it('readResult distinguishes missing secrets from I/O or decryption failures', () => {
+ setSession('local', 'local-v1');
+ expect(ownerScopedImSecrets.readResult?.('telegram-bot-offline')).toEqual({
+ kind: 'missing',
+ });
+
+ expect(ownerScopedImSecrets.write('telegram-bot-offline', '1')).toBe(true);
+ expect(ownerScopedImSecrets.readResult?.('telegram-bot-offline')).toEqual({
+ kind: 'value',
+ value: '1',
+ });
+
+ const target = __testing.scopedSecretPath('telegram-bot-offline');
+ expect(target).not.toBeNull();
+ fs.writeFileSync(target!, Buffer.from('corrupt').toString('base64'), 'utf-8');
+ expect(ownerScopedImSecrets.readResult?.('telegram-bot-offline')).toEqual({ kind: 'error' });
+ // 旧 read 契约保持兼容:调用方若不需要区分,错误仍折叠为 null。
+ expect(ownerScopedImSecrets.read('telegram-bot-offline')).toBeNull();
+ });
+
it('claims legacy working directories only for a verified cloud owner', () => {
const legacy = path.join(mocks.root, 'im-working-dir', 'bot-a');
fs.mkdirSync(legacy, { recursive: true });
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index 9c4448112e..76ea17dbf5 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -45,6 +45,7 @@ import {
} from './telegram/behaviorStore';
import { listTelegramKnownGroups } from './telegram/groupWindow';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
import { imHostAccountScope } from './accountScopeBridge';
import { ownerScopedImSecrets } from './ownerScopedStorage';
import { captureImAccountGeneration, isImAccountGenerationCurrent } from './accountBoundary';
@@ -144,6 +145,7 @@ const host: IMHost = {
},
secrets: ownerScopedImSecrets,
ipc: {
+ throwIpcError,
handle(channel, handler) {
// IM 凭证/配置通道(set-config/get-status/disconnect 等)全部是敏感面:
// 统一在适配器入口验可信 app renderer, 包侧 handler 拿不到 event 也
diff --git a/apps/desktop/src/main/im/ownerScopedStorage.ts b/apps/desktop/src/main/im/ownerScopedStorage.ts
index fadbf33072..18c389eb20 100644
--- a/apps/desktop/src/main/im/ownerScopedStorage.ts
+++ b/apps/desktop/src/main/im/ownerScopedStorage.ts
@@ -8,7 +8,7 @@ import { app, safeStorage } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
-import type { IMHost } from '@cindy/im';
+import type { IMHost, IMSecretReadResult } from '@cindy/im';
import {
dataOwnerStorageKey,
@@ -143,6 +143,23 @@ function prepareSecretPath(name: string): string | null {
return scoped;
}
+/** Read a secret without collapsing a missing file and an I/O/decryption failure. */
+function readSecretResult(name: string): IMSecretReadResult {
+ try {
+ if (!safeStorage.isEncryptionAvailable()) return { kind: 'error' };
+ const target = prepareSecretPath(name);
+ if (!target) return { kind: 'error' };
+ const encrypted = fs.readFileSync(target, 'utf-8');
+ return {
+ kind: 'value',
+ value: safeStorage.decryptString(Buffer.from(encrypted, 'base64')),
+ };
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };
+ return { kind: 'error' };
+ }
+}
+
/** @cindy/im secret adapter whose logical keys follow the active data owner. */
export const ownerScopedImSecrets: ImSecrets = {
isAvailable: () => safeStorage.isEncryptionAvailable() && scopedSecretPath('probe') !== null,
@@ -159,15 +176,10 @@ export const ownerScopedImSecrets: ImSecrets = {
}
},
read(name) {
- try {
- if (!safeStorage.isEncryptionAvailable()) return null;
- const target = prepareSecretPath(name);
- if (!target || !fs.existsSync(target)) return null;
- return safeStorage.decryptString(Buffer.from(fs.readFileSync(target, 'utf-8'), 'base64'));
- } catch {
- return null;
- }
+ const result = readSecretResult(name);
+ return result.kind === 'value' ? result.value : null;
},
+ readResult: readSecretResult,
remove(name) {
try {
const target = prepareSecretPath(name);
diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
index 82663f8f8f..e6c36b9aea 100644
--- a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
@@ -383,6 +383,9 @@ function host(
remove: vi.fn(),
},
ipc: {
+ throwIpcError: (code, message) => {
+ throw new Error(`[${code}] ${message}`);
+ },
handle: vi.fn(),
broadcast: vi.fn(),
},
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 523bad7345..06f6ed6c37 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -238,6 +238,17 @@ type DiscordBotSessionAuthCheckWire = {
providerId: string | null;
providerLabel: string | null;
};
+/**
+ * 个人 Telegram bot 的传输状态(与 @cindy/im 的 IMStatus 同形; preload 不引包,
+ * 就地声明)。offline = 凭证保留但用户主动下线, 与 idle(未配置)严格区分。
+ */
+type TelegramBotStatusWire =
+ | { kind: 'idle' }
+ | { kind: 'connecting' }
+ | { kind: 'connected'; appId: string }
+ | { kind: 'conflict'; appId: string }
+ | { kind: 'offline'; appId: string }
+ | { kind: 'error'; reason: string; code?: 'invalid-token' | 'provider-api' | 'network' | 'secret-unavailable' };
/**
* Factory for lazy, ref-counted IPC fan-out subscriptions.
@@ -1572,39 +1583,26 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 桌面端直连 Telegram Bot API 长轮询, 不经 Cindy 服务器。
telegramBot: {
getStatus: (): Promise<{
- status:
- | { kind: 'idle' }
- | { kind: 'connecting' }
- | { kind: 'connected'; appId: string }
- | { kind: 'conflict'; appId: string }
- | { kind: 'error'; reason: string };
+ status: TelegramBotStatusWire;
ownerUserId: string | null;
botUsername: string | null;
}> => ipcRenderer.invoke('telegramBot:get-status'),
setConfig: (payload: { token: string; ownerUserId: string }): Promise<{
- status:
- | { kind: 'idle' }
- | { kind: 'connecting' }
- | { kind: 'connected'; appId: string }
- | { kind: 'conflict'; appId: string }
- | { kind: 'error'; reason: string };
- saveErrorStatus?:
- | { kind: 'idle' }
- | { kind: 'connecting' }
- | { kind: 'connected'; appId: string }
- | { kind: 'conflict'; appId: string }
- | { kind: 'error'; reason: string };
+ status: TelegramBotStatusWire;
+ saveErrorStatus?: TelegramBotStatusWire;
ownerUserId: string | null;
botUsername: string | null;
}> => ipcRenderer.invoke('telegramBot:set-config', payload),
disconnect: (): Promise<{
- status:
- | { kind: 'idle' }
- | { kind: 'connecting' }
- | { kind: 'connected'; appId: string }
- | { kind: 'conflict'; appId: string }
- | { kind: 'error'; reason: string };
+ status: TelegramBotStatusWire;
}> => ipcRenderer.invoke('telegramBot:disconnect'),
+ /**
+ * 上线/下线: 只切轮询, 保留 token 与绑定信息(与 disconnect 清凭证相对)。
+ * 换机器时把这一端让出来, 之后随时可再上线。
+ */
+ setOnline: (payload: { online: boolean }): Promise<{
+ status: TelegramBotStatusWire;
+ }> => ipcRenderer.invoke('telegramBot:set-online', payload),
checkSessionAuth: (): Promise<DiscordBotSessionAuthCheckWire> =>
ipcRenderer.invoke('telegramBot:check-session-auth'),
// 行为配置(emoji 回应等级 / 回复引用) — 设置卡可视化操作面, 改动即生效。
diff --git a/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx b/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx
index 3465052d4a..56ad369e20 100644
--- a/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx
@@ -1,12 +1,24 @@
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Loader2, Trash2 } from 'lucide-react';
+import {
+ AlertTriangle,
+ Check,
+ ChevronDown,
+ ChevronRight,
+ Eye,
+ EyeOff,
+ Loader2,
+ Power,
+ PowerOff,
+ Trash2,
+} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
-import { useTelegramBot } from '@/hooks/useTelegramBot';
+import { describeTelegramStatusFailure, useTelegramBot } from '@/hooks/useTelegramBot';
import { ImChannelSettingsCard, useImChannelSettingsSummary } from './ImChannelSettingsCard';
import { ImDefaultSettingsSection } from './ImDefaultSettingsSection';
+import { TelegramRemoteDevices } from './TelegramRemoteDevices';
import {
TelegramBehaviorSettings,
TelegramGroupActivationSettings,
@@ -20,9 +32,22 @@ const statusKey: Record<TelegramBotTransportStatus['kind'], string> = {
connecting: 'settings.telegramBot.status.connecting',
connected: 'settings.telegramBot.status.connected',
conflict: 'settings.telegramBot.status.conflict',
+ offline: 'settings.telegramBot.status.offline',
error: 'settings.telegramBot.status.error',
};
+/** 已有绑定的三档 —— 都带 appId(bot 数字 id), 卡片可直接展示。 */
+type TelegramBoundStatus = Extract<TelegramBotTransportStatus, { appId: string }>;
+
+/**
+ * 有凭证的三档(已连接 / 被另一台占用 / 主动下线)都走已连接卡: 它们都不该
+ * 显示 token 表单 —— 尤其 conflict, 落表单会让"被另一台设备占用"看起来像
+ * "还没配置"。error(token 无效)与 connecting 仍走表单。
+ */
+function hasBinding(s: TelegramBotTransportStatus): s is TelegramBoundStatus {
+ return s.kind === 'connected' || s.kind === 'offline' || s.kind === 'conflict';
+}
+
function statusColor(s: TelegramBotTransportStatus): string {
switch (s.kind) {
case 'idle':
@@ -30,6 +55,9 @@ function statusColor(s: TelegramBotTransportStatus): string {
case 'connecting':
case 'conflict':
return 'var(--settings-badge-saved)';
+ // 主动下线是用户自己选的正常状态, 不是故障 —— 中性灰, 不用告警色。
+ case 'offline':
+ return 'var(--settings-badge-needs-config)';
case 'connected':
return 'var(--settings-badge-connected)';
case 'error':
@@ -59,9 +87,11 @@ export function TelegramBotSection({
validationError,
isSaving,
isDisconnecting,
+ isTogglingOnline,
canConnect,
connect,
disconnect,
+ setOnline,
} = useTelegramBot();
const [showToken, setShowToken] = useState(false);
@@ -153,12 +183,16 @@ export function TelegramBotSection({
<div className="h-px w-full bg-[var(--border-default)]" />
<TelegramGroupActivationSettings />
<div className="h-px w-full bg-[var(--border-default)]" />
- {status.kind === 'connected' ? (
+ {hasBinding(status) ? (
<ConnectedCard
+ status={status}
botLabel={botUsername ? `@${botUsername}` : status.appId}
ownerUserId={ownerUserId}
isDisconnecting={isDisconnecting}
+ isTogglingOnline={isTogglingOnline}
onDisconnect={() => void handleDisconnectClick()}
+ onToggleOnline={() => void setOnline(status.kind === 'offline')}
+ remoteDevices={<TelegramRemoteDevices selfAppId={status.appId} />}
/>
) : (
<div className="flex flex-col gap-3">
@@ -229,7 +263,7 @@ export function TelegramBotSection({
</p>
) : status.kind === 'error' ? (
<p className="text-12 text-[var(--settings-error-text)]" role="alert">
- {status.reason}
+ {describeTelegramStatusFailure(status, t)}
</p>
) : (
<p className="text-12 text-[var(--settings-source-meta)]">
@@ -324,14 +358,34 @@ export function TelegramBotSection({
);
}
-/** 已连接状态卡 —— 结构对齐 DiscordBotSection 的 ConnectedCard。 */
+/** 已绑定状态卡(已连接 / 已下线 / 被占用三档共用) —— 结构对齐 DiscordBotSection。 */
function ConnectedCard(props: {
+ status: TelegramBoundStatus;
botLabel: string;
ownerUserId: string;
isDisconnecting: boolean;
+ isTogglingOnline: boolean;
onDisconnect: () => void;
+ onToggleOnline: () => void;
+ /** 「我的其他设备」区块;无其他设备时组件自身渲染 null。 */
+ remoteDevices: React.ReactNode;
}) {
const { t } = useTranslation();
+ const kind = props.status.kind;
+ const isOffline = kind === 'offline';
+ const busy = props.isDisconnecting || props.isTogglingOnline;
+ const headingKey =
+ kind === 'offline'
+ ? 'settings.telegramBot.connected.headingOffline'
+ : kind === 'conflict'
+ ? 'settings.telegramBot.connected.headingConflict'
+ : 'settings.telegramBot.connected.heading';
+ const noteKey =
+ kind === 'offline'
+ ? 'settings.telegramBot.connected.noteOffline'
+ : kind === 'conflict'
+ ? 'settings.telegramBot.connected.noteConflict'
+ : 'settings.telegramBot.connected.note';
return (
<div
className={cn(
@@ -341,15 +395,27 @@ function ConnectedCard(props: {
)}
>
<div className="flex items-start gap-3">
- <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)] text-[var(--settings-badge-connected)]">
- <Check size={16} />
+ <div
+ className={cn(
+ 'mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full',
+ 'border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)]',
+ )}
+ style={{ color: statusColor(props.status) }}
+ >
+ {kind === 'offline' ? (
+ <PowerOff size={16} />
+ ) : kind === 'conflict' ? (
+ <AlertTriangle size={16} />
+ ) : (
+ <Check size={16} />
+ )}
</div>
<div className="min-w-0 flex-1">
<div className="text-13 font-medium text-[var(--settings-section-title)]">
- {t('settings.telegramBot.connected.heading')}
+ {t(headingKey)}
</div>
<div className="mt-1 text-12 leading-[1.6] text-[var(--settings-section-desc)]">
- {t('settings.telegramBot.connected.note')}
+ {t(noteKey)}
</div>
</div>
</div>
@@ -368,15 +434,44 @@ function ConnectedCard(props: {
</div>
</div>
<div className="flex gap-2 pt-1">
+ {/* 下线/上线: 可逆且零数据损失, 不加二次确认(解绑才需要确认)。 */}
+ <button
+ type="button"
+ onClick={props.onToggleOnline}
+ disabled={busy}
+ className={cn(
+ 'flex h-[36px] flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',
+ 'text-12 font-medium text-[var(--settings-btn-secondary-text)]',
+ busy && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {props.isTogglingOnline ? (
+ <span className="inline-flex animate-spin motion-reduce:animate-none" aria-hidden>
+ <Loader2 size={13} />
+ </span>
+ ) : isOffline ? (
+ <Power size={13} />
+ ) : (
+ <PowerOff size={13} />
+ )}
+ {props.isTogglingOnline
+ ? t(
+ isOffline
+ ? 'settings.telegramBot.goingOnlineAction'
+ : 'settings.telegramBot.goingOfflineAction',
+ )
+ : t(isOffline ? 'settings.telegramBot.goOnline' : 'settings.telegramBot.goOffline')}
+ </button>
<button
type="button"
onClick={props.onDisconnect}
- disabled={props.isDisconnecting}
+ disabled={busy}
className={cn(
'flex h-[36px] flex-1 items-center justify-center gap-1.5 rounded-full',
'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',
'text-12 font-medium text-[var(--settings-btn-secondary-text)]',
- props.isDisconnecting && 'cursor-not-allowed opacity-40',
+ busy && 'cursor-not-allowed opacity-40',
)}
>
{props.isDisconnecting ? (
@@ -391,6 +486,7 @@ function ConnectedCard(props: {
: t('settings.telegramBot.disconnect')}
</button>
</div>
+ {props.remoteDevices}
</div>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx b/apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx
new file mode 100644
index 0000000000..1d72384653
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx
@@ -0,0 +1,264 @@
+/**
+ * TelegramRemoteDevices —— 个人 Telegram bot 设置卡里的「我的其他设备」区块。
+ *
+ * 为什么需要它: 个人 bot 是 BYO token 直连 Bot API 的长轮询, 同一 token 同时
+ * 只有一台设备能收消息, 而两台设备之间没有任何通信通道。想让另一端让位, 原本
+ * 只能人肉跑去那台机器上操作 —— 这里借 device-link 隧道补上这一步。
+ *
+ * 边界(与被控端 telegramRemoteControl.ts 对称): 只能让对方**下线**(停轮询),
+ * 拿不到也删不掉对方的凭证; 解绑仍然只能在那台机器本地做。
+ *
+ * 老被控端没有这两个 channel → 隧道回 CHANNEL_NOT_ALLOWED, 这里显示「该设备
+ * 版本不支持」而不是静默失败 —— 远程下线要等对方升级到含此功能的版本才可用,
+ * 这一点必须让用户当场看见, 否则会以为是自己点错了。
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Loader2, PowerOff, RefreshCw } from 'lucide-react';
+
+import { cn } from '@/lib/utils';
+import { createLogger } from '@/lib/logger';
+import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
+import { useSelectableDevices } from '@/hooks/useControllableDevices';
+
+const log = createLogger('TelegramRemoteDevices');
+
+const STATUS_CHANNEL = 'device-link:telegram:status';
+const SET_ONLINE_CHANNEL = 'device-link:telegram:set-online';
+
+/** 与被控端 TelegramRemoteStatus 同形(无凭证 / 无 owner id / 无 bot 身份)。 */
+interface RemoteStatus {
+ kind: 'idle' | 'connecting' | 'connected' | 'conflict' | 'offline' | 'error';
+ appId: string | null;
+ /** 诊断原文(可能是英文技术串), 不直接展示。 */
+ reason: string | null;
+ /** 稳定错误分类, 展示走 i18n。 */
+ code: 'invalid-token' | 'provider-api' | 'network' | 'secret-unavailable' | null;
+}
+
+/** 每台设备的探测结果:未知(拉取中)/ 拿到状态 / 版本太老 / 拉取失败。 */
+type Probe =
+ | { state: 'loading' }
+ | { state: 'ok'; status: RemoteStatus }
+ | { state: 'unsupported' }
+ | { state: 'failed' };
+
+function isChannelNotAllowed(err: unknown): boolean {
+ return extractIpcError(err)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED';
+}
+
+/** Stable device-link IPC codes → localized copy; never surface transport messages in UI. */
+const TELEGRAM_REMOTE_FAILURE_I18N: Record<string, string> = {
+ PRECONDITION_FAILED: 'settings.telegramBot.remoteDevices.state.otherBot',
+ DEVICE_LINK_REMOTE_DISABLED: 'settings.telegramBot.remoteDevices.failure.remoteDisabled',
+ DEVICE_LINK_ACCESS_REVOKED: 'settings.telegramBot.remoteDevices.failure.accessRevoked',
+ DEVICE_LINK_CONTROL_DISABLED: 'settings.telegramBot.remoteDevices.failure.controlDisabled',
+ DEVICE_LINK_NOT_CONNECTED: 'settings.telegramBot.remoteDevices.failure.unreachable',
+ DEVICE_LINK_DEVICE_OFFLINE: 'settings.telegramBot.remoteDevices.failure.unreachable',
+ DEVICE_LINK_TIMEOUT: 'settings.telegramBot.remoteDevices.failure.unreachable',
+ DEVICE_LINK_UNAVAILABLE: 'settings.telegramBot.remoteDevices.failure.unreachable',
+ DEVICE_LINK_STANDBY: 'settings.telegramBot.remoteDevices.failure.unreachable',
+ DEVICE_LINK_VERSION_MISMATCH: 'settings.telegramBot.remoteDevices.state.unsupported',
+};
+
+export function telegramRemoteFailureKey(err: unknown): string {
+ const code = extractIpcError(err)?.code;
+ return (
+ (code && TELEGRAM_REMOTE_FAILURE_I18N[code])
+ || 'settings.telegramBot.remoteDevices.failure.unknown'
+ );
+}
+
+export function TelegramRemoteDevices({ selfAppId }: { selfAppId: string | null }) {
+ const { t } = useTranslation();
+ const { devices, loaded } = useSelectableDevices();
+ const [probes, setProbes] = useState<Record<string, Probe>>({});
+ const [busyDeviceId, setBusyDeviceId] = useState<string | null>(null);
+ /** 请求序号: presence 抖动会重触发探测, 老响应不得覆盖新一轮结果。 */
+ const probeSeq = useRef(0);
+
+ const probeAll = useCallback(async () => {
+ const seq = ++probeSeq.current;
+ const online = devices.filter((d) => d.online);
+ if (online.length === 0) {
+ setProbes({});
+ return;
+ }
+ setProbes((prev) => {
+ const next: Record<string, Probe> = {};
+ for (const d of online) next[d.deviceId] = prev[d.deviceId] ?? { state: 'loading' };
+ return next;
+ });
+ await Promise.all(
+ online.map(async (d) => {
+ let probe: Probe;
+ try {
+ const result = (await window.electronAPI.deviceLink.invoke(
+ d.deviceId,
+ STATUS_CHANNEL,
+ [],
+ )) as RemoteStatus;
+ probe = { state: 'ok', status: result };
+ } catch (err) {
+ probe = isChannelNotAllowed(err) ? { state: 'unsupported' } : { state: 'failed' };
+ if (probe.state === 'failed') {
+ log.debug('telegram status probe failed', {
+ deviceId: d.deviceId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ if (probeSeq.current !== seq) return;
+ setProbes((prev) => ({ ...prev, [d.deviceId]: probe }));
+ }),
+ );
+ }, [devices]);
+
+ useEffect(() => {
+ if (!loaded) return;
+ void probeAll();
+ }, [loaded, probeAll]);
+
+ const takeOffline = useCallback(
+ async (deviceId: string, expectedAppId: string) => {
+ if (busyDeviceId) return;
+ setBusyDeviceId(deviceId);
+ try {
+ const result = (await window.electronAPI.deviceLink.invoke(deviceId, SET_ONLINE_CHANNEL, [
+ { online: false, expectedAppId },
+ ])) as RemoteStatus;
+ setProbes((prev) => ({ ...prev, [deviceId]: { state: 'ok', status: result } }));
+ // 远端执行失败也会作为成功的 device-link 响应回来(例如目标机写不进下线标志时
+ // 只落 error 并保持轮询)。不核对终态就报成功, 会让人以为冲突已经解除。
+ if (result.kind !== 'offline') {
+ toast.error(
+ t('logic.toasts.telegramRemoteFailed', {
+ // 远端的 reason 同样是诊断原文, 展示一律走 code / 状态 i18n。
+ message:
+ result.kind === 'error' && result.code
+ ? t(`settings.telegramBot.errorCode.${result.code}`)
+ : t(`settings.telegramBot.remoteDevices.state.${result.kind}`),
+ }),
+ );
+ return;
+ }
+ toast.success(t('logic.toasts.telegramRemoteWentOffline'));
+ } catch (err) {
+ if (isChannelNotAllowed(err)) {
+ setProbes((prev) => ({ ...prev, [deviceId]: { state: 'unsupported' } }));
+ toast.error(t('logic.toasts.telegramRemoteUnsupported'));
+ } else {
+ const ipcError = extractIpcError(err);
+ if (ipcError?.code === 'PRECONDITION_FAILED') await probeAll();
+ // 原始 message 只写诊断日志;toast 只能展示稳定 code 对应的 locale 文案。
+ log.error('remote set-online failed', {
+ code: ipcError?.code ?? null,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ toast.error(
+ t('logic.toasts.telegramRemoteFailed', {
+ message: t(telegramRemoteFailureKey(err)),
+ }),
+ );
+ }
+ } finally {
+ setBusyDeviceId(null);
+ }
+ },
+ [busyDeviceId, probeAll, t],
+ );
+
+ // 一台其他设备都没有时整块不出现 —— 单机用户不该看到一个恒空的区块。
+ if (!loaded || devices.length === 0) return null;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <span className="flex-1 text-12 font-medium text-[var(--settings-section-desc)]">
+ {t('settings.telegramBot.remoteDevices.title')}
+ </span>
+ <button
+ type="button"
+ onClick={() => void probeAll()}
+ aria-label={t('settings.telegramBot.remoteDevices.refresh')}
+ className="flex shrink-0 items-center justify-center bg-transparent p-0 text-[var(--settings-trash-icon)] transition-colors hover:text-[var(--settings-trash-icon-hover)]"
+ >
+ <RefreshCw size={13} />
+ </button>
+ </div>
+ <p className="text-11 leading-[1.6] text-[var(--settings-source-meta)]">
+ {t('settings.telegramBot.remoteDevices.hint')}
+ </p>
+ <div className="flex flex-col gap-1.5">
+ {devices.map((d) => {
+ const probe: Probe = d.online
+ ? (probes[d.deviceId] ?? { state: 'loading' })
+ : { state: 'failed' };
+ const status = probe.state === 'ok' ? probe.status : null;
+ // 只有"正在占着同一个 bot"才值得给下线按钮: 不同 bot 根本不冲突,
+ // 已下线/未绑定的更没有可下线的东西。
+ const sameBot = !!status?.appId && (!selfAppId || status.appId === selfAppId);
+ const canTakeOffline =
+ d.online && sameBot && (status.kind === 'connected' || status.kind === 'conflict');
+ const detail = !d.online
+ ? t('settings.telegramBot.remoteDevices.state.offlineDevice')
+ : probe.state === 'loading'
+ ? t('settings.telegramBot.remoteDevices.state.checking')
+ : probe.state === 'unsupported'
+ ? t('settings.telegramBot.remoteDevices.state.unsupported')
+ : probe.state === 'failed'
+ ? t('settings.telegramBot.remoteDevices.state.unreachable')
+ : status && !status.appId
+ ? t('settings.telegramBot.remoteDevices.state.notConfigured')
+ : status && !sameBot
+ ? t('settings.telegramBot.remoteDevices.state.otherBot')
+ : t(`settings.telegramBot.remoteDevices.state.${status?.kind ?? 'idle'}`);
+ return (
+ <div
+ key={d.deviceId}
+ className={cn(
+ 'flex items-center gap-3 rounded-lg px-3 py-2',
+ 'border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',
+ !d.online && 'opacity-50',
+ )}
+ >
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-12 font-medium text-[var(--settings-section-title)]">
+ {d.name}
+ </span>
+ <span className="truncate text-11 text-[var(--settings-source-meta)]">{detail}</span>
+ </div>
+ {canTakeOffline ? (
+ <button
+ type="button"
+ onClick={() => void takeOffline(d.deviceId, status.appId!)}
+ disabled={busyDeviceId !== null}
+ className={cn(
+ 'flex h-[28px] shrink-0 items-center justify-center gap-1.5 rounded-full px-3',
+ 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',
+ 'text-11 font-medium text-[var(--settings-btn-secondary-text)]',
+ busyDeviceId !== null && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {busyDeviceId === d.deviceId ? (
+ <span
+ className="inline-flex animate-spin motion-reduce:animate-none"
+ aria-hidden
+ >
+ <Loader2 size={12} />
+ </span>
+ ) : (
+ <PowerOff size={12} />
+ )}
+ {t('settings.telegramBot.remoteDevices.takeOffline')}
+ </button>
+ ) : null}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/TelegramRemoteDevices.errorI18n.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/TelegramRemoteDevices.errorI18n.test.ts
new file mode 100644
index 0000000000..90d6d9fe64
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/TelegramRemoteDevices.errorI18n.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { telegramRemoteFailureKey } from '../TelegramRemoteDevices';
+
+const ipcError = (code: string, message = 'internal transport message') =>
+ new Error(`[${code}] ${message}`);
+
+describe('TelegramRemoteDevices remote failure i18n', () => {
+ it.each([
+ ['PRECONDITION_FAILED', 'settings.telegramBot.remoteDevices.state.otherBot'],
+ ['DEVICE_LINK_REMOTE_DISABLED', 'settings.telegramBot.remoteDevices.failure.remoteDisabled'],
+ ['DEVICE_LINK_ACCESS_REVOKED', 'settings.telegramBot.remoteDevices.failure.accessRevoked'],
+ ['DEVICE_LINK_CONTROL_DISABLED', 'settings.telegramBot.remoteDevices.failure.controlDisabled'],
+ ['DEVICE_LINK_NOT_CONNECTED', 'settings.telegramBot.remoteDevices.failure.unreachable'],
+ ['DEVICE_LINK_DEVICE_OFFLINE', 'settings.telegramBot.remoteDevices.failure.unreachable'],
+ ['DEVICE_LINK_TIMEOUT', 'settings.telegramBot.remoteDevices.failure.unreachable'],
+ ['DEVICE_LINK_UNAVAILABLE', 'settings.telegramBot.remoteDevices.failure.unreachable'],
+ ['DEVICE_LINK_STANDBY', 'settings.telegramBot.remoteDevices.failure.unreachable'],
+ ['DEVICE_LINK_VERSION_MISMATCH', 'settings.telegramBot.remoteDevices.state.unsupported'],
+ ])('maps %s without exposing its raw message', (code, expectedKey) => {
+ expect(telegramRemoteFailureKey(ipcError(code, 'raw English must stay out of the toast'))).toBe(
+ expectedKey,
+ );
+ });
+
+ it('uses a localized fallback for unknown IPC codes and non-IPC errors', () => {
+ const fallback = 'settings.telegramBot.remoteDevices.failure.unknown';
+ expect(telegramRemoteFailureKey(ipcError('INTERNAL', 'raw internal failure'))).toBe(fallback);
+ expect(telegramRemoteFailureKey(new Error('raw unstructured failure'))).toBe(fallback);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useTelegramBot.ts b/apps/desktop/src/renderer/hooks/useTelegramBot.ts
index 932aff6546..abcab0426b 100644
--- a/apps/desktop/src/renderer/hooks/useTelegramBot.ts
+++ b/apps/desktop/src/renderer/hooks/useTelegramBot.ts
@@ -18,6 +18,22 @@ interface TelegramBotCache {
let cachedState: TelegramBotCache | null = null;
+/**
+ * 把传输层状态翻成当前语言的失败原因。
+ *
+ * main 层的 `reason` 是诊断原文——既有英文技术串(`network unreachable`)也有硬编码
+ * 中文,直接塞进 toast 会给非中文用户拼出混合语言。稳定分类走 `code` → i18n key;
+ * 只有旧路径/其它渠道没带 code 时才回退 reason(总比空白强)。
+ */
+export function describeTelegramStatusFailure(
+ status: TelegramBotTransportStatus,
+ t: (key: string) => string,
+): string {
+ if (status.kind !== 'error') return t(`settings.telegramBot.status.${status.kind}`);
+ if (status.code) return t(`settings.telegramBot.errorCode.${status.code}`);
+ return status.reason;
+}
+
export interface UseTelegramBotReturn {
token: string;
setToken: (v: string) => void;
@@ -28,9 +44,13 @@ export interface UseTelegramBotReturn {
validationError: string | null;
isSaving: boolean;
isDisconnecting: boolean;
+ /** 上线/下线切换在途(与解绑分开, 两个按钮各自禁用)。 */
+ isTogglingOnline: boolean;
canConnect: boolean;
connect: () => Promise<boolean>;
disconnect: () => Promise<void>;
+ /** 只切轮询, 保留 token 与绑定信息 —— 与 disconnect(清凭证)是两个动作。 */
+ setOnline: (online: boolean) => Promise<void>;
}
/** 个人 Telegram bot 设置卡的状态钩子 — 与 useDiscordBot 同构(token 手填模式)。 */
@@ -47,6 +67,7 @@ export function useTelegramBot(): UseTelegramBotReturn {
const [validationError, setValidationError] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [isDisconnecting, setIsDisconnecting] = useState(false);
+ const [isTogglingOnline, setIsTogglingOnline] = useState(false);
useEffect(() => {
let cancelled = false;
@@ -171,11 +192,53 @@ export function useTelegramBot(): UseTelegramBotReturn {
}
}, [isDisconnecting, t]);
+ const setOnline = useCallback(
+ async (online: boolean) => {
+ if (isTogglingOnline) return;
+ setIsTogglingOnline(true);
+ try {
+ const result = await window.electronAPI.telegramBot.setOnline({ online });
+ setStatus(result.status);
+ // 与 disconnect 的关键差异: 绑定信息一律保留, 不清 owner/botUsername。
+ cachedState = {
+ ownerUserId: cachedState?.ownerUserId ?? '',
+ botUsername: cachedState?.botUsername ?? null,
+ status: result.status,
+ };
+ // IPC 正常 resolve ≠ 切换成功: 上线可能因 token 失效/网络不可达落到 error,
+ // 下线可能因安全存储写不进而保持原样。只有真到达目标态才报成功, 否则用户
+ // 会拿到一个「其实没发生」的确认。
+ const reached = online ? result.status.kind === 'connected' : result.status.kind === 'offline';
+ if (!reached) {
+ toast.error(
+ t('logic.toasts.telegramBotToggleOnlineFailed', {
+ message: describeTelegramStatusFailure(result.status, t),
+ }),
+ );
+ return;
+ }
+ toast.success(
+ online
+ ? t('logic.toasts.telegramBotWentOnline')
+ : t('logic.toasts.telegramBotWentOffline'),
+ );
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.error('setOnline failed:', msg);
+ toast.error(t('logic.toasts.telegramBotToggleOnlineFailed', { message: msg }));
+ } finally {
+ setIsTogglingOnline(false);
+ }
+ },
+ [isTogglingOnline, t],
+ );
+
const canConnect =
BOT_TOKEN_PATTERN.test(token.trim()) &&
OWNER_USER_ID_PATTERN.test(ownerUserId.trim()) &&
!isSaving &&
- !isDisconnecting;
+ !isDisconnecting &&
+ !isTogglingOnline;
return {
token,
@@ -187,8 +250,10 @@ export function useTelegramBot(): UseTelegramBotReturn {
validationError,
isSaving,
isDisconnecting,
+ isTogglingOnline,
canConnect,
connect,
disconnect,
+ setOnline,
};
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5662968fc0..927fc8ebd2 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1880,11 +1880,16 @@
"connecting": "Connecting…",
"connected": "Connected",
"conflict": "In use by another device",
+ "offline": "Offline",
"error": "Connection failed"
},
"connected": {
"heading": "Telegram bot connected",
"note": "DM your bot or @mention it in a group and messages are routed to {{appName}} on this machine; recent group chatter is included as context.",
+ "headingOffline": "Offline on this device",
+ "noteOffline": "Not receiving messages. Your bot token and binding are still saved on this machine — go back online any time.",
+ "headingConflict": "In use by another device",
+ "noteConflict": "Only one device can receive messages for the same bot, and this one keeps contending for it. Take that device offline below to let this one take over, or choose \"Go offline here\" to leave the slot to it.",
"botLabel": "Bot account",
"ownerLabel": "My user ID"
},
@@ -1897,6 +1902,43 @@
"formHint": "The user ID is numeric; DM @userinfobot to look up your own ID.",
"connect": "Connect",
"connectingAction": "Connecting…",
+ "errorCode": {
+ "invalid-token": "Bot token is invalid or was reset — enter it again",
+ "provider-api": "Telegram returned an error — try again shortly",
+ "network": "Network unreachable — can't connect to Telegram",
+ "secret-unavailable": "System secure storage is unavailable, credentials cannot be saved"
+ },
+ "goOffline": "Go offline here",
+ "goingOfflineAction": "Going offline…",
+ "goOnline": "Go online here",
+ "goingOnlineAction": "Going online…",
+ "remoteDevices": {
+ "title": "My other devices",
+ "refresh": "Check again",
+ "hint": "Taking a device offline stops it from receiving messages. Its token and binding stay intact, so it can come back online on its own at any time.",
+ "takeOffline": "Take offline",
+ "state": {
+ "checking": "Checking…",
+ "connected": "Using this bot",
+ "conflict": "Contending for this bot",
+ "offline": "Offline",
+ "connecting": "Connecting…",
+ "idle": "Not set up",
+ "error": "Connection failed",
+ "notConfigured": "No Telegram bot configured",
+ "otherBot": "Bound to a different bot — no conflict",
+ "offlineDevice": "Device offline — can't control it remotely",
+ "unreachable": "Status unavailable",
+ "unsupported": "This device's version can't be taken offline remotely"
+ },
+ "failure": {
+ "remoteDisabled": "Remote control is turned off on that device",
+ "accessRevoked": "That device has revoked this device's access",
+ "controlDisabled": "Control of that device is turned off on this device",
+ "unreachable": "That device is offline or unreachable",
+ "unknown": "The remote request failed. Check the device status and try again"
+ }
+ },
"disconnect": "Unbind",
"disconnectingAction": "Unbinding…",
"disconnectAria": "Unbind Telegram bot",
@@ -7961,6 +8003,12 @@
"telegramBotSaveFailed": "Save failed: {{message}}",
"telegramBotDisconnected": "Telegram bot unbound",
"telegramBotDisconnectFailed": "Unbind failed: {{message}}",
+ "telegramBotWentOffline": "Now offline — your binding is kept",
+ "telegramBotWentOnline": "Back online",
+ "telegramBotToggleOnlineFailed": "Could not switch: {{message}}",
+ "telegramRemoteWentOffline": "That device is now offline",
+ "telegramRemoteUnsupported": "That device's Cindy is too old for remote offline — update it first",
+ "telegramRemoteFailed": "Could not take it offline: {{message}}",
"dingtalkBotConnected": "DingTalk bot connected",
"dingtalkBotConnectFailed": "DingTalk bot connection failed; check credentials, Stream mode, and your network",
"dingtalkBotAuthFailed": "DingTalk rejected the credentials. Confirm that the Client ID and Client Secret belong to the same app",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e81221c9a7..d93ba02d0a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1879,11 +1879,16 @@
"connecting": "接続中…",
"connected": "接続済み",
"conflict": "別のデバイスで使用中",
+ "offline": "オフライン",
"error": "接続に失敗"
},
"connected": {
"heading": "Telegram Bot 接続済み",
"note": "Bot への DM やグループでのメンションは、このマシンの {{appName}} にルーティングされます。グループの直近の会話はコンテキストとして添付されます。",
+ "headingOffline": "このデバイスでオフライン中",
+ "noteOffline": "メッセージの受信を停止しています。Bot Token と連携情報はこのマシンに保持されているため、いつでもオンラインに戻せます。",
+ "headingConflict": "別のデバイスで使用中",
+ "noteConflict": "同じ Bot でメッセージを受信できるデバイスは同時に 1 台だけで、このマシンは取り合いを繰り返しています。下でそのデバイスをオフラインにすればこのマシンが引き継ぎます。譲る場合は「このデバイスをオフライン」を押してください。",
"botLabel": "Bot アカウント",
"ownerLabel": "自分のユーザー ID"
},
@@ -1896,6 +1901,43 @@
"formHint": "ユーザー ID は数字です。@userinfobot に DM すると自分の ID を確認できます。",
"connect": "接続",
"connectingAction": "接続中…",
+ "errorCode": {
+ "invalid-token": "Bot Token が無効か再発行されています。入力し直してください",
+ "provider-api": "Telegram 側でエラーが発生しました。しばらくしてから再試行してください",
+ "network": "ネットワークに到達できず、Telegram に接続できません",
+ "secret-unavailable": "システムの安全なストレージが利用できず、認証情報を保存できません"
+ },
+ "goOffline": "このデバイスをオフライン",
+ "goingOfflineAction": "オフラインにしています…",
+ "goOnline": "このデバイスをオンライン",
+ "goingOnlineAction": "オンラインにしています…",
+ "remoteDevices": {
+ "title": "自分の他のデバイス",
+ "refresh": "再確認",
+ "hint": "デバイスをオフラインにすると、そのデバイスはメッセージを受信しなくなります。Token と連携情報は消えないので、そのデバイス側でいつでもオンラインに戻せます。",
+ "takeOffline": "オフラインにする",
+ "state": {
+ "checking": "確認中…",
+ "connected": "この Bot を使用中",
+ "conflict": "この Bot を取り合い中",
+ "offline": "オフライン",
+ "connecting": "接続中…",
+ "idle": "未設定",
+ "error": "接続に失敗",
+ "notConfigured": "Telegram ボットが未設定",
+ "otherBot": "別の Bot に連携中(競合なし)",
+ "offlineDevice": "デバイスがオフラインのため操作できません",
+ "unreachable": "状態を取得できません",
+ "unsupported": "このデバイスのバージョンではリモートでオフラインにできません"
+ },
+ "failure": {
+ "remoteDisabled": "そのデバイスでリモート操作が無効になっています",
+ "accessRevoked": "そのデバイスがこのデバイスからのアクセスを取り消しました",
+ "controlDisabled": "このデバイスでは、そのデバイスの操作が無効になっています",
+ "unreachable": "そのデバイスはオフラインか、到達できません",
+ "unknown": "リモート操作に失敗しました。デバイスの状態を確認して再試行してください"
+ }
+ },
"disconnect": "連携解除",
"disconnectingAction": "解除中…",
"disconnectAria": "Telegram ボットの連携を解除",
@@ -7949,6 +7991,12 @@
"telegramBotSaveFailed": "保存に失敗しました:{{message}}",
"telegramBotDisconnected": "Telegram ボットの連携を解除しました",
"telegramBotDisconnectFailed": "連携解除に失敗しました:{{message}}",
+ "telegramBotWentOffline": "オフラインにしました(連携情報は保持されます)",
+ "telegramBotWentOnline": "オンラインにしました",
+ "telegramBotToggleOnlineFailed": "切り替えに失敗しました:{{message}}",
+ "telegramRemoteWentOffline": "そのデバイスをオフラインにしました",
+ "telegramRemoteUnsupported": "そのデバイスの Cindy はリモートオフラインに未対応です。先に更新してください",
+ "telegramRemoteFailed": "リモートでオフラインにできませんでした:{{message}}",
"dingtalkBotConnected": "DingTalk ボットに接続しました",
"dingtalkBotConnectFailed": "DingTalk ボットに接続できません。認証情報、Stream モード、ネットワークを確認してください",
"dingtalkBotAuthFailed": "DingTalk が認証情報を拒否しました。Client ID と Client Secret が同じアプリのものか確認してください",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f389a0a6c9..6cf8aa35bb 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1879,11 +1879,16 @@
"connecting": "연결 중…",
"connected": "연결됨",
"conflict": "다른 기기에서 사용 중",
+ "offline": "오프라인",
"error": "연결 실패"
},
"connected": {
"heading": "Telegram 봇 연결됨",
"note": "봇에게 DM을 보내거나 그룹에서 멘션하면 이 기기의 {{appName}}로 전달됩니다. 그룹의 최근 대화는 컨텍스트로 함께 전달됩니다.",
+ "headingOffline": "이 기기에서 오프라인",
+ "noteOffline": "메시지 수신을 중지했습니다. Bot Token과 연동 정보는 이 기기에 그대로 남아 있어 언제든 다시 온라인으로 전환할 수 있습니다.",
+ "headingConflict": "다른 기기에서 사용 중",
+ "noteConflict": "같은 봇으로 메시지를 받을 수 있는 기기는 한 번에 하나뿐이며, 이 기기가 계속 경쟁하고 있습니다. 아래에서 그 기기를 오프라인으로 만들면 이 기기가 이어받습니다. 넘겨주려면 「이 기기 오프라인」을 누르세요.",
"botLabel": "봇 계정",
"ownerLabel": "내 사용자 ID"
},
@@ -1896,6 +1901,43 @@
"formHint": "사용자 ID는 숫자입니다. @userinfobot에게 DM을 보내면 자신의 ID를 확인할 수 있습니다.",
"connect": "연결",
"connectingAction": "연결 중…",
+ "errorCode": {
+ "invalid-token": "Bot Token이 유효하지 않거나 재발급되었습니다. 다시 입력하세요",
+ "provider-api": "Telegram에서 오류를 반환했습니다. 잠시 후 다시 시도하세요",
+ "network": "네트워크에 연결할 수 없어 Telegram에 접속하지 못했습니다",
+ "secret-unavailable": "시스템 보안 저장소를 사용할 수 없어 자격 증명을 저장할 수 없습니다"
+ },
+ "goOffline": "이 기기 오프라인",
+ "goingOfflineAction": "전환 중…",
+ "goOnline": "이 기기 온라인",
+ "goingOnlineAction": "전환 중…",
+ "remoteDevices": {
+ "title": "내 다른 기기",
+ "refresh": "다시 확인",
+ "hint": "기기를 오프라인으로 만들면 해당 기기는 메시지를 받지 않습니다. 토큰과 연동 정보는 지워지지 않으므로 그 기기에서 언제든 다시 온라인으로 전환할 수 있습니다.",
+ "takeOffline": "오프라인으로",
+ "state": {
+ "checking": "확인 중…",
+ "connected": "이 봇을 사용 중",
+ "conflict": "이 봇을 두고 경쟁 중",
+ "offline": "오프라인",
+ "connecting": "연결 중…",
+ "idle": "설정 안 됨",
+ "error": "연결 실패",
+ "notConfigured": "Telegram 봇이 설정되지 않음",
+ "otherBot": "다른 봇에 연동됨 (충돌 없음)",
+ "offlineDevice": "기기가 오프라인이라 조작할 수 없음",
+ "unreachable": "상태를 가져올 수 없음",
+ "unsupported": "이 기기의 버전은 원격 오프라인을 지원하지 않음"
+ },
+ "failure": {
+ "remoteDisabled": "해당 기기에서 원격 제어가 꺼져 있습니다",
+ "accessRevoked": "해당 기기에서 이 기기의 접근 권한을 취소했습니다",
+ "controlDisabled": "이 기기에서 해당 기기 제어가 꺼져 있습니다",
+ "unreachable": "해당 기기가 오프라인이거나 연결할 수 없습니다",
+ "unknown": "원격 요청에 실패했습니다. 기기 상태를 확인한 후 다시 시도하세요"
+ }
+ },
"disconnect": "연동 해제",
"disconnectingAction": "해제 중…",
"disconnectAria": "Telegram 봇 연동 해제",
@@ -7949,6 +7991,12 @@
"telegramBotSaveFailed": "저장 실패: {{message}}",
"telegramBotDisconnected": "Telegram 봇 연동이 해제됨",
"telegramBotDisconnectFailed": "연동 해제 실패: {{message}}",
+ "telegramBotWentOffline": "오프라인으로 전환됨 (연동 정보는 유지)",
+ "telegramBotWentOnline": "온라인으로 전환됨",
+ "telegramBotToggleOnlineFailed": "전환 실패: {{message}}",
+ "telegramRemoteWentOffline": "해당 기기를 오프라인으로 전환했습니다",
+ "telegramRemoteUnsupported": "해당 기기의 Cindy 버전은 원격 오프라인을 지원하지 않습니다. 먼저 업데이트하세요",
+ "telegramRemoteFailed": "원격 오프라인 전환 실패: {{message}}",
"dingtalkBotConnected": "DingTalk 봇이 연결됨",
"dingtalkBotConnectFailed": "DingTalk 봇 연결 실패. 자격 증명, Stream 모드, 네트워크를 확인하세요",
"dingtalkBotAuthFailed": "DingTalk에서 자격 증명을 거부했습니다. Client ID와 Client Secret이 동일한 앱의 것인지 확인하세요",
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 6e05d1e37e..ef19a88f89 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1879,11 +1879,16 @@
"connecting": "连接中…",
"connected": "已连接",
"conflict": "已被另一台设备使用",
+ "offline": "已下线",
"error": "连接失败"
},
"connected": {
"heading": "已连接 Telegram Bot",
"note": "私聊 Bot 或在群里 @ 它,消息会路由到本机的 {{appName}};群里最近的消息会作为上下文一起带上。",
+ "headingOffline": "已在这台设备下线",
+ "noteOffline": "已停止接收消息。Bot Token 和绑定信息仍保留在本机,随时可以重新上线。",
+ "headingConflict": "已被另一台设备使用",
+ "noteConflict": "同一个 Bot 同时只能有一台设备接收消息,本机正在反复争抢。可以在下方让那台设备下线、由本机接管;或者点「本机下线」把位置让给它。",
"botLabel": "Bot 账号",
"ownerLabel": "我的用户 ID"
},
@@ -1896,6 +1901,43 @@
"formHint": "用户 ID 是纯数字;私聊 @userinfobot 可以查到自己的 ID。",
"connect": "连接",
"connectingAction": "连接中…",
+ "errorCode": {
+ "invalid-token": "Bot Token 无效或已被重置,请重新填写",
+ "provider-api": "Telegram 服务返回错误,请稍后重试",
+ "network": "网络不可达,连不上 Telegram",
+ "secret-unavailable": "系统安全存储不可用,凭证无法保存"
+ },
+ "goOffline": "本机下线",
+ "goingOfflineAction": "下线中…",
+ "goOnline": "本机上线",
+ "goingOnlineAction": "上线中…",
+ "remoteDevices": {
+ "title": "我的其他设备",
+ "refresh": "重新检查",
+ "hint": "让某台设备下线后,它就不再接收消息。它的 Token 和绑定不会被清除,之后在那台设备上随时能自己再上线。",
+ "takeOffline": "让它下线",
+ "state": {
+ "checking": "检查中…",
+ "connected": "正在使用这个 Bot",
+ "conflict": "正在争抢这个 Bot",
+ "offline": "已下线",
+ "connecting": "连接中…",
+ "idle": "未配置",
+ "error": "连接失败",
+ "notConfigured": "未配置 Telegram 机器人",
+ "otherBot": "绑的是另一个 Bot,不冲突",
+ "offlineDevice": "设备离线,无法远程操作",
+ "unreachable": "查不到状态",
+ "unsupported": "该设备版本不支持远程下线"
+ },
+ "failure": {
+ "remoteDisabled": "该设备已关闭远程控制",
+ "accessRevoked": "该设备已撤销本机的访问权限",
+ "controlDisabled": "本机已关闭对该设备的控制",
+ "unreachable": "该设备已离线或暂时无法连接",
+ "unknown": "远程请求失败,请检查设备状态后重试"
+ }
+ },
"disconnect": "解绑",
"disconnectingAction": "解绑中…",
"disconnectAria": "解绑 Telegram 机器人",
@@ -7949,6 +7991,12 @@
"telegramBotSaveFailed": "保存失败:{{message}}",
"telegramBotDisconnected": "已解绑 Telegram 机器人",
"telegramBotDisconnectFailed": "解绑失败:{{message}}",
+ "telegramBotWentOffline": "已下线,绑定信息已保留",
+ "telegramBotWentOnline": "已上线",
+ "telegramBotToggleOnlineFailed": "切换失败:{{message}}",
+ "telegramRemoteWentOffline": "已让该设备下线",
+ "telegramRemoteUnsupported": "该设备的 Cindy 版本还不支持远程下线,需要先更新",
+ "telegramRemoteFailed": "远程下线失败:{{message}}",
"dingtalkBotConnected": "钉钉机器人已连接",
"dingtalkBotConnectFailed": "钉钉机器人连接失败,请检查凭证、Stream 模式和网络",
"dingtalkBotAuthFailed": "钉钉未通过凭证校验,请确认 Client ID 和 Client Secret 来自同一个应用",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index c6fd8ae06c..f626aad69a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -416,7 +416,12 @@ type TelegramBotTransportStatus =
| { kind: 'connecting' }
| { kind: 'connected'; appId: string }
| { kind: 'conflict'; appId: string }
- | { kind: 'error'; reason: string };
+ /** 凭证保留、用户主动下线(不轮询); 与 idle=未配置 严格区分。 */
+ | { kind: 'offline'; appId: string }
+ | { kind: 'error'; reason: string; code?: TelegramBotErrorCode };
+
+/** 稳定错误分类;renderer 据此取 i18n 文案,不直接展示 main 层 reason。 */
+type TelegramBotErrorCode = 'invalid-token' | 'provider-api' | 'network' | 'secret-unavailable';
type DingTalkBotTransportStatus = DiscordBotTransportStatus;
type WecomBotTransportStatus =
@@ -1807,6 +1812,10 @@ interface ElectronAPI {
disconnect: () => Promise<{
status: TelegramBotTransportStatus;
}>;
+ /** 上线/下线(保留 token 与绑定信息, 只切轮询)。 */
+ setOnline: (payload: { online: boolean }) => Promise<{
+ status: TelegramBotTransportStatus;
+ }>;
checkSessionAuth: () => Promise<DiscordBotSessionAuthCheckResult>;
getBehavior: () => Promise<TelegramBotBehavior>;
setBehavior: (patch: Partial<TelegramBotBehavior>) => Promise<TelegramBotBehavior>;
diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.ts
index d215246b19..e5133472a7 100644
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@ -15,6 +15,8 @@ import {
DL_VOICE_CREDENTIAL_SYNC_CHANNEL,
DL_VOICE_DICTIONARY_LEARNING_CHANNEL,
DL_HISTORY_MESSAGES_CHANNEL,
+ DL_TELEGRAM_STATUS_CHANNEL,
+ DL_TELEGRAM_SET_ONLINE_CHANNEL,
} from '../allowlist.js';
import { SESSION_ACTIVITY_CHANNEL } from '../topics.js';
@@ -215,6 +217,26 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {
expect(DL_VOICE_DICTIONARY_LEARNING_CHANNEL).toBe('device-link:voice:dictionary-learning');
});
+ it('放行个人 Telegram bot 的跨设备上下线(窄口径例外),但本地那条 IPC 仍绝不放行', () => {
+ // 放行的是两条 device-link 专用通道:被控端 dispatch 拦截执行, 只切轮询。
+ expect(REMOTE_INVOKE_ALLOWLIST.has(DL_TELEGRAM_STATUS_CHANNEL)).toBe(true);
+ expect(REMOTE_INVOKE_ALLOWLIST.has(DL_TELEGRAM_SET_ONLINE_CHANNEL)).toBe(true);
+ // 本地 IM IPC 一律不得入表:它们在 im/host.ts 统一挂了
+ // assertTrustedAppRendererEvent(只认真实 sender), 是有意拦住 IM 凭证/配置面的
+ // 闸门。未来若有人图省事把 telegramBot:* 加进来, 这条直接红 —— 尤其
+ // disconnect / set-config 会清凭证或换 token, 远程绝不该碰。
+ for (const ch of [
+ 'telegramBot:set-online',
+ 'telegramBot:disconnect',
+ 'telegramBot:set-config',
+ 'telegramBot:get-status',
+ 'discordBot:set-config',
+ 'feishuBot:set-config',
+ ]) {
+ expect(REMOTE_INVOKE_ALLOWLIST.has(ch)).toBe(false);
+ }
+ });
+
it('绝不放行:本机副作用 / 全局设置写 / 账号密钥 / 裸写库 / 窗口 UI', () => {
for (const ch of [
'shell:open-path',
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 60903df952..c15e8007ce 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -77,6 +77,38 @@ export const DL_VOICE_TRANSCRIBE_CHANNEL = 'device-link:voice:transcribe';
*/
export const DL_VOICE_CREDENTIAL_SYNC_CHANNEL = 'device-link:voice:credential-sync';
+/**
+ * 个人 Telegram bot 的跨设备上下线 channel(控制端 → 被控端)。
+ *
+ * 背景:个人 Telegram bot 是 BYO token 直连 Bot API 的 getUpdates 长轮询,
+ * 同一 token 同时只有一台设备能收消息(Telegram 侧 409),而两台设备之间**没有
+ * 任何通信通道**。换机器时想让另一端让位, 除了人肉去那台机器操作, 没有别的办法
+ * —— 这两个 channel 就是补这个缺口。
+ *
+ * 为什么不直接把 telegramBot:set-online 放进 allowlist: IM 的所有 IPC 在
+ * host.ipc.handle 里统一包了 assertTrustedAppRendererEvent(见 im/host.ts),
+ * 只认 Electron 持有的真实 sender; 而 dispatchLocalInvoke 用的是合成 event
+ * (sender: undefined), 必然判定不可信。那道闸是有意拦着的(IM 凭证/配置面全算
+ * 敏感面), 不该为远程下线放宽 —— 故与 media:fetch / voice:* 同款: 不是
+ * ipcMain handler, 由被控端 dispatch 在通用路由前拦截执行。
+ *
+ * 准入论证(对照本文件顶部三条判据):
+ * 1. 不依赖 event.sender / 窗口;
+ * 2. 无本机 UI / shell / 对话框副作用;
+ * 3. 语义只在被控端执行才正确 —— 要停的正是那台机器的轮询。
+ * 与"永不放行"的两类刻意划清界限:**不碰凭证**(token / owner id 不读不写不
+ * 外传, 下线只写一个布尔标志、解绑仍然只能本机操作), 也**不是通用设置写**
+ * (单一用途、只切轮询, 不是 *_SET 那种任意配置面)。
+ *
+ * status 是只读投影, 且刻意不含 ownerUserId —— 控制端只需要知道"哪台在用、
+ * 用的哪个 bot", 没有理由让 Telegram 用户 id 过网线。
+ *
+ * 老被控端不识别 → CHANNEL_NOT_ALLOWED, 控制端据此显示「该设备版本不支持」
+ * 而不是静默失败。
+ */
+export const DL_TELEGRAM_STATUS_CHANNEL = 'device-link:telegram:status';
+export const DL_TELEGRAM_SET_ONLINE_CHANNEL = 'device-link:telegram:set-online';
+
/**
* 手机端语音词典学习回写 channel。
*
@@ -430,6 +462,10 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
'worktree:create',
'worktree:discard-precreated',
'worktree:removal-preview',
+ // —— 个人 Telegram bot 跨设备上下线(准入论证见上方 DL_TELEGRAM_* 常量注释)——
+ // 两条都由被控端 dispatch 拦截执行, 不是 ipcMain handler。
+ DL_TELEGRAM_STATUS_CHANNEL,
+ DL_TELEGRAM_SET_ONLINE_CHANNEL,
];
/** 远程可调用的 invoke channel 全集(被控端 dispatch 前的权威校验依据) */
diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
index 3ee525513a..122c1ae7a2 100644
--- a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
@@ -63,6 +63,9 @@ function makeHost() {
isAvailable: () => true,
},
ipc: {
+ throwIpcError: (code, message) => {
+ throw new Error(`[${code}] ${message}`);
+ },
handle: (channel, handler) => void handlers.set(channel, handler),
broadcast: (channel, payload) =>
void broadcasts.push({ channel, payload }),
diff --git a/packages/lizi-im/src/discord/__tests__/components.test.ts b/packages/lizi-im/src/discord/__tests__/components.test.ts
index 4dc7aa72de..64e245b2e7 100644
--- a/packages/lizi-im/src/discord/__tests__/components.test.ts
+++ b/packages/lizi-im/src/discord/__tests__/components.test.ts
@@ -434,7 +434,13 @@ function makeHost(opts: { readSecret?: (key: string) => string | null } = {}): I
remove: () => {},
isAvailable: () => true,
},
- ipc: { handle: () => {}, broadcast: () => {} },
+ ipc: {
+ throwIpcError: (code, message) => {
+ throw new Error(`[${code}] ${message}`);
+ },
+ handle: () => {},
+ broadcast: () => {},
+ },
httpPostForm: async () => ({ status: 200, body: {} }),
createLogger: () => ({
info: () => {},
diff --git a/packages/lizi-im/src/discord/__tests__/inbound.test.ts b/packages/lizi-im/src/discord/__tests__/inbound.test.ts
index 2fa2f55af0..b46a22b049 100644
--- a/packages/lizi-im/src/discord/__tests__/inbound.test.ts
+++ b/packages/lizi-im/src/discord/__tests__/inbound.test.ts
@@ -1742,6 +1742,9 @@ function makeHost(options: {
isAvailable: options.isAvailable ?? (() => true),
},
ipc: {
+ throwIpcError: (code, message) => {
+ throw new Error(`[${code}] ${message}`);
+ },
handle: (channel, handler) => {
handlers.set(channel, handler);
},
diff --git a/packages/lizi-im/src/discord/__tests__/outbound.test.ts b/packages/lizi-im/src/discord/__tests__/outbound.test.ts
index 11d833f375..c20f786a93 100644
--- a/packages/lizi-im/src/discord/__tests__/outbound.test.ts
+++ b/packages/lizi-im/src/discord/__tests__/outbound.test.ts
@@ -229,7 +229,13 @@ function makeHost(): IMHost {
remove: () => {},
isAvailable: () => true,
},
- ipc: { handle: () => {}, broadcast: () => {} },
+ ipc: {
+ throwIpcError: (code, message) => {
+ throw new Error(`[${code}] ${message}`);
+ },
+ handle: () => {},
+ broadcast: () => {},
+ },
httpPostForm: async () => ({ status: 200, body: {} }),
createLogger: () => ({
info: () => {},
diff --git a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
index 30078b73fc..bd607a5547 100644
--- a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts
@@ -88,6 +88,9 @@ const host = {
remove: () => {},
},
ipc: {
+ throwIpcError: (code: 'INVALID_PARAMS', message: string) => {
+ throw new Error(`[${code}] ${message}`);
+ },
handle: (channel: string, handler: IpcHandler) => {
handlers.set(channel, handler);
},
diff --git a/packages/lizi-im/src/feishu/__tests__/mediaStore.test.ts b/packages/lizi-im/src/feishu/__tests__/mediaStore.test.ts
index 93d6c773cf..742355c89d 100644
--- a/packages/lizi-im/src/feishu/__tests__/mediaStore.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/mediaStore.test.ts
@@ -55,7 +55,13 @@ function wireHost(mediaDir: string, media?: IMHostMediaCache): void {
read: () => null,
remove: () => {},
},
- ipc: { handle: () => {}, broadcast: () => {} },
+ ipc: {
+ throwIpcError: (code: 'INVALID_PARAMS', message: string) => {
+ throw new Error(`[${code}] ${message}`);
+ },
+ handle: () => {},
+ broadcast: () => {},
+ },
httpPostForm: async () => ({ status: 200, body: {} }),
} as unknown as IMHost;
setHost(host, defaultLogger('im:feishu:test'));
diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.ts
index 74f116d1bf..e8f0f28910 100644
--- a/packages/lizi-im/src/index.ts
+++ b/packages/lizi-im/src/index.ts
@@ -28,6 +28,8 @@ export type {
IMMessageEvent,
IMCardActionEvent,
IMStatus,
+ IMErrorCode,
+ IMSecretReadResult,
InteractiveCardButton,
InteractiveCardSpec,
StreamingTextHandle,
diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
index 0aadc8fcb9..e77caa5cf9 100644
--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
@@ -104,10 +104,18 @@ function createHost(tmpDir: string): { host: IMHost; broadcasts: unknown[]; secr
secrets: {
write: (name, value) => (secrets.set(name, value), true),
read: (name) => secrets.get(name) ?? null,
+ readResult: (name) =>
+ secrets.has(name)
+ ? { kind: 'value', value: secrets.get(name)! }
+ : { kind: 'missing' },
remove: (name) => void secrets.delete(name),
isAvailable: () => true,
},
ipc: {
+ throwIpcError: (code, message) => {
+ const error = Object.assign(new Error(`[${code}] ${message}`), { code });
+ throw error;
+ },
handle: (channel, handler) => void handlers.set(channel, handler),
broadcast: (_channel, payload) => void broadcasts.push(payload),
},
@@ -211,6 +219,49 @@ describe('TelegramIM', () => {
expect(ctx.secrets.has('telegram-bot-token')).toBe(false);
});
+ it('set-config 连接失败且旧 secret 回滚写失败: 落下线闩锁, 重启不得用混合配置上线', async () => {
+ await im.dispose();
+ const oldToken = '999:old-token-abcdefghijklmnop';
+ const newToken = '888:new-token-abcdefghijklmnop';
+ const oldApi = createFakeApi();
+ const rejectedApi = createFakeApi({
+ getMeError: new TelegramApiError('getMe', 401, 'Unauthorized'),
+ });
+ im = new TelegramIM(ctx.host, {
+ apiFactory: (token) => (token === oldToken ? oldApi : rejectedApi),
+ });
+ im.registerIpc();
+ const handler = ctx.handlers.get('telegramBot:set-config')!;
+ await handler({ token: oldToken, ownerUserId: OWNER_ID });
+ expect(im.getStatus().kind).toBe('connected');
+
+ const originalWrite = ctx.host.secrets.write;
+ ctx.host.secrets.write = (name, value) => {
+ // 新 token 已经落盘;模拟连接失败后恢复旧 token 时安全存储拒写。
+ if (name === 'telegram-bot-token' && value === oldToken) return false;
+ return originalWrite(name, value);
+ };
+ const result = (await handler({ token: newToken, ownerUserId: '222' })) as {
+ status: { kind: string };
+ saveErrorStatus?: { kind: string };
+ };
+
+ expect(result.status.kind).toBe('error');
+ expect(result.saveErrorStatus?.kind).toBe('error');
+ expect(ctx.secrets.get('telegram-bot-token')).toBe(newToken);
+ expect(ctx.secrets.get('telegram-bot-offline')).toBe('1');
+ ctx.host.secrets.write = originalWrite;
+
+ // 模拟重启:即使磁盘仍是未完成回滚的新 token,也只能停在 offline,零联网。
+ await im.dispose();
+ const rebootApi = createFakeApi();
+ const rebooted = new TelegramIM(ctx.host, { apiFactory: () => rebootApi });
+ await rebooted.init();
+ expect(rebooted.getStatus().kind).toBe('offline');
+ expect(rebootApi.calls).toHaveLength(0);
+ await rebooted.dispose();
+ });
+
it('私聊: 非 owner 忽略, owner 消息进 onMessage', async () => {
const events: IMMessageEvent[] = [];
im.onMessage((e) => events.push(e));
@@ -456,6 +507,392 @@ describe('TelegramIM', () => {
});
});
+ it('set-online:false → offline, 停止轮询但保留 token/owner/offset', async () => {
+ await connect();
+ await vi.waitFor(() => {
+ expect(api.calls.some((c) => c.method === 'getUpdates')).toBe(true);
+ });
+ // 先让游标前进一格, 验证下线不会把它一并清掉。
+ api.pushUpdates([privateMessage('hi', Number(OWNER_ID), 7)]);
+ await vi.waitFor(() => {
+ expect(ctx.secrets.get('telegram-updates-offset')).toBeDefined();
+ });
+ const offsetBeforeOffline = ctx.secrets.get('telegram-updates-offset');
+
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+
+ expect(im.getStatus()).toEqual({ kind: 'offline', appId: String(BOT.id) });
+ expect(ctx.secrets.get('telegram-bot-offline')).toBe('1');
+ // 解绑才清凭证; 下线只是让位, 绑定信息必须原样留着。
+ expect(ctx.secrets.get('telegram-bot-token')).toBe('999:secret-token-abcdefghijk');
+ expect(ctx.secrets.get('telegram-owner-user-id')).toBe(OWNER_ID);
+ expect(ctx.secrets.get('telegram-updates-offset')).toBe(offsetBeforeOffline);
+
+ // 轮询确已停: 之后不再产生新的 getUpdates 调用。
+ const pollsAtOffline = api.calls.filter((c) => c.method === 'getUpdates').length;
+ await new Promise((r) => setTimeout(r, 50));
+ expect(api.calls.filter((c) => c.method === 'getUpdates').length).toBe(pollsAtOffline);
+ });
+
+ it('下线后立即上线重放同一 update: 旧世代收尾不得移除新任务的游标低水位', async () => {
+ const events: IMMessageEvent[] = [];
+ im.onMessage((event) => events.push(event));
+ await connect();
+
+ let releaseOldDownload!: () => void;
+ let releaseReplayDownload!: () => void;
+ const oldDownload = new Promise<void>((resolve) => (releaseOldDownload = resolve));
+ const replayDownload = new Promise<void>((resolve) => (releaseReplayDownload = resolve));
+ let getFileCalls = 0;
+ const originalCall = api.call.bind(api);
+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
+ if (method === 'getFile') {
+ getFileCalls += 1;
+ await (getFileCalls === 1 ? oldDownload : replayDownload);
+ }
+ return originalCall(method, params, signal);
+ }) as typeof api.call;
+ const attachment: TgUpdate = {
+ update_id: 50,
+ message: {
+ message_id: 50,
+ from: { id: 111, is_bot: false, first_name: 'U' },
+ chat: { id: 111, type: 'private' },
+ date: 1_753_000_000,
+ caption: '慢附件',
+ photo: [{ file_id: 'slow', file_unique_id: 'slow-u', width: 10, height: 10 }],
+ },
+ };
+
+ api.pushUpdates([attachment]);
+ await vi.waitFor(() => expect(getFileCalls).toBe(1));
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+ await ctx.handlers.get('telegramBot:set-online')!({ online: true });
+ api.pushUpdates([attachment]);
+
+ // 同 chat 的重放排在旧任务后;旧任务一收口,重放开始并继续悬在下载中。
+ releaseOldDownload();
+ await vi.waitFor(() => expect(getFileCalls).toBe(2));
+ // 另一 chat 的后续 update 收口会尝试补写游标。先等它确实处理完成,再断言
+ // 游标仍不能越过仍在途的重放 50(避免只读到上一个批次留下的旧值)。
+ api.pushUpdates([
+ groupMessage({ text: 'other chat', fromId: 111, messageId: 51, mentionBot: true }),
+ ]);
+ await vi.waitFor(() => expect(events).toHaveLength(1));
+ expect(events[0].text).toBe('other chat');
+ expect(ctx.secrets.get('telegram-updates-offset')).toBe(`${BOT.id}:50`);
+
+ releaseReplayDownload();
+ await vi.waitFor(() => expect(events).toHaveLength(2));
+ await vi.waitFor(() => {
+ expect(ctx.secrets.get('telegram-updates-offset')).toBe(`${BOT.id}:52`);
+ });
+ });
+
+ it('set-online 畸形 payload 一律报错且不产生上下线副作用', async () => {
+ await connect();
+ await vi.waitFor(() => expect(api.calls.some((c) => c.method === 'getUpdates')).toBe(true));
+ const handler = ctx.handlers.get('telegramBot:set-online')!;
+
+ for (const bad of [
+ undefined,
+ null,
+ true,
+ 'false',
+ [],
+ {},
+ { online: 'false' },
+ { online: 0 },
+ { online: null },
+ ]) {
+ await expect(
+ handler(bad),
+ `payload ${JSON.stringify(bad) ?? 'undefined'} 应被拒绝`,
+ ).rejects.toMatchObject({
+ code: 'INVALID_PARAMS',
+ message: expect.stringMatching(/^\[INVALID_PARAMS\]/),
+ });
+ expect(im.getStatus().kind).toBe('connected');
+ expect(ctx.secrets.has('telegram-bot-offline')).toBe(false);
+ }
+
+ // 轮询仍在继续,证明畸形输入没有暗中走到 goOffline。
+ const pollsBefore = api.calls.filter((c) => c.method === 'getUpdates').length;
+ api.pushUpdates([privateMessage('still online', Number(OWNER_ID), 23)]);
+ await vi.waitFor(() => {
+ expect(api.calls.filter((c) => c.method === 'getUpdates').length).toBeGreaterThan(pollsBefore);
+ });
+ });
+
+ it('下线标志写盘失败 → 报错且**不停轮询**(不留会自己复活的假下线)', async () => {
+ await connect();
+ await vi.waitFor(() => {
+ expect(api.calls.some((c) => c.method === 'getUpdates')).toBe(true);
+ });
+ // 模拟 safeStorage 写失败(Linux 无 keychain / 磁盘写不进)。
+ const originalWrite = ctx.host.secrets.write;
+ ctx.host.secrets.write = (name, value) =>
+ name === 'telegram-bot-offline' ? false : originalWrite(name, value);
+
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+
+ expect(im.getStatus().kind).toBe('error');
+ expect(ctx.secrets.has('telegram-bot-offline')).toBe(false);
+ // 关键: 轮询仍在跑 —— 用户看到明确失败, 而不是"看着下线了、重启又上来抢"。
+ const pollsBefore = api.calls.filter((c) => c.method === 'getUpdates').length;
+ api.pushUpdates([privateMessage('still here', Number(OWNER_ID), 21)]);
+ await vi.waitFor(() => {
+ expect(api.calls.filter((c) => c.method === 'getUpdates').length).toBeGreaterThan(
+ pollsBefore,
+ );
+ });
+ ctx.host.secrets.write = originalWrite;
+ });
+
+ it('存储在 remove→read 窗口读取失败: isAvailable 仍为 true 也必须 fail closed', async () => {
+ await connect();
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+ // remove 看似成功(不抛), 但紧接着单文件读取失败;此时 isAvailable 仍为 true。
+ // 若把"读不到"当成"已删除", 删除失败就被静默放过: 用户看到已上线,
+ // 重启后存储恢复、标志还在, 又被打回 offline。
+ const originalRemove = ctx.host.secrets.remove;
+ const originalReadResult = ctx.host.secrets.readResult!;
+ ctx.host.secrets.remove = (name) => {
+ if (name !== 'telegram-bot-offline') originalRemove(name);
+ if (name === 'telegram-bot-offline') {
+ ctx.host.secrets.readResult = (key) =>
+ key === 'telegram-bot-offline' ? { kind: 'error' } : originalReadResult(key);
+ }
+ };
+
+ await ctx.handlers.get('telegramBot:set-online')!({ online: true });
+
+ expect(im.getStatus().kind).toBe('error');
+ // 标志确实还在盘上 —— 证明"读不出来"时放行会是真的错。
+ ctx.host.secrets.readResult = originalReadResult;
+ expect(ctx.secrets.get('telegram-bot-offline')).toBe('1');
+ ctx.host.secrets.remove = originalRemove;
+ });
+
+ it('init 读取下线标志失败时不联网, 不把失败误判成标志缺失', async () => {
+ ctx.secrets.set('telegram-bot-token', '999:secret-token-abcdefghijk');
+ const originalReadResult = ctx.host.secrets.readResult!;
+ ctx.host.secrets.readResult = (name) =>
+ name === 'telegram-bot-offline' ? { kind: 'error' } : originalReadResult(name);
+
+ await im.init();
+
+ expect(im.getStatus().kind).toBe('error');
+ expect(api.calls).toHaveLength(0);
+ });
+
+ it('轮询中读取 token 失败时下线报错, 不误报 idle 且不停止轮询', async () => {
+ await connect();
+ await vi.waitFor(() => expect(api.calls.some((c) => c.method === 'getUpdates')).toBe(true));
+ const originalReadResult = ctx.host.secrets.readResult!;
+ ctx.host.secrets.readResult = (name) =>
+ name === 'telegram-bot-token' ? { kind: 'error' } : originalReadResult(name);
+
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+
+ expect(im.getStatus().kind).toBe('error');
+ expect(ctx.secrets.has('telegram-bot-offline')).toBe(false);
+ const pollsBefore = api.calls.filter((c) => c.method === 'getUpdates').length;
+ api.pushUpdates([privateMessage('still polling', Number(OWNER_ID), 22)]);
+ await vi.waitFor(() => {
+ expect(api.calls.filter((c) => c.method === 'getUpdates').length).toBeGreaterThan(pollsBefore);
+ });
+ });
+
+ it('下线标志删不掉时上线要报错, 不能假装已上线(重启会打回 offline)', async () => {
+ await connect();
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+ // 模拟 remove 失败(文件锁/权限/磁盘错误 —— 真实实现吞掉异常且无返回值)。
+ const originalRemove = ctx.host.secrets.remove;
+ ctx.host.secrets.remove = (name) => {
+ if (name !== 'telegram-bot-offline') originalRemove(name);
+ };
+
+ await ctx.handlers.get('telegramBot:set-online')!({ online: true });
+
+ // 标志还在 → 重启会回到 offline, 所以此刻绝不能显示成已上线。
+ expect(ctx.secrets.get('telegram-bot-offline')).toBe('1');
+ expect(im.getStatus().kind).toBe('error');
+ ctx.host.secrets.remove = originalRemove;
+ });
+
+ it('安全存储不可用时下线报错, 不会误判成「未配置」而放任轮询继续', async () => {
+ await connect();
+ await vi.waitFor(() => {
+ expect(api.calls.some((c) => c.method === 'getUpdates')).toBe(true);
+ });
+ const originalAvailable = ctx.host.secrets.isAvailable;
+ ctx.host.secrets.isAvailable = () => false;
+
+ await im.goOffline();
+
+ // 关键: 不是 idle。idle 会让设置页显示"未配置"、而轮询其实还在跑。
+ expect(im.getStatus().kind).toBe('error');
+ ctx.host.secrets.isAvailable = originalAvailable;
+ });
+
+ it('getMe 在途时被下线: 连接结果作废, 不得写 connected、不得起轮询', async () => {
+ // 复现远程下线的真实窗口: 目标机正在 connect 等 getMe, 另一台设备把它下线。
+ // 控制端已收到「已下线」, 这里若无条件写回 connected 就会回来继续抢同一个 bot。
+ ctx.secrets.set('telegram-bot-token', '999:secret-token-abcdefghijk');
+ ctx.secrets.set('telegram-owner-user-id', OWNER_ID);
+ let releaseGetMe: (() => void) | null = null;
+ const slowApi = createFakeApi();
+ const originalCall = slowApi.call.bind(slowApi);
+ slowApi.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
+ if (method === 'getMe') {
+ await new Promise<void>((resolve) => {
+ releaseGetMe = resolve;
+ });
+ }
+ return originalCall(method, params, signal);
+ }) as typeof slowApi.call;
+ const slowIm = new TelegramIM(ctx.host, { apiFactory: () => slowApi });
+ slowIm.registerIpc();
+
+ const connecting = slowIm.init();
+ await vi.waitFor(() => expect(releaseGetMe).not.toBeNull());
+ // getMe 还挂着 —— 此刻下线
+ await slowIm.goOffline();
+ releaseGetMe!();
+ await connecting;
+
+ expect(slowIm.getStatus().kind).toBe('offline');
+ expect(slowApi.calls.some((c) => c.method === 'getUpdates')).toBe(false);
+ await slowIm.dispose();
+ });
+
+ it('换账号后不继承上个账号的 bot 身份(离线态拿不到 getMe 也不许张冠李戴)', async () => {
+ await connect();
+ expect(
+ (
+ (await ctx.handlers.get('telegramBot:get-status')!()) as { botUsername: string | null }
+ ).botUsername,
+ ).toBe(BOT.username);
+
+ // 账号 A 登出 → 账号 B 的 bot 已持久化为下线态
+ await im.dispose();
+ ctx.secrets.set('telegram-bot-token', '888:another-account-token-xyz');
+ ctx.secrets.set('telegram-owner-user-id', '222');
+ ctx.secrets.set('telegram-bot-offline', '1');
+ await im.init();
+
+ const status = (await ctx.handlers.get('telegramBot:get-status')!()) as {
+ status: { kind: string; appId?: string };
+ botUsername: string | null;
+ };
+ expect(status.status.kind).toBe('offline');
+ expect(status.status.appId).toBe('888');
+ // 关键: 不是 A 的 my_cindy_bot
+ expect(status.botUsername).toBeNull();
+ });
+
+ it('带下线标志时 init 直接 offline, 零网络请求(重启不抢回轮询)', async () => {
+ ctx.secrets.set('telegram-bot-token', '999:secret-token-abcdefghijk');
+ ctx.secrets.set('telegram-owner-user-id', OWNER_ID);
+ ctx.secrets.set('telegram-bot-offline', '1');
+
+ await im.init();
+
+ // botId 从 token 前缀解析而来, 不发 getMe。
+ expect(im.getStatus()).toEqual({ kind: 'offline', appId: String(BOT.id) });
+ expect(api.calls).toHaveLength(0);
+ });
+
+ it('set-online:true → 清标志并重新拉起轮询', async () => {
+ ctx.secrets.set('telegram-bot-token', '999:secret-token-abcdefghijk');
+ ctx.secrets.set('telegram-owner-user-id', OWNER_ID);
+ ctx.secrets.set('telegram-bot-offline', '1');
+ await im.init();
+ expect(api.calls).toHaveLength(0);
+
+ await ctx.handlers.get('telegramBot:set-online')!({ online: true });
+
+ expect(im.getStatus()).toEqual({ kind: 'connected', appId: String(BOT.id) });
+ expect(ctx.secrets.has('telegram-bot-offline')).toBe(false);
+ await vi.waitFor(() => {
+ expect(api.calls.some((c) => c.method === 'getUpdates')).toBe(true);
+ });
+ });
+
+ it('先下线再解绑: 仍要清掉 Telegram 里的命令菜单(否则失效命令永久残留)', async () => {
+ await connect();
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+ // 下线已把 this.api 置空;此时解绑若不复活 client, deleteMyCommands 会被跳过,
+ // 而 token 随即删除 —— 以后再没机会清, /help 等入口就永久留在 Telegram 里。
+ const before = api.calls.filter((c) => c.method === 'deleteMyCommands').length;
+
+ await ctx.handlers.get('telegramBot:disconnect')!();
+
+ await vi.waitFor(() => {
+ expect(api.calls.filter((c) => c.method === 'deleteMyCommands').length).toBe(before + 1);
+ });
+ expect(im.getStatus()).toEqual({ kind: 'idle' });
+ });
+
+ it('连接失败带稳定 code, 供 UI 取本地化文案(不直接展示英文 reason)', async () => {
+ const failing = createFakeApi({
+ getMeError: new TelegramApiError('getMe', 401, 'Unauthorized'),
+ });
+ const failIm = new TelegramIM(ctx.host, { apiFactory: () => failing });
+ failIm.registerIpc();
+ await ctx.handlers.get('telegramBot:set-config')!({
+ token: '999:secret-token-abcdefghijk',
+ ownerUserId: OWNER_ID,
+ });
+ const status = failIm.getStatus();
+ expect(status.kind).toBe('error');
+ if (status.kind === 'error') expect(status.code).toBe('invalid-token');
+ await failIm.dispose();
+ });
+
+ it('解绑清掉下线标志(否则重填 token 后重启又被判回 offline)', async () => {
+ await connect();
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+ expect(ctx.secrets.get('telegram-bot-offline')).toBe('1');
+
+ await ctx.handlers.get('telegramBot:disconnect')!();
+
+ expect(im.getStatus()).toEqual({ kind: 'idle' });
+ expect(ctx.secrets.has('telegram-bot-offline')).toBe(false);
+ expect(ctx.secrets.has('telegram-bot-token')).toBe(false);
+ });
+
+ it('重填 token 时标志删不掉要报错, 不能连上后重启又掉回 offline', async () => {
+ await connect();
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+ const originalRemove = ctx.host.secrets.remove;
+ ctx.host.secrets.remove = (name) => {
+ if (name !== 'telegram-bot-offline') originalRemove(name);
+ };
+
+ await ctx.handlers.get('telegramBot:set-config')!({
+ token: '999:secret-token-abcdefghijk',
+ ownerUserId: OWNER_ID,
+ });
+
+ // 标志还在 → 重启必回 offline, 所以不能报告成功。
+ expect(ctx.secrets.get('telegram-bot-offline')).toBe('1');
+ expect(im.getStatus().kind).toBe('error');
+ ctx.host.secrets.remove = originalRemove;
+ });
+
+ it('下线态重新填 token 点连接: 清掉遗留标志, 直接连上', async () => {
+ await connect();
+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });
+ expect(ctx.secrets.get('telegram-bot-offline')).toBe('1');
+
+ await connect();
+
+ expect(im.getStatus()).toEqual({ kind: 'connected', appId: String(BOT.id) });
+ expect(ctx.secrets.has('telegram-bot-offline')).toBe(false);
+ });
+
it('相册 settle 期间同 chat 的后续消息保序: 先答相册再答追问', async () => {
const events: IMMessageEvent[] = [];
im.onMessage((e) => events.push(e));
diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.ts
index 26fa8b6998..9b18fe8da2 100644
--- a/packages/lizi-im/src/telegram/index.ts
+++ b/packages/lizi-im/src/telegram/index.ts
@@ -28,6 +28,7 @@ import type {
IMCardActionEvent,
IMHost,
IMMessageEvent,
+ IMSecretReadResult,
IMStatus,
InteractiveCardSpec,
SendFileResult,
@@ -64,6 +65,12 @@ const LEGACY_RUNTIME_ACTIVE_SECRET_KEY = 'telegram-bot-runtime-active';
* 重放, 而下游 turn 无 messageId 幂等; 落盘让重启从上次处理完的位置续读。
*/
const UPDATES_OFFSET_SECRET_KEY = 'telegram-updates-offset';
+/**
+ * 用户主动下线标志('1' = 下线)。与凭证分离是本功能的全部要点: 下线只停轮询,
+ * token / owner / offset 一律保留, 重启后仍保持下线(否则换机器时把另一台停掉
+ * 的意义就没了 — 它一重启就又来抢 getUpdates)。解绑(disconnect)会连同清除。
+ */
+const OFFLINE_SECRET_KEY = 'telegram-bot-offline';
const POLL_TIMEOUT_SEC = 50;
/**
@@ -222,8 +229,12 @@ export class TelegramIM extends BaseIM implements ChannelIM {
* (2026-07-30 #1098 review: 全局 await 会让一个 chat 的相册下载拖住全部)。
*/
private readonly chatQueues = new Map<string, Promise<void>>();
- /** 已分发未收口的 update_id — 持久化游标的低水位以它为准, 掉线不丢任何在途消息。 */
- private readonly inflightUpdateIds = new Set<number>();
+ /**
+ * 已分发未收口的 update。key 是每次分发的独立身份而非裸 update_id:
+ * offline→online 后 Telegram 会重放未提交的同一 update_id,旧世代任务收尾时
+ * 只能删除自己的登记,不能误删新世代的重放任务并让游标越过去。
+ */
+ private readonly inflightUpdates = new Map<symbol, number>();
/**
* 待配对的回挂触发队列(laneUserId → 原生 message_id FIFO): 多条消息在上一
* 轮还没出话时先后触发同一 lane, 各自的答案必须挂回各自的提问 — 单值会被
@@ -258,15 +269,119 @@ export class TelegramIM extends BaseIM implements ChannelIM {
async init(): Promise<void> {
this.disposing = false;
- const token = this.host.secrets.read(TOKEN_SECRET_KEY)?.trim() ?? '';
+ const tokenResult = this.secretReadResult(TOKEN_SECRET_KEY);
+ if (tokenResult.kind === 'error') {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return;
+ }
+ const token = tokenResult.kind === 'value' ? tokenResult.value.trim() : '';
this.ownerUserId = this.host.secrets.read(OWNER_USER_ID_SECRET_KEY)?.trim() ?? '';
if (!token) {
this.setStatus({ kind: 'idle' });
return;
}
+ // 主动下线态必须跨重启保持: 这里一旦 connect 就会重新抢 getUpdates, 把
+ // 用户特意让位给另一台设备的轮询又夺回来。零网络请求进 offline。
+ const offlineFlagState = this.offlineFlagState();
+ if (offlineFlagState === 'unknown') {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return;
+ }
+ if (offlineFlagState === 'set') {
+ // botId 能从 token 前缀解析, 但 username / 显示名只有 getMe 拿得到 —— 而
+ // 下线态不发请求。同进程内换账号(A→B)时若不清, get-status 会把 A 的 bot
+ // 身份和 B 的离线状态一起报给设置卡。宁可留空, 不可张冠李戴。
+ this.botId = botIdFromToken(token);
+ this.botUsername = '';
+ this.botDisplayName = '';
+ this.setStatus({ kind: 'offline', appId: this.botContextId });
+ return;
+ }
await this.connect(token);
}
+ /**
+ * 主动下线: 停轮询但**保留全部绑定信息**(token / owner / offset / 命令菜单)。
+ * 用途是换机器时把这一端让出来 —— 与 disconnect(解绑, 清凭证)是两个动作。
+ * 不向 owner 播报(与 dispose 同口径, 见文件头部生命周期静默说明)。
+ */
+ async goOffline(): Promise<void> {
+ // 先判安全存储可用性: 不可用时 read 一律返回 null, 会把"读不到 token"误判成
+ // "未配置" → 设 idle 却不停轮询, 变成「UI 显示未配置、bot 还在收消息」。
+ // 这条路径远程下线也会走(telegramRemoteControl 不做预检), 必须在这里兜住。
+ if (!this.host.secrets.isAvailable()) {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return;
+ }
+ const tokenResult = this.secretReadResult(TOKEN_SECRET_KEY);
+ if (tokenResult.kind === 'error') {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return;
+ }
+ const token = tokenResult.kind === 'value' ? tokenResult.value.trim() : '';
+ if (!token) {
+ this.setStatus({ kind: 'idle' });
+ return;
+ }
+ // 标志必须先落盘成功再停轮询: 反过来的话, 写失败时本机已经停了、UI 也显示
+ // 已下线, 但重启就会自动上线回来抢另一台的轮询 —— 恰好毁掉下线的全部意义。
+ // 宁可停在"没下线成功"的明确错误上, 也不留一个会自己复活的假下线。
+ if (!this.host.secrets.write(OFFLINE_SECRET_KEY, '1')) {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return;
+ }
+ // 换代先行: 在途 poll 循环据 configVersion 自行退出, 不会把下线状态覆盖回去。
+ this.configVersion += 1;
+ this.clearAllTypingLoops();
+ this.pendingReplyTargets.clear();
+ this.turnReplyTargets.clear();
+ await this.stopPolling();
+ if (!this.botId) this.botId = botIdFromToken(token);
+ this.setStatus({ kind: 'offline', appId: this.botContextId });
+ }
+
+ /** 从下线态恢复: 清标志并按保留的 token 重新建连(offset 续上, 不重放)。 */
+ async goOnline(): Promise<boolean> {
+ const tokenResult = this.secretReadResult(TOKEN_SECRET_KEY);
+ if (tokenResult.kind === 'error') {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return false;
+ }
+ const token = tokenResult.kind === 'value' ? tokenResult.value.trim() : '';
+ this.host.secrets.remove(OFFLINE_SECRET_KEY);
+ // remove 返回 void 且吞掉异常(文件锁/权限/磁盘错误), 只能回读确认。标志没删掉
+ // 却照常连上, 会让用户看到"已上线"、重启后却又回到 offline —— 与写标志失败
+ // 同源的静默失败, 同样宁可停在明确错误上。
+ // 只有明确读到"不存在"才算删成功: 'unknown'(存储在 remove→read 窗口里失效)
+ // 同样 fail closed, 否则删除失败会被当成成功放过。
+ if (this.offlineFlagState() !== 'absent') {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return false;
+ }
+ if (!token) {
+ this.setStatus({ kind: 'idle' });
+ return false;
+ }
+ this.configVersion += 1;
+ await this.stopPolling();
+ return this.connect(token);
+ }
+
+ /** Read with explicit missing/error semantics; legacy hosts fail closed. */
+ private secretReadResult(name: string): IMSecretReadResult {
+ return this.host.secrets.readResult?.(name) ?? { kind: 'error' };
+ }
+
+ /**
+ * 下线标志的三态判定。只有可靠读到 ENOENT 才是 absent;文件存在(无论内容)
+ * 都视为 set,I/O/解密失败或旧 host 没实现 readResult 都是 unknown。
+ */
+ private offlineFlagState(): 'set' | 'absent' | 'unknown' {
+ const result = this.secretReadResult(OFFLINE_SECRET_KEY);
+ if (result.kind === 'error') return 'unknown';
+ return result.kind === 'missing' ? 'absent' : 'set';
+ }
+
// 生命周期静默: dispose / 重连不向 owner 发任何播报(桌面端频繁重启会刷屏)。
async dispose(): Promise<void> {
this.disposing = true;
@@ -276,6 +391,11 @@ export class TelegramIM extends BaseIM implements ChannelIM {
this.pendingReplyTargets.clear();
this.turnReplyTargets.clear();
await this.stopPolling();
+ // bot 身份是上一个账号的连接期产物: 登出/换账号后必须清干净, 否则下一个
+ // 账号在 offline 等拿不到 getMe 的状态下会继承旧账号的 bot 名字。
+ this.botId = 0;
+ this.botUsername = '';
+ this.botDisplayName = '';
this.setStatus({ kind: 'idle' });
}
@@ -293,12 +413,21 @@ export class TelegramIM extends BaseIM implements ChannelIM {
const ownerUserId =
typeof config.ownerUserId === 'string' ? config.ownerUserId.trim() : '';
if (!this.host.secrets.isAvailable()) {
- this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON });
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
return configResult();
}
- const previousToken = this.host.secrets.read(TOKEN_SECRET_KEY);
- const previousOwnerUserId = this.host.secrets.read(OWNER_USER_ID_SECRET_KEY);
+ // 回滚前必须先可靠读取旧值;把读取失败当成“不存在”会在后续失败时误删旧配置。
+ const previousTokenResult = this.secretReadResult(TOKEN_SECRET_KEY);
+ const previousOwnerResult = this.secretReadResult(OWNER_USER_ID_SECRET_KEY);
+ if (previousTokenResult.kind === 'error' || previousOwnerResult.kind === 'error') {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return configResult();
+ }
+ const previousToken =
+ previousTokenResult.kind === 'value' ? previousTokenResult.value : null;
+ const previousOwnerUserId =
+ previousOwnerResult.kind === 'value' ? previousOwnerResult.value : null;
const previousRuntimeOwnerUserId = this.ownerUserId;
const tokenSaved = token ? this.host.secrets.write(TOKEN_SECRET_KEY, token) : true;
@@ -306,10 +435,12 @@ export class TelegramIM extends BaseIM implements ChannelIM {
? this.host.secrets.write(OWNER_USER_ID_SECRET_KEY, ownerUserId)
: true;
if (!tokenSaved || !ownerSaved) {
- this.restoreSecret(TOKEN_SECRET_KEY, previousToken);
- this.restoreSecret(OWNER_USER_ID_SECRET_KEY, previousOwnerUserId);
- this.ownerUserId = previousOwnerUserId?.trim() || previousRuntimeOwnerUserId;
- this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON });
+ await this.rollbackConfigOrFailClosed(
+ previousToken,
+ previousOwnerUserId,
+ previousRuntimeOwnerUserId,
+ );
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
return configResult();
}
@@ -318,12 +449,29 @@ export class TelegramIM extends BaseIM implements ChannelIM {
this.configVersion += 1;
await this.stopPolling();
this.ownerUserId = nextOwnerUserId;
+ // 手动填 token 点连接 = 明确要在这台机器上用, 清掉遗留的下线标志,
+ // 否则连上了但重启后又被 init 判回 offline。remove 吞异常且无返回值
+ // (Windows 文件锁尤甚, 见 engineering-conventions「文件系统差异」), 必须
+ // 回读确认 —— 否则用户重填 token 看似恢复、重启后又掉回 offline。
+ this.host.secrets.remove(OFFLINE_SECRET_KEY);
+ if (this.offlineFlagState() !== 'absent') {
+ await this.rollbackConfigOrFailClosed(
+ previousToken,
+ previousOwnerUserId,
+ previousRuntimeOwnerUserId,
+ );
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return configResult();
+ }
const connected = await this.connect(token);
if (!connected) {
const failedStatus = this.status;
- this.restoreSecret(TOKEN_SECRET_KEY, previousToken);
- this.restoreSecret(OWNER_USER_ID_SECRET_KEY, previousOwnerUserId);
- this.ownerUserId = previousOwnerUserId?.trim() || previousRuntimeOwnerUserId;
+ const restored = await this.rollbackConfigOrFailClosed(
+ previousToken,
+ previousOwnerUserId,
+ previousRuntimeOwnerUserId,
+ );
+ if (!restored) return configResult(this.status);
const previous = previousToken?.trim();
if (previous) {
this.configVersion += 1;
@@ -351,9 +499,44 @@ export class TelegramIM extends BaseIM implements ChannelIM {
botUsername: this.botUsername || null,
}));
+ /**
+ * 上线/下线开关(不碰凭证)。单 channel 双向 —— handler 不依赖 event.sender、
+ * 无本机 UI/shell 副作用、语义只在被控端执行才正确, 满足 device-link
+ * allowlist 的三条准入判据, 后续做跨设备下线可原样登记。
+ */
+ this.host.ipc.handle('telegramBot:set-online', async (payload) => {
+ if (!isRecord(payload) || typeof payload.online !== 'boolean') {
+ this.host.ipc.throwIpcError(
+ 'INVALID_PARAMS',
+ 'expected an object payload { online: boolean }',
+ );
+ }
+ const { online } = payload;
+ if (!this.host.secrets.isAvailable()) {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return { status: this.status };
+ }
+ if (online) {
+ await this.goOnline();
+ } else {
+ await this.goOffline();
+ }
+ return { status: this.status };
+ });
+
this.host.ipc.handle('telegramBot:disconnect', async () => {
this.configVersion += 1;
const disconnectedOwnerUserId = this.ownerUserId;
+ // 下线态 this.api 已被 stopPolling 置空,但解绑仍要用它清命令菜单、发解绑
+ // 通知 —— 不复活的话「先下线再解绑」会让 /help 等失效命令永久留在 Telegram
+ // 里,而 token 随即被删,以后再也没机会清。用保留的 token 临时造一个
+ // client(best-effort;末尾 stopPolling 会再次置空)。
+ if (!this.api) {
+ const retainedToken = this.host.secrets.read(TOKEN_SECRET_KEY)?.trim() ?? '';
+ if (retainedToken) {
+ this.api = (this.opts.apiFactory ?? createTelegramApiClient)(retainedToken);
+ }
+ }
// 顺手清掉 owner scope 的命令菜单(解绑后菜单残留会误导)。
if (this.api && disconnectedOwnerUserId) {
void this.api
@@ -373,6 +556,9 @@ export class TelegramIM extends BaseIM implements ChannelIM {
this.host.secrets.remove(OWNER_USER_ID_SECRET_KEY);
this.host.secrets.remove(LEGACY_RUNTIME_ACTIVE_SECRET_KEY);
this.host.secrets.remove(UPDATES_OFFSET_SECRET_KEY);
+ // 解绑必须连下线标志一起清: 留着的话重新填 token 会连上、但重启即回
+ // offline, 表现为"填了 token 却不工作"。
+ this.host.secrets.remove(OFFLINE_SECRET_KEY);
await this.stopPolling();
this.setStatus({ kind: 'idle' });
return { status: this.status };
@@ -626,14 +812,38 @@ export class TelegramIM extends BaseIM implements ChannelIM {
private async connect(token: string): Promise<boolean> {
const api = (this.opts.apiFactory ?? createTelegramApiClient)(token);
+ // getMe 是网络请求, 这段窗口里另一台设备可能远程下线、用户可能本地下线或
+ // 登出。这些路径都只递增 configVersion + 停当前 poll —— 尚未创建 poll 的
+ // 本次 connect 不受影响, 返回后会无条件写 connected 并拉起新一轮轮询,
+ // 于是控制端已经收到「已下线」, 目标机却又回来抢同一个 bot。
+ // 捕获出发时的世代, 回来后核对: 失效就安静退出, 不写状态、不起轮询。
+ const generation = this.configVersion;
this.setStatus({ kind: 'connecting' });
let me: TgUser;
try {
me = await api.call<TgUser>('getMe');
} catch (err) {
+ if (this.configVersion !== generation || this.disposing) return false;
this.setStatus(mapConnectErrorToStatus(err));
return false;
}
+ // 世代变了(被下线/登出/换 token)或已 dispose → 本次连接结果作废。offline
+ // 标志再查一次是防守: 远程下线写标志与递增世代之间也有窗口。
+ if (this.configVersion !== generation || this.disposing) {
+ this.log.info('connect result discarded: superseded by offline/dispose during getMe');
+ return false;
+ }
+ const offlineFlagState = this.offlineFlagState();
+ if (offlineFlagState !== 'absent') {
+ if (offlineFlagState === 'unknown') {
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ } else {
+ this.botId = me.id;
+ this.setStatus({ kind: 'offline', appId: String(me.id) });
+ }
+ this.log.info('connect result discarded: offline flag is set or unreadable after getMe');
+ return false;
+ }
this.api = api;
this.botId = me.id;
this.botUsername = me.username ?? '';
@@ -736,7 +946,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
continue;
}
if (err instanceof TelegramApiError && (err.errorCode === 401 || err.errorCode === 404)) {
- this.setStatus({ kind: 'error', reason: 'invalid token' });
+ this.setStatus({ kind: 'error', reason: 'invalid token', code: 'invalid-token' });
return;
}
// 网络抖动/超时: connecting + 指数退避重试。
@@ -774,7 +984,8 @@ export class TelegramIM extends BaseIM implements ChannelIM {
const chatId =
update.message?.chat.id ?? update.callback_query?.message?.chat.id ?? 'global';
const key = String(chatId);
- this.inflightUpdateIds.add(update.update_id);
+ const inflightKey = Symbol();
+ this.inflightUpdates.set(inflightKey, update.update_id);
const prev = this.chatQueues.get(key) ?? Promise.resolve();
const next = prev
.then(async () => {
@@ -787,7 +998,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
}
})
.finally(() => {
- this.inflightUpdateIds.delete(update.update_id);
+ this.inflightUpdates.delete(inflightKey);
if (this.chatQueues.get(key) === next) this.chatQueues.delete(key);
if (!this.disposing && this.configVersion === generation) this.persistOffsetCapped();
});
@@ -1486,12 +1697,52 @@ export class TelegramIM extends BaseIM implements ChannelIM {
// ── owner notices / secrets ────────────────────────────────────────────────
- private restoreSecret(key: string, previousValue: string | null): void {
+ /** 恢复一项 secret 并回读确认;调用成功不等于数据真的落盘。 */
+ private restoreSecret(key: string, previousValue: string | null): boolean {
if (previousValue === null) {
this.host.secrets.remove(key);
- return;
+ return this.secretReadResult(key).kind === 'missing';
+ }
+ if (!this.host.secrets.write(key, previousValue)) return false;
+ const restored = this.secretReadResult(key);
+ return restored.kind === 'value' && restored.value === previousValue;
+ }
+
+ /**
+ * 配置事务回滚。任一 secret 无法恢复时,运行态立即停轮询并重新落下线闩锁;
+ * 即使磁盘留下新 token 或新旧混合配置,重启也不会拿它自动上线。
+ */
+ private async rollbackConfigOrFailClosed(
+ previousToken: string | null,
+ previousOwnerUserId: string | null,
+ previousRuntimeOwnerUserId: string,
+ ): Promise<boolean> {
+ // 两项都必须尝试,不能因第一项失败而把另一项也留在新值。
+ const tokenRestored = this.restoreSecret(TOKEN_SECRET_KEY, previousToken);
+ const ownerRestored = this.restoreSecret(OWNER_USER_ID_SECRET_KEY, previousOwnerUserId);
+ this.ownerUserId = previousOwnerUserId?.trim() || previousRuntimeOwnerUserId;
+ if (tokenRestored && ownerRestored) return true;
+
+ this.configVersion += 1;
+ this.clearAllTypingLoops();
+ this.pendingReplyTargets.clear();
+ this.turnReplyTargets.clear();
+ await this.stopPolling();
+ const latchWritten = this.host.secrets.write(OFFLINE_SECRET_KEY, '1');
+ const latchConfirmed = latchWritten && this.offlineFlagState() === 'set';
+ if (!latchConfirmed) {
+ // 最后兜底:闩锁无法确认时删除 token 并回读。二者任一可靠落盘,重启都不会
+ // 自动上线;若存储整体失效,运行态仍保持停止并显式报错。
+ this.host.secrets.remove(TOKEN_SECRET_KEY);
+ const tokenRemovalConfirmed = this.secretReadResult(TOKEN_SECRET_KEY).kind === 'missing';
+ if (!tokenRemovalConfirmed) {
+ this.log.warn(
+ 'telegram config rollback failed and no durable offline guard could be confirmed',
+ );
+ }
}
- this.host.secrets.write(key, previousValue);
+ this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });
+ return false;
}
/** 持久化游标按 botId 命名空间 — 换 bot(token)后旧 offset 无意义, 归零。 */
@@ -1528,7 +1779,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
for (const album of this.albumsInFlight) {
floor = Math.min(floor, album.firstUpdateId);
}
- for (const updateId of this.inflightUpdateIds) {
+ for (const updateId of this.inflightUpdates.values()) {
floor = Math.min(floor, updateId);
}
this.persistOffset(Math.min(this.lastSeenOffset, floor));
@@ -1624,20 +1875,36 @@ export function createTelegramIM(host: IMHost, opts?: TelegramIMOptions): Telegr
export type { TelegramGroupWindowEntry } from './inbound.js';
+/**
+ * reason 保留原文供日志/诊断; code 是给 UI 用的稳定分类 —— 渲染层按 code 取
+ * i18n 文案, 不再把这些英文技术串直接怼给用户看。
+ */
function mapConnectErrorToStatus(err: unknown): IMStatus {
if (err instanceof TelegramApiError) {
if (err.errorCode === 401 || err.errorCode === 404) {
- return { kind: 'error', reason: 'invalid token' };
+ return { kind: 'error', reason: 'invalid token', code: 'invalid-token' };
}
- return { kind: 'error', reason: `telegram api ${err.errorCode}` };
+ return { kind: 'error', reason: `telegram api ${err.errorCode}`, code: 'provider-api' };
}
- return { kind: 'error', reason: 'network unreachable' };
+ return { kind: 'error', reason: 'network unreachable', code: 'network' };
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+/**
+ * 从 BotFather token(`<botId>:<secret>`)取 botId。下线态不建连也就没有 getMe,
+ * 但设置卡仍要显示 bot 标识、群窗口仍按 botId 命名空间查询 — 前缀本身就是
+ * botId, 不值得为此发一次网络请求。形态不符返回 0(与"未连接"同值)。
+ */
+function botIdFromToken(token: string): number {
+ const separator = token.indexOf(':');
+ if (separator <= 0) return 0;
+ const n = Number(token.slice(0, separator));
+ return Number.isSafeInteger(n) && n > 0 ? n : 0;
+}
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve) => {
const timer = setTimeout(done, ms);
diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.ts
index ec77420b87..9a980b920f 100644
--- a/packages/lizi-im/src/types.ts
+++ b/packages/lizi-im/src/types.ts
@@ -8,6 +8,12 @@
import type { Logger } from './logger.js';
+/** Result of a secret read when callers must distinguish absence from failure. */
+export type IMSecretReadResult =
+ | { kind: 'value'; value: string }
+ | { kind: 'missing' }
+ | { kind: 'error' };
+
/**
* Host-injected capabilities. Hosts must provide encrypted KV storage, an IPC
* bridge, and a couple of derived paths. Optionally a logger factory; otherwise
@@ -20,6 +26,12 @@ export interface IMHost {
write(name: string, plaintext: string): boolean;
/** Read; missing or unavailable returns null. */
read(name: string): string | null;
+ /**
+ * Read without collapsing a missing key and a storage/decryption failure.
+ * Optional for backwards-compatible hosts; callers that require certainty
+ * must treat an absent implementation as `error`.
+ */
+ readResult?(name: string): IMSecretReadResult;
/** Remove (no-op if missing). */
remove(name: string): void;
/** Whether encryption is currently usable (e.g. Linux without keychain). */
@@ -28,6 +40,8 @@ export interface IMHost {
/** IPC bridge (replaces electron.ipcMain + BrowserWindow). */
ipc: {
+ /** Raise a host-standard, renderer-decodable IPC error. */
+ throwIpcError(code: 'INVALID_PARAMS', message: string): never;
/** Register an `invoke` handler. @cindy/im owns channel names. */
handle(
channel: string,
@@ -229,12 +243,33 @@ export interface IMCardActionEvent {
scopeKey?: string;
}
+/**
+ * 稳定的传输层错误分类。`reason` 是给日志/诊断看的原文(可能是英文技术串或
+ * 渠道原始描述), **不适合直接当 UI 文案**;渲染层按本枚举映射到 i18n key。
+ * 可选字段 —— 未标注 code 的渠道/旧路径由消费方回退到 reason。
+ */
+export type IMErrorCode =
+ /** token 无效 / 被吊销(401 / 404)。 */
+ | 'invalid-token'
+ /** 渠道 API 返回了其它失败码(限流、服务端错误等)。 */
+ | 'provider-api'
+ /** 网络不可达 / 请求异常。 */
+ | 'network'
+ /** 系统安全存储不可用或写入失败,凭证与状态无法落盘。 */
+ | 'secret-unavailable';
+
export type IMStatus =
| { kind: 'idle' }
| { kind: 'connecting' }
| { kind: 'connected'; appId: string }
| { kind: 'conflict'; appId: string }
- | { kind: 'error'; reason: string };
+ /**
+ * 凭证仍在、但用户主动下线 —— 不轮询、不收派发, 重启后保持。
+ * 与 idle 严格区分: idle = 没配置(无凭证), offline = 配好了但停用。
+ * 换机器时把另一端停掉而不清凭证, 之后随时可一键上线。
+ */
+ | { kind: 'offline'; appId: string }
+ | { kind: 'error'; reason: string; code?: IMErrorCode };
// ── Outbound spec ─────────────────────────────────────────────────────────────
// p2p only — outbound APIs always take a single openId: string.
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
index e3754a915f..4345d5fedb 100644
--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -81,6 +81,9 @@ function createHost() {
isAvailable: () => true,
},
ipc: {
+ throwIpcError: (code, message) => {
+ throw new Error(`[${code}] ${message}`);
+ },
handle: (channel, handler) => void ipcHandlers.set(channel, handler),
broadcast: (_channel, payload) => broadcasts.push(payload),
},