diff --git a/README.md b/README.md
index b0c3e94..f2554ae 100644
--- a/README.md
+++ b/README.md
@@ -376,15 +376,15 @@ off set 客厅吸顶灯 2/1 = false
| 连接 |
mijia_auth |
- 连接米家网关(需 6 位一次性登录码;已连接时无需再次认证) |
+ 连接米家网关(需 6 位一次性登录码;已连接时无需再次认证。reconnect=true 更换网关或重新登录,新连接成功后才替换原连接) |
mijia_disconnect |
- 断开网关连接 |
+ 断开网关连接(共享连接下所有客户端都会断开,需要新的登录码才能重连) |
mijia_status |
- 检查连接状态 |
+ 检查连接状态(verify=true 实际询问网关一次,确认连接可用) |
| 设备 |
diff --git a/docs/one-command-setup-plan.md b/docs/one-command-setup-plan.md
new file mode 100644
index 0000000..2be3caf
--- /dev/null
+++ b/docs/one-command-setup-plan.md
@@ -0,0 +1,120 @@
+# 一条命令安装与管理:实施计划
+
+状态:已确认方案,按三个阶段实施。第 1 阶段进行中。
+
+## 1. 目标
+
+把现在「先选部署方式、再改配置、再装 Skill」的安装过程,收敛为一条命令加一个三步向导:
+
+```bash
+npx -y oh-my-sage-mcp@latest setup
+```
+
+- 首次运行进入安装向导:选服务位置 → 连网关 → 接入 AI Agent。
+- 之后运行进入管理菜单:网关登录与验证、AI Agent 接入、更新、高级设置、卸载。
+- NAS 用户在 NAS 上用一条 `docker run` 起服务,再在电脑上用同一条命令接入。
+- 用户需要提供的只有三样:网关 IP、6 位登录码、要接入哪些 AI Agent。
+
+## 2. 已确定的设计决策
+
+| 决策 | 原因 |
+|---|---|
+| 菜单入口是显式子命令 `setup`,不根据「是否在终端」自动切换 | `oh-my-sage-mcp` 是现有客户端的 MCP 启动命令,不能改变其行为 |
+| 向导只装本机常驻服务;按需启动(stdio)保留为手动高级用法 | 菜单管不到 AI Agent 自己拉起的 stdio 进程 |
+| 本机服务装在用户目录,不用 `npm install -g`,不要管理员权限 | 后台服务需要稳定路径;全局目录在部分系统需要 sudo |
+| 本机服务也自动生成访问密钥并写入客户端配置 | 管理操作经过 HTTP,本机其他程序也能访问回环地址 |
+| 菜单是一个带访问密钥的 MCP 客户端,调用服务现有工具 | 本机与 NAS 服务用同一套逻辑,不另造管理接口 |
+| 登录码不保存、不记日志;保存网关地址 | 登录码一次性,协议层无法续期(见 `src/core/gateway/client.ts` `authenticate`) |
+| Skill 随 npm 包下发同版本文件,向导和更新时一起安装 | `npx skills add allocnode/oh-my-sage` 取的是 GitHub main,可能和服务版本不一致 |
+| 写入客户端配置时记录清单,只修改或移除本工具写入的内容 | 改密钥后同步、卸载时都需要知道写过哪里 |
+| 换网关、重新登录必须「新连接成功后才替换旧连接」 | 共享服务里,失败的重新登录不能连带断掉所有客户端 |
+| 更新默认「下次登录生效」,可选「立即重启」 | 立即重启会断开网关、要新的登录码 |
+| 兼容 0.1.x:保留 `GATEWAY_URL` 与 stdio 方式;向导发现旧计划任务或旧配置时提供接管 | 已有用户按旧文档安装 |
+
+## 3. 不做的事
+
+- 不自动扫描局域网找网关(未验证可行性,且电脑上扫到不代表 NAS 能连到)。
+- 不在电脑上的菜单里远程部署、升级 NAS 上的 Docker。
+- 不把网页版并入向导。
+- 不承诺网关登录长期有效或自动续登。
+
+## 4. 第 1 阶段:修复共享连接的安全问题(发布 0.1.2)
+
+不改用法,只修现有缺陷。NAS 上的常驻服务也直接受益。
+
+| # | 问题 | 位置 | 改法 | 完成标准 |
+|---|---|---|---|---|
+| 1.1 | 重新登录时先关旧连接,新连接失败后所有客户端掉线 | `src/core/gateway/manager.ts` `connect()` | 新建客户端并认证成功后再替换,旧连接随后关闭;失败时关闭新客户端、保留旧连接 | 单元测试:新登录失败后 `isConnected()` 仍为 true 且仍是旧客户端 |
+| 1.2 | 并发登录互相覆盖 | 同上 | `connect()` 串行化,后到的请求等前一个完成 | 单元测试:两次并发登录按顺序执行,结束后只有最后成功的那个连接存活 |
+| 1.3 | 工具说明建议 AI 用完断开、重新登录先断开 | `src/mcp/tools/auth.ts` | 删除「建议在完成所有操作后调用」;`mijia_disconnect` 写明会断开所有客户端且登录码作废;`mijia_auth` 增加 `reconnect` 参数用于已连接时更换网关或重新登录,提示不再要求先断开 | 说明文本不再出现上述建议;已有 HTTP 测试通过 |
+| 1.4 | 无法真实验证连接(只看本地标志,设备表有 30 秒缓存) | `manager.ts`、`mijia_status` | 管理器增加 `verify()`,绕过缓存向网关发一次轻量只读请求(`getVarScopeList`,实测约 23 ms、224 字节);`mijia_status` 增加可选 `verify` 参数,返回是否响应与耗时 | 单元测试覆盖响应、超时、未连接三种结果 |
+
+验证(本地只做无副作用检查,行为测试由 CI 与 Alex 执行):
+
+```bash
+npm run lint
+npx tsc --noEmit -p tsconfig.mcp.json
+npx tsc --noEmit
+```
+
+CI 运行单元测试与打包冒烟测试。合并后按发版流程打 `v0.1.2`。
+
+## 5. 第 2 阶段:服务端支撑与 setup 向导(发布 0.2.0)
+
+### 5.1 服务端
+
+- **状态目录**:`MCP_STATE_DIR`,默认 Windows `%LOCALAPPDATA%\oh-my-sage`,macOS `~/Library/Application Support/oh-my-sage`,Linux `${XDG_STATE_HOME:-~/.local/state}/oh-my-sage`,Docker `/data`。
+- **保存网关地址**:`mijia_auth` 成功后把地址写入 `state.json`。地址优先级:本次参数 > 已保存 > `GATEWAY_URL`。
+- **Docker**:`docker-compose.yml` 挂载数据卷到 `/data`;Dockerfile 设 `MCP_STATE_DIR=/data`。
+- **规则草稿**:`src/mcp/tools/graphDraft.ts` 默认路径从系统临时目录移到状态目录(评估后决定,避免两个进程共用同一份临时文件的旧问题回归)。
+
+### 5.2 npm 包
+
+- `scripts/build-npm-package.mjs` 把 `.agents/skills/mijia-automation` 复制进包。
+- 新增依赖评估:交互界面库(候选 `@clack/prompts`),以体积和 Windows 终端兼容性为准。
+
+### 5.3 setup 命令(新文件 `src/mcp/setup/`)
+
+```
+首次运行
+├─ 1. 服务:本机常驻 / 连接已有服务(地址 + 访问密钥,当场验证身份与版本)
+├─ 2. 网关:输入地址 → 由服务所在机器测试 → 6 位登录码 → 验证并保存(可跳过)
+└─ 3. AI Agent:用户勾选 → 写 MCP 配置 + 装同版本 Skill → 不支持的给出完整配置
+ 完成页分别显示:服务 / 网关 / 客户端 状态
+
+之后运行
+顶部:服务状态 · 网关状态(附上次验证时间)· 已接入客户端
+├─ 1. 网关:输入新登录码 / 验证连接 / 更换网关(新连接成功才替换)
+├─ 2. AI Agent:添加 / 检查修复 / 移除(只动本工具写入的)/ 显示手动配置
+├─ 3. 更新:下次登录生效(默认)/ 立即重启(需新登录码)
+├─ 4. 高级:启停服务 / 改端口或密钥(同步各客户端)/ 查看日志(脱敏)/ 切换服务
+├─ 5. 卸载或解除接入(先列清单再执行;远程服务只解除本机接入)
+└─ 0. 退出(服务继续运行)
+```
+
+关键行为:
+
+- 本机安装:`npm install --prefix <状态目录>/app oh-my-sage-mcp@<版本>`,后台服务指向该目录,复用 `deploy/install-local.*` 注册服务。
+- 某步失败只重试该步,已完成部分保留。
+- 已登录时不因打开菜单或重复安装而重新认证。
+- 写配置清单保存在状态目录 `clients.json`:客户端、文件路径、写入的键、Skill 路径。
+- 迁移:发现 `oh-my-sage-mcp` 计划任务 / launchd / systemd 服务或客户端里的 stdio 配置时,提示接管,不另装一份。
+
+### 5.4 动手前要核实的事
+
+- [ ] `add-mcp` 写入带注释的配置文件(JSONC)时是否保留注释与其他项;是否支持 HTTP `headers`。不满足就自己按客户端写。
+- [ ] 各客户端 Skill 目录,以及 `npx skills add <本地路径>` 是否可用。
+- [ ] 腾讯 WorkBuddy、TRAE、Qoder、通义灵码的 MCP 配置文件位置。
+- [ ] 网关登录能保持多久(需在真实网关上观察,不能主动断开现有连接)。
+
+## 6. 第 3 阶段:Docker 镜像与 README(随 0.2.0)
+
+- `release.yml` 增加构建并推送镜像到 GHCR(`ghcr.io/allocnode/oh-my-sage-mcp`)。
+- 首次推送后镜像可能默认私有,需要仓库所有者在 GitHub 上改为公开(未验证)。
+- README「快速开始」缩成:电脑一条 `npx … setup`;NAS 一条 `docker run`。参数、手动配置、stdio 方式移到 `deploy/README.md`。
+
+## 7. 边界与风险
+
+- 发版到 npm、推送镜像、合并到 upstream 都是对外操作,每个阶段合并前确认。
+- 不在真实网关上调用 `mijia_disconnect`,不触发设备。
+- 在真实网关上的行为验证(重新登录、连接保持时长)由 Alex 安排,开发过程只用替身测试。
diff --git a/package-lock.json b/package-lock.json
index cd1d146..6435c9c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "oh-my-sage",
- "version": "0.1.1",
+ "version": "0.1.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "oh-my-sage",
- "version": "0.1.1",
+ "version": "0.1.2",
"dependencies": {
"@ai-sdk/anthropic": "^0.0.51",
"@ai-sdk/openai": "^0.0.58",
diff --git a/package.json b/package.json
index a65ec72..8250410 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "oh-my-sage",
- "version": "0.1.1",
+ "version": "0.1.2",
"private": true,
"scripts": {
diff --git a/src/core/gateway/manager.ts b/src/core/gateway/manager.ts
index 22c7d45..3de46c8 100644
--- a/src/core/gateway/manager.ts
+++ b/src/core/gateway/manager.ts
@@ -1,6 +1,11 @@
/**
* Core - Gateway 连接管理器
* 统一管理 Gateway 连接状态
+ *
+ * HTTP 常驻模式下所有客户端共享同一个管理器,因此:
+ * - 重新登录(换网关、换登录码)必须在新连接认证成功后才替换旧连接,
+ * 失败时保留旧连接,避免一次输错登录码让所有客户端一起掉线;
+ * - 登录请求串行执行,避免两个并发登录互相覆盖。
*/
import { GatewayClient } from './client';
@@ -19,55 +24,106 @@ async function warmUp(gateway: GatewayClient): Promise {
}
}
+/** 验证连接时使用的只读请求:返回体很小(实测约 200 字节、20 ms 级) */
+export const VERIFY_METHOD = 'getVarScopeList';
+export const VERIFY_TIMEOUT_MS = 5000;
+
+export interface GatewayVerifyResult {
+ /** 本地记录的连接状态 */
+ connected: boolean;
+ /** 网关是否实际响应了只读请求;未连接时为 false */
+ responsive: boolean;
+ /** 请求耗时(毫秒),仅在发出请求时返回 */
+ latencyMs?: number;
+ /** 失败原因 */
+ error?: string;
+}
+
+/** 管理器使用的网关客户端最小接口,便于测试替换 */
+export type GatewayClientLike = Pick;
+
+export interface GatewayManagerOptions {
+ /** 创建网关客户端;默认 new GatewayClient(),测试时可替换 */
+ createClient?: () => GatewayClientLike;
+ /** 登录成功后是否后台预热设备表与 MIOT Spec,默认 true */
+ warmUp?: boolean;
+}
+
export interface GatewayManager {
gateway: GatewayClient | null;
isConnected(): boolean;
+ /**
+ * 登录网关。已有连接时,新连接认证成功后才替换旧连接;失败时旧连接保持可用。
+ * 多次调用按顺序执行。
+ */
connect(passcode: string, gatewayUrl?: string): Promise;
disconnect(): Promise;
ensureConnected(): void;
+ /** 向网关发一次轻量只读请求,确认连接确实可用(不读缓存、不重新登录) */
+ verify?(timeoutMs?: number): Promise;
}
-export function createGatewayManager(): GatewayManager {
- let gateway: GatewayClient | null = null;
+export function createGatewayManager(options: GatewayManagerOptions = {}): GatewayManager {
+ const createClient = options.createClient ?? (() => new GatewayClient());
+ const shouldWarmUp = options.warmUp ?? true;
+ let gateway: GatewayClientLike | null = null;
+ // 登录队列:保证 connect() 串行执行
+ let queue: Promise = Promise.resolve();
+
+ const closeQuietly = async (client: GatewayClientLike | null): Promise => {
+ if (!client) return;
+ try {
+ await client.close();
+ } catch {
+ // 忽略关闭错误
+ }
+ };
+
+ const doConnect = async (passcode: string, gatewayUrl?: string): Promise => {
+ const url = gatewayUrl || process.env.GATEWAY_URL;
+ if (!url) {
+ throw new Error('未配置网关地址:请在 mijia_auth 的 gateway_url 参数中提供网关地址,或在 MCP 配置里设置 GATEWAY_URL 环境变量');
+ }
+
+ const next = createClient();
+ try {
+ await next.connect(url);
+ await next.authenticate(passcode);
+ } catch (error) {
+ // 新连接失败:关闭它,旧连接(如果有)保持不变
+ await closeQuietly(next);
+ throw error;
+ }
+
+ const previous = gateway;
+ gateway = next;
+ await closeQuietly(previous);
+
+ // 后台预热:设备表与所有设备型号的 MIOT Spec(外网请求每个约数百毫秒)。
+ // 不等待、不影响登录结果,失败只是退回按需拉取。
+ if (shouldWarmUp && next instanceof GatewayClient) void warmUp(next);
+ };
return {
get gateway() {
- return gateway;
+ return gateway as GatewayClient | null;
},
isConnected(): boolean {
return gateway !== null && gateway.isConnected();
},
- async connect(passcode: string, gatewayUrl?: string): Promise {
- const url = gatewayUrl || process.env.GATEWAY_URL;
- if (!url) {
- throw new Error('未配置网关地址:请在 mijia_auth 的 gateway_url 参数中提供网关地址,或在 MCP 配置里设置 GATEWAY_URL 环境变量');
- }
-
- if (gateway) {
- try {
- await gateway.close();
- } catch {
- }
- }
-
- gateway = new GatewayClient();
- await gateway.connect(url);
- await gateway.authenticate(passcode);
- // 后台预热:设备表与所有设备型号的 MIOT Spec(外网请求每个约数百毫秒)。
- // 不等待、不影响登录结果,失败只是退回按需拉取。
- void warmUp(gateway);
+ connect(passcode: string, gatewayUrl?: string): Promise {
+ const run = queue.then(() => doConnect(passcode, gatewayUrl));
+ // 队列只关心顺序,不传播上一次的失败
+ queue = run.catch(() => undefined);
+ return run;
},
async disconnect(): Promise {
- if (gateway) {
- try {
- await gateway.close();
- } catch {
- }
- gateway = null;
- }
+ const current = gateway;
+ gateway = null;
+ await closeQuietly(current);
},
ensureConnected(): void {
@@ -75,5 +131,24 @@ export function createGatewayManager(): GatewayManager {
throw new Error('网关未连接,请先调用 mijia_auth');
}
},
+
+ async verify(timeoutMs: number = VERIFY_TIMEOUT_MS): Promise {
+ const current = gateway;
+ if (!current || !current.isConnected()) {
+ return { connected: false, responsive: false, error: '网关未连接' };
+ }
+ const started = Date.now();
+ try {
+ await current.callApi(VERIFY_METHOD, {}, timeoutMs);
+ return { connected: true, responsive: true, latencyMs: Date.now() - started };
+ } catch (error) {
+ return {
+ connected: current.isConnected(),
+ responsive: false,
+ latencyMs: Date.now() - started,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ },
};
}
diff --git a/src/mcp/tools/auth.ts b/src/mcp/tools/auth.ts
index 3af921e..ad86e5e 100644
--- a/src/mcp/tools/auth.ts
+++ b/src/mcp/tools/auth.ts
@@ -25,11 +25,15 @@ export function registerAuthTools(
建议先调用 mijia_status:若已连接(例如 HTTP 模式下其他会话已登录),可直接使用,无需登录码。
注意:登录码是一次性的:一个登录码只能用于一次认证尝试(成功或失败后即作废)。
-每次连接(含断开后重连)都必须向用户索取一个【新的】登录码,不可复用旧码。
+每次连接都必须向用户索取一个【新的】登录码,不可复用旧码。
+
+已连接时如需更换网关或重新登录,传 reconnect=true,不要先调用 mijia_disconnect:
+新连接认证成功后才会替换现有连接;失败时现有连接保持可用,不影响其他客户端。
Args:
- passcode (string): 6位数字登录码,从网关设备上获取
- gateway_url (string, optional): 网关地址。未提供时使用 MCP 配置的 GATEWAY_URL 环境变量;两者都没有时会返回错误,请提供地址
+ - reconnect (boolean, optional): 已连接时仍重新登录(更换网关或刷新登录),默认 false
Returns:
- success: boolean - 连接是否成功
@@ -44,6 +48,7 @@ Error Handling:
inputSchema: z.object({
passcode: z.string().regex(/^\d{6}$/, "必须是6位数字").describe("6位数字登录码(一次性,每次连接都需新的)"),
gateway_url: z.string().url().optional().describe("网关地址,可选;缺省时使用 GATEWAY_URL 环境变量,两者都无则报错"),
+ reconnect: z.boolean().optional().describe("已连接时仍重新登录(更换网关或刷新登录);新连接成功后才替换现有连接,默认 false"),
}),
annotations: {
readOnlyHint: false,
@@ -52,14 +57,14 @@ Error Handling:
openWorldHint: true,
},
},
- async ({ passcode, gateway_url }) => {
- if (gatewayManager.isConnected()) {
+ async ({ passcode, gateway_url, reconnect }) => {
+ if (gatewayManager.isConnected() && !reconnect) {
// HTTP 模式下多个客户端共享同一网关连接:新会话无需登录码即可直接使用
return textResult(
formatJson({
success: false,
connected: true,
- error: "网关已连接且可直接使用,无需再次认证(不需要登录码);如确需更换网关或重新登录,请先调用 mijia_disconnect",
+ error: "网关已连接且可直接使用,无需再次认证(不需要登录码);如确需更换网关或重新登录,传 reconnect=true(新连接成功后才替换现有连接)",
}),
undefined,
true
@@ -76,7 +81,16 @@ Error Handling:
{ success: true, connected: true, gateway_url: url }
);
} catch (error) {
- return textResult(formatJson({ success: false, error: String(error) }), undefined, true);
+ const connected = gatewayManager.isConnected();
+ return textResult(
+ formatJson({
+ success: false,
+ error: String(error),
+ ...(connected ? { connected: true, message: "新连接失败,原有网关连接保持可用" } : {}),
+ }),
+ undefined,
+ true
+ );
}
}
);
@@ -88,7 +102,9 @@ Error Handling:
title: "断开网关连接",
description: `断开与米家网关的连接。
-调用后可重新调用 mijia_auth 建立新连接。建议在完成所有操作后调用以释放资源。`,
+仅在用户明确要求断开时调用;完成任务后不要调用。
+HTTP 常驻模式下所有客户端共享这一个连接,断开会让所有客户端同时失去连接,且需要用户提供新的登录码才能重新连接。
+更换网关或重新登录请用 mijia_auth 的 reconnect=true,不需要先断开。`,
inputSchema: z.object({}),
annotations: {
readOnlyHint: false,
@@ -116,9 +132,17 @@ Error Handling:
已连接时可直接调用其他工具,无需 mijia_auth;未连接时需向用户索取新的登录码后调用 mijia_auth。
+Args:
+ - verify (boolean, optional): 向网关实际发一次轻量只读请求,确认连接确实可用(不消耗登录码、不重新登录),默认 false
+
Returns:
- - connected: boolean - 是否已连接(反映网关连接的实时状态)`,
- inputSchema: z.object({}),
+ - connected: boolean - 本地记录的连接状态
+ - responsive: boolean - 仅 verify=true 时返回,网关是否实际响应
+ - latencyMs: number - 仅 verify=true 时返回,请求耗时
+ - error: string - 仅 verify=true 且未响应时返回`,
+ inputSchema: z.object({
+ verify: z.boolean().optional().describe("向网关实际发一次只读请求确认连接可用,默认 false"),
+ }),
annotations: {
readOnlyHint: true,
destructiveHint: false,
@@ -126,7 +150,11 @@ Returns:
openWorldHint: true,
},
},
- async () => {
+ async ({ verify }) => {
+ if (verify && gatewayManager.verify) {
+ const result = await gatewayManager.verify();
+ return textResult(formatJson(result), { ...result });
+ }
const connected = gatewayManager.isConnected();
return textResult(formatJson({ connected }), { connected });
}
diff --git a/tests/core/gatewayManager.test.ts b/tests/core/gatewayManager.test.ts
new file mode 100644
index 0000000..5e093b9
--- /dev/null
+++ b/tests/core/gatewayManager.test.ts
@@ -0,0 +1,157 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createGatewayManager, VERIFY_METHOD, type GatewayClientLike } from '../../src/core/gateway/manager';
+
+/** 不连接真实网关的替身客户端:按登录码决定认证成败,可控制只读请求的结果 */
+class FakeClient implements GatewayClientLike {
+ static created: FakeClient[] = [];
+ connected = false;
+ closed = false;
+ url = '';
+ calls: string[] = [];
+ callResult: 'ok' | 'fail' = 'ok';
+ authDelayMs = 0;
+
+ constructor() {
+ FakeClient.created.push(this);
+ }
+
+ async connect(url: string): Promise {
+ if (url.includes('unreachable')) throw new Error('connect ECONNREFUSED');
+ this.url = url;
+ }
+
+ async authenticate(passcode: string): Promise {
+ if (this.authDelayMs) await new Promise((resolve) => setTimeout(resolve, this.authDelayMs));
+ if (passcode === '000000') throw new Error('登录码已被使用或无效');
+ this.connected = true;
+ }
+
+ async close(): Promise {
+ this.closed = true;
+ this.connected = false;
+ }
+
+ isConnected(): boolean {
+ return this.connected;
+ }
+
+ async callApi(method: string): Promise {
+ this.calls.push(method);
+ if (this.callResult === 'fail') throw new Error(`API call timeout: ${method}`);
+ return { scopes: [] } as T;
+ }
+}
+
+function managerWithFakes(delays: number[] = []) {
+ FakeClient.created = [];
+ let index = 0;
+ return createGatewayManager({
+ warmUp: false,
+ createClient: () => {
+ const client = new FakeClient();
+ client.authDelayMs = delays[index++] ?? 0;
+ return client;
+ },
+ });
+}
+
+test('重新登录失败时保留原有连接', async () => {
+ const manager = managerWithFakes();
+ await manager.connect('111111', 'http://gw-a');
+ const original = FakeClient.created[0];
+ assert.equal(manager.isConnected(), true);
+
+ await assert.rejects(manager.connect('000000', 'http://gw-b'), /登录码/);
+ assert.equal(manager.isConnected(), true);
+ assert.equal(manager.gateway as unknown, original);
+ assert.equal(original.closed, false);
+ assert.equal(FakeClient.created[1].closed, true, '失败的新连接要被关闭');
+
+ await assert.rejects(manager.connect('222222', 'http://unreachable'), /ECONNREFUSED/);
+ assert.equal(manager.gateway as unknown, original);
+});
+
+test('重新登录成功后才替换并关闭旧连接', async () => {
+ const manager = managerWithFakes();
+ await manager.connect('111111', 'http://gw-a');
+ const original = FakeClient.created[0];
+
+ await manager.connect('222222', 'http://gw-b');
+ const next = FakeClient.created[1];
+ assert.equal(manager.gateway as unknown, next);
+ assert.equal(next.url, 'http://gw-b');
+ assert.equal(original.closed, true);
+ assert.equal(manager.isConnected(), true);
+});
+
+test('首次登录失败时保持未连接', async () => {
+ const manager = managerWithFakes();
+ await assert.rejects(manager.connect('000000', 'http://gw-a'), /登录码/);
+ assert.equal(manager.isConnected(), false);
+ assert.equal(manager.gateway, null);
+});
+
+test('未配置网关地址时报错且不创建客户端', async () => {
+ const saved = process.env.GATEWAY_URL;
+ delete process.env.GATEWAY_URL;
+ try {
+ const manager = managerWithFakes();
+ await assert.rejects(manager.connect('111111'), /未配置网关地址/);
+ assert.equal(FakeClient.created.length, 0);
+ } finally {
+ if (saved !== undefined) process.env.GATEWAY_URL = saved;
+ }
+});
+
+test('并发登录按调用顺序串行执行,最后一次成功的连接生效', async () => {
+ // 第一次认证更慢:若不串行,第一次会在第二次之后完成并覆盖它
+ const manager = managerWithFakes([40, 0]);
+ const first = manager.connect('111111', 'http://gw-a');
+ const second = manager.connect('222222', 'http://gw-b');
+ await Promise.all([first, second]);
+
+ const [a, b] = FakeClient.created;
+ assert.equal(manager.gateway as unknown, b);
+ assert.equal(a.closed, true);
+ assert.equal(b.closed, false);
+});
+
+test('前一次登录失败不影响排在后面的登录', async () => {
+ const manager = managerWithFakes([20, 0]);
+ const failed = manager.connect('000000', 'http://gw-a');
+ const ok = manager.connect('222222', 'http://gw-b');
+ await assert.rejects(failed);
+ await ok;
+ assert.equal(manager.isConnected(), true);
+ assert.equal((manager.gateway as unknown as FakeClient).url, 'http://gw-b');
+});
+
+test('verify:未连接、网关响应、网关不响应三种结果', async () => {
+ const manager = managerWithFakes();
+ assert.deepEqual(await manager.verify!(), { connected: false, responsive: false, error: '网关未连接' });
+
+ await manager.connect('111111', 'http://gw-a');
+ const client = FakeClient.created[0];
+ const ok = await manager.verify!();
+ assert.equal(ok.responsive, true);
+ assert.equal(ok.connected, true);
+ assert.equal(typeof ok.latencyMs, 'number');
+ assert.deepEqual(client.calls, [VERIFY_METHOD]);
+
+ client.callResult = 'fail';
+ const bad = await manager.verify!();
+ assert.equal(bad.responsive, false);
+ assert.match(bad.error ?? '', /timeout/);
+ // 验证失败不会断开或替换连接
+ assert.equal(manager.gateway as unknown, client);
+ assert.equal(client.closed, false);
+});
+
+test('disconnect 关闭当前连接', async () => {
+ const manager = managerWithFakes();
+ await manager.connect('111111', 'http://gw-a');
+ await manager.disconnect();
+ assert.equal(manager.isConnected(), false);
+ assert.equal(FakeClient.created[0].closed, true);
+});
diff --git a/tests/mcp/http.test.ts b/tests/mcp/http.test.ts
index c6016eb..8bc0e72 100644
--- a/tests/mcp/http.test.ts
+++ b/tests/mcp/http.test.ts
@@ -6,21 +6,23 @@ import path from 'node:path';
import test from 'node:test';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
-import type { GatewayManager } from '../../src/core/gateway/manager';
+import type { GatewayManager, GatewayVerifyResult } from '../../src/core/gateway/manager';
import { defaultAllowedHosts, resolveHttpOptions, startHttpServer, type RunningHttpServer } from '../../src/mcp/http';
import { GraphDraftStore } from '../../src/mcp/tools/graphDraft';
const TOKEN = 'test-token-123';
/** 不会真正连接网关的替身:只暴露可切换的连接状态 */
-function stubManager(): GatewayManager & { connected: boolean } {
+function stubManager(): GatewayManager & { connected: boolean; verifyResult: GatewayVerifyResult } {
return {
connected: false,
+ verifyResult: { connected: false, responsive: false, error: '网关未连接' },
gateway: null,
isConnected() { return this.connected; },
async connect() { throw new Error('stub: 不连接真实网关'); },
async disconnect() { this.connected = false; },
ensureConnected() { if (!this.connected) throw new Error('网关未连接,请先调用 mijia_auth'); },
+ async verify() { return this.verifyResult; },
};
}
@@ -144,6 +146,14 @@ test('HTTP 传输:健康检查、认证、Host 校验、并发与共享网关
assert.equal(auth.isError, true);
const text = (auth.content as Array<{ type: string; text: string }>)[0].text;
assert.match(text, /已连接且可直接使用/);
+ assert.match(text, /reconnect=true/);
+ assert.doesNotMatch(text, /先调用 mijia_disconnect/);
+
+ // verify=true 实际询问网关;替身返回可控结果
+ manager.verifyResult = { connected: true, responsive: true, latencyMs: 3 };
+ const verified = structured(await a.callTool({ name: 'mijia_status', arguments: { verify: true } }));
+ assert.equal(verified.responsive, true);
+ assert.equal(verified.latencyMs, 3);
// 一个会话断开网关,另一个会话立即看到
await a.callTool({ name: 'mijia_disconnect', arguments: {} });