conversation-session-compact-manual-queue.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { clearAppData } from "../../../helpers/desktop-app.js";
  2. import {
  3. assertUpstreamRequestCapture,
  4. waitForUpstreamNetworkCapture,
  5. } from "../../../helpers/upstream-capture.js";
  6. import { UPSTREAM_MODEL } from "../../../helpers/upstream-provider.js";
  7. import {
  8. E2E_REPLY_TOKEN,
  9. buildReadonlyToolPrompt,
  10. countUpstreamRequestsContaining,
  11. expectNoUpstreamRequestForTextWithin,
  12. getQueueItems,
  13. prepareConversationE2E,
  14. sendPrompt,
  15. waitForChatState,
  16. waitForCompactMarkerStatus,
  17. waitForComposerText,
  18. waitForQueueContaining,
  19. waitForQueueCount,
  20. } from "../../../helpers/conversation-session.js";
  21. const COMPACT_REQUEST_SENTINEL = "CRITICAL: Respond with TEXT ONLY";
  22. describe("会话区手动 Compact 与 Held Queue E2E", () => {
  23. after(async () => {
  24. await browser.electron.restoreAllMocks();
  25. await clearAppData();
  26. });
  27. it("held queue 存在时手动 compact 应保留 queue 且不自动消费", async function () {
  28. this.timeout(180000);
  29. await prepareConversationE2E();
  30. const runId = Date.now();
  31. const prepPromptOne = `E2E_COMPACT_PREP_ONE_${runId}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  32. await sendPrompt(prepPromptOne);
  33. await waitForUpstreamNetworkCapture(`E2E_COMPACT_PREP_ONE_${runId}`);
  34. await waitForChatState(
  35. (snapshot) => snapshot.state === "idle",
  36. "第一轮 compact 预置消息没有完成",
  37. 30000,
  38. );
  39. const prepPromptTwo = buildReadonlyToolPrompt(
  40. `E2E_COMPACT_PREP_TWO_${runId}`,
  41. );
  42. await sendPrompt(prepPromptTwo);
  43. await waitForUpstreamNetworkCapture(`E2E_COMPACT_PREP_TWO_${runId}`);
  44. await waitForChatState(
  45. (snapshot) => snapshot.state === "idle",
  46. "第二轮 compact 预置消息没有完成",
  47. 30000,
  48. );
  49. const readySnapshot = await waitForChatState(
  50. (snapshot) =>
  51. Boolean(snapshot.taskId) &&
  52. snapshot.runtimeStatus === "completed" &&
  53. snapshot.activeInputId === null,
  54. "manual compact held queue 预置 task 没有进入 idle completed",
  55. 30000,
  56. );
  57. const taskId = readySnapshot.taskId;
  58. if (!taskId) {
  59. throw new Error(
  60. `manual compact held queue 缺少 taskId: ${JSON.stringify(readySnapshot)}`,
  61. );
  62. }
  63. const queuedPrompt = `E2E_COMPACT_QUEUE_HELD_${runId}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  64. const injectedQueue = await injectRendererHeldQueuePromptForE2E(
  65. taskId,
  66. queuedPrompt,
  67. );
  68. await waitForQueueContaining(`E2E_COMPACT_QUEUE_HELD_${runId}`);
  69. const heldQueue = await waitForQueueCount(1);
  70. const heldQueueItemId = heldQueue[0]?.id;
  71. expect(heldQueueItemId).toBeTruthy();
  72. expect(heldQueueItemId).toBe(injectedQueue.promptId);
  73. await waitForChatState(
  74. (snapshot) =>
  75. snapshot.state !== "streaming" &&
  76. snapshot.runtimeStatus === "completed" &&
  77. snapshot.activeInputId === null &&
  78. snapshot.queueCount === 1 &&
  79. snapshot.stopRequested,
  80. // 修复原因:该 case 验证 manual compact 与 held queue 的交互;
  81. // 用 renderer 测试桥构造 idle held queue,避免 replay 慢流 stop 后请求长时间 pending 误伤 compact。
  82. "没有构造出 idle held queue 状态",
  83. 30000,
  84. );
  85. const queuedRequestsBefore = await countUpstreamRequestsContaining(
  86. `E2E_COMPACT_QUEUE_HELD_${runId}`,
  87. );
  88. await sendPrompt("/compact");
  89. await waitForComposerText("", "/compact 发送后输入框没有清空");
  90. const startedMarker = await waitForCompactMarkerStatus("started", "manual");
  91. expect(startedMarker.inputId).toBeTruthy();
  92. expect(await getQueueItems()).toHaveLength(1);
  93. expect((await getQueueItems())[0]?.id).toBe(heldQueueItemId);
  94. const compactRecord = await waitForUpstreamNetworkCapture(
  95. COMPACT_REQUEST_SENTINEL,
  96. );
  97. assertUpstreamRequestCapture(compactRecord, {
  98. expectedText: COMPACT_REQUEST_SENTINEL,
  99. model: UPSTREAM_MODEL,
  100. });
  101. const completedMarker = await waitForCompactMarkerStatus(
  102. "completed",
  103. "manual",
  104. startedMarker.inputId,
  105. );
  106. expect(completedMarker.operationId).toBeTruthy();
  107. const finalQueue = await waitForQueueCount(1);
  108. expect(finalQueue[0]?.id).toBe(heldQueueItemId);
  109. expect(
  110. await countUpstreamRequestsContaining(`E2E_COMPACT_QUEUE_HELD_${runId}`),
  111. ).toBe(queuedRequestsBefore);
  112. const appendPrompt = `E2E_COMPACT_QUEUE_APPEND_AFTER_SUCCESS_${runId}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  113. const appendRequestsBefore = await countUpstreamRequestsContaining(
  114. `E2E_COMPACT_QUEUE_APPEND_AFTER_SUCCESS_${runId}`,
  115. );
  116. await sendPrompt(appendPrompt);
  117. await waitForComposerText(
  118. "",
  119. "completed held queue 下发送普通文本后输入框没有清空",
  120. );
  121. await waitForQueueContaining(
  122. `E2E_COMPACT_QUEUE_APPEND_AFTER_SUCCESS_${runId}`,
  123. );
  124. const appendedQueue = await waitForQueueCount(2);
  125. expect(appendedQueue[0]?.id).toBe(heldQueueItemId);
  126. expect(appendedQueue[1]?.content).toContain(
  127. `E2E_COMPACT_QUEUE_APPEND_AFTER_SUCCESS_${runId}`,
  128. );
  129. await expectNoUpstreamRequestForTextWithin(
  130. `E2E_COMPACT_QUEUE_APPEND_AFTER_SUCCESS_${runId}`,
  131. 800,
  132. );
  133. expect(
  134. await countUpstreamRequestsContaining(
  135. `E2E_COMPACT_QUEUE_APPEND_AFTER_SUCCESS_${runId}`,
  136. ),
  137. ).toBe(appendRequestsBefore);
  138. });
  139. });
  140. interface RendererHeldQueueInjectionResult {
  141. ok: boolean;
  142. promptId?: string;
  143. reason?: string;
  144. workspaceIdentity?: string | null;
  145. workspacePath?: string | null;
  146. }
  147. async function injectRendererHeldQueuePromptForE2E(
  148. taskId: string,
  149. content: string,
  150. ): Promise<RendererHeldQueueInjectionResult & { promptId: string }> {
  151. const result = (await browser.execute(
  152. (taskIdArg, contentArg) => {
  153. type RendererTaskMeta = {
  154. taskId?: string;
  155. workspaceIdentity?: string;
  156. workspacePath?: string;
  157. };
  158. type RendererWorkspace = {
  159. activeTaskId?: string | null;
  160. optimisticTaskListByTaskId?: Record<string, RendererTaskMeta>;
  161. taskListCache?: RendererTaskMeta[];
  162. };
  163. type RendererStore = {
  164. getState?: () => {
  165. enqueueTaskQueuedPrompt?: (
  166. workspacePath: string,
  167. taskId: string,
  168. prompt: {
  169. content: string;
  170. id: string;
  171. kind: "text";
  172. prompt: string;
  173. timestamp: number;
  174. },
  175. workspaceIdentity?: string,
  176. ) => void;
  177. setTaskStopRequested?: (
  178. workspacePath: string,
  179. taskId: string,
  180. requested: boolean,
  181. workspaceIdentity?: string,
  182. ) => void;
  183. workspaces?: Record<string, RendererWorkspace>;
  184. };
  185. };
  186. const storeApi = (
  187. window as Window & { __zcodeSessionStoreE2E?: RendererStore }
  188. ).__zcodeSessionStoreE2E;
  189. const state = storeApi?.getState?.();
  190. if (!state?.enqueueTaskQueuedPrompt || !state.setTaskStopRequested) {
  191. return { ok: false, reason: "store-api-missing" };
  192. }
  193. const workspaceEntry = Object.entries(state.workspaces ?? {}).find(
  194. ([, workspace]) =>
  195. workspace.activeTaskId === taskIdArg ||
  196. Boolean(workspace.optimisticTaskListByTaskId?.[taskIdArg]) ||
  197. Boolean(
  198. workspace.taskListCache?.some((task) => task.taskId === taskIdArg),
  199. ),
  200. );
  201. if (!workspaceEntry) {
  202. return { ok: false, reason: "task-workspace-not-found" };
  203. }
  204. const [workspaceKey, workspace] = workspaceEntry;
  205. const task =
  206. workspace.optimisticTaskListByTaskId?.[taskIdArg] ??
  207. workspace.taskListCache?.find((item) => item.taskId === taskIdArg);
  208. const workspacePath = task?.workspacePath ?? workspaceKey;
  209. const workspaceIdentity = task?.workspaceIdentity;
  210. const promptId = `queued-e2e-compact-manual-${Date.now()}-${Math.random()
  211. .toString(36)
  212. .slice(2, 6)}`;
  213. state.enqueueTaskQueuedPrompt(
  214. workspacePath,
  215. taskIdArg,
  216. {
  217. content: contentArg,
  218. id: promptId,
  219. kind: "text",
  220. prompt: contentArg,
  221. timestamp: Date.now(),
  222. },
  223. workspaceIdentity,
  224. );
  225. state.setTaskStopRequested(
  226. workspacePath,
  227. taskIdArg,
  228. true,
  229. workspaceIdentity,
  230. );
  231. return {
  232. ok: true,
  233. promptId,
  234. workspaceIdentity: workspaceIdentity ?? null,
  235. workspacePath,
  236. };
  237. },
  238. taskId,
  239. content,
  240. )) as RendererHeldQueueInjectionResult;
  241. if (!result.ok || !result.promptId) {
  242. throw new Error(
  243. `manual compact held queue 注入失败: ${result.reason ?? "unknown"}`,
  244. );
  245. }
  246. return result as RendererHeldQueueInjectionResult & { promptId: string };
  247. }