workflowActorSessionSidePane.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // @vitest-environment jsdom
  2. // actor transcript 面板(docs/dynamic-workflow/presentation.md「Subagent transcripts」):
  3. // 嵌套只读 SessionPane,组合方式照 SubagentSessionSidePane。
  4. //
  5. // 这里钉的是**组合**,不是会话内容:actor 会话是真实持久会话,它的实时性、冷恢复与回看
  6. // 全部由既有 SessionPane 链路负责。所以唯一需要保证的是「读到的是那个 actor 的会话,
  7. // 而且是只读的」——把 sessionId 接错,面板会安静地显示另一个人的对话。
  8. //
  9. // 另一半是**未启动门**(「actor transcript 的未启动态」):actor 会话在首个 ask 派发时才
  10. // 创建,所以提前点开 tab 会订阅一条还不存在的会话,投影 store 随即停在 error 只等手动
  11. // retry。门在 notStarted 时不挂订阅,改渲染占位。
  12. import { createElement, type ReactNode } from "react";
  13. import { renderToStaticMarkup } from "react-dom/server";
  14. import { afterEach, describe, expect, it, vi } from "vitest";
  15. import type { WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  16. import type { WorkflowActorSessionSidePaneTab } from "@/lib/workspaceSidePane.js";
  17. const paneState = vi.hoisted(() => ({
  18. props: null as Record<string, unknown> | null,
  19. /**
  20. * SessionPane **每次渲染**时的 sessionId(不是每次挂载——同一次挂载重渲染会重复入列)。
  21. * 因此空数组才是可断言的强命题;判身份时看去重集合,别把重渲染次数写进期望。
  22. */
  23. rendered: [] as string[],
  24. }));
  25. // layer 必须是**稳定引用**:门在渲染期同步 acquire 父会话租约(以 layer 为 useMemo 依赖),
  26. // 每次渲染换一个新对象就会每帧建一份新租约。生产里 useV4Conversation 返回的是 useMemo 过的
  27. // bundle,本来就稳定。
  28. const leaseState = vi.hoisted(() => ({
  29. /** 经由 layer 订阅过的 sessionId 序列——门的断言面就是这一条。 */
  30. acquired: [] as string[],
  31. release: vi.fn(),
  32. }));
  33. const conversation = vi.hoisted(() => ({
  34. layer: {
  35. acquire: (sessionId: string) => {
  36. leaseState.acquired.push(sessionId);
  37. return { release: leaseState.release };
  38. },
  39. },
  40. }));
  41. vi.mock("@/v4/SessionPane.js", async () => {
  42. const React = await import("react");
  43. return {
  44. SessionPane: (props: Record<string, unknown>) => {
  45. paneState.props = props;
  46. paneState.rendered.push(String(props.sessionId));
  47. // 复刻真 SessionPane 的订阅接缝(`SessionPane.tsx:1617-1633`:挂载 effect 里
  48. // `layer.acquire(effectiveSessionId)`,而 acquire 立刻 connect)。桩必须真的走一遍,
  49. // 否则「从没订阅过 actor 会话」会退化成一句空断言——桩本来就不订阅任何东西。
  50. React.useEffect(() => {
  51. const lease = conversation.layer.acquire(String(props.sessionId));
  52. return () => lease.release();
  53. }, [props.sessionId]);
  54. return React.createElement("div", { "data-testid": "mock-session-pane" });
  55. },
  56. };
  57. });
  58. const scopeState = vi.hoisted(() => ({ scope: null as unknown }));
  59. vi.mock("@/v4/V4ConversationContext.js", async () => {
  60. const React = await import("react");
  61. return {
  62. V4PaneConversationProvider: ({ children, scope }: { children?: ReactNode; scope: unknown }) => {
  63. scopeState.scope = scope;
  64. return React.createElement(React.Fragment, null, children);
  65. },
  66. useV4Conversation: () => conversation,
  67. };
  68. });
  69. const projectionState = vi.hoisted(() => ({ snapshot: null as unknown }));
  70. vi.mock("@/v4/useConversationProjection.js", () => ({
  71. // 复刻生产语义:**租约为 null 时没有 snapshot**(`CLOSED_STATE`)。这一条不能图省事,
  72. // 否则门看起来在首帧就有投影,而生产里它还没有——SessionPane 会先挂一次、订阅失败,
  73. // 而失败的 store 会在 SessionDataLayer 的 keep-warm 里带着 status:"error" 活满 30s,
  74. // 门放行时的 acquire 直接复用它(refCount++ 不再 connect),死面板照旧。
  75. useConversationProjection: (lease: unknown) =>
  76. lease === null || lease === undefined
  77. ? { snapshot: undefined }
  78. : { snapshot: projectionState.snapshot },
  79. }));
  80. // eslint-disable-next-line import/first -- 必须在 mock 之后再引入被测组件。
  81. import { cleanup, render } from "@testing-library/react";
  82. // eslint-disable-next-line import/first
  83. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  84. // eslint-disable-next-line import/first
  85. import { WorkflowActorSessionSidePane } from "@/app-shell/WorkflowActorSessionSidePane.js";
  86. // eslint-disable-next-line import/first
  87. import { openWorkflowActorSessionSidePane } from "@/lib/workspaceSidePane.js";
  88. const ACTOR_SESSION_ID = "dwf-dwfrun-1-actor_1@2";
  89. function tabOf(overrides: Partial<WorkflowActorSessionSidePaneTab> = {}) {
  90. const state = openWorkflowActorSessionSidePane(null, {
  91. workspaceKey: "ssh://host/workspace",
  92. workspacePath: "/workspace",
  93. workspaceIdentity: "ssh://host/workspace",
  94. remoteSessionId: "remote-1",
  95. parentSessionId: "parent-a",
  96. runId: "dwfrun-1",
  97. actorSessionId: ACTOR_SESSION_ID,
  98. siteId: "actor#1",
  99. ordinal: 2,
  100. actorName: "reviewer",
  101. });
  102. const tab = state.tabs[0] as WorkflowActorSessionSidePaneTab;
  103. return { ...tab, ...overrides };
  104. }
  105. /**
  106. * 该 actor 的 run 投影。`nodes` 决定门的判定;门按槽位 (runId, siteId, ordinal) 查 actor,
  107. * `actors` 可整体换掉(`[]` = 这个槽位还没出现)。
  108. */
  109. function snapshotWith(
  110. nodes: WorkflowRunState["nodes"],
  111. sessionId = ACTOR_SESSION_ID,
  112. actors: WorkflowRunState["actors"] = [
  113. { siteId: "actor#1", ordinal: 2, name: "reviewer", sessionId, status: "waiting" },
  114. ],
  115. ) {
  116. return {
  117. rows: { window: [] },
  118. workflowRuns: {
  119. revision: 1,
  120. runs: [
  121. {
  122. runId: "dwfrun-1",
  123. status: "running" as const,
  124. usage: { spentTokens: 0, nodesUsed: 0 },
  125. actors,
  126. nodes,
  127. lastEventSequence: 1,
  128. },
  129. ],
  130. },
  131. };
  132. }
  133. function renderTab(tab: WorkflowActorSessionSidePaneTab, locale: "en-US" | "zh-CN" = "en-US") {
  134. return createElement(
  135. ZCodeIntlProvider,
  136. { initialLocale: locale },
  137. createElement(WorkflowActorSessionSidePane, { tab, focused: true }),
  138. );
  139. }
  140. function renderPane(locale: "en-US" | "zh-CN" = "en-US") {
  141. return render(
  142. createElement(
  143. ZCodeIntlProvider,
  144. { initialLocale: locale },
  145. createElement(WorkflowActorSessionSidePane, { tab: tabOf(), focused: true }),
  146. ),
  147. );
  148. }
  149. describe("WorkflowActorSessionSidePane", () => {
  150. afterEach(() => {
  151. cleanup();
  152. paneState.props = null;
  153. paneState.rendered = [];
  154. scopeState.scope = null;
  155. projectionState.snapshot = null;
  156. leaseState.acquired = [];
  157. leaseState.release.mockClear();
  158. });
  159. it("把 actor 会话喂给一个只读的嵌套 SessionPane", () => {
  160. renderToStaticMarkup(
  161. createElement(WorkflowActorSessionSidePane, { tab: tabOf(), focused: true }),
  162. );
  163. expect(paneState.props).toMatchObject({
  164. allowWorkspaceFileRewind: true,
  165. focused: true,
  166. paneId: tabOf().id,
  167. readOnly: true,
  168. // 关键一行:读的是 actor 会话,不是父会话,也不是 run id。
  169. sessionId: "dwf-dwfrun-1-actor_1@2",
  170. telemetryVisible: true,
  171. workspacePath: "/workspace",
  172. });
  173. });
  174. it("不下发 subagent 下钻回调:actor 的工具面里没有 subagent", () => {
  175. // 引擎 spec 的「Actor tool surface」把 subagent 关掉了,所以这里既没有嵌套下钻可点,
  176. // 也就不该假装有一个入口。
  177. renderToStaticMarkup(
  178. createElement(WorkflowActorSessionSidePane, { tab: tabOf(), focused: false }),
  179. );
  180. expect(paneState.props?.onOpenSubagentSession).toBeUndefined();
  181. // rootSessionId 同理:actor 会话不在任何 subagent 树里,编一个根会让只读面板
  182. // 去订阅一条与它无关的会话。
  183. expect(paneState.props?.rootSessionId).toBeUndefined();
  184. });
  185. it("workspace scope 从 tab 上原样传给 pane provider(远程同路径工作区不串台)", () => {
  186. renderToStaticMarkup(
  187. createElement(WorkflowActorSessionSidePane, { tab: tabOf(), focused: false }),
  188. );
  189. expect(scopeState.scope).toEqual({
  190. workspacePath: "/workspace",
  191. workspaceIdentity: "ssh://host/workspace",
  192. remoteSessionId: "remote-1",
  193. });
  194. });
  195. it("非 focused 时不上报前台 telemetry", () => {
  196. renderToStaticMarkup(
  197. createElement(WorkflowActorSessionSidePane, { tab: tabOf(), focused: false }),
  198. );
  199. expect(paneState.props).toMatchObject({ focused: false, telemetryVisible: false });
  200. });
  201. });
  202. describe("WorkflowActorSessionSidePane 未启动门", () => {
  203. afterEach(() => {
  204. cleanup();
  205. paneState.props = null;
  206. paneState.rendered = [];
  207. scopeState.scope = null;
  208. projectionState.snapshot = null;
  209. leaseState.acquired = [];
  210. leaseState.release.mockClear();
  211. });
  212. it("actor 尚未派发任何节点时渲染占位,且**不挂订阅**", () => {
  213. // 这就是那个 bug:会话在首个 ask 派发时才创建,提前订阅必然 sessionNotFound,
  214. // 而投影 store 失败后只等手动 retry。门在这里不让 SessionPane 挂上。
  215. projectionState.snapshot = snapshotWith([
  216. { siteId: "ask#1", ordinal: 1, phase: "queued", actorSiteId: "actor#1", actorOrdinal: 2 },
  217. ]);
  218. const view = renderPane();
  219. expect(view.queryByTestId("workflow-actor-not-started")).not.toBeNull();
  220. // 门要保证的那条**否定**,也是最先该说话的一条:acquire 从没收到过 actor 会话 id。
  221. // 写成否定而不是 `toEqual(["parent-a"])`,是为了让将来多出一个正当的 acquire 时,
  222. // 这条断言仍然只说它该说的那件事。
  223. expect(leaseState.acquired).not.toContain(ACTOR_SESSION_ID);
  224. // 同时确认门**真的**读到了投影:父会话被订阅了。否则上面那条否定可以靠「什么都没做」通过。
  225. expect(leaseState.acquired).toContain("parent-a");
  226. // 连一帧都没渲染过。渲染过一帧就订阅过一次,而失败的 store 会在 keep-warm 里活满 30s
  227. // 并被后续 acquire 原样复用——那时门放行也换不回一个活面板。
  228. expect(paneState.rendered).toEqual([]);
  229. expect(view.queryByTestId("mock-session-pane")).toBeNull();
  230. expect(paneState.props).toBeNull();
  231. });
  232. it("占位文案双语可读", () => {
  233. projectionState.snapshot = snapshotWith([]);
  234. const en = renderPane("en-US");
  235. expect(en.getByTestId("workflow-actor-not-started").textContent).toContain("Not started yet");
  236. cleanup();
  237. const zh = renderPane("zh-CN");
  238. expect(zh.getByTestId("workflow-actor-not-started").textContent).toContain("尚未启动");
  239. });
  240. it("投影抬升到 dispatched 后自动换成嵌套 SessionPane(自愈,无需 retry)", () => {
  241. projectionState.snapshot = snapshotWith([]);
  242. const view = renderPane();
  243. expect(view.queryByTestId("workflow-actor-not-started")).not.toBeNull();
  244. projectionState.snapshot = snapshotWith([
  245. { siteId: "ask#1", ordinal: 1, phase: "dispatched", actorSiteId: "actor#1", actorOrdinal: 2 },
  246. ]);
  247. view.rerender(
  248. createElement(
  249. ZCodeIntlProvider,
  250. { initialLocale: "en-US" },
  251. createElement(WorkflowActorSessionSidePane, { tab: tabOf(), focused: true }),
  252. ),
  253. );
  254. expect(view.queryByTestId("workflow-actor-not-started")).toBeNull();
  255. expect(view.queryByTestId("mock-session-pane")).not.toBeNull();
  256. expect(paneState.props).toMatchObject({ sessionId: ACTOR_SESSION_ID, readOnly: true });
  257. // 自愈的正面证据:门放行后订阅**真的**发生了(首次派发之前它一次都没发生过)。
  258. expect(leaseState.acquired).toContain(ACTOR_SESSION_ID);
  259. });
  260. it("started 与 unknown 都照旧订阅:投影里查不到这个 actor 时绝不拦", () => {
  261. // run 被 8-run 上限淘汰或冷恢复后投影为空,直接订阅是 transcript 唯一的路——
  262. // 拦 unknown 等于把已完结 run 的唯一持久视图关死。tab 带着会话 id,就订阅它。
  263. projectionState.snapshot = snapshotWith([], ACTOR_SESSION_ID, []);
  264. const unknown = renderPane();
  265. expect(unknown.queryByTestId("mock-session-pane")).not.toBeNull();
  266. expect(unknown.queryByTestId("workflow-actor-not-started")).toBeNull();
  267. expect(leaseState.acquired).toContain(ACTOR_SESSION_ID);
  268. cleanup();
  269. leaseState.acquired = [];
  270. // 投影整体缺席(父会话还没连上 / 冷启动)同样是 unknown。
  271. projectionState.snapshot = null;
  272. const empty = renderPane();
  273. expect(empty.queryByTestId("mock-session-pane")).not.toBeNull();
  274. expect(leaseState.acquired).toContain(ACTOR_SESSION_ID);
  275. });
  276. it("未启动药丸开的槽位 tab(没有会话 id):占位、不订阅;actor 带着会话出现并派发后自愈", () => {
  277. // docs/dynamic-workflow/presentation.md「The pill」:tab 可以在 actor 出现之前就开。
  278. const { actorSessionId: _absent, ...slotTab } = tabOf();
  279. projectionState.snapshot = snapshotWith([], ACTOR_SESSION_ID, []);
  280. const view = render(renderTab(slotTab));
  281. expect(view.queryByTestId("workflow-actor-not-started")).not.toBeNull();
  282. expect(leaseState.acquired).toContain("parent-a");
  283. expect(leaseState.acquired).not.toContain(ACTOR_SESSION_ID);
  284. expect(paneState.rendered).toEqual([]);
  285. // actor 出现但还没派发:仍是占位(会话 id 已知,但订阅它必然 sessionNotFound)。
  286. // 面板是 memo 的,桩投影不会自己触发重渲染,所以每次换一个等价的 tab 对象。
  287. projectionState.snapshot = snapshotWith([]);
  288. view.rerender(renderTab({ ...slotTab }));
  289. expect(view.queryByTestId("workflow-actor-not-started")).not.toBeNull();
  290. expect(paneState.rendered).toEqual([]);
  291. // 首个节点派发:会话 id 从投影里来,SessionPane 挂上——tab 自己从没拿到过会话 id。
  292. projectionState.snapshot = snapshotWith([
  293. { siteId: "ask#1", ordinal: 1, phase: "dispatched", actorSiteId: "actor#1", actorOrdinal: 2 },
  294. ]);
  295. view.rerender(renderTab({ ...slotTab }));
  296. expect(view.queryByTestId("workflow-actor-not-started")).toBeNull();
  297. expect(paneState.props).toMatchObject({ sessionId: ACTOR_SESSION_ID, readOnly: true });
  298. expect(leaseState.acquired).toContain(ACTOR_SESSION_ID);
  299. });
  300. it("started 时订阅的是 actor 会话本身,不是父会话的替身", () => {
  301. // 门是加在 SessionPane **之前**的一层,最容易的接错方式就是把父会话 id 传下去。
  302. projectionState.snapshot = snapshotWith([
  303. {
  304. siteId: "ask#1",
  305. ordinal: 1,
  306. phase: "settled",
  307. outcome: "ok",
  308. actorSiteId: "actor#1",
  309. actorOrdinal: 2,
  310. },
  311. ]);
  312. renderPane();
  313. // 看去重集合而不是序列:重渲染次数不是契约,"只见过这一个会话 id"才是。
  314. expect(new Set(paneState.rendered)).toEqual(new Set([ACTOR_SESSION_ID]));
  315. expect(leaseState.acquired).toContain(ACTOR_SESSION_ID);
  316. });
  317. });