windowHostControllerProjection.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { ZCodeTaskMeta } from "@zcode/shared";
  3. import {
  4. CONTROLLER_TASKS_INDEX_TOPIC,
  5. CONTROLLER_WORKSPACES_TOPIC,
  6. } from "@zcode/shared/zcode-protocol-v4";
  7. import { createWindowHostControllerProjection } from "../src/host/windowHostControllerProjection.js";
  8. function taskMeta(params: {
  9. taskId: string;
  10. workspacePath?: string;
  11. workspaceIdentity?: string;
  12. title?: string;
  13. updatedAt?: number;
  14. }): ZCodeTaskMeta {
  15. return {
  16. taskId: params.taskId,
  17. traceId: `trace-${params.taskId}`,
  18. title: params.title ?? params.taskId,
  19. workspacePath: params.workspacePath ?? "/work/demo",
  20. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  21. createdAt: 1,
  22. updatedAt: params.updatedAt ?? 2,
  23. mode: "default",
  24. };
  25. }
  26. const localScope = {
  27. kind: "local" as const,
  28. workspacePath: "/work/demo",
  29. };
  30. const remoteScope = {
  31. kind: "remote" as const,
  32. remoteSessionId: "remote-session-1",
  33. workspacePath: "/work/demo",
  34. workspaceIdentity: "remote:ssh:dev:/work/demo",
  35. };
  36. describe("WindowHostControllerProjection", () => {
  37. it("task-index 是 membership 左表,sessions-index 只能覆盖已有 task 的 live facts", () => {
  38. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  39. projection.registerSource({ scope: localScope, mutate: vi.fn() });
  40. projection.replaceSourceSnapshot({
  41. scope: localScope,
  42. taskIndex: [
  43. {
  44. meta: taskMeta({ taskId: "task-indexed" }),
  45. membership: { pinned: false, archived: false, active: true },
  46. },
  47. ],
  48. sessionsIndex: [
  49. { taskId: "task-indexed", liveStatus: "waiting" },
  50. { taskId: "session-only", liveStatus: "running" },
  51. ],
  52. });
  53. expect(projection.getTasks()).toEqual([
  54. expect.objectContaining({
  55. address: expect.objectContaining({ taskId: "task-indexed" }),
  56. liveStatus: "waiting",
  57. }),
  58. ]);
  59. });
  60. it("没有 live overlay 时不把持久化 running/阻塞残留当作当前运行事实", () => {
  61. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  62. projection.registerSource({ scope: localScope, mutate: vi.fn() });
  63. projection.replaceSourceSnapshot({
  64. scope: localScope,
  65. taskIndex: [
  66. {
  67. meta: {
  68. ...taskMeta({ taskId: "waiting-task" }),
  69. status: "running",
  70. pendingInteraction: { interactionId: "ask-1", kind: "userInput" },
  71. },
  72. membership: { pinned: false, archived: false, active: true },
  73. },
  74. ],
  75. sessionsIndex: [],
  76. });
  77. expect(projection.getTasks()[0]?.liveStatus).toBe("idle");
  78. });
  79. it("运行时 overlay 可独立更新 activity/阻塞交互,且不会把 live facts 写回 membership", () => {
  80. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  81. const frames: unknown[] = [];
  82. projection.registerSource({ scope: localScope, mutate: vi.fn() });
  83. projection.replaceSourceSnapshot({
  84. scope: localScope,
  85. taskIndex: [
  86. {
  87. meta: taskMeta({ taskId: "live-task", title: "持久标题", updatedAt: 2 }),
  88. membership: { pinned: false, archived: false, active: true },
  89. },
  90. ],
  91. sessionsIndex: [
  92. {
  93. taskId: "live-task",
  94. title: "运行标题",
  95. updatedAt: 8,
  96. liveStatus: "waiting",
  97. pendingInteraction: {
  98. interactionId: "permission-1",
  99. kind: "permission",
  100. toolName: "Bash",
  101. },
  102. activity: {
  103. phase: "running",
  104. lastActivityAt: 8,
  105. hasBackgroundWork: true,
  106. pendingInteractions: { permissionCount: 1, userInputCount: 0 },
  107. },
  108. },
  109. ],
  110. });
  111. projection.subscribe({
  112. topic: CONTROLLER_TASKS_INDEX_TOPIC,
  113. onFrame: (frame) => frames.push(frame),
  114. });
  115. frames.length = 0;
  116. expect(projection.getTasks()[0]).toMatchObject({
  117. liveStatus: "waiting",
  118. activity: {
  119. phase: "running",
  120. lastActivityAt: 8,
  121. pendingInteractions: { permissionCount: 1, userInputCount: 0 },
  122. },
  123. meta: {
  124. title: "运行标题",
  125. updatedAt: 8,
  126. pendingInteraction: { interactionId: "permission-1", kind: "permission" },
  127. },
  128. });
  129. projection.replaceSourceSessionOverlays(localScope, [
  130. {
  131. taskId: "live-task",
  132. title: "完成标题",
  133. updatedAt: 12,
  134. liveStatus: "completed",
  135. activity: {
  136. phase: "completedSuccess",
  137. lastActivityAt: 12,
  138. hasBackgroundWork: false,
  139. },
  140. },
  141. ]);
  142. expect(projection.getTasks()[0]).toMatchObject({
  143. liveStatus: "completed",
  144. activity: {
  145. phase: "completedSuccess",
  146. lastActivityAt: 12,
  147. hasBackgroundWork: false,
  148. },
  149. meta: { title: "完成标题", updatedAt: 12 },
  150. });
  151. expect(projection.getTasks()[0]?.meta.pendingInteraction).toBeUndefined();
  152. expect(frames).toHaveLength(1);
  153. });
  154. it("同路径 local 与 remote identity 的 task 不串行", () => {
  155. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  156. projection.registerSource({ scope: localScope, mutate: vi.fn() });
  157. projection.registerSource({ scope: remoteScope, mutate: vi.fn() });
  158. projection.replaceSourceSnapshot({
  159. scope: localScope,
  160. taskIndex: [
  161. {
  162. meta: taskMeta({ taskId: "same-task" }),
  163. membership: { pinned: false, archived: false, active: true },
  164. },
  165. ],
  166. sessionsIndex: [],
  167. });
  168. projection.replaceSourceSnapshot({
  169. scope: remoteScope,
  170. taskIndex: [
  171. {
  172. meta: taskMeta({
  173. taskId: "same-task",
  174. workspaceIdentity: remoteScope.workspaceIdentity,
  175. }),
  176. membership: { pinned: true, archived: false, active: true },
  177. },
  178. ],
  179. sessionsIndex: [{ taskId: "same-task", liveStatus: "running" }],
  180. });
  181. expect(projection.getTasks()).toHaveLength(2);
  182. expect(
  183. projection.getTasks().find((task) => task.address.remoteSessionId)?.membership.pinned,
  184. ).toBe(true);
  185. expect(projection.getTasks().find((task) => !task.address.remoteSessionId)?.liveStatus).toBe(
  186. "idle",
  187. );
  188. });
  189. it("断连保留最后可信 rows 并标 offline,所有 mutation fail-closed", async () => {
  190. const localMutate = vi.fn();
  191. const remoteMutate = vi.fn();
  192. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  193. projection.registerSource({ scope: localScope, mutate: localMutate });
  194. projection.registerSource({ scope: remoteScope, mutate: remoteMutate });
  195. projection.replaceSourceSnapshot({
  196. scope: remoteScope,
  197. taskIndex: [
  198. {
  199. meta: taskMeta({
  200. taskId: "remote-task",
  201. workspaceIdentity: remoteScope.workspaceIdentity,
  202. }),
  203. membership: { pinned: false, archived: false, active: true },
  204. },
  205. ],
  206. sessionsIndex: [{ taskId: "remote-task", liveStatus: "running" }],
  207. });
  208. projection.disconnectSource(remoteScope);
  209. const row = projection.getTasks()[0]!;
  210. expect(row).toMatchObject({ sourceAvailability: "offline", liveStatus: "running" });
  211. await expect(projection.mutate(row.address, { kind: "pin", pinned: true })).rejects.toThrow(
  212. "远程 source 当前离线",
  213. );
  214. expect(remoteMutate).not.toHaveBeenCalled();
  215. expect(localMutate).not.toHaveBeenCalled();
  216. });
  217. it("重连 snapshot 原子替换离线投影,不混入旧 task", () => {
  218. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  219. projection.registerSource({ scope: remoteScope, mutate: vi.fn() });
  220. projection.replaceSourceSnapshot({
  221. scope: remoteScope,
  222. taskIndex: [
  223. {
  224. meta: taskMeta({ taskId: "old-task", workspaceIdentity: remoteScope.workspaceIdentity }),
  225. membership: { pinned: false, archived: false, active: true },
  226. },
  227. ],
  228. sessionsIndex: [],
  229. });
  230. projection.disconnectSource(remoteScope);
  231. projection.replaceSourceSnapshot({
  232. scope: remoteScope,
  233. taskIndex: [
  234. {
  235. meta: taskMeta({ taskId: "new-task", workspaceIdentity: remoteScope.workspaceIdentity }),
  236. membership: { pinned: false, archived: false, active: true },
  237. },
  238. ],
  239. sessionsIndex: [],
  240. });
  241. expect(projection.getTasks().map((task) => task.address.taskId)).toEqual(["new-task"]);
  242. expect(projection.getTasks()[0]?.sourceAvailability).toBe("online");
  243. });
  244. it("remoteSessionId 换代时在同一个 delta frame 移除旧地址并写入新 snapshot", () => {
  245. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  246. const nextScope = { ...remoteScope, remoteSessionId: "remote-session-2" };
  247. const frames: Array<{ payload: { kind: string; deltas?: Array<{ op: string }> } }> = [];
  248. projection.registerSource({ scope: remoteScope, mutate: vi.fn() });
  249. projection.replaceSourceSnapshot({
  250. scope: remoteScope,
  251. taskIndex: [
  252. {
  253. meta: taskMeta({ taskId: "old-task", workspaceIdentity: remoteScope.workspaceIdentity }),
  254. membership: { pinned: false, archived: false, active: true },
  255. },
  256. ],
  257. sessionsIndex: [],
  258. });
  259. projection.disconnectSource(remoteScope);
  260. projection.registerSource({ scope: nextScope, mutate: vi.fn() });
  261. projection.subscribe({
  262. topic: CONTROLLER_TASKS_INDEX_TOPIC,
  263. onFrame: (frame) => frames.push(frame as (typeof frames)[number]),
  264. });
  265. frames.length = 0;
  266. projection.replaceSourceSnapshot({
  267. scope: nextScope,
  268. replacesScope: remoteScope,
  269. taskIndex: [
  270. {
  271. meta: taskMeta({ taskId: "new-task", workspaceIdentity: remoteScope.workspaceIdentity }),
  272. membership: { pinned: false, archived: false, active: true },
  273. },
  274. ],
  275. sessionsIndex: [],
  276. });
  277. expect(frames).toHaveLength(1);
  278. expect(frames[0]?.payload.deltas?.map((delta) => delta.op)).toEqual([
  279. "task.removed",
  280. "task.upserted",
  281. ]);
  282. expect(projection.getTasks()).toEqual([
  283. expect.objectContaining({
  284. address: expect.objectContaining({
  285. remoteSessionId: "remote-session-2",
  286. taskId: "new-task",
  287. }),
  288. }),
  289. ]);
  290. });
  291. it("关闭 remote scope 清理其内存投影,Grouped facts 始终只返回 local", () => {
  292. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  293. projection.registerSource({ scope: localScope, mutate: vi.fn() });
  294. projection.registerSource({ scope: remoteScope, mutate: vi.fn() });
  295. projection.replaceSourceSnapshot({
  296. scope: localScope,
  297. taskIndex: [
  298. {
  299. meta: taskMeta({ taskId: "local-task" }),
  300. membership: { pinned: false, archived: false, active: true },
  301. },
  302. ],
  303. sessionsIndex: [],
  304. });
  305. projection.replaceSourceSnapshot({
  306. scope: remoteScope,
  307. taskIndex: [
  308. {
  309. meta: taskMeta({
  310. taskId: "remote-task",
  311. workspaceIdentity: remoteScope.workspaceIdentity,
  312. }),
  313. membership: { pinned: false, archived: false, active: true },
  314. },
  315. ],
  316. sessionsIndex: [],
  317. });
  318. expect(projection.getGroupedTaskFacts().map((task) => task.address.taskId)).toEqual([
  319. "local-task",
  320. ]);
  321. projection.removeSource(remoteScope);
  322. expect(projection.getTasks().map((task) => task.address.taskId)).toEqual(["local-task"]);
  323. });
  324. it("列表 mutation 根据完整 address 路由唯一 source,identity mismatch 不回落", async () => {
  325. const localMutate = vi.fn(async () => undefined);
  326. const remoteMutate = vi.fn(async () => undefined);
  327. const projection = createWindowHostControllerProjection({ createId: () => "id-1" });
  328. projection.registerSource({ scope: localScope, mutate: localMutate });
  329. projection.registerSource({ scope: remoteScope, mutate: remoteMutate });
  330. projection.replaceSourceSnapshot({
  331. scope: remoteScope,
  332. taskIndex: [
  333. {
  334. meta: taskMeta({
  335. taskId: "remote-task",
  336. workspaceIdentity: remoteScope.workspaceIdentity,
  337. }),
  338. membership: { pinned: false, archived: false, active: true },
  339. },
  340. ],
  341. sessionsIndex: [],
  342. });
  343. const address = projection.getTasks()[0]!.address;
  344. await projection.mutate(address, { kind: "archive", archived: true });
  345. expect(remoteMutate).toHaveBeenCalledWith(address, { kind: "archive", archived: true });
  346. expect(localMutate).not.toHaveBeenCalled();
  347. await expect(
  348. projection.mutate(
  349. { ...address, workspaceIdentity: "remote:ssh:wrong:/work/demo" },
  350. { kind: "archive", archived: true },
  351. ),
  352. ).rejects.toThrow("没有与任务地址匹配的 source");
  353. expect(localMutate).not.toHaveBeenCalled();
  354. });
  355. it("两个 topic 都产生 snapshot/delta seq + logEpoch,订阅彼此独立", () => {
  356. let id = 0;
  357. const projection = createWindowHostControllerProjection({ createId: () => `id-${++id}` });
  358. const taskFrames: unknown[] = [];
  359. const workspaceFrames: unknown[] = [];
  360. const tasksSubscription = projection.subscribe({
  361. topic: CONTROLLER_TASKS_INDEX_TOPIC,
  362. onFrame: (frame) => taskFrames.push(frame),
  363. });
  364. projection.subscribe({
  365. topic: CONTROLLER_WORKSPACES_TOPIC,
  366. onFrame: (frame) => workspaceFrames.push(frame),
  367. });
  368. projection.registerSource({ scope: localScope, mutate: vi.fn() });
  369. projection.replaceSourceSnapshot({
  370. scope: localScope,
  371. taskIndex: [
  372. {
  373. meta: taskMeta({ taskId: "local-task" }),
  374. membership: { pinned: false, archived: false, active: true },
  375. },
  376. ],
  377. sessionsIndex: [],
  378. });
  379. expect(taskFrames).toEqual([
  380. expect.objectContaining({
  381. topic: CONTROLLER_TASKS_INDEX_TOPIC,
  382. fromSeq: 0,
  383. logEpoch: expect.any(String),
  384. payload: expect.objectContaining({ kind: "snapshot" }),
  385. }),
  386. expect.objectContaining({
  387. topic: CONTROLLER_TASKS_INDEX_TOPIC,
  388. fromSeq: 0,
  389. toSeq: 1,
  390. payload: expect.objectContaining({ kind: "deltas" }),
  391. }),
  392. ]);
  393. expect(workspaceFrames).toHaveLength(2);
  394. expect(tasksSubscription.ack.subscriptionId).not.toBe(
  395. (workspaceFrames[0] as { subscriptionId: string }).subscriptionId,
  396. );
  397. projection.replaceSourceSnapshot({
  398. scope: localScope,
  399. taskIndex: [
  400. {
  401. meta: taskMeta({ taskId: "local-task" }),
  402. membership: { pinned: false, archived: false, active: true },
  403. },
  404. ],
  405. sessionsIndex: [],
  406. });
  407. expect(taskFrames).toHaveLength(2);
  408. expect(workspaceFrames).toHaveLength(2);
  409. });
  410. });