webRemoteControlEntry.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. WebRemoteControlV2ConnectionError,
  4. type WebRemoteControlRelayV2Device,
  5. } from "@zcode/shared/web-remote-relay";
  6. import {
  7. WebRemoteControlEntry,
  8. type WebRemoteControlDeviceListAccount,
  9. } from "#src/web-remote-control/index.js";
  10. function setup(
  11. jwt: string | null = null,
  12. href = "https://zcode.z.ai/remote/v4?app_version=3.13.0&sid=device-1&mid=mid-1&name=Desktop",
  13. account: WebRemoteControlDeviceListAccount | null = null,
  14. ) {
  15. const auth = {
  16. getZCodeJwtToken: () => jwt,
  17. getActiveAccount: vi.fn(() => (jwt ? account : null)),
  18. startLogin: vi.fn(),
  19. logout: vi.fn(async () => {
  20. jwt = null;
  21. }),
  22. };
  23. const token = vi.fn(async () => "one-use-token");
  24. const connect = vi.fn();
  25. const onView = vi.fn();
  26. const devices = vi.fn<
  27. (jwt: string, signal: AbortSignal) => Promise<WebRemoteControlRelayV2Device[]>
  28. >(async () => []);
  29. const storage = new Map<string, string>();
  30. let visible: (() => void) | undefined;
  31. const storageAdapter = {
  32. getItem: (key: string) => storage.get(key) ?? null,
  33. setItem: (key: string, value: string) => {
  34. storage.set(key, value);
  35. },
  36. };
  37. const entry = new WebRemoteControlEntry({
  38. auth,
  39. token,
  40. connect,
  41. onView,
  42. getHref: () => href,
  43. devices,
  44. replaceHref: (next) => {
  45. href = next;
  46. },
  47. storage: storageAdapter,
  48. locale: "en-US",
  49. subscribeVisible: (listener) => {
  50. visible = listener;
  51. return () => {
  52. visible = undefined;
  53. };
  54. },
  55. });
  56. return {
  57. entry,
  58. auth,
  59. token,
  60. connect,
  61. onView,
  62. devices,
  63. storage,
  64. storageAdapter,
  65. setJwt: (value: string | null) => {
  66. jwt = value;
  67. },
  68. show: () => visible?.(),
  69. get href() {
  70. return href;
  71. },
  72. };
  73. }
  74. describe("V2 手机入口", () => {
  75. it("无 JWT 先登录,保留完整扫码 URL 且不建连", async () => {
  76. const h = setup();
  77. await h.entry.start();
  78. expect(h.onView).toHaveBeenLastCalledWith({ kind: "login" });
  79. expect(h.connect).not.toHaveBeenCalled();
  80. expect(h.token).not.toHaveBeenCalled();
  81. h.entry.startLogin();
  82. expect(h.auth.startLogin).toHaveBeenCalledWith({ appReturnTo: h.href });
  83. });
  84. it.each(["zai", "bigmodel"] as const)(
  85. "扫码登录透传所选平台 %s 并保留返回地址",
  86. async (provider) => {
  87. const h = setup();
  88. await h.entry.start();
  89. h.entry.startLogin(provider);
  90. expect(h.auth.startLogin).toHaveBeenCalledWith({ provider, appReturnTo: h.href });
  91. expect(h.connect).not.toHaveBeenCalled();
  92. expect(h.token).not.toHaveBeenCalled();
  93. },
  94. );
  95. it.each([
  96. "code=code-1&state=state-1",
  97. "authCode=bigmodel-code&state=state-1",
  98. "error=access_denied&state=state-1",
  99. ])("回调优先于登录门禁:%s", async (query) => {
  100. const h = setup(null, `https://zcode.z.ai/remote/v4/?${query}`);
  101. await h.entry.start();
  102. expect(h.onView).toHaveBeenCalledWith({ kind: "callback" });
  103. expect(h.connect).not.toHaveBeenCalled();
  104. });
  105. it("已登录但无 SID 拉当前账号设备,空列表不建连", async () => {
  106. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  107. await h.entry.start();
  108. expect(h.onView).toHaveBeenLastCalledWith({
  109. kind: "devices",
  110. devices: [],
  111. loading: false,
  112. error: false,
  113. });
  114. expect(h.devices).toHaveBeenCalledWith("jwt", expect.any(AbortSignal));
  115. expect(h.token).not.toHaveBeenCalled();
  116. expect(h.connect).not.toHaveBeenCalled();
  117. });
  118. it("有 SID 直接连接;每次请求 token 都重新读登录态", async () => {
  119. const h = setup("jwt");
  120. await h.entry.start();
  121. const connection = h.connect.mock.calls[0][0];
  122. expect(connection.params).toEqual({
  123. deviceSid: "device-1",
  124. deviceMid: "mid-1",
  125. deviceName: "Desktop",
  126. appVersion: "3.13.0",
  127. });
  128. const signal = new AbortController().signal;
  129. expect(await connection.getToken(signal)).toBe("one-use-token");
  130. expect(h.token).toHaveBeenCalledWith("jwt", signal);
  131. await h.auth.logout();
  132. await expect(connection.getToken(signal)).rejects.toMatchObject({ reason: "auth-required" });
  133. });
  134. it("401 清会话回登录;账号不匹配保留失败页直至用户切换账号", async () => {
  135. const h = setup("jwt");
  136. await h.entry.start();
  137. const connection = h.connect.mock.calls[0][0];
  138. connection.onFailure({ reason: "device-not-owned" });
  139. expect(h.onView).toHaveBeenLastCalledWith({
  140. kind: "failure",
  141. failure: { reason: "device-not-owned" },
  142. });
  143. expect(h.auth.logout).not.toHaveBeenCalled();
  144. await h.entry.switchAccount();
  145. expect(h.onView).toHaveBeenLastCalledWith({ kind: "login" });
  146. h.entry.startLogin();
  147. expect(h.auth.startLogin).toHaveBeenLastCalledWith({ appReturnTo: h.href });
  148. connection.onFailure({ reason: "auth-required" });
  149. await Promise.resolve();
  150. expect(h.onView).toHaveBeenLastCalledWith({ kind: "login" });
  151. });
  152. it("拒绝 V1 hash/t,不能继续尝试连接", async () => {
  153. const h = setup("jwt", "https://zcode.z.ai/remote/v4?sid=device-1&hash=secret&t=1");
  154. await h.entry.start();
  155. expect(h.onView).toHaveBeenCalledWith({
  156. kind: "failure",
  157. failure: { reason: "invalid-mobile-connection" },
  158. });
  159. expect(h.connect).not.toHaveBeenCalled();
  160. });
  161. });
  162. const onlineDevice: WebRemoteControlRelayV2Device = {
  163. device_sid: "last-device",
  164. device_mid: "abcdefgh-1234",
  165. online: true,
  166. created_at: 1,
  167. meta: { name: "Alice’s MacBook" },
  168. };
  169. const singleOnlineGroup = (device: WebRemoteControlRelayV2Device) => ({
  170. deviceMid: device.device_mid,
  171. name: device.meta.name,
  172. onlineConnections: [device],
  173. });
  174. it("同一完整 MID 的 1 在线和 11 条历史离线注册只展示一个设备,连接仍选原 SID", async () => {
  175. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  176. const offline = Array.from({ length: 11 }, (_, index) => ({
  177. ...onlineDevice,
  178. device_sid: `history-${index}`,
  179. online: false,
  180. meta: {},
  181. }));
  182. h.devices.mockResolvedValue([...offline, onlineDevice]);
  183. await h.entry.start();
  184. expect(h.onView.mock.lastCall[0].devices).toEqual([
  185. {
  186. deviceMid: onlineDevice.device_mid,
  187. name: "Alice’s MacBook",
  188. onlineConnections: [onlineDevice],
  189. },
  190. ]);
  191. await h.entry.refreshDevices();
  192. expect(h.onView.mock.lastCall[0].devices).toHaveLength(1);
  193. h.entry.selectDevice("history-0");
  194. expect(h.connect).not.toHaveBeenCalled();
  195. h.entry.selectDevice("last-device");
  196. expect(h.connect.mock.lastCall[0].params.deviceSid).toBe("last-device");
  197. });
  198. it("同 MID 全离线只展示一项,完整 MID 不同但前八位相同的设备不能合并", async () => {
  199. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  200. h.devices.mockResolvedValue([
  201. { ...onlineDevice, online: false, meta: {} },
  202. { ...onlineDevice, device_sid: "history", online: false, meta: {} },
  203. {
  204. ...onlineDevice,
  205. device_sid: "another",
  206. device_mid: "abcdefgh-5678",
  207. online: false,
  208. meta: {},
  209. },
  210. ]);
  211. await h.entry.start();
  212. expect(h.onView.mock.lastCall[0].devices).toEqual([
  213. { deviceMid: "abcdefgh-1234", name: undefined, onlineConnections: [] },
  214. { deviceMid: "abcdefgh-5678", name: undefined, onlineConnections: [] },
  215. ]);
  216. h.entry.selectDevice("last-device");
  217. expect(h.connect).not.toHaveBeenCalled();
  218. });
  219. it("多个在线 SID 保留在同一设备项内,任意连接都可被明确选择且刷新后旧连接失效", async () => {
  220. const h = setup("jwt", "https://zcode.z.ai/remote/v4?app_version=3.13.0");
  221. const other = { ...onlineDevice, device_sid: "other", meta: { name: "ZCode Dev" } };
  222. h.devices.mockResolvedValue([other, onlineDevice]);
  223. await h.entry.start();
  224. expect(h.onView.mock.lastCall[0].devices).toEqual([
  225. {
  226. deviceMid: onlineDevice.device_mid,
  227. name: "Alice’s MacBook",
  228. onlineConnections: [onlineDevice, other],
  229. },
  230. ]);
  231. expect(h.connect).not.toHaveBeenCalled();
  232. h.devices.mockResolvedValue([onlineDevice, other]);
  233. await h.entry.refreshDevices();
  234. expect(h.onView.mock.lastCall[0].devices[0].onlineConnections).toEqual([onlineDevice, other]);
  235. h.devices.mockResolvedValue([{ ...onlineDevice, online: false, meta: {} }, other]);
  236. await h.entry.refreshDevices();
  237. h.entry.selectDevice("last-device");
  238. expect(h.connect).not.toHaveBeenCalled();
  239. h.entry.selectDevice("other");
  240. expect(Object.fromEntries(new URL(h.href).searchParams)).toEqual({
  241. app_version: "3.13.0",
  242. sid: "other",
  243. mid: onlineDevice.device_mid,
  244. name: "ZCode Dev",
  245. });
  246. expect(h.storage.get("zcode-web-remote-last-device-sid")).toBe("other");
  247. expect(h.storage.get("zcode-web-remote-last-device-mid")).toBe(onlineDevice.device_mid);
  248. });
  249. it("最近 SID 在线时优先连接原 SID,即使同 MID 还有其他在线连接", async () => {
  250. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  251. const preferred = { ...onlineDevice, device_sid: "preferred", meta: { name: "ZCode Dev" } };
  252. h.storage.set("zcode-web-remote-last-device-sid", "preferred");
  253. h.devices.mockResolvedValue([onlineDevice, preferred]);
  254. await h.entry.start();
  255. expect(h.connect).toHaveBeenCalledOnce();
  256. expect(h.connect.mock.lastCall[0].params.deviceSid).toBe("preferred");
  257. });
  258. it("最近 SID 离线时,同一台电脑恰好一个在线连接则自动接上;MID 取自列表中的离线记录", async () => {
  259. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  260. const preferred = { ...onlineDevice, device_sid: "preferred", online: false, meta: {} };
  261. h.storage.set("zcode-web-remote-last-device-sid", "preferred");
  262. h.devices.mockResolvedValue([onlineDevice, preferred]);
  263. await h.entry.start();
  264. expect(h.connect).toHaveBeenCalledOnce();
  265. expect(h.connect.mock.lastCall[0].params).toMatchObject({
  266. deviceSid: "last-device",
  267. deviceMid: onlineDevice.device_mid,
  268. });
  269. expect(h.storage.get("zcode-web-remote-last-device-sid")).toBe("last-device");
  270. expect(h.storage.get("zcode-web-remote-last-device-mid")).toBe(onlineDevice.device_mid);
  271. });
  272. it("最近 SID 已被删除时按记住的最近 MID 接上唯一在线连接", async () => {
  273. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  274. h.storage.set("zcode-web-remote-last-device-sid", "deleted-sid");
  275. h.storage.set("zcode-web-remote-last-device-mid", onlineDevice.device_mid);
  276. const otherMachine = { ...onlineDevice, device_mid: "mid-other", device_sid: "other-sid" };
  277. h.devices.mockResolvedValue([otherMachine, onlineDevice]);
  278. await h.entry.start();
  279. expect(h.connect).toHaveBeenCalledOnce();
  280. expect(h.connect.mock.lastCall[0].params.deviceSid).toBe("last-device");
  281. });
  282. it.each([
  283. ["同 MID 有多个在线连接", [onlineDevice, { ...onlineDevice, device_sid: "second" }]],
  284. ["同 MID 全离线", [{ ...onlineDevice, online: false, meta: {} }]],
  285. ["只有其他电脑在线", [{ ...onlineDevice, device_mid: "mid-other", device_sid: "other-sid" }]],
  286. ])("最近 SID 不在线且%s时展示列表,不猜测连接目标", async (_case, records) => {
  287. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  288. h.storage.set("zcode-web-remote-last-device-sid", "deleted-sid");
  289. h.storage.set("zcode-web-remote-last-device-mid", onlineDevice.device_mid);
  290. h.devices.mockResolvedValue(records);
  291. await h.entry.start();
  292. expect(h.connect).not.toHaveBeenCalled();
  293. expect(h.onView.mock.lastCall[0].kind).toBe("devices");
  294. });
  295. it("列表视图携带当前账号展示资料,刷新后保持", async () => {
  296. const account = { displayName: "Ada", provider: "zai" as const };
  297. const h = setup("jwt", "https://zcode.z.ai/remote/v4", account);
  298. h.devices.mockResolvedValue([{ ...onlineDevice, meta: { name: "Mac", platform: "darwin" } }]);
  299. await h.entry.start();
  300. expect(h.onView.mock.lastCall[0]).toMatchObject({
  301. account,
  302. devices: [{ deviceMid: onlineDevice.device_mid, platform: "darwin" }],
  303. });
  304. await h.entry.refreshDevices();
  305. expect(h.onView.mock.lastCall[0].account).toEqual(account);
  306. });
  307. it("无码入口自动连接当前账号在线的最近设备,并回写可恢复 URL", async () => {
  308. const h = setup("jwt", "https://zcode.z.ai/remote/v4?app_version=3.13.0&name=stale");
  309. h.storage.set("zcode-web-remote-last-device-sid", "last-device");
  310. h.devices.mockResolvedValue([onlineDevice]);
  311. await h.entry.start();
  312. expect(h.connect).toHaveBeenCalledOnce();
  313. expect(h.connect.mock.calls[0][0].params).toEqual({
  314. deviceSid: "last-device",
  315. deviceMid: "abcdefgh-1234",
  316. deviceName: "Alice’s MacBook",
  317. appVersion: "3.13.0",
  318. });
  319. const url = new URL(h.href);
  320. expect(Object.fromEntries(url.searchParams)).toEqual({
  321. sid: "last-device",
  322. mid: "abcdefgh-1234",
  323. name: "Alice’s MacBook",
  324. app_version: "3.13.0",
  325. });
  326. });
  327. it("最近设备离线时在线置顶按名字排序;手动/回前台刷新不自动连接,选择后只接纳一次", async () => {
  328. const h = setup("jwt", "https://zcode.z.ai/remote/v4?app_version=3.13.0&name=stale");
  329. h.storage.set("zcode-web-remote-last-device-sid", "last-device");
  330. const offline = { ...onlineDevice, online: false, meta: {} };
  331. const beta = {
  332. ...onlineDevice,
  333. device_mid: "mid-beta",
  334. device_sid: "beta",
  335. meta: { name: "Beta" },
  336. };
  337. const alpha = {
  338. ...onlineDevice,
  339. device_mid: "mid-alpha",
  340. device_sid: "alpha",
  341. meta: { name: "Alpha" },
  342. };
  343. const unnamed = { ...onlineDevice, device_mid: "mid-unnamed", device_sid: "unnamed", meta: {} };
  344. h.devices.mockResolvedValue([offline, beta, unnamed, alpha]);
  345. await h.entry.start();
  346. expect(h.onView).toHaveBeenLastCalledWith({
  347. kind: "devices",
  348. devices: [
  349. singleOnlineGroup(alpha),
  350. singleOnlineGroup(beta),
  351. singleOnlineGroup(unnamed),
  352. { deviceMid: offline.device_mid, name: undefined, onlineConnections: [] },
  353. ],
  354. loading: false,
  355. error: false,
  356. });
  357. h.entry.selectDevice("last-device");
  358. expect(h.connect).not.toHaveBeenCalled();
  359. h.devices.mockResolvedValue([onlineDevice, unnamed]);
  360. await h.entry.refreshDevices();
  361. h.show();
  362. await vi.waitFor(() => expect(h.devices).toHaveBeenCalledTimes(3));
  363. expect(h.connect).not.toHaveBeenCalled();
  364. await vi.waitFor(() =>
  365. expect(h.onView).toHaveBeenLastCalledWith({
  366. kind: "devices",
  367. devices: [singleOnlineGroup(onlineDevice), singleOnlineGroup(unnamed)],
  368. loading: false,
  369. error: false,
  370. }),
  371. );
  372. h.entry.selectDevice("unnamed");
  373. h.entry.selectDevice("unnamed");
  374. expect(h.connect).toHaveBeenCalledOnce();
  375. expect(Object.fromEntries(new URL(h.href).searchParams)).toEqual({
  376. app_version: "3.13.0",
  377. sid: "unnamed",
  378. mid: "mid-unnamed",
  379. });
  380. expect(h.storage.get("zcode-web-remote-last-device-sid")).toBe("unnamed");
  381. h.show();
  382. expect(h.devices).toHaveBeenCalledTimes(3);
  383. });
  384. it("切换账号取消并发刷新,迟到旧账号列表不能覆盖登录页", async () => {
  385. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  386. const pending = Promise.withResolvers<WebRemoteControlRelayV2Device[]>();
  387. h.devices.mockReturnValue(pending.promise);
  388. const started = h.entry.start();
  389. h.show();
  390. void h.entry.refreshDevices();
  391. expect(h.devices).toHaveBeenCalledOnce();
  392. const signal = h.devices.mock.calls[0][1];
  393. await h.entry.switchAccount();
  394. expect(signal.aborted).toBe(true);
  395. pending.resolve([onlineDevice]);
  396. await started;
  397. expect(h.onView).toHaveBeenLastCalledWith({ kind: "login" });
  398. expect(h.connect).not.toHaveBeenCalled();
  399. h.show();
  400. expect(h.devices).toHaveBeenCalledOnce();
  401. });
  402. it("列表刷新失败显示错误且禁用旧列表,401 则回登录并保留 URL", async () => {
  403. const h = setup("jwt", "https://zcode.z.ai/remote/v4?app_version=3.13.0");
  404. h.devices.mockResolvedValue([onlineDevice]);
  405. await h.entry.start();
  406. h.devices.mockRejectedValueOnce(new Error("network"));
  407. await h.entry.refreshDevices();
  408. expect(h.onView).toHaveBeenLastCalledWith({
  409. kind: "devices",
  410. devices: [singleOnlineGroup(onlineDevice)],
  411. loading: false,
  412. error: true,
  413. });
  414. h.entry.selectDevice("last-device");
  415. expect(h.connect).not.toHaveBeenCalled();
  416. h.devices.mockRejectedValueOnce(new WebRemoteControlV2ConnectionError("auth-required"));
  417. await h.entry.refreshDevices();
  418. expect(h.onView).toHaveBeenLastCalledWith({ kind: "login" });
  419. expect(h.auth.logout).toHaveBeenCalledOnce();
  420. h.entry.startLogin();
  421. expect(h.auth.startLogin).toHaveBeenCalledWith({ appReturnTo: h.href });
  422. });
  423. it("选择其他设备释放连接、移除目标参数并跳过最近设备;旧连接事件无效", async () => {
  424. const h = setup("jwt");
  425. await h.entry.start();
  426. const old = h.connect.mock.calls[0][0];
  427. old.onPaired();
  428. expect(h.storage.get("zcode-web-remote-last-device-sid")).toBe("device-1");
  429. expect(h.storage.get("zcode-web-remote-last-device-mid")).toBe("mid-1");
  430. h.devices.mockResolvedValue([{ ...onlineDevice, device_sid: "device-1" }]);
  431. await h.entry.chooseOtherDevice();
  432. expect(old.signal.aborted).toBe(true);
  433. expect(Object.fromEntries(new URL(h.href).searchParams)).toEqual({ app_version: "3.13.0" });
  434. expect(h.connect).toHaveBeenCalledOnce();
  435. old.onFailure({ reason: "auth-required" });
  436. old.onPaired();
  437. expect(h.auth.logout).not.toHaveBeenCalled();
  438. expect(h.onView.mock.lastCall[0].kind).toBe("devices");
  439. });
  440. it("账号在列表显示后变化时,旧设备选择重新经过当前账号列表", async () => {
  441. const h = setup("alice", "https://zcode.z.ai/remote/v4");
  442. h.devices.mockResolvedValue([onlineDevice]);
  443. await h.entry.start();
  444. h.setJwt("bob");
  445. h.devices.mockResolvedValue([]);
  446. h.entry.selectDevice("last-device");
  447. await vi.waitFor(() =>
  448. expect(h.devices).toHaveBeenLastCalledWith("bob", expect.any(AbortSignal)),
  449. );
  450. expect(h.connect).not.toHaveBeenCalled();
  451. expect(new URL(h.href).searchParams.has("sid")).toBe(false);
  452. });
  453. it("存储不可用不阻断手动选择;已有 SID 业务状态保持原样", async () => {
  454. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  455. h.storage.set("zcode-web-remote-client-id:last-device", "existing-client");
  456. vi.spyOn(h.storageAdapter, "getItem").mockImplementation(() => {
  457. throw new Error("blocked");
  458. });
  459. vi.spyOn(h.storageAdapter, "setItem").mockImplementation(() => {
  460. throw new Error("blocked");
  461. });
  462. h.devices.mockResolvedValue([onlineDevice]);
  463. await h.entry.start();
  464. expect(h.onView.mock.lastCall[0].devices).toEqual([singleOnlineGroup(onlineDevice)]);
  465. h.entry.selectDevice("last-device");
  466. expect(h.connect).toHaveBeenCalledOnce();
  467. h.connect.mock.calls[0][0].onPaired();
  468. expect(h.storage.get("zcode-web-remote-client-id:last-device")).toBe("existing-client");
  469. });
  470. it("最近 SID 不属于当前账号时不连接;同名按 MID/SID 排序且没有轮询", async () => {
  471. vi.useFakeTimers();
  472. try {
  473. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  474. h.storage.set("zcode-web-remote-last-device-sid", "other-account-device");
  475. const b = { ...onlineDevice, device_mid: "mid-b" };
  476. const a2 = { ...onlineDevice, device_mid: "mid-a", device_sid: "sid-2" };
  477. const a1 = { ...a2, device_sid: "sid-1" };
  478. h.devices.mockResolvedValue([b, a2, a1]);
  479. await h.entry.start();
  480. expect(h.onView.mock.lastCall[0].devices).toEqual([
  481. { deviceMid: "mid-a", name: "Alice’s MacBook", onlineConnections: [a1, a2] },
  482. singleOnlineGroup(b),
  483. ]);
  484. await vi.advanceTimersByTimeAsync(60_000);
  485. expect(h.devices).toHaveBeenCalledOnce();
  486. expect(h.connect).not.toHaveBeenCalled();
  487. h.entry.dispose();
  488. h.show();
  489. expect(h.devices).toHaveBeenCalledOnce();
  490. } finally {
  491. vi.useRealTimers();
  492. }
  493. });
  494. it("聚合列表刷新期间拒绝所有 SID,刷新成全离线后保留记住的名字但不保留连接", async () => {
  495. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  496. const other = { ...onlineDevice, device_sid: "other" };
  497. h.devices.mockResolvedValue([onlineDevice, other]);
  498. await h.entry.start();
  499. const pending = Promise.withResolvers<WebRemoteControlRelayV2Device[]>();
  500. h.devices.mockReturnValueOnce(pending.promise);
  501. const refreshed = h.entry.refreshDevices();
  502. h.entry.selectDevice("last-device");
  503. h.entry.selectDevice("other");
  504. expect(h.connect).not.toHaveBeenCalled();
  505. pending.resolve([onlineDevice, other].map((device) => ({ ...device, online: false, meta: {} })));
  506. await refreshed;
  507. expect(h.onView.mock.lastCall[0].devices).toEqual([
  508. { deviceMid: onlineDevice.device_mid, name: "Alice’s MacBook", onlineConnections: [] },
  509. ]);
  510. h.entry.selectDevice("other");
  511. expect(h.connect).not.toHaveBeenCalled();
  512. });
  513. const DEVICE_NAMES_KEY = "zcode-web-remote-device-names";
  514. describe("本地记住的设备名与平台", () => {
  515. it("在线平台写入缓存,下次该设备离线时仍显示记住的平台", async () => {
  516. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  517. h.devices.mockResolvedValue([
  518. { ...onlineDevice, meta: { name: "Alice’s MacBook", platform: "darwin" } },
  519. ]);
  520. await h.entry.start();
  521. expect(JSON.parse(h.storage.get(DEVICE_NAMES_KEY)!)).toEqual([
  522. ["abcdefgh-1234", "Alice’s MacBook", "darwin"],
  523. ]);
  524. const next = setup("jwt", "https://zcode.z.ai/remote/v4");
  525. next.storage.set(DEVICE_NAMES_KEY, h.storage.get(DEVICE_NAMES_KEY)!);
  526. next.devices.mockResolvedValue([{ ...onlineDevice, online: false, meta: {} }]);
  527. await next.entry.start();
  528. expect(next.onView.mock.lastCall[0].devices).toEqual([
  529. {
  530. deviceMid: "abcdefgh-1234",
  531. name: "Alice’s MacBook",
  532. platform: "darwin",
  533. onlineConnections: [],
  534. },
  535. ]);
  536. });
  537. it("在线设备名按 MID 写入本地缓存;下次入口该设备离线时显示记住的名字且仍不可连接", async () => {
  538. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  539. h.devices.mockResolvedValue([onlineDevice]);
  540. await h.entry.start();
  541. expect(JSON.parse(h.storage.get(DEVICE_NAMES_KEY)!)).toEqual([
  542. ["abcdefgh-1234", "Alice’s MacBook"],
  543. ]);
  544. // 模拟下次打开:新入口实例复用同一份 localStorage 内容
  545. const next = setup("jwt", "https://zcode.z.ai/remote/v4");
  546. next.storage.set(DEVICE_NAMES_KEY, h.storage.get(DEVICE_NAMES_KEY)!);
  547. next.devices.mockResolvedValue([
  548. { ...onlineDevice, device_sid: "history", online: false, meta: {} },
  549. ]);
  550. await next.entry.start();
  551. expect(next.onView).toHaveBeenLastCalledWith({
  552. kind: "devices",
  553. devices: [{ deviceMid: "abcdefgh-1234", name: "Alice’s MacBook", onlineConnections: [] }],
  554. loading: false,
  555. error: false,
  556. });
  557. next.entry.selectDevice("history");
  558. expect(next.connect).not.toHaveBeenCalled();
  559. });
  560. it("在线记录无名字时回退到记住的名字;电脑改名后上线刷新覆盖旧名字", async () => {
  561. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  562. h.storage.set(DEVICE_NAMES_KEY, JSON.stringify([["abcdefgh-1234", "Old Name"]]));
  563. h.devices.mockResolvedValue([{ ...onlineDevice, meta: {} }]);
  564. await h.entry.start();
  565. expect(h.onView.mock.lastCall[0].devices[0].name).toBe("Old Name");
  566. h.devices.mockResolvedValue([{ ...onlineDevice, meta: { name: " New Name " } }]);
  567. await h.entry.refreshDevices();
  568. expect(h.onView.mock.lastCall[0].devices[0].name).toBe("New Name");
  569. expect(JSON.parse(h.storage.get(DEVICE_NAMES_KEY)!)).toEqual([["abcdefgh-1234", "New Name"]]);
  570. });
  571. it("离线设备按记住的名字排序,没有名字的离线设备排最后;全离线刷新不写缓存", async () => {
  572. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  573. const seeded = JSON.stringify([
  574. ["mid-b", "Beta"],
  575. ["mid-a", "Alpha"],
  576. ]);
  577. h.storage.set(DEVICE_NAMES_KEY, seeded);
  578. const offline = (mid: string) => ({
  579. ...onlineDevice,
  580. device_mid: mid,
  581. device_sid: `${mid}-sid`,
  582. online: false,
  583. meta: {},
  584. });
  585. h.devices.mockResolvedValue([offline("mid-c"), offline("mid-b"), offline("mid-a")]);
  586. await h.entry.start();
  587. expect(h.onView.mock.lastCall[0].devices).toEqual([
  588. { deviceMid: "mid-a", name: "Alpha", onlineConnections: [] },
  589. { deviceMid: "mid-b", name: "Beta", onlineConnections: [] },
  590. { deviceMid: "mid-c", name: undefined, onlineConnections: [] },
  591. ]);
  592. expect(h.storage.get(DEVICE_NAMES_KEY)).toBe(seeded);
  593. });
  594. it("缓存内容损坏按空处理,不阻断列表;刷新成功后重写为合法内容", async () => {
  595. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  596. h.storage.set(DEVICE_NAMES_KEY, "{not json");
  597. h.devices.mockResolvedValue([
  598. onlineDevice,
  599. { ...onlineDevice, device_mid: "mid-x", device_sid: "sid-x", online: false, meta: {} },
  600. ]);
  601. await h.entry.start();
  602. expect(h.onView.mock.lastCall[0].devices).toEqual([
  603. singleOnlineGroup(onlineDevice),
  604. { deviceMid: "mid-x", name: undefined, onlineConnections: [] },
  605. ]);
  606. expect(JSON.parse(h.storage.get(DEVICE_NAMES_KEY)!)).toEqual([
  607. ["abcdefgh-1234", "Alice’s MacBook"],
  608. ]);
  609. });
  610. it("切换账号不清除设备名缓存", async () => {
  611. const h = setup("jwt", "https://zcode.z.ai/remote/v4");
  612. h.devices.mockResolvedValue([onlineDevice]);
  613. await h.entry.start();
  614. await h.entry.switchAccount();
  615. expect(h.onView).toHaveBeenLastCalledWith({ kind: "login" });
  616. expect(JSON.parse(h.storage.get(DEVICE_NAMES_KEY)!)).toEqual([
  617. ["abcdefgh-1234", "Alice’s MacBook"],
  618. ]);
  619. });
  620. });