conversation-session-background.test.ts 128 KB

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