conversation-session-background.test.ts 125 KB

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