conversation-session-background.test.ts 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181
  1. import {
  2. assertIncomingMessage,
  3. assertTaskNotificationContents,
  4. } from "#e2e/helpers/incoming-message-evidence";
  5. import { execFile } from "node:child_process";
  6. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  7. import {
  8. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  9. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  10. TID_CHAT_BACKGROUND_RESULT_TITLE,
  11. TID_CHAT_LOADING,
  12. TID_CHAT_MESSAGES,
  13. TID_CHAT_USER_MESSAGE,
  14. TID_V4_BACKGROUND_WORK_CANCEL,
  15. TID_V4_SESSION_PANE,
  16. TID_V4_TURN_NAVIGATOR_ITEM,
  17. testId,
  18. } from "@zcode/shared/test-ids";
  19. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  20. import { assertForkAfterBackgroundNotification } from "#e2e/helpers/fork-background-history";
  21. import { clearAppData, seedSettings } from "#e2e/helpers/desktop-app";
  22. import {
  23. waitForCompactMarkerStatus,
  24. waitForCompactMarkerStatuses,
  25. } from "#e2e/helpers/conversation-session-compact";
  26. import {
  27. countUpstreamRequests,
  28. findFirstUpstreamRequestIndex,
  29. getUpstreamRequestEvidence,
  30. getUpstreamRequestRecordCount,
  31. getLatestUpstreamToolResultByToolCallId,
  32. waitForUpstreamRequest,
  33. } from "#e2e/helpers/conversation-session-network";
  34. import {
  35. clickFirstQueueSendNow,
  36. waitForQueueOrderContaining,
  37. } from "#e2e/helpers/conversation-session-queue";
  38. import {
  39. expandToolCallDetails,
  40. listToolCallBlocks,
  41. waitForToolCallBlockByToolCallId,
  42. waitForToolCallBlockByToolName,
  43. } from "#e2e/helpers/conversation-session-tool";
  44. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  45. import {
  46. assertVisibleV4UserMessagesNotContaining,
  47. clickV4Stop,
  48. getV4ConversationState,
  49. getV4Messages,
  50. getV4PaneSnapshot,
  51. openV4ComposerRunningBackgroundWorks,
  52. prepareV4ConversationE2E,
  53. selectV4TaskById,
  54. sendV4Prompt,
  55. sendV4PromptAndWaitAccepted,
  56. waitForV4AssistantMessageContaining,
  57. waitForV4ComposerText,
  58. waitForV4ConversationState,
  59. waitForV4TimelineContaining,
  60. waitForV4UserMessageContaining,
  61. V4_MAIN_PANE_ID,
  62. } from "#e2e/helpers/v4-conversation";
  63. import {
  64. ensureToolCrossProductFullAccessMode,
  65. respondToToolCrossProductBlockers,
  66. } from "#e2e/helpers/conversation-session-tool-cross-product";
  67. import {
  68. beginConversationTelemetryCapture,
  69. checkpointConversationTelemetryCase,
  70. waitForConversationReportDelta,
  71. type ConversationTelemetryReport,
  72. } from "#e2e/helpers/conversation-telemetry-parity-capture";
  73. const BACKGROUND_E2E_TIMEOUT_MS = 240000;
  74. const BACKGROUND_RUNTIME_ROOT = resolveE2ERuntimePath("conversation-session-background");
  75. const BG14_PREVIEW_RELEASE_FILE = resolveE2ERuntimePath(
  76. "conversation-session-background",
  77. "bg14-preview-release",
  78. );
  79. const BG08_ROOT_PID_FILE = resolveE2ERuntimePath(
  80. "conversation-session-background",
  81. "bg08-root.pid",
  82. );
  83. const BG08_LAUNCHER_PID_FILE = resolveE2ERuntimePath(
  84. "conversation-session-background",
  85. "bg08-launcher.pid",
  86. );
  87. const BG08_WORKER_PID_FILE = resolveE2ERuntimePath(
  88. "conversation-session-background",
  89. "bg08-worker.pid",
  90. );
  91. const BG08_LAUNCHER_SCRIPT_FILE = resolveE2ERuntimePath(
  92. "conversation-session-background",
  93. "bg08-launcher.cjs",
  94. );
  95. const BG08_LAUNCHER_SCRIPT = [
  96. 'const { spawn } = require("node:child_process");',
  97. 'const { writeFileSync } = require("node:fs");',
  98. 'writeFileSync(process.argv[2], String(process.pid) + "\\n");',
  99. 'const worker = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {',
  100. ' stdio: "ignore",',
  101. "});",
  102. 'if (!worker.pid) throw new Error("BG08 worker did not start");',
  103. 'writeFileSync(process.argv[3], String(worker.pid) + "\\n");',
  104. "setInterval(() => {}, 1000);",
  105. ].join("\n");
  106. const BG21_RELEASE_FILE = resolveE2ERuntimePath(
  107. "conversation-session-background",
  108. "bg21-child-tool-release",
  109. );
  110. const BG38_STARTED_FILE = resolveE2ERuntimePath(
  111. "conversation-session-background",
  112. "bg38-bash-started",
  113. );
  114. const BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE = resolveE2ERuntimePath(
  115. "conversation-session-background",
  116. "background-send-now-queue-release",
  117. );
  118. const BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE = resolveE2ERuntimePath(
  119. "conversation-session-background",
  120. "background-child-tool-idle-release",
  121. );
  122. const BACKGROUND_PARENT_ANCHOR_RELEASE_FILE = resolveE2ERuntimePath(
  123. "conversation-session-background",
  124. "background-parent-anchor-release",
  125. );
  126. const BACKGROUND_SWITCH_BACK_RELEASE_FILE = resolveE2ERuntimePath(
  127. "conversation-session-background",
  128. "background-switch-back-release",
  129. );
  130. const BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE = resolveE2ERuntimePath(
  131. "conversation-session-background",
  132. "agent-composition-mixed-foreground-release",
  133. );
  134. interface BackgroundResultPresentationSnapshot {
  135. assistantText: string;
  136. historyContentCount: number;
  137. visibleHistoryContentCount: number;
  138. historyTriggerId: string | null;
  139. historyTriggerCount: number;
  140. historyExpanded: string | null;
  141. titleOutsideHistory: boolean;
  142. navigatorItemCount: number;
  143. title: string;
  144. }
  145. async function getBackgroundResultPresentation(
  146. expectedTitle: string,
  147. ): Promise<BackgroundResultPresentationSnapshot | null> {
  148. return browser.execute(
  149. (titleTestId, historyTriggerTestId, historyContentTestId, navigatorItemTestId, title) => {
  150. const titleNode = Array.from(
  151. document.querySelectorAll<HTMLElement>(`[data-testid^="${titleTestId}-"]`),
  152. ).find((node) => node.textContent?.trim() === title);
  153. const turn = titleNode?.closest<HTMLElement>("[data-turn-key]");
  154. if (!titleNode || !turn) return null;
  155. return {
  156. assistantText: turn.innerText,
  157. historyContentCount: turn.querySelectorAll(`[data-testid^="${historyContentTestId}-"]`)
  158. .length,
  159. visibleHistoryContentCount: Array.from(
  160. turn.querySelectorAll<HTMLElement>(`[data-testid^="${historyContentTestId}-"]`),
  161. ).filter(
  162. (node) =>
  163. node.getBoundingClientRect().height > 0 &&
  164. getComputedStyle(node).visibility !== "hidden",
  165. ).length,
  166. historyTriggerId:
  167. turn
  168. .querySelector(`[data-testid^="${historyTriggerTestId}-"]`)
  169. ?.getAttribute("data-testid") ?? null,
  170. historyTriggerCount: turn.querySelectorAll(`[data-testid^="${historyTriggerTestId}-"]`)
  171. .length,
  172. navigatorItemCount: document.querySelectorAll(`[data-testid^="${navigatorItemTestId}-"]`)
  173. .length,
  174. historyExpanded:
  175. turn
  176. .querySelector(`[data-testid^="${historyTriggerTestId}-"]`)
  177. ?.getAttribute("aria-expanded") ?? null,
  178. titleOutsideHistory: titleNode.closest('[data-slot="collapsible-content"]') === null,
  179. title: titleNode.textContent?.trim() ?? "",
  180. };
  181. },
  182. TID_CHAT_BACKGROUND_RESULT_TITLE,
  183. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  184. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  185. TID_V4_TURN_NAVIGATOR_ITEM,
  186. expectedTitle,
  187. );
  188. }
  189. async function waitForBackgroundResultPresentation(options: {
  190. assistantMarker: string;
  191. expectedTitle: string;
  192. failureLabel: string;
  193. }): Promise<void> {
  194. let snapshot: BackgroundResultPresentationSnapshot | null = null;
  195. let titles: string[] = [];
  196. try {
  197. await browser.waitUntil(
  198. async () => {
  199. snapshot = await getBackgroundResultPresentation(options.expectedTitle);
  200. // 失败时带上页面里实际出现的结果轮标题,区分“标题不同”与“折叠状态不对”。
  201. titles = await browser.execute(
  202. (titleTestId) =>
  203. Array.from(
  204. document.querySelectorAll<HTMLElement>(`[data-testid^="${titleTestId}-"]`),
  205. ).map((node) => node.textContent?.trim() ?? ""),
  206. TID_CHAT_BACKGROUND_RESULT_TITLE,
  207. );
  208. return Boolean(
  209. snapshot &&
  210. snapshot.assistantText.includes(options.assistantMarker) &&
  211. snapshot.historyTriggerCount === 1 &&
  212. snapshot.historyExpanded === "false" &&
  213. snapshot.titleOutsideHistory &&
  214. snapshot.visibleHistoryContentCount === 0 &&
  215. snapshot.navigatorItemCount === 0,
  216. );
  217. },
  218. {
  219. timeout: 60000,
  220. timeoutMsg: `${options.failureLabel} 结果轮等待超时`,
  221. },
  222. );
  223. } catch (error) {
  224. throw new Error(
  225. `${options.failureLabel} 没有显示结构化标题、完成态折叠入口缺失,或被计入 turn navigator; titles=${JSON.stringify(titles)}; snapshot=${JSON.stringify(snapshot)}`,
  226. { cause: error },
  227. );
  228. }
  229. expect(snapshot).toMatchObject({
  230. visibleHistoryContentCount: 0,
  231. historyTriggerCount: 1,
  232. historyExpanded: "false",
  233. titleOutsideHistory: true,
  234. navigatorItemCount: 0,
  235. title: options.expectedTitle,
  236. });
  237. // 必须观察实际过程容器:仅检查触发器状态会漏掉内容仍可见的回归。
  238. const completed = await getBackgroundResultPresentation(options.expectedTitle);
  239. expect(completed?.historyTriggerId).toBeTruthy();
  240. const trigger = await $(`[data-testid="${completed!.historyTriggerId}"]`);
  241. for (const expanded of [true, false]) {
  242. await trigger.click();
  243. await browser.waitUntil(
  244. async () => {
  245. const current = await getBackgroundResultPresentation(options.expectedTitle);
  246. return Boolean(
  247. current &&
  248. current.historyExpanded === String(expanded) &&
  249. current.visibleHistoryContentCount === (expanded ? 1 : 0) &&
  250. (!expanded ||
  251. (current.historyContentCount === 1 &&
  252. current.assistantText.includes("background-history-visible"))) &&
  253. current.titleOutsideHistory &&
  254. current.assistantText.includes(options.assistantMarker),
  255. );
  256. },
  257. {
  258. timeout: 5000,
  259. timeoutMsg: `${options.failureLabel} 过程${expanded ? "展开" : "收起"}后内容可见性或最终结果不符合预期`,
  260. },
  261. );
  262. }
  263. }
  264. describe("会话区 Background Runtime Task E2E", () => {
  265. before(async function () {
  266. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  267. await mkdir(BACKGROUND_RUNTIME_ROOT, { recursive: true });
  268. await writeFile(BG08_LAUNCHER_SCRIPT_FILE, BG08_LAUNCHER_SCRIPT, "utf-8");
  269. await removeBg08PidFiles();
  270. await seedSettings({ messageStreamShowTodos: true });
  271. await prepareV4ConversationE2E();
  272. });
  273. afterEach(async () => {
  274. // BG21 / send-now 的 child Bash 使用文件 barrier;失败收尾也要先释放,
  275. // 避免遗留后台进程。
  276. await Promise.all([
  277. writeFile(BG21_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined),
  278. writeFile(BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE, "release\n", "utf-8").catch(
  279. () => undefined,
  280. ),
  281. writeFile(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, "release\n", "utf-8").catch(
  282. () => undefined,
  283. ),
  284. writeFile(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined),
  285. writeFile(BACKGROUND_SWITCH_BACK_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined),
  286. ]);
  287. await stopIfBusy();
  288. await cleanupBg08ProcessTree();
  289. await rm(BG21_RELEASE_FILE, { force: true }).catch(() => undefined);
  290. await rm(BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE, { force: true }).catch(() => undefined);
  291. await rm(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, { force: true }).catch(() => undefined);
  292. await rm(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, { force: true }).catch(() => undefined);
  293. await rm(BACKGROUND_SWITCH_BACK_RELEASE_FILE, { force: true }).catch(() => undefined);
  294. await rm(BG38_STARTED_FILE, { force: true }).catch(() => undefined);
  295. await removeBg08PidFiles();
  296. });
  297. after(async () => {
  298. await browser.electron.restoreAllMocks();
  299. await rm(BACKGROUND_RUNTIME_ROOT, { force: true, recursive: true });
  300. await clearAppData();
  301. });
  302. it("background Agent 完成后通过 task-notification 唤醒父会话且不显示 synthetic user", async function () {
  303. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  304. await startNewBackgroundDraft();
  305. const prompt =
  306. "E2E_BACKGROUND_AGENT: Launch a background agent and summarize only after its notification.";
  307. const requestCountBefore = await getUpstreamRequestRecordCount();
  308. await sendV4PromptAndWaitAccepted(
  309. prompt,
  310. "E2E_BACKGROUND_AGENT",
  311. "background Agent prompt 没有被 composer 接受",
  312. );
  313. await waitForToolCallBlockByToolName("Agent", 60000);
  314. await respondToBackgroundBlockers();
  315. const launchIndex = await waitForFirstRequestIndex(
  316. {
  317. includes: ["E2E_BACKGROUND_AGENT", "Async agent launched successfully"],
  318. },
  319. requestCountBefore,
  320. "background Agent launch tool result 没有进入父模型请求",
  321. );
  322. const notificationIndex = await waitForFirstRequestIndex(
  323. {
  324. includes: ["<task-notification>", "E2E_BACKGROUND_AGENT_CHILD_RESULT"],
  325. },
  326. launchIndex,
  327. "background Agent completion notification 没有进入父模型请求",
  328. );
  329. expect(notificationIndex).toBeGreaterThan(launchIndex);
  330. await waitForV4AssistantMessageContaining("background-agent-notification-consumed-ok");
  331. // Bug 根因:V4 completed turn 会把旧 Agent tool card 收进 timeline history;
  332. // 本 case 的主合同由 notification 请求顺序、独立结果轮和无 synthetic user 共同覆盖,
  333. // 不再重复依赖 legacy card 的瞬时展开状态。
  334. await waitForIdle("background Agent notification 后会话没有回到 idle");
  335. await waitForBackgroundResultPresentation({
  336. assistantMarker: "background-agent-notification-consumed-ok",
  337. expectedTitle: "Check background",
  338. failureLabel: "background Agent 独立结果轮",
  339. });
  340. await assertNoVisibleTaskNotification();
  341. await browser.refresh();
  342. await waitForBackgroundResultPresentation({
  343. assistantMarker: "background-agent-notification-consumed-ok",
  344. expectedTitle: "Check background",
  345. failureLabel: "background Agent 刷新恢复结果轮",
  346. });
  347. });
  348. it("background Bash 完成后复用同一 notification/wake 链路", async function () {
  349. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  350. await startNewBackgroundDraft();
  351. const capture = await beginBackgroundTelemetryCapture();
  352. const prompt =
  353. "E2E_BACKGROUND_BASH: Run a background Bash command and report after notification.";
  354. const requestCountBefore = await getUpstreamRequestRecordCount();
  355. await sendV4Prompt(prompt);
  356. await waitForV4ComposerText("", "background Bash prompt 发送后输入框没有清空");
  357. await waitForV4UserMessageContaining("E2E_BACKGROUND_BASH");
  358. await waitForToolCallBlockByToolName("Bash", 60000);
  359. await respondToBackgroundBlockers();
  360. const launchIndex = await waitForFirstRequestIndex(
  361. {
  362. includes: ["E2E_BACKGROUND_BASH", "Command running in background"],
  363. },
  364. requestCountBefore,
  365. "background Bash launch tool result 没有进入父模型请求",
  366. );
  367. const notificationIndex = await waitForFirstRequestIndex(
  368. {
  369. includes: [
  370. "E2E_BACKGROUND_BASH",
  371. "<task-notification>",
  372. "<tool-use-id>toolu_e2e_background_bash</tool-use-id>",
  373. "<status>completed</status>",
  374. ],
  375. },
  376. launchIndex,
  377. "background Bash completion notification 没有进入父模型请求",
  378. );
  379. expect(notificationIndex).toBeGreaterThan(launchIndex);
  380. await waitForV4AssistantMessageContaining("background-bash-notification-consumed-ok");
  381. await waitForIdle("background Bash notification 后会话没有回到 idle");
  382. await waitForBackgroundResultPresentation({
  383. assistantMarker: "background-bash-notification-consumed-ok",
  384. expectedTitle: "Print background marker",
  385. failureLabel: "background Bash 独立结果轮",
  386. });
  387. // 失败原因:完成后的 Bash 块收在 assistant history 里,waitForToolCallBlock 找不到时会
  388. // 主动展开 history;放在“结果轮默认收起”断言之前,就是测试自己把它展开了。
  389. // 必须先验证默认收起,再读块状态。
  390. const block = await waitForToolCallBlockByToolName("Bash", 30000);
  391. expect(block.status).not.toBe("running");
  392. await assertNoVisibleTaskNotification();
  393. const reports = await waitForConversationReportDelta(capture, {
  394. message_completion: 2,
  395. });
  396. assertMainCompletionAgentCompositions(reports, ["main_only", "main_only"]);
  397. assertMainCompletionMessageSources(reports, ["chat", "background_task"]);
  398. });
  399. it("background task running 时用户普通消息应直接发送而不是进入 queue", async function () {
  400. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  401. await startNewBackgroundDraft();
  402. const launchPrompt =
  403. "E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP: Start a long background Bash command and wait for my next message.";
  404. const requestCountBefore = await getUpstreamRequestRecordCount();
  405. await sendV4Prompt(launchPrompt);
  406. await waitForV4ComposerText("", "background direct user prompt setup 发送后输入框没有清空");
  407. await waitForV4UserMessageContaining("E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP");
  408. await waitForToolCallBlockByToolCallId("toolu_e2e_background_direct_user_prompt_bash", 60000);
  409. await respondToBackgroundBlockers();
  410. const launchIndex = await waitForFirstRequestIndex(
  411. {
  412. includes: ["E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP", "Command running in background"],
  413. },
  414. requestCountBefore,
  415. "background direct user prompt setup 的 Bash launch result 没有进入父模型请求",
  416. );
  417. await waitForV4AssistantMessageContaining("background-direct-user-prompt-launched-ok");
  418. await waitForIdle("background direct user prompt setup 后父会话没有回到 idle");
  419. await waitForBackgroundTaskControlRow(
  420. "bash",
  421. "background direct user prompt bash sleep",
  422. "background direct user prompt Bash 没有出现在统一 background control UI",
  423. );
  424. const directPrompt =
  425. "E2E_BACKGROUND_DIRECT_USER_PROMPT: This message should be sent immediately while the background task is still running. Payload: E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD.";
  426. await sendV4Prompt(directPrompt);
  427. await waitForV4ComposerText("", "background running 时用户新消息发送后输入框没有清空");
  428. await waitForV4UserMessageContaining("E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD");
  429. const directSnapshot = await getV4ConversationState();
  430. expect(directSnapshot.queueCount).toBe(0);
  431. const directPromptIndex = await waitForFirstRequestIndex(
  432. {
  433. includes: [
  434. "E2E_BACKGROUND_DIRECT_USER_PROMPT",
  435. "E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD",
  436. ],
  437. lastUserMessageIncludes: ["E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD"],
  438. },
  439. launchIndex,
  440. "background running 时用户普通消息没有立即进入 provider request",
  441. );
  442. expect(directPromptIndex).toBeGreaterThan(launchIndex);
  443. await waitForV4AssistantMessageContaining("background-direct-user-prompt-received-ok");
  444. await waitForIdle("background running 时用户普通消息响应后会话没有回到 idle");
  445. await waitForBackgroundTaskControlRow(
  446. "bash",
  447. "background direct user prompt bash sleep",
  448. "用户普通消息完成后 background Bash control row 不应消失",
  449. );
  450. await clickStopBackgroundTaskControlRow("bash", "background direct user prompt bash sleep");
  451. const notificationIndex = await waitForFirstRequestIndex(
  452. {
  453. includes: [
  454. "E2E_BACKGROUND_DIRECT_USER_PROMPT_SETUP",
  455. "<task-notification>",
  456. "<tool-use-id>toolu_e2e_background_direct_user_prompt_bash</tool-use-id>",
  457. "<status>killed</status>",
  458. ],
  459. lastUserMessageIncludes: ["<task-notification>"],
  460. },
  461. directPromptIndex,
  462. "background direct user prompt Bash stop notification 没有进入父模型请求",
  463. );
  464. expect(notificationIndex).toBeGreaterThan(directPromptIndex);
  465. await waitForV4AssistantMessageContaining("background-direct-user-prompt-bash-stopped-ok");
  466. await waitForNoBackgroundTaskControlRow(
  467. "bash",
  468. "background direct user prompt bash sleep",
  469. "被停止的 background direct user prompt Bash 仍显示为 running",
  470. );
  471. await waitForIdle("background direct user prompt Bash stop notification 后会话没有回到 idle");
  472. await assertNoVisibleTaskNotification();
  473. });
  474. it("background task running 且 main idle 时允许 compact,完成 notification 基于 compact 后上下文继续", async function () {
  475. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  476. await startNewBackgroundDraft();
  477. const prompt =
  478. "E2E_BACKGROUND_COMPACT_AFTER_IDLE: Start a background Bash, then stay idle while I compact the conversation.";
  479. const requestCountBefore = await getUpstreamRequestRecordCount();
  480. await sendV4PromptAndWaitAccepted(
  481. prompt,
  482. "E2E_BACKGROUND_COMPACT_AFTER_IDLE",
  483. "background compact setup prompt 没有被 composer 接受",
  484. );
  485. await waitForToolCallBlockByToolCallId("toolu_e2e_background_compact_after_idle_bash", 60000);
  486. await respondToBackgroundBlockers();
  487. const launchIndex = await waitForFirstRequestIndex(
  488. {
  489. includes: ["E2E_BACKGROUND_COMPACT_AFTER_IDLE", "Command running in background"],
  490. },
  491. requestCountBefore,
  492. "background compact Bash launch tool result 没有进入父模型请求",
  493. );
  494. await waitForV4AssistantMessageContaining("background-compact-launched-ok");
  495. await waitForIdle("background compact setup 后 main 没有回到 idle");
  496. await waitForBackgroundTaskControlRow(
  497. "bash",
  498. "background compact bash sleep",
  499. "background compact Bash 没有出现在统一 background control UI",
  500. );
  501. await sendV4Prompt("/compact");
  502. await waitForV4ComposerText("", "background running 时 /compact 发送后输入框没有清空");
  503. // Bug 根因:V4 compact row 会原位从 running 更新成 success,快速 replay 下
  504. // started 可能在 WDIO 首次轮询前就收口;completed 同样能证明命令已被 admission。
  505. const compactMarker = await waitForCompactMarkerStatuses(["started", "completed"], "manual");
  506. expect(compactMarker.inputId).toBeTruthy();
  507. if (compactMarker.status !== "completed") {
  508. await waitForCompactMarkerStatus("completed", "manual", compactMarker.inputId);
  509. }
  510. const notificationIndex = await waitForFirstRequestIndex(
  511. {
  512. includes: [
  513. "<task-notification>",
  514. "E2E_BACKGROUND_COMPACT_SUMMARY_MARKER",
  515. "toolu_e2e_background_compact_after_idle_bash",
  516. "<status>completed</status>",
  517. ],
  518. lastUserMessageIncludes: ["<task-notification>"],
  519. },
  520. launchIndex,
  521. "background compact 后 completion notification 没有基于 compact 摘要进入父模型请求",
  522. );
  523. expect(notificationIndex).toBeGreaterThan(launchIndex);
  524. await waitForV4AssistantMessageContaining("background-compact-notification-consumed-ok");
  525. await waitForIdle("background compact notification 后会话没有回到 idle");
  526. await assertNoVisibleTaskNotification();
  527. });
  528. it("foreground long-running Bash timeout 后会转为 background,并在完成后从 UI 移除", async function () {
  529. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  530. await startNewBackgroundDraft();
  531. const prompt =
  532. "E2E_BACKGROUND_AUTO_TIMEOUT_BASH: Run an eligible foreground Bash command that should auto-background on timeout, then report after completion.";
  533. const requestCountBefore = await getUpstreamRequestRecordCount();
  534. await sendV4PromptAndWaitAccepted(
  535. prompt,
  536. "E2E_BACKGROUND_AUTO_TIMEOUT_BASH",
  537. "foreground Bash auto-background prompt 没有被 composer 接受",
  538. );
  539. await waitForToolCallBlockByToolCallId("toolu_e2e_background_auto_timeout_bash", 60000);
  540. await respondToBackgroundBlockers();
  541. const launchIndex = await waitForFirstRequestIndex(
  542. {
  543. // 前台 Bash 超时转后台时,结果写明超时并给出后台任务 ID。
  544. includes: ["E2E_BACKGROUND_AUTO_TIMEOUT_BASH", "and was moved to the background (ID:"],
  545. },
  546. requestCountBefore,
  547. "foreground Bash timeout 后没有返回 backgrounded tool result",
  548. );
  549. await waitForBackgroundTaskControlRow(
  550. "bash",
  551. "auto timeout bash sleep",
  552. "auto-background Bash 没有出现在统一 background control UI",
  553. );
  554. const notificationIndex = await waitForFirstRequestIndex(
  555. {
  556. includes: [
  557. "E2E_BACKGROUND_AUTO_TIMEOUT_BASH",
  558. "<task-notification>",
  559. "<tool-use-id>toolu_e2e_background_auto_timeout_bash</tool-use-id>",
  560. "<status>completed</status>",
  561. ],
  562. lastUserMessageIncludes: ["<task-notification>"],
  563. },
  564. launchIndex,
  565. "auto-background Bash completion notification 没有进入父模型请求",
  566. );
  567. expect(notificationIndex).toBeGreaterThan(launchIndex);
  568. await waitForV4AssistantMessageContaining("background-auto-timeout-bash-completed-ok");
  569. await waitForNoBackgroundTaskControlRow(
  570. "bash",
  571. "auto timeout bash sleep",
  572. "自然完成的 auto-background Bash 仍显示为 running",
  573. );
  574. await waitForIdle("auto-background Bash notification 后会话没有回到 idle");
  575. await assertNoVisibleTaskNotification();
  576. });
  577. it("explicit background Bash 越过 input timeout 后仍自然完成且只通知一次", async function () {
  578. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  579. await startNewBackgroundDraft();
  580. const prompt =
  581. "E2E_BG37_EXPLICIT_TIMEOUT: Start an explicit background Bash whose timeout is shorter than its runtime, then report after completion.";
  582. const requestCountBefore = await getUpstreamRequestRecordCount();
  583. await sendV4PromptAndWaitAccepted(
  584. prompt,
  585. "E2E_BG37_EXPLICIT_TIMEOUT",
  586. "BG37 prompt 没有被 composer 接受",
  587. );
  588. await waitForToolCallBlockByToolCallId("toolu_e2e_bg37_explicit_timeout", 60000);
  589. await respondToBackgroundBlockers();
  590. const launchIndex = await waitForFirstRequestIndex(
  591. {
  592. includes: ["E2E_BG37_EXPLICIT_TIMEOUT", "Command running in background"],
  593. },
  594. requestCountBefore,
  595. "BG37 explicit Bash 没有返回 background task ID",
  596. );
  597. const launchResult = await getLatestUpstreamToolResultByToolCallId(
  598. "toolu_e2e_bg37_explicit_timeout",
  599. );
  600. const outputPath = /Output is being written to: (.+?)\. You will be notified/u.exec(
  601. launchResult?.content ?? "",
  602. )?.[1];
  603. expect(outputPath).toBeTruthy();
  604. // 根因回归:后台 launch 成功不能代替实时落盘证据;在 DONE 之前读取同一路径。
  605. const runningOutput = await readFile(outputPath!, "utf8");
  606. expect(runningOutput).toContain("E2E_BG37_STARTED");
  607. expect(runningOutput).not.toContain("E2E_BG37_DONE");
  608. await waitForBackgroundTaskControlRow(
  609. "bash",
  610. "BG37 explicit timeout bash",
  611. "BG37 explicit Bash 没有出现在 background control UI",
  612. );
  613. await browser.pause(100);
  614. await waitForBackgroundTaskControlRow(
  615. "bash",
  616. "BG37 explicit timeout bash",
  617. "BG37 explicit Bash 越过 input timeout 后不应被终止",
  618. );
  619. const notificationIndex = await waitForFirstRequestIndex(
  620. {
  621. includes: [
  622. "E2E_BG37_EXPLICIT_TIMEOUT",
  623. "<task-notification>",
  624. "<tool-use-id>toolu_e2e_bg37_explicit_timeout</tool-use-id>",
  625. "<status>completed</status>",
  626. ],
  627. lastUserMessageIncludes: ["<task-notification>"],
  628. },
  629. launchIndex,
  630. "BG37 explicit Bash completion notification 没有进入父模型请求",
  631. );
  632. await waitForV4AssistantMessageContaining("bg37-explicit-timeout-completed-ok");
  633. expect(
  634. await countUpstreamRequests(
  635. {
  636. includes: [
  637. "<task-notification>",
  638. "<tool-use-id>toolu_e2e_bg37_explicit_timeout</tool-use-id>",
  639. ],
  640. },
  641. { afterIndex: launchIndex },
  642. ),
  643. ).toBe(1);
  644. expect(notificationIndex).toBeGreaterThan(launchIndex);
  645. await waitForNoBackgroundTaskControlRow(
  646. "bash",
  647. "BG37 explicit timeout bash",
  648. "BG37 completed Bash 仍显示为 running",
  649. );
  650. await waitForIdle("BG37 completion notification 后会话没有回到 idle");
  651. const completedOutput = await readFile(outputPath!, "utf8");
  652. expect(completedOutput).toContain("E2E_BG37_STARTED");
  653. expect(completedOutput).toContain("E2E_BG37_DONE");
  654. });
  655. it("explicit Bash commit 后停止 parent turn 不会终止后台进程", async function () {
  656. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  657. await rm(BG38_STARTED_FILE, { force: true }).catch(() => undefined);
  658. await startNewBackgroundDraft();
  659. const prompt =
  660. "E2E_BG38_PARENT_ABORT: Start an explicit background Bash, keep the parent turn running, and let me stop that turn after the task starts.";
  661. const requestCountBefore = await getUpstreamRequestRecordCount();
  662. await sendV4PromptAndWaitAccepted(
  663. prompt,
  664. "E2E_BG38_PARENT_ABORT",
  665. "BG38 prompt 没有被 composer 接受",
  666. );
  667. await waitForToolCallBlockByToolCallId("toolu_e2e_bg38_parent_abort", 60000);
  668. await respondToBackgroundBlockers();
  669. const launchIndex = await waitForFirstRequestIndex(
  670. {
  671. includes: ["E2E_BG38_PARENT_ABORT", "Command running in background"],
  672. },
  673. requestCountBefore,
  674. "BG38 explicit Bash 没有完成 background commit",
  675. );
  676. await waitForBackgroundTaskControlRow(
  677. "bash",
  678. "BG38 parent abort bash",
  679. "BG38 committed Bash 没有出现在 background control UI",
  680. );
  681. let startedMarker = "";
  682. await browser.waitUntil(
  683. async () => {
  684. startedMarker = await readFile(BG38_STARTED_FILE, "utf-8").catch(() => "");
  685. return startedMarker.includes("E2E_BG38_STARTED");
  686. },
  687. {
  688. timeout: 30000,
  689. timeoutMsg: `BG38 Bash 没有写出 started marker; latest=${startedMarker}`,
  690. },
  691. );
  692. await waitForMainLoading("BG38 parent turn 在 stop 前没有保持 running");
  693. await clickV4Stop();
  694. await waitForV4ConversationState(
  695. (snapshot) => snapshot.state !== "streaming",
  696. "BG38 parent turn stop 后没有退出 streaming",
  697. 30000,
  698. );
  699. await waitForBackgroundTaskControlRow(
  700. "bash",
  701. "BG38 parent abort bash",
  702. "BG38 parent turn stop 后后台 control row 不应消失",
  703. );
  704. const notificationIndex = await waitForFirstRequestIndex(
  705. {
  706. includes: [
  707. "E2E_BG38_PARENT_ABORT",
  708. "<task-notification>",
  709. "<tool-use-id>toolu_e2e_bg38_parent_abort</tool-use-id>",
  710. "<status>completed</status>",
  711. "E2E_BG38_DONE",
  712. ],
  713. lastUserMessageIncludes: ["<task-notification>"],
  714. },
  715. launchIndex,
  716. "BG38 parent abort 后 Bash 没有自然完成",
  717. );
  718. await waitForV4AssistantMessageContaining("bg38-parent-abort-background-completed-ok");
  719. expect(
  720. await countUpstreamRequests(
  721. {
  722. includes: [
  723. "<task-notification>",
  724. "<tool-use-id>toolu_e2e_bg38_parent_abort</tool-use-id>",
  725. ],
  726. },
  727. { afterIndex: launchIndex },
  728. ),
  729. ).toBe(1);
  730. expect(notificationIndex).toBeGreaterThan(launchIndex);
  731. await waitForNoBackgroundTaskControlRow(
  732. "bash",
  733. "BG38 parent abort bash",
  734. "BG38 completed Bash 留下 orphan control row",
  735. );
  736. await waitForIdle("BG38 completion notification 后会话没有回到 idle");
  737. });
  738. it("首 token 为 sleep 的 foreground Bash timeout 后不会转 background", async function () {
  739. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  740. await startNewBackgroundDraft();
  741. const prompt =
  742. "E2E_BG39_SLEEP_HARD_TIMEOUT: Run a foreground Bash whose first raw token is sleep with a timeout shorter than its runtime.";
  743. const requestCountBefore = await getUpstreamRequestRecordCount();
  744. await sendV4PromptAndWaitAccepted(
  745. prompt,
  746. "E2E_BG39_SLEEP_HARD_TIMEOUT",
  747. "BG39 prompt 没有被 composer 接受",
  748. );
  749. await waitForToolCallBlockByToolCallId("toolu_e2e_bg39_sleep_timeout", 60000);
  750. await respondToBackgroundBlockers();
  751. const completionIndex = await waitForFirstRequestIndex(
  752. {
  753. includes: ["E2E_BG39_SLEEP_HARD_TIMEOUT", "Command timed out after 0s"],
  754. excludes: ["Command running in background"],
  755. },
  756. requestCountBefore,
  757. "BG39 sleep Bash 没有返回 foreground timeout 结果",
  758. );
  759. // 硬超时按失败结果投影:Exit code 143 与超时行,不带中断标记;50ms 向下取整为 0s。
  760. const timeoutResult = await getLatestUpstreamToolResultByToolCallId(
  761. "toolu_e2e_bg39_sleep_timeout",
  762. );
  763. expect(timeoutResult?.isError).toBe(true);
  764. expect(timeoutResult?.content).toBe("Exit code 143\nCommand timed out after 0s");
  765. await waitForV4AssistantMessageContaining("bg39-sleep-hard-timeout-ok");
  766. await browser.pause(500);
  767. expect(
  768. await countUpstreamRequests(
  769. {
  770. includes: [
  771. "<task-notification>",
  772. "<tool-use-id>toolu_e2e_bg39_sleep_timeout</tool-use-id>",
  773. ],
  774. },
  775. { afterIndex: completionIndex },
  776. ),
  777. ).toBe(0);
  778. await waitForNoBackgroundTaskControlRow(
  779. "bash",
  780. "BG39 sleep hard timeout",
  781. "BG39 sleep Bash 不应生成 background control row",
  782. );
  783. await waitForIdle("BG39 foreground timeout 后会话没有回到 idle");
  784. });
  785. it("普通 foreground 长 Bash running 过程中仍显示底部 loading", async function () {
  786. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  787. await rm(BG14_PREVIEW_RELEASE_FILE, { force: true });
  788. await startNewBackgroundDraft();
  789. const prompt =
  790. "E2E_FOREGROUND_LONG_BASH_LOADING: Run a normal foreground Bash command long enough to show loading, then report after completion.";
  791. const requestCountBefore = await getUpstreamRequestRecordCount();
  792. await sendV4PromptAndWaitAccepted(
  793. prompt,
  794. "E2E_FOREGROUND_LONG_BASH_LOADING",
  795. "foreground long Bash loading prompt 没有被 composer 接受",
  796. );
  797. await waitForToolCallBlockByToolCallId("toolu_e2e_foreground_long_bash_loading", 60000);
  798. await respondToBackgroundBlockers();
  799. await waitForMainLoading("普通 foreground 长 Bash running 时应显示底部 loading");
  800. try {
  801. const trigger = await $(
  802. '[data-testid="tool-summary-trigger-toolu_e2e_foreground_long_bash_loading"]',
  803. );
  804. if ((await trigger.getAttribute("aria-expanded")) === "true") await trigger.click();
  805. await browser.waitUntil(
  806. async () => !(await $('[data-testid^="bash-output-preview-"]').isExisting()),
  807. { timeout: 5000, timeoutMsg: "收起的 Bash 不应渲染运行输出" },
  808. );
  809. await trigger.click();
  810. await browser.waitUntil(
  811. async () => {
  812. const preview = await $('[data-testid="bash-output-preview-full"]');
  813. return (
  814. (await preview.isDisplayed()) && (await preview.getText()).includes("progress-line-30")
  815. );
  816. },
  817. { timeout: 10000, timeoutMsg: "Bash 展开预览未显示长文本" },
  818. );
  819. const full = await $('[data-testid="bash-output-preview-full"]');
  820. expect(await full.getText()).toContain("progress-line-30");
  821. expect(await full.getText()).toContain("progress-line-120");
  822. // 共享 renderer 保持预览换行,长输出不能使用单行截断样式。
  823. expect(
  824. await browser.execute(() => {
  825. const node = document.querySelector('[data-testid="bash-output-preview-full"]');
  826. return node instanceof HTMLElement && getComputedStyle(node).whiteSpace === "pre-wrap";
  827. }),
  828. ).toBe(true);
  829. } finally {
  830. await writeFile(BG14_PREVIEW_RELEASE_FILE, "release");
  831. }
  832. const completionIndex = await waitForFirstRequestIndex(
  833. {
  834. includes: ["E2E_FOREGROUND_LONG_BASH_LOADING", "<persisted-output>"],
  835. },
  836. requestCountBefore,
  837. "foreground long Bash 完成后的 tool result 没有进入父模型请求",
  838. );
  839. expect(completionIndex).toBeGreaterThan(requestCountBefore);
  840. await waitForV4AssistantMessageContaining("foreground-long-bash-loading-completed-ok");
  841. await waitForIdle("foreground long Bash 完成后会话没有回到 idle");
  842. expect(await $('[data-testid="bash-output-preview-full"]').isExisting()).toBe(false);
  843. // turn 完成后工具进入已折叠的 assistant history;先按产品入口重新展开历史,再展开工具卡。
  844. await expandToolCallDetails("toolu_e2e_foreground_long_bash_loading");
  845. // 历史展开动画会先挂载节点再显示正文,等待实际输出,前台不再展示文件入口。
  846. const result = await $('[data-testid="bash-result-output"]');
  847. await browser.waitUntil(
  848. async () =>
  849. (await result.isDisplayed()) && (await result.getText()).includes("progress-line-1"),
  850. { timeout: 10000, timeoutMsg: "Bash 终态头部正文未显示" },
  851. );
  852. expect(await $('[data-testid="bash-output-notice"]').isExisting()).toBe(false);
  853. expect(await $('[data-testid="bash-output-file"]').isExisting()).toBe(false);
  854. expect(await result.getText()).not.toContain("E2E_FOREGROUND_LONG_BASH_DONE");
  855. expect(await result.getText()).not.toContain("<persisted-output>");
  856. // provider 保持原有小摘要和完整文件契约,Desktop 仅显示 Bash 的头部正文。
  857. const modelResult = await getLatestUpstreamToolResultByToolCallId(
  858. "toolu_e2e_foreground_long_bash_loading",
  859. );
  860. expect(modelResult?.content).toContain("<persisted-output>");
  861. expect(modelResult?.content).not.toContain("E2E_FOREGROUND_LONG_BASH_DONE");
  862. const outputPath = modelResult?.content.match(/Full output saved to: ([^\n]+)/)?.[1];
  863. if (!outputPath) throw new Error("Bash provider result is missing the retained output path");
  864. const output = await readFile(outputPath, "utf8");
  865. expect(Buffer.byteLength(output)).toBeGreaterThan(30000);
  866. expect(output).toContain("E2E_FOREGROUND_LONG_BASH_DONE");
  867. });
  868. it("background Bash 可以从统一 background control UI 停止", async function () {
  869. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  870. await startNewBackgroundDraft();
  871. const prompt =
  872. "E2E_BACKGROUND_CANCEL_BASH: Start a long background Bash command, wait for it to be stopped, then report the stop notification.";
  873. const requestCountBefore = await getUpstreamRequestRecordCount();
  874. await sendV4PromptAndWaitAccepted(
  875. prompt,
  876. "E2E_BACKGROUND_CANCEL_BASH",
  877. "background Bash cancel prompt 没有被 composer 接受",
  878. );
  879. await waitForToolCallBlockByToolCallId("toolu_e2e_background_cancel_bash", 60000);
  880. await respondToBackgroundBlockers();
  881. const launchIndex = await waitForFirstRequestIndex(
  882. {
  883. includes: ["E2E_BACKGROUND_CANCEL_BASH", "Command running in background"],
  884. },
  885. requestCountBefore,
  886. "background Bash cancel launch tool result 没有进入父模型请求",
  887. );
  888. await openV4ComposerRunningBackgroundWorks();
  889. await waitForBackgroundTaskControlRow(
  890. "bash",
  891. "background cancel bash process tree",
  892. "background Bash 没有出现在统一 background control UI",
  893. );
  894. const [launcherPid, workerPid] = await Promise.all([
  895. waitForRunningPidFile(BG08_LAUNCHER_PID_FILE, "BG08 launcher"),
  896. waitForRunningPidFile(BG08_WORKER_PID_FILE, "BG08 worker"),
  897. ]);
  898. let rootPid: number | null = null;
  899. if (process.platform !== "win32") {
  900. rootPid = await waitForRunningPidFile(BG08_ROOT_PID_FILE, "BG08 root Bash");
  901. const [rootProcessGroupId, launcherProcessGroupId, workerProcessGroupId] = await Promise.all([
  902. readPosixProcessGroupId(rootPid),
  903. readPosixProcessGroupId(launcherPid),
  904. readPosixProcessGroupId(workerPid),
  905. ]);
  906. // Bug 根因:Bash job control 会把 launcher/worker 放入根 shell 之外的 PGID;
  907. // 这里只验证真实构造成功,避免普通同组进程让杀树回归得到假阳性。
  908. expect(launcherProcessGroupId).not.toBe(rootProcessGroupId);
  909. expect(workerProcessGroupId).toBe(launcherProcessGroupId);
  910. }
  911. await clickStopBackgroundTaskControlRow("bash", "background cancel bash process tree");
  912. await waitForV4AssistantMessageContaining("background-cancel-bash-launched-ok");
  913. const notificationIndex = await waitForFirstRequestIndex(
  914. {
  915. includes: [
  916. "E2E_BACKGROUND_CANCEL_BASH",
  917. "<task-notification>",
  918. "<tool-use-id>toolu_e2e_background_cancel_bash</tool-use-id>",
  919. "<status>killed</status>",
  920. ],
  921. lastUserMessageIncludes: ["<task-notification>"],
  922. },
  923. launchIndex,
  924. "background Bash stop notification 没有进入父模型请求",
  925. );
  926. expect(notificationIndex).toBeGreaterThan(launchIndex);
  927. await waitForV4AssistantMessageContaining("background-cancel-bash-stopped-ok");
  928. await waitForNoBackgroundTaskControlRow(
  929. "bash",
  930. "background cancel bash process tree",
  931. "被停止的 background Bash 仍显示为 running",
  932. );
  933. await Promise.all([
  934. rootPid === null ? Promise.resolve() : waitForProcessExit(rootPid, "BG08 root Bash"),
  935. waitForProcessExit(launcherPid, "BG08 launcher"),
  936. waitForProcessExit(workerPid, "BG08 worker"),
  937. ]);
  938. await waitForIdle("background Bash stop notification 后会话没有回到 idle");
  939. await assertNoVisibleTaskNotification();
  940. });
  941. it("background Agent 可以从统一 background control UI 停止", async function () {
  942. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  943. await startNewBackgroundDraft();
  944. const prompt =
  945. "E2E_BACKGROUND_CANCEL_AGENT: Start a long background Agent and stop it from the background control UI.";
  946. const requestCountBefore = await getUpstreamRequestRecordCount();
  947. await sendV4PromptAndWaitAccepted(
  948. prompt,
  949. "E2E_BACKGROUND_CANCEL_AGENT",
  950. "background Agent cancel prompt 没有被 composer 接受",
  951. );
  952. await waitForToolCallBlockByToolCallId("toolu_e2e_background_cancel_agent", 60000);
  953. await respondToBackgroundBlockers();
  954. const launchIndex = await waitForFirstRequestIndex(
  955. {
  956. includes: ["E2E_BACKGROUND_CANCEL_AGENT", "Async agent launched successfully"],
  957. },
  958. requestCountBefore,
  959. "background Agent cancel launch tool result 没有进入父模型请求",
  960. );
  961. await waitForBackgroundTaskControlRow(
  962. "agent",
  963. "E2E background cancel agent",
  964. "background Agent 没有出现在统一 background control UI",
  965. );
  966. await clickStopBackgroundTaskControlRow("agent", "E2E background cancel agent");
  967. await waitForV4AssistantMessageContaining("background-cancel-agent-launched-ok");
  968. const notificationIndex = await waitForFirstRequestIndex(
  969. {
  970. includes: [
  971. "E2E_BACKGROUND_CANCEL_AGENT",
  972. "<task-notification>",
  973. "<tool-use-id>toolu_e2e_background_cancel_agent</tool-use-id>",
  974. // 停止状态词是 killed,summary 写明是用户停止的。
  975. "<status>killed</status>",
  976. "was stopped by user</summary>",
  977. ],
  978. lastUserMessageIncludes: ["<task-notification>"],
  979. },
  980. launchIndex,
  981. "background Agent stop notification 没有进入父模型请求",
  982. );
  983. expect(notificationIndex).toBeGreaterThan(launchIndex);
  984. await waitForV4AssistantMessageContaining("background-cancel-agent-stopped-ok");
  985. await waitForNoBackgroundTaskControlRow(
  986. "agent",
  987. "E2E background cancel agent",
  988. "被停止的 background Agent 仍显示为 running",
  989. );
  990. await waitForIdle("background Agent stop notification 后会话没有回到 idle");
  991. await assertNoVisibleTaskNotification();
  992. });
  993. it("TaskStop tool 停止 background Agent 时复用同一 notification 链路", async function () {
  994. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  995. await startNewBackgroundDraft();
  996. const prompt =
  997. "E2E_BACKGROUND_TASKSTOP_AGENT: Start a background Agent, then use TaskStop on its task id and report after the stop notification.";
  998. const requestCountBefore = await getUpstreamRequestRecordCount();
  999. await sendV4PromptAndWaitAccepted(
  1000. prompt,
  1001. "E2E_BACKGROUND_TASKSTOP_AGENT",
  1002. "TaskStop background Agent prompt 没有被 composer 接受",
  1003. );
  1004. await waitForToolCallBlockByToolCallId("toolu_e2e_background_taskstop_agent", 60000);
  1005. await respondToBackgroundBlockers();
  1006. const taskStopIndex = await waitForFirstRequestIndex(
  1007. {
  1008. includes: [
  1009. "E2E_BACKGROUND_TASKSTOP_AGENT",
  1010. "Async agent launched successfully",
  1011. "agentId: agent_",
  1012. "TaskStop",
  1013. ],
  1014. },
  1015. requestCountBefore,
  1016. "background Agent launch 后父模型没有调用 TaskStop",
  1017. );
  1018. const notificationIndex = await waitForFirstRequestIndex(
  1019. {
  1020. includes: [
  1021. "E2E_BACKGROUND_TASKSTOP_AGENT",
  1022. "Successfully stopped task:",
  1023. "<task-notification>",
  1024. "<tool-use-id>toolu_e2e_background_taskstop_agent</tool-use-id>",
  1025. // 模型用 TaskStop 停止:summary 写明是 ZCode 停止的。
  1026. "<status>killed</status>",
  1027. "was stopped by ZCode</summary>",
  1028. ],
  1029. lastUserMessageIncludes: ["<task-notification>"],
  1030. },
  1031. taskStopIndex,
  1032. "TaskStop 后 background Agent stop notification 没有进入父模型请求",
  1033. );
  1034. expect(notificationIndex).toBeGreaterThan(taskStopIndex);
  1035. await waitForV4AssistantMessageContaining("background-taskstop-agent-stopped-ok");
  1036. await waitForIdle("TaskStop background Agent notification 后会话没有回到 idle");
  1037. await assertNoVisibleTaskNotification();
  1038. });
  1039. it("background notification 会在 active tool-loop 下一轮模型请求前合流", async function () {
  1040. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1041. await startNewBackgroundDraft();
  1042. const prompt =
  1043. "E2E_BACKGROUND_ACTIVE_LOOP_BASH: Start a quick background Bash and keep the tool loop active until it can report completion.";
  1044. const requestCountBefore = await getUpstreamRequestRecordCount();
  1045. await sendV4PromptAndWaitAccepted(
  1046. prompt,
  1047. "E2E_BACKGROUND_ACTIVE_LOOP_BASH",
  1048. "active-loop background Bash prompt 没有被 composer 接受",
  1049. );
  1050. await waitForToolCallBlockByToolCallId("toolu_e2e_background_active_loop_bash_bg", 60000);
  1051. await waitForToolCallBlockByToolCallId("toolu_e2e_background_active_loop_bash_wait", 60000);
  1052. await respondToBackgroundBlockers();
  1053. await respondToBackgroundBlockers();
  1054. const activeLoopIndex = await waitForFirstRequestIndex(
  1055. {
  1056. includes: [
  1057. "E2E_BACKGROUND_ACTIVE_LOOP_BASH",
  1058. "E2E_BACKGROUND_ACTIVE_LOOP_WAIT_DONE",
  1059. "<task-notification>",
  1060. "<tool-use-id>toolu_e2e_background_active_loop_bash_bg</tool-use-id>",
  1061. "<status>completed</status>",
  1062. ],
  1063. lastUserMessageIncludes: ["<task-notification>"],
  1064. },
  1065. requestCountBefore,
  1066. "active-loop 后续模型请求没有同时包含 Bash tool result 和 task-notification",
  1067. );
  1068. expect(activeLoopIndex).toBeGreaterThan(requestCountBefore);
  1069. expect(
  1070. await countUpstreamRequests(
  1071. {
  1072. includes: ["E2E_BACKGROUND_ACTIVE_LOOP_BASH", "toolu_e2e_background_active_loop_bash_bg"],
  1073. lastUserMessageExcludes: ["<task-notification>"],
  1074. },
  1075. { afterIndex: requestCountBefore },
  1076. ),
  1077. ).toBe(0);
  1078. expect(
  1079. await countUpstreamRequests(
  1080. {
  1081. includes: [
  1082. "<task-notification>",
  1083. "<tool-use-id>toolu_e2e_background_active_loop_bash_bg</tool-use-id>",
  1084. ],
  1085. lastUserMessageIncludes: ["<task-notification>"],
  1086. },
  1087. { afterIndex: requestCountBefore },
  1088. ),
  1089. ).toBe(1);
  1090. await waitForV4AssistantMessageContaining("background-active-loop-notification-consumed-ok");
  1091. await waitForIdle("active-loop background notification 后会话没有回到 idle");
  1092. await assertNoVisibleTaskNotification();
  1093. await assertForkAfterBackgroundNotification("background-active-loop-notification-consumed-ok");
  1094. });
  1095. it("goal verifier 会等 background notification 被消费后再验证", async function () {
  1096. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1097. await startNewBackgroundDraft();
  1098. const goal =
  1099. '/goal E2E_BACKGROUND_GOAL: Finish only after consuming the background agent result and then reply with "upstream-e2e-ok".';
  1100. const requestCountBefore = await getUpstreamRequestRecordCount();
  1101. await sendV4Prompt(goal);
  1102. await waitForV4ComposerText("", "background goal /goal 发送后输入框没有清空");
  1103. await waitForV4UserMessageContaining("E2E_BACKGROUND_GOAL");
  1104. await waitForToolCallBlockByToolName("Agent", 60000);
  1105. await respondToBackgroundBlockers();
  1106. const notificationIndex = await waitForFirstRequestIndex(
  1107. {
  1108. includes: ["<task-notification>", "E2E_BACKGROUND_GOAL_CHILD_RESULT"],
  1109. },
  1110. requestCountBefore,
  1111. "goal background Agent completion notification 没有进入父模型请求",
  1112. );
  1113. await waitForV4AssistantMessageContaining("E2E_BACKGROUND_GOAL_NOTIFICATION_CONSUMED");
  1114. const verifierIndex = await waitForFirstRequestIndex(
  1115. {
  1116. includes: ["E2E_BACKGROUND_GOAL", "Verify whether the active session goal"],
  1117. },
  1118. notificationIndex,
  1119. "background notification 后没有触发 goal verifier",
  1120. );
  1121. expect(verifierIndex).toBeGreaterThan(notificationIndex);
  1122. expect(
  1123. await countUpstreamRequests(
  1124. {
  1125. includes: ["E2E_BACKGROUND_GOAL", "Verify whether the active session goal"],
  1126. },
  1127. { beforeIndex: notificationIndex },
  1128. ),
  1129. ).toBe(0);
  1130. await waitForV4ConversationState(
  1131. // Bug 根因:旧聊天根节点把已验证目标投影为 complete,V4 状态面板使用
  1132. // verified 表达同一终态;转正用例必须兼容两套展示契约。
  1133. (snapshot) => snapshot.targetStatus === "complete" || snapshot.targetStatus === "verified",
  1134. "background goal verifier 没有把 target 标记为 complete/verified",
  1135. 90000,
  1136. );
  1137. await assertNoVisibleTaskNotification();
  1138. });
  1139. it("running background Agent 可以通过 SendMessage 收到 steer 消息", async function () {
  1140. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1141. await startNewBackgroundDraft();
  1142. const prompt =
  1143. "E2E_BACKGROUND_SEND_MESSAGE: Launch a background agent, then send it a coordinator message while it is still running.";
  1144. const requestCountBefore = await getUpstreamRequestRecordCount();
  1145. await sendV4Prompt(prompt);
  1146. await waitForV4ComposerText("", "background SendMessage prompt 发送后输入框没有清空");
  1147. await waitForV4UserMessageContaining("E2E_BACKGROUND_SEND_MESSAGE");
  1148. await waitForToolCallBlockByToolName("Agent", 60000);
  1149. await respondToBackgroundBlockers();
  1150. // child prompt 不写出 payload:child 只收到 message,payload 在 child 请求里只能出现一次。
  1151. const sendMessageIndex = await waitForFirstRequestIndex(
  1152. {
  1153. includes: [
  1154. "E2E_BACKGROUND_SEND_MESSAGE",
  1155. "Async agent launched successfully",
  1156. "agentId: agent_",
  1157. ],
  1158. excludes: ["sent to its active turn"],
  1159. },
  1160. requestCountBefore,
  1161. "background Agent launch 后父模型没有调用 SendMessage",
  1162. );
  1163. const sendMessageResultIndex = await waitForFirstRequestIndex(
  1164. {
  1165. includes: [
  1166. "E2E_BACKGROUND_SEND_MESSAGE",
  1167. "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1168. "sent to its active turn",
  1169. ],
  1170. },
  1171. sendMessageIndex,
  1172. "background Agent SendMessage tool result 没有进入父模型请求",
  1173. );
  1174. const coordinatorQuery = {
  1175. includes: ["E2E_BACKGROUND_SEND_MESSAGE_CHILD_BASH_DONE"],
  1176. lastUserMessageIncludes: [
  1177. "The coordinator sent a message while you were working:",
  1178. "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1179. ],
  1180. };
  1181. // 验收真实 wire;旧 debug 文件同时检查请求和响应且依赖 retention,不是稳定的 provider 合同。
  1182. await waitForFirstRequestIndex(
  1183. coordinatorQuery,
  1184. requestCountBefore - 1,
  1185. "running child 没有收到 coordinator 提示",
  1186. );
  1187. const coordinatorEvidence = await getUpstreamRequestEvidence(coordinatorQuery, {
  1188. afterIndex: requestCountBefore - 1,
  1189. });
  1190. await assertIncomingMessage(coordinatorEvidence[0]!.requestJson, {
  1191. presentation: "coordinator_steer",
  1192. marker: "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1193. role: "user",
  1194. // summary 只用于 UI 预览,child 只收到 message。
  1195. body: "E2E_BACKGROUND_SEND_MESSAGE_PAYLOAD",
  1196. });
  1197. const notificationIndex = await waitForFirstRequestIndex(
  1198. {
  1199. includes: ["<task-notification>", "E2E_BACKGROUND_SEND_MESSAGE_CHILD_RECEIVED"],
  1200. },
  1201. sendMessageResultIndex,
  1202. "SendMessage 后 background Agent completion notification 没有进入父模型请求",
  1203. );
  1204. expect(sendMessageIndex).toBeGreaterThan(requestCountBefore);
  1205. expect(sendMessageResultIndex).toBeGreaterThan(sendMessageIndex);
  1206. expect(notificationIndex).toBeGreaterThan(sendMessageResultIndex);
  1207. await waitForIdle("background SendMessage notification 后会话没有回到 idle");
  1208. await assertNoVisibleTaskNotification();
  1209. });
  1210. it("foreground subagent 运行 child tool 时 main 仍会显示底部 loading", async function () {
  1211. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1212. await startNewBackgroundDraft();
  1213. const capture = await beginBackgroundTelemetryCapture();
  1214. const prompt =
  1215. "E2E_FOREGROUND_AGENT_CHILD_TOOL_STREAMING_STATUS: Launch a foreground agent that runs a visible child Bash tool while the parent conversation is still running.";
  1216. const requestCountBefore = await getUpstreamRequestRecordCount();
  1217. await sendV4Prompt(prompt);
  1218. await waitForV4ComposerText("", "foreground child tool streaming prompt 发送后输入框没有清空");
  1219. await waitForV4UserMessageContaining("E2E_FOREGROUND_AGENT_CHILD_TOOL_STREAMING_STATUS");
  1220. await waitForToolCallBlockByToolCallId("toolu_e2e_foreground_child_tool_agent", 60000);
  1221. await respondToBackgroundBlockers();
  1222. // Bug 根因:V4 明确把 child tool history 留在 child conversation topic,
  1223. // 父 timeline 只保留 Agent 事实;main loading 应由前台父 Agent 生命周期维持。
  1224. await waitForMainLoading("foreground subagent 运行 child tool 时应保持 main 底部 loading");
  1225. await assertNoMainToolCallById(
  1226. "toolu_e2e_foreground_child_tool_bash",
  1227. "foreground child Bash 不应被镜像成 main timeline tool row",
  1228. );
  1229. const completionIndex = await waitForFirstRequestIndex(
  1230. {
  1231. includes: [
  1232. "E2E_FOREGROUND_AGENT_CHILD_TOOL_STREAMING_STATUS",
  1233. "E2E_FOREGROUND_AGENT_CHILD_TOOL_DONE",
  1234. ],
  1235. },
  1236. requestCountBefore,
  1237. "foreground child tool Agent completion 没有进入父模型请求",
  1238. );
  1239. expect(completionIndex).toBeGreaterThan(requestCountBefore);
  1240. await waitForV4AssistantMessageContaining("foreground-agent-child-tool-streaming-completed-ok");
  1241. await waitForIdle("foreground child tool Agent completion 后会话没有回到 idle");
  1242. const reports = await waitForConversationReportDelta(capture, {
  1243. agent_step: 1,
  1244. message_completion: 1,
  1245. });
  1246. assertMainCompletionAgentCompositions(reports, ["main_plus_fg"]);
  1247. assertMainCompletionMessageSources(reports, ["chat"]);
  1248. });
  1249. it("同一 main turn 同时消费 foreground 和 background subagent 结果", async function () {
  1250. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1251. await startNewBackgroundDraft();
  1252. await rm(BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE, { force: true });
  1253. const capture = await beginBackgroundTelemetryCapture();
  1254. const prompt =
  1255. "E2E_AGENT_COMPOSITION_MIXED: Launch one foreground Agent and one background Agent, then summarize both results.";
  1256. const requestCountBefore = await getUpstreamRequestRecordCount();
  1257. try {
  1258. await sendV4Prompt(prompt);
  1259. await waitForV4ComposerText("", "mixed agent composition prompt 发送后输入框没有清空");
  1260. await waitForV4UserMessageContaining("E2E_AGENT_COMPOSITION_MIXED");
  1261. await waitForToolCallBlockByToolCallId("toolu_e2e_composition_mixed_foreground", 60000);
  1262. await waitForToolCallBlockByToolCallId("toolu_e2e_composition_mixed_background", 60000);
  1263. await browser.waitUntil(
  1264. async () => {
  1265. const evidence = await getUpstreamRequestEvidence(
  1266. {
  1267. lastUserMessageIncludes: ["E2E_AGENT_COMPOSITION_MIXED_FOREGROUND_CHILD"],
  1268. },
  1269. { afterIndex: requestCountBefore },
  1270. );
  1271. return evidence.some(
  1272. (record) =>
  1273. record.fixtureId === "upstream-agent-composition-mixed-foreground-child" &&
  1274. record.status === "complete",
  1275. );
  1276. },
  1277. {
  1278. timeout: 45000,
  1279. timeoutMsg: "mixed agent composition foreground child 没有进入 Bash barrier",
  1280. },
  1281. );
  1282. await respondToBackgroundBlockers();
  1283. await browser.waitUntil(
  1284. async () => {
  1285. const evidence = await getUpstreamRequestEvidence(
  1286. {
  1287. lastUserMessageIncludes: ["E2E_AGENT_COMPOSITION_MIXED_BACKGROUND_CHILD"],
  1288. },
  1289. { afterIndex: requestCountBefore },
  1290. );
  1291. return evidence.some(
  1292. (record) =>
  1293. record.fixtureId === "upstream-agent-composition-mixed-background-child" &&
  1294. record.status === "complete",
  1295. );
  1296. },
  1297. {
  1298. timeout: 45000,
  1299. timeoutMsg: "mixed agent composition background child 没有完成 provider response",
  1300. },
  1301. );
  1302. await writeFile(BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE, "release\n", "utf-8");
  1303. const mixedRequestIndex = await waitForFirstRequestIndex(
  1304. {
  1305. includes: [
  1306. "E2E_AGENT_COMPOSITION_MIXED_FOREGROUND_DONE",
  1307. "E2E_AGENT_COMPOSITION_MIXED_BACKGROUND_DONE",
  1308. "<task-notification>",
  1309. ],
  1310. lastUserMessageIncludes: [
  1311. "<task-notification>",
  1312. "E2E_AGENT_COMPOSITION_MIXED_FOREGROUND_DONE",
  1313. ],
  1314. },
  1315. requestCountBefore,
  1316. "mixed agent composition 没有在同一 main request 消费 foreground 和 background 结果",
  1317. );
  1318. expect(mixedRequestIndex).toBeGreaterThan(requestCountBefore);
  1319. await waitForV4AssistantMessageContaining("agent-composition-mixed-completed-ok");
  1320. await waitForIdle("mixed agent composition 收口后会话没有回到 idle");
  1321. const reports = await waitForConversationReportDelta(capture, {
  1322. agent_step: 1,
  1323. message_completion: 1,
  1324. });
  1325. assertMainCompletionAgentCompositions(reports, ["main_plus_fg_bg"]);
  1326. assertMainCompletionMessageSources(reports, ["chat"]);
  1327. } finally {
  1328. await writeFile(BACKGROUND_MIXED_FOREGROUND_RELEASE_FILE, "release\n", "utf-8").catch(
  1329. () => undefined,
  1330. );
  1331. }
  1332. });
  1333. it("background subagent 的 child tool 只留在 child conversation,idle main 不显示底部 loading", async function () {
  1334. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1335. await startNewBackgroundDraft();
  1336. const capture = await beginBackgroundTelemetryCapture();
  1337. await rm(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, { force: true });
  1338. const prompt =
  1339. "E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_STATUS: Launch a background agent that runs a visible child Bash tool while the parent conversation is idle.";
  1340. const requestCountBefore = await getUpstreamRequestRecordCount();
  1341. await sendV4Prompt(prompt);
  1342. await waitForV4ComposerText("", "background child tool idle prompt 发送后输入框没有清空");
  1343. await waitForV4UserMessageContaining("E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_STATUS");
  1344. await waitForToolCallBlockByToolCallId("toolu_e2e_background_idle_child_tool_agent", 60000);
  1345. await respondToBackgroundBlockers();
  1346. const launchIndex = await waitForFirstRequestIndex(
  1347. {
  1348. includes: [
  1349. "E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_STATUS",
  1350. "Async agent launched successfully",
  1351. ],
  1352. },
  1353. requestCountBefore,
  1354. "background child tool idle Agent launch tool result 没有进入父模型请求",
  1355. );
  1356. await waitForV4AssistantMessageContaining("background-agent-child-tool-idle-launched-ok");
  1357. await waitForIdle("background child tool idle launch 后父会话没有先回到 idle");
  1358. await waitForBackgroundTaskControlRow(
  1359. "agent",
  1360. "E2E background child tool idle",
  1361. "background child tool idle Agent 没有出现在统一 background control UI",
  1362. );
  1363. await assertNoMainToolCallById(
  1364. "toolu_e2e_background_idle_child_tool_bash",
  1365. "background child Bash 不应被镜像成 main timeline tool row",
  1366. );
  1367. await assertNoMainFakeLoading(
  1368. "background subagent child tool update 不应让 idle main 显示底部 loading",
  1369. );
  1370. await writeFile(BACKGROUND_CHILD_TOOL_IDLE_RELEASE_FILE, "release\n", "utf-8");
  1371. const notificationIndex = await waitForFirstRequestIndex(
  1372. {
  1373. includes: ["<task-notification>", "E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_DONE"],
  1374. lastUserMessageIncludes: ["<task-notification>"],
  1375. },
  1376. launchIndex,
  1377. "background child tool idle Agent completion notification 没有进入父模型请求",
  1378. );
  1379. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1380. await waitForV4AssistantMessageContaining(
  1381. "background-agent-child-tool-idle-notification-consumed-ok",
  1382. );
  1383. await waitForIdle("background child tool idle notification 后会话没有回到 idle");
  1384. const { eventReport: reports } = await checkpointConversationTelemetryCase(capture, {
  1385. caseId: "BG13-token-identity",
  1386. minimumReportInventory: { agent_step: 1, message_completion: 2 },
  1387. minimumArmsInventory: {},
  1388. proof: ["child Bash + Agent usage owner", "new UUID v7 wake message"],
  1389. });
  1390. assertBackgroundToolStepTelemetry(reports, "toolu_e2e_background_idle_child_tool_bash");
  1391. assertMainCompletionAgentCompositions(reports, ["main_only", "main_plus_bg"]);
  1392. assertMainCompletionMessageSources(reports, ["chat", "background_subagent"]);
  1393. await assertNoVisibleTaskNotification();
  1394. });
  1395. it("background subagent 的 child tool 不污染后续主回复且原 Agent 控制身份稳定", async function () {
  1396. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1397. await startNewBackgroundDraft();
  1398. const capture = await beginBackgroundTelemetryCapture();
  1399. const prompt =
  1400. "E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR: Launch a background agent whose child tool update arrives after my next main prompt has completed.";
  1401. const followUpPrompt =
  1402. "E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP: This main prompt should complete before the background child Bash update arrives.";
  1403. const requestCountBefore = await getUpstreamRequestRecordCount();
  1404. await rm(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, { force: true });
  1405. await sendV4Prompt(prompt);
  1406. await waitForV4ComposerText("", "background parent anchor prompt 发送后输入框没有清空");
  1407. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR");
  1408. await waitForToolCallBlockByToolCallId("toolu_e2e_background_parent_anchor_agent", 60000);
  1409. await respondToBackgroundBlockers();
  1410. const launchIndex = await waitForFirstRequestIndex(
  1411. {
  1412. includes: ["E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR", "Async agent launched successfully"],
  1413. },
  1414. requestCountBefore,
  1415. "background parent anchor Agent launch tool result 没有进入父模型请求",
  1416. );
  1417. await waitForV4AssistantMessageContaining("background-child-tool-parent-anchor-launched-ok");
  1418. await waitForIdle("background parent anchor launch 后父会话没有先回到 idle");
  1419. await waitForBackgroundTaskControlRow(
  1420. "agent",
  1421. "E2E background child tool parent anchor",
  1422. "background parent anchor Agent 没有出现在统一 background control UI",
  1423. );
  1424. await sendV4Prompt(followUpPrompt);
  1425. await waitForV4ComposerText("", "background parent anchor follow-up 发送后输入框没有清空");
  1426. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP");
  1427. const followUpIndex = await waitForFirstRequestIndex(
  1428. {
  1429. includes: ["E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP"],
  1430. lastUserMessageIncludes: ["E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_FOLLOWUP"],
  1431. },
  1432. launchIndex,
  1433. "background parent anchor follow-up 没有立即进入 provider request",
  1434. );
  1435. expect(followUpIndex).toBeGreaterThan(launchIndex);
  1436. await waitForV4AssistantMessageContaining(
  1437. "background-child-tool-parent-anchor-main-followup-ok",
  1438. );
  1439. await waitForBackgroundTaskControlRow(
  1440. "agent",
  1441. "E2E background child tool parent anchor",
  1442. "background child tool 到达后原 Agent 控制身份没有保持",
  1443. );
  1444. await assertNoMainToolCallById(
  1445. "toolu_e2e_background_parent_anchor_child_bash",
  1446. "background child Bash 不应污染后续 main timeline",
  1447. );
  1448. await writeFile(BACKGROUND_PARENT_ANCHOR_RELEASE_FILE, "release\n", "utf-8");
  1449. await respondToBackgroundBlockers();
  1450. const notificationIndex = await waitForFirstRequestIndex(
  1451. {
  1452. includes: ["<task-notification>", "E2E_BACKGROUND_CHILD_TOOL_PARENT_ANCHOR_CHILD_DONE"],
  1453. lastUserMessageIncludes: ["<task-notification>"],
  1454. },
  1455. followUpIndex,
  1456. "background parent anchor Agent completion notification 没有进入父模型请求",
  1457. );
  1458. expect(notificationIndex).toBeGreaterThan(followUpIndex);
  1459. await waitForV4AssistantMessageContaining(
  1460. "background-child-tool-parent-anchor-notification-consumed-ok",
  1461. );
  1462. await waitForIdle("background parent anchor notification 后会话没有回到 idle");
  1463. const { eventReport: reports } = await checkpointConversationTelemetryCase(capture, {
  1464. caseId: "BG18-token-identity",
  1465. minimumReportInventory: { agent_step: 1, message_completion: 3 },
  1466. minimumArmsInventory: {},
  1467. proof: [
  1468. "child usage retains original launch identity after follow-up",
  1469. "new UUID v7 wake message",
  1470. ],
  1471. });
  1472. assertBackgroundToolStepTelemetry(reports, "toolu_e2e_background_parent_anchor_child_bash");
  1473. assertMainCompletionAgentCompositions(reports, ["main_only", "main_only", "main_plus_bg"]);
  1474. assertMainCompletionMessageSources(reports, ["chat", "chat", "background_subagent"]);
  1475. await assertNoVisibleTaskNotification();
  1476. });
  1477. it("切换 session 期间完成的 background subagent 切回后应保留父 Agent 描述并收口", async function () {
  1478. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1479. await startNewBackgroundDraft();
  1480. const prompt =
  1481. "E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH: Launch a background agent whose child Bash completes while I am viewing another session.";
  1482. const requestCountBefore = await getUpstreamRequestRecordCount();
  1483. await rm(BG21_RELEASE_FILE, { force: true });
  1484. await sendV4Prompt(prompt);
  1485. await waitForV4ComposerText("", "background session switch prompt 发送后输入框没有清空");
  1486. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH");
  1487. await waitForToolCallBlockByToolCallId("toolu_e2e_background_session_switch_agent", 60000);
  1488. await respondToBackgroundBlockers();
  1489. const launchIndex = await waitForFirstRequestIndex(
  1490. {
  1491. includes: ["E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH", "Async agent launched successfully"],
  1492. },
  1493. requestCountBefore,
  1494. "background session switch Agent launch tool result 没有进入父模型请求",
  1495. );
  1496. await waitForV4AssistantMessageContaining("background-session-switch-launched-ok");
  1497. const sessionSwitchSnapshot = await waitForIdle(
  1498. "background session switch launch 后父会话没有先回到 idle",
  1499. );
  1500. const sourceTaskId = sessionSwitchSnapshot.taskId;
  1501. if (!sourceTaskId) {
  1502. throw new Error(
  1503. `background session switch 缺少 source taskId: ${JSON.stringify(sessionSwitchSnapshot)}`,
  1504. );
  1505. }
  1506. await waitForBackgroundTaskControlRow(
  1507. "agent",
  1508. "E2E background session switch child tool",
  1509. "background session switch Agent 没有出现在统一 background control UI",
  1510. );
  1511. await assertNoMainToolCallById(
  1512. "toolu_e2e_background_session_switch_child_bash",
  1513. "background session switch child Bash 不应进入 main timeline",
  1514. );
  1515. await startNewBackgroundDraft();
  1516. await waitForV4ConversationState(
  1517. (snapshot) => snapshot.taskId === null && snapshot.sessionId === null,
  1518. "background session switch 没有切到新草稿 task",
  1519. 30000,
  1520. );
  1521. await writeFile(BG21_RELEASE_FILE, "release\n", "utf-8");
  1522. const notificationIndex = await waitForFirstRequestIndex(
  1523. {
  1524. includes: ["<task-notification>", "E2E_BACKGROUND_CHILD_TOOL_SESSION_SWITCH_CHILD_DONE"],
  1525. lastUserMessageIncludes: ["<task-notification>"],
  1526. },
  1527. launchIndex,
  1528. "background session switch Agent completion notification 没有进入父模型请求",
  1529. );
  1530. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1531. await selectV4TaskById(sourceTaskId);
  1532. await waitForV4ConversationState(
  1533. (snapshot) => snapshot.taskId === sourceTaskId,
  1534. "background session switch 切回原 task 后 chat root 没有恢复到原 task",
  1535. 30000,
  1536. );
  1537. await waitForV4AssistantMessageContaining("background-session-switch-notification-consumed-ok");
  1538. await waitForIdle("background session switch notification 后会话没有回到 idle");
  1539. await waitForNoBackgroundTaskControlRow(
  1540. "agent",
  1541. "E2E background session switch child tool",
  1542. "background session switch 切回后父 Agent control 没有收口",
  1543. );
  1544. // Bug 根因:V4 终态 Agent 事实由 timeline/subagent row 承载,不再写回 legacy
  1545. // renderer ToolCallBlock;切回后的收口应验证当前 V4 timeline 与 control 消失。
  1546. await waitForV4TimelineContaining("E2E background session switch child tool", 60000);
  1547. expect((await getV4PaneSnapshot()).timelineText).not.toContain("Unknown");
  1548. await assertNoMainToolCallById(
  1549. "toolu_e2e_background_session_switch_child_bash",
  1550. "background session switch 切回后不应把 child Bash 复活成 main row",
  1551. );
  1552. await assertNoVisibleTaskNotification();
  1553. });
  1554. it("切回 session 时 background subagent 仍 running,后续应继续收口父 Agent 状态", async function () {
  1555. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1556. await startNewBackgroundDraft();
  1557. const prompt =
  1558. "E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING: Launch a background agent whose child Bash is still running when I switch back.";
  1559. const requestCountBefore = await getUpstreamRequestRecordCount();
  1560. await rm(BACKGROUND_SWITCH_BACK_RELEASE_FILE, { force: true });
  1561. await sendV4Prompt(prompt);
  1562. await waitForV4ComposerText("", "background switch-back-running prompt 发送后输入框没有清空");
  1563. await waitForV4UserMessageContaining("E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING");
  1564. await waitForToolCallBlockByToolCallId("toolu_e2e_background_switch_back_running_agent", 60000);
  1565. await respondToBackgroundBlockers();
  1566. const launchIndex = await waitForFirstRequestIndex(
  1567. {
  1568. includes: [
  1569. "E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING",
  1570. "Async agent launched successfully",
  1571. ],
  1572. },
  1573. requestCountBefore,
  1574. "background switch-back-running Agent launch tool result 没有进入父模型请求",
  1575. );
  1576. await waitForV4AssistantMessageContaining("background-switch-back-running-launched-ok");
  1577. const sourceSnapshot = await waitForIdle(
  1578. "background switch-back-running launch 后父会话没有先回到 idle",
  1579. );
  1580. const sourceTaskId = sourceSnapshot.taskId;
  1581. if (!sourceTaskId) {
  1582. throw new Error(
  1583. `background switch-back-running 缺少 source taskId: ${JSON.stringify(sourceSnapshot)}`,
  1584. );
  1585. }
  1586. await waitForBackgroundTaskControlRow(
  1587. "agent",
  1588. "E2E background switch back running child tool",
  1589. "background switch-back-running Agent 没有出现在统一 background control UI",
  1590. );
  1591. await assertNoMainToolCallById(
  1592. "toolu_e2e_background_switch_back_running_child_bash",
  1593. "background switch-back-running child Bash 不应进入 main timeline",
  1594. );
  1595. await startNewBackgroundDraft();
  1596. await waitForV4ConversationState(
  1597. (snapshot) => snapshot.taskId === null && snapshot.sessionId === null,
  1598. "background switch-back-running 没有切到新草稿 task",
  1599. 30000,
  1600. );
  1601. await selectV4TaskById(sourceTaskId);
  1602. await waitForV4ConversationState(
  1603. (snapshot) => snapshot.taskId === sourceTaskId,
  1604. "background switch-back-running 切回原 task 后 chat root 没有恢复到原 task",
  1605. 30000,
  1606. );
  1607. await waitForBackgroundTaskControlRow(
  1608. "agent",
  1609. "E2E background switch back running child tool",
  1610. "background switch-back-running 切回后父 Agent running control 没有恢复",
  1611. );
  1612. await assertNoMainToolCallById(
  1613. "toolu_e2e_background_switch_back_running_child_bash",
  1614. "background switch-back-running 切回后不应把 child Bash 投影到 main timeline",
  1615. );
  1616. await writeFile(BACKGROUND_SWITCH_BACK_RELEASE_FILE, "release\n", "utf-8");
  1617. const notificationIndex = await waitForFirstRequestIndex(
  1618. {
  1619. includes: [
  1620. "<task-notification>",
  1621. "E2E_BACKGROUND_CHILD_TOOL_SWITCH_BACK_RUNNING_CHILD_DONE",
  1622. ],
  1623. lastUserMessageIncludes: ["<task-notification>"],
  1624. },
  1625. launchIndex,
  1626. "background switch-back-running Agent completion notification 没有进入父模型请求",
  1627. );
  1628. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1629. await waitForV4AssistantMessageContaining(
  1630. "background-switch-back-running-notification-consumed-ok",
  1631. );
  1632. await waitForIdle("background switch-back-running notification 后会话没有回到 idle");
  1633. await waitForNoBackgroundTaskControlRow(
  1634. "agent",
  1635. "E2E background switch back running child tool",
  1636. "background switch-back-running 完成后父 Agent control 没有收口",
  1637. );
  1638. await waitForV4TimelineContaining("E2E background switch back running child tool", 60000);
  1639. expect((await getV4PaneSnapshot()).timelineText).not.toContain("Unknown");
  1640. await assertNoMainToolCallById(
  1641. "toolu_e2e_background_switch_back_running_child_bash",
  1642. "background switch-back-running 完成后不应把 child Bash 复活成 main row",
  1643. );
  1644. await assertNoVisibleTaskNotification();
  1645. });
  1646. it("background-only running 时点击 queued prompt 立即发送不应 stop background task", async function () {
  1647. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1648. await startNewBackgroundDraft();
  1649. const prompt =
  1650. "E2E_BACKGROUND_SEND_NOW_QUEUE: Launch a background agent with a visible child Bash tool, then wait.";
  1651. const queuedPrompt =
  1652. "E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD: This queued prompt should send now without stopping the background agent.";
  1653. const holdPrompt =
  1654. 'E2E_HOLD_STREAM E2E_BACKGROUND_SEND_NOW_QUEUE_HOLD: Reply with exactly "upstream-e2e-ok" and no other text.';
  1655. const requestCountBefore = await getUpstreamRequestRecordCount();
  1656. await sendV4Prompt(prompt);
  1657. await waitForV4ComposerText("", "background send-now queue prompt 发送后输入框没有清空");
  1658. await waitForV4UserMessageContaining("E2E_BACKGROUND_SEND_NOW_QUEUE");
  1659. await waitForToolCallBlockByToolCallId("toolu_e2e_background_send_now_queue_agent", 60000);
  1660. await respondToBackgroundBlockers();
  1661. const launchIndex = await waitForFirstRequestIndex(
  1662. {
  1663. includes: ["E2E_BACKGROUND_SEND_NOW_QUEUE", "Async agent launched successfully"],
  1664. },
  1665. requestCountBefore,
  1666. "background send-now queue Agent launch tool result 没有进入父模型请求",
  1667. );
  1668. await waitForV4AssistantMessageContaining("background-send-now-queue-launched-ok");
  1669. await waitForIdle("background send-now queue launch 后父会话没有先回到 idle");
  1670. await waitForBackgroundTaskControlRow(
  1671. "agent",
  1672. "E2E background send now queue",
  1673. "background send-now queue Agent 没有保持 running control",
  1674. );
  1675. await assertNoMainToolCallById(
  1676. "toolu_e2e_background_send_now_queue_child_bash",
  1677. "background send-now queue child Bash 不应进入 main timeline",
  1678. );
  1679. await assertNoMainFakeLoading(
  1680. "background send-now queue child tool update 不应让 idle main 显示底部 loading",
  1681. );
  1682. // Bug 根因:旧 case 直接调用已删除的 renderer store enqueue API,构造的是
  1683. // 产品 UI 无法到达的状态。现在先启动可停止的主 turn、真实排队,再 stop 进入
  1684. // idle + paused queue;background Agent 仍 running,随后从队列点击“立即”。
  1685. await sendV4Prompt(holdPrompt);
  1686. await waitForV4ComposerText("", "background send-now hold prompt 发送后输入框没有清空");
  1687. await waitForV4UserMessageContaining("E2E_BACKGROUND_SEND_NOW_QUEUE_HOLD");
  1688. await waitForV4ConversationState(
  1689. (snapshot) => snapshot.state === "streaming",
  1690. "background send-now hold prompt 没有进入 streaming",
  1691. 30000,
  1692. );
  1693. await sendV4Prompt(queuedPrompt);
  1694. await waitForV4ComposerText("", "background send-now queued prompt 没有清空");
  1695. const queuedBeforeSendNow = await waitForQueueOrderContaining(
  1696. ["E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD"],
  1697. "background-only running send-now 点击前没有形成 queued prompt",
  1698. );
  1699. expect(queuedBeforeSendNow[0]?.kind).toBe("text");
  1700. await clickV4Stop();
  1701. await waitForV4ConversationState(
  1702. (snapshot) =>
  1703. snapshot.state !== "streaming" && !snapshot.stopRequested && snapshot.queueCount === 1,
  1704. "background send-now stop 后没有进入 background-only + paused queue",
  1705. 30000,
  1706. );
  1707. await waitForBackgroundTaskControlRow(
  1708. "agent",
  1709. "E2E background send now queue",
  1710. "background send-now stop main turn 后误停了 background Agent",
  1711. );
  1712. const sentNowItem = await clickFirstQueueSendNow();
  1713. expect(sentNowItem.content).toContain("E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD");
  1714. await browser.pause(80);
  1715. const afterClickSnapshot = await getV4ConversationState();
  1716. expect(afterClickSnapshot.stopRequested).toBe(false);
  1717. const queuedPromptIndex = await waitForFirstRequestIndex(
  1718. {
  1719. includes: ["E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD"],
  1720. lastUserMessageIncludes: ["E2E_BACKGROUND_SEND_NOW_QUEUE_PAYLOAD"],
  1721. },
  1722. launchIndex,
  1723. "background-only running 下 queued prompt 点击立即发送后没有直接进入 provider request",
  1724. );
  1725. expect(queuedPromptIndex).toBeGreaterThan(launchIndex);
  1726. await waitForV4AssistantMessageContaining("background-send-now-queue-received-ok");
  1727. // Bug 根因:固定 sleep 窗口在 25 条全量回放负载下可能先于 UI 断言结束,
  1728. // 让用例偶发看不到 running control。点击“立即”完成后再释放 child,才能
  1729. // 确保测试窗口由交互事件决定,而不是依赖机器速度。
  1730. await writeFile(BACKGROUND_SEND_NOW_QUEUE_RELEASE_FILE, "release\n", "utf-8");
  1731. const notificationIndex = await waitForFirstRequestIndex(
  1732. {
  1733. includes: ["<task-notification>", "E2E_BACKGROUND_SEND_NOW_QUEUE_CHILD_DONE"],
  1734. lastUserMessageIncludes: ["<task-notification>"],
  1735. },
  1736. queuedPromptIndex,
  1737. "background send-now queue Agent completion notification 没有进入父模型请求",
  1738. );
  1739. expect(notificationIndex).toBeGreaterThan(queuedPromptIndex);
  1740. await waitForV4AssistantMessageContaining("background-send-now-queue-notification-consumed-ok");
  1741. await waitForIdle("background send-now queue notification 后会话没有回到 idle");
  1742. await assertNoVisibleTaskNotification();
  1743. });
  1744. it("main turn 启动 background task 后结束时会继续 drain 已有 queue,后续 queued prompt 不丢失", async function () {
  1745. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1746. await startNewBackgroundDraft();
  1747. const backgroundLaunchPrompt =
  1748. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END: Start a background agent, but let me queue follow-up messages while this main turn is still running.";
  1749. const queuedPromptTwo =
  1750. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2: Q2 should queue while the background launch turn is still active.";
  1751. const queuedPromptThree =
  1752. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3: Q3 should queue behind Q2 while the background launch turn is still active.";
  1753. const queuedPromptFour =
  1754. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4: Q4 should queue behind Q3 while the background launch turn is still active.";
  1755. const requestCountBefore = await getUpstreamRequestRecordCount();
  1756. // Bug 根因:capture 的 afterIndex 使用最后一个数组下标;启动前记录数直接传入
  1757. // 会漏掉本轮恰好落在 index=requestCountBefore 的首条请求,导致后续 queue drain
  1758. // 证明在真实请求已完成时仍被报告为未命中。
  1759. const lastRequestIndexBefore = requestCountBefore - 1;
  1760. await sendV4Prompt(backgroundLaunchPrompt);
  1761. await waitForV4ComposerText("", "background queue drain launch prompt 发送后输入框没有清空");
  1762. await waitForV4UserMessageContaining("E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END");
  1763. const backgroundPromptIndex = await waitForFirstRequestIndex(
  1764. {
  1765. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END"],
  1766. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END"],
  1767. },
  1768. lastRequestIndexBefore,
  1769. "background launch prompt 没有进入 provider request",
  1770. );
  1771. await waitForToolCallBlockByToolCallId("toolu_e2e_background_queue_drain_agent", 60000);
  1772. await respondToBackgroundBlockers();
  1773. await waitForBackgroundTaskControlRow(
  1774. "agent",
  1775. "E2E background queue drain agent",
  1776. "background queue drain Agent 没有出现在统一 background control UI",
  1777. );
  1778. await waitForV4ConversationState(
  1779. (snapshot) => snapshot.state === "streaming",
  1780. "background queue drain launch ack delay 期间 main 没有保持 running",
  1781. 30000,
  1782. );
  1783. await sendV4Prompt(queuedPromptTwo);
  1784. await waitForV4ComposerText("", "background queue drain Q2 入队后输入框没有清空");
  1785. await waitForQueueOrderContaining(
  1786. ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1787. "background Agent running 且 launch ack 未结束时 Q2 没有进入 queue",
  1788. );
  1789. await sendV4Prompt(queuedPromptThree);
  1790. await waitForV4ComposerText("", "background queue drain Q3 入队后输入框没有清空");
  1791. await waitForQueueOrderContaining(
  1792. [
  1793. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1794. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1795. ],
  1796. "background Agent running 且 launch ack 未结束时 Q2/Q3 queue 顺序不正确",
  1797. );
  1798. await sendV4Prompt(queuedPromptFour);
  1799. await waitForV4ComposerText("", "background queue drain Q4 入队后输入框没有清空");
  1800. await waitForQueueOrderContaining(
  1801. [
  1802. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1803. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1804. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1805. ],
  1806. "background Agent running 且 launch ack 未结束时 Q2/Q3/Q4 queue 顺序不正确",
  1807. );
  1808. await startVisibleUserMessageSampler();
  1809. const launchIndex = await waitForFirstRequestIndex(
  1810. {
  1811. includes: [
  1812. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END",
  1813. "Async agent launched successfully",
  1814. ],
  1815. },
  1816. backgroundPromptIndex,
  1817. "background queue drain Agent launch tool result 没有进入父模型请求",
  1818. );
  1819. expect(launchIndex).toBeGreaterThan(backgroundPromptIndex);
  1820. await waitForV4AssistantMessageContaining("background-queue-drain-launched-ok");
  1821. const secondQueuedIndex = await waitForFirstRequestIndex(
  1822. {
  1823. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1824. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1825. },
  1826. launchIndex,
  1827. "background prompt 完成后 Q2 没有继续 drain",
  1828. );
  1829. expect(secondQueuedIndex).toBeGreaterThan(launchIndex);
  1830. await waitForVisibleUserMessagesContainingAll(
  1831. ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2"],
  1832. "Q2 drain 后应渲染为可见 user message",
  1833. );
  1834. await waitForQueueOrderContaining(
  1835. [
  1836. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1837. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1838. ],
  1839. "Q2 drain 期间 Q3/Q4 应仍留在 queue 中",
  1840. );
  1841. expect(
  1842. await countUpstreamRequests(
  1843. {
  1844. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1845. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1846. },
  1847. { afterIndex: secondQueuedIndex },
  1848. ),
  1849. ).toBe(0);
  1850. await waitForV4AssistantMessageContaining("background-queue-drain-first-ok");
  1851. const thirdQueuedIndex = await waitForFirstRequestIndex(
  1852. {
  1853. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3"],
  1854. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3"],
  1855. },
  1856. secondQueuedIndex,
  1857. "Q2 完成后 Q3 没有继续 drain",
  1858. );
  1859. expect(thirdQueuedIndex).toBeGreaterThan(secondQueuedIndex);
  1860. await waitForVisibleUserMessagesContainingAll(
  1861. [
  1862. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1863. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1864. ],
  1865. "Q3 drain 后 Q2/Q3 应同时保留在可见 user messages 中",
  1866. );
  1867. await waitForQueueOrderContaining(
  1868. ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1869. "Q3 drain 期间 Q4 应仍留在 queue 中",
  1870. );
  1871. expect(
  1872. await countUpstreamRequests(
  1873. {
  1874. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1875. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1876. },
  1877. { afterIndex: thirdQueuedIndex },
  1878. ),
  1879. ).toBe(0);
  1880. await waitForV4AssistantMessageContaining("background-queue-drain-second-ok");
  1881. const fourthQueuedIndex = await waitForFirstRequestIndex(
  1882. {
  1883. includes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1884. lastUserMessageIncludes: ["E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4"],
  1885. },
  1886. thirdQueuedIndex,
  1887. "Q3 完成后 Q4 没有继续 drain",
  1888. );
  1889. expect(fourthQueuedIndex).toBeGreaterThan(thirdQueuedIndex);
  1890. await waitForVisibleUserMessagesContainingAll(
  1891. [
  1892. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1893. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1894. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1895. ],
  1896. "Q4 drain 后 Q2/Q3/Q4 应同时保留在可见 user messages 中",
  1897. );
  1898. assertVisibleUserMessageMarkersNeverDisappear(await stopVisibleUserMessageSampler(), [
  1899. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q2",
  1900. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q3",
  1901. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_Q4",
  1902. ]);
  1903. await waitForV4AssistantMessageContaining("background-queue-drain-third-ok");
  1904. // 失败原因:child 回复原来是固定 30s 延迟,赌主线 launch ack/Q2/Q3/Q4 先跑完;慢机器上
  1905. // Q3→Q4 的 drain 间隔(session snapshot 慢 3.8s)让 child 先完成,notification 排到 Q4 之前。
  1906. // 改为受控流:Q4 回复完成后才放行 child,notification 必然在 Q4 之后,断言不再依赖时钟。
  1907. await releaseControlledReplay("upstream-background-queue-drain-child-delayed-result");
  1908. const notificationIndex = await waitForFirstRequestIndex(
  1909. {
  1910. includes: ["<task-notification>", "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_CHILD_DONE"],
  1911. lastUserMessageIncludes: ["<task-notification>"],
  1912. },
  1913. fourthQueuedIndex,
  1914. "background queue drain Agent completion notification 没有进入父模型请求",
  1915. );
  1916. expect(notificationIndex).toBeGreaterThan(fourthQueuedIndex);
  1917. await waitForV4AssistantMessageContaining("background-queue-drain-notification-consumed-ok");
  1918. await waitForIdle("background queue drain notification 后会话没有回到 idle");
  1919. await assertNoVisibleTaskNotification();
  1920. });
  1921. it("background subagent 内部 background Bash 完成后只做 child cleanup", async function () {
  1922. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1923. await startNewBackgroundDraft();
  1924. const prompt =
  1925. "E2E_BACKGROUND_NESTED_BASH: Launch a background agent that starts a background Bash command and then finishes.";
  1926. const requestCountBefore = await getUpstreamRequestRecordCount();
  1927. await sendV4Prompt(prompt);
  1928. await waitForV4ComposerText("", "nested background Bash prompt 发送后输入框没有清空");
  1929. await waitForV4UserMessageContaining("E2E_BACKGROUND_NESTED_BASH");
  1930. await waitForToolCallBlockByToolName("Agent", 60000);
  1931. await respondToBackgroundBlockers();
  1932. const launchIndex = await waitForFirstRequestIndex(
  1933. {
  1934. includes: ["E2E_BACKGROUND_NESTED_BASH", "Async agent launched successfully"],
  1935. },
  1936. requestCountBefore,
  1937. "nested background Agent launch tool result 没有进入父模型请求",
  1938. );
  1939. const notificationIndex = await waitForFirstRequestIndex(
  1940. {
  1941. includes: ["<task-notification>", "E2E_BACKGROUND_NESTED_BASH_CHILD_DONE"],
  1942. },
  1943. launchIndex,
  1944. "nested background Agent completion notification 没有进入父模型请求",
  1945. );
  1946. expect(notificationIndex).toBeGreaterThan(launchIndex);
  1947. await waitForV4AssistantMessageContaining("background-nested-bash-notification-consumed-ok");
  1948. await waitForIdle("nested background Agent notification 后会话没有回到 idle");
  1949. await browser.pause(2500);
  1950. // Bug 根因:TaskOutput 的工具 description 本身包含 `<task-notification>`;旧断言扫描
  1951. // 整条 model-io JSONL,会把正常 child 首次请求里的工具 schema 与 Bash tool call ID
  1952. // 拼成一次伪 wake。这里改查 provider 实际请求,并把通知限定在 latest user message;
  1953. // 唯一 Bash tool call ID 与时间边界仍保留,真实的 sealed-child wake 仍会被准确捕获。
  1954. const unexpectedChildWakeCount = await countUpstreamRequests(
  1955. {
  1956. includes: ["toolu_e2e_background_nested_child_bash"],
  1957. lastUserMessageIncludes: ["<task-notification>"],
  1958. },
  1959. { afterIndex: launchIndex },
  1960. );
  1961. if (unexpectedChildWakeCount > 0) {
  1962. throw new Error(
  1963. "sealed child runtime 不应被 nested background Bash completion 重新唤起; " +
  1964. `count=${unexpectedChildWakeCount}`,
  1965. );
  1966. }
  1967. expect(unexpectedChildWakeCount).toBe(0);
  1968. expect(
  1969. await countUpstreamRequests(
  1970. {
  1971. includes: ["<task-notification>", "E2E_BACKGROUND_NESTED_BASH_CHILD_DONE"],
  1972. lastUserMessageIncludes: ["<task-notification>"],
  1973. },
  1974. { afterIndex: requestCountBefore },
  1975. ),
  1976. ).toBe(1);
  1977. await assertNoVisibleTaskNotification();
  1978. });
  1979. it("partial runtime snapshot 不应清掉缺失的 running background control row", async function () {
  1980. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  1981. await startNewBackgroundDraft();
  1982. const requestCountBefore = await getUpstreamRequestRecordCount();
  1983. await sendV4Prompt(
  1984. "E2E_BACKGROUND_SNAPSHOT_CONTROL: Start two background Bash tasks. One should finish first while the other keeps running.",
  1985. );
  1986. await waitForV4ComposerText("", "BG23 prompt 发送后输入框没有清空");
  1987. await waitForV4UserMessageContaining("E2E_BACKGROUND_SNAPSHOT_CONTROL");
  1988. await waitForToolCallBlockByToolCallId("toolu_e2e_bg23_bash_one", 60000);
  1989. await waitForToolCallBlockByToolCallId("toolu_e2e_bg23_bash_two", 60000);
  1990. await respondToBackgroundBlockers();
  1991. await respondToBackgroundBlockers();
  1992. const launchIndex = await waitForFirstRequestIndex(
  1993. {
  1994. includes: [
  1995. "E2E_BACKGROUND_SNAPSHOT_CONTROL",
  1996. "toolu_e2e_bg23_bash_one",
  1997. "toolu_e2e_bg23_bash_two",
  1998. "Command running in background",
  1999. ],
  2000. },
  2001. requestCountBefore,
  2002. "BG23 两个 background Bash launch result 没有进入父模型请求",
  2003. );
  2004. await waitForV4AssistantMessageContaining("background-snapshot-control-ready-ok");
  2005. await waitForIdle("BG23 setup prompt 后会话没有回到 idle");
  2006. await waitForBackgroundTaskControlRow(
  2007. "bash",
  2008. "E2E BG23 bash one",
  2009. "BG23 初始第一个 Bash background control row 没有显示在右上角面板",
  2010. );
  2011. await waitForBackgroundTaskControlRow(
  2012. "bash",
  2013. "E2E BG23 bash two",
  2014. "BG23 初始第二个 Bash background control row 没有显示在右上角面板",
  2015. );
  2016. const firstNotificationIndex = await waitForFirstRequestIndex(
  2017. {
  2018. includes: [
  2019. "E2E_BACKGROUND_SNAPSHOT_CONTROL",
  2020. "<task-notification>",
  2021. "<tool-use-id>toolu_e2e_bg23_bash_one</tool-use-id>",
  2022. "<status>completed</status>",
  2023. ],
  2024. lastUserMessageIncludes: ["<task-notification>"],
  2025. },
  2026. launchIndex,
  2027. "BG23 第一个 background Bash completion notification 没有进入父模型请求",
  2028. );
  2029. expect(firstNotificationIndex).toBeGreaterThan(launchIndex);
  2030. await waitForV4AssistantMessageContaining("background-snapshot-control-first-notification-ok");
  2031. await waitForIdle("BG23 第一个 background Bash notification 后会话没有回到 idle");
  2032. await waitForNoBackgroundTaskControlRow(
  2033. "bash",
  2034. "E2E BG23 bash one",
  2035. "BG23 第一个 terminal Bash row 没有从右上角面板消失",
  2036. );
  2037. await waitForBackgroundTaskControlRow(
  2038. "bash",
  2039. "E2E BG23 bash two",
  2040. "BG23 第一个 Bash 完成后第二个 running Bash row 被错误清掉",
  2041. );
  2042. await clickStopBackgroundTaskControlRow("bash", "E2E BG23 bash two");
  2043. const stopNotificationIndex = await waitForFirstRequestIndex(
  2044. {
  2045. includes: [
  2046. "E2E_BACKGROUND_SNAPSHOT_CONTROL",
  2047. "<task-notification>",
  2048. "<tool-use-id>toolu_e2e_bg23_bash_two</tool-use-id>",
  2049. "<status>killed</status>",
  2050. ],
  2051. lastUserMessageIncludes: ["<task-notification>"],
  2052. },
  2053. firstNotificationIndex,
  2054. "BG23 第二个 background Bash stop notification 没有进入父模型请求",
  2055. );
  2056. expect(stopNotificationIndex).toBeGreaterThan(firstNotificationIndex);
  2057. await waitForV4AssistantMessageContaining("background-snapshot-control-second-stopped-ok");
  2058. await waitForIdle("BG23 第二个 background Bash stop notification 后会话没有回到 idle");
  2059. await waitForNoBackgroundTaskControlRow(
  2060. "bash",
  2061. "E2E BG23 bash two",
  2062. "BG23 第二个 Bash stop 后 row 没有从右上角面板消失",
  2063. );
  2064. });
  2065. it("background Agent notification 处理中不应清掉仍 running 的其它 Agent control row", async function () {
  2066. this.timeout(BACKGROUND_E2E_TIMEOUT_MS);
  2067. await startNewBackgroundDraft();
  2068. const requestCountBefore = await getUpstreamRequestRecordCount();
  2069. await sendV4Prompt(
  2070. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE: Start one long-running background agent and three short-lived background agents. The three short-lived agents should finish before the long-running agent.",
  2071. );
  2072. await waitForV4ComposerText("", "BG24 prompt 发送后输入框没有清空");
  2073. await waitForV4UserMessageContaining("E2E_BACKGROUND_AGENT_CONTROL_PRESERVE");
  2074. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_long_running_agent", 60000);
  2075. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_short_lived_one_agent", 60000);
  2076. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_short_lived_two_agent", 60000);
  2077. await waitForToolCallBlockByToolCallId("toolu_e2e_bg24_short_lived_three_agent", 60000);
  2078. await respondToBackgroundBlockers();
  2079. const launchIndex = await waitForFirstRequestIndex(
  2080. {
  2081. includes: [
  2082. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2083. "toolu_e2e_bg24_long_running_agent",
  2084. "toolu_e2e_bg24_short_lived_one_agent",
  2085. "toolu_e2e_bg24_short_lived_two_agent",
  2086. "toolu_e2e_bg24_short_lived_three_agent",
  2087. "Async agent launched successfully",
  2088. ],
  2089. },
  2090. requestCountBefore,
  2091. "BG24 四个 background Agent launch result 没有进入父模型请求",
  2092. );
  2093. await waitForV4AssistantMessageContaining("background-agent-control-preserve-ready-ok");
  2094. const sourceSnapshot = await waitForIdle("BG24 setup prompt 后会话没有回到 idle");
  2095. const sourceTaskId = sourceSnapshot.taskId;
  2096. if (!sourceTaskId) {
  2097. throw new Error(`BG24 setup 后缺少 source taskId: ${JSON.stringify(sourceSnapshot)}`);
  2098. }
  2099. await waitForBackgroundTaskControlRow(
  2100. "agent",
  2101. "E2E BG24 long-running keepalive agent",
  2102. "BG24 初始 long-running Agent background control row 没有显示在右上角面板",
  2103. );
  2104. await waitForBackgroundTaskControlRow(
  2105. "agent",
  2106. "E2E BG24 short-lived three agent",
  2107. "BG24 初始第三个 short-lived Agent background control row 没有显示在右上角面板",
  2108. );
  2109. const firstShortLivedNotificationIndex = await waitForFirstRequestIndex(
  2110. {
  2111. includes: [
  2112. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2113. "<task-notification>",
  2114. "<tool-use-id>toolu_e2e_bg24_short_lived_one_agent</tool-use-id>",
  2115. "<status>completed</status>",
  2116. "E2E_BG24_SHORT_LIVED_ONE_CHILD_DONE",
  2117. ],
  2118. lastUserMessageIncludes: ["<task-notification>"],
  2119. },
  2120. launchIndex,
  2121. "BG24 第一个 short-lived background Agent completion notification 没有进入父模型请求",
  2122. );
  2123. expect(firstShortLivedNotificationIndex).toBeGreaterThan(launchIndex);
  2124. await waitForV4AssistantMessageContaining(
  2125. "background-agent-control-preserve-short-lived-one-notification-ok",
  2126. );
  2127. await waitForBackgroundTaskControlRow(
  2128. "agent",
  2129. "E2E BG24 long-running keepalive agent",
  2130. "BG24 第一个 short-lived Agent 完成后 long-running running Agent row 被错误清掉",
  2131. );
  2132. await startBackgroundTaskControlPresenceProbe(
  2133. "agent",
  2134. "E2E BG24 long-running keepalive agent",
  2135. sourceTaskId,
  2136. );
  2137. const secondShortLivedNotificationIndex = await waitForFirstRequestIndex(
  2138. {
  2139. includes: [
  2140. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2141. "<task-notification>",
  2142. "<tool-use-id>toolu_e2e_bg24_short_lived_two_agent</tool-use-id>",
  2143. "<status>completed</status>",
  2144. "E2E_BG24_SHORT_LIVED_TWO_CHILD_DONE",
  2145. ],
  2146. lastUserMessageIncludes: ["<task-notification>"],
  2147. },
  2148. firstShortLivedNotificationIndex,
  2149. "BG24 第二个 short-lived background Agent completion notification 没有进入父模型请求",
  2150. );
  2151. expect(secondShortLivedNotificationIndex).toBeGreaterThan(firstShortLivedNotificationIndex);
  2152. await startNewBackgroundDraft();
  2153. await waitForV4ConversationState(
  2154. (snapshot) => snapshot.taskId === null && snapshot.sessionId === null,
  2155. "BG24 第二个 notification 处理中没有切到新草稿 task",
  2156. 30000,
  2157. );
  2158. await selectV4TaskById(sourceTaskId);
  2159. await waitForV4ConversationState(
  2160. (snapshot) => snapshot.taskId === sourceTaskId,
  2161. "BG24 第二个 notification 处理中切回原 task 后 chat root 没有恢复",
  2162. 30000,
  2163. );
  2164. await waitForBackgroundTaskControlRow(
  2165. "agent",
  2166. "E2E BG24 long-running keepalive agent",
  2167. "BG24 第二个 notification 处理中切回原 task 后 long-running running Agent row 没有恢复",
  2168. );
  2169. await waitForV4AssistantMessageContaining(
  2170. "background-agent-control-preserve-short-lived-two-notification-ok",
  2171. );
  2172. await waitForBackgroundTaskControlRow(
  2173. "agent",
  2174. "E2E BG24 long-running keepalive agent",
  2175. "BG24 第二个 short-lived Agent 完成后 long-running running Agent row 被错误清掉",
  2176. );
  2177. const thirdShortLivedNotificationIndex = await waitForFirstRequestIndex(
  2178. {
  2179. includes: [
  2180. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2181. "<task-notification>",
  2182. "<tool-use-id>toolu_e2e_bg24_short_lived_three_agent</tool-use-id>",
  2183. "<status>completed</status>",
  2184. "E2E_BG24_SHORT_LIVED_THREE_CHILD_DONE",
  2185. ],
  2186. lastUserMessageIncludes: ["<task-notification>"],
  2187. },
  2188. secondShortLivedNotificationIndex,
  2189. "BG24 第三个 short-lived background Agent completion notification 没有进入父模型请求",
  2190. );
  2191. expect(thirdShortLivedNotificationIndex).toBeGreaterThan(secondShortLivedNotificationIndex);
  2192. const afterTodoIndex = await waitForFirstRequestIndex(
  2193. {
  2194. includes: [
  2195. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2196. "toolu_e2e_bg24_todo_write",
  2197. "E2E_BG24_TODO_UPDATED",
  2198. ],
  2199. },
  2200. thirdShortLivedNotificationIndex,
  2201. "BG24 short-lived notification 中的 TodoWrite tool result 没有进入后续父模型请求",
  2202. );
  2203. expect(afterTodoIndex).toBeGreaterThan(thirdShortLivedNotificationIndex);
  2204. await waitForV4AssistantMessageContaining(
  2205. "background-agent-control-preserve-short-lived-notification-ok",
  2206. );
  2207. await waitForIdle("BG24 short-lived Agent notification 后会话没有回到 idle");
  2208. const presenceProbe = await stopBackgroundTaskControlPresenceProbe();
  2209. expect(presenceProbe.observedPresent).toBe(true);
  2210. expect(presenceProbe.missingTransitions).toEqual([]);
  2211. await waitForNoBackgroundTaskControlRow(
  2212. "agent",
  2213. "E2E BG24 short-lived three agent",
  2214. "BG24 已完成的第三个 short-lived Agent row 没有从右上角面板消失",
  2215. );
  2216. await waitForBackgroundTaskControlRow(
  2217. "agent",
  2218. "E2E BG24 long-running keepalive agent",
  2219. "BG24 short-lived Agent 完成后 long-running running Agent row 被错误清掉",
  2220. );
  2221. await clickStopBackgroundTaskControlRow("agent", "E2E BG24 long-running keepalive agent");
  2222. const stopNotificationIndex = await waitForFirstRequestIndex(
  2223. {
  2224. includes: [
  2225. "E2E_BACKGROUND_AGENT_CONTROL_PRESERVE",
  2226. "<task-notification>",
  2227. "<tool-use-id>toolu_e2e_bg24_long_running_agent</tool-use-id>",
  2228. "<status>killed</status>",
  2229. "was stopped by user</summary>",
  2230. ],
  2231. lastUserMessageIncludes: ["<task-notification>"],
  2232. },
  2233. thirdShortLivedNotificationIndex,
  2234. "BG24 long-running background Agent stop notification 没有进入父模型请求",
  2235. );
  2236. expect(stopNotificationIndex).toBeGreaterThan(thirdShortLivedNotificationIndex);
  2237. await waitForV4AssistantMessageContaining(
  2238. "background-agent-control-preserve-long-running-stopped-ok",
  2239. );
  2240. await waitForIdle("BG24 long-running Agent stop notification 后会话没有回到 idle");
  2241. await waitForNoBackgroundTaskControlRow(
  2242. "agent",
  2243. "E2E BG24 long-running keepalive agent",
  2244. "BG24 stop 后 long-running Agent row 没有从右上角面板消失",
  2245. );
  2246. });
  2247. });
  2248. async function waitForFirstRequestIndex(
  2249. query: Parameters<typeof waitForUpstreamRequest>[0],
  2250. afterIndex: number,
  2251. timeoutMsg: string,
  2252. ) {
  2253. await waitForUpstreamRequest(query, timeoutMsg, 45000, { afterIndex });
  2254. const index = await findFirstUpstreamRequestIndex(query, { afterIndex });
  2255. if (index === null) {
  2256. throw new Error(`${timeoutMsg}; request disappeared after wait`);
  2257. }
  2258. if (
  2259. query.includes?.includes("<task-notification>") ||
  2260. query.lastUserMessageIncludes?.includes("<task-notification>")
  2261. ) {
  2262. const records = await getUpstreamRequestEvidence(query, {
  2263. afterIndex: index - 1,
  2264. beforeIndex: index + 1,
  2265. });
  2266. await assertTaskNotificationContents(records[0]!.requestJson, `background-request-${index}`);
  2267. }
  2268. return index;
  2269. }
  2270. async function waitForRunningPidFile(path: string, label: string): Promise<number> {
  2271. let recordedPid: number | null = null;
  2272. await browser.waitUntil(
  2273. async () => {
  2274. recordedPid = await readRecordedPid(path);
  2275. return recordedPid !== null && isProcessAlive(recordedPid);
  2276. },
  2277. {
  2278. timeout: 30000,
  2279. timeoutMsg: `${label} 没有写入 fresh PID marker 或进程未保持运行`,
  2280. },
  2281. );
  2282. return recordedPid!;
  2283. }
  2284. async function readRecordedPid(path: string): Promise<number | null> {
  2285. const raw = await readFile(path, "utf-8").catch(() => "");
  2286. const pid = Number(raw.trim());
  2287. return Number.isInteger(pid) && pid > 1 ? pid : null;
  2288. }
  2289. function isProcessAlive(pid: number): boolean {
  2290. try {
  2291. process.kill(pid, 0);
  2292. return true;
  2293. } catch (error) {
  2294. return (error as NodeJS.ErrnoException).code === "EPERM";
  2295. }
  2296. }
  2297. async function readPosixProcessGroupId(pid: number): Promise<number> {
  2298. const stdout = await new Promise<string>((resolve, reject) => {
  2299. execFile("ps", ["-o", "pgid=", "-p", String(pid)], (error, output) => {
  2300. if (error) {
  2301. reject(error);
  2302. return;
  2303. }
  2304. resolve(output);
  2305. });
  2306. });
  2307. const processGroupId = Number(stdout.trim());
  2308. if (!Number.isInteger(processGroupId) || processGroupId <= 1) {
  2309. throw new Error(`无法读取 PID ${pid} 的 POSIX PGID: ${JSON.stringify(stdout)}`);
  2310. }
  2311. return processGroupId;
  2312. }
  2313. async function waitForProcessExit(pid: number, label: string): Promise<void> {
  2314. await browser.waitUntil(() => !isProcessAlive(pid), {
  2315. timeout: 15000,
  2316. timeoutMsg: `${label} PID ${pid} 在 background stop 收口后仍存活`,
  2317. });
  2318. }
  2319. async function cleanupBg08ProcessTree(): Promise<void> {
  2320. const processFiles = [BG08_WORKER_PID_FILE, BG08_LAUNCHER_PID_FILE];
  2321. if (process.platform !== "win32") {
  2322. processFiles.push(BG08_ROOT_PID_FILE);
  2323. }
  2324. for (const path of processFiles) {
  2325. const pid = await readRecordedPid(path);
  2326. if (pid === null || !isProcessAlive(pid)) continue;
  2327. try {
  2328. process.kill(pid, "SIGKILL");
  2329. } catch {
  2330. // 测试收尾与进程自然退出存在竞争,已退出即视为完成。
  2331. }
  2332. }
  2333. }
  2334. async function removeBg08PidFiles(): Promise<void> {
  2335. await Promise.all(
  2336. [BG08_ROOT_PID_FILE, BG08_LAUNCHER_PID_FILE, BG08_WORKER_PID_FILE].map((path) =>
  2337. rm(path, { force: true }).catch(() => undefined),
  2338. ),
  2339. );
  2340. }
  2341. async function waitForVisibleUserMessagesContainingAll(
  2342. markers: readonly string[],
  2343. timeoutMsg: string,
  2344. ) {
  2345. let latestMessages: Awaited<ReturnType<typeof getV4Messages>> = [];
  2346. await browser.waitUntil(
  2347. async () => {
  2348. latestMessages = await getV4Messages("user");
  2349. return markers.every((marker) =>
  2350. latestMessages.some((message) => message.text.includes(marker)),
  2351. );
  2352. },
  2353. {
  2354. timeout: 60000,
  2355. timeoutMsg: `${timeoutMsg}; visibleUserMessages=${JSON.stringify(
  2356. latestMessages.map((message) => ({
  2357. id: message.id,
  2358. text: message.text.slice(0, 200),
  2359. })),
  2360. )}`,
  2361. },
  2362. );
  2363. }
  2364. type VisibleUserMessageSample = {
  2365. at: number;
  2366. messages: Array<{
  2367. id: string | null;
  2368. text: string;
  2369. }>;
  2370. };
  2371. async function startVisibleUserMessageSampler() {
  2372. await browser.execute(
  2373. (messagesTestId: string, userMessagePrefix: string) => {
  2374. type SamplerState = {
  2375. intervalId: ReturnType<typeof setInterval>;
  2376. samples: VisibleUserMessageSample[];
  2377. };
  2378. const sampleWindow = window as typeof window & {
  2379. __zcodeBg17UserMessageSampler?: SamplerState;
  2380. };
  2381. if (sampleWindow.__zcodeBg17UserMessageSampler) {
  2382. clearInterval(sampleWindow.__zcodeBg17UserMessageSampler.intervalId);
  2383. }
  2384. const collect = () => {
  2385. const root = document.querySelector<HTMLElement>(`[data-testid="${messagesTestId}"]`);
  2386. const messages = Array.from(
  2387. root?.querySelectorAll<HTMLElement>(`[data-testid^="${userMessagePrefix}-"]`) ?? [],
  2388. ).map((element) => ({
  2389. id: element.getAttribute("data-message-id"),
  2390. text: element.innerText.replace(/\u00a0/g, " ").trim(),
  2391. }));
  2392. sampleWindow.__zcodeBg17UserMessageSampler?.samples.push({
  2393. at: Date.now(),
  2394. messages,
  2395. });
  2396. };
  2397. sampleWindow.__zcodeBg17UserMessageSampler = {
  2398. intervalId: setInterval(collect, 50),
  2399. samples: [],
  2400. };
  2401. collect();
  2402. },
  2403. TID_CHAT_MESSAGES,
  2404. TID_CHAT_USER_MESSAGE,
  2405. );
  2406. }
  2407. async function stopVisibleUserMessageSampler() {
  2408. return await browser.execute(() => {
  2409. const sampleWindow = window as typeof window & {
  2410. __zcodeBg17UserMessageSampler?: {
  2411. intervalId: ReturnType<typeof setInterval>;
  2412. samples: VisibleUserMessageSample[];
  2413. };
  2414. };
  2415. const sampler = sampleWindow.__zcodeBg17UserMessageSampler;
  2416. if (!sampler) {
  2417. return [] satisfies VisibleUserMessageSample[];
  2418. }
  2419. clearInterval(sampler.intervalId);
  2420. delete sampleWindow.__zcodeBg17UserMessageSampler;
  2421. return sampler.samples;
  2422. });
  2423. }
  2424. function assertVisibleUserMessageMarkersNeverDisappear(
  2425. samples: readonly VisibleUserMessageSample[],
  2426. markers: readonly string[],
  2427. ) {
  2428. const seen = new Set<string>();
  2429. const violations: Array<{
  2430. marker: string;
  2431. sampleIndex: number;
  2432. at: number;
  2433. messages: VisibleUserMessageSample["messages"];
  2434. }> = [];
  2435. for (const [sampleIndex, sample] of samples.entries()) {
  2436. const presentMarkers = new Set(
  2437. markers.filter((marker) => sample.messages.some((message) => message.text.includes(marker))),
  2438. );
  2439. for (const marker of presentMarkers) {
  2440. seen.add(marker);
  2441. }
  2442. for (const marker of seen) {
  2443. if (!presentMarkers.has(marker)) {
  2444. violations.push({
  2445. marker,
  2446. sampleIndex,
  2447. at: sample.at,
  2448. messages: sample.messages,
  2449. });
  2450. }
  2451. }
  2452. }
  2453. expect(violations).toEqual([]);
  2454. }
  2455. async function waitForIdle(timeoutMsg: string) {
  2456. return waitForV4ConversationState(
  2457. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  2458. timeoutMsg,
  2459. 90000,
  2460. );
  2461. }
  2462. async function assertNoVisibleTaskNotification() {
  2463. await assertVisibleV4UserMessagesNotContaining("<task-notification>");
  2464. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_AGENT_CHILD_RESULT");
  2465. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_GOAL_CHILD_RESULT");
  2466. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_SEND_MESSAGE_CHILD_RECEIVED");
  2467. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_AGENT_CHILD_TOOL_IDLE_DONE");
  2468. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_COMPACT_AFTER_IDLE_DONE");
  2469. await assertVisibleV4UserMessagesNotContaining(
  2470. "E2E_BACKGROUND_QUEUE_DRAIN_AFTER_MAIN_END_CHILD_DONE",
  2471. );
  2472. await assertVisibleV4UserMessagesNotContaining("E2E_BACKGROUND_NESTED_BASH_CHILD_DONE");
  2473. }
  2474. async function assertNoMainFakeLoading(timeoutMsg: string) {
  2475. await browser.pause(600);
  2476. const [snapshot, loadingTexts] = await Promise.all([
  2477. getV4ConversationState(),
  2478. getVisibleChatLoadingTexts(),
  2479. ]);
  2480. if (snapshot.state === "streaming" || loadingTexts.length > 0) {
  2481. throw new Error(
  2482. `${timeoutMsg}; state=${JSON.stringify(snapshot)}; loading=${JSON.stringify(loadingTexts)}`,
  2483. );
  2484. }
  2485. }
  2486. async function waitForMainLoading(timeoutMsg: string) {
  2487. let latestSnapshot = await getV4ConversationState();
  2488. let latestLoadingTexts: string[] = [];
  2489. await browser.waitUntil(
  2490. async () => {
  2491. latestSnapshot = await getV4ConversationState();
  2492. latestLoadingTexts = await getVisibleChatLoadingTexts();
  2493. // Bugfix: Windows Electron 下 foreground Bash 有时只暴露 chat root streaming 状态,
  2494. // 不稳定渲染旧的底部 loading 节点;这里验证主会话没有退成 background-only idle 即可。
  2495. return latestSnapshot.state === "streaming";
  2496. },
  2497. {
  2498. interval: 100,
  2499. timeout: 5000,
  2500. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(
  2501. latestSnapshot,
  2502. )}; loading=${JSON.stringify(latestLoadingTexts)}`,
  2503. },
  2504. );
  2505. }
  2506. async function getVisibleChatLoadingTexts(): Promise<string[]> {
  2507. return browser.execute((chatLoadingTestId) => {
  2508. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2509. const isElementVisible = (element: HTMLElement) =>
  2510. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2511. return Array.from(
  2512. document.querySelectorAll<HTMLElement>(`[data-testid="${chatLoadingTestId}"]`),
  2513. )
  2514. .filter(isElementVisible)
  2515. .map((element) => element.innerText.replace(/\u00a0/g, " ").trim());
  2516. }, TID_CHAT_LOADING);
  2517. }
  2518. async function assertNoMainToolCallById(toolCallId: string, failureMessage: string) {
  2519. const blocks = await listToolCallBlocks();
  2520. const mirrored = blocks.filter((block) => block.toolCallId?.includes(toolCallId));
  2521. if (mirrored.length > 0) {
  2522. throw new Error(`${failureMessage}; mirrored=${JSON.stringify(mirrored)}`);
  2523. }
  2524. }
  2525. async function beginBackgroundTelemetryCapture() {
  2526. // 跨 case 复用采集器会混入中间用例的 completion,失败后游标也可能只推进一半。
  2527. // 每条 case 从空 HTTP 调用记录和 ARMS 缓冲开始,保留精确数量断言。
  2528. // 本文件中途会重启 Main(fork 冷恢复);begin 按当前进程重装并清空 net.fetch 记录器,
  2529. // 不能复用重启前登记的 wdio mock(见 helper 注释)。
  2530. return beginConversationTelemetryCapture();
  2531. }
  2532. async function startNewBackgroundDraft() {
  2533. // Bash fixture 的相对路径属于夹具项目;全局新建会切到另一个 cwd,读不到 PID/释放文件。
  2534. // 初始空草稿直接复用,避免准备步骤重复新建;已有任务仍走同一项目的新建入口。
  2535. await prepareV4ConversationE2E({ skipProvider: true });
  2536. // Bug 根因:suite 只在 before 设置 yolo,新草稿恢复默认 build 后 child Bash 会停在审批。
  2537. // 生命周期用例在每次 draft admission 前固定前置;权限代理仍由独立 interaction spec 验证。
  2538. await ensureToolCrossProductFullAccessMode();
  2539. }
  2540. async function respondToBackgroundBlockers() {
  2541. // Full access 前置条件下正常路径没有 blocker;只做一次兼容探测,不能再固定等待
  2542. // 3 秒,否则 4 秒 child Bash 会在 UI running 断言前结束,掩盖真实生命周期窗口。
  2543. await respondToToolCrossProductBlockers();
  2544. }
  2545. type BackgroundTaskControlKind = "agent" | "bash";
  2546. interface BackgroundTaskControlRowSnapshot {
  2547. buttonDisabled: boolean;
  2548. kind: string | null;
  2549. text: string;
  2550. visible: boolean;
  2551. }
  2552. interface BackgroundTaskProjectionSnapshot {
  2553. projectionSeq: string | null;
  2554. runningSubagentIds: string | null;
  2555. runningSubagentWorkIds: string | null;
  2556. sessionId: string | null;
  2557. }
  2558. async function waitForBackgroundTaskControlRow(
  2559. kind: BackgroundTaskControlKind,
  2560. textIncludes: string,
  2561. timeoutMsg: string,
  2562. ) {
  2563. let latest: BackgroundTaskControlRowSnapshot[] = [];
  2564. let projection: BackgroundTaskProjectionSnapshot | null = null;
  2565. await browser.waitUntil(
  2566. async () => {
  2567. try {
  2568. await openV4ComposerRunningBackgroundWorks();
  2569. } catch (error) {
  2570. projection = await getBackgroundTaskProjectionSnapshot();
  2571. throw new Error(
  2572. `${error instanceof Error ? error.message : String(error)}; projection=${JSON.stringify(projection)}`,
  2573. { cause: error },
  2574. );
  2575. }
  2576. latest = await getBackgroundTaskControlRows({ visibleOnly: false });
  2577. return latest.some(
  2578. (row) => row.visible && row.kind === kind && row.text.includes(textIncludes),
  2579. );
  2580. },
  2581. {
  2582. interval: 250,
  2583. timeout: 30000,
  2584. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latest)}; projection=${JSON.stringify(projection)}`,
  2585. },
  2586. );
  2587. }
  2588. async function getBackgroundTaskProjectionSnapshot(): Promise<BackgroundTaskProjectionSnapshot> {
  2589. return browser.execute(
  2590. (paneTestId) => {
  2591. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  2592. return {
  2593. projectionSeq: pane?.getAttribute("data-projection-seq") ?? null,
  2594. runningSubagentIds: pane?.getAttribute("data-running-subagent-ids") ?? null,
  2595. runningSubagentWorkIds: pane?.getAttribute("data-running-subagent-work-ids") ?? null,
  2596. sessionId: pane?.getAttribute("data-session-id") ?? null,
  2597. };
  2598. },
  2599. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  2600. );
  2601. }
  2602. async function waitForNoBackgroundTaskControlRow(
  2603. kind: BackgroundTaskControlKind,
  2604. textIncludes: string,
  2605. timeoutMsg: string,
  2606. ) {
  2607. let latest: BackgroundTaskControlRowSnapshot[] = [];
  2608. await browser.waitUntil(
  2609. async () => {
  2610. latest = await getBackgroundTaskControlRows({ visibleOnly: false });
  2611. return !latest.some((row) => row.kind === kind && row.text.includes(textIncludes));
  2612. },
  2613. {
  2614. interval: 250,
  2615. timeout: 30000,
  2616. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latest)}`,
  2617. },
  2618. );
  2619. }
  2620. interface BackgroundTaskControlPresenceProbeResult {
  2621. missingTransitions: Array<{
  2622. atMs: number;
  2623. panelState: string | null;
  2624. rows: string[];
  2625. storeJobs: string[];
  2626. }>;
  2627. observedPresent: boolean;
  2628. }
  2629. async function startBackgroundTaskControlPresenceProbe(
  2630. kind: BackgroundTaskControlKind,
  2631. textIncludes: string,
  2632. taskId: string,
  2633. ) {
  2634. await openV4ComposerRunningBackgroundWorks();
  2635. await browser.execute(
  2636. (expectedKind, expectedText, expectedTaskId, v4SessionPanePrefix) => {
  2637. const probeKey = "__zcodeBackgroundTaskControlPresenceProbe";
  2638. const probeWindow = window as typeof window & {
  2639. __zcodeBackgroundTaskControlPresenceProbe?: {
  2640. intervalId: number;
  2641. missingTransitions: Array<{
  2642. atMs: number;
  2643. panelState: string | null;
  2644. rows: string[];
  2645. storeJobs: string[];
  2646. }>;
  2647. hasLeftTask: boolean;
  2648. hasReturnedToTask: boolean;
  2649. observedPresent: boolean;
  2650. startedAt: number;
  2651. wasPresent: boolean | null;
  2652. };
  2653. };
  2654. const existing = probeWindow[probeKey];
  2655. if (existing) {
  2656. window.clearInterval(existing.intervalId);
  2657. }
  2658. const state: NonNullable<(typeof probeWindow)[typeof probeKey]> = {
  2659. intervalId: 0,
  2660. missingTransitions: [],
  2661. hasLeftTask: false,
  2662. hasReturnedToTask: false,
  2663. observedPresent: false,
  2664. startedAt: performance.now(),
  2665. wasPresent: null,
  2666. };
  2667. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2668. const isElementVisible = (element: HTMLElement) =>
  2669. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2670. const sample = () => {
  2671. const legacyTaskId = document
  2672. .querySelector<HTMLElement>('[data-testid="chat-view"]')
  2673. ?.getAttribute("data-task-id");
  2674. const v4SessionId = document
  2675. .querySelector<HTMLElement>(`[data-testid="${v4SessionPanePrefix}-workspace-main"]`)
  2676. ?.getAttribute("data-session-id");
  2677. // Bug 根因:V4 无 legacy chat-view;presence probe 需要从主 pane
  2678. // 读取 session id,否则切回目标 task 后仍会被误判成“尚未返回”。
  2679. const activeTaskId =
  2680. legacyTaskId || (v4SessionId && v4SessionId !== "draft" ? v4SessionId : null);
  2681. if (activeTaskId !== expectedTaskId) {
  2682. state.hasLeftTask = true;
  2683. state.wasPresent = null;
  2684. return;
  2685. }
  2686. if (state.hasLeftTask) {
  2687. state.hasReturnedToTask = true;
  2688. }
  2689. const rows = Array.from(
  2690. document.querySelectorAll<HTMLElement>("[data-background-task-kind]"),
  2691. );
  2692. const present = rows.some(
  2693. (row) =>
  2694. row.getAttribute("data-background-task-kind") === expectedKind &&
  2695. row.innerText.includes(expectedText) &&
  2696. isElementVisible(row),
  2697. );
  2698. state.observedPresent ||= present;
  2699. if (state.hasReturnedToTask && state.wasPresent === true && !present) {
  2700. const store = (
  2701. window as typeof window & {
  2702. __zcodeSessionStoreE2E?: {
  2703. getState: () => {
  2704. workspaces: Record<
  2705. string,
  2706. {
  2707. taskRuntimeByTaskId?: Record<
  2708. string,
  2709. {
  2710. backgroundTaskControls?: Array<{
  2711. jobId: string;
  2712. status: string;
  2713. title?: string;
  2714. }>;
  2715. }
  2716. >;
  2717. }
  2718. >;
  2719. };
  2720. };
  2721. }
  2722. ).__zcodeSessionStoreE2E;
  2723. const taskRuntime = Object.values(store?.getState().workspaces ?? {})
  2724. .map((workspace) => workspace.taskRuntimeByTaskId?.[expectedTaskId])
  2725. .find(Boolean);
  2726. state.missingTransitions.push({
  2727. atMs: Math.round(performance.now() - state.startedAt),
  2728. panelState:
  2729. document
  2730. .querySelector<HTMLElement>('[data-status-capsule="activity"]')
  2731. ?.getAttribute("data-state") ?? null,
  2732. rows: rows.map((row) => row.innerText.replace(/\u00a0/g, " ").trim()),
  2733. storeJobs: (taskRuntime?.backgroundTaskControls ?? []).map(
  2734. (job) => `${job.jobId}:${job.status}:${job.title ?? ""}`,
  2735. ),
  2736. });
  2737. }
  2738. state.wasPresent = present;
  2739. };
  2740. sample();
  2741. state.intervalId = window.setInterval(sample, 16);
  2742. probeWindow[probeKey] = state;
  2743. },
  2744. kind,
  2745. textIncludes,
  2746. taskId,
  2747. TID_V4_SESSION_PANE,
  2748. );
  2749. }
  2750. async function stopBackgroundTaskControlPresenceProbe(): Promise<BackgroundTaskControlPresenceProbeResult> {
  2751. return browser.execute(() => {
  2752. const probeKey = "__zcodeBackgroundTaskControlPresenceProbe";
  2753. const probeWindow = window as typeof window & {
  2754. __zcodeBackgroundTaskControlPresenceProbe?: {
  2755. intervalId: number;
  2756. missingTransitions: BackgroundTaskControlPresenceProbeResult["missingTransitions"];
  2757. observedPresent: boolean;
  2758. };
  2759. };
  2760. const state = probeWindow[probeKey];
  2761. if (!state) {
  2762. return { missingTransitions: [], observedPresent: false };
  2763. }
  2764. window.clearInterval(state.intervalId);
  2765. delete probeWindow[probeKey];
  2766. return {
  2767. missingTransitions: state.missingTransitions,
  2768. observedPresent: state.observedPresent,
  2769. };
  2770. });
  2771. }
  2772. async function clickStopBackgroundTaskControlRow(
  2773. kind: BackgroundTaskControlKind,
  2774. textIncludes: string,
  2775. ) {
  2776. let latest:
  2777. | { clicked: true; rows: [] }
  2778. | { clicked: false; rows: BackgroundTaskControlRowSnapshot[] } = {
  2779. clicked: false,
  2780. rows: [],
  2781. };
  2782. await browser.waitUntil(
  2783. async () => {
  2784. await openV4ComposerRunningBackgroundWorks();
  2785. latest = await browser.execute(
  2786. (expectedKind, expectedText, cancelButtonPrefix) => {
  2787. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2788. const isElementVisible = (element: HTMLElement) =>
  2789. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2790. const rows = Array.from(
  2791. document.querySelectorAll<HTMLElement>("[data-background-task-kind]"),
  2792. );
  2793. const row = rows.find(
  2794. (candidate) =>
  2795. isElementVisible(candidate) &&
  2796. candidate.getAttribute("data-background-task-kind") === expectedKind &&
  2797. candidate.innerText.includes(expectedText),
  2798. );
  2799. // Bug 根因:V4 Agent 行的第一个 button 是透明的 child session 下钻入口,
  2800. // 旧 helper 会误点详情而没有发出 stop。取消动作必须按专用 test id 定位。
  2801. // Agent 行的停止按钮改为按 taskId/executionId 停止后,testid 是
  2802. // `v4-running-subagent-stop`;终端行仍是 `v4-background-work-cancel-<workId>`。
  2803. const button = row?.querySelector<HTMLButtonElement>(
  2804. `[data-testid^="${cancelButtonPrefix}-"], [data-testid="v4-running-subagent-stop"]`,
  2805. );
  2806. if (!row || !button || button.disabled || !isElementVisible(button)) {
  2807. return {
  2808. clicked: false,
  2809. rows: rows.map((candidate) => ({
  2810. buttonDisabled:
  2811. candidate.querySelector<HTMLButtonElement>("button")?.disabled ?? false,
  2812. kind: candidate.getAttribute("data-background-task-kind"),
  2813. text: candidate.innerText.replace(/\u00a0/g, " ").trim(),
  2814. visible: isElementVisible(candidate),
  2815. })),
  2816. };
  2817. }
  2818. button.click();
  2819. return { clicked: true, rows: [] };
  2820. },
  2821. kind,
  2822. textIncludes,
  2823. TID_V4_BACKGROUND_WORK_CANCEL,
  2824. );
  2825. return latest.clicked;
  2826. },
  2827. {
  2828. interval: 250,
  2829. timeout: 30000,
  2830. timeoutMsg: `没有点击到 background control stop button: ${JSON.stringify(latest)}`,
  2831. },
  2832. );
  2833. }
  2834. async function getBackgroundTaskControlRows({
  2835. visibleOnly,
  2836. }: {
  2837. visibleOnly: boolean;
  2838. }): Promise<BackgroundTaskControlRowSnapshot[]> {
  2839. return browser.execute((filterVisible) => {
  2840. // display: contents 祖先没有布局盒但子元素仍可见,不能用祖先零尺寸判隐藏。
  2841. const isElementVisible = (element: HTMLElement) =>
  2842. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  2843. return Array.from(document.querySelectorAll<HTMLElement>("[data-background-task-kind]"))
  2844. .map((row) => ({
  2845. buttonDisabled: row.querySelector<HTMLButtonElement>("button")?.disabled ?? false,
  2846. kind: row.getAttribute("data-background-task-kind"),
  2847. text: row.innerText.replace(/\u00a0/g, " ").trim(),
  2848. visible: isElementVisible(row),
  2849. }))
  2850. .filter((row) => !filterVisible || row.visible);
  2851. }, visibleOnly);
  2852. }
  2853. async function stopIfBusy() {
  2854. const snapshot = await getV4ConversationState().catch(() => null);
  2855. if (snapshot?.state !== "streaming" || snapshot.stopRequested) {
  2856. return;
  2857. }
  2858. await browser.keys(["Escape"]).catch(() => undefined);
  2859. await waitForV4ConversationState(
  2860. (candidate) => candidate.state !== "streaming" || candidate.stopRequested,
  2861. "background E2E 收尾时没有停止当前运行",
  2862. 30000,
  2863. ).catch(() => undefined);
  2864. }
  2865. function assertBackgroundToolStepTelemetry(
  2866. reports: ConversationTelemetryReport[],
  2867. childToolCallId: string,
  2868. ): void {
  2869. const backgroundSteps = reports.filter(
  2870. (report) =>
  2871. report.element_name === "agent_step" &&
  2872. (report.event_extra_detail as Record<string, unknown> | undefined)?.agent_role ===
  2873. "background subagent",
  2874. );
  2875. expect(backgroundSteps).toHaveLength(2);
  2876. const detail = backgroundSteps[0]?.event_extra_detail as Record<string, unknown> | undefined;
  2877. expect(detail).toMatchObject({
  2878. agent_role: "background subagent",
  2879. step_type: "tool_call",
  2880. status: "success",
  2881. tool_name: "Bash",
  2882. loop_index: "1",
  2883. token_usage_scope: "",
  2884. total_tokens: "0",
  2885. });
  2886. expect(typeof detail?.agent_id).toBe("string");
  2887. expect(String(detail?.agent_id)).not.toHaveLength(0);
  2888. expect(typeof detail?.model_name).toBe("string");
  2889. expect(detail?.model_name).not.toBe("");
  2890. expect(typeof detail?.model_provider).toBe("string");
  2891. expect(detail?.model_provider).not.toBe("");
  2892. expect(typeof detail?.provider_name).toBe("string");
  2893. expect(detail?.provider_name).not.toBe("");
  2894. expect(typeof backgroundSteps[0]?.message_id).toBe("string");
  2895. expect(backgroundSteps[0]?.message_id).not.toBe("");
  2896. expect(typeof backgroundSteps[0]?.talk_id).toBe("string");
  2897. expect(backgroundSteps[0]?.talk_id).not.toBe("");
  2898. expect(String(detail?.tool_call_id)).toBe(
  2899. `tool_subagent_${String(detail?.agent_id)}_${childToolCallId}`,
  2900. );
  2901. // 两个 fixture child 请求各 input=128,tool_use output=16、最终 text output=12。
  2902. // usage 只出现在收口 Agent step,不能复制到 child Bash,也不能串到后续 main turn。
  2903. const aggregate = backgroundSteps[1]!;
  2904. const aggregateDetail = aggregate.event_extra_detail as Record<string, unknown>;
  2905. expect(aggregateDetail).toMatchObject({
  2906. agent_role: "background subagent",
  2907. agent_id: detail?.agent_id,
  2908. step_type: "tool_call",
  2909. tool_name: "Agent",
  2910. status: "success",
  2911. loop_index: "2",
  2912. token_usage_scope: "subagent_requests",
  2913. model_request_count: "2",
  2914. input_tokens: "256",
  2915. output_tokens: "28",
  2916. total_tokens: "284",
  2917. model_name: detail?.model_name,
  2918. model_provider: detail?.model_provider,
  2919. provider_name: detail?.provider_name,
  2920. });
  2921. expect(aggregateDetail.tool_call_id).toBe(
  2922. `tool_subagent_${String(detail?.agent_id)}_${String(aggregateDetail.parent_tool_call_id)}`,
  2923. );
  2924. const completions = reports.filter((report) => report.element_name === "message_completion");
  2925. expect(aggregate.message_id).toBe(completions[0]?.message_id);
  2926. expect(aggregate.message_id).toBe(backgroundSteps[0]?.message_id);
  2927. expect(reports.indexOf(aggregate)).toBeGreaterThan(reports.indexOf(completions[0]!));
  2928. for (const completion of completions) {
  2929. expect(completion.message_id).toMatch(
  2930. /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
  2931. );
  2932. expect(
  2933. reports.filter(
  2934. (report) =>
  2935. report.element_name === "agent_step" &&
  2936. report.message_id === completion.message_id &&
  2937. !(report.event_extra_detail as Record<string, unknown>)?.agent_role,
  2938. ).length,
  2939. ).toBeGreaterThan(0);
  2940. }
  2941. expect(
  2942. reports.filter(
  2943. (report) =>
  2944. report.element_name === "message_completion" &&
  2945. ["child_session_id", "parent_tool_call_id"].some((key) =>
  2946. Object.hasOwn(
  2947. (report.event_extra_detail as Record<string, unknown> | undefined) ?? {},
  2948. key,
  2949. ),
  2950. ),
  2951. ),
  2952. ).toHaveLength(0);
  2953. }
  2954. function assertMainCompletionAgentCompositions(
  2955. reports: ConversationTelemetryReport[],
  2956. expectedCompositions: string[],
  2957. ): void {
  2958. const completions = reports.filter((report) => report.element_name === "message_completion");
  2959. expect(completions).toHaveLength(expectedCompositions.length);
  2960. expect(
  2961. completions.map(
  2962. (report) =>
  2963. (report.event_extra_detail as Record<string, unknown> | undefined)?.agent_composition,
  2964. ),
  2965. ).toEqual(expectedCompositions);
  2966. const messageIds = completions.map((report) => String(report.message_id ?? ""));
  2967. expect(messageIds.every((messageId) => messageId.length > 0)).toBe(true);
  2968. expect(new Set(messageIds).size).toBe(messageIds.length);
  2969. }
  2970. function assertMainCompletionMessageSources(
  2971. reports: ConversationTelemetryReport[],
  2972. expectedSources: string[],
  2973. ): void {
  2974. const completions = reports.filter((report) => report.element_name === "message_completion");
  2975. expect(completions).toHaveLength(expectedSources.length);
  2976. expect(
  2977. completions.map(
  2978. (report) =>
  2979. (report.event_extra_detail as Record<string, unknown> | undefined)?.message_source,
  2980. ),
  2981. ).toEqual(expectedSources);
  2982. }