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。

fix(im): stabilize DingTalk Stream setup

davide4f983792a6e
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useDingTalkBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useDingTalkBot.test.ts
new file mode 100644
index 0000000000..8284c94101
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useDingTalkBot.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment jsdom
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const toastError = vi.hoisted(() => vi.fn());
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: {
+ success: vi.fn(),
+ error: toastError,
+ },
+}));
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({
+ error: vi.fn(),
+ warn: vi.fn(),
+ info: vi.fn(),
+ debug: vi.fn(),
+ }),
+}));
+
+type DingTalkState = {
+ appKey: string | null;
+ hasSecret: boolean;
+ ownerUserId: string | null;
+ status: DingTalkBotTransportStatus;
+};
+
+function installDingTalkApi() {
+ const initialState: DingTalkState = {
+ appKey: null,
+ hasSecret: false,
+ ownerUserId: null,
+ status: { kind: 'idle' },
+ };
+ const api = {
+ getState: vi.fn(async () => initialState),
+ save: vi.fn(async () => initialState),
+ reconnect: vi.fn(async () => initialState),
+ clear: vi.fn(async () => ({ ok: true as const })),
+ onStatusChange: vi.fn(() => () => {}),
+ onOwnerChange: vi.fn(() => () => {}),
+ };
+ (window as unknown as { electronAPI: { dingtalkBot: typeof api } }).electronAPI = {
+ dingtalkBot: api,
+ };
+ return api;
+}
+
+let useDingTalkBot: typeof import('../useDingTalkBot').useDingTalkBot;
+
+describe('useDingTalkBot', () => {
+ beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ ({ useDingTalkBot } = await import('../useDingTalkBot'));
+ });
+
+ it('preserves the credential draft and shows the Stream-specific error after a failed save', async () => {
+ const api = installDingTalkApi();
+ api.save.mockRejectedValueOnce(
+ new Error(
+ "Error invoking remote method 'dingtalkBot:save': Error: " +
+ '[DINGTALK_STREAM_CONNECTION_FAILED] DINGTALK_STREAM_CONNECTION_FAILED',
+ ),
+ );
+ const { result } = renderHook(() => useDingTalkBot());
+
+ await waitFor(() => expect(api.getState).toHaveBeenCalledOnce());
+ act(() => {
+ result.current.setAppKey('test-client-id');
+ result.current.setAppSecret('test-client-secret');
+ });
+
+ await act(async () => {
+ await expect(result.current.connect()).resolves.toBe(false);
+ });
+
+ expect(result.current.appKey).toBe('test-client-id');
+ expect(result.current.appSecret).toBe('test-client-secret');
+ expect(api.getState).toHaveBeenCalledOnce();
+ expect(toastError).toHaveBeenCalledWith('logic.toasts.dingtalkBotStreamFailed');
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useDingTalkBot.ts b/apps/desktop/src/renderer/hooks/useDingTalkBot.ts
index 2bb579ad0d..aada35d933 100644
--- a/apps/desktop/src/renderer/hooks/useDingTalkBot.ts
+++ b/apps/desktop/src/renderer/hooks/useDingTalkBot.ts
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { createLogger } from '@/lib/logger';
import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
const log = createLogger('useDingTalkBot');
@@ -15,6 +16,19 @@ interface CachedState {
let cachedState: CachedState | null = null;
+function connectFailureToastKey(error: unknown): string {
+ switch (extractIpcError(error)?.code) {
+ case 'DINGTALK_AUTH_FAILED':
+ return 'logic.toasts.dingtalkBotAuthFailed';
+ case 'DINGTALK_NETWORK_FAILED':
+ return 'logic.toasts.dingtalkBotNetworkFailed';
+ case 'DINGTALK_STREAM_CONNECTION_FAILED':
+ return 'logic.toasts.dingtalkBotStreamFailed';
+ default:
+ return 'logic.toasts.dingtalkBotConnectFailed';
+ }
+}
+
export function useDingTalkBot() {
const { t } = useTranslation();
const [appKey, setAppKeyState] = useState(() => cachedState?.appKey ?? '');
@@ -112,12 +126,9 @@ export function useDingTalkBot() {
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
log.error('save failed:', message);
- try {
- updateState(await window.electronAPI.dingtalkBot.getState());
- } catch {
- // Preserve the actionable connection error when state refresh also fails.
- }
- toast.error(t('logic.toasts.dingtalkBotConnectFailed'));
+ // saveAndConnect restores the last persisted connection on failure. Keep
+ // the user's current credential draft so they can correct and retry it.
+ toast.error(t(connectFailureToastKey(error)));
return false;
} finally {
setIsSaving(false);
@@ -139,7 +150,7 @@ export function useDingTalkBot() {
} catch {
// The toast below remains the user-facing fallback.
}
- toast.error(t('logic.toasts.dingtalkBotConnectFailed'));
+ toast.error(t(connectFailureToastKey(error)));
return false;
} finally {
setIsSaving(false);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 33ac2c690a..5a823cdb87 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2686,7 +2686,8 @@
"slack": "New Slack threads use this Agent and model.",
"discord": "New Discord conversations use this Agent and model. Send /new in an existing DM to apply it.",
"wechat": "New WeChat conversations use this Agent, model, and permission mode. Send /new in an existing chat to apply them.",
- "telegram": "New Telegram conversations use this Agent and model. Send /new in an existing conversation to apply it."
+ "telegram": "New Telegram conversations use this Agent and model. Send /new in an existing conversation to apply it.",
+ "dingtalk": "New DingTalk conversations use this Agent and model. Send /new in an existing conversation to apply it."
},
"agentLabel": "Agent",
"modelLabel": "Model Configuration",
@@ -7623,6 +7624,9 @@
"telegramBotDisconnectFailed": "Unbind failed: {{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",
+ "dingtalkBotNetworkFailed": "Cannot reach DingTalk Open Platform. Check your network or proxy and try again",
+ "dingtalkBotStreamFailed": "Credentials are valid, but the Stream connection was not established. Enable the bot, select Stream mode, and publish the app version",
"dingtalkBotDisconnected": "DingTalk bot unbound",
"dingtalkBotDisconnectFailed": "Failed to unbind DingTalk bot"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 9b19b6e0fb..6fd07b3d1d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2685,7 +2685,8 @@
"slack": "Slack の新しいスレッドでは、この Agent とモデルを使用します。",
"discord": "Discord の新規会話では、この Agent とモデルを使用します。既存の DM には /new で適用します。",
"wechat": "WeChat の新規会話では、この Agent・モデル・権限モードを使用します。既存のチャットには /new で適用します。",
- "telegram": "Telegram の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。"
+ "telegram": "Telegram の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。",
+ "dingtalk": "DingTalk の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。"
},
"agentLabel": "Agent",
"modelLabel": "モデル設定",
@@ -7612,6 +7613,9 @@
"telegramBotDisconnectFailed": "連携解除に失敗しました:{{message}}",
"dingtalkBotConnected": "DingTalk ボットに接続しました",
"dingtalkBotConnectFailed": "DingTalk ボットに接続できません。認証情報、Stream モード、ネットワークを確認してください",
+ "dingtalkBotAuthFailed": "DingTalk が認証情報を拒否しました。Client ID と Client Secret が同じアプリのものか確認してください",
+ "dingtalkBotNetworkFailed": "DingTalk オープンプラットフォームに接続できません。ネットワークまたはプロキシを確認して再試行してください",
+ "dingtalkBotStreamFailed": "認証情報は有効ですが、Stream 接続を確立できません。ボットを有効化し、Stream モードを選択してアプリのバージョンを公開してください",
"dingtalkBotDisconnected": "DingTalk ボットの連携を解除しました",
"dingtalkBotDisconnectFailed": "DingTalk ボットの連携解除に失敗しました"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8cd161a9cd..8857a41de2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2685,7 +2685,8 @@
"slack": "새 Slack 스레드는 이 Agent와 모델을 사용합니다.",
"discord": "새 Discord 대화는 이 Agent와 모델을 사용합니다. 기존 DM에는 /new를 보내 적용하세요.",
"wechat": "새 WeChat 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 기존 채팅에는 /new를 보내 적용하세요.",
- "telegram": "새 Telegram 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요."
+ "telegram": "새 Telegram 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요.",
+ "dingtalk": "새 DingTalk 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요."
},
"agentLabel": "Agent",
"modelLabel": "모델 설정",
@@ -7612,6 +7613,9 @@
"telegramBotDisconnectFailed": "연동 해제 실패: {{message}}",
"dingtalkBotConnected": "DingTalk 봇이 연결됨",
"dingtalkBotConnectFailed": "DingTalk 봇 연결 실패. 자격 증명, Stream 모드, 네트워크를 확인하세요",
+ "dingtalkBotAuthFailed": "DingTalk에서 자격 증명을 거부했습니다. Client ID와 Client Secret이 동일한 앱의 것인지 확인하세요",
+ "dingtalkBotNetworkFailed": "DingTalk 오픈 플랫폼에 연결할 수 없습니다. 네트워크 또는 프록시를 확인한 후 다시 시도하세요",
+ "dingtalkBotStreamFailed": "자격 증명은 유효하지만 Stream 연결이 설정되지 않았습니다. 봇을 활성화하고 Stream 모드를 선택한 뒤 앱 버전을 게시하세요",
"dingtalkBotDisconnected": "DingTalk 봇 연동이 해제됨",
"dingtalkBotDisconnectFailed": "DingTalk 봇 연동 해제 실패"
},
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 bcc1eadd13..c2ee2bd507 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2685,7 +2685,8 @@
"slack": "Slack 新 thread 会使用这组 Agent 和模型。",
"discord": "Discord 新对话会使用这组 Agent 和模型;已有私聊发送 /new 后应用。",
"wechat": "微信新对话会使用这组 Agent、模型和权限模式;已有私聊发送 /new 后应用。",
- "telegram": "Telegram 新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。"
+ "telegram": "Telegram 新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。",
+ "dingtalk": "钉钉新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。"
},
"agentLabel": "Agent",
"modelLabel": "模型配置",
@@ -7612,6 +7613,9 @@
"telegramBotDisconnectFailed": "解绑失败:{{message}}",
"dingtalkBotConnected": "钉钉机器人已连接",
"dingtalkBotConnectFailed": "钉钉机器人连接失败,请检查凭证、Stream 模式和网络",
+ "dingtalkBotAuthFailed": "钉钉未通过凭证校验,请确认 Client ID 和 Client Secret 来自同一个应用",
+ "dingtalkBotNetworkFailed": "无法访问钉钉开放平台,请检查网络或 Proxy 后重试",
+ "dingtalkBotStreamFailed": "凭证有效,但 Stream 连接未建立;请确认已启用机器人、选择 Stream 模式并发布应用版本",
"dingtalkBotDisconnected": "已解绑钉钉机器人",
"dingtalkBotDisconnectFailed": "钉钉机器人解绑失败"
},
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index daa20f72ef..cb393cccfb 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -118,6 +118,10 @@ export type IpcErrorCode =
| 'MODEL_ACCESS_DISABLED' // 服务端灰度未启用(503)——走手填兜底
| 'MODEL_ACCESS_UNSUPPORTED' // 企业未接入(403)——XD 网关不可用,不重试
| 'PLAN_CHANGE_NOT_AVAILABLE' // 当前订阅不能切换到目标套餐,可返回候选列表重选
+ // 钉钉机器人连接
+ | 'DINGTALK_AUTH_FAILED' // Client ID / Client Secret 被钉钉拒绝
+ | 'DINGTALK_NETWORK_FAILED' // 钉钉凭证校验接口不可达
+ | 'DINGTALK_STREAM_CONNECTION_FAILED' // 凭证有效,但 Stream WebSocket 未建立
// 个人资料自助修改(settings → 用户卡片;服务端直写)
| 'PROFILE_AVATAR_UPLOAD_FAILED' // 头像经 oss-server 预签名直传失败(presign 或 PUT 阶段)
| 'PROFILE_UPDATE_FAILED' // PATCH /api/me/profile 失败(网络 / 服务端拒绝)
@@ -233,6 +237,9 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'MODEL_ACCESS_DISABLED',
'MODEL_ACCESS_UNSUPPORTED',
'PLAN_CHANGE_NOT_AVAILABLE',
+ 'DINGTALK_AUTH_FAILED',
+ 'DINGTALK_NETWORK_FAILED',
+ 'DINGTALK_STREAM_CONNECTION_FAILED',
'PROFILE_AVATAR_UPLOAD_FAILED',
'PROFILE_UPDATE_FAILED',
'SHARE_FILE_INVALID',
diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
index 68d904f315..3f1a730009 100644
--- a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
@@ -69,6 +69,15 @@ function makeHost() {
return { host, secrets, handlers, broadcasts };
}
+function validCredentialFetcher() {
+ return vi.fn<typeof fetch>(
+ async () =>
+ new Response(
+ JSON.stringify({ accessToken: "test-token", expireIn: 7200 }),
+ ),
+ );
+}
+
function directMessage(overrides: Record<string, unknown> = {}) {
return {
conversationId: "direct-chat",
@@ -88,7 +97,10 @@ describe("DingTalkIM", () => {
it("claims the first direct sender, acknowledges immediately, and drops other direct users", async () => {
const { host, secrets } = makeHost();
const client = new FakeClient();
- const im = new DingTalkIM(host, { clientFactory: () => client });
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher: validCredentialFetcher(),
+ });
const received: IMMessageEvent[] = [];
im.onMessage((event) => received.push(event));
await im.init();
@@ -120,7 +132,10 @@ describe("DingTalkIM", () => {
it("routes mentioned group messages to one lane with speaker metadata", async () => {
const { host } = makeHost();
const client = new FakeClient();
- const im = new DingTalkIM(host, { clientFactory: () => client });
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher: validCredentialFetcher(),
+ });
const received: IMMessageEvent[] = [];
im.onMessage((event) => received.push(event));
await im.init();
@@ -151,7 +166,10 @@ describe("DingTalkIM", () => {
it("does not expose the app secret through public state", async () => {
const { host } = makeHost();
const client = new FakeClient();
- const im = new DingTalkIM(host, { clientFactory: () => client });
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher: validCredentialFetcher(),
+ });
im.registerIpc();
await im.init();
const state = im.getPublicState();
@@ -164,6 +182,67 @@ describe("DingTalkIM", () => {
expect(state).not.toHaveProperty("appSecret");
});
+ it("accepts an open Stream socket without waiting for a REGISTERED system message", async () => {
+ const { host } = makeHost();
+ const client = new FakeClient();
+ client.connect = vi.fn(async () => {
+ client.connected = true;
+ client.registered = false;
+ });
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher: validCredentialFetcher(),
+ });
+
+ await im.init();
+
+ expect(im.getPublicState().status).toEqual({
+ kind: "connected",
+ appId: "app-key",
+ });
+ });
+
+ it("classifies rejected credentials before opening the Stream socket", async () => {
+ const { host } = makeHost();
+ const client = new FakeClient();
+ client.connect = vi.fn();
+ const fetcher = vi.fn<typeof fetch>(
+ async () =>
+ new Response(JSON.stringify({ code: "InvalidParameter" }), {
+ status: 401,
+ }),
+ );
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher,
+ });
+
+ await im.init();
+
+ expect(client.connect).not.toHaveBeenCalled();
+ expect(im.getPublicState().status).toEqual({
+ kind: "error",
+ reason: "DINGTALK_AUTH_FAILED",
+ });
+ });
+
+ it("classifies a Stream socket that never opens", async () => {
+ const { host } = makeHost();
+ const client = new FakeClient();
+ client.connect = vi.fn(async () => undefined);
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher: validCredentialFetcher(),
+ });
+
+ await im.init();
+
+ expect(im.getPublicState().status).toEqual({
+ kind: "error",
+ reason: "DINGTALK_STREAM_CONNECTION_FAILED",
+ });
+ });
+
it("does not emit a slow media callback after the connection is disposed", async () => {
const { host, secrets } = makeHost();
secrets.set("dingtalk-bot-owner-user-id", "owner-1");
diff --git a/packages/lizi-im/src/dingtalk/api.ts b/packages/lizi-im/src/dingtalk/api.ts
index d374f40acc..a1f58cc825 100644
--- a/packages/lizi-im/src/dingtalk/api.ts
+++ b/packages/lizi-im/src/dingtalk/api.ts
@@ -43,6 +43,10 @@ export class DingTalkApiClient {
this.activeRequests.clear();
}
+ async validateCredentials(): Promise<void> {
+ await this.getAccessToken();
+ }
+
async sendText(target: DingTalkOutboundTarget, text: string): Promise<void> {
if (target.sessionWebhook && this.isWebhookUsable(target)) {
try {
diff --git a/packages/lizi-im/src/dingtalk/index.ts b/packages/lizi-im/src/dingtalk/index.ts
index 6cf741a203..ad6accc2e3 100644
--- a/packages/lizi-im/src/dingtalk/index.ts
+++ b/packages/lizi-im/src/dingtalk/index.ts
@@ -36,10 +36,15 @@ const DEDUP_CAPACITY = 2_048;
const STATUS_POLL_MS = 2_000;
const INTERACTION_TIMEOUT_MS = 30 * 60 * 1_000;
const OUTBOUND_CHUNK_SIZE = 3_500;
-const REGISTRATION_TIMEOUT_MS = 10_000;
+const CONNECTION_ERROR_CODES = [
+ "DINGTALK_AUTH_FAILED",
+ "DINGTALK_NETWORK_FAILED",
+ "DINGTALK_STREAM_CONNECTION_FAILED",
+] as const;
type MessageHandler = (event: IMMessageEvent) => void;
type StatusHandler = (status: IMStatus) => void;
+type DingTalkConnectionErrorCode = (typeof CONNECTION_ERROR_CODES)[number];
export interface DingTalkStreamClient {
readonly connected: boolean;
@@ -217,36 +222,48 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
}
async sendFile(
- _userId: string,
- _absPath: string,
- _displayName?: string,
+ userId: string,
+ absPath: string,
+ displayName?: string,
): Promise<SendFileResult> {
+ void userId;
+ void absPath;
+ void displayName;
return { ok: false, reason: "SEND_FAIL" };
}
sendInteractiveCard(
- _userId: string,
- _spec: InteractiveCardSpec,
+ userId: string,
+ spec: InteractiveCardSpec,
): Promise<{ messageId: string }> {
+ void userId;
+ void spec;
return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));
}
updateInteractiveCard(
- _messageId: string,
- _spec: InteractiveCardSpec,
+ messageId: string,
+ spec: InteractiveCardSpec,
): Promise<void> {
+ void messageId;
+ void spec;
return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));
}
- patchMarkdownCard(_messageId: string, _markdown: string): Promise<void> {
+ patchMarkdownCard(messageId: string, markdown: string): Promise<void> {
+ void messageId;
+ void markdown;
return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));
}
startStreamingText(
- _userId: string,
- _initial?: string,
- _opts?: { threadTs?: string },
+ userId: string,
+ initial?: string,
+ opts?: { threadTs?: string },
): Promise<StreamingTextHandle> {
+ void userId;
+ void initial;
+ void opts;
return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));
}
@@ -346,6 +363,21 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
await this.stopConnection();
const version = this.connectionVersion;
this.setStatus({ kind: "connecting" });
+ const api = new DingTalkApiClient(
+ credentials.appKey,
+ credentials.appSecret,
+ this.options.fetcher,
+ );
+ try {
+ await api.validateCredentials();
+ } catch (error) {
+ api.close();
+ throw createConnectionError(
+ isCredentialRejection(error)
+ ? "DINGTALK_AUTH_FAILED"
+ : "DINGTALK_NETWORK_FAILED",
+ );
+ }
const client = (this.options.clientFactory ?? defaultClientFactory)(
credentials,
);
@@ -357,23 +389,27 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
if (this.host.accountScope && accountToken === null) return;
void this.acceptDownstream(message, version, accountToken);
});
- await client.connect();
+ try {
+ await client.connect();
+ } catch {
+ client.disconnect();
+ api.close();
+ throw createConnectionError("DINGTALK_STREAM_CONNECTION_FAILED");
+ }
if (version !== this.connectionVersion) {
client.disconnect();
+ api.close();
throw new Error("DINGTALK_CONNECTION_REPLACED");
}
- if (!client.connected || !(await waitForRegistration(client))) {
+ if (!client.connected) {
client.disconnect();
- throw new Error("DINGTALK_CONNECTION_FAILED");
+ api.close();
+ throw createConnectionError("DINGTALK_STREAM_CONNECTION_FAILED");
}
client.config.autoReconnect = true;
this.client = client;
this.appKey = credentials.appKey;
- this.api = new DingTalkApiClient(
- credentials.appKey,
- credentials.appSecret,
- this.options.fetcher,
- );
+ this.api = api;
this.setStatus({ kind: "connected", appId: credentials.appKey });
this.startStatusMonitor(version);
}
@@ -396,7 +432,7 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
this.stopStatusMonitor();
this.statusTimer = setInterval(() => {
if (version !== this.connectionVersion || !this.client) return;
- if (this.client.connected && this.client.registered) {
+ if (this.client.connected) {
if (this.status.kind !== "connected") {
this.setStatus({ kind: "connected", appId: this.appKey });
}
@@ -743,22 +779,25 @@ function normalizeFinalText(text: string): string {
function safeConnectionError(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
- if (message === "DINGTALK_CONNECTION_FAILED") {
- return "DINGTALK_CONNECTION_FAILED";
+ for (const code of CONNECTION_ERROR_CODES) {
+ if (message.startsWith(`[${code}]`)) return code;
}
return "DINGTALK_CONNECTION_ERROR";
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+function createConnectionError(code: DingTalkConnectionErrorCode): Error {
+ return new Error(`[${code}] ${code}`);
}
-async function waitForRegistration(
- client: DingTalkStreamClient,
-): Promise<boolean> {
- const deadline = Date.now() + REGISTRATION_TIMEOUT_MS;
- while (client.connected && !client.registered && Date.now() < deadline) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- return client.connected && client.registered;
+function isCredentialRejection(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error);
+ return (
+ /\bHTTP (?:400|401|403)\b/.test(message) ||
+ message === "dingtalk API request returned an error" ||
+ message === "dingtalk access token response is invalid"
+ );
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}