useGlobalTaskListSessionsIndex.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // timeline/pinned/archived 查询路径:tasks-index 提供持久行与 membership,
  2. // sessions-index 只补充实时 activity/detail。验证 kind 过滤与字段权威边界;
  3. // 纯本地无搜索场景旧 listTaskList 零调用;搜索场景回落旧全文检索路径。
  4. import { act, createElement } from "react";
  5. import { createRoot, type Root } from "react-dom/client";
  6. import { afterEach, describe, expect, it, vi } from "vitest";
  7. import { Emitter } from "@zcode/rpc";
  8. import type { IServiceAccessor, ZCodeTaskListKind } from "@zcode/services";
  9. import type { ZCodeTaskMeta } from "@zcode/shared";
  10. import type {
  11. SessionsIndexTopicFrame,
  12. SessionsIndexTopicWireFrame,
  13. SessionSummary,
  14. } from "@zcode/shared/zcode-protocol-v4";
  15. import { ServiceProvider } from "@/hooks/useServices.js";
  16. import { useGlobalTaskList } from "@/hooks/useGlobalTaskList.js";
  17. import { useRemoteWorkspaceSessionStore } from "@/store/remoteWorkspaceSessionStore.js";
  18. import { useTaskQueryCacheStore } from "@/store/taskQueryCacheStore.js";
  19. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  20. import type { WorkspaceTabState } from "@/store/tabStore.js";
  21. function createSession(overrides: Partial<SessionSummary> = {}): SessionSummary {
  22. return {
  23. sessionId: "s-1",
  24. workspaceId: "ws-1",
  25. title: "Session 1",
  26. phase: "completedSuccess",
  27. sessionEnded: true,
  28. hasBackgroundWork: false,
  29. lastActivityAt: 2,
  30. createdAt: 1,
  31. ...overrides,
  32. };
  33. }
  34. function createWorkspaceTab(): WorkspaceTabState {
  35. return {
  36. id: "workspace-1",
  37. kind: "workspace",
  38. label: "workspace",
  39. workspacePath: "/workspace",
  40. };
  41. }
  42. function createTaskMeta(overrides: Partial<ZCodeTaskMeta> = {}): ZCodeTaskMeta {
  43. return {
  44. createdAt: 1,
  45. mode: "default",
  46. taskId: "s-1",
  47. title: "Task 1",
  48. traceId: "trace-s-1",
  49. updatedAt: 2,
  50. workspacePath: "/workspace",
  51. ...overrides,
  52. } as ZCodeTaskMeta;
  53. }
  54. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  55. const element = {
  56. addEventListener: () => {},
  57. appendChild: (child: { parentNode?: unknown }) => {
  58. child.parentNode = element;
  59. return child;
  60. },
  61. childNodes: [] as unknown[],
  62. getAttribute: () => null,
  63. insertBefore: (child: { parentNode?: unknown }) => {
  64. child.parentNode = element;
  65. return child;
  66. },
  67. nodeName: tagName.toUpperCase(),
  68. nodeType: 1,
  69. ownerDocument,
  70. parentNode: null as unknown,
  71. removeAttribute: () => {},
  72. removeChild: (child: { parentNode?: unknown }) => {
  73. child.parentNode = null;
  74. return child;
  75. },
  76. removeEventListener: () => {},
  77. setAttribute: () => {},
  78. style: {},
  79. tagName: tagName.toUpperCase(),
  80. };
  81. return element as unknown as Element;
  82. }
  83. function installMinimalDom() {
  84. const documentMock = {
  85. addEventListener: () => {},
  86. createElement: (tagName: string) =>
  87. createMinimalElement(documentMock as unknown as Document, tagName),
  88. createElementNS: (_namespace: string, tagName: string) =>
  89. createMinimalElement(documentMock as unknown as Document, tagName),
  90. createTextNode: (nodeValue: string) => ({
  91. nodeType: 3,
  92. nodeValue,
  93. ownerDocument: documentMock,
  94. parentNode: null,
  95. }),
  96. nodeType: 9,
  97. removeEventListener: () => {},
  98. } as unknown as Document;
  99. const windowMock = {
  100. addEventListener: () => {},
  101. clearTimeout,
  102. document: documentMock,
  103. HTMLIFrameElement: function HTMLIFrameElement() {},
  104. HTMLElement: function HTMLElement() {},
  105. Node: function Node() {},
  106. removeEventListener: () => {},
  107. setTimeout,
  108. };
  109. Object.defineProperty(globalThis, "document", {
  110. configurable: true,
  111. value: documentMock,
  112. });
  113. Object.defineProperty(globalThis, "window", {
  114. configurable: true,
  115. value: windowMock,
  116. });
  117. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  118. configurable: true,
  119. value: true,
  120. });
  121. return createMinimalElement(documentMock);
  122. }
  123. async function flushMicrotasks() {
  124. await Promise.resolve();
  125. await Promise.resolve();
  126. await Promise.resolve();
  127. }
  128. function snapshotFrame(sessions: SessionSummary[]): SessionsIndexTopicFrame {
  129. return {
  130. topic: "sessions-index//workspace",
  131. subscriptionId: "sub-1",
  132. fromSeq: 0,
  133. toSeq: 1,
  134. sentAt: 1,
  135. payload: {
  136. kind: "snapshot",
  137. snapshot: { protocolVersion: 1, workspaceId: "ws-1", logEpoch: "e1", sessions },
  138. },
  139. };
  140. }
  141. let logicalFrameSerial = 0;
  142. function physicalFrame(
  143. frame: SessionsIndexTopicFrame,
  144. deliveryKind: "initial" | "online" = "online",
  145. ): SessionsIndexTopicWireFrame {
  146. logicalFrameSerial += 1;
  147. return {
  148. wireVersion: 3,
  149. kind: "complete",
  150. deliveryKind,
  151. logicalFrameId: `logical-global-local-${logicalFrameSerial}`,
  152. logicalFrameOrdinal: logicalFrameSerial,
  153. topic: frame.topic,
  154. subscriptionId: frame.subscriptionId,
  155. frame,
  156. };
  157. }
  158. interface HarnessOptions {
  159. kind: ZCodeTaskListKind;
  160. expanded?: boolean;
  161. searchQuery?: string;
  162. sessions: SessionSummary[];
  163. pinnedIds?: string[];
  164. archivedTaskIds?: string[];
  165. activeTaskMetas?: ZCodeTaskMeta[];
  166. archivedTaskMetas?: ZCodeTaskMeta[];
  167. pinnedTaskMetas?: ZCodeTaskMeta[];
  168. }
  169. function v4Handshake() {
  170. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  171. return {
  172. helloConversationV4: vi.fn(async () => ({
  173. kind: "hello" as const,
  174. protocolVersion: 3 as const,
  175. connectionId: "connection-local",
  176. clientMode: "desktop-continuous" as const,
  177. deliveryProfile: "continuous" as const,
  178. serverTime: 1,
  179. capabilities: {
  180. nativeDialogs: true,
  181. localTerminal: true,
  182. binaryFrames: false,
  183. compression: "none" as const,
  184. },
  185. auth: {},
  186. })),
  187. initializeConversationV4: vi.fn(async () => {}),
  188. resyncSessionsIndexV4: vi.fn(async (params: { subscriptionId: string }) => ({
  189. ack: { subscriptionId: params.subscriptionId, mode: "snapshot" as const, logEpoch: "e1" },
  190. })),
  191. onAgentRuntimeRestarted: runtimeRestarts.event,
  192. };
  193. }
  194. async function renderHarness(options: HarnessOptions) {
  195. const listTaskList = vi.fn(async () => ({ items: [], total: 0, hasMore: false }));
  196. const frameListeners: Array<(frame: SessionsIndexTopicWireFrame) => void> = [];
  197. const archivedIds = new Set(options.archivedTaskIds ?? []);
  198. const pinnedIds = new Set(options.pinnedIds ?? []);
  199. const defaultTaskMetas = options.sessions.map((session) =>
  200. createTaskMeta({
  201. createdAt: session.createdAt,
  202. taskId: session.sessionId,
  203. title: session.title,
  204. traceId: `trace-${session.sessionId}`,
  205. updatedAt: session.lastActivityAt,
  206. }),
  207. );
  208. const activeTaskMetas =
  209. options.activeTaskMetas ??
  210. defaultTaskMetas.filter(
  211. (task) => !pinnedIds.has(task.taskId) && !archivedIds.has(task.taskId),
  212. );
  213. const pinnedTaskMetas =
  214. options.pinnedTaskMetas ??
  215. defaultTaskMetas.filter(
  216. (task) => pinnedIds.has(task.taskId) && !archivedIds.has(task.taskId),
  217. );
  218. const archivedTaskMetas =
  219. options.archivedTaskMetas ??
  220. (options.archivedTaskIds ?? []).map((taskId) =>
  221. createTaskMeta({ taskId, title: taskId, traceId: `trace-${taskId}` }),
  222. );
  223. const controllerFrames = new Emitter<never>();
  224. const controllerListTaskList = vi.fn(async (params: { kind: ZCodeTaskListKind; search?: string; limit?: number }) => {
  225. if (params.search) {
  226. return listTaskList();
  227. }
  228. const rows =
  229. params.kind === "pinned"
  230. ? pinnedTaskMetas
  231. : params.kind === "archived"
  232. ? archivedTaskMetas
  233. : params.kind === "active"
  234. ? [...activeTaskMetas, ...pinnedTaskMetas]
  235. : activeTaskMetas;
  236. const sessionById = new Map(options.sessions.map((session) => [session.sessionId, session]));
  237. const items = rows
  238. .map((task) => {
  239. const session = sessionById.get(task.taskId);
  240. return {
  241. ...task,
  242. ...(session
  243. ? {
  244. title: session.title,
  245. updatedAt: session.lastActivityAt,
  246. status:
  247. session.phase === "completedSuccess"
  248. ? ("completed" as const)
  249. : session.phase === "completedError"
  250. ? ("error" as const)
  251. : task.status,
  252. }
  253. : {}),
  254. sourceAvailability: "online" as const,
  255. };
  256. })
  257. .sort((left, right) => right.updatedAt - left.updatedAt);
  258. const visible = params.limit == null ? items : items.slice(0, params.limit);
  259. return { items: visible, total: items.length, hasMore: items.length > visible.length };
  260. });
  261. const services = {
  262. windowControllerService: {
  263. listTaskList: controllerListTaskList,
  264. mutateTask: vi.fn(async () => null),
  265. subscribeControllerV4: vi.fn(async ({ topic }: { topic: string }) => ({
  266. ack: { subscriptionId: `sub-${topic}`, mode: "snapshot" as const, logEpoch: "e1" },
  267. })),
  268. resyncControllerV4: vi.fn(async ({ subscriptionId }: { subscriptionId: string }) => ({
  269. ack: { subscriptionId, mode: "snapshot" as const, logEpoch: "e1" },
  270. })),
  271. unsubscribeControllerV4: vi.fn(async () => {}),
  272. onDynamicControllerFrame: () => controllerFrames.event,
  273. },
  274. zcodeTaskService: {
  275. listTaskList,
  276. listPinnedTaskIds: vi.fn(async () => options.pinnedIds ?? []),
  277. listArchivedTasks: vi.fn(async () => archivedTaskMetas),
  278. listTasks: vi.fn(async () => activeTaskMetas),
  279. listPinnedTasks: vi.fn(async () => pinnedTaskMetas),
  280. onDynamicWorkspaceEvent: () => () => ({ dispose() {} }),
  281. },
  282. zcodeAgentService: {
  283. ...v4Handshake(),
  284. subscribeSessionsIndexV4: vi.fn(async () => {
  285. const initial = snapshotFrame(options.sessions);
  286. for (const listener of frameListeners) listener(physicalFrame(initial, "initial"));
  287. return {
  288. ack: { subscriptionId: "sub-1", mode: "snapshot" as const, logEpoch: "e1" },
  289. };
  290. }),
  291. unsubscribeSessionsIndexV4: vi.fn(async () => {}),
  292. onDynamicSessionsIndexFrame:
  293. () => (listener: (frame: SessionsIndexTopicWireFrame) => void) => {
  294. frameListeners.push(listener);
  295. return { dispose: () => {} };
  296. },
  297. },
  298. } as unknown as IServiceAccessor;
  299. const workspaceTabs = [createWorkspaceTab()];
  300. let latest: ReturnType<typeof useGlobalTaskList> | null = null;
  301. function Probe() {
  302. latest = useGlobalTaskList({
  303. collapsedLimit: 5,
  304. expanded: options.expanded ?? false,
  305. kind: options.kind,
  306. searchQuery: options.searchQuery ?? "",
  307. sortBy: "updated",
  308. workspaceTabs,
  309. });
  310. return null;
  311. }
  312. const root: Root = createRoot(installMinimalDom());
  313. await act(async () => {
  314. root.render(createElement(ServiceProvider, { services }, createElement(Probe)));
  315. await flushMicrotasks();
  316. });
  317. await act(async () => {
  318. await flushMicrotasks();
  319. });
  320. return {
  321. getItems: () => latest?.items ?? [],
  322. listTaskList,
  323. unmount: () =>
  324. act(() => {
  325. root.unmount();
  326. }),
  327. };
  328. }
  329. describe("useGlobalTaskList tasks-index 行 + sessions-index detail", () => {
  330. afterEach(() => {
  331. useTaskQueryCacheStore.getState().clearAll();
  332. useRemoteWorkspaceSessionStore.setState({
  333. baseServices: null,
  334. sessionsById: {},
  335. sessionIdByWorkspaceIdentity: {},
  336. sessionIdByWorkspacePath: {},
  337. });
  338. useZCodeSessionStore.setState({ workspaces: {} });
  339. delete (globalThis as { document?: unknown }).document;
  340. delete (globalThis as { window?: unknown }).window;
  341. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  342. });
  343. it("timeline:行来自 tasks-index,排除 pinned/archived,listTaskList 零调用", async () => {
  344. const harness = await renderHarness({
  345. kind: "timeline",
  346. sessions: [
  347. createSession({ sessionId: "s-1", lastActivityAt: 10 }),
  348. createSession({ sessionId: "s-2", lastActivityAt: 30 }),
  349. createSession({ sessionId: "s-3", lastActivityAt: 20 }),
  350. ],
  351. pinnedIds: ["s-2"],
  352. archivedTaskIds: ["s-3"],
  353. });
  354. expect(harness.getItems().map((task) => task.taskId)).toEqual(["s-1"]);
  355. expect(harness.listTaskList).not.toHaveBeenCalled();
  356. harness.unmount();
  357. });
  358. it("timeline:从 tasks-index membership join 未读,但实时状态归 sessions-index", async () => {
  359. const harness = await renderHarness({
  360. kind: "timeline",
  361. sessions: [createSession({ sessionId: "s-1", phase: "completedSuccess" })],
  362. activeTaskMetas: [createTaskMeta({ taskId: "s-1", unreadAt: 123, status: "error" })],
  363. });
  364. const item = harness.getItems()[0];
  365. expect(item?.taskId).toBe("s-1");
  366. expect(item?.unreadAt).toBe(123);
  367. expect(item?.status).toBe("completed");
  368. expect(harness.listTaskList).not.toHaveBeenCalled();
  369. harness.unmount();
  370. });
  371. it("pinned:只含 pinned 且非 archived", async () => {
  372. const harness = await renderHarness({
  373. kind: "pinned",
  374. sessions: [
  375. createSession({ sessionId: "s-1" }),
  376. createSession({ sessionId: "s-2", lastActivityAt: 5 }),
  377. ],
  378. pinnedIds: ["s-1", "s-2"],
  379. archivedTaskIds: ["s-2"],
  380. });
  381. expect(harness.getItems().map((task) => task.taskId)).toEqual(["s-1"]);
  382. expect(harness.listTaskList).not.toHaveBeenCalled();
  383. harness.unmount();
  384. });
  385. it("archived:只含 archived", async () => {
  386. const harness = await renderHarness({
  387. kind: "archived",
  388. sessions: [
  389. createSession({ sessionId: "s-1" }),
  390. createSession({ sessionId: "s-2", lastActivityAt: 5 }),
  391. ],
  392. archivedTaskIds: ["s-2"],
  393. });
  394. expect(harness.getItems().map((task) => task.taskId)).toEqual(["s-2"]);
  395. expect(harness.listTaskList).not.toHaveBeenCalled();
  396. harness.unmount();
  397. });
  398. it("tasks-index 有 25 行而 sessions-index 仅有 5 条摘要时,timeline 仍保留 25 行", async () => {
  399. const taskMetas = Array.from({ length: 25 }, (_, index) => {
  400. const taskId = `task-${String(index + 1).padStart(2, "0")}`;
  401. return createTaskMeta({ taskId, traceId: `trace-${taskId}`, updatedAt: index + 1 });
  402. });
  403. const harness = await renderHarness({
  404. kind: "timeline",
  405. expanded: true,
  406. sessions: taskMetas.slice(0, 5).map((task) =>
  407. createSession({
  408. sessionId: task.taskId,
  409. lastActivityAt: task.updatedAt + 100,
  410. title: `Live ${task.taskId}`,
  411. }),
  412. ),
  413. activeTaskMetas: taskMetas,
  414. });
  415. expect(harness.getItems()).toHaveLength(25);
  416. expect(harness.getItems().some((task) => task.taskId === "task-25")).toBe(true);
  417. harness.unmount();
  418. });
  419. it("搜索场景回落旧 listTaskList(全文检索/snippets 依赖 sqlite)", async () => {
  420. const harness = await renderHarness({
  421. kind: "active",
  422. searchQuery: "hello",
  423. sessions: [createSession({ sessionId: "s-1" })],
  424. });
  425. expect(harness.listTaskList).toHaveBeenCalled();
  426. harness.unmount();
  427. });
  428. });