conversation-session-composer-draft-switching.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import { DEFAULT_WORKSPACE, clearAppData } from "#e2e/helpers/desktop-app";
  2. import {
  3. E2E_REPLY_TOKEN,
  4. getV4ConversationState,
  5. prepareV4ConversationE2E,
  6. selectV4TaskById,
  7. sendV4Prompt,
  8. startNewV4Draft,
  9. waitForV4ConversationState,
  10. waitForV4ComposerText,
  11. waitForV4UserMessageContaining,
  12. setV4ComposerText,
  13. } from "#e2e/helpers/v4-conversation";
  14. import { waitForVisibleAttachmentNames } from "#e2e/helpers/conversation-session-composer-prefill";
  15. import { getV4ComposerDraftScopeSnapshot } from "#e2e/helpers/conversation-session-store";
  16. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  17. interface DraftExpectation {
  18. attachmentFilenames: string[];
  19. text: string;
  20. }
  21. describe("会话区 composer 草稿切换保留 E2E", () => {
  22. after(async () => {
  23. await browser.electron.restoreAllMocks();
  24. await clearAppData();
  25. });
  26. it("切换 completed/running/未发送 task 时应保留输入框正文和附件", async function () {
  27. this.timeout(260000);
  28. await prepareV4ConversationE2E();
  29. // 本例验证同一项目内的 session/草稿附件;任务入口的换目录由 PD01/02 单独断言。
  30. await startDraftFromProject(DEFAULT_WORKSPACE);
  31. const runId = Date.now();
  32. const completedPrompt = `E2E_COMPOSER_DRAFT_COMPLETED_SEED_${runId}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  33. await sendV4Prompt(completedPrompt);
  34. await waitForV4UserMessageContaining(`E2E_COMPOSER_DRAFT_COMPLETED_SEED_${runId}`);
  35. const completedTaskId = await waitForTaskIdle("completed seed 没有完成");
  36. const completedDraft = {
  37. text: `E2E_COMPOSER_DRAFT_COMPLETED_TEXT_${runId}`,
  38. attachmentFilenames: [`completed-note-${runId}.txt`, `completed-image-${runId}.png`],
  39. };
  40. await fillComposerDraft(completedTaskId, completedDraft);
  41. await waitForComposerDraftScope(completedTaskId, completedDraft);
  42. const runningPrompt = `E2E_SLOW_STREAM E2E_COMPOSER_DRAFT_RUNNING_SEED_${runId}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  43. await startNewV4Draft();
  44. await sendV4Prompt(runningPrompt);
  45. await waitForV4UserMessageContaining(`E2E_COMPOSER_DRAFT_RUNNING_SEED_${runId}`);
  46. const runningTaskId = await waitForTaskStreaming("running seed 没有进入 streaming");
  47. const runningDraft = {
  48. text: `E2E_COMPOSER_DRAFT_RUNNING_TEXT_${runId}`,
  49. attachmentFilenames: [`running-note-${runId}.txt`, `running-image-${runId}.png`],
  50. };
  51. await fillComposerDraft(runningTaskId, runningDraft);
  52. await waitForComposerDraftScope(runningTaskId, runningDraft);
  53. await startNewV4Draft();
  54. const unsentDraft = {
  55. text: `E2E_COMPOSER_DRAFT_UNSENT_TEXT_${runId}`,
  56. attachmentFilenames: [`unsent-note-${runId}.md`, `unsent-image-${runId}.png`],
  57. };
  58. await fillComposerDraft(null, unsentDraft);
  59. await waitForComposerDraftScope(null, unsentDraft);
  60. await selectV4TaskById(completedTaskId);
  61. await waitForComposerDraftVisible(completedTaskId, completedDraft);
  62. await assertComposerDraftScope(runningTaskId, runningDraft);
  63. await selectV4TaskById(runningTaskId);
  64. await waitForComposerDraftVisible(runningTaskId, runningDraft);
  65. await assertTaskStillRunningOrSettled(runningTaskId);
  66. await startNewV4Draft();
  67. await waitForComposerDraftVisible(null, unsentDraft);
  68. await assertComposerDraftScope(completedTaskId, completedDraft);
  69. await assertComposerDraftScope(runningTaskId, runningDraft);
  70. });
  71. });
  72. async function fillComposerDraft(taskId: string | null, expectation: DraftExpectation) {
  73. await setV4ComposerText(expectation.text);
  74. await seedComposerAttachmentScope(expectation.attachmentFilenames);
  75. await waitForComposerDraftVisibleOnCurrentScope(expectation);
  76. }
  77. async function seedComposerAttachmentScope(filenames: string[]) {
  78. const result = await browser.execute((nextFilenames) => {
  79. const w = window as typeof window & {
  80. __zcodeComposerAttachmentUploadStoreE2E?: {
  81. getState: () => { scopes: Record<string, unknown[]> };
  82. setState: (state: { scopes: Record<string, unknown[]> }) => void;
  83. };
  84. __zcodeCurrentComposerAttachmentScopeKeyE2E?: string;
  85. };
  86. const store = w.__zcodeComposerAttachmentUploadStoreE2E;
  87. const scopeKey = w.__zcodeCurrentComposerAttachmentScopeKeyE2E;
  88. if (!store || !scopeKey) return { ok: false, reason: "scope-missing" };
  89. store.setState({
  90. scopes: {
  91. ...store.getState().scopes,
  92. [scopeKey]: nextFilenames.map((filename, index) => ({
  93. id: `e2e-composer-draft-attachment-${index}`,
  94. filename,
  95. mimeType: filename.endsWith(".png") ? "image/png" : "text/plain",
  96. sizeBytes: 1,
  97. referenceOwnership: "composer",
  98. uploadStatus: "ready",
  99. uploadProgress: 100,
  100. attachmentRef: {
  101. ref: `/e2e/${filename}`,
  102. fileName: filename,
  103. mime: filename.endsWith(".png") ? "image/png" : "text/plain",
  104. bytes: 1,
  105. },
  106. operationId: `e2e-composer-draft-attachment-${index}`,
  107. autoRetryCount: 0,
  108. runtimeRebuildRetryCount: 0,
  109. staged: false,
  110. adopted: false,
  111. showComplete: false,
  112. localZeroCopy: false,
  113. })),
  114. },
  115. });
  116. return { ok: true };
  117. }, filenames);
  118. if (!result.ok) throw new Error(`附件 scope 写入失败: ${JSON.stringify(result)}`);
  119. }
  120. async function waitForComposerDraftVisibleOnCurrentScope(expectation: DraftExpectation) {
  121. await waitForV4ComposerText(expectation.text, `composer 没有显示草稿文本: ${expectation.text}`);
  122. const filenames = expectation.attachmentFilenames;
  123. const textFilenames = filenames.filter((filename) => !filename.endsWith(".png"));
  124. if (textFilenames.length > 0) {
  125. await waitForVisibleAttachmentNames(textFilenames);
  126. }
  127. const imageCount = filenames.filter((filename) => filename.endsWith(".png")).length;
  128. if (imageCount > 0) {
  129. await browser.waitUntil(
  130. async () =>
  131. browser.execute(
  132. (expectedCount) =>
  133. document.querySelectorAll(
  134. '[data-composer-attachment-kind="image"][data-upload-status="ready"]',
  135. ).length >= expectedCount,
  136. imageCount,
  137. ),
  138. {
  139. timeout: 10000,
  140. timeoutMsg: `composer 图片附件没有显示: ${imageCount}`,
  141. },
  142. );
  143. }
  144. }
  145. async function waitForComposerDraftVisible(taskId: string | null, expectation: DraftExpectation) {
  146. await waitForV4ConversationState(
  147. (snapshot) => (taskId === null ? snapshot.taskId === null : snapshot.taskId === taskId),
  148. `没有切到目标 task scope: ${taskId ?? "__draft__"}`,
  149. 30000,
  150. );
  151. await waitForComposerDraftVisibleOnCurrentScope(expectation);
  152. await assertComposerDraftScope(taskId, expectation);
  153. }
  154. async function waitForComposerDraftScope(taskId: string | null, expectation: DraftExpectation) {
  155. await browser.waitUntil(
  156. async () => {
  157. const snapshot = await getV4ComposerDraftScopeSnapshot(DEFAULT_WORKSPACE, taskId);
  158. return matchesDraftScope(snapshot, expectation);
  159. },
  160. {
  161. timeout: 10000,
  162. timeoutMsg: `composer draft scope 未保存: ${JSON.stringify({
  163. taskId,
  164. expectation,
  165. })}`,
  166. },
  167. );
  168. }
  169. async function assertComposerDraftScope(taskId: string | null, expectation: DraftExpectation) {
  170. const snapshot = await getV4ComposerDraftScopeSnapshot(DEFAULT_WORKSPACE, taskId);
  171. expect(snapshot.exists).toBe(true);
  172. expect(snapshot.text).toBe(expectation.text);
  173. expect(snapshot.mode).not.toBeNull();
  174. }
  175. function matchesDraftScope(
  176. snapshot: Awaited<ReturnType<typeof getV4ComposerDraftScopeSnapshot>>,
  177. expectation: DraftExpectation,
  178. ) {
  179. return snapshot.exists && snapshot.text === expectation.text && snapshot.mode !== null;
  180. }
  181. async function waitForTaskIdle(timeoutMsg: string) {
  182. const snapshot = await waitForV4ConversationState(
  183. (current) => current.state === "idle" && Boolean(current.taskId),
  184. timeoutMsg,
  185. 90000,
  186. );
  187. if (!snapshot.taskId) {
  188. throw new Error(`${timeoutMsg}: taskId missing`);
  189. }
  190. return snapshot.taskId;
  191. }
  192. async function waitForTaskStreaming(timeoutMsg: string) {
  193. const snapshot = await waitForV4ConversationState(
  194. (current) => current.state === "streaming" && Boolean(current.taskId),
  195. timeoutMsg,
  196. 30000,
  197. );
  198. if (!snapshot.taskId) {
  199. throw new Error(`${timeoutMsg}: taskId missing`);
  200. }
  201. return snapshot.taskId;
  202. }
  203. async function assertTaskStillRunningOrSettled(taskId: string) {
  204. const snapshot = await getV4ConversationState();
  205. expect(snapshot.taskId).toBe(taskId);
  206. expect(["streaming", "idle"]).toContain(snapshot.state);
  207. }