windowHostControllerService.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. import { describe, expect, it, vi } from "vitest";
  2. import { Emitter } from "@zcode/rpc";
  3. import type { ZCodeTaskMeta } from "@zcode/shared";
  4. import type {
  5. IZCodeAgentService,
  6. IZCodeTaskService,
  7. WindowHostControllerFrame,
  8. } from "@zcode/services";
  9. import {
  10. CONTROLLER_TASKS_INDEX_TOPIC,
  11. type SessionsIndexTopicWireCandidate,
  12. } from "@zcode/shared/zcode-protocol-v4";
  13. import { createWindowHostControllerRuntime } from "../src/host/windowHostControllerService.js";
  14. function meta(params: {
  15. taskId: string;
  16. workspacePath?: string;
  17. workspaceIdentity?: string;
  18. createdAt?: number;
  19. }): ZCodeTaskMeta {
  20. return {
  21. taskId: params.taskId,
  22. traceId: `trace-${params.taskId}`,
  23. title: params.taskId,
  24. workspacePath: params.workspacePath ?? "/work/demo",
  25. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  26. createdAt: params.createdAt ?? 1,
  27. updatedAt: params.createdAt ?? 1,
  28. mode: "default",
  29. };
  30. }
  31. function taskService(params: {
  32. active?: ZCodeTaskMeta[];
  33. pinned?: ZCodeTaskMeta[];
  34. archived?: ZCodeTaskMeta[];
  35. search?: ZCodeTaskMeta[];
  36. }) {
  37. return {
  38. listTasks: vi.fn(async () => params.active ?? []),
  39. listPinnedTasks: vi.fn(async () => params.pinned ?? []),
  40. listArchivedTasks: vi.fn(async () => params.archived ?? []),
  41. listTaskList: vi.fn(async () => ({
  42. items: params.search ?? [],
  43. total: params.search?.length ?? 0,
  44. hasMore: false,
  45. })),
  46. setTaskPinned: vi.fn(async ({ pinned }: { pinned: boolean }) =>
  47. meta({ taskId: pinned ? "pinned" : "unpinned" }),
  48. ),
  49. archiveTask: vi.fn(async () => meta({ taskId: "archived" })),
  50. unarchiveTask: vi.fn(async () => meta({ taskId: "unarchived" })),
  51. deleteTask: vi.fn(async () => undefined),
  52. setTaskUnread: vi.fn(async () => meta({ taskId: "unread" })),
  53. } as unknown as IZCodeTaskService;
  54. }
  55. const remoteIdentity = "remote:ssh:dev:22:user:/work/demo";
  56. describe("WindowHostControllerService", () => {
  57. it("routes unopened remote task commands by Source identity without requiring a logical attachment or earlier list query", async () => {
  58. const workspaceIdentity = "remote:server:source-1:/work/demo";
  59. const remote = taskService({ active: [meta({ taskId: "remote", workspaceIdentity })] });
  60. remote.renameTask = vi.fn(async ({ title }) => ({
  61. ...meta({ taskId: "remote", workspaceIdentity }),
  62. title,
  63. }));
  64. const runtime = createWindowHostControllerRuntime({
  65. createId: () => "id",
  66. resolveSource: (scope) =>
  67. scope.workspaceIdentity === workspaceIdentity
  68. ? {
  69. scope: {
  70. kind: "remote",
  71. sourceServerId: "source-1",
  72. workspacePath: scope.workspacePath,
  73. workspaceIdentity,
  74. },
  75. taskService: remote,
  76. sourceAvailability: "online",
  77. }
  78. : null,
  79. });
  80. const address = {
  81. sourceServerId: "source-1",
  82. workspacePath: "/work/demo",
  83. workspaceIdentity,
  84. taskId: "remote",
  85. };
  86. await runtime.service.mutateTask({ address, mutation: { kind: "rename", title: "New title" } });
  87. expect(remote.renameTask).toHaveBeenCalledWith({
  88. workspacePath: "/work/demo",
  89. workspaceIdentity,
  90. taskId: "remote",
  91. title: "New title",
  92. });
  93. await expect(
  94. runtime.service.mutateTask({
  95. address: { ...address, sourceServerId: "other" },
  96. mutation: { kind: "pin", pinned: true },
  97. }),
  98. ).rejects.toThrow();
  99. expect(remote.setTaskPinned).not.toHaveBeenCalled();
  100. const list = await runtime.service.listTaskList({
  101. kind: "active",
  102. workspaceScopes: [{ workspacePath: "/work/demo", workspaceIdentity }],
  103. sortBy: "updated",
  104. });
  105. expect(list.items).toHaveLength(1);
  106. expect(list.items[0]).toMatchObject({ taskId: "remote", sourceServerId: "source-1" });
  107. expect(list.items[0]?.remoteSessionId).toBeUndefined();
  108. });
  109. it("从 source Agent 的 existing-only sessions-index 读取 live activity", async () => {
  110. const frames = new Emitter<SessionsIndexTopicWireCandidate>();
  111. const runtimeLifecycle = new Emitter<{
  112. workspaceKey: string;
  113. workspacePath: string;
  114. workspaceIdentity?: string;
  115. state: "available" | "unavailable";
  116. runtimeIdentity: { workspaceKey: string; generation: number };
  117. }>();
  118. const agentService = {
  119. onDynamicSessionsIndexFrame: vi.fn(() => frames.event),
  120. onAgentRuntimeLifecycle: runtimeLifecycle.event,
  121. onAgentRuntimeRestarted: vi.fn(() => ({ dispose: vi.fn() })),
  122. subscribeSessionsIndexV4: vi.fn(async () => {
  123. frames.fire({
  124. wireVersion: 3,
  125. kind: "complete",
  126. deliveryKind: "initial",
  127. logicalFrameId: "initial-1",
  128. logicalFrameOrdinal: 1,
  129. topic: "sessions-index//work/demo",
  130. subscriptionId: "sessions-sub-1",
  131. frame: {
  132. topic: "sessions-index//work/demo",
  133. subscriptionId: "sessions-sub-1",
  134. fromSeq: 0,
  135. toSeq: 1,
  136. sentAt: 1,
  137. payload: {
  138. kind: "snapshot",
  139. snapshot: {
  140. protocolVersion: 1,
  141. workspaceId: "/work/demo",
  142. logEpoch: "sessions-epoch-1",
  143. sessions: [
  144. {
  145. sessionId: "live",
  146. workspaceId: "/work/demo",
  147. title: "正在运行",
  148. phase: "running",
  149. sessionEnded: false,
  150. hasBackgroundWork: true,
  151. workflowActivity: {
  152. runs: [
  153. {
  154. runId: "run-1",
  155. toolCallId: "tool-1",
  156. name: "Deep research",
  157. status: "running",
  158. phases: [{ name: "Research", status: "running" }],
  159. currentPhase: "Research",
  160. agentsWorking: 1,
  161. },
  162. ],
  163. },
  164. pendingInteraction: {
  165. interactionId: "ask-1",
  166. kind: "userInput",
  167. toolName: "AskUserQuestion",
  168. },
  169. pendingInteractionSummary: {
  170. permissionCount: 0,
  171. userInputCount: 1,
  172. },
  173. lastActivityAt: 20,
  174. createdAt: 1,
  175. },
  176. ],
  177. },
  178. },
  179. },
  180. });
  181. return {
  182. ack: { subscriptionId: "sessions-sub-1", mode: "snapshot", logEpoch: "sessions-epoch-1" },
  183. };
  184. }),
  185. resyncSessionsIndexV4: vi.fn(),
  186. unsubscribeSessionsIndexV4: vi.fn(async () => undefined),
  187. } as unknown as IZCodeAgentService;
  188. const local = taskService({ active: [meta({ taskId: "live" })] });
  189. const runtime = createWindowHostControllerRuntime({
  190. createId: () => "id",
  191. resolveSource: (scope) => ({
  192. scope: { kind: "local" as const, ...scope },
  193. taskService: local,
  194. agentService,
  195. sourceAvailability: "online" as const,
  196. }),
  197. });
  198. const result = await runtime.service.listTaskList({
  199. kind: "active",
  200. workspaceScopes: [{ workspacePath: "/work/demo" }],
  201. sortBy: "updated",
  202. });
  203. expect(agentService.subscribeSessionsIndexV4).toHaveBeenCalledWith(
  204. expect.objectContaining({
  205. workspacePath: "/work/demo",
  206. subscriberScope: "window-controller",
  207. runtimePolicy: "existing-only",
  208. }),
  209. );
  210. expect(result.items).toEqual([
  211. expect.objectContaining({
  212. taskId: "live",
  213. title: "正在运行",
  214. updatedAt: 20,
  215. liveStatus: "waiting",
  216. pendingInteraction: expect.objectContaining({ interactionId: "ask-1" }),
  217. activity: {
  218. phase: "running",
  219. lastActivityAt: 20,
  220. hasBackgroundWork: true,
  221. workflowActivity: {
  222. runs: [
  223. {
  224. runId: "run-1",
  225. toolCallId: "tool-1",
  226. name: "Deep research",
  227. status: "running",
  228. phases: [{ name: "Research", status: "running" }],
  229. currentPhase: "Research",
  230. agentsWorking: 1,
  231. },
  232. ],
  233. },
  234. pendingInteractions: { permissionCount: 0, userInputCount: 1 },
  235. },
  236. }),
  237. ]);
  238. frames.fire({
  239. wireVersion: 3,
  240. kind: "complete",
  241. deliveryKind: "online",
  242. logicalFrameId: "delta-2",
  243. logicalFrameOrdinal: 2,
  244. topic: "sessions-index//work/demo",
  245. subscriptionId: "sessions-sub-1",
  246. frame: {
  247. topic: "sessions-index//work/demo",
  248. subscriptionId: "sessions-sub-1",
  249. fromSeq: 1,
  250. toSeq: 2,
  251. sentAt: 2,
  252. payload: {
  253. kind: "deltas",
  254. deltas: [
  255. {
  256. op: "session.upserted",
  257. session: {
  258. sessionId: "live",
  259. workspaceId: "/work/demo",
  260. title: "已经完成",
  261. phase: "completedSuccess",
  262. sessionEnded: true,
  263. hasBackgroundWork: false,
  264. lastActivityAt: 30,
  265. createdAt: 1,
  266. },
  267. },
  268. ],
  269. },
  270. },
  271. });
  272. const completed = await runtime.service.listTaskList({
  273. kind: "active",
  274. workspaceScopes: [{ workspacePath: "/work/demo" }],
  275. sortBy: "updated",
  276. });
  277. expect(completed.items[0]).toMatchObject({
  278. liveStatus: "completed",
  279. activity: { phase: "completedSuccess", lastActivityAt: 30 },
  280. });
  281. expect(local.listTasks).toHaveBeenCalledTimes(1);
  282. expect(local.listPinnedTasks).toHaveBeenCalledTimes(1);
  283. expect(local.listArchivedTasks).toHaveBeenCalledTimes(1);
  284. runtime.dispose();
  285. });
  286. it("在 Host 内聚合 local 与 remote task rows,并为结果附加 source 地址", async () => {
  287. const local = taskService({ active: [meta({ taskId: "local", createdAt: 1 })] });
  288. const remote = taskService({
  289. pinned: [meta({ taskId: "remote", workspaceIdentity: remoteIdentity, createdAt: 2 })],
  290. });
  291. const runtime = createWindowHostControllerRuntime({
  292. createId: () => "id",
  293. resolveSource: (scope) =>
  294. scope.workspaceIdentity
  295. ? {
  296. scope: {
  297. kind: "remote" as const,
  298. sourceServerId: "source-server-1",
  299. serverDisplayName: "Dev Server",
  300. remoteSessionId: "remote-1",
  301. ...scope,
  302. workspaceIdentity: scope.workspaceIdentity,
  303. },
  304. taskService: remote,
  305. sourceAvailability: "online" as const,
  306. }
  307. : {
  308. scope: { kind: "local" as const, ...scope },
  309. taskService: local,
  310. sourceAvailability: "online" as const,
  311. },
  312. });
  313. const result = await runtime.service.listTaskList({
  314. kind: "active",
  315. workspaceScopes: [
  316. { workspacePath: "/work/demo" },
  317. { workspacePath: "/work/demo", workspaceIdentity: remoteIdentity },
  318. ],
  319. sortBy: "created",
  320. });
  321. expect(result.items.map((item) => item.taskId)).toEqual(["remote", "local"]);
  322. expect(result.items[0]).toMatchObject({
  323. sourceServerId: "source-server-1",
  324. serverDisplayName: "Dev Server",
  325. remoteSessionId: "remote-1",
  326. sourceAvailability: "online",
  327. });
  328. });
  329. it("同一 source 的并发列表查询共享一次 task-index refresh", async () => {
  330. const local = taskService({ active: [meta({ taskId: "local" })] });
  331. const runtime = createWindowHostControllerRuntime({
  332. createId: () => "id",
  333. resolveSource: (scope) => ({
  334. scope: { kind: "local" as const, ...scope },
  335. taskService: local,
  336. sourceAvailability: "online" as const,
  337. }),
  338. });
  339. await Promise.all([
  340. runtime.service.listTaskList({
  341. kind: "active",
  342. workspaceScopes: [{ workspacePath: "/work/demo" }],
  343. sortBy: "updated",
  344. }),
  345. runtime.service.listTaskList({
  346. kind: "timeline",
  347. workspaceScopes: [{ workspacePath: "/work/demo" }],
  348. sortBy: "updated",
  349. }),
  350. ]);
  351. expect(local.listTasks).toHaveBeenCalledTimes(1);
  352. expect(local.listPinnedTasks).toHaveBeenCalledTimes(1);
  353. expect(local.listArchivedTasks).toHaveBeenCalledTimes(1);
  354. });
  355. it("断连后保留最后可信投影,非搜索可读但写入 fail-closed", async () => {
  356. const remote = taskService({
  357. active: [meta({ taskId: "remote", workspaceIdentity: remoteIdentity })],
  358. });
  359. let online = true;
  360. const runtime = createWindowHostControllerRuntime({
  361. createId: () => "id",
  362. resolveSource: (scope) => ({
  363. scope: {
  364. kind: "remote" as const,
  365. remoteSessionId: "remote-1",
  366. ...scope,
  367. workspaceIdentity: scope.workspaceIdentity!,
  368. },
  369. taskService: online ? remote : undefined,
  370. sourceAvailability: online ? "online" : "offline",
  371. }),
  372. });
  373. const query = {
  374. kind: "active" as const,
  375. workspaceScopes: [{ workspacePath: "/work/demo", workspaceIdentity: remoteIdentity }],
  376. sortBy: "updated" as const,
  377. };
  378. await runtime.service.listTaskList(query);
  379. online = false;
  380. runtime.disconnectSource({
  381. kind: "remote",
  382. remoteSessionId: "remote-1",
  383. workspacePath: "/work/demo",
  384. workspaceIdentity: remoteIdentity,
  385. });
  386. const offline = await runtime.service.listTaskList(query);
  387. expect(offline.items).toEqual([
  388. expect.objectContaining({ taskId: "remote", sourceAvailability: "offline" }),
  389. ]);
  390. await expect(
  391. runtime.service.mutateTask({
  392. address: {
  393. remoteSessionId: "remote-1",
  394. workspacePath: "/work/demo",
  395. workspaceIdentity: remoteIdentity,
  396. taskId: "remote",
  397. },
  398. mutation: { kind: "delete" },
  399. }),
  400. ).rejects.toThrow("远程 source 当前离线");
  401. expect(remote.deleteTask).not.toHaveBeenCalled();
  402. });
  403. it("全文搜索只查询在线 source,不用离线摘要伪造结果", async () => {
  404. const runtime = createWindowHostControllerRuntime({
  405. createId: () => "id",
  406. resolveSource: (scope) => ({
  407. scope: {
  408. kind: "remote" as const,
  409. remoteSessionId: "remote-1",
  410. ...scope,
  411. workspaceIdentity: scope.workspaceIdentity!,
  412. },
  413. sourceAvailability: "offline" as const,
  414. }),
  415. });
  416. const result = await runtime.service.listTaskList({
  417. kind: "active",
  418. workspaceScopes: [{ workspacePath: "/work/demo", workspaceIdentity: remoteIdentity }],
  419. sortBy: "updated",
  420. search: "needle",
  421. });
  422. expect(result).toEqual({ items: [], total: 0, hasMore: false });
  423. });
  424. it("列表 mutation 按完整 task address 路由到唯一 task service", async () => {
  425. const remote = taskService({
  426. active: [meta({ taskId: "remote", workspaceIdentity: remoteIdentity })],
  427. });
  428. const runtime = createWindowHostControllerRuntime({
  429. createId: () => "id",
  430. resolveSource: (scope) => ({
  431. scope: {
  432. kind: "remote" as const,
  433. remoteSessionId: "remote-1",
  434. ...scope,
  435. workspaceIdentity: scope.workspaceIdentity!,
  436. },
  437. taskService: remote,
  438. sourceAvailability: "online" as const,
  439. }),
  440. });
  441. await runtime.service.listTaskList({
  442. kind: "active",
  443. workspaceScopes: [{ workspacePath: "/work/demo", workspaceIdentity: remoteIdentity }],
  444. sortBy: "updated",
  445. });
  446. await runtime.service.mutateTask({
  447. address: {
  448. remoteSessionId: "remote-1",
  449. workspacePath: "/work/demo",
  450. workspaceIdentity: remoteIdentity,
  451. taskId: "remote",
  452. },
  453. mutation: { kind: "pin", pinned: true },
  454. });
  455. expect(remote.setTaskPinned).toHaveBeenCalledWith({
  456. taskId: "remote",
  457. workspacePath: "/work/demo",
  458. workspaceIdentity: remoteIdentity,
  459. pinned: true,
  460. });
  461. });
  462. it("归档条件删除保留 remote 地址与跳过结果,离线 source 禁止写入", async () => {
  463. const remote = taskService({
  464. archived: [meta({ taskId: "remote", workspaceIdentity: remoteIdentity })],
  465. });
  466. remote.deleteArchivedTask = vi.fn(async () => false);
  467. let online = true;
  468. const runtime = createWindowHostControllerRuntime({
  469. createId: () => "id",
  470. resolveSource: (scope) => ({
  471. scope: {
  472. kind: "remote" as const,
  473. remoteSessionId: "remote-1",
  474. ...scope,
  475. workspaceIdentity: scope.workspaceIdentity!,
  476. },
  477. taskService: remote,
  478. sourceAvailability: online ? "online" : "offline",
  479. }),
  480. });
  481. const address = await runtime.resolveTaskAddress({
  482. workspacePath: "/work/demo",
  483. workspaceIdentity: remoteIdentity,
  484. taskId: "remote",
  485. });
  486. expect(await runtime.service.deleteArchivedTask({ address })).toBe(false);
  487. expect(remote.deleteArchivedTask).toHaveBeenCalledWith({
  488. workspacePath: "/work/demo",
  489. workspaceIdentity: remoteIdentity,
  490. taskId: "remote",
  491. });
  492. online = false;
  493. await expect(runtime.service.deleteArchivedTask({ address })).rejects.toThrow("离线");
  494. expect(remote.deleteArchivedTask).toHaveBeenCalledTimes(1);
  495. });
  496. it("remote attachment 首次列表写入会先建立 Controller source", async () => {
  497. const remote = taskService({
  498. active: [meta({ taskId: "remote", workspaceIdentity: remoteIdentity })],
  499. });
  500. const runtime = createWindowHostControllerRuntime({
  501. createId: () => "id",
  502. resolveSource: (scope) => ({
  503. scope: {
  504. kind: "remote" as const,
  505. remoteSessionId: "remote-1",
  506. ...scope,
  507. workspaceIdentity: scope.workspaceIdentity!,
  508. },
  509. taskService: remote,
  510. sourceAvailability: "online" as const,
  511. }),
  512. });
  513. const address = await runtime.resolveTaskAddress({
  514. taskId: "remote",
  515. workspacePath: "/work/demo",
  516. workspaceIdentity: remoteIdentity,
  517. attachmentScope: {
  518. kind: "remote",
  519. remoteSessionId: "remote-1",
  520. workspacePath: "/work/demo",
  521. workspaceIdentity: remoteIdentity,
  522. },
  523. });
  524. await runtime.service.mutateTask({
  525. address,
  526. mutation: { kind: "mark-unread" },
  527. });
  528. expect(remote.setTaskUnread).toHaveBeenCalledWith({
  529. taskId: "remote",
  530. workspacePath: "/work/demo",
  531. workspaceIdentity: remoteIdentity,
  532. unread: true,
  533. });
  534. });
  535. it("remote attachment 已过期时不刷新或写入当前同 workspace source", async () => {
  536. const remote = taskService({
  537. active: [meta({ taskId: "remote", workspaceIdentity: remoteIdentity })],
  538. });
  539. const runtime = createWindowHostControllerRuntime({
  540. createId: () => "id",
  541. resolveSource: (scope) => ({
  542. scope: {
  543. kind: "remote" as const,
  544. remoteSessionId: "remote-current",
  545. ...scope,
  546. workspaceIdentity: scope.workspaceIdentity!,
  547. },
  548. taskService: remote,
  549. sourceAvailability: "online" as const,
  550. }),
  551. });
  552. await expect(
  553. runtime.resolveTaskAddress({
  554. taskId: "remote",
  555. workspacePath: "/work/demo",
  556. workspaceIdentity: remoteIdentity,
  557. attachmentScope: {
  558. kind: "remote",
  559. remoteSessionId: "remote-stale",
  560. workspacePath: "/work/demo",
  561. workspaceIdentity: remoteIdentity,
  562. },
  563. }),
  564. ).rejects.toThrow("列表 mutation 与 remote attachment source 不匹配");
  565. expect(remote.listTasks).not.toHaveBeenCalled();
  566. expect(remote.setTaskUnread).not.toHaveBeenCalled();
  567. });
  568. it("单个 remote source 读取失败不影响 local 与其他 source 列表", async () => {
  569. const local = taskService({ active: [meta({ taskId: "local" })] });
  570. const brokenRemote = taskService({});
  571. brokenRemote.listTasks = vi.fn(async () => {
  572. throw new Error("remote unavailable");
  573. });
  574. const sourceErrors = vi.fn();
  575. const runtime = createWindowHostControllerRuntime({
  576. createId: () => "id",
  577. onSourceError: sourceErrors,
  578. resolveSource: (scope) =>
  579. scope.workspaceIdentity
  580. ? {
  581. scope: {
  582. kind: "remote" as const,
  583. remoteSessionId: "remote-1",
  584. ...scope,
  585. workspaceIdentity: scope.workspaceIdentity,
  586. },
  587. taskService: brokenRemote,
  588. sourceAvailability: "online" as const,
  589. }
  590. : {
  591. scope: { kind: "local" as const, ...scope },
  592. taskService: local,
  593. sourceAvailability: "online" as const,
  594. },
  595. });
  596. const result = await runtime.service.listTaskList({
  597. kind: "active",
  598. workspaceScopes: [
  599. { workspacePath: "/work/demo" },
  600. { workspacePath: "/work/demo", workspaceIdentity: remoteIdentity },
  601. ],
  602. sortBy: "updated",
  603. });
  604. expect(result.items.map((item) => item.taskId)).toEqual(["local"]);
  605. expect(sourceErrors).toHaveBeenCalledWith(
  606. expect.objectContaining({ kind: "remote" }),
  607. "refresh",
  608. expect.any(Error),
  609. );
  610. });
  611. it("重连 snapshot 读取失败时保留旧离线投影,后续成功后再原子替换", async () => {
  612. const oldService = taskService({
  613. active: [meta({ taskId: "old", workspaceIdentity: remoteIdentity })],
  614. });
  615. const nextService = taskService({
  616. active: [meta({ taskId: "new", workspaceIdentity: remoteIdentity })],
  617. });
  618. let sessionId = "remote-old";
  619. let service: IZCodeTaskService = oldService;
  620. const runtime = createWindowHostControllerRuntime({
  621. createId: () => "id",
  622. resolveSource: (scope) => ({
  623. scope: {
  624. kind: "remote" as const,
  625. remoteSessionId: sessionId,
  626. ...scope,
  627. workspaceIdentity: scope.workspaceIdentity!,
  628. },
  629. taskService: service,
  630. sourceAvailability: "online" as const,
  631. }),
  632. });
  633. const query = {
  634. kind: "active" as const,
  635. workspaceScopes: [{ workspacePath: "/work/demo", workspaceIdentity: remoteIdentity }],
  636. sortBy: "updated" as const,
  637. };
  638. await runtime.service.listTaskList(query);
  639. runtime.disconnectSource({
  640. kind: "remote",
  641. remoteSessionId: "remote-old",
  642. workspacePath: "/work/demo",
  643. workspaceIdentity: remoteIdentity,
  644. });
  645. sessionId = "remote-new";
  646. service = nextService;
  647. nextService.listTasks = vi.fn(async () => {
  648. throw new Error("snapshot unavailable");
  649. });
  650. await expect(
  651. runtime.replaceDisconnectedSource(
  652. {
  653. kind: "remote",
  654. remoteSessionId: "remote-old",
  655. workspacePath: "/work/demo",
  656. workspaceIdentity: remoteIdentity,
  657. },
  658. {
  659. scope: {
  660. kind: "remote",
  661. remoteSessionId: "remote-new",
  662. workspacePath: "/work/demo",
  663. workspaceIdentity: remoteIdentity,
  664. },
  665. taskService: nextService,
  666. sourceAvailability: "online",
  667. },
  668. ),
  669. ).rejects.toThrow("snapshot unavailable");
  670. expect(await runtime.service.listTaskList(query)).toEqual(
  671. expect.objectContaining({
  672. items: [
  673. expect.objectContaining({
  674. taskId: "old",
  675. remoteSessionId: "remote-old",
  676. sourceAvailability: "offline",
  677. }),
  678. ],
  679. }),
  680. );
  681. runtime.disconnectSource({
  682. kind: "remote",
  683. remoteSessionId: "remote-new",
  684. workspacePath: "/work/demo",
  685. workspaceIdentity: remoteIdentity,
  686. });
  687. const finalService = taskService({
  688. active: [meta({ taskId: "new", workspaceIdentity: remoteIdentity })],
  689. });
  690. sessionId = "remote-final";
  691. service = finalService;
  692. await runtime.replaceDisconnectedSource(
  693. {
  694. kind: "remote",
  695. remoteSessionId: "remote-new",
  696. workspacePath: "/work/demo",
  697. workspaceIdentity: remoteIdentity,
  698. },
  699. {
  700. scope: {
  701. kind: "remote",
  702. remoteSessionId: "remote-final",
  703. workspacePath: "/work/demo",
  704. workspaceIdentity: remoteIdentity,
  705. },
  706. taskService: finalService,
  707. sourceAvailability: "online",
  708. },
  709. );
  710. const replaced = await runtime.service.listTaskList(query);
  711. expect(replaced.items).toEqual([
  712. expect.objectContaining({
  713. taskId: "new",
  714. remoteSessionId: "remote-final",
  715. sourceAvailability: "online",
  716. }),
  717. ]);
  718. const snapshots: WindowHostControllerFrame[] = [];
  719. const frameSubscription = runtime.service.onDynamicControllerFrame()((frame) => {
  720. snapshots.push(frame);
  721. });
  722. await runtime.service.subscribeControllerV4({
  723. topic: CONTROLLER_TASKS_INDEX_TOPIC,
  724. visibility: "foreground",
  725. });
  726. const snapshot = snapshots.at(-1);
  727. expect(snapshot?.topic).toBe(CONTROLLER_TASKS_INDEX_TOPIC);
  728. expect(
  729. snapshot?.topic === CONTROLLER_TASKS_INDEX_TOPIC && snapshot.payload.kind === "snapshot"
  730. ? snapshot.payload.snapshot.tasks.map((task) => task.address.remoteSessionId)
  731. : [],
  732. ).toEqual(["remote-final"]);
  733. frameSubscription.dispose();
  734. });
  735. it("Registry replacement CAS 失效时丢弃 provisional source 并保留旧投影", async () => {
  736. const oldService = taskService({
  737. active: [meta({ taskId: "old", workspaceIdentity: remoteIdentity })],
  738. });
  739. const nextService = taskService({
  740. active: [meta({ taskId: "new", workspaceIdentity: remoteIdentity })],
  741. });
  742. const disposeDynamicSubscription = vi.fn();
  743. nextService.onDynamicWorkspaceEvent = vi.fn(() => () => ({
  744. dispose: disposeDynamicSubscription,
  745. }));
  746. let sessionId = "remote-old";
  747. let service: IZCodeTaskService = oldService;
  748. let sourceAvailability: "online" | "offline" = "online";
  749. const runtime = createWindowHostControllerRuntime({
  750. createId: () => "id",
  751. resolveSource: (scope) => ({
  752. scope: {
  753. kind: "remote" as const,
  754. remoteSessionId: sessionId,
  755. ...scope,
  756. workspaceIdentity: scope.workspaceIdentity!,
  757. },
  758. taskService: service,
  759. sourceAvailability,
  760. }),
  761. });
  762. const query = {
  763. kind: "active" as const,
  764. workspaceScopes: [{ workspacePath: "/work/demo", workspaceIdentity: remoteIdentity }],
  765. sortBy: "updated" as const,
  766. };
  767. await runtime.service.listTaskList(query);
  768. runtime.disconnectSource({
  769. kind: "remote",
  770. remoteSessionId: "remote-old",
  771. workspacePath: "/work/demo",
  772. workspaceIdentity: remoteIdentity,
  773. });
  774. sourceAvailability = "offline";
  775. sessionId = "remote-new";
  776. service = nextService;
  777. await expect(
  778. runtime.replaceDisconnectedSource(
  779. {
  780. kind: "remote",
  781. remoteSessionId: "remote-old",
  782. workspacePath: "/work/demo",
  783. workspaceIdentity: remoteIdentity,
  784. },
  785. {
  786. scope: {
  787. kind: "remote",
  788. remoteSessionId: "remote-new",
  789. workspacePath: "/work/demo",
  790. workspaceIdentity: remoteIdentity,
  791. },
  792. taskService: nextService,
  793. sourceAvailability: "online",
  794. },
  795. { canCommit: () => false, rollbackOnFailure: true },
  796. ),
  797. ).rejects.toThrow("Controller source replacement generation 已失效");
  798. expect(disposeDynamicSubscription).toHaveBeenCalledTimes(1);
  799. sessionId = "remote-old";
  800. service = oldService;
  801. expect(await runtime.service.listTaskList(query)).toEqual(
  802. expect.objectContaining({
  803. items: [
  804. expect.objectContaining({
  805. taskId: "old",
  806. remoteSessionId: "remote-old",
  807. sourceAvailability: "offline",
  808. }),
  809. ],
  810. }),
  811. );
  812. });
  813. });