v4-conversation.ts 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873
  1. import { selectCombinedComposerThoughtLevel } from "./composer-model-picker.js";
  2. /* eslint-disable max-lines -- v4 conversation e2e helper 集中承载 pane/composer/queue/分屏等全部定位与断言原语,拆分会让 spec 的导入面漂移。 */
  3. // v4 竖切(protocol-v4)conversation e2e helper。
  4. // 与旧 conversation-session.ts 的区别:所有定位走 TID_V4_* 常量(testid contract v2,
  5. // 带 paneId 维度),状态断言读 v4 pane 的 data-* 投影属性,不再依赖旧 ChatView DOM。
  6. // 旧 helper 的登录/工作区/provider 部分继续复用(desktop-app.ts / upstream-provider.ts)。
  7. import { encodeCustomModelValue } from "@zcode/shared";
  8. import {
  9. TID_CHAT_MODE_SELECT_ITEM,
  10. TID_CHAT_MODE_SELECT_TRIGGER,
  11. TID_CHAT_SUMMARY_PANEL,
  12. TID_CHAT_MODEL_SELECT_GROUP,
  13. TID_CHAT_MODEL_SELECT_ITEM,
  14. TID_CHAT_MODEL_SELECT_TRIGGER,
  15. TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM,
  16. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  17. TID_PROMPT_SUGGESTION_OPTION,
  18. TID_PROMPT_SUGGESTION_PANEL,
  19. TID_LOGIN_API_KEY_CONTINUE_BUTTON,
  20. TID_LOGIN_API_KEY_INPUT,
  21. TID_LOGIN_USE_API_KEY_BUTTON,
  22. TID_TASK_ITEM,
  23. TID_TASK_NEW_BUTTON,
  24. TID_V4_AUTODRAIN_TOGGLE,
  25. TID_V4_ATTACHMENT,
  26. TID_V4_BACKGROUND_WORK_ITEM,
  27. TID_V4_COMPOSER,
  28. TID_V4_COMPOSER_BACKGROUND_WORK_TRIGGER,
  29. TID_V4_COMPOSER_CLEAR_QUEUE_SEND,
  30. TID_V4_COMPOSER_INPUT,
  31. TID_V4_COMPOSER_KEEP_QUEUE_SEND,
  32. TID_V4_COMPOSER_SEND,
  33. TID_V4_DELETE_SESSION,
  34. TID_V4_EDIT,
  35. TID_V4_EDIT_INPUT,
  36. TID_V4_EDIT_REWIND_WORKSPACE,
  37. TID_V4_EDIT_SUBMIT,
  38. TID_V4_EDIT_WORKSPACE_CONFLICT_CONVERSATION_ONLY,
  39. TID_V4_EDIT_WORKSPACE_CONFLICT_DIALOG,
  40. TID_V4_FOLLOWUP_TOGGLE,
  41. TID_V4_MODEL_CONFIG,
  42. TID_V4_PAUSED_QUEUE_SEND_DIALOG,
  43. TID_V4_PANE_SHELL,
  44. TID_V4_QUEUE,
  45. TID_V4_QUEUE_ITEM,
  46. TID_V4_QUEUE_PAUSED_BANNER,
  47. TID_V4_QUEUE_RESUME,
  48. TID_V4_RENAME_INPUT,
  49. TID_V4_RENAME_SUBMIT,
  50. TID_V4_ROW,
  51. TID_V4_ROW_ATTACHMENTS,
  52. TID_V4_SESSION_PANE,
  53. TID_V4_SESSION_TITLE,
  54. TID_V4_SPLIT_CLOSE,
  55. TID_V4_SPLIT_DOWN,
  56. TID_V4_SPLIT_DIVIDER,
  57. TID_V4_SPLIT_OPEN,
  58. TID_V4_TASK_OPEN_IN_SPLIT,
  59. TID_V4_STOP,
  60. TID_V4_TIMELINE,
  61. TID_V4_TIMELINE_BOTTOM,
  62. TID_V4_TURN_NAVIGATOR,
  63. TID_V4_TURN_NAVIGATOR_ITEM,
  64. TID_V4_TURN_NAVIGATOR_TOOLTIP,
  65. testId,
  66. } from "@zcode/shared/test-ids";
  67. import {
  68. clickTestIdByDom,
  69. DEFAULT_WORKSPACE,
  70. dispatchMouseDownByExactTestId,
  71. setCurrentElectronRendererContentSize,
  72. setInputValueByTestIdDom,
  73. waitForDefaultWorkspaceReady,
  74. } from "./desktop-app.js";
  75. import {
  76. ensureUpstreamProviderForE2E,
  77. selectUpstreamModel,
  78. selectUpstreamThoughtLevel,
  79. } from "./upstream-provider.js";
  80. import { readV4ChatRootSnapshotInBrowser } from "./conversation-session-chat-root-snapshot-script.js";
  81. import { getTaskStoreSnapshot as readTaskStoreSnapshotForDiagnostics } from "./conversation-session-store.js";
  82. import { sel } from "./selectors.js";
  83. import { skipOccupationOnboardingIfPresent } from "./occupation-onboarding.js";
  84. import { startDraftFromProject, waitForProjectRow } from "#e2e/helpers/project-sidebar";
  85. export const LOGIN_API_KEY = "e2e-login-api-key";
  86. export const E2E_REPLY_TOKEN = "upstream-e2e-ok";
  87. interface PrepareV4ConversationE2EOptions {
  88. resetDraftBeforeProvider?: boolean;
  89. skipProvider?: boolean;
  90. /** 跳过 ensureV4ShellReady 的 ZCodeProject 等待。已登录冷启(真实凭据 seed 后 reloadSession)
  91. * 的 app 按 startupWorkspace 语义落在 conversation backing workspace,ZCodeProject 永远不出现;
  92. * 调用方需自行等待 v4 shell 就绪(如侧栏新任务按钮)。见 ANALYSIS r3-rerun §46。 */
  93. skipShellReady?: boolean;
  94. }
  95. /** 单 pane 竖切固定 paneId(V4ChatPane 写死 workspace-main)。 */
  96. export const V4_MAIN_PANE_ID = "workspace-main";
  97. export interface V4PaneSnapshot {
  98. /** data-session-id;draft 表示未绑定 CLI session。 */
  99. sessionId: string | null;
  100. initialDraftProvider: string;
  101. initialDraftModel: string;
  102. /** stop 按钮是否存在(= projection.control.canStop)。 */
  103. canStop: boolean;
  104. /** timeline 全部行文本(虚拟滚动下为当前渲染窗口内的行)。 */
  105. timelineText: string;
  106. rowCount: number;
  107. }
  108. export interface V4CompactMarkerSnapshot {
  109. origin: string | null;
  110. rowId: number | null;
  111. status: string | null;
  112. text: string;
  113. }
  114. export interface V4ConversationStateSnapshot {
  115. activeInputId: string | null;
  116. modelSwitchPending: boolean;
  117. queueCount: number;
  118. runtimeStatus: string | null;
  119. sessionId: string | null;
  120. state: string | null;
  121. stopRequested: boolean;
  122. targetId: string | null;
  123. targetObjective: string | null;
  124. targetStatus: string | null;
  125. taskId: string | null;
  126. }
  127. export interface V4MessageSnapshot {
  128. id: string | null;
  129. role: "assistant" | "user";
  130. text: string;
  131. }
  132. export async function prepareV4ConversationE2E(options: PrepareV4ConversationE2EOptions = {}) {
  133. if (!options.skipShellReady) {
  134. await ensureV4ShellReady();
  135. }
  136. if (!options.skipShellReady || options.resetDraftBeforeProvider) {
  137. // Provider helper 也校验固定 cwd,必须先返回夹具项目,且不能把模型写入上一条会话。
  138. await ensureV4PreparationDraft(options);
  139. }
  140. if (!options.skipProvider) {
  141. await ensureUpstreamProviderForE2E({ skipToolbarSelection: true });
  142. }
  143. await ensureV4PreparationDraft(options);
  144. if (!options.skipShellReady) {
  145. await waitForDefaultWorkspaceReady(30000);
  146. }
  147. if (!options.skipProvider) {
  148. // 新 Composer 会保留已经初始化的空选择。仅写 Recent 不能覆盖这个草稿;
  149. // 测试准备必须像用户一样选择目标模型和档位,不能依赖旧初始化副作用。
  150. await selectUpstreamModel();
  151. await selectUpstreamThoughtLevel();
  152. }
  153. }
  154. async function ensureV4ShellReady() {
  155. try {
  156. // 新隔离 profile 的职业引导会遮住工作区,先复用真实 UI 跳过流程。
  157. await skipOccupationOnboardingIfPresent();
  158. await waitForProjectRow(DEFAULT_WORKSPACE, { timeout: 30000 });
  159. return;
  160. } catch (error) {
  161. if (!(await hasApiKeyLoginButton())) {
  162. throw error;
  163. }
  164. await loginWithApiKey();
  165. await skipOccupationOnboardingIfPresent();
  166. await waitForProjectRow(DEFAULT_WORKSPACE, { timeout: 30000 });
  167. }
  168. }
  169. async function ensureV4PreparationDraft(options: PrepareV4ConversationE2EOptions) {
  170. // Bug 根因:全局新建会创建独立 cwd;反复点击会让固定目录夹具与 Agent 工作区分离。
  171. // 只按实际 cwd 复用空草稿;为补项目标签而新建会打断冷启动预热,导致首发失败。
  172. // 其他 cwd 或已有内容才走项目级新建;显式全局新建 helper 保持原语义。
  173. const ready = await browser.execute(
  174. (inputId, paneId, stopId, workspacePath) => {
  175. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneId}"]`);
  176. const input = pane?.querySelector<HTMLElement>(`[data-testid="${inputId}"]`);
  177. const activePath = (
  178. window as Window & {
  179. __zcodeTabStoreE2E?: { getState(): { activeWorkspacePath?: string | null } };
  180. }
  181. ).__zcodeTabStoreE2E?.getState().activeWorkspacePath;
  182. return Boolean(
  183. pane?.dataset.sessionId === "draft" &&
  184. input?.getClientRects().length &&
  185. !input.textContent?.trim() &&
  186. !pane.querySelector(`[data-testid="${stopId}"]`) &&
  187. (!workspacePath || activePath === workspacePath),
  188. );
  189. },
  190. TID_V4_COMPOSER_INPUT,
  191. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  192. TID_V4_STOP,
  193. options.skipShellReady ? null : DEFAULT_WORKSPACE,
  194. );
  195. if (ready) return;
  196. if (options.skipShellReady) {
  197. await startNewV4Draft();
  198. } else {
  199. await startDraftFromProject(DEFAULT_WORKSPACE);
  200. }
  201. }
  202. async function hasApiKeyLoginButton() {
  203. const exists = await browser
  204. .execute(
  205. (currentTestId) => Boolean(document.querySelector(`[data-testid="${currentTestId}"]`)),
  206. TID_LOGIN_USE_API_KEY_BUTTON,
  207. )
  208. .catch(() => false);
  209. return Boolean(exists);
  210. }
  211. export async function loginWithApiKey() {
  212. await clickTestIdByDom(TID_LOGIN_USE_API_KEY_BUTTON, {
  213. timeout: 30000,
  214. timeoutMsg: "欢迎页没有出现 API Key 登录入口",
  215. });
  216. await setInputValueByTestIdDom(TID_LOGIN_API_KEY_INPUT, LOGIN_API_KEY, {
  217. timeout: 15000,
  218. timeoutMsg: "API Key 登录输入框没有出现",
  219. });
  220. await browser.waitUntil(
  221. async () =>
  222. browser.execute((continueButtonTestId) => {
  223. const button = document.querySelector<HTMLElement>(
  224. `[data-testid="${continueButtonTestId}"]`,
  225. );
  226. return button instanceof HTMLButtonElement && !button.disabled;
  227. }, TID_LOGIN_API_KEY_CONTINUE_BUTTON),
  228. {
  229. timeout: 15000,
  230. timeoutMsg: "API Key 登录继续按钮没有变为可用",
  231. },
  232. );
  233. await clickTestIdByDom(TID_LOGIN_API_KEY_CONTINUE_BUTTON, {
  234. timeout: 15000,
  235. timeoutMsg: "API Key 登录继续按钮没有出现或不可点击",
  236. });
  237. }
  238. /** 新建草稿:点侧栏新任务按钮,等 v4 pane 回到 draft 态。 */
  239. export async function startNewV4Draft() {
  240. await clickTestIdByDom(TID_TASK_NEW_BUTTON, {
  241. timeout: 15000,
  242. timeoutMsg: "侧栏新任务按钮没有出现或不可点击",
  243. });
  244. await waitForV4Pane(
  245. (snapshot) => snapshot.sessionId === "draft",
  246. "新建任务后 v4 pane 没有回到 draft 态",
  247. );
  248. }
  249. export function getV4PaneSnapshot(paneId: string = V4_MAIN_PANE_ID): Promise<V4PaneSnapshot> {
  250. return browser.execute(
  251. (paneTestId, stopTestId, timelineTestId, rowPrefix) => {
  252. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  253. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  254. return {
  255. sessionId: pane?.getAttribute("data-session-id") ?? null,
  256. initialDraftProvider: pane?.getAttribute("data-initial-draft-provider") ?? "",
  257. initialDraftModel: pane?.getAttribute("data-initial-draft-model") ?? "",
  258. canStop: Boolean(pane?.querySelector(`[data-testid="${stopTestId}"]`)),
  259. timelineText: (timeline?.innerText ?? "").replace(/ /g, " "),
  260. rowCount: pane?.querySelectorAll(`[data-testid^="${rowPrefix}-"]`).length ?? 0,
  261. };
  262. },
  263. testId(TID_V4_SESSION_PANE, paneId),
  264. TID_V4_STOP,
  265. TID_V4_TIMELINE,
  266. TID_V4_ROW,
  267. );
  268. }
  269. export async function waitForV4Pane(
  270. predicate: (snapshot: V4PaneSnapshot) => boolean,
  271. timeoutMsg: string,
  272. timeout = 30000,
  273. paneId: string = V4_MAIN_PANE_ID,
  274. ) {
  275. let latest: V4PaneSnapshot | null = null;
  276. try {
  277. await browser.waitUntil(
  278. async () => {
  279. latest = await getV4PaneSnapshot(paneId);
  280. return predicate(latest);
  281. },
  282. { timeout, timeoutMsg },
  283. );
  284. } catch (error) {
  285. latest = await getV4PaneSnapshot(paneId);
  286. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  287. cause: error,
  288. });
  289. }
  290. // 原因:会话切换时 pane 可能短暂经过 draft。waitUntil 已命中目标快照后若再读一次 DOM,
  291. // 调用方拿到的可能反而是下一帧过渡态,造成“条件通过但返回值不满足条件”的假失败。
  292. return latest ?? getV4PaneSnapshot(paneId);
  293. }
  294. export async function waitForV4ConversationState(
  295. predicate: (snapshot: V4ConversationStateSnapshot) => boolean,
  296. timeoutMsg: string,
  297. timeout = 30000,
  298. ) {
  299. let latest: V4ConversationStateSnapshot | null = null;
  300. try {
  301. await browser.waitUntil(
  302. async () => {
  303. latest = await getV4ConversationState();
  304. return predicate(latest);
  305. },
  306. { timeout, timeoutMsg },
  307. );
  308. } catch (error) {
  309. latest = await getV4ConversationState();
  310. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  311. cause: error,
  312. });
  313. }
  314. // 修复原因:命中 predicate 后再次读取会跨过 running/completed 瞬时边界,
  315. // 让调用方拿到与 waitUntil 判定不一致的状态。
  316. return latest ?? getV4ConversationState();
  317. }
  318. export async function getV4ConversationState(): Promise<V4ConversationStateSnapshot> {
  319. const browserSnapshot = await browser.execute(
  320. readV4ChatRootSnapshotInBrowser,
  321. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  322. TID_V4_QUEUE_ITEM,
  323. TID_V4_STOP,
  324. );
  325. if (browserSnapshot.bridgeError) {
  326. throw new Error(
  327. `无法读取 V4 conversation workspace: ${browserSnapshot.bridgeError}; ` +
  328. `workspaceKey=${browserSnapshot.workspaceKey}; paneSessionId=${browserSnapshot.paneSessionId}`,
  329. );
  330. }
  331. if (!browserSnapshot.taskId) {
  332. return {
  333. activeInputId: null,
  334. modelSwitchPending: browserSnapshot.modelSwitchPending,
  335. queueCount: browserSnapshot.queueCount,
  336. runtimeStatus: browserSnapshot.runtimeStatus,
  337. sessionId: null,
  338. state: browserSnapshot.runtimeStatus === "streaming" ? "streaming" : "idle",
  339. stopRequested: false,
  340. targetId: null,
  341. targetObjective: null,
  342. targetStatus: null,
  343. taskId: null,
  344. };
  345. }
  346. const taskStore = await readTaskStoreSnapshotForDiagnostics(
  347. browserSnapshot.taskId,
  348. browserSnapshot.workspaceKey ?? undefined,
  349. );
  350. if (!taskStore.workspaceKey) {
  351. throw new Error(
  352. `无法读取 V4 conversation task: ${taskStore.error}; ` +
  353. `workspaceKey=${browserSnapshot.workspaceKey}; taskId=${browserSnapshot.taskId}`,
  354. );
  355. }
  356. const goalProjection = await browser.execute(
  357. (paneTestId, panelTestId) => {
  358. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  359. const panel = pane?.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  360. if (!panel) return null;
  361. return {
  362. objective: panel.getAttribute("data-goal-objective"),
  363. status: panel.getAttribute("data-goal-status"),
  364. };
  365. },
  366. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  367. TID_CHAT_SUMMARY_PANEL,
  368. );
  369. const hasBlockingGoalWork =
  370. goalProjection?.status === "active" || goalProjection?.status === "verifying";
  371. const effectiveRuntimeStatus =
  372. browserSnapshot.runtimeStatus === "streaming" ? "streaming" : taskStore.runtimeStatus;
  373. return {
  374. activeInputId: taskStore.activeInputId,
  375. modelSwitchPending: browserSnapshot.modelSwitchPending,
  376. queueCount: browserSnapshot.queueCount,
  377. runtimeStatus: effectiveRuntimeStatus,
  378. sessionId: browserSnapshot.taskId,
  379. state: effectiveRuntimeStatus === "streaming" || hasBlockingGoalWork ? "streaming" : "idle",
  380. stopRequested: taskStore.stopRequested,
  381. targetId: taskStore.taskMeta?.targetId ?? null,
  382. targetObjective: goalProjection?.objective ?? taskStore.taskMeta?.targetObjective ?? null,
  383. targetStatus: goalProjection?.status ?? taskStore.taskMeta?.targetStatus ?? null,
  384. taskId: browserSnapshot.taskId,
  385. };
  386. }
  387. /**
  388. * v4 composer 输入(M5 起为 Lexical contenteditable):写入走
  389. * setInputValueByTestIdDom 的 __zcodeLexicalInputE2E bridge 分支(驱动真实 editor state)。
  390. */
  391. export async function sendV4Prompt(prompt: string) {
  392. await setV4ComposerText(prompt);
  393. const mainPaneTestId = testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID);
  394. try {
  395. await browser.waitUntil(
  396. async () =>
  397. browser.execute(
  398. (paneTestId, sendButtonTestId) => {
  399. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  400. const button = pane?.querySelector<HTMLButtonElement>(
  401. `[data-testid="${sendButtonTestId}"]`,
  402. );
  403. return Boolean(button && !button.disabled);
  404. },
  405. mainPaneTestId,
  406. TID_V4_COMPOSER_SEND,
  407. ),
  408. {
  409. timeout: 30000,
  410. timeoutMsg: "v4 发送按钮没有变为可用",
  411. },
  412. );
  413. } catch (error) {
  414. // 修复原因:会话切换竞态发生时,单独的“按钮 disabled”无法区分 projection connecting、
  415. // 上一轮仍在运行或 composer 未写入;把失败瞬间的 DOM 状态带回日志,避免继续靠猜测修复。
  416. const diagnostics = await browser.execute(
  417. (paneTestId, inputTestId, sendTestId, stopTestId) => {
  418. const panes = Array.from(
  419. document.querySelectorAll<HTMLElement>(`[data-testid^="${paneTestId}"]`),
  420. );
  421. const active = document.activeElement as HTMLElement | null;
  422. return {
  423. activeTestId: active?.getAttribute("data-testid") ?? null,
  424. panes: panes.map((pane) => {
  425. const input = pane.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  426. const send = pane.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  427. return {
  428. paneTestId: pane.getAttribute("data-testid"),
  429. sessionId: pane.getAttribute("data-session-id"),
  430. inputText: input?.innerText ?? input?.textContent ?? null,
  431. sendDisabled: send?.disabled ?? null,
  432. sendTitle: send?.getAttribute("title") ?? null,
  433. canStop: Boolean(pane.querySelector(`[data-testid="${stopTestId}"]`)),
  434. };
  435. }),
  436. };
  437. },
  438. TID_V4_SESSION_PANE,
  439. TID_V4_COMPOSER_INPUT,
  440. TID_V4_COMPOSER_SEND,
  441. TID_V4_STOP,
  442. );
  443. throw new Error(`v4 发送按钮没有变为可用; diagnostics=${JSON.stringify(diagnostics)}`, {
  444. cause: error,
  445. });
  446. }
  447. const submitResult = await browser.execute(
  448. (paneTestId, sendButtonTestId) => {
  449. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  450. const button = pane?.querySelector<HTMLButtonElement>(`[data-testid="${sendButtonTestId}"]`);
  451. if (!pane) return { submitted: false, reason: "pane-missing" };
  452. if (!button) return { submitted: false, reason: "button-missing" };
  453. if (button.disabled) return { submitted: false, reason: "button-disabled" };
  454. const form = button.closest("form");
  455. if (!form) {
  456. button.click();
  457. return { submitted: true, method: "click-fallback" };
  458. }
  459. let submitEventSeen = false;
  460. const onSubmit = () => {
  461. submitEventSeen = true;
  462. };
  463. form.addEventListener("submit", onSubmit, { capture: true, once: true });
  464. form.requestSubmit(button);
  465. return {
  466. submitted: submitEventSeen,
  467. method: "request-submit",
  468. reason: submitEventSeen ? undefined : "submit-event-not-seen",
  469. };
  470. },
  471. mainPaneTestId,
  472. TID_V4_COMPOSER_SEND,
  473. );
  474. if (!submitResult.submitted) {
  475. throw new Error(`v4 composer 没有派发 submit 事件: ${JSON.stringify(submitResult)}`);
  476. }
  477. }
  478. /**
  479. * 发送普通 prompt 并等待 renderer 明确接受:主 pane composer 清空且真实 user row 出现。
  480. * 不重试 submit,避免首发已进入 Host、但慢渲染尚未投影时重复发送同一条消息。
  481. */
  482. export async function sendV4PromptAndWaitAccepted(
  483. prompt: string,
  484. userMessageMarker: string,
  485. timeoutMsg: string,
  486. timeout = 60_000,
  487. ) {
  488. await sendV4Prompt(prompt);
  489. let latest: {
  490. composerText: string | null;
  491. paneExists: boolean;
  492. sendDisabled: boolean | null;
  493. sessionId: string | null;
  494. userMessageSeen: boolean;
  495. } | null = null;
  496. const readAcceptance = () =>
  497. browser.execute(
  498. (paneTestId, inputTestId, sendTestId, timelineTestId, marker) => {
  499. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  500. const input = pane?.querySelector<
  501. HTMLElement & { __zcodeLexicalInputE2E?: { getText: () => string } }
  502. >(`[data-testid="${inputTestId}"]`);
  503. const send = pane?.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  504. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  505. const userMessageSeen = Array.from(
  506. timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [],
  507. ).some(
  508. (row) =>
  509. row.classList.contains("group/user-row") &&
  510. (row.innerText || row.textContent || "").includes(marker),
  511. );
  512. return {
  513. composerText: input?.__zcodeLexicalInputE2E?.getText() ?? null,
  514. paneExists: Boolean(pane),
  515. sendDisabled: send?.disabled ?? null,
  516. sessionId: pane?.getAttribute("data-session-id") ?? null,
  517. userMessageSeen,
  518. };
  519. },
  520. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  521. TID_V4_COMPOSER_INPUT,
  522. TID_V4_COMPOSER_SEND,
  523. TID_V4_TIMELINE,
  524. userMessageMarker,
  525. );
  526. try {
  527. await browser.waitUntil(
  528. async () => {
  529. latest = await readAcceptance();
  530. return latest.composerText === "" && latest.userMessageSeen;
  531. },
  532. { timeout, timeoutMsg },
  533. );
  534. } catch (error) {
  535. latest = await readAcceptance().catch(() => latest);
  536. const state = await getV4ConversationState().catch((stateError) => ({
  537. error: stateError instanceof Error ? stateError.message : String(stateError),
  538. }));
  539. throw new Error(
  540. `${timeoutMsg}; acceptance=${JSON.stringify(latest)}; state=${JSON.stringify(state)}`,
  541. { cause: error },
  542. );
  543. }
  544. }
  545. /** 只写入 v4 composer,不触发发送。 */
  546. export async function setV4ComposerText(text: string) {
  547. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, text, {
  548. timeout: 15000,
  549. timeoutMsg: "v4 composer 输入框没有出现或不可输入",
  550. });
  551. }
  552. export async function waitForV4ComposerText(expected: string, timeoutMsg: string, timeout = 10000) {
  553. await browser.waitUntil(async () => (await getV4ComposerText()) === expected, {
  554. timeout,
  555. timeoutMsg,
  556. });
  557. }
  558. /** 点击 v4 composer 发送按钮(输入已由调用方写入,如 slash 命令)。 */
  559. export async function clickV4Send() {
  560. await browser.waitUntil(
  561. async () =>
  562. browser.execute((sendButtonTestId) => {
  563. const button = document.querySelector<HTMLButtonElement>(
  564. `[data-testid="${sendButtonTestId}"]`,
  565. );
  566. return Boolean(button && !button.disabled);
  567. }, TID_V4_COMPOSER_SEND),
  568. {
  569. timeout: 30000,
  570. timeoutMsg: "v4 发送按钮没有变为可用",
  571. },
  572. );
  573. await clickTestIdByDom(TID_V4_COMPOSER_SEND, {
  574. timeout: 15000,
  575. timeoutMsg: "v4 发送按钮没有出现或不可点击",
  576. });
  577. }
  578. export async function waitForV4TimelineContaining(text: string, timeout = 60000) {
  579. await waitForV4Pane(
  580. (snapshot) => snapshot.timelineText.includes(text),
  581. `v4 timeline 中没有出现: ${text}`,
  582. timeout,
  583. );
  584. }
  585. /**
  586. * 只等待当前 V4 pane 的 assistant 正文,避免用户 prompt 中的同名 marker
  587. * 抢先满足完成屏障。formal case 不应为此回退到 legacy conversation helper。
  588. */
  589. export async function waitForV4AssistantMessageContaining(
  590. text: string,
  591. timeout = 90000,
  592. paneId: string = V4_MAIN_PANE_ID,
  593. ) {
  594. let latestAssistantMessages: string[] = [];
  595. const readAssistantMessages = () =>
  596. browser.execute(
  597. (paneTestId, timelineTestId) => {
  598. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  599. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  600. return Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  601. .filter((row) => row.classList.contains("group/assistant-row"))
  602. .map((row) => row.innerText.replace(/\u00a0/g, " ").trim());
  603. },
  604. testId(TID_V4_SESSION_PANE, paneId),
  605. TID_V4_TIMELINE,
  606. );
  607. try {
  608. await browser.waitUntil(
  609. async () => {
  610. latestAssistantMessages = await readAssistantMessages();
  611. return latestAssistantMessages.some((message) => message.includes(text));
  612. },
  613. {
  614. timeout,
  615. timeoutMsg: `v4 assistant 消息中没有出现: ${text}`,
  616. },
  617. );
  618. } catch (error) {
  619. latestAssistantMessages = await readAssistantMessages().catch(() => latestAssistantMessages);
  620. throw new Error(
  621. `v4 assistant 消息中没有出现: ${text}; latest=${JSON.stringify(latestAssistantMessages)}`,
  622. { cause: error },
  623. );
  624. }
  625. }
  626. export function getV4Messages(role?: "assistant" | "user"): Promise<V4MessageSnapshot[]> {
  627. return browser.execute(
  628. (paneTestId, timelineTestId, selectedRole) => {
  629. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  630. const timeline = pane?.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  631. return Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  632. .map((element) => {
  633. const currentRole = element.classList.contains("group/user-row")
  634. ? "user"
  635. : element.classList.contains("group/assistant-row")
  636. ? "assistant"
  637. : null;
  638. return {
  639. id: element.getAttribute("data-row-id"),
  640. role: currentRole,
  641. text: element.innerText.replace(/\u00a0/g, " ").trim(),
  642. };
  643. })
  644. .filter(
  645. (message): message is V4MessageSnapshot =>
  646. message.role !== null && (!selectedRole || message.role === selectedRole),
  647. );
  648. },
  649. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  650. TID_V4_TIMELINE,
  651. role,
  652. );
  653. }
  654. export async function waitForV4UserMessageContaining(text: string) {
  655. let latestMessages: V4MessageSnapshot[] = [];
  656. try {
  657. await browser.waitUntil(
  658. async () => {
  659. latestMessages = await getV4Messages("user");
  660. return latestMessages.some((message) => message.text.includes(text));
  661. },
  662. {
  663. timeout: 60000,
  664. timeoutMsg: `v4 user 消息中没有出现: ${text}`,
  665. },
  666. );
  667. } catch (error) {
  668. const [state, composer, queue] = await Promise.all([
  669. getV4ConversationState().catch((stateError) => ({
  670. error: stateError instanceof Error ? stateError.message : String(stateError),
  671. })),
  672. getV4ComposerText().catch((composerError) =>
  673. composerError instanceof Error ? composerError.message : String(composerError),
  674. ),
  675. getV4QueueItems().catch((queueError) => [
  676. {
  677. queueItemId: "<queue-read-error>",
  678. text: queueError instanceof Error ? queueError.message : String(queueError),
  679. },
  680. ]),
  681. ]);
  682. throw new Error(
  683. `v4 user 消息中没有出现: ${text}; latestMessages=${JSON.stringify(latestMessages)}; state=${JSON.stringify(state)}; queue=${JSON.stringify(queue)}; composer=${JSON.stringify(composer)}`,
  684. { cause: error },
  685. );
  686. }
  687. }
  688. export async function assertVisibleV4UserMessagesNotContaining(text: string) {
  689. const messages = await getV4Messages("user");
  690. expect(messages.map((message) => message.text).join("\n")).not.toContain(text);
  691. }
  692. export async function clickV4Stop() {
  693. await clickTestIdByDom(TID_V4_STOP, {
  694. timeout: 30000,
  695. timeoutMsg: "v4 stop 按钮没有出现或不可点击",
  696. });
  697. }
  698. /** 点击第一个可见的 fork 按钮(完成态 assistant 行),返回是否点到。 */
  699. export async function clickFirstV4Fork() {
  700. const buttons = await browser.$$('[data-testid^="v4-fork-"]');
  701. for (const button of buttons) {
  702. await moveV4ForkRowIntoHoverState(button);
  703. if (!(await button.isDisplayed()) || !(await button.isEnabled())) {
  704. continue;
  705. }
  706. // Bug 根因:直接在 renderer 里调用 HTMLElement.click() 会绕过 WebDriver 的
  707. // 用户交互路径;Radix/React 组合控件在长批次中可能只更新视觉层而未提交 fork。
  708. // 使用 WebDriver 原生 click,保留同一个按钮和断言语义,确保触发真实 pointer/click 事件。
  709. await button.click();
  710. return true;
  711. }
  712. return false;
  713. }
  714. export async function waitForV4Fork(timeout = 60000) {
  715. await browser.waitUntil(
  716. async () => {
  717. const buttons = await browser.$$('[data-testid^="v4-fork-"]');
  718. for (const button of buttons) {
  719. await moveV4ForkRowIntoHoverState(button);
  720. if ((await button.isDisplayed()) && (await button.isEnabled())) {
  721. return true;
  722. }
  723. }
  724. return false;
  725. },
  726. { timeout, timeoutMsg: "v4 fork 按钮没有出现(assistant 行未完成?)" },
  727. );
  728. }
  729. async function moveV4ForkRowIntoHoverState(button: WebdriverIO.Element): Promise<void> {
  730. const rowTestId = await browser.execute(
  731. (element) => element.closest<HTMLElement>("[data-row-id]")?.dataset.rowId ?? null,
  732. button,
  733. );
  734. const row = rowTestId ? await browser.$(`[data-row-id="${rowTestId}"]`) : await button.$("..");
  735. // Bug 根因:assistant action toolbar 默认由 group-hover 隐藏,旧 helper 只检查 DOM
  736. // 存在就直接点隐藏按钮;长列表中该 click 不会触发真实 fork。先把所属 turn 移入
  737. // hover 状态,再用可见且 enabled 的按钮完成同一用户操作,不改变 case 证明。
  738. await row.moveTo();
  739. }
  740. /** 点击第一个可见的 edit 按钮(user 行),返回是否点到。 */
  741. export async function clickFirstV4Edit() {
  742. return browser.execute(() => {
  743. const btn = document.querySelector<HTMLButtonElement>('[data-testid^="v4-edit-"]');
  744. btn?.click();
  745. return Boolean(btn);
  746. });
  747. }
  748. export async function waitForV4Edit(timeout = 60000) {
  749. await browser.waitUntil(
  750. async () =>
  751. browser.execute((editPrefix) => {
  752. const exactPattern = new RegExp(`^${editPrefix}-\\d+$`);
  753. return Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).some(
  754. (candidate) => exactPattern.test(candidate.dataset.testid ?? ""),
  755. );
  756. }, TID_V4_EDIT),
  757. { timeout, timeoutMsg: "v4 edit 按钮没有出现(user 行未完成?)" },
  758. );
  759. }
  760. /** 读取 v4 queue 面板当前项数与文本。 */
  761. export function getV4QueueItems(): Promise<Array<{ queueItemId: string; text: string }>> {
  762. return browser.execute(() =>
  763. Array.from(document.querySelectorAll<HTMLElement>('li[data-testid^="v4-queue-item-"]'))
  764. // 修复原因:删除/编辑/立即发送按钮以及行内输入都共享
  765. // `v4-queue-item-*` 前缀和 data-queue-item-id;只按前缀会把一个 item
  766. // 统计成 4~5 个,误报 projection 没有显示 queue。列表项元素是唯一权威行。
  767. .filter((el) => el.hasAttribute("data-queue-item-id"))
  768. .map((el) => ({
  769. queueItemId: el.getAttribute("data-queue-item-id") ?? "",
  770. text: (el.innerText || "").replace(/ /g, " ").trim(),
  771. })),
  772. );
  773. }
  774. /** 读取 queue.autoDrain 权威 DOM 投影,供 fault/恢复 case 证明错误后不会自动消费。 */
  775. export function getV4QueueAutoDrain(): Promise<boolean | null> {
  776. return browser.execute((queueTestId) => {
  777. const queue = document.querySelector<HTMLElement>(`[data-testid="${queueTestId}"]`);
  778. const value = queue?.getAttribute("data-queue-auto-drain");
  779. return value === null || value === undefined ? null : value === "true";
  780. }, TID_V4_QUEUE);
  781. }
  782. export async function waitForV4QueueCount(expected: number, timeout = 30000) {
  783. await browser.waitUntil(async () => (await getV4QueueItems()).length === expected, {
  784. timeout,
  785. timeoutMsg: `v4 queue 项数没有达到 ${expected}`,
  786. });
  787. }
  788. /** 点击某 queue 项的删除按钮(按 queueItemId)。 */
  789. export async function clickV4QueueItemDelete(queueItemId: string) {
  790. return browser.execute((id) => {
  791. const btn = document.querySelector<HTMLButtonElement>(
  792. `[data-testid="v4-queue-item-delete-${id}"]`,
  793. );
  794. btn?.click();
  795. return Boolean(btn);
  796. }, queueItemId);
  797. }
  798. /** 点击某 queue 项的编辑按钮(按 queueItemId,撤回到 composer)。 */
  799. export async function clickV4QueueItemEdit(queueItemId: string, clickCount = 1) {
  800. return browser.execute(
  801. (id, count) => {
  802. const btn = document.querySelector<HTMLButtonElement>(
  803. `[data-testid="v4-queue-item-edit-${id}"]`,
  804. );
  805. for (let index = 0; index < count; index += 1) {
  806. btn?.click();
  807. }
  808. return Boolean(btn);
  809. },
  810. queueItemId,
  811. clickCount,
  812. );
  813. }
  814. /** 点击某 queue 项的立即发送按钮(按 queueItemId)。 */
  815. export async function clickV4QueueItemSendNow(queueItemId: string) {
  816. return browser.execute((id) => {
  817. const btn = document.querySelector<HTMLButtonElement>(
  818. `[data-testid="v4-queue-item-send-now-${id}"]`,
  819. );
  820. btn?.click();
  821. return Boolean(btn);
  822. }, queueItemId);
  823. }
  824. // ── 暂停队列发送确认与恢复(B06/B07/B14/B15/C08)──
  825. // 原因:旧 E2E 把 clear/keep 当作 composer 的两颗替代发送按钮;产品交互改成
  826. // 正常发送按钮先打开 modal 后,必须显式走“发送 → 等 modal → 选择”,否则测试会
  827. // 把只打开弹窗误判成消息已经提交。
  828. /** 暂停队列发送确认 modal 与两个操作按钮是否同时存在。 */
  829. export function hasV4PausedQueueSendDialog(): Promise<boolean> {
  830. return browser.execute(
  831. (dialogTestId, clearTestId, keepTestId) =>
  832. Boolean(
  833. document.querySelector(`[data-testid="${dialogTestId}"]`) &&
  834. document.querySelector(`[data-testid="${clearTestId}"]`) &&
  835. document.querySelector(`[data-testid="${keepTestId}"]`),
  836. ),
  837. TID_V4_PAUSED_QUEUE_SEND_DIALOG,
  838. TID_V4_COMPOSER_CLEAR_QUEUE_SEND,
  839. TID_V4_COMPOSER_KEEP_QUEUE_SEND,
  840. );
  841. }
  842. /** 等待正常发送按钮提交后出现暂停队列确认 modal。 */
  843. export async function waitForV4PausedQueueSendDialog(timeout = 30000) {
  844. await browser.waitUntil(async () => hasV4PausedQueueSendDialog(), {
  845. timeout,
  846. timeoutMsg: "暂停队列发送确认 modal 没有出现(清空/发送按钮缺失)",
  847. });
  848. }
  849. /** 通过正常发送按钮打开 modal,再选择“保留队列并发送”。 */
  850. export async function sendV4PausedQueueKeep(prompt: string) {
  851. await sendV4Prompt(prompt);
  852. await waitForV4PausedQueueSendDialog();
  853. await clickTestIdByDom(TID_V4_COMPOSER_KEEP_QUEUE_SEND, {
  854. timeout: 15000,
  855. timeoutMsg: "暂停队列确认 modal 的“发送消息”按钮没有出现或不可点击",
  856. });
  857. }
  858. /** 通过正常发送按钮打开 modal,再选择“清空队列并发送”。 */
  859. export async function sendV4PausedQueueClear(prompt: string) {
  860. await sendV4Prompt(prompt);
  861. await waitForV4PausedQueueSendDialog();
  862. await clickTestIdByDom(TID_V4_COMPOSER_CLEAR_QUEUE_SEND, {
  863. timeout: 15000,
  864. timeoutMsg: "暂停队列确认 modal 的“清空队列”按钮没有出现或不可点击",
  865. });
  866. }
  867. /** 暂停提示条与“继续”按钮是否同时存在。 */
  868. export function hasV4PausedQueueBanner(): Promise<boolean> {
  869. return browser.execute(
  870. (bannerTestId, resumeTestId) =>
  871. Boolean(
  872. document.querySelector(`[data-testid="${bannerTestId}"]`) &&
  873. document.querySelector(`[data-testid="${resumeTestId}"]`),
  874. ),
  875. TID_V4_QUEUE_PAUSED_BANNER,
  876. TID_V4_QUEUE_RESUME,
  877. );
  878. }
  879. export async function waitForV4PausedQueueBanner(timeout = 30000) {
  880. await browser.waitUntil(async () => hasV4PausedQueueBanner(), {
  881. timeout,
  882. timeoutMsg: "暂停队列提示条或“继续”按钮没有出现",
  883. });
  884. }
  885. /** 点击暂停队列提示条的“继续”,恢复 CLI FIFO 自动消费。 */
  886. export async function clickV4PausedQueueResume() {
  887. await waitForV4PausedQueueBanner();
  888. await clickTestIdByDom(TID_V4_QUEUE_RESUME, {
  889. timeout: 15000,
  890. timeoutMsg: "暂停队列提示条的“继续”按钮没有出现或不可点击",
  891. });
  892. }
  893. /** 读取后台工作面板项(workId + status)。 */
  894. export function getV4BackgroundWorks(): Promise<Array<{ workId: string; status: string | null }>> {
  895. return browser.execute((itemPrefix) => {
  896. return Array.from(
  897. document.querySelectorAll<HTMLElement>(`[data-testid^="${itemPrefix}-"]`),
  898. ).map((el) => ({
  899. workId: el.getAttribute("data-work-id") ?? "",
  900. status: el.getAttribute("data-work-status"),
  901. }));
  902. }, TID_V4_BACKGROUND_WORK_ITEM);
  903. }
  904. /** 读取 Composer 当前 session 的后台任务计数与响应式展示形态;无入口返回 null。 */
  905. export function getV4ComposerBackgroundWorkCounts(): Promise<{
  906. bashCount: number;
  907. workflowCount: number;
  908. subagentCount: number;
  909. totalCount: number;
  910. /** 入口点击的落点(docs/dynamic-workflow/presentation.md):"panel" | "workflow-run"。 */
  911. openTarget: string;
  912. typedVisible: boolean;
  913. compactVisible: boolean;
  914. } | null> {
  915. return browser.execute((triggerTestId) => {
  916. const trigger = document.querySelector<HTMLElement>(`[data-testid="${triggerTestId}"]`);
  917. if (!trigger) return null;
  918. const isVisible = (layout: string) => {
  919. const element = trigger.querySelector<HTMLElement>(
  920. `[data-composer-background-layout="${layout}"]`,
  921. );
  922. return Boolean(element && getComputedStyle(element).display !== "none");
  923. };
  924. return {
  925. bashCount: Number(trigger.dataset.backgroundBashCount ?? "0"),
  926. workflowCount: Number(trigger.dataset.backgroundWorkflowCount ?? "0"),
  927. subagentCount: Number(trigger.dataset.backgroundSubagentCount ?? "0"),
  928. totalCount: Number(trigger.dataset.backgroundTotalCount ?? "0"),
  929. openTarget: trigger.dataset.backgroundOpenTarget ?? "panel",
  930. typedVisible: isVisible("typed"),
  931. compactVisible: isVisible("compact"),
  932. };
  933. }, TID_V4_COMPOSER_BACKGROUND_WORK_TRIGGER);
  934. }
  935. /** Electron driver 不实现 WebDriver window/rect;通过主进程 BrowserWindow 调整 viewport。 */
  936. export async function setV4ElectronWindowSize(width: number, height: number) {
  937. // Bug 根因:外框和 renderer 内容区的差值随平台及 zoom 改变,固定误差会误报超时。
  938. // 复用精确绑定当前窗口的内容区 helper,同时保留尺寸应用失败的断言。
  939. await setCurrentElectronRendererContentSize(width, height);
  940. }
  941. /** 从 Composer 单一入口展开 Status panel,并直达所有非空后台类型区块。 */
  942. export async function openV4ComposerRunningBackgroundWorks(timeout = 30000) {
  943. await clickTestIdByDom(TID_V4_COMPOSER_BACKGROUND_WORK_TRIGGER, {
  944. timeout,
  945. timeoutMsg: "Composer 后台任务入口没有出现或不可点击",
  946. });
  947. await browser.waitUntil(
  948. async () =>
  949. browser.execute(
  950. (panelTestId, itemPrefix) => {
  951. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  952. const terminalCount = Number(panel?.dataset.runningTerminalCount ?? "0");
  953. const agentCount = Number(panel?.dataset.runningAgentCount ?? "0");
  954. const terminalTrigger = panel?.querySelector<HTMLElement>(
  955. '[data-status-section-trigger="terminal"]',
  956. );
  957. const agentTrigger = panel?.querySelector<HTMLElement>(
  958. '[data-status-section-trigger="agent"]',
  959. );
  960. return Boolean(
  961. panel?.dataset.state === "expanded" &&
  962. (terminalCount === 0 || terminalTrigger?.getAttribute("aria-expanded") === "true") &&
  963. (agentCount === 0 || agentTrigger?.getAttribute("aria-expanded") === "true") &&
  964. panel.querySelector(`[data-testid^="${itemPrefix}-"]`),
  965. );
  966. },
  967. TID_CHAT_SUMMARY_PANEL,
  968. TID_V4_BACKGROUND_WORK_ITEM,
  969. ),
  970. { timeout, timeoutMsg: "Composer 入口没有直达展开的终端/智能体明细" },
  971. );
  972. }
  973. /** 展开统一 status panel 的非空后台类型区块;定位只依赖结构化属性,不依赖中英文。 */
  974. export async function openV4RunningBackgroundWorks(timeout = 30000) {
  975. await browser.waitUntil(
  976. async () =>
  977. browser.execute(
  978. (panelTestId, itemPrefix) => {
  979. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  980. if (!panel || Number(panel.dataset.runningBackgroundCount ?? "0") < 1) {
  981. return false;
  982. }
  983. if (panel.dataset.state === "collapsed") {
  984. panel.querySelector<HTMLButtonElement>("button")?.click();
  985. return false;
  986. }
  987. const sections = [
  988. {
  989. count: Number(panel.dataset.runningTerminalCount ?? "0"),
  990. name: "terminal",
  991. },
  992. {
  993. count: Number(panel.dataset.runningAgentCount ?? "0"),
  994. name: "agent",
  995. },
  996. ];
  997. let allOpen = true;
  998. for (const section of sections) {
  999. if (section.count === 0) continue;
  1000. const trigger = panel.querySelector<HTMLButtonElement>(
  1001. `[data-status-section-trigger="${section.name}"]`,
  1002. );
  1003. if (!trigger) return false;
  1004. if (trigger.getAttribute("aria-expanded") !== "true") {
  1005. trigger.click();
  1006. allOpen = false;
  1007. }
  1008. }
  1009. return allOpen && Boolean(panel.querySelector(`[data-testid^="${itemPrefix}-"]`));
  1010. },
  1011. TID_CHAT_SUMMARY_PANEL,
  1012. TID_V4_BACKGROUND_WORK_ITEM,
  1013. ),
  1014. { timeout, timeoutMsg: "status panel 没有展开终端/智能体 background work" },
  1015. );
  1016. }
  1017. export function getLatestV4CommandAck(type: string): Promise<{
  1018. type: string;
  1019. status: string;
  1020. reasonCode?: string;
  1021. } | null> {
  1022. return browser.execute((commandType) => {
  1023. const entries =
  1024. (
  1025. window as Window & {
  1026. __zcodeV4CommandAcksE2E?: Array<{
  1027. type: string;
  1028. status: string;
  1029. reasonCode?: string;
  1030. }>;
  1031. }
  1032. ).__zcodeV4CommandAcksE2E ?? [];
  1033. return [...entries].reverse().find((entry) => entry.type === commandType) ?? null;
  1034. }, type);
  1035. }
  1036. /** 等待指定 v4 command 的结构化 ACK,避免业务断言把 command 卡住误报成模型无回复。 */
  1037. export async function waitForLatestV4CommandAck(type: string, timeout = 30000) {
  1038. let latest: Awaited<ReturnType<typeof getLatestV4CommandAck>> = null;
  1039. await browser.waitUntil(
  1040. async () => {
  1041. latest = await getLatestV4CommandAck(type);
  1042. return latest !== null;
  1043. },
  1044. { timeout, timeoutMsg: `v4 command 没有返回 ACK: ${type}` },
  1045. );
  1046. return latest!;
  1047. }
  1048. /** 点击某后台工作的取消按钮(cancelBackgroundWork 命令,按 workId)。 */
  1049. export async function clickV4BackgroundWorkCancel(workId: string) {
  1050. return browser.execute((id) => {
  1051. const btn = document.querySelector<HTMLButtonElement>(
  1052. `[data-testid="v4-background-work-cancel-${id}"]`,
  1053. );
  1054. btn?.click();
  1055. return Boolean(btn);
  1056. }, workId);
  1057. }
  1058. /** 点击会话删除按钮(deleteSession 命令)。 */
  1059. export async function clickV4DeleteSession() {
  1060. return clickTestIdByDom(TID_V4_DELETE_SESSION, {
  1061. timeout: 15000,
  1062. timeoutMsg: "v4 删除按钮没有出现",
  1063. });
  1064. }
  1065. /** 读取 Composer 当前 mode/模型选择显示。 */
  1066. export function getV4ModelConfig(): Promise<{
  1067. mode: string | null;
  1068. provider: string | null;
  1069. model: string | null;
  1070. source: string | null;
  1071. thought: string | null;
  1072. }> {
  1073. return browser.execute((modelTestId) => {
  1074. const el = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  1075. return {
  1076. mode: el?.getAttribute("data-mode") ?? null,
  1077. provider: el?.getAttribute("data-provider") ?? null,
  1078. model: el?.getAttribute("data-model") ?? null,
  1079. source: el?.getAttribute("data-source") ?? null,
  1080. thought: el?.getAttribute("data-thought") ?? null,
  1081. };
  1082. }, TID_V4_MODEL_CONFIG);
  1083. }
  1084. /** 等待当前 Composer 已从持久 Draft 完成 mode/模型选择初始化。 */
  1085. export async function waitForV4ComposerSelectionReady(timeout = 30_000) {
  1086. let latest = await getV4ModelConfig();
  1087. await browser.waitUntil(
  1088. async () => {
  1089. latest = await getV4ModelConfig();
  1090. return (
  1091. latest.source === "composer" &&
  1092. Boolean(latest.mode?.trim()) &&
  1093. Boolean(latest.provider?.trim()) &&
  1094. Boolean(latest.model?.trim())
  1095. );
  1096. },
  1097. {
  1098. timeout,
  1099. timeoutMsg: `v4 Composer 选择没有就绪: ${JSON.stringify(latest)}`,
  1100. },
  1101. );
  1102. }
  1103. /** 读取 draft 当前模型及其思考档位;V4 投影优先,legacy 目录仅作水合前 fallback。 */
  1104. export function getV4DraftThoughtState(workspacePath: string): Promise<{
  1105. current: string | null;
  1106. model: string | null;
  1107. values: string[];
  1108. }> {
  1109. return browser.execute(
  1110. (path, modelTestId) => {
  1111. const e2eWindow = window as Window & {
  1112. __zcodeSessionStoreE2E?: {
  1113. getState: () => {
  1114. getWorkspaceState?: (workspacePath: string) => {
  1115. configOptions?: Array<{
  1116. category?: string;
  1117. currentValue?: unknown;
  1118. options?: Array<{ value: string }>;
  1119. }>;
  1120. };
  1121. };
  1122. };
  1123. };
  1124. const options =
  1125. e2eWindow.__zcodeSessionStoreE2E?.getState().getWorkspaceState?.(path).configOptions ?? [];
  1126. const model = options.find((option) => option.category === "model");
  1127. const thought = options.find((option) => option.category === "thought_level");
  1128. const v4Config = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  1129. const v4ThoughtLevels = (v4Config?.dataset.thoughtLevels ?? "")
  1130. .split(",")
  1131. .map((value) => value.trim())
  1132. .filter(Boolean);
  1133. return {
  1134. current:
  1135. v4Config?.dataset.thought?.trim() ||
  1136. (typeof thought?.currentValue === "string" ? thought.currentValue : null),
  1137. model:
  1138. v4Config?.dataset.model?.trim() ||
  1139. (typeof model?.currentValue === "string" ? model.currentValue : null),
  1140. values:
  1141. v4ThoughtLevels.length > 0
  1142. ? v4ThoughtLevels
  1143. : (thought?.options?.map((option) => option.value) ?? []),
  1144. };
  1145. },
  1146. workspacePath,
  1147. TID_V4_MODEL_CONFIG,
  1148. );
  1149. }
  1150. /**
  1151. * 通过 composer 工具条切换模型 + 思考深度(switchModelConfig 命令)。
  1152. * M5:调试表单(provider/model/thought 文本框 + 应用)已被真实模型选择器替换——
  1153. * helper 适配为驱动 ModelConfigSelect(含 provider 分组二级菜单)与思考深度选择器,
  1154. * spec 的断言语义不变(config 投影更新为目标值)。
  1155. */
  1156. export async function switchV4Model(provider: string, model: string, thought: string) {
  1157. // 1) 模型:打开菜单 → (必要时展开 provider 分组子菜单)→ 点目标模型项。
  1158. const modelItemTestId = testId(
  1159. TID_CHAT_MODEL_SELECT_ITEM,
  1160. encodeCustomModelValue(provider, model),
  1161. );
  1162. const providerGroupTestIds = [
  1163. testId(TID_CHAT_MODEL_SELECT_GROUP, `registry-provider:${provider}`),
  1164. ];
  1165. // 模型菜单是受控 DropdownMenu(pointerdown 打开),element.click() 不触发;
  1166. // 与旧 upstream helper 同口径用 WebDriver 真实点击。
  1167. const modelTrigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  1168. await modelTrigger.waitForClickable({ timeout: 30000 });
  1169. await modelTrigger.click();
  1170. await browser.waitUntil(
  1171. async () =>
  1172. browser.execute(
  1173. (itemTestId, groupTestIds) => {
  1174. const item = document.querySelector<HTMLElement>(`[data-testid="${itemTestId}"]`);
  1175. if (item) {
  1176. item.click();
  1177. return true;
  1178. }
  1179. // 自定义 provider 模型在二级菜单:先触发分组展开(hover + click 双保险)。
  1180. const group = groupTestIds
  1181. .map((groupTestId) =>
  1182. document.querySelector<HTMLElement>(`[data-testid="${groupTestId}"]`),
  1183. )
  1184. .find((candidate): candidate is HTMLElement => Boolean(candidate));
  1185. if (!group) {
  1186. const providerTrigger = document.querySelector<HTMLElement>(
  1187. '[data-testid="composer-provider-trigger"]',
  1188. );
  1189. providerTrigger?.focus();
  1190. providerTrigger?.dispatchEvent(
  1191. new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }),
  1192. );
  1193. }
  1194. if (group) {
  1195. group.focus();
  1196. for (const eventName of ["pointerenter", "mouseenter", "mousemove"] as const) {
  1197. group.dispatchEvent(
  1198. new MouseEvent(eventName, {
  1199. bubbles: true,
  1200. cancelable: true,
  1201. view: window,
  1202. }),
  1203. );
  1204. }
  1205. group.click();
  1206. }
  1207. return false;
  1208. },
  1209. modelItemTestId,
  1210. providerGroupTestIds,
  1211. ),
  1212. {
  1213. timeout: 45000,
  1214. timeoutMsg: `v4 模型选择器没有出现目标模型项: ${provider}/${model}`,
  1215. },
  1216. );
  1217. // 模型 config 投影落定后再切思考深度:thought 命令的 provider/model 参数取自
  1218. // 最新投影,模型切换未回流前切 thought 会被 UI 跳过(config-empty 防御)。
  1219. await browser.waitUntil(async () => (await getV4ModelConfig()).model === model, {
  1220. timeout: 30000,
  1221. timeoutMsg: `模型切换后 config.model 投影没有更新为 ${model}`,
  1222. });
  1223. if (thought && (await selectCombinedComposerThoughtLevel(thought))) return;
  1224. if (!thought && (await modelTrigger.getAttribute("data-composer-combined-model")) === "true") {
  1225. await browser.keys("Escape");
  1226. return;
  1227. }
  1228. // 无 reasoning metadata 的 custom provider 不渲染 thought selector。协议类 E2E
  1229. // 传空值表示只切模型,不能把不存在的思考深度控件当作模型切换失败。
  1230. if (!thought) {
  1231. return;
  1232. }
  1233. // 2) 思考深度:Radix Select 的 item 在真实 pointer 事件上确认(element.click() 无效),
  1234. // trigger/item 都用 WebDriver 真实点击。
  1235. await selectRadixOption(
  1236. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  1237. testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thought),
  1238. `v4 思考深度选择器没有出现目标档位: ${thought}`,
  1239. );
  1240. }
  1241. /** Radix Select 通用驱动:真实点击 trigger 展开,item 需要完整 pointer 手势才会确认。 */
  1242. async function selectRadixOption(triggerTestId: string, itemTestId: string, timeoutMsg: string) {
  1243. const trigger = $(sel(triggerTestId));
  1244. await trigger.waitForClickable({ timeout: 30000 });
  1245. await trigger.click();
  1246. const item = $(sel(itemTestId));
  1247. try {
  1248. await item.waitForClickable({ timeout: 15000 });
  1249. } catch (error) {
  1250. throw new Error(timeoutMsg, { cause: error });
  1251. }
  1252. // Radix SelectItem 的确认:mouse 手势要求 trusted pointer 链路(合成事件被手势
  1253. // 判定忽略),键盘路径(item 聚焦 + Enter,SELECTION_KEYS)是自动化下最稳的确认方式。
  1254. const confirmResult = await browser.execute((currentTestId) => {
  1255. const element = document.querySelector<HTMLElement>(`[data-testid="${currentTestId}"]`);
  1256. if (!element) {
  1257. return {
  1258. ok: false,
  1259. reason: "item-missing",
  1260. testIds: Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  1261. .map((el) => el.dataset.testid ?? "")
  1262. .filter((id) => id.includes("select"))
  1263. .slice(0, 40),
  1264. };
  1265. }
  1266. element.focus();
  1267. const focused = document.activeElement === element;
  1268. element.dispatchEvent(
  1269. new KeyboardEvent("keydown", {
  1270. key: "Enter",
  1271. bubbles: true,
  1272. cancelable: true,
  1273. }),
  1274. );
  1275. return { ok: true, focused };
  1276. }, itemTestId);
  1277. if (!confirmResult || confirmResult.ok !== true) {
  1278. throw new Error(`${timeoutMsg}(item 确认阶段异常: ${JSON.stringify(confirmResult)})`);
  1279. }
  1280. // 选择生效 ⇔ SelectContent 卸载(item 消失);未关闭说明确认未生效,抛诊断。
  1281. await browser
  1282. .waitUntil(
  1283. async () =>
  1284. browser.execute(
  1285. (currentTestId) => !document.querySelector(`[data-testid="${currentTestId}"]`),
  1286. itemTestId,
  1287. ),
  1288. { timeout: 5000 },
  1289. )
  1290. .catch(() => {
  1291. throw new Error(`${timeoutMsg}(item 确认后菜单未关闭——选择未生效)`);
  1292. });
  1293. }
  1294. /** 读取 goal 横幅(data-goal-status / data-goal-objective 投影属性);无目标返回 null。 */
  1295. export function getV4GoalProjection(): Promise<{
  1296. status: string | null;
  1297. objective: string | null;
  1298. } | null> {
  1299. return browser.execute(
  1300. (paneTestId, paneId, panelTestId) => {
  1301. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}-${paneId}"]`);
  1302. const el = pane?.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  1303. if (!el) return null;
  1304. return {
  1305. status: el.getAttribute("data-goal-status"),
  1306. objective: el.getAttribute("data-goal-objective"),
  1307. };
  1308. },
  1309. TID_V4_SESSION_PANE,
  1310. V4_MAIN_PANE_ID,
  1311. TID_CHAT_SUMMARY_PANEL,
  1312. );
  1313. }
  1314. /** 打开 latest user query 行内编辑并填入新文本,但不提交。 */
  1315. export async function beginFirstV4UserQueryEdit(newText: string) {
  1316. let rowId: string | null = null;
  1317. let lastClickedRowId: string | null = null;
  1318. let lastClickedAt = 0;
  1319. await browser.waitUntil(
  1320. async () => {
  1321. const state = await browser.execute(
  1322. (editPrefix, editInputPrefix) => {
  1323. const actionPattern = new RegExp(`^${editPrefix}-(\\d+)$`);
  1324. const inputPattern = new RegExp(`^${editInputPrefix}-(\\d+)$`);
  1325. const testIds = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"));
  1326. const input = testIds
  1327. .filter((candidate) => inputPattern.test(candidate.dataset.testid ?? ""))
  1328. .at(-1);
  1329. if (input) {
  1330. return {
  1331. inputRowId: inputPattern.exec(input.dataset.testid ?? "")?.[1] ?? null,
  1332. actionRowId: null,
  1333. };
  1334. }
  1335. const action = testIds
  1336. .filter((candidate) => actionPattern.test(candidate.dataset.testid ?? ""))
  1337. .at(-1);
  1338. return {
  1339. inputRowId: null,
  1340. actionRowId: actionPattern.exec(action?.dataset.testid ?? "")?.[1] ?? null,
  1341. };
  1342. },
  1343. TID_V4_EDIT,
  1344. TID_V4_EDIT_INPUT,
  1345. );
  1346. if (state.inputRowId) {
  1347. rowId = state.inputRowId;
  1348. return true;
  1349. }
  1350. if (!state.actionRowId) return false;
  1351. const now = Date.now();
  1352. if (lastClickedRowId !== state.actionRowId || now - lastClickedAt >= 500) {
  1353. lastClickedRowId = state.actionRowId;
  1354. lastClickedAt = now;
  1355. await clickTestIdByDom(testId(TID_V4_EDIT, state.actionRowId), {
  1356. timeout: 2000,
  1357. timeoutMsg: `v4 行内编辑按钮在 projection 收口时消失: rowId=${state.actionRowId}`,
  1358. }).catch(() => undefined);
  1359. }
  1360. return false;
  1361. },
  1362. {
  1363. timeout: 15000,
  1364. timeoutMsg: "v4 latest user edit action 出现后没有进入稳定行内编辑态",
  1365. interval: 100,
  1366. },
  1367. );
  1368. if (!rowId) {
  1369. throw new Error("v4 latest user edit action 没有出现");
  1370. }
  1371. // Bug 根因:compact success 会先投影成功 marker,再清理 active work;这两帧之间
  1372. // 旧 edit action 可能短暂可见后被 canEdit 收口撤下。单次 DOM click 会把刚打开的
  1373. // 本地 editing 状态随 onEdit 消失一起关闭。等待稳定 input,并在 action 恢复后重试。
  1374. await setInputValueByTestIdDom(testId(TID_V4_EDIT_INPUT, rowId), newText, {
  1375. timeout: 15000,
  1376. timeoutMsg: `v4 行内编辑输入框没有出现: rowId=${rowId}`,
  1377. });
  1378. return rowId;
  1379. }
  1380. /** 按真实行内编辑交互提交 latest user query,主 composer 草稿不参与。 */
  1381. export async function editFirstV4UserQuery(newText: string) {
  1382. const rowId = await beginFirstV4UserQueryEdit(newText);
  1383. await clickTestIdByDom(testId(TID_V4_EDIT_SUBMIT, rowId), {
  1384. timeout: 15000,
  1385. timeoutMsg: `v4 行内编辑提交按钮没有出现: rowId=${rowId}`,
  1386. });
  1387. return rowId;
  1388. }
  1389. /** 提交行内编辑的“对话 + 文件重置”路径。 */
  1390. export async function clickV4EditWorkspaceReset(rowId: string) {
  1391. await clickTestIdByDom(testId(TID_V4_EDIT_REWIND_WORKSPACE, rowId), {
  1392. timeout: 15000,
  1393. timeoutMsg: `v4 对话 + 文件重置按钮没有出现或不可点击: rowId=${rowId}`,
  1394. });
  1395. }
  1396. export async function waitForV4EditWorkspaceConflict(timeout = 30000) {
  1397. await browser.waitUntil(
  1398. async () =>
  1399. browser.execute(
  1400. (testIdValue) => Boolean(document.querySelector(`[data-testid="${testIdValue}"]`)),
  1401. TID_V4_EDIT_WORKSPACE_CONFLICT_DIALOG,
  1402. ),
  1403. { timeout, timeoutMsg: "v4 edit 文件冲突弹窗没有出现" },
  1404. );
  1405. }
  1406. export async function clickV4EditConflictConversationOnly() {
  1407. await clickTestIdByDom(TID_V4_EDIT_WORKSPACE_CONFLICT_CONVERSATION_ONLY, {
  1408. timeout: 15000,
  1409. timeoutMsg: "v4 edit 冲突弹窗没有出现仅重置对话按钮",
  1410. });
  1411. }
  1412. /** 读取结构化 compact marker;状态与来源只读 data-*,不依赖本地化 label。 */
  1413. export function getV4CompactMarkers(
  1414. paneId: string = V4_MAIN_PANE_ID,
  1415. ): Promise<V4CompactMarkerSnapshot[]> {
  1416. return browser.execute(
  1417. (paneTestId, rowPrefix) => {
  1418. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  1419. return Array.from(
  1420. pane?.querySelectorAll<HTMLElement>(
  1421. `[data-testid^="${rowPrefix}-"][data-row-kind="timelineMarker"][data-marker-type="compact"]`,
  1422. ) ?? [],
  1423. ).map((row) => {
  1424. const rowId = row.dataset.rowId ? Number(row.dataset.rowId) : Number.NaN;
  1425. return {
  1426. origin: row.dataset.origin ?? null,
  1427. rowId: Number.isFinite(rowId) ? rowId : null,
  1428. status: row.dataset.status ?? null,
  1429. text: row.innerText.trim(),
  1430. };
  1431. });
  1432. },
  1433. testId(TID_V4_SESSION_PANE, paneId),
  1434. TID_V4_ROW,
  1435. );
  1436. }
  1437. /** 等待结构化 compact marker;不读取本地化 label。 */
  1438. export async function waitForV4CompactMarker(
  1439. expected: { status: string; origin: "manual" | "auto" },
  1440. timeout = 90000,
  1441. ) {
  1442. await browser.waitUntil(
  1443. async () =>
  1444. (await getV4CompactMarkers()).some(
  1445. (marker) => marker.status === expected.status && marker.origin === expected.origin,
  1446. ),
  1447. {
  1448. timeout,
  1449. timeoutMsg: `v4 compact marker 未达到 ${expected.origin}/${expected.status}`,
  1450. },
  1451. );
  1452. }
  1453. /** 读取会话标题显示(data-title 投影属性)。 */
  1454. export function getV4SessionTitle(): Promise<string | null> {
  1455. return browser.execute((titleTestId) => {
  1456. const el = document.querySelector<HTMLElement>(`[data-testid="${titleTestId}"]`);
  1457. return el?.getAttribute("data-title") ?? null;
  1458. }, TID_V4_SESSION_TITLE);
  1459. }
  1460. /** 在 header 重命名输入框写入标题并点提交(renameSession 命令)。 */
  1461. export async function renameV4Session(title: string) {
  1462. await setInputValueByTestIdDom(TID_V4_RENAME_INPUT, title, {
  1463. timeout: 15000,
  1464. timeoutMsg: "v4 重命名输入框没有出现",
  1465. });
  1466. await clickTestIdByDom(TID_V4_RENAME_SUBMIT, {
  1467. timeout: 15000,
  1468. timeoutMsg: "v4 重命名提交按钮没有出现",
  1469. });
  1470. }
  1471. /** 读取输入控制条:autoDrain(data-auto-drain)与 followupMode(data-followup-mode)。 */
  1472. export function getV4InputControlState(): Promise<{
  1473. autoDrain: string | null;
  1474. followupMode: string | null;
  1475. }> {
  1476. return browser.execute(
  1477. (autoDrainTestId, followupTestId) => {
  1478. const autoBtn = document.querySelector<HTMLElement>(`[data-testid="${autoDrainTestId}"]`);
  1479. const followupBtn = document.querySelector<HTMLElement>(`[data-testid="${followupTestId}"]`);
  1480. return {
  1481. autoDrain: autoBtn?.getAttribute("data-auto-drain") ?? null,
  1482. followupMode: followupBtn?.getAttribute("data-followup-mode") ?? null,
  1483. };
  1484. },
  1485. TID_V4_AUTODRAIN_TOGGLE,
  1486. TID_V4_FOLLOWUP_TOGGLE,
  1487. );
  1488. }
  1489. /** 点击 autoDrain 开关(setAutoDrain 命令)。 */
  1490. export async function clickV4AutoDrainToggle() {
  1491. return clickTestIdByDom(TID_V4_AUTODRAIN_TOGGLE, {
  1492. timeout: 15000,
  1493. timeoutMsg: "v4 autoDrain 开关没有出现",
  1494. });
  1495. }
  1496. /** 点击 followupMode 开关(setFollowupMode 命令)。 */
  1497. export async function clickV4FollowupToggle() {
  1498. return clickTestIdByDom(TID_V4_FOLLOWUP_TOGGLE, {
  1499. timeout: 15000,
  1500. timeoutMsg: "v4 followupMode 开关没有出现",
  1501. });
  1502. }
  1503. /** 拖拽某 queue 项到目标 queue 项上(按 queueItemId)。 */
  1504. export async function dragV4QueueItemOnto(sourceQueueItemId: string, targetQueueItemId: string) {
  1505. const positions = (await browser.execute(
  1506. (sourceId, targetId) => {
  1507. const dragHandle = Array.from(
  1508. document.querySelectorAll<HTMLElement>('[data-v4-queue-drag-handle="true"]'),
  1509. ).find((el) => el.getAttribute("data-queue-item-id") === sourceId);
  1510. const targetItem = Array.from(
  1511. document.querySelectorAll<HTMLElement>("li[data-queue-item-id]"),
  1512. ).find((el) => el.getAttribute("data-queue-item-id") === targetId);
  1513. if (!dragHandle || !targetItem) {
  1514. return {
  1515. ok: false,
  1516. reason: "missing-element",
  1517. hasDragHandle: Boolean(dragHandle),
  1518. hasTargetItem: Boolean(targetItem),
  1519. };
  1520. }
  1521. const dragRect = dragHandle.getBoundingClientRect();
  1522. const targetRect = targetItem.getBoundingClientRect();
  1523. return {
  1524. ok: true,
  1525. startX: Math.round(dragRect.left + dragRect.width / 2),
  1526. startY: Math.round(dragRect.top + dragRect.height / 2),
  1527. endX: Math.round(targetRect.left + targetRect.width / 2),
  1528. endY: Math.round(targetRect.top + targetRect.height / 2),
  1529. };
  1530. },
  1531. sourceQueueItemId,
  1532. targetQueueItemId,
  1533. )) as
  1534. | { ok: true; startX: number; startY: number; endX: number; endY: number }
  1535. | {
  1536. ok: false;
  1537. reason: string;
  1538. hasDragHandle: boolean;
  1539. hasTargetItem: boolean;
  1540. };
  1541. if (!positions.ok) {
  1542. throw new Error(`v4 队列项拖拽元素不存在: ${JSON.stringify(positions)}`);
  1543. }
  1544. await browser.performActions([
  1545. {
  1546. id: "v4-queue-drag-pointer",
  1547. type: "pointer",
  1548. parameters: { pointerType: "mouse" },
  1549. actions: [
  1550. {
  1551. type: "pointerMove",
  1552. duration: 0,
  1553. x: positions.startX,
  1554. y: positions.startY,
  1555. },
  1556. { type: "pointerDown", button: 0 },
  1557. { type: "pause", duration: 80 },
  1558. {
  1559. type: "pointerMove",
  1560. duration: 120,
  1561. x: positions.startX,
  1562. y: positions.startY - 10,
  1563. },
  1564. {
  1565. type: "pointerMove",
  1566. duration: 260,
  1567. x: positions.endX,
  1568. y: positions.endY,
  1569. },
  1570. { type: "pointerUp", button: 0 },
  1571. ],
  1572. },
  1573. ]);
  1574. await browser.releaseActions();
  1575. // 修复原因:dnd-kit 会屏蔽拖拽结束后的紧随 click,E2E 用空白 click 消耗这次屏蔽,
  1576. // 避免后续按钮点击被误吞。
  1577. await browser.execute(() => {
  1578. document.body.dispatchEvent(
  1579. new MouseEvent("click", {
  1580. bubbles: true,
  1581. cancelable: true,
  1582. view: window,
  1583. }),
  1584. );
  1585. });
  1586. await browser.pause(50);
  1587. }
  1588. // ── M5④ 虚拟滚动:timeline 滚动状态读写 ──
  1589. // 虚拟化后 DOM 只有挂载的 turn units;raw 行数分别走 timeline 容器的
  1590. // data-window-row-count(rows.window)与 data-total-row-count(rows.totalCount),
  1591. // 避免把 mounted unit、logical unit 与持久 raw row 三种计量单位混用。
  1592. export interface V4TimelineScrollState {
  1593. scrollTop: number;
  1594. scrollHeight: number;
  1595. clientHeight: number;
  1596. /** raw projection window 行数。 */
  1597. windowRowCount: number;
  1598. /** turn-level logical render unit 数。 */
  1599. renderUnitCount: number;
  1600. /** 全序行数(data-total-row-count)。 */
  1601. totalRowCount: number;
  1602. /** 底部跟随态(data-following:"true" | "false")。 */
  1603. following: string | null;
  1604. /** 实际挂载到 DOM 的 turn unit 数(虚拟化窗口 + overscan)。 */
  1605. mountedRenderUnitCount: number;
  1606. /** 「回到底部」按钮是否出现。 */
  1607. hasBackToBottom: boolean;
  1608. }
  1609. export function getV4TimelineScrollState(): Promise<V4TimelineScrollState> {
  1610. return browser.execute(
  1611. (timelineTestId, bottomTestId) => {
  1612. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1613. return {
  1614. scrollTop: timeline?.scrollTop ?? 0,
  1615. scrollHeight: timeline?.scrollHeight ?? 0,
  1616. clientHeight: timeline?.clientHeight ?? 0,
  1617. windowRowCount: Number(timeline?.getAttribute("data-window-row-count") ?? 0),
  1618. renderUnitCount: Number(timeline?.getAttribute("data-render-unit-count") ?? 0),
  1619. totalRowCount: Number(timeline?.getAttribute("data-total-row-count") ?? 0),
  1620. following: timeline?.getAttribute("data-following") ?? null,
  1621. mountedRenderUnitCount:
  1622. timeline?.querySelectorAll('[data-v4-turn-unit="true"]').length ?? 0,
  1623. hasBackToBottom: Boolean(document.querySelector(`[data-testid="${bottomTestId}"]`)),
  1624. };
  1625. },
  1626. TID_V4_TIMELINE,
  1627. TID_V4_TIMELINE_BOTTOM,
  1628. );
  1629. }
  1630. /**
  1631. * 把 timeline 滚到顶(scrollTop=0,触发原生 scroll 事件 → 解除底部跟随),
  1632. * 并等虚拟化窗口对齐到新滚动位置后才返回。
  1633. *
  1634. * bugfix(虚拟化语义):scrollTop 赋值后 scroll 事件要到下一渲染帧才派发,
  1635. * virtualizer 收到事件才重渲染顶端行——期间 DOM 仍是旧的底部窗口
  1636. * (实测:scrollTop=0 后旧行 58..72 还挂在视口下方 3272px 处),此时视口里没有
  1637. * 任何行。CDP execute 往返快于一帧,调用方紧接着的 DOM 采样会读到过期窗口。
  1638. * 这里等「有行真正落进视口」(虚拟窗口已对齐当前滚动位置)再返回。
  1639. * 注意不能等 scrollTop 停在 0:到顶会触发 loadOlder,prepend 锚定会立刻把
  1640. * scrollTop 平移到保持阅读位置的新值(这正是被测语义),0 只是瞬态。
  1641. */
  1642. export async function scrollV4TimelineToTop() {
  1643. await browser.execute((timelineTestId) => {
  1644. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1645. if (!timeline) return;
  1646. // 修复原因:ConversationTimeline 会先用 wheel/touch/key 记录真实用户意图,
  1647. // 仅写 scrollTop 的脚本滚动可能被布局保护窗口归类为虚拟化校正,继续保持底部跟随。
  1648. timeline.dispatchEvent(
  1649. new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -600 }),
  1650. );
  1651. timeline.scrollTop = 0;
  1652. timeline.dispatchEvent(new Event("scroll"));
  1653. }, TID_V4_TIMELINE);
  1654. await browser.waitUntil(
  1655. async () =>
  1656. browser.execute(
  1657. (timelineTestId, rowPrefix) => {
  1658. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1659. if (!timeline) return false;
  1660. const timelineTop = timeline.getBoundingClientRect().top;
  1661. const viewportHeight = timeline.clientHeight;
  1662. return Array.from(
  1663. timeline.querySelectorAll<HTMLElement>(`[data-testid^="${rowPrefix}-"]`),
  1664. ).some((row) => {
  1665. const rect = row.getBoundingClientRect();
  1666. return rect.bottom - timelineTop > 0 && rect.top - timelineTop < viewportHeight;
  1667. });
  1668. },
  1669. TID_V4_TIMELINE,
  1670. TID_V4_ROW,
  1671. ),
  1672. {
  1673. timeout: 15000,
  1674. timeoutMsg: "scrollTop=0 后虚拟化窗口没有对齐到滚动位置(视口内始终没有行)",
  1675. },
  1676. );
  1677. }
  1678. /** 点「回到底部」按钮(恢复跟随并贴底)。 */
  1679. export async function clickV4TimelineBackToBottom() {
  1680. return clickTestIdByDom(TID_V4_TIMELINE_BOTTOM, {
  1681. timeout: 15000,
  1682. timeoutMsg: "v4 回到底部按钮没有出现",
  1683. });
  1684. }
  1685. // ── TN:v4 对话轮次导航 minimap ──
  1686. export interface V4TurnNavigatorState {
  1687. centerOffsetPx: number;
  1688. composerLeftGutterPx: number;
  1689. exists: boolean;
  1690. firstItemLeftOffsetPx: number;
  1691. visible: boolean;
  1692. itemCount: number;
  1693. paneWidthPx: number;
  1694. items: Array<{
  1695. active: boolean;
  1696. height: number;
  1697. left: number;
  1698. testId: string;
  1699. top: number;
  1700. turnId: string | null;
  1701. unitIndex: number | null;
  1702. visualColorTone: string | null;
  1703. visualScale: number | null;
  1704. visualTone: string | null;
  1705. }>;
  1706. }
  1707. export function getV4TurnNavigatorState(): Promise<V4TurnNavigatorState> {
  1708. return browser.execute(
  1709. (navigatorTestId, itemPrefix, timelineTestId, composerTestId, sessionPaneTestId) => {
  1710. const pane = document.querySelector<HTMLElement>(`[data-testid="${sessionPaneTestId}"]`);
  1711. const scope: Document | HTMLElement = pane ?? document;
  1712. const navigator = scope.querySelector<HTMLElement>(`[data-testid="${navigatorTestId}"]`);
  1713. const timeline = scope.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  1714. const composer = scope.querySelector<HTMLElement>(`[data-testid="${composerTestId}"]`);
  1715. const style = navigator ? window.getComputedStyle(navigator) : null;
  1716. const rect = navigator?.getBoundingClientRect();
  1717. const timelineRect = timeline?.getBoundingClientRect();
  1718. const composerRect = composer?.getBoundingClientRect();
  1719. const paneRect = pane?.getBoundingClientRect();
  1720. const items = Array.from(
  1721. navigator?.querySelectorAll<HTMLElement>(`[data-testid^="${itemPrefix}-"]`) ?? [],
  1722. ).map((el) => {
  1723. const itemRect = el.getBoundingClientRect();
  1724. return {
  1725. active: el.getAttribute("data-active") === "true",
  1726. height: itemRect.height,
  1727. left: itemRect.left,
  1728. testId: el.dataset.testid ?? "",
  1729. top: itemRect.top,
  1730. turnId: el.getAttribute("data-turn-id"),
  1731. unitIndex:
  1732. el.getAttribute("data-unit-index") === null
  1733. ? null
  1734. : Number(el.getAttribute("data-unit-index")),
  1735. visualColorTone: el.getAttribute("data-visual-color-tone"),
  1736. visualScale:
  1737. el.getAttribute("data-visual-scale") === null
  1738. ? null
  1739. : Number(el.getAttribute("data-visual-scale")),
  1740. visualTone: el.getAttribute("data-visual-tone"),
  1741. };
  1742. });
  1743. const firstItemLeftOffsetPx =
  1744. items[0] && timelineRect ? items[0].left - timelineRect.left : Number.NaN;
  1745. const firstItem = items[0];
  1746. const lastItem = items.at(-1);
  1747. const stackCenter =
  1748. firstItem && lastItem ? (firstItem.top + lastItem.top + lastItem.height) / 2 : Number.NaN;
  1749. const timelineCenter = timelineRect ? timelineRect.top + timelineRect.height / 2 : Number.NaN;
  1750. return {
  1751. centerOffsetPx: stackCenter - timelineCenter,
  1752. composerLeftGutterPx:
  1753. composerRect && timelineRect ? composerRect.left - timelineRect.left : Number.NaN,
  1754. exists: Boolean(navigator),
  1755. firstItemLeftOffsetPx,
  1756. visible: Boolean(
  1757. navigator &&
  1758. style &&
  1759. rect &&
  1760. style.display !== "none" &&
  1761. style.visibility !== "hidden" &&
  1762. rect.width > 0 &&
  1763. rect.height > 0,
  1764. ),
  1765. itemCount: items.length,
  1766. items,
  1767. paneWidthPx: paneRect?.width ?? Number.NaN,
  1768. };
  1769. },
  1770. TID_V4_TURN_NAVIGATOR,
  1771. TID_V4_TURN_NAVIGATOR_ITEM,
  1772. TID_V4_TIMELINE,
  1773. TID_V4_COMPOSER,
  1774. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  1775. );
  1776. }
  1777. export async function waitForV4TurnNavigator(
  1778. predicate: (state: V4TurnNavigatorState) => boolean,
  1779. timeoutMsg: string,
  1780. timeout = 30000,
  1781. ) {
  1782. let latest: V4TurnNavigatorState | null = null;
  1783. try {
  1784. await browser.waitUntil(
  1785. async () => {
  1786. latest = await getV4TurnNavigatorState();
  1787. return predicate(latest);
  1788. },
  1789. { timeout, timeoutMsg },
  1790. );
  1791. } catch (error) {
  1792. latest = await getV4TurnNavigatorState();
  1793. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  1794. cause: error,
  1795. });
  1796. }
  1797. return getV4TurnNavigatorState();
  1798. }
  1799. async function getV4TurnNavigatorItemTestIdByIndex(index: number) {
  1800. const state = await getV4TurnNavigatorState();
  1801. const item = state.items[index];
  1802. if (!item) {
  1803. throw new Error(
  1804. `v4 turn navigator item 不存在: index=${index}; latest=${JSON.stringify(state)}`,
  1805. );
  1806. }
  1807. return item.testId;
  1808. }
  1809. export async function hoverV4TurnNavigatorItemByIndex(index: number) {
  1810. const itemTestId = await getV4TurnNavigatorItemTestIdByIndex(index);
  1811. const item = $(sel(itemTestId));
  1812. await item.waitForDisplayed({ timeout: 15000 });
  1813. await item.moveTo();
  1814. return itemTestId;
  1815. }
  1816. export async function focusV4TurnNavigatorItemByIndex(index: number) {
  1817. const itemTestId = await getV4TurnNavigatorItemTestIdByIndex(index);
  1818. await browser.execute((currentTestId) => {
  1819. document.querySelector<HTMLElement>(`[data-testid="${currentTestId}"]`)?.focus();
  1820. }, itemTestId);
  1821. return itemTestId;
  1822. }
  1823. export async function clickV4TurnNavigatorItemByIndex(index: number) {
  1824. const itemTestId = await getV4TurnNavigatorItemTestIdByIndex(index);
  1825. await browser.execute((currentTestId) => {
  1826. document.querySelector<HTMLButtonElement>(`[data-testid="${currentTestId}"]`)?.click();
  1827. }, itemTestId);
  1828. return itemTestId;
  1829. }
  1830. export function getV4TurnNavigatorTooltipText(): Promise<string> {
  1831. return browser.execute((tooltipPrefix) => {
  1832. const tooltip = document.querySelector<HTMLElement>(`[data-testid^="${tooltipPrefix}-"]`);
  1833. return (tooltip?.innerText ?? "").replace(/ /g, " ");
  1834. }, TID_V4_TURN_NAVIGATOR_TOOLTIP);
  1835. }
  1836. export async function waitForV4TurnNavigatorTooltip(
  1837. predicate: (text: string) => boolean,
  1838. timeoutMsg: string,
  1839. timeout = 15000,
  1840. ) {
  1841. let latest = "";
  1842. try {
  1843. await browser.waitUntil(
  1844. async () => {
  1845. latest = await getV4TurnNavigatorTooltipText();
  1846. return predicate(latest);
  1847. },
  1848. { timeout, timeoutMsg },
  1849. );
  1850. } catch (error) {
  1851. latest = await getV4TurnNavigatorTooltipText();
  1852. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  1853. cause: error,
  1854. });
  1855. }
  1856. return getV4TurnNavigatorTooltipText();
  1857. }
  1858. // ── M5⑤ 分屏(Layout/Focus 两层):pane 级定位与焦点断言 ──
  1859. // 分屏后同 testid(composer 输入/发送等)在两个 pane 各有一份,全局 helper 只会
  1860. // 命中 DOM 序第一个(primary)。以下 helper 一律先按 v4-pane-shell-<paneId>
  1861. // 收口作用域再定位,焦点断言读外壳的 data-focused。
  1862. /** 读取当前 focused pane 的 paneId(data-focused="true" 的外壳);无外壳返回 null。 */
  1863. export function getV4FocusedPaneId(): Promise<string | null> {
  1864. return browser.execute((shellPrefix) => {
  1865. const focused = document.querySelector<HTMLElement>(
  1866. `[data-testid^="${shellPrefix}-"][data-focused="true"]`,
  1867. );
  1868. return focused?.getAttribute("data-pane-id") ?? null;
  1869. }, TID_V4_PANE_SHELL);
  1870. }
  1871. /**
  1872. * 首个非 primary pane 的 paneId(分屏二期 paneId 动态分配:pane-1/pane-2/…,
  1873. * 一期固定 "split" 仅存于 v1 持久化迁移形态);无分屏返回 null。
  1874. */
  1875. export function getV4SecondaryPaneId(): Promise<string | null> {
  1876. return browser.execute(
  1877. (shellPrefix, mainPaneId) => {
  1878. const shells = Array.from(
  1879. document.querySelectorAll<HTMLElement>(`[data-testid^="${shellPrefix}-"]`),
  1880. );
  1881. for (const shell of shells) {
  1882. const paneId = shell.getAttribute("data-pane-id");
  1883. if (paneId && paneId !== mainPaneId) {
  1884. return paneId;
  1885. }
  1886. }
  1887. return null;
  1888. },
  1889. TID_V4_PANE_SHELL,
  1890. V4_MAIN_PANE_ID,
  1891. );
  1892. }
  1893. /** 当前 workbench 中全部 paneId。 */
  1894. export function getV4PaneIds(): Promise<string[]> {
  1895. return browser.execute((shellPrefix) => {
  1896. return Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${shellPrefix}-"]`))
  1897. .map((shell) => shell.getAttribute("data-pane-id"))
  1898. .filter((paneId): paneId is string => Boolean(paneId));
  1899. }, TID_V4_PANE_SHELL);
  1900. }
  1901. /** 是否存在非 primary pane(分屏布局)。 */
  1902. export async function hasV4SplitPane(): Promise<boolean> {
  1903. return (await getV4SecondaryPaneId()) !== null;
  1904. }
  1905. /** 点击 primary pane header 的「向右拆分」按钮,等新 pane 出现并返回其 paneId。 */
  1906. export async function openV4SplitPane(): Promise<string> {
  1907. await clickTestIdByDom(TID_V4_SPLIT_OPEN, {
  1908. timeout: 15000,
  1909. timeoutMsg: "v4 拆分按钮没有出现或不可点击",
  1910. });
  1911. let paneId: string | null = null;
  1912. await browser.waitUntil(
  1913. async () => {
  1914. paneId = await getV4SecondaryPaneId();
  1915. return paneId !== null;
  1916. },
  1917. {
  1918. timeout: 15000,
  1919. timeoutMsg: "点击拆分按钮后新 pane 没有出现",
  1920. },
  1921. );
  1922. return paneId as unknown as string;
  1923. }
  1924. /** 在指定 pane 上点击向右/向下拆分按钮,返回本次新增 paneId。 */
  1925. export async function openV4SplitPaneFrom(
  1926. paneId: string,
  1927. direction: "right" | "down" = "right",
  1928. ): Promise<string> {
  1929. const before = new Set(await getV4PaneIds());
  1930. const splitButtonTestId = direction === "down" ? TID_V4_SPLIT_DOWN : TID_V4_SPLIT_OPEN;
  1931. const clicked = await browser.execute(
  1932. (shellTestId, buttonTestId) => {
  1933. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  1934. const button = shell?.querySelector<HTMLButtonElement>(`[data-testid="${buttonTestId}"]`);
  1935. if (!button || button.disabled) return false;
  1936. button.click();
  1937. return true;
  1938. },
  1939. testId(TID_V4_PANE_SHELL, paneId),
  1940. splitButtonTestId,
  1941. );
  1942. if (!clicked) {
  1943. throw new Error(`pane ${paneId} 的 ${direction} 拆分按钮不存在或不可用`);
  1944. }
  1945. let addedPaneId: string | null = null;
  1946. await browser.waitUntil(
  1947. async () => {
  1948. const after = await getV4PaneIds();
  1949. addedPaneId = after.find((id) => !before.has(id)) ?? null;
  1950. return addedPaneId !== null;
  1951. },
  1952. {
  1953. timeout: 15000,
  1954. timeoutMsg: `pane ${paneId} 点击 ${direction} 拆分后没有新增 pane`,
  1955. },
  1956. );
  1957. return addedPaneId as unknown as string;
  1958. }
  1959. /** 点击非 primary pane header 的「关闭窗格」按钮,并等该 pane 外壳消失。 */
  1960. export async function closeV4SplitPane() {
  1961. await clickTestIdByDom(TID_V4_SPLIT_CLOSE, {
  1962. timeout: 15000,
  1963. timeoutMsg: "v4 关闭窗格按钮没有出现或不可点击",
  1964. });
  1965. await browser.waitUntil(async () => !(await hasV4SplitPane()), {
  1966. timeout: 15000,
  1967. timeoutMsg: "点击关闭窗格后 pane 没有消失",
  1968. });
  1969. }
  1970. // ── 布局持久化 / 拖拽调宽 / 侧栏分屏入口 ──
  1971. /** paneLayoutStore 的 localStorage 键(packages/ui paneLayoutStore.PANE_LAYOUT_STORAGE_KEY,分屏二期 v2)。 */
  1972. export const V4_PANE_LAYOUT_STORAGE_KEY = "zcode-v4-pane-layout:v2";
  1973. export const V4_WORKBENCH_GROUP_STORAGE_KEY = "zcode-v4-session-workbench-groups:v1";
  1974. /** v2 持久化载荷形态(与 packages/ui paneLayoutStore PersistedPaneLayoutV2 对偶,e2e 断言/篡改用)。 */
  1975. export interface V4PersistedPaneLayout {
  1976. root: {
  1977. type: string;
  1978. ratio?: number;
  1979. [key: string]: unknown;
  1980. };
  1981. panes: Record<string, { workspaceScope: { workspacePath: string }; sessionId: string | null }>;
  1982. focusedPaneId: string;
  1983. }
  1984. /** promoted 分屏的唯一持久化 owner(与 packages/ui workbenchGroupStore 对偶)。 */
  1985. export interface V4PersistedWorkbenchGroups {
  1986. activeGroupId: string | null;
  1987. groups: Record<
  1988. string,
  1989. {
  1990. root: {
  1991. type: string;
  1992. ratio?: number;
  1993. [key: string]: unknown;
  1994. };
  1995. panes: Record<
  1996. string,
  1997. {
  1998. workspaceScope: { workspacePath: string };
  1999. sessionId: string;
  2000. }
  2001. >;
  2002. focusedPaneId: string;
  2003. }
  2004. >;
  2005. }
  2006. /** 读取当前分屏占比(primary 外壳宽 / 容器宽);无分屏或容器不可测返回 null。 */
  2007. export function getV4SplitRatio(): Promise<number | null> {
  2008. return browser.execute(
  2009. (primaryShellTestId, shellPrefix, mainPaneId) => {
  2010. const primary = document.querySelector<HTMLElement>(`[data-testid="${primaryShellTestId}"]`);
  2011. const hasSecondary = Array.from(
  2012. document.querySelectorAll<HTMLElement>(`[data-testid^="${shellPrefix}-"]`),
  2013. ).some((shell) => shell.getAttribute("data-pane-id") !== mainPaneId);
  2014. const container = primary?.parentElement;
  2015. if (!primary || !hasSecondary || !container) return null;
  2016. const containerWidth = container.getBoundingClientRect().width;
  2017. if (containerWidth <= 0) return null;
  2018. return primary.getBoundingClientRect().width / containerWidth;
  2019. },
  2020. testId(TID_V4_PANE_SHELL, V4_MAIN_PANE_ID),
  2021. TID_V4_PANE_SHELL,
  2022. V4_MAIN_PANE_ID,
  2023. );
  2024. }
  2025. /**
  2026. * 把分屏分隔条拖到容器宽度的 targetRatio 处(pointer events:down → move → up;
  2027. * 分隔条 pointerup 提交 store → 持久化)。
  2028. */
  2029. export async function dragV4SplitDividerTo(targetRatio: number) {
  2030. const dispatched = await browser.execute(
  2031. (dividerTestId, primaryShellTestId, ratio) => {
  2032. const divider = document.querySelector<HTMLElement>(`[data-testid="${dividerTestId}"]`);
  2033. const container = document.querySelector<HTMLElement>(
  2034. `[data-testid="${primaryShellTestId}"]`,
  2035. )?.parentElement;
  2036. if (!divider || !container) return false;
  2037. const containerRect = container.getBoundingClientRect();
  2038. const dividerRect = divider.getBoundingClientRect();
  2039. const startX = dividerRect.left + dividerRect.width / 2;
  2040. const y = dividerRect.top + dividerRect.height / 2;
  2041. const targetX = containerRect.left + containerRect.width * ratio;
  2042. const base = {
  2043. bubbles: true,
  2044. cancelable: true,
  2045. button: 0,
  2046. pointerId: 1,
  2047. pointerType: "mouse",
  2048. } as const;
  2049. divider.dispatchEvent(
  2050. new PointerEvent("pointerdown", { ...base, clientX: startX, clientY: y }),
  2051. );
  2052. divider.dispatchEvent(
  2053. new PointerEvent("pointermove", {
  2054. ...base,
  2055. clientX: (startX + targetX) / 2,
  2056. clientY: y,
  2057. }),
  2058. );
  2059. divider.dispatchEvent(
  2060. new PointerEvent("pointermove", { ...base, clientX: targetX, clientY: y }),
  2061. );
  2062. divider.dispatchEvent(
  2063. new PointerEvent("pointerup", { ...base, clientX: targetX, clientY: y }),
  2064. );
  2065. return true;
  2066. },
  2067. TID_V4_SPLIT_DIVIDER,
  2068. testId(TID_V4_PANE_SHELL, V4_MAIN_PANE_ID),
  2069. targetRatio,
  2070. );
  2071. if (!dispatched) {
  2072. throw new Error("分屏分隔条不存在,无法拖拽");
  2073. }
  2074. }
  2075. /** 等待实际分屏占比进入 target±tolerance。 */
  2076. export async function waitForV4SplitRatio(target: number, tolerance = 0.03, timeout = 15000) {
  2077. let latest: number | null = null;
  2078. await browser.waitUntil(
  2079. async () => {
  2080. latest = await getV4SplitRatio();
  2081. return latest !== null && Math.abs(latest - target) <= tolerance;
  2082. },
  2083. {
  2084. timeout,
  2085. timeoutMsg: `分屏占比没有达到 ${target}(最近值 ${latest})`,
  2086. },
  2087. );
  2088. }
  2089. /** 右键侧栏会话项 → 上下文菜单「在分屏打开」→ 等新 pane 出现并返回其 paneId(仅桌面 shell)。 */
  2090. export async function openV4SplitFromSidebar(sessionId: string): Promise<string> {
  2091. const before = new Set(await getV4PaneIds());
  2092. await browser.waitUntil(
  2093. async () =>
  2094. browser.execute(
  2095. (itemTestId) => {
  2096. const item = document.querySelector<HTMLElement>(`[data-testid="${itemTestId}"]`);
  2097. if (!item) return false;
  2098. const rect = item.getBoundingClientRect();
  2099. item.dispatchEvent(
  2100. new MouseEvent("contextmenu", {
  2101. bubbles: true,
  2102. cancelable: true,
  2103. button: 2,
  2104. clientX: rect.left + rect.width / 2,
  2105. clientY: rect.top + rect.height / 2,
  2106. }),
  2107. );
  2108. return true;
  2109. },
  2110. testId(TID_TASK_ITEM, sessionId),
  2111. ),
  2112. {
  2113. timeout: 15000,
  2114. timeoutMsg: `侧栏会话项不存在: ${sessionId}`,
  2115. },
  2116. );
  2117. await clickTestIdByDom(TID_V4_TASK_OPEN_IN_SPLIT, {
  2118. timeout: 15000,
  2119. timeoutMsg: "会话项上下文菜单「在分屏打开」没有出现",
  2120. });
  2121. let paneId: string | null = null;
  2122. await browser.waitUntil(
  2123. async () => {
  2124. const after = await getV4PaneIds();
  2125. paneId =
  2126. after.find((candidate) => !before.has(candidate)) ??
  2127. (before.size === 1 ? await getV4SecondaryPaneId() : null);
  2128. return paneId !== null;
  2129. },
  2130. {
  2131. timeout: 15000,
  2132. timeoutMsg: "「在分屏打开」后新 pane 没有出现",
  2133. },
  2134. );
  2135. return paneId as unknown as string;
  2136. }
  2137. /** 点击侧栏会话项并等待 primary pane 绑定到该 session。 */
  2138. export async function selectV4TaskById(sessionId: string, taskListTimeout = 15000) {
  2139. await clickTestIdByDom(testId(TID_TASK_ITEM, sessionId), {
  2140. timeout: taskListTimeout,
  2141. timeoutMsg: `任务列表没有可点击的 v4 task: ${sessionId}`,
  2142. });
  2143. await waitForV4Pane(
  2144. (snapshot) => snapshot.sessionId === sessionId,
  2145. `点击侧栏 task 后 primary pane 没有切到 ${sessionId}`,
  2146. 30000,
  2147. V4_MAIN_PANE_ID,
  2148. );
  2149. }
  2150. /** 对 pane 外壳派发 pointerdown(Focus 层 onPointerDownCapture → focus 该 pane)。 */
  2151. export async function focusV4Pane(paneId: string) {
  2152. const dispatched = await browser.execute(
  2153. (shellTestId) => {
  2154. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2155. if (!shell) return false;
  2156. shell.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true }));
  2157. return true;
  2158. },
  2159. testId(TID_V4_PANE_SHELL, paneId),
  2160. );
  2161. if (!dispatched) {
  2162. throw new Error(`focusV4Pane: pane 外壳不存在: ${paneId}`);
  2163. }
  2164. await browser.waitUntil(async () => (await getV4FocusedPaneId()) === paneId, {
  2165. timeout: 15000,
  2166. timeoutMsg: `pane ${paneId} 没有获得焦点`,
  2167. });
  2168. }
  2169. /** pane 作用域内点 stop(分屏时全局 TID_V4_STOP 会命中 DOM 序第一个 pane)。 */
  2170. export async function clickV4StopInPane(paneId: string) {
  2171. const clicked = await browser.execute(
  2172. (shellTestId, stopTestId) => {
  2173. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2174. const btn = shell?.querySelector<HTMLButtonElement>(`[data-testid="${stopTestId}"]`);
  2175. btn?.click();
  2176. return Boolean(btn);
  2177. },
  2178. testId(TID_V4_PANE_SHELL, paneId),
  2179. TID_V4_STOP,
  2180. );
  2181. if (!clicked) {
  2182. throw new Error(`pane ${paneId} 内没有可点击的 stop 按钮`);
  2183. }
  2184. }
  2185. /** pane 作用域内点分屏 pane 的 session pane snapshot(按 paneId)。 */
  2186. export async function waitForV4PaneById(
  2187. paneId: string,
  2188. predicate: (snapshot: V4PaneSnapshot) => boolean,
  2189. timeoutMsg: string,
  2190. timeout = 30000,
  2191. ) {
  2192. return waitForV4Pane(predicate, timeoutMsg, timeout, paneId);
  2193. }
  2194. /** pane 作用域内写 composer 文本并点发送(同 sendV4Prompt,但按 paneId 收口)。 */
  2195. export async function sendV4PromptInPane(paneId: string, prompt: string) {
  2196. const paneShellTestId = testId(TID_V4_PANE_SHELL, paneId);
  2197. // M5:composer 为 Lexical contenteditable——写入走编辑器挂载的 __zcodeLexicalInputE2E
  2198. // bridge(驱动真实 editor state);bridge.focus() 同时驱动 Focus 层 → composer 归属该 pane。
  2199. await browser.waitUntil(
  2200. async () =>
  2201. browser.execute(
  2202. (shellTestId, inputTestId, nextValue) => {
  2203. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2204. const element = shell?.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2205. if (!element) return false;
  2206. const bridge = (
  2207. element as HTMLElement & {
  2208. __zcodeLexicalInputE2E?: {
  2209. focus: () => void;
  2210. getText: () => string;
  2211. setText: (text: string) => void;
  2212. };
  2213. }
  2214. ).__zcodeLexicalInputE2E;
  2215. if (!bridge) return false;
  2216. bridge.focus();
  2217. bridge.setText(nextValue);
  2218. return bridge.getText() === nextValue;
  2219. },
  2220. paneShellTestId,
  2221. TID_V4_COMPOSER_INPUT,
  2222. prompt,
  2223. ),
  2224. {
  2225. timeout: 15000,
  2226. timeoutMsg: `pane ${paneId} 的 composer 输入框没有出现或不可输入`,
  2227. },
  2228. );
  2229. await browser.waitUntil(
  2230. async () =>
  2231. browser.execute(
  2232. (shellTestId, sendTestId) => {
  2233. const shell = document.querySelector<HTMLElement>(`[data-testid="${shellTestId}"]`);
  2234. const button = shell?.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  2235. if (!button || button.disabled) return false;
  2236. button.click();
  2237. return true;
  2238. },
  2239. paneShellTestId,
  2240. TID_V4_COMPOSER_SEND,
  2241. ),
  2242. {
  2243. timeout: 30000,
  2244. timeoutMsg: `pane ${paneId} 的发送按钮没有变为可用`,
  2245. },
  2246. );
  2247. }
  2248. /** 等待 v4 权限弹窗出现(V4InteractionDialogs → PermissionDialog,role=listbox)。 */
  2249. export function hasV4PermissionDialog(): Promise<boolean> {
  2250. return browser.execute(() => {
  2251. const normalize = (value: string | null | undefined) => (value ?? "").replace(/ /g, " ").trim();
  2252. return Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some(
  2253. (element) => {
  2254. const label = normalize(element.getAttribute("aria-label"));
  2255. return label === "Permission required" || label === "需要权限";
  2256. },
  2257. );
  2258. });
  2259. }
  2260. /** V4 普通 permission 声明 freeText 能力时,底部输入行必须实际挂载。 */
  2261. export function hasV4PermissionFeedbackInput(): Promise<boolean> {
  2262. return browser.execute(() =>
  2263. Boolean(
  2264. document.querySelector(
  2265. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2266. ),
  2267. ),
  2268. );
  2269. }
  2270. export async function waitForV4PermissionDialog(timeout = 60000) {
  2271. await browser.waitUntil(hasV4PermissionDialog, { timeout, timeoutMsg: "v4 权限弹窗没有出现" });
  2272. }
  2273. export interface V4PermissionRuleScope {
  2274. kind: "exact" | "prefix";
  2275. text: string;
  2276. }
  2277. export async function getV4PermissionRuleScopes(): Promise<V4PermissionRuleScope[]> {
  2278. return browser.execute(() => {
  2279. const normalize = (value: string | null | undefined) => (value ?? "").replace(/ /g, " ").trim();
  2280. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2281. (element) => {
  2282. const label = normalize(element.getAttribute("aria-label"));
  2283. return label === "Permission required" || label === "需要权限";
  2284. },
  2285. );
  2286. return Array.from(
  2287. listbox?.querySelectorAll<HTMLElement>("[data-permission-rule-scope]") ?? [],
  2288. ).map((element) => ({
  2289. kind: element.getAttribute("data-permission-rule-scope") === "prefix" ? "prefix" : "exact",
  2290. text: normalize(element.innerText),
  2291. }));
  2292. });
  2293. }
  2294. export interface V4PermissionDockState {
  2295. inDock: boolean;
  2296. composerMounted: boolean;
  2297. composerHidden: boolean;
  2298. interactionBeforeComposer: boolean;
  2299. composerAriaHidden: string | null;
  2300. composerDisplay: string | null;
  2301. }
  2302. async function readV4PermissionDockState(): Promise<V4PermissionDockState> {
  2303. return browser.execute((composerTestId) => {
  2304. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2305. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2306. (el) => {
  2307. const label = normalize(el.getAttribute("aria-label"));
  2308. return label === "Permission required" || label === "需要权限";
  2309. },
  2310. );
  2311. const dock = listbox?.closest<HTMLElement>('[data-v4-composer-dock="true"]') ?? null;
  2312. const composer = dock?.querySelector<HTMLElement>(`[data-testid="${composerTestId}"]`) ?? null;
  2313. const composerDisplay = composer ? getComputedStyle(composer).display : null;
  2314. const interactionBeforeComposer = Boolean(
  2315. listbox &&
  2316. composer &&
  2317. listbox.compareDocumentPosition(composer) & Node.DOCUMENT_POSITION_FOLLOWING,
  2318. );
  2319. return {
  2320. inDock: Boolean(dock),
  2321. composerMounted: Boolean(composer),
  2322. composerHidden:
  2323. composer?.getAttribute("aria-hidden") === "true" && composerDisplay === "none",
  2324. interactionBeforeComposer,
  2325. composerAriaHidden: composer?.getAttribute("aria-hidden") ?? null,
  2326. composerDisplay,
  2327. };
  2328. }, TID_V4_COMPOSER);
  2329. }
  2330. /**
  2331. * 等待真实权限弹窗进入 v4 composer dock,并确认阻塞期间 composer 只隐藏不卸载。
  2332. */
  2333. export async function waitForV4PermissionDialogInComposerDock(timeout = 60000) {
  2334. await waitForV4PermissionDialog(timeout);
  2335. await browser.waitUntil(
  2336. async () => {
  2337. const state = await readV4PermissionDockState();
  2338. return (
  2339. state.inDock &&
  2340. state.composerMounted &&
  2341. state.composerHidden &&
  2342. state.interactionBeforeComposer
  2343. );
  2344. },
  2345. { timeout, timeoutMsg: "v4 权限弹窗没有进入 composer dock 或 composer 未正确隐藏" },
  2346. );
  2347. return readV4PermissionDockState();
  2348. }
  2349. /**
  2350. * 批准 v4 权限弹窗的第一个选项(Allow once)。PermissionDialog 首项默认选中,
  2351. * 单击已选中项即确认 onRespond → resolveInteraction 命令。为稳妥点两次
  2352. *(第一次若只是选中,第二次确认)。
  2353. */
  2354. export async function approveV4Permission(feedback?: string) {
  2355. await waitForV4PermissionDialog();
  2356. if (feedback !== undefined) {
  2357. const input = await $(
  2358. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2359. );
  2360. await input.waitForDisplayed({ timeout: 15000 });
  2361. await input.setValue(feedback);
  2362. }
  2363. const confirmFirstOption = () =>
  2364. browser.execute(() => {
  2365. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2366. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2367. (el) => {
  2368. const label = normalize(el.getAttribute("aria-label"));
  2369. return label === "Permission required" || label === "需要权限";
  2370. },
  2371. );
  2372. const option = listbox?.querySelector<HTMLButtonElement>('button[role="option"]');
  2373. option?.click();
  2374. return Boolean(option);
  2375. });
  2376. await confirmFirstOption();
  2377. // 弹窗消失即视为已应答;若首次点击只是选中,再点一次确认。
  2378. const dismissed = await browser
  2379. .waitUntil(
  2380. async () => {
  2381. const stillOpen = await browser.execute(() => {
  2382. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2383. return Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some(
  2384. (el) => {
  2385. const label = normalize(el.getAttribute("aria-label"));
  2386. return label === "Permission required" || label === "需要权限";
  2387. },
  2388. );
  2389. });
  2390. if (stillOpen) {
  2391. await confirmFirstOption();
  2392. return false;
  2393. }
  2394. return true;
  2395. },
  2396. { timeout: 15000, timeoutMsg: "v4 权限弹窗批准后没有关闭" },
  2397. )
  2398. .then(() => true)
  2399. .catch(() => false);
  2400. return dismissed;
  2401. }
  2402. /** 填写拒绝反馈并确认 Deny,反馈走同一个 resolveInteraction 应答。 */
  2403. export async function denyV4PermissionWithFeedback(feedback: string, submitWithEnter = false) {
  2404. await waitForV4PermissionDialog();
  2405. const input = await $(
  2406. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2407. );
  2408. await input.waitForDisplayed({ timeout: 15000 });
  2409. await input.setValue(feedback);
  2410. // 空白输入行不能提交;普通 Deny 仍可确认且只回传基础拒绝文案。
  2411. if (!feedback.trim() && !submitWithEnter) {
  2412. await browser.execute(() => {
  2413. document
  2414. .querySelector<HTMLButtonElement>('[role="option"][data-permission-option-kind^="reject"]')
  2415. ?.focus();
  2416. });
  2417. }
  2418. await browser.waitUntil(
  2419. () =>
  2420. browser.execute((hasFeedback: boolean) => {
  2421. const selectedDeny = document.querySelector(
  2422. '[role="option"][data-permission-option-kind^="reject"][aria-selected="true"]',
  2423. );
  2424. const input = document.querySelector<HTMLTextAreaElement>(
  2425. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  2426. );
  2427. return hasFeedback
  2428. ? !selectedDeny &&
  2429. document.activeElement === input &&
  2430. input?.parentElement?.classList.contains("bg-selected")
  2431. : Boolean(selectedDeny);
  2432. }, Boolean(feedback.trim())),
  2433. { timeout: 5000, timeoutMsg: "权限反馈行与普通 Deny 的独立选择状态不符合预期" },
  2434. );
  2435. if (submitWithEnter) {
  2436. await input.click();
  2437. await browser.keys("Enter");
  2438. }
  2439. const clicked = submitWithEnter
  2440. ? true
  2441. : await browser.execute(() => {
  2442. const normalize = (v: string | null | undefined) => (v ?? "").replace(/ /g, " ").trim();
  2443. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2444. (el) => {
  2445. const label = normalize(el.getAttribute("aria-label"));
  2446. return label === "Permission required" || label === "需要权限";
  2447. },
  2448. );
  2449. // 按稳定的阻塞交互区域定位,避免新增视觉分组后依赖 listbox 的直接父节点。
  2450. const confirmButton = listbox
  2451. ?.closest('[data-v4-composer-dock="true"]')
  2452. ?.querySelector<HTMLButtonElement>(
  2453. 'button[aria-label="Confirm"],button[aria-label="确认"]',
  2454. );
  2455. confirmButton?.click();
  2456. return Boolean(confirmButton);
  2457. });
  2458. if (!clicked) return false;
  2459. return browser
  2460. .waitUntil(async () => !(await hasV4PermissionDialog()), {
  2461. timeout: 15000,
  2462. timeoutMsg: "v4 权限弹窗拒绝后没有关闭",
  2463. })
  2464. .then(() => true)
  2465. .catch(() => false);
  2466. }
  2467. /** 选择携带 CLI suggestion 的项目级始终允许选项。 */
  2468. export async function approveV4PermissionAlways() {
  2469. await waitForV4PermissionDialog();
  2470. const confirmAlwaysOption = () =>
  2471. browser.execute(() => {
  2472. const normalize = (value: string | null | undefined) =>
  2473. (value ?? "").replace(/ /g, " ").trim();
  2474. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  2475. (element) => {
  2476. const label = normalize(element.getAttribute("aria-label"));
  2477. return label === "Permission required" || label === "需要权限";
  2478. },
  2479. );
  2480. const option = Array.from(
  2481. listbox?.querySelectorAll<HTMLButtonElement>('button[role="option"]') ?? [],
  2482. ).find((button) => button.dataset.permissionOptionKind === "allowAlways");
  2483. option?.click();
  2484. return Boolean(option);
  2485. });
  2486. if (!(await confirmAlwaysOption())) return false;
  2487. return browser
  2488. .waitUntil(
  2489. async () => {
  2490. const stillOpen = await hasV4PermissionDialog();
  2491. if (stillOpen) {
  2492. await confirmAlwaysOption();
  2493. return false;
  2494. }
  2495. return true;
  2496. },
  2497. { timeout: 15000, timeoutMsg: "v4 项目始终允许后权限弹窗没有关闭" },
  2498. )
  2499. .then(() => true)
  2500. .catch(() => false);
  2501. }
  2502. // ── M5 composer 工具条 / slash 面板 ──
  2503. /** 读取 composer 当前文本(Lexical E2E bridge)。bridge 未挂载返回 null。 */
  2504. export function getV4ComposerText(): Promise<string | null> {
  2505. return browser.execute((inputTestId) => {
  2506. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2507. const bridge = (
  2508. element as (HTMLElement & { __zcodeLexicalInputE2E?: { getText: () => string } }) | null
  2509. )?.__zcodeLexicalInputE2E;
  2510. return bridge ? bridge.getText() : null;
  2511. }, TID_V4_COMPOSER_INPUT);
  2512. }
  2513. /** composer 本体或其 Lexical 子节点当前是否持有焦点。 */
  2514. export function isV4ComposerFocused(): Promise<boolean> {
  2515. return browser.execute((inputTestId) => {
  2516. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2517. return Boolean(element && document.activeElement && element.contains(document.activeElement));
  2518. }, TID_V4_COMPOSER_INPUT);
  2519. }
  2520. /** 读取 composer 附件卡片的可观察文件名与 ready 状态。 */
  2521. export function getV4ComposerAttachments(): Promise<
  2522. Array<{ text: string; uploadStatus: string | null }>
  2523. > {
  2524. return browser.execute(
  2525. (attachmentPrefix) =>
  2526. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${attachmentPrefix}-"]`))
  2527. .filter((element) => element.hasAttribute("data-upload-status"))
  2528. .map((element) => {
  2529. // Bug 原因:媒体卡片按产品设计只展示缩略图,文件名在 img alt 中;读取
  2530. // innerText 会把 ready 的图片误判成“附件没有进入 ready”。
  2531. const mediaFilename = element.querySelector<HTMLImageElement>("img[alt]")?.alt.trim();
  2532. return {
  2533. text: mediaFilename || (element.innerText || element.textContent || "").trim(),
  2534. uploadStatus: element.getAttribute("data-upload-status"),
  2535. };
  2536. }),
  2537. TID_V4_ATTACHMENT,
  2538. );
  2539. }
  2540. /** slash 候选面板是否出现。 */
  2541. export function hasV4SlashPanel(): Promise<boolean> {
  2542. return browser.execute(
  2543. (panelTestId) => Boolean(document.querySelector(`[data-testid="${panelTestId}"]`)),
  2544. TID_PROMPT_SUGGESTION_PANEL,
  2545. );
  2546. }
  2547. /** 读取 slash 面板当前候选项 id(如 "slash:compact")。 */
  2548. export function getV4SlashOptionIds(): Promise<string[]> {
  2549. return browser.execute((optionPrefix) => {
  2550. return Array.from(
  2551. document.querySelectorAll<HTMLElement>(`[data-testid^="${optionPrefix}-"]`),
  2552. ).map((element) => element.getAttribute("data-option-id") ?? "");
  2553. }, TID_PROMPT_SUGGESTION_OPTION);
  2554. }
  2555. /** 等待 slash 面板出现且包含目标候选项。 */
  2556. export async function waitForV4SlashOption(optionId: string, timeout = 15000) {
  2557. await browser.waitUntil(
  2558. async () => (await hasV4SlashPanel()) && (await getV4SlashOptionIds()).includes(optionId),
  2559. {
  2560. timeout,
  2561. timeoutMsg: `slash 面板没有出现候选项: ${optionId}`,
  2562. },
  2563. );
  2564. }
  2565. /**
  2566. * 点选 slash 候选项。面板选项在 mousedown 上确认(preventDefault 防 blur),
  2567. * element.click() 不派发 mousedown,这里显式 dispatch。
  2568. */
  2569. export async function clickV4SlashOption(optionId: string) {
  2570. const optionTestId = testId(TID_PROMPT_SUGGESTION_OPTION, optionId);
  2571. let dispatched = false;
  2572. await browser.waitUntil(
  2573. async () => {
  2574. // Bug 根因:Windows Skill option id 含反斜杠,动态 CSS selector 无法精确命中;
  2575. // 同时 React 可能在候选加载时重挂载节点,所以定位与 mousedown 必须在一次查询内重试。
  2576. dispatched = await browser.execute(dispatchMouseDownByExactTestId, optionTestId);
  2577. return dispatched;
  2578. },
  2579. {
  2580. timeout: 15000,
  2581. timeoutMsg: `slash 面板候选项不可点击: ${optionId}`,
  2582. },
  2583. );
  2584. return dispatched;
  2585. }
  2586. /** 通过 composer 工具条切换协作模式(switchCollaborationMode 命令)。 */
  2587. export async function switchV4Mode(mode: string) {
  2588. await selectRadixOption(
  2589. TID_CHAT_MODE_SELECT_TRIGGER,
  2590. testId(TID_CHAT_MODE_SELECT_ITEM, mode),
  2591. `v4 模式选择器没有出现目标模式项: ${mode}`,
  2592. );
  2593. }
  2594. /** 读取 config 投影扩展锚点(data-mode / data-usage-*,M5 additive)。 */
  2595. export function getV4ConfigProjection(): Promise<{
  2596. mode: string | null;
  2597. planEnabled: boolean;
  2598. usageUsed: number;
  2599. usageMax: number;
  2600. }> {
  2601. return browser.execute((modelTestId) => {
  2602. const el = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  2603. return {
  2604. mode: el?.getAttribute("data-mode") ?? null,
  2605. usageUsed: Number(el?.getAttribute("data-usage-used") || 0),
  2606. planEnabled: el?.getAttribute("data-plan-enabled") === "true",
  2607. usageMax: Number(el?.getAttribute("data-usage-max") || 0),
  2608. };
  2609. }, TID_V4_MODEL_CONFIG);
  2610. }
  2611. // ── M5 composer mention(@/#/$)/ 附件 ──
  2612. // mention 面板与 slash 面板共用 TID_PROMPT_SUGGESTION_PANEL / _OPTION 契约,
  2613. // 故读取/点选原语与 slash 同源;option-id 前缀区分(file:/session:/skill:)。
  2614. /**
  2615. * 等待 mention 面板出现且含以 prefix 打头的候选项(如 "session:")。
  2616. * 返回首个命中的完整 option-id。
  2617. */
  2618. export async function waitForV4MentionOptionPrefix(
  2619. prefix: string,
  2620. timeout = 15000,
  2621. ): Promise<string> {
  2622. let matched: string | undefined;
  2623. await browser.waitUntil(
  2624. async () => {
  2625. if (!(await hasV4SlashPanel())) return false;
  2626. matched = (await getV4SlashOptionIds()).find((id) => id.startsWith(prefix));
  2627. return Boolean(matched);
  2628. },
  2629. {
  2630. timeout,
  2631. timeoutMsg: `mention 面板没有出现以 "${prefix}" 打头的候选项`,
  2632. },
  2633. );
  2634. return matched as string;
  2635. }
  2636. /** 经真实 paste 事件向 v4 composer 加入一个 File,并走既有 eager upload。 */
  2637. export async function pasteV4ComposerFileAttachment(
  2638. filename = "e2e-pasted.png",
  2639. options: { base64?: string; mimeType?: string; pngBase64?: string } = {},
  2640. ): Promise<string> {
  2641. const pasted = await browser.execute(
  2642. (inputTestId, fileName, explicitBase64, explicitPngBase64, explicitMimeType) => {
  2643. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  2644. const editable =
  2645. input?.querySelector<HTMLElement>('[contenteditable="true"]') ??
  2646. (input?.getAttribute("contenteditable") === "true" ? input : null);
  2647. if (!editable) return false;
  2648. // 修复原因:旧 fixture 虽能被 file 识别为 PNG,但 production Jimp 会拒绝其尾部数据;
  2649. // 使用已通过同一解码器验证的 1×1 PNG,避免图片 E2E 在业务读取前退化为占位文本。
  2650. const imageBase64 =
  2651. explicitBase64 ??
  2652. explicitPngBase64 ??
  2653. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4AWMAAQAABQABNtCI3QAAAABJRU5ErkJggg==";
  2654. const binary = atob(imageBase64);
  2655. const bytes = new Uint8Array(binary.length);
  2656. for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
  2657. const file = new File([bytes], fileName, { type: explicitMimeType ?? "image/png" });
  2658. const dataTransfer = new DataTransfer();
  2659. dataTransfer.items.add(file);
  2660. const pasteEvent = new ClipboardEvent("paste", {
  2661. clipboardData: dataTransfer,
  2662. bubbles: true,
  2663. cancelable: true,
  2664. });
  2665. editable.focus();
  2666. editable.dispatchEvent(pasteEvent);
  2667. return true;
  2668. },
  2669. TID_V4_COMPOSER_INPUT,
  2670. filename,
  2671. options.base64,
  2672. options.pngBase64,
  2673. options.mimeType,
  2674. );
  2675. if (!pasted) {
  2676. throw new Error("v4 composer 输入框没有出现,无法派发粘贴事件");
  2677. }
  2678. return filename;
  2679. }
  2680. /** 向 v4 composer 派发图片文件;保留既有 case 的语义化入口。 */
  2681. export function pasteV4ComposerImageAttachment(
  2682. filename = "e2e-pasted.png",
  2683. options: { base64?: string; mimeType?: string; pngBase64?: string } = {},
  2684. ): Promise<string> {
  2685. return pasteV4ComposerFileAttachment(filename, options);
  2686. }
  2687. /** 等待某个 user 行渲染出附件簇,返回文件 pill 文本及媒体缩略图的可访问文件名。 */
  2688. export async function waitForV4RowAttachments(
  2689. timeout = 60000,
  2690. expectedNames: readonly string[] = [],
  2691. ): Promise<string> {
  2692. let text = "";
  2693. await browser.waitUntil(
  2694. async () => {
  2695. text = await browser.execute((attachmentsPrefix) => {
  2696. const el = document.querySelector<HTMLElement>(`[data-testid^="${attachmentsPrefix}-"]`);
  2697. if (!el) return "";
  2698. // Bug 原因:已发送媒体只有缩略图,文件名由 img alt 承载,不能用 innerText
  2699. // 是否为空来判断附件簇有没有渲染。
  2700. const visibleText = (el.innerText ?? "").trim();
  2701. const mediaFilenames = Array.from(el.querySelectorAll<HTMLImageElement>("img[alt]"))
  2702. .map((image) => image.alt.trim())
  2703. .filter(Boolean);
  2704. return [visibleText, ...mediaFilenames].filter(Boolean).join("\n");
  2705. }, TID_V4_ROW_ATTACHMENTS);
  2706. // 文本卡和媒体缩略图异步挂载;需要整组附件的 case 不能把第一张卡当作全组就绪。
  2707. return text.trim().length > 0 && expectedNames.every((name) => text.includes(name));
  2708. },
  2709. { timeout, timeoutMsg: "user 行没有渲染出附件簇(TID_V4_ROW_ATTACHMENTS)" },
  2710. );
  2711. return text;
  2712. }