useGlobalTaskListRemoteSessionsIndex.test.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. // remote shard(web/手机远控/SSH workspace)也以各 endpoint 的 tasks-index
  2. // 持久行为列表左表,sessions-index 帧只补 activity/detail;旧 listTaskList 零调用。
  3. import { act, createElement, type ReactNode } from "react";
  4. import { createRoot, type Root } from "react-dom/client";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { Emitter } from "@zcode/rpc";
  7. import type { IServiceAccessor } from "@zcode/services";
  8. import type { ZCodeTaskMeta } from "@zcode/shared";
  9. import type {
  10. SessionsIndexTopicFrame,
  11. SessionsIndexTopicWireFrame,
  12. SessionSummary,
  13. } from "@zcode/shared/zcode-protocol-v4";
  14. import { ServiceProvider } from "@/hooks/useServices.js";
  15. import { useGlobalTaskList } from "@/hooks/useGlobalTaskList.js";
  16. import { useSessionsMentionProvider } from "@/mentions/providers/sessionsMentionProvider.js";
  17. import { useRemoteWorkspaceSessionStore } from "@/store/remoteWorkspaceSessionStore.js";
  18. import { TabStoreProvider, useTabStoreApi } from "@/store/TabStoreProvider.js";
  19. import { useTaskQueryCacheStore } from "@/store/taskQueryCacheStore.js";
  20. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  21. import type { WorkspaceTabState } from "@/store/tabStore.js";
  22. import {
  23. buildWorkspaceSessionsIndexSourceKey,
  24. useWorkspaceSessionsIndexItems,
  25. type WorkspaceSessionsIndexScope,
  26. } from "@/v4/useWorkspaceSessionsIndexItems.js";
  27. const REMOTE_IDENTITY = "host-a:/remote-ws";
  28. const REMOTE_SESSION_ID = "remote-session-1";
  29. function createSession(
  30. overrides: Partial<SessionSummary> = {},
  31. ): SessionSummary {
  32. return {
  33. sessionId: "s-local-1",
  34. workspaceId: "ws-1",
  35. title: "Session",
  36. phase: "completedSuccess",
  37. sessionEnded: true,
  38. hasBackgroundWork: false,
  39. lastActivityAt: 2,
  40. createdAt: 1,
  41. ...overrides,
  42. };
  43. }
  44. function createTaskMeta(
  45. taskId: string,
  46. overrides: Partial<ZCodeTaskMeta> = {},
  47. ): ZCodeTaskMeta {
  48. return {
  49. taskId,
  50. traceId: `trace-${taskId}`,
  51. title: taskId,
  52. workspacePath: "/workspace",
  53. createdAt: 1,
  54. updatedAt: 2,
  55. mode: "default",
  56. ...overrides,
  57. } as ZCodeTaskMeta;
  58. }
  59. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  60. const element = {
  61. addEventListener: () => {},
  62. appendChild: (child: { parentNode?: unknown }) => {
  63. child.parentNode = element;
  64. return child;
  65. },
  66. childNodes: [] as unknown[],
  67. getAttribute: () => null,
  68. insertBefore: (child: { parentNode?: unknown }) => {
  69. child.parentNode = element;
  70. return child;
  71. },
  72. nodeName: tagName.toUpperCase(),
  73. nodeType: 1,
  74. ownerDocument,
  75. parentNode: null as unknown,
  76. removeAttribute: () => {},
  77. removeChild: (child: { parentNode?: unknown }) => {
  78. child.parentNode = null;
  79. return child;
  80. },
  81. removeEventListener: () => {},
  82. setAttribute: () => {},
  83. style: {},
  84. tagName: tagName.toUpperCase(),
  85. };
  86. return element as unknown as Element;
  87. }
  88. function installMinimalDom() {
  89. const documentMock = {
  90. addEventListener: () => {},
  91. createElement: (tagName: string) =>
  92. createMinimalElement(documentMock as unknown as Document, tagName),
  93. createElementNS: (_namespace: string, tagName: string) =>
  94. createMinimalElement(documentMock as unknown as Document, tagName),
  95. createTextNode: (nodeValue: string) => ({
  96. nodeType: 3,
  97. nodeValue,
  98. ownerDocument: documentMock,
  99. parentNode: null,
  100. }),
  101. nodeType: 9,
  102. removeEventListener: () => {},
  103. } as unknown as Document;
  104. const windowMock = {
  105. addEventListener: () => {},
  106. clearTimeout,
  107. document: documentMock,
  108. HTMLIFrameElement: function HTMLIFrameElement() {},
  109. HTMLElement: function HTMLElement() {},
  110. Node: function Node() {},
  111. removeEventListener: () => {},
  112. setTimeout,
  113. };
  114. Object.defineProperty(globalThis, "document", {
  115. configurable: true,
  116. value: documentMock,
  117. });
  118. Object.defineProperty(globalThis, "window", {
  119. configurable: true,
  120. value: windowMock,
  121. });
  122. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  123. configurable: true,
  124. value: true,
  125. });
  126. return createMinimalElement(documentMock);
  127. }
  128. async function flushMicrotasks() {
  129. await Promise.resolve();
  130. await Promise.resolve();
  131. await Promise.resolve();
  132. }
  133. function snapshotFrame(
  134. workspaceId: string,
  135. sessions: SessionSummary[],
  136. ): SessionsIndexTopicFrame {
  137. return {
  138. topic: `sessions-index/${workspaceId}`,
  139. subscriptionId: `sub-${workspaceId}`,
  140. fromSeq: 0,
  141. toSeq: 1,
  142. sentAt: 1,
  143. payload: {
  144. kind: "snapshot",
  145. snapshot: { protocolVersion: 1, workspaceId, logEpoch: "e1", sessions },
  146. },
  147. };
  148. }
  149. let logicalFrameSerial = 0;
  150. function physicalFrame(
  151. frame: SessionsIndexTopicFrame,
  152. deliveryKind: "initial" | "online" = "online",
  153. ): SessionsIndexTopicWireFrame {
  154. logicalFrameSerial += 1;
  155. return {
  156. wireVersion: 3,
  157. kind: "complete",
  158. deliveryKind,
  159. logicalFrameId: `logical-global-remote-${logicalFrameSerial}`,
  160. logicalFrameOrdinal: logicalFrameSerial,
  161. topic: frame.topic,
  162. subscriptionId: frame.subscriptionId,
  163. frame,
  164. };
  165. }
  166. interface EndpointMockOptions {
  167. workspaceId: string;
  168. sessions: SessionSummary[];
  169. sessionsByWorkspaceKey?: Record<string, SessionSummary[]>;
  170. pinnedTaskIds?: string[];
  171. /** listTasks 返回的 tasks-index 持久行。 */
  172. activeTaskMetas?: ZCodeTaskMeta[];
  173. pinnedTaskMetas?: ZCodeTaskMeta[];
  174. /** 用于覆盖 ACK 延迟期间 scope 集合变化的竞态。 */
  175. subscribeGate?: Promise<void>;
  176. subscribeGatesByWorkspaceKey?: Record<string, Promise<void>>;
  177. }
  178. function createDeferred(): { promise: Promise<void>; resolve: () => void } {
  179. let resolve!: () => void;
  180. const promise = new Promise<void>((currentResolve) => {
  181. resolve = currentResolve;
  182. });
  183. return { promise, resolve };
  184. }
  185. function v4Handshake(connectionId: string) {
  186. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  187. return {
  188. helloConversationV4: vi.fn(async () => ({
  189. kind: "hello" as const,
  190. protocolVersion: 3 as const,
  191. connectionId,
  192. clientMode: "desktop-continuous" as const,
  193. deliveryProfile: "continuous" as const,
  194. serverTime: 1,
  195. capabilities: {
  196. nativeDialogs: true,
  197. localTerminal: true,
  198. binaryFrames: false,
  199. compression: "none" as const,
  200. },
  201. auth: {},
  202. })),
  203. initializeConversationV4: vi.fn(async () => {}),
  204. resyncSessionsIndexV4: vi.fn(
  205. async (params: { subscriptionId: string }) => ({
  206. ack: {
  207. subscriptionId: params.subscriptionId,
  208. mode: "snapshot" as const,
  209. logEpoch: "e1",
  210. },
  211. }),
  212. ),
  213. onAgentRuntimeRestarted: runtimeRestarts.event,
  214. };
  215. }
  216. function createEndpointServices(options: EndpointMockOptions) {
  217. const frameListeners: Array<(frame: SessionsIndexTopicWireFrame) => void> =
  218. [];
  219. const listTaskList = vi.fn(async () => ({
  220. items: [],
  221. total: 0,
  222. hasMore: false,
  223. }));
  224. const subscribeSessionsIndexV4 = vi.fn(
  225. async (params: { workspacePath: string; workspaceIdentity?: string }) => {
  226. const workspaceKey =
  227. params.workspaceIdentity?.trim() || params.workspacePath;
  228. const subscriptionId = options.sessionsByWorkspaceKey
  229. ? `sub-${workspaceKey}`
  230. : `sub-${options.workspaceId}`;
  231. const ack = {
  232. subscriptionId,
  233. mode: "snapshot" as const,
  234. logEpoch: "e1",
  235. };
  236. await (options.subscribeGatesByWorkspaceKey?.[workspaceKey] ??
  237. options.subscribeGate);
  238. const initial = {
  239. ...snapshotFrame(
  240. workspaceKey,
  241. options.sessionsByWorkspaceKey?.[workspaceKey] ?? options.sessions,
  242. ),
  243. subscriptionId,
  244. topic: `sessions-index/${workspaceKey}`,
  245. };
  246. for (const listener of frameListeners)
  247. listener(physicalFrame(initial, "initial"));
  248. return { ack };
  249. },
  250. );
  251. const unsubscribeSessionsIndexV4 = vi.fn(async () => {});
  252. const defaultTaskMetasForScope = (params: {
  253. workspacePath: string;
  254. workspaceIdentity?: string;
  255. }): ZCodeTaskMeta[] => {
  256. const workspaceKey =
  257. params.workspaceIdentity?.trim() || params.workspacePath;
  258. const sessions =
  259. options.sessionsByWorkspaceKey?.[workspaceKey] ?? options.sessions;
  260. return sessions.map((session) =>
  261. createTaskMeta(session.sessionId, {
  262. createdAt: session.createdAt,
  263. title: session.title,
  264. updatedAt: session.lastActivityAt,
  265. workspacePath: params.workspacePath,
  266. ...(params.workspaceIdentity
  267. ? { workspaceIdentity: params.workspaceIdentity }
  268. : {}),
  269. }),
  270. );
  271. };
  272. const pinnedIds = new Set(options.pinnedTaskIds ?? []);
  273. const controllerFrames = new Emitter<never>();
  274. const controllerListTaskList = vi.fn(
  275. async (params: {
  276. kind: "pinned" | "archived" | "timeline" | "active";
  277. workspaceScopes: Array<{ workspacePath: string; workspaceIdentity?: string }>;
  278. limit?: number;
  279. }) => {
  280. const rows = params.workspaceScopes.flatMap((scope) => {
  281. const sourceRows =
  282. options.activeTaskMetas ?? defaultTaskMetasForScope(scope);
  283. const filtered = sourceRows.filter((task) => {
  284. const pinned = pinnedIds.has(task.taskId);
  285. if (params.kind === "pinned") return pinned;
  286. if (params.kind === "archived") return false;
  287. if (params.kind === "timeline") return !pinned;
  288. return true;
  289. });
  290. return filtered.map((task) => ({
  291. ...task,
  292. workspacePath: scope.workspacePath,
  293. ...(scope.workspaceIdentity
  294. ? { workspaceIdentity: scope.workspaceIdentity, remoteSessionId: REMOTE_SESSION_ID }
  295. : {}),
  296. sourceAvailability: "online" as const,
  297. }));
  298. });
  299. rows.sort((left, right) => right.updatedAt - left.updatedAt);
  300. const items = params.limit == null ? rows : rows.slice(0, params.limit);
  301. return { items, total: rows.length, hasMore: rows.length > items.length };
  302. },
  303. );
  304. const services = {
  305. windowControllerService: {
  306. listTaskList: controllerListTaskList,
  307. mutateTask: vi.fn(async () => null),
  308. subscribeControllerV4: vi.fn(async ({ topic }: { topic: string }) => ({
  309. ack: { subscriptionId: `sub-${topic}`, mode: "snapshot" as const, logEpoch: "e1" },
  310. })),
  311. resyncControllerV4: vi.fn(async ({ subscriptionId }: { subscriptionId: string }) => ({
  312. ack: { subscriptionId, mode: "snapshot" as const, logEpoch: "e1" },
  313. })),
  314. unsubscribeControllerV4: vi.fn(async () => {}),
  315. onDynamicControllerFrame: () => controllerFrames.event,
  316. },
  317. zcodeTaskService: {
  318. listTaskList,
  319. listPinnedTaskIds: vi.fn(
  320. async (): Promise<string[]> => options.pinnedTaskIds ?? [],
  321. ),
  322. listArchivedTasks: vi.fn(async (): Promise<ZCodeTaskMeta[]> => []),
  323. listTasks: vi.fn(
  324. async (params: { workspacePath: string; workspaceIdentity?: string }) =>
  325. options.activeTaskMetas ??
  326. defaultTaskMetasForScope(params).filter(
  327. (task) => !pinnedIds.has(task.taskId),
  328. ),
  329. ),
  330. listPinnedTasks: vi.fn(
  331. async (params: { workspacePath: string; workspaceIdentity?: string }) =>
  332. options.pinnedTaskMetas ??
  333. defaultTaskMetasForScope(params).filter((task) =>
  334. pinnedIds.has(task.taskId),
  335. ),
  336. ),
  337. onDynamicWorkspaceEvent: () => () => ({ dispose() {} }),
  338. },
  339. zcodeAgentService: {
  340. ...v4Handshake(`connection-${options.workspaceId}`),
  341. subscribeSessionsIndexV4,
  342. unsubscribeSessionsIndexV4,
  343. onDynamicSessionsIndexFrame:
  344. () => (listener: (frame: SessionsIndexTopicWireFrame) => void) => {
  345. frameListeners.push(listener);
  346. return { dispose: () => {} };
  347. },
  348. },
  349. } as unknown as IServiceAccessor;
  350. return {
  351. services,
  352. frameListeners,
  353. listTaskList,
  354. subscribeSessionsIndexV4,
  355. unsubscribeSessionsIndexV4,
  356. controllerListTaskList,
  357. };
  358. }
  359. function createWorkspaceTabs(): WorkspaceTabState[] {
  360. return [
  361. {
  362. id: "workspace-local",
  363. kind: "workspace",
  364. label: "local",
  365. workspacePath: "/workspace",
  366. },
  367. {
  368. id: "workspace-remote",
  369. kind: "workspace",
  370. label: "remote",
  371. workspacePath: "/remote-ws",
  372. workspaceIdentity: REMOTE_IDENTITY,
  373. remoteSessionId: REMOTE_SESSION_ID,
  374. } as WorkspaceTabState,
  375. ];
  376. }
  377. function WorkspaceTabsSeed({
  378. activeWorkspaceIdentity,
  379. activeWorkspacePath,
  380. children,
  381. tabs,
  382. }: {
  383. activeWorkspaceIdentity?: string;
  384. activeWorkspacePath: string;
  385. children: ReactNode;
  386. tabs: WorkspaceTabState[];
  387. }) {
  388. const store = useTabStoreApi();
  389. if (store.getState().tabs.length === 0) {
  390. const activeTab = tabs.find(
  391. (tab) =>
  392. (tab.workspaceIdentity?.trim() || tab.workspacePath) ===
  393. (activeWorkspaceIdentity?.trim() || activeWorkspacePath),
  394. );
  395. store.setState({
  396. tabs,
  397. activeTabId: activeTab?.id ?? null,
  398. activeWorkspacePath,
  399. activeWorkspaceIdentity: activeWorkspaceIdentity ?? null,
  400. });
  401. }
  402. return children;
  403. }
  404. describe("useGlobalTaskList remote shard tasks-index 行 + sessions-index detail", () => {
  405. afterEach(() => {
  406. useTaskQueryCacheStore.getState().clearAll();
  407. useRemoteWorkspaceSessionStore.setState({
  408. baseServices: null,
  409. sessionsById: {},
  410. sessionIdByWorkspaceIdentity: {},
  411. sessionIdByWorkspacePath: {},
  412. });
  413. useZCodeSessionStore.setState({ workspaces: {} });
  414. delete (globalThis as { document?: unknown }).document;
  415. delete (globalThis as { window?: unknown }).window;
  416. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown })
  417. .IS_REACT_ACT_ENVIRONMENT;
  418. });
  419. it("remote A 已就绪后分步追加并移除 ACK 延迟的 remote B,不重启 A", async () => {
  420. const zcodeAck = createDeferred();
  421. const base = createEndpointServices({
  422. workspaceId: "ws-base",
  423. sessions: [],
  424. });
  425. const macIdentity = "remote:ssh:mac:/Users/dev";
  426. const macProjectIdentity = "remote:ssh:mac:/Users/dev/ZCodeProject";
  427. const mac = createEndpointServices({
  428. workspaceId: "ws-mac",
  429. sessions: [],
  430. sessionsByWorkspaceKey: {
  431. [macIdentity]: [
  432. createSession({
  433. sessionId: "s-mac",
  434. workspaceId: macIdentity,
  435. lastActivityAt: 10,
  436. }),
  437. ],
  438. [macProjectIdentity]: [
  439. createSession({
  440. sessionId: "s-mac-project",
  441. workspaceId: macProjectIdentity,
  442. lastActivityAt: 20,
  443. }),
  444. ],
  445. },
  446. });
  447. const zcodeIdentity = "remote:ssh:zcode:/root";
  448. const zcodeProjectIdentity = "remote:ssh:zcode:/root/demo-project";
  449. const zcode = createEndpointServices({
  450. workspaceId: "ws-zcode",
  451. sessions: [],
  452. sessionsByWorkspaceKey: {
  453. [zcodeIdentity]: [
  454. createSession({
  455. sessionId: "s-zcode",
  456. workspaceId: zcodeIdentity,
  457. lastActivityAt: 30,
  458. }),
  459. ],
  460. [zcodeProjectIdentity]: [
  461. createSession({
  462. sessionId: "s-zcode-project",
  463. workspaceId: zcodeProjectIdentity,
  464. lastActivityAt: 40,
  465. }),
  466. ],
  467. },
  468. subscribeGate: zcodeAck.promise,
  469. });
  470. const macScope: WorkspaceSessionsIndexScope = {
  471. endpointKey: "remote-mac",
  472. workspacePath: "/Users/dev",
  473. workspaceIdentity: macIdentity,
  474. agentService: mac.services.zcodeAgentService,
  475. };
  476. const macProjectScope: WorkspaceSessionsIndexScope = {
  477. endpointKey: "remote-mac",
  478. workspacePath: "/Users/dev/ZCodeProject",
  479. workspaceIdentity: macProjectIdentity,
  480. agentService: mac.services.zcodeAgentService,
  481. };
  482. const zcodeScope: WorkspaceSessionsIndexScope = {
  483. endpointKey: "remote-zcode",
  484. workspacePath: "/root",
  485. workspaceIdentity: zcodeIdentity,
  486. agentService: zcode.services.zcodeAgentService,
  487. };
  488. const zcodeProjectScope: WorkspaceSessionsIndexScope = {
  489. endpointKey: "remote-zcode",
  490. workspacePath: "/root/demo-project",
  491. workspaceIdentity: zcodeProjectIdentity,
  492. agentService: zcode.services.zcodeAgentService,
  493. };
  494. let scopes: WorkspaceSessionsIndexScope[] = [macScope, macProjectScope];
  495. let latest: ReturnType<typeof useWorkspaceSessionsIndexItems> | null = null;
  496. function Probe() {
  497. latest = useWorkspaceSessionsIndexItems(scopes);
  498. return null;
  499. }
  500. const root: Root = createRoot(installMinimalDom());
  501. await act(async () => {
  502. root.render(
  503. createElement(
  504. ServiceProvider,
  505. { services: base.services },
  506. createElement(Probe),
  507. ),
  508. );
  509. await flushMicrotasks();
  510. });
  511. expect(mac.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  512. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  513. "s-mac-project",
  514. "s-mac",
  515. ]);
  516. const macSourceKey = buildWorkspaceSessionsIndexSourceKey(macScope);
  517. const macProjectSourceKey =
  518. buildWorkspaceSessionsIndexSourceKey(macProjectScope);
  519. const macRevisionBefore = latest?.sourceRevisionByScopeKey[macSourceKey];
  520. const macProjectRevisionBefore =
  521. latest?.sourceRevisionByScopeKey[macProjectSourceKey];
  522. await act(async () => {
  523. const macDelta: SessionsIndexTopicFrame = {
  524. topic: `sessions-index/${macIdentity}`,
  525. subscriptionId: `sub-${macIdentity}`,
  526. fromSeq: 1,
  527. toSeq: 2,
  528. sentAt: 2,
  529. payload: {
  530. kind: "deltas",
  531. deltas: [
  532. {
  533. op: "session.upserted",
  534. session: createSession({
  535. sessionId: "s-mac",
  536. workspaceId: macIdentity,
  537. lastActivityAt: 15,
  538. }),
  539. },
  540. ],
  541. },
  542. };
  543. for (const listener of mac.frameListeners)
  544. listener(physicalFrame(macDelta));
  545. await flushMicrotasks();
  546. });
  547. expect(latest?.sourceRevisionByScopeKey[macSourceKey]).not.toBe(
  548. macRevisionBefore,
  549. );
  550. expect(latest?.sourceRevisionByScopeKey[macProjectSourceKey]).toBe(
  551. macProjectRevisionBefore,
  552. );
  553. scopes = [macScope, macProjectScope, zcodeScope];
  554. await act(async () => {
  555. root.render(
  556. createElement(
  557. ServiceProvider,
  558. { services: base.services },
  559. createElement(Probe),
  560. ),
  561. );
  562. await flushMicrotasks();
  563. });
  564. expect(mac.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  565. expect(mac.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  566. expect(zcode.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  567. expect(latest?.hydratingEndpointKeys).toEqual(["remote-zcode"]);
  568. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  569. "s-mac-project",
  570. "s-mac",
  571. ]);
  572. scopes = [macScope, macProjectScope, zcodeScope, zcodeProjectScope];
  573. await act(async () => {
  574. root.render(
  575. createElement(
  576. ServiceProvider,
  577. { services: base.services },
  578. createElement(Probe),
  579. ),
  580. );
  581. await flushMicrotasks();
  582. });
  583. expect(mac.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  584. expect(mac.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  585. expect(zcode.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  586. await act(async () => {
  587. zcodeAck.resolve();
  588. await flushMicrotasks();
  589. });
  590. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  591. "s-zcode-project",
  592. "s-zcode",
  593. "s-mac-project",
  594. "s-mac",
  595. ]);
  596. scopes = [macScope, macProjectScope];
  597. await act(async () => {
  598. root.render(
  599. createElement(
  600. ServiceProvider,
  601. { services: base.services },
  602. createElement(Probe),
  603. ),
  604. );
  605. await flushMicrotasks();
  606. });
  607. expect(zcode.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  608. expect(mac.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  609. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  610. "s-mac-project",
  611. "s-mac",
  612. ]);
  613. await act(async () => {
  614. root.unmount();
  615. await flushMicrotasks();
  616. });
  617. expect(mac.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  618. });
  619. it("local __base__ 与 remote 集合增删时只 acquire/release 变化的 remote scope", async () => {
  620. const local = createEndpointServices({
  621. workspaceId: "ws-local-stable",
  622. sessions: [
  623. createSession({
  624. sessionId: "s-local-stable",
  625. workspaceId: "ws-local-stable",
  626. lastActivityAt: 10,
  627. }),
  628. ],
  629. });
  630. const remote = createEndpointServices({
  631. workspaceId: "ws-remote-added",
  632. sessions: [
  633. createSession({
  634. sessionId: "s-remote-added",
  635. workspaceId: "ws-remote-added",
  636. lastActivityAt: 20,
  637. }),
  638. ],
  639. });
  640. const localScope: WorkspaceSessionsIndexScope = {
  641. workspacePath: "/workspace",
  642. agentService: local.services.zcodeAgentService,
  643. };
  644. const remoteScope: WorkspaceSessionsIndexScope = {
  645. endpointKey: "remote-added",
  646. workspacePath: "/remote-added",
  647. workspaceIdentity: "remote:ssh:added:/remote-added",
  648. agentService: remote.services.zcodeAgentService,
  649. };
  650. let scopes: WorkspaceSessionsIndexScope[] = [localScope];
  651. let latest: ReturnType<typeof useWorkspaceSessionsIndexItems> | null = null;
  652. function Probe() {
  653. latest = useWorkspaceSessionsIndexItems(scopes);
  654. return null;
  655. }
  656. const root: Root = createRoot(installMinimalDom());
  657. await act(async () => {
  658. root.render(
  659. createElement(
  660. ServiceProvider,
  661. { services: local.services },
  662. createElement(Probe),
  663. ),
  664. );
  665. await flushMicrotasks();
  666. });
  667. scopes = [localScope, remoteScope];
  668. await act(async () => {
  669. root.render(
  670. createElement(
  671. ServiceProvider,
  672. { services: local.services },
  673. createElement(Probe),
  674. ),
  675. );
  676. await flushMicrotasks();
  677. });
  678. expect(local.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  679. expect(local.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  680. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  681. "s-remote-added",
  682. "s-local-stable",
  683. ]);
  684. scopes = [localScope];
  685. await act(async () => {
  686. root.render(
  687. createElement(
  688. ServiceProvider,
  689. { services: local.services },
  690. createElement(Probe),
  691. ),
  692. );
  693. await flushMicrotasks();
  694. });
  695. expect(remote.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  696. expect(local.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  697. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  698. "s-local-stable",
  699. ]);
  700. await act(async () => {
  701. root.unmount();
  702. await flushMicrotasks();
  703. });
  704. expect(local.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  705. });
  706. it("local pinned 新增 workspace scope 时保留已有任务,不发布空中间帧", async () => {
  707. const addedWorkspaceAck = createDeferred();
  708. const local = createEndpointServices({
  709. workspaceId: "ws-local-pinned-scope",
  710. sessions: [],
  711. sessionsByWorkspaceKey: {
  712. "/workspace-a": [
  713. createSession({
  714. sessionId: "s-pinned-a",
  715. workspaceId: "/workspace-a",
  716. lastActivityAt: 10,
  717. }),
  718. ],
  719. "/workspace-b": [
  720. createSession({
  721. sessionId: "s-pinned-b",
  722. workspaceId: "/workspace-b",
  723. lastActivityAt: 20,
  724. }),
  725. ],
  726. },
  727. pinnedTaskIds: ["s-pinned-a", "s-pinned-b"],
  728. subscribeGatesByWorkspaceKey: {
  729. "/workspace-b": addedWorkspaceAck.promise,
  730. },
  731. });
  732. const workspaceA: WorkspaceTabState = {
  733. id: "workspace-a",
  734. kind: "workspace",
  735. label: "workspace-a",
  736. workspacePath: "/workspace-a",
  737. };
  738. const workspaceB: WorkspaceTabState = {
  739. id: "workspace-b",
  740. kind: "workspace",
  741. label: "workspace-b",
  742. workspacePath: "/workspace-b",
  743. };
  744. let workspaceTabs = [workspaceA];
  745. let latest: ReturnType<typeof useGlobalTaskList> | null = null;
  746. const renderStates: string[][] = [];
  747. function Probe() {
  748. latest = useGlobalTaskList({
  749. collapsedLimit: 20,
  750. expanded: true,
  751. kind: "pinned",
  752. searchQuery: "",
  753. sortBy: "updated",
  754. workspaceTabs,
  755. });
  756. renderStates.push((latest?.items ?? []).map((item) => item.taskId));
  757. return null;
  758. }
  759. const root: Root = createRoot(installMinimalDom());
  760. await act(async () => {
  761. root.render(
  762. createElement(
  763. ServiceProvider,
  764. { services: local.services },
  765. createElement(Probe),
  766. ),
  767. );
  768. await flushMicrotasks();
  769. });
  770. await act(async () => {
  771. await flushMicrotasks();
  772. });
  773. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  774. "s-pinned-a",
  775. ]);
  776. const renderCountBeforeScopeAdd = renderStates.length;
  777. workspaceTabs = [workspaceA, workspaceB];
  778. await act(async () => {
  779. root.render(
  780. createElement(
  781. ServiceProvider,
  782. { services: local.services },
  783. createElement(Probe),
  784. ),
  785. );
  786. await flushMicrotasks();
  787. });
  788. const scopeAddStates = renderStates.slice(renderCountBeforeScopeAdd);
  789. expect(scopeAddStates.length).toBeGreaterThan(0);
  790. expect(
  791. scopeAddStates.every((taskIds) => taskIds.includes("s-pinned-a")),
  792. ).toBe(true);
  793. await act(async () => {
  794. addedWorkspaceAck.resolve();
  795. await flushMicrotasks();
  796. });
  797. await act(async () => {
  798. await flushMicrotasks();
  799. });
  800. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  801. "s-pinned-b",
  802. "s-pinned-a",
  803. ]);
  804. await act(async () => {
  805. root.unmount();
  806. await flushMicrotasks();
  807. });
  808. });
  809. it("remote service generation 换代只替换目标 scope,local __base__ 保持订阅", async () => {
  810. const local = createEndpointServices({
  811. workspaceId: "ws-local-generation",
  812. sessions: [
  813. createSession({
  814. sessionId: "s-local-generation",
  815. workspaceId: "ws-local-generation",
  816. lastActivityAt: 10,
  817. }),
  818. ],
  819. });
  820. const remoteOld = createEndpointServices({
  821. workspaceId: "ws-remote-old",
  822. sessions: [
  823. createSession({
  824. sessionId: "s-remote-old",
  825. workspaceId: "ws-remote-old",
  826. lastActivityAt: 20,
  827. }),
  828. ],
  829. });
  830. const remoteNew = createEndpointServices({
  831. workspaceId: "ws-remote-new",
  832. sessions: [
  833. createSession({
  834. sessionId: "s-remote-new",
  835. workspaceId: "ws-remote-new",
  836. lastActivityAt: 30,
  837. }),
  838. ],
  839. });
  840. const localScope: WorkspaceSessionsIndexScope = {
  841. workspacePath: "/workspace-generation",
  842. agentService: local.services.zcodeAgentService,
  843. };
  844. const remoteScopeBase = {
  845. endpointKey: "remote-generation",
  846. workspacePath: "/remote-generation",
  847. workspaceIdentity: "remote:ssh:generation:/remote-generation",
  848. };
  849. let scopes: WorkspaceSessionsIndexScope[] = [
  850. localScope,
  851. {
  852. ...remoteScopeBase,
  853. agentService: remoteOld.services.zcodeAgentService,
  854. },
  855. ];
  856. let latest: ReturnType<typeof useWorkspaceSessionsIndexItems> | null = null;
  857. function Probe() {
  858. latest = useWorkspaceSessionsIndexItems(scopes);
  859. return null;
  860. }
  861. const root: Root = createRoot(installMinimalDom());
  862. await act(async () => {
  863. root.render(
  864. createElement(
  865. ServiceProvider,
  866. { services: local.services },
  867. createElement(Probe),
  868. ),
  869. );
  870. await flushMicrotasks();
  871. });
  872. scopes = [
  873. localScope,
  874. {
  875. ...remoteScopeBase,
  876. agentService: remoteNew.services.zcodeAgentService,
  877. },
  878. ];
  879. await act(async () => {
  880. root.render(
  881. createElement(
  882. ServiceProvider,
  883. { services: local.services },
  884. createElement(Probe),
  885. ),
  886. );
  887. await flushMicrotasks();
  888. });
  889. expect(remoteOld.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  890. expect(remoteNew.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  891. expect(local.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  892. expect(local.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  893. expect((latest?.items ?? []).map((item) => item.taskId)).toEqual([
  894. "s-remote-new",
  895. "s-local-generation",
  896. ]);
  897. await act(async () => {
  898. root.unmount();
  899. await flushMicrotasks();
  900. });
  901. expect(remoteNew.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  902. expect(local.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  903. });
  904. it("窗口 Controller 一次聚合 local/remote scope,不再由 Renderer 订阅 endpoint shard", async () => {
  905. const local = createEndpointServices({
  906. workspaceId: "ws-local",
  907. sessions: [createSession({ sessionId: "s-local-1", lastActivityAt: 10 })],
  908. activeTaskMetas: [createTaskMeta("s-local-1", { unreadAt: 111 })],
  909. });
  910. const remote = createEndpointServices({
  911. workspaceId: "ws-remote",
  912. sessions: [
  913. createSession({
  914. sessionId: "s-remote-1",
  915. workspaceId: "ws-remote",
  916. lastActivityAt: 20,
  917. }),
  918. ],
  919. activeTaskMetas: [
  920. createTaskMeta("s-remote-1", {
  921. workspacePath: "/remote-ws",
  922. workspaceIdentity: REMOTE_IDENTITY,
  923. unreadAt: 222,
  924. }),
  925. ],
  926. });
  927. let remoteTitle = "s-remote-1";
  928. local.controllerListTaskList.mockImplementation(async () => ({
  929. items: [
  930. {
  931. ...createTaskMeta("s-remote-1", {
  932. title: remoteTitle,
  933. workspacePath: "/remote-ws",
  934. workspaceIdentity: REMOTE_IDENTITY,
  935. unreadAt: 222,
  936. updatedAt: 20,
  937. }),
  938. remoteSessionId: REMOTE_SESSION_ID,
  939. sourceAvailability: "online" as const,
  940. },
  941. {
  942. ...createTaskMeta("s-local-1", { unreadAt: 111, updatedAt: 10 }),
  943. sourceAvailability: "online" as const,
  944. },
  945. ],
  946. total: 2,
  947. hasMore: false,
  948. }));
  949. useRemoteWorkspaceSessionStore.setState({
  950. sessionsById: {
  951. [REMOTE_SESSION_ID]: {
  952. sessionId: REMOTE_SESSION_ID,
  953. services: remote.services,
  954. },
  955. },
  956. sessionIdByWorkspaceIdentity: { [REMOTE_IDENTITY]: REMOTE_SESSION_ID },
  957. sessionIdByWorkspacePath: { "/remote-ws": REMOTE_SESSION_ID },
  958. });
  959. const workspaceTabs = createWorkspaceTabs();
  960. let latest: ReturnType<typeof useGlobalTaskList> | null = null;
  961. function Probe() {
  962. latest = useGlobalTaskList({
  963. collapsedLimit: 10,
  964. expanded: false,
  965. kind: "timeline",
  966. searchQuery: "",
  967. sortBy: "updated",
  968. workspaceTabs,
  969. });
  970. return null;
  971. }
  972. const root: Root = createRoot(installMinimalDom());
  973. await act(async () => {
  974. root.render(
  975. createElement(
  976. ServiceProvider,
  977. { services: local.services },
  978. createElement(Probe),
  979. ),
  980. );
  981. await flushMicrotasks();
  982. });
  983. await act(async () => {
  984. await flushMicrotasks();
  985. });
  986. await act(async () => {
  987. await flushMicrotasks();
  988. });
  989. expect(local.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  990. expect(remote.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  991. expect(local.controllerListTaskList).toHaveBeenCalledWith(
  992. expect.objectContaining({
  993. workspaceScopes: expect.arrayContaining([
  994. expect.objectContaining({ workspacePath: "/workspace" }),
  995. expect.objectContaining({
  996. workspacePath: "/remote-ws",
  997. workspaceIdentity: REMOTE_IDENTITY,
  998. }),
  999. ]),
  1000. }),
  1001. );
  1002. // 聚合列表:remote(20) 在 local(10) 之前;Renderer 不再调用 endpoint task service。
  1003. const items = latest?.items ?? [];
  1004. expect(items.map((task) => task.taskId)).toEqual([
  1005. "s-remote-1",
  1006. "s-local-1",
  1007. ]);
  1008. expect(local.listTaskList).not.toHaveBeenCalled();
  1009. expect(remote.listTaskList).not.toHaveBeenCalled();
  1010. // remote meta 归属正确(workspaceIdentity 维度)+ unread 双端 join。
  1011. const remoteItem = items.find((task) => task.taskId === "s-remote-1");
  1012. expect(remoteItem?.workspaceIdentity).toBe(REMOTE_IDENTITY);
  1013. expect(remoteItem?.unreadAt).toBe(222);
  1014. const localItem = items.find((task) => task.taskId === "s-local-1");
  1015. expect(localItem?.unreadAt).toBe(111);
  1016. // Controller 刷新后收敛远端 rename。
  1017. await act(async () => {
  1018. remoteTitle = "Renamed remote";
  1019. await latest?.refresh();
  1020. await flushMicrotasks();
  1021. });
  1022. await act(async () => {
  1023. await flushMicrotasks();
  1024. });
  1025. expect(
  1026. (latest?.items ?? []).find((task) => task.taskId === "s-remote-1")?.title,
  1027. ).toBe("Renamed remote");
  1028. act(() => {
  1029. root.unmount();
  1030. });
  1031. });
  1032. it("远端 workspace 的 # 会话候选只订阅对应 remote endpoint", async () => {
  1033. const local = createEndpointServices({
  1034. workspaceId: "ws-local",
  1035. sessions: [],
  1036. });
  1037. const remote = createEndpointServices({
  1038. workspaceId: "ws-remote",
  1039. sessions: [],
  1040. });
  1041. useRemoteWorkspaceSessionStore.setState({
  1042. baseServices: local.services,
  1043. sessionsById: {
  1044. [REMOTE_SESSION_ID]: {
  1045. sessionId: REMOTE_SESSION_ID,
  1046. services: remote.services,
  1047. },
  1048. },
  1049. sessionIdByWorkspaceIdentity: { [REMOTE_IDENTITY]: REMOTE_SESSION_ID },
  1050. sessionIdByWorkspacePath: { "/remote-ws": REMOTE_SESSION_ID },
  1051. });
  1052. function Probe() {
  1053. useSessionsMentionProvider(
  1054. "glm",
  1055. "/remote-ws",
  1056. REMOTE_IDENTITY,
  1057. "",
  1058. true,
  1059. "current-workspace",
  1060. "empty",
  1061. "sessions",
  1062. );
  1063. return null;
  1064. }
  1065. const root: Root = createRoot(installMinimalDom());
  1066. await act(async () => {
  1067. root.render(
  1068. createElement(
  1069. ServiceProvider,
  1070. { services: local.services },
  1071. createElement(TabStoreProvider, null, createElement(Probe)),
  1072. ),
  1073. );
  1074. await flushMicrotasks();
  1075. });
  1076. await act(async () => {
  1077. await flushMicrotasks();
  1078. });
  1079. expect(local.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  1080. expect(remote.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  1081. expect(remote.subscribeSessionsIndexV4).toHaveBeenCalledWith({
  1082. runtimePolicy: "existing-only",
  1083. workspacePath: "/remote-ws",
  1084. workspaceIdentity: REMOTE_IDENTITY,
  1085. });
  1086. act(() => {
  1087. root.unmount();
  1088. });
  1089. });
  1090. it("@ 保持当前 workspace,# 聚合同一 Host 并按 workspace 各限制 20 条", async () => {
  1091. const buildWorkspaceSessions = (workspaceId: string, prefix: string) => [
  1092. ...Array.from({ length: 20 }, (_, index) =>
  1093. createSession({
  1094. sessionId: `${prefix}-recent-${index}`,
  1095. workspaceId,
  1096. title: `${prefix} recent ${index}`,
  1097. lastActivityAt: 100 - index,
  1098. createdAt: 100 - index,
  1099. }),
  1100. ),
  1101. createSession({
  1102. sessionId: `${prefix}-old-target`,
  1103. workspaceId,
  1104. title: `${prefix} archived target`,
  1105. lastActivityAt: 1,
  1106. createdAt: 1,
  1107. }),
  1108. ];
  1109. const local = createEndpointServices({
  1110. workspaceId: "ws-local",
  1111. sessions: [],
  1112. sessionsByWorkspaceKey: {
  1113. "/workspace-a": buildWorkspaceSessions("/workspace-a", "alpha"),
  1114. "/workspace-b": buildWorkspaceSessions("/workspace-b", "beta"),
  1115. },
  1116. });
  1117. useRemoteWorkspaceSessionStore.setState({ baseServices: local.services });
  1118. const workspaceTabs: WorkspaceTabState[] = [
  1119. {
  1120. id: "workspace-a",
  1121. kind: "workspace",
  1122. label: "workspace-a",
  1123. workspacePath: "/workspace-a",
  1124. },
  1125. {
  1126. id: "workspace-b",
  1127. kind: "workspace",
  1128. label: "workspace-b",
  1129. workspacePath: "/workspace-b",
  1130. },
  1131. ];
  1132. let latest: ReturnType<typeof useSessionsMentionProvider> | null = null;
  1133. function Probe({
  1134. query = "",
  1135. workspaceScope,
  1136. }: {
  1137. query?: string;
  1138. workspaceScope: "current-workspace" | "same-authority-workspaces";
  1139. }) {
  1140. latest = useSessionsMentionProvider(
  1141. "glm",
  1142. "/workspace-a",
  1143. undefined,
  1144. query,
  1145. true,
  1146. workspaceScope,
  1147. "empty",
  1148. "sessions",
  1149. );
  1150. return null;
  1151. }
  1152. const root: Root = createRoot(installMinimalDom());
  1153. const renderProbe = (
  1154. workspaceScope: "current-workspace" | "same-authority-workspaces",
  1155. query = "",
  1156. ) =>
  1157. root.render(
  1158. createElement(
  1159. ServiceProvider,
  1160. { services: local.services },
  1161. createElement(
  1162. TabStoreProvider,
  1163. null,
  1164. createElement(
  1165. WorkspaceTabsSeed,
  1166. { activeWorkspacePath: "/workspace-a", tabs: workspaceTabs },
  1167. createElement(Probe, { query, workspaceScope }),
  1168. ),
  1169. ),
  1170. ),
  1171. );
  1172. await act(async () => {
  1173. renderProbe("current-workspace");
  1174. await flushMicrotasks();
  1175. });
  1176. await act(async () => {
  1177. await flushMicrotasks();
  1178. });
  1179. expect(local.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  1180. expect(local.subscribeSessionsIndexV4).toHaveBeenCalledWith(
  1181. expect.objectContaining({ workspacePath: "/workspace-a" }),
  1182. );
  1183. expect(latest?.items).toHaveLength(21);
  1184. expect((latest?.items ?? []).map((item) => item.value)).toContain(
  1185. "alpha-old-target",
  1186. );
  1187. await act(async () => {
  1188. renderProbe("same-authority-workspaces");
  1189. await flushMicrotasks();
  1190. });
  1191. await act(async () => {
  1192. await flushMicrotasks();
  1193. });
  1194. expect(local.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  1195. expect(local.subscribeSessionsIndexV4).toHaveBeenCalledWith(
  1196. expect.objectContaining({ workspacePath: "/workspace-b" }),
  1197. );
  1198. expect(latest?.items).toHaveLength(40);
  1199. expect(
  1200. (latest?.items ?? []).filter((item) => item.description === "workspace-a"),
  1201. ).toHaveLength(20);
  1202. expect(
  1203. (latest?.items ?? []).filter((item) => item.description === "workspace-b"),
  1204. ).toHaveLength(20);
  1205. expect((latest?.items ?? []).map((item) => item.value)).not.toContain(
  1206. "beta-old-target",
  1207. );
  1208. await act(async () => {
  1209. renderProbe("same-authority-workspaces", "beta archived target");
  1210. await flushMicrotasks();
  1211. });
  1212. expect((latest?.items ?? []).map((item) => item.value)).toEqual([
  1213. "beta-old-target",
  1214. ]);
  1215. act(() => {
  1216. root.unmount();
  1217. });
  1218. });
  1219. it("远端 # 会话候选只聚合同一 remote authority 的 workspace", async () => {
  1220. const local = createEndpointServices({
  1221. workspaceId: "ws-local",
  1222. sessions: [],
  1223. });
  1224. const remoteAId = "remote-session-a";
  1225. const remoteBId = "remote-session-b";
  1226. const remoteAIdentity = "remote:ssh:a:/repo-a";
  1227. const remoteAProjectIdentity = "remote:ssh:a:/repo-b";
  1228. const remoteBIdentity = "remote:ssh:b:/repo-a";
  1229. const remoteA = createEndpointServices({
  1230. workspaceId: "ws-remote-a",
  1231. sessions: [],
  1232. sessionsByWorkspaceKey: {
  1233. [remoteAIdentity]: [
  1234. createSession({
  1235. sessionId: "s-remote-a-current",
  1236. workspaceId: remoteAIdentity,
  1237. title: "Remote A current",
  1238. lastActivityAt: 10,
  1239. }),
  1240. ],
  1241. [remoteAProjectIdentity]: [
  1242. createSession({
  1243. sessionId: "s-remote-a-project",
  1244. workspaceId: remoteAProjectIdentity,
  1245. title: "Remote A project",
  1246. lastActivityAt: 20,
  1247. }),
  1248. ],
  1249. },
  1250. });
  1251. const remoteB = createEndpointServices({
  1252. workspaceId: "ws-remote-b",
  1253. sessions: [
  1254. createSession({
  1255. sessionId: "s-remote-b",
  1256. workspaceId: remoteBIdentity,
  1257. title: "Foreign remote",
  1258. lastActivityAt: 30,
  1259. }),
  1260. ],
  1261. });
  1262. useRemoteWorkspaceSessionStore.setState({
  1263. baseServices: local.services,
  1264. sessionsById: {
  1265. [remoteAId]: { sessionId: remoteAId, services: remoteA.services },
  1266. [remoteBId]: { sessionId: remoteBId, services: remoteB.services },
  1267. },
  1268. sessionIdByWorkspaceIdentity: {
  1269. [remoteAIdentity]: remoteAId,
  1270. [remoteAProjectIdentity]: remoteAId,
  1271. [remoteBIdentity]: remoteBId,
  1272. },
  1273. sessionIdByWorkspacePath: {},
  1274. });
  1275. const workspaceTabs: WorkspaceTabState[] = [
  1276. {
  1277. id: "remote-a-root",
  1278. kind: "workspace",
  1279. label: "repo-a",
  1280. workspacePath: "/repo-a",
  1281. workspaceIdentity: remoteAIdentity,
  1282. remoteSessionId: remoteAId,
  1283. },
  1284. {
  1285. id: "remote-a-project",
  1286. kind: "workspace",
  1287. label: "repo-b",
  1288. workspacePath: "/repo-b",
  1289. workspaceIdentity: remoteAProjectIdentity,
  1290. remoteSessionId: remoteAId,
  1291. },
  1292. {
  1293. id: "remote-b-root",
  1294. kind: "workspace",
  1295. label: "repo-a",
  1296. workspacePath: "/repo-a",
  1297. workspaceIdentity: remoteBIdentity,
  1298. remoteSessionId: remoteBId,
  1299. },
  1300. {
  1301. id: "local-root",
  1302. kind: "workspace",
  1303. label: "local",
  1304. workspacePath: "/local",
  1305. },
  1306. ];
  1307. let latest: ReturnType<typeof useSessionsMentionProvider> | null = null;
  1308. function Probe() {
  1309. latest = useSessionsMentionProvider(
  1310. "glm",
  1311. "/repo-a",
  1312. remoteAIdentity,
  1313. "",
  1314. true,
  1315. "same-authority-workspaces",
  1316. "empty",
  1317. "sessions",
  1318. );
  1319. return null;
  1320. }
  1321. const root: Root = createRoot(installMinimalDom());
  1322. await act(async () => {
  1323. root.render(
  1324. createElement(
  1325. ServiceProvider,
  1326. { services: local.services },
  1327. createElement(
  1328. TabStoreProvider,
  1329. null,
  1330. createElement(
  1331. WorkspaceTabsSeed,
  1332. {
  1333. activeWorkspaceIdentity: remoteAIdentity,
  1334. activeWorkspacePath: "/repo-a",
  1335. tabs: workspaceTabs,
  1336. },
  1337. createElement(Probe),
  1338. ),
  1339. ),
  1340. ),
  1341. );
  1342. await flushMicrotasks();
  1343. });
  1344. await act(async () => {
  1345. await flushMicrotasks();
  1346. });
  1347. expect(remoteA.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  1348. expect(remoteB.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  1349. expect(local.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  1350. expect((latest?.items ?? []).map((item) => item.value)).toEqual([
  1351. "s-remote-a-current",
  1352. "s-remote-a-project",
  1353. ]);
  1354. act(() => {
  1355. root.unmount();
  1356. });
  1357. });
  1358. it("# 面板未启用时不预订阅 sessions-index", async () => {
  1359. const local = createEndpointServices({
  1360. workspaceId: "ws-local",
  1361. sessions: [],
  1362. });
  1363. function Probe() {
  1364. useSessionsMentionProvider(
  1365. "glm",
  1366. "/workspace",
  1367. undefined,
  1368. "",
  1369. false,
  1370. "same-authority-workspaces",
  1371. "empty",
  1372. "sessions",
  1373. );
  1374. return null;
  1375. }
  1376. const root: Root = createRoot(installMinimalDom());
  1377. await act(async () => {
  1378. root.render(
  1379. createElement(
  1380. ServiceProvider,
  1381. { services: local.services },
  1382. createElement(TabStoreProvider, null, createElement(Probe)),
  1383. ),
  1384. );
  1385. await flushMicrotasks();
  1386. });
  1387. expect(local.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  1388. act(() => {
  1389. root.unmount();
  1390. });
  1391. });
  1392. });