zcodeAgentService.test.ts 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970
  1. import {
  2. existsSync,
  3. mkdtempSync,
  4. readFileSync,
  5. realpathSync,
  6. rmSync,
  7. writeFileSync,
  8. } from "node:fs";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { DatabaseSync } from "node:sqlite";
  12. import { afterEach, describe, expect, it, vi } from "vitest";
  13. import {
  14. ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS,
  15. type ZCodeSessionRuntimePreferencesScope,
  16. } from "@zcode/shared";
  17. import { createZCodeAgentService } from "../src/zcode-agent/zcodeAgentService.js";
  18. import { ZCodeAgentProcessManager } from "../src/zcode-agent/zcodeAgentProcessManager.js";
  19. import type { ZCodeProtocolClient } from "../src/zcode-agent/zcodeProtocolClient.js";
  20. import { ZCODE_AGENT_MCP_STATUS_MODE_UNSUPPORTED_ERROR_CODE } from "../src/zcode-agent/zcodeAgentErrors.js";
  21. import type { ZCodeAgentServiceEvent } from "../src/zcode-agent/zcodeAgent.js";
  22. import { getTasksIndexDatabasePath, setDataBaseDir } from "../src/paths.js";
  23. const protocolModelProperties = {
  24. inputFormat: {
  25. supportsText: true,
  26. supportsImage: false,
  27. supportsVideo: false,
  28. supportsAudio: false,
  29. supportsPdf: false,
  30. },
  31. outputFormat: { supportsText: true },
  32. };
  33. const protocolModelPropertiesJson = JSON.stringify(protocolModelProperties);
  34. function createReadyZCodeAgentService(options?: Parameters<typeof createZCodeAgentService>[0]) {
  35. return createZCodeAgentService({
  36. modelSelectionReadinessSource: {
  37. async getView() {
  38. return {
  39. revision: 1,
  40. providers: [
  41. {
  42. providerId: "glm",
  43. config: {
  44. kind: "api" as const,
  45. api: {
  46. type: "openai-chat-completions" as const,
  47. baseUrl: "https://provider.test/v1",
  48. },
  49. models: ["glm-4.6"],
  50. },
  51. models: [{ modelId: "glm-4.6", config: {} }],
  52. },
  53. ],
  54. };
  55. },
  56. },
  57. ...options,
  58. });
  59. }
  60. // 一个最小的 ZCode Protocol stdio fake agent:
  61. // 第一次收到 session/subscribe 返回错误(模拟 "Session is not active" 之类的瞬时失败),
  62. // 第二次返回成功并带一条 session.titleUpdated 事件。用来验证订阅建立失败后会重试。
  63. const FLAKY_SUBSCRIBE_FAKE_AGENT = `
  64. let buf = "";
  65. let subscribeCount = 0;
  66. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  67. process.stdin.on("data", (chunk) => {
  68. buf += chunk.toString("utf8");
  69. let idx;
  70. while ((idx = buf.indexOf("\\n")) >= 0) {
  71. const line = buf.slice(0, idx);
  72. buf = buf.slice(idx + 1);
  73. if (!line.trim()) continue;
  74. let msg;
  75. try { msg = JSON.parse(line); } catch { continue; }
  76. if (msg.method === "session/subscribe" && msg.id !== undefined) {
  77. subscribeCount += 1;
  78. if (subscribeCount === 1) {
  79. send({ id: msg.id, error: { code: -32000, message: "Session is not active" } });
  80. } else {
  81. send({
  82. id: msg.id,
  83. result: {
  84. sessionId: msg.params.sessionId,
  85. eventSeq: 1,
  86. events: [{
  87. type: "session.titleUpdated",
  88. eventId: "evt-1",
  89. sessionId: msg.params.sessionId,
  90. seq: 1,
  91. timestamp: 1700000000000,
  92. payload: { previousTitle: "", source: "default", title: "from-retry" },
  93. }],
  94. },
  95. });
  96. }
  97. }
  98. }
  99. });
  100. `;
  101. const SUBSCRIBE_REPLAY_FAKE_AGENT = `
  102. let buf = "";
  103. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  104. process.stdin.on("data", (chunk) => {
  105. buf += chunk.toString("utf8");
  106. let idx;
  107. while ((idx = buf.indexOf("\\n")) >= 0) {
  108. const line = buf.slice(0, idx);
  109. buf = buf.slice(idx + 1);
  110. if (!line.trim()) continue;
  111. let msg;
  112. try { msg = JSON.parse(line); } catch { continue; }
  113. if (msg.method === "session/subscribe" && msg.id !== undefined) {
  114. send({
  115. id: msg.id,
  116. result: {
  117. sessionId: msg.params.sessionId,
  118. eventSeq: 1,
  119. events: [{
  120. type: "session.titleUpdated",
  121. eventId: "evt-replay-title",
  122. sessionId: msg.params.sessionId,
  123. seq: 1,
  124. timestamp: 1700000000000,
  125. payload: { previousTitle: "", source: "generated", title: "replay-title" },
  126. }],
  127. },
  128. });
  129. }
  130. }
  131. });
  132. `;
  133. const CUA_OPERATION_LIVE_EVENT_FAKE_AGENT = `
  134. let buf = "";
  135. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  136. function operationEvent(kind, eventId, sequenceNumber, sessionId, turnId, extra = {}) {
  137. return {
  138. kind,
  139. eventId,
  140. sequenceNumber,
  141. sessionId,
  142. timestamp: Date.now(),
  143. ...(turnId ? { turnId } : {}),
  144. ...extra,
  145. };
  146. }
  147. process.stdin.on("data", (chunk) => {
  148. buf += chunk.toString("utf8");
  149. let idx;
  150. while ((idx = buf.indexOf("\\n")) >= 0) {
  151. const line = buf.slice(0, idx);
  152. buf = buf.slice(idx + 1);
  153. if (!line.trim()) continue;
  154. let msg;
  155. try { msg = JSON.parse(line); } catch { continue; }
  156. if (msg.method !== "session/subscribe" || msg.id === undefined) continue;
  157. const sessionId = msg.params.sessionId;
  158. send({ id: msg.id, result: { sessionId, eventSeq: 0, events: [] } });
  159. const turnId = "turn-cua-live";
  160. const started = operationEvent("tool-started", "evt-tool-started", 3, sessionId, turnId, {
  161. toolCallId: "call-cua-live",
  162. });
  163. setTimeout(() => {
  164. send({ method: "computer-use/operation-event", params: operationEvent(
  165. "turn-started", "evt-turn-started", 1, sessionId, turnId,
  166. ) });
  167. send({ method: "computer-use/operation-event", params: operationEvent(
  168. "tool-started", "evt-invalid", 2, sessionId, turnId, {
  169. toolCallId: "",
  170. }) });
  171. send({ method: "computer-use/operation-event", params: operationEvent(
  172. "tool-scheduled", "evt-tool-scheduled", 2, sessionId, turnId, {
  173. toolCallId: "call-cua-live",
  174. toolName: "mcp__node_repl__js",
  175. computerUse: true,
  176. }) });
  177. send({ method: "computer-use/operation-event", params: started });
  178. send({ method: "computer-use/operation-event", params: started });
  179. send({ method: "computer-use/operation-event", params: operationEvent(
  180. "turn-completed", "evt-turn-completed", 4, sessionId, turnId,
  181. ) });
  182. }, 0);
  183. }
  184. });
  185. `;
  186. const CUA_OPERATION_RUNTIME_EXIT_FAKE_AGENT = `
  187. let buf = "";
  188. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  189. function operationEvent(kind, eventId, sequenceNumber, sessionId, turnId, extra = {}) {
  190. return {
  191. kind,
  192. eventId,
  193. sequenceNumber,
  194. sessionId,
  195. timestamp: Date.now(),
  196. ...(turnId ? { turnId } : {}),
  197. ...extra,
  198. };
  199. }
  200. process.stdin.on("data", (chunk) => {
  201. buf += chunk.toString("utf8");
  202. let idx;
  203. while ((idx = buf.indexOf("\\n")) >= 0) {
  204. const line = buf.slice(0, idx);
  205. buf = buf.slice(idx + 1);
  206. if (!line.trim()) continue;
  207. let msg;
  208. try { msg = JSON.parse(line); } catch { continue; }
  209. if (msg.method !== "session/subscribe" || msg.id === undefined) continue;
  210. const sessionId = msg.params.sessionId;
  211. send({ id: msg.id, result: { sessionId, eventSeq: 0, events: [] } });
  212. setTimeout(() => {
  213. const turnId = "turn-cua-runtime-exit";
  214. send({ method: "computer-use/operation-event", params: operationEvent(
  215. "turn-started", "evt-runtime-exit-turn", 1, sessionId, turnId,
  216. ) });
  217. send({ method: "computer-use/operation-event", params: operationEvent(
  218. "tool-scheduled", "evt-runtime-exit-scheduled", 2, sessionId, turnId, {
  219. toolCallId: "call-runtime-exit",
  220. toolName: "mcp__node_repl__js",
  221. computerUse: true,
  222. }) });
  223. send({ method: "computer-use/operation-event", params: operationEvent(
  224. "tool-started", "evt-runtime-exit-tool", 3, sessionId, turnId, {
  225. toolCallId: "call-runtime-exit",
  226. }) });
  227. setTimeout(() => process.exit(1), 10);
  228. }, 0);
  229. }
  230. });
  231. `;
  232. const BROWSER_DISCOVERY_FAKE_AGENT = `
  233. let buf = "";
  234. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  235. function context(sessionId) {
  236. return {
  237. requestId: "browser-request-context",
  238. sessionId,
  239. turnId: "turn-browser-1",
  240. workspaceKey: "remote:ssh:dev:/workspace/app",
  241. workspacePath: "/workspace/app",
  242. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  243. remoteSessionId: "remote-session-1",
  244. clientMode: "web-remote-replayable",
  245. sessionContext: "live",
  246. };
  247. }
  248. process.stdin.on("data", (chunk) => {
  249. buf += chunk.toString("utf8");
  250. let idx;
  251. while ((idx = buf.indexOf("\\n")) >= 0) {
  252. const line = buf.slice(0, idx);
  253. buf = buf.slice(idx + 1);
  254. if (!line.trim()) continue;
  255. let msg;
  256. try { msg = JSON.parse(line); } catch { continue; }
  257. if (msg.method === "session/subscribe" && msg.id !== undefined) {
  258. send({
  259. id: msg.id,
  260. result: { sessionId: msg.params.sessionId, eventSeq: 0, events: [] },
  261. });
  262. send({
  263. id: "browser-list-1",
  264. method: "interaction/browserList",
  265. params: context(msg.params.sessionId),
  266. });
  267. continue;
  268. }
  269. if (msg.id === "browser-list-1" && msg.result?.browsers?.[0]?.id) {
  270. send({
  271. id: "browser-execute-1",
  272. method: "interaction/browserExecute",
  273. params: {
  274. ...context("sess-browser"),
  275. requestId: "browser-execute-request",
  276. browserId: msg.result.browsers[0].id,
  277. browserGeneration: msg.result.browsers[0].generation,
  278. command: { method: "getState" },
  279. },
  280. });
  281. }
  282. }
  283. });
  284. `;
  285. const SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT = `
  286. const fs = require("node:fs");
  287. const logPath = process.argv[2];
  288. const rejectBrowserAmbient = process.argv[3] === "reject-browser-ambient";
  289. let buf = "";
  290. let pendingCreate;
  291. let pendingSend;
  292. let userExecutionResolved = false;
  293. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  294. function record(msg) {
  295. fs.appendFileSync(logPath, JSON.stringify({ method: msg.method, params: msg.params }) + "\\n");
  296. }
  297. function rejectBrowserAmbientParams(id) {
  298. const issues = [{
  299. code: "unrecognized_keys",
  300. keys: ["browserAmbientContext"],
  301. path: [],
  302. message: 'Unrecognized key: "browserAmbientContext"',
  303. }];
  304. send({
  305. id,
  306. error: {
  307. code: -32602,
  308. message: 'Invalid params — (root): Unrecognized key: "browserAmbientContext"',
  309. data: { name: "ZodError", message: JSON.stringify(issues) },
  310. },
  311. });
  312. }
  313. function workspaceState(workspace) {
  314. return {
  315. workspace,
  316. settings: {
  317. model: {
  318. current: { providerId: "zai-api", modelId: "glm-4.6" },
  319. available: [{ ref: { providerId: "zai-api", modelId: "glm-4.6" }, label: "GLM 4.6", properties: ${protocolModelPropertiesJson} }],
  320. },
  321. thoughtLevel: { enabled: false, available: [] },
  322. mode: { current: "build" },
  323. },
  324. };
  325. }
  326. function snapshot(workspace, sessionId = "sess_shell_settings") {
  327. return {
  328. protocol: { name: "ZCode Protocol", version: 1 },
  329. session: {
  330. sessionId,
  331. workspace,
  332. sessionKind: "interactive",
  333. title: "Shell settings",
  334. mode: "build",
  335. status: "idle",
  336. createdAt: 1,
  337. updatedAt: 2,
  338. },
  339. settings: workspaceState(workspace).settings,
  340. projection: {
  341. sessionId,
  342. status: "idle",
  343. mode: "build",
  344. turnCount: 1,
  345. totalTokenCount: 0,
  346. contextUsed: 0,
  347. contextWindow: 128000,
  348. pendingPermissions: [],
  349. activeToolCalls: [],
  350. backgroundJobs: [],
  351. },
  352. runtime: { eventSeq: 0, stateRevision: 1, pendingRequestIds: [] },
  353. messages: [],
  354. };
  355. }
  356. process.stdin.on("data", (chunk) => {
  357. buf += chunk.toString("utf8");
  358. let idx;
  359. while ((idx = buf.indexOf("\\n")) >= 0) {
  360. const line = buf.slice(0, idx);
  361. buf = buf.slice(idx + 1);
  362. if (!line.trim()) continue;
  363. let msg;
  364. try { msg = JSON.parse(line); } catch { continue; }
  365. if (msg.method === "session/create" && msg.id !== undefined) {
  366. record(msg);
  367. pendingCreate = msg;
  368. send({
  369. id: "runtime-preferences-materialization",
  370. method: "session/requestRuntimePreferences",
  371. params: {
  372. sessionId: msg.params.sessionId ?? "sess_shell_settings",
  373. scope: "runtime-materialization",
  374. },
  375. });
  376. continue;
  377. }
  378. if (msg.method === "session/resume" && msg.id !== undefined) {
  379. record(msg);
  380. send({ id: msg.id, result: snapshot(msg.params.workspace, msg.params.sessionId) });
  381. continue;
  382. }
  383. if (msg.method === "session/send" && msg.id !== undefined) {
  384. record(msg);
  385. if (rejectBrowserAmbient && msg.params.browserAmbientContext !== undefined) {
  386. rejectBrowserAmbientParams(msg.id);
  387. continue;
  388. }
  389. if (!userExecutionResolved) {
  390. pendingSend = msg;
  391. send({
  392. id: "runtime-preferences-user-execution",
  393. method: "session/requestRuntimePreferences",
  394. params: {
  395. sessionId: msg.params.sessionId,
  396. scope: "user-execution",
  397. },
  398. });
  399. continue;
  400. }
  401. send({
  402. id: msg.id,
  403. result: {
  404. sessionId: msg.params.sessionId,
  405. accepted: true,
  406. stateRevision: 2,
  407. },
  408. });
  409. continue;
  410. }
  411. if (msg.id === "runtime-preferences-materialization" && pendingCreate) {
  412. const create = pendingCreate;
  413. pendingCreate = undefined;
  414. send({ id: create.id, result: snapshot(create.params.workspace, create.params.sessionId) });
  415. continue;
  416. }
  417. if (msg.id === "runtime-preferences-user-execution" && pendingSend) {
  418. const prompt = pendingSend;
  419. pendingSend = undefined;
  420. userExecutionResolved = true;
  421. send({
  422. id: prompt.id,
  423. result: {
  424. sessionId: prompt.params.sessionId,
  425. accepted: true,
  426. stateRevision: 2,
  427. },
  428. });
  429. }
  430. }
  431. });
  432. `;
  433. const RUNTIME_PREFERENCES_FAKE_AGENT = `
  434. const fs = require("node:fs");
  435. const logPath = process.argv[2];
  436. const requestMode = process.argv[3] ?? "valid";
  437. let buf = "";
  438. let pendingCreate;
  439. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  440. function record(obj) { fs.appendFileSync(logPath, JSON.stringify(obj) + "\\n"); }
  441. function workspaceState(workspace) {
  442. return {
  443. workspace,
  444. settings: {
  445. model: {
  446. current: { providerId: "zai-api", modelId: "glm-4.6" },
  447. available: [{ ref: { providerId: "zai-api", modelId: "glm-4.6" }, label: "GLM 4.6", properties: ${protocolModelPropertiesJson} }],
  448. },
  449. thoughtLevel: { enabled: false, available: [] },
  450. mode: { current: "build" },
  451. },
  452. };
  453. }
  454. function snapshot(workspace) {
  455. const sessionId = "sess_runtime_preferences";
  456. return {
  457. protocol: { name: "ZCode Protocol", version: 1 },
  458. session: {
  459. sessionId,
  460. workspace,
  461. sessionKind: "interactive",
  462. title: "Runtime preferences",
  463. mode: "build",
  464. status: "idle",
  465. createdAt: 1,
  466. updatedAt: 2,
  467. },
  468. settings: workspaceState(workspace).settings,
  469. projection: {
  470. sessionId,
  471. status: "idle",
  472. mode: "build",
  473. turnCount: 0,
  474. totalTokenCount: 0,
  475. contextUsed: 0,
  476. contextWindow: 128000,
  477. pendingPermissions: [],
  478. activeToolCalls: [],
  479. backgroundJobs: [],
  480. },
  481. runtime: { eventSeq: 0, stateRevision: 1, pendingRequestIds: [] },
  482. messages: [],
  483. };
  484. }
  485. function completeCreateRequest() {
  486. const msg = pendingCreate;
  487. pendingCreate = undefined;
  488. record({ method: msg.method, params: msg.params });
  489. send({ id: msg.id, result: snapshot(msg.params.workspace) });
  490. }
  491. process.stdin.on("data", (chunk) => {
  492. buf += chunk.toString("utf8");
  493. let idx;
  494. while ((idx = buf.indexOf("\\n")) >= 0) {
  495. const line = buf.slice(0, idx);
  496. buf = buf.slice(idx + 1);
  497. if (!line.trim()) continue;
  498. let msg;
  499. try { msg = JSON.parse(line); } catch { continue; }
  500. if (msg.method === "session/create" && msg.id !== undefined) {
  501. // Worker 进程已经自持 Registry,runtime preferences 在 session 创建时物化。
  502. pendingCreate = msg;
  503. send({
  504. id: "runtime-preferences-1",
  505. method: "session/requestRuntimePreferences",
  506. params: requestMode === "invalid"
  507. ? {}
  508. : { sessionId: "sess_runtime_preferences", scope: "runtime-materialization" },
  509. });
  510. if (requestMode === "disconnect") {
  511. process.stdin.destroy();
  512. process.stdout.end();
  513. }
  514. continue;
  515. }
  516. if (msg.id === "runtime-preferences-1" && (msg.result !== undefined || msg.error)) {
  517. record({
  518. method: "session/requestRuntimePreferences:response",
  519. result: msg.result,
  520. error: msg.error,
  521. });
  522. completeCreateRequest();
  523. }
  524. }
  525. });
  526. `;
  527. const DELAYED_COMPACT_FAKE_AGENT = `
  528. let buf = "";
  529. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  530. function createSnapshot(sessionId) {
  531. return {
  532. protocol: { name: "ZCode Protocol", version: 1 },
  533. session: {
  534. sessionId,
  535. workspace: {
  536. workspacePath: "/workspace/compact",
  537. workspaceKey: "/workspace/compact",
  538. },
  539. sessionKind: "interactive",
  540. title: "Compact",
  541. mode: "build",
  542. status: "idle",
  543. createdAt: 1,
  544. updatedAt: 1,
  545. },
  546. settings: {
  547. model: {
  548. current: { providerId: "glm", modelId: "glm-4.6" },
  549. available: [{ ref: { providerId: "glm", modelId: "glm-4.6" }, label: "GLM 4.6", properties: ${protocolModelPropertiesJson} }],
  550. },
  551. thoughtLevel: { enabled: true, available: [] },
  552. mode: { current: "build" },
  553. },
  554. projection: {
  555. sessionId,
  556. status: "idle",
  557. mode: "build",
  558. turnCount: 0,
  559. totalTokenCount: 0,
  560. contextUsed: 0,
  561. contextWindow: 128000,
  562. pendingPermissions: [],
  563. activeToolCalls: [],
  564. backgroundJobs: [],
  565. },
  566. runtime: { eventSeq: 0, stateRevision: 1, pendingRequestIds: [] },
  567. messages: [],
  568. };
  569. }
  570. process.stdin.on("data", (chunk) => {
  571. buf += chunk.toString("utf8");
  572. let idx;
  573. while ((idx = buf.indexOf("\\n")) >= 0) {
  574. const line = buf.slice(0, idx);
  575. buf = buf.slice(idx + 1);
  576. if (!line.trim()) continue;
  577. let msg;
  578. try { msg = JSON.parse(line); } catch { continue; }
  579. if (msg.method === "session/compact" && msg.id !== undefined) {
  580. setTimeout(() => {
  581. send({
  582. id: msg.id,
  583. result: {
  584. response: "",
  585. snapshot: createSnapshot(msg.params.sessionId),
  586. compact: {
  587. state: "accepted",
  588. inputId: msg.params.inputId,
  589. },
  590. },
  591. });
  592. }, 80);
  593. }
  594. }
  595. });
  596. `;
  597. const LEGACY_CREATE_PARAMS_FAKE_AGENT = `
  598. let buf = "";
  599. let currentWorkspace = null;
  600. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  601. function createSnapshot(workspace, thoughtLevel) {
  602. return {
  603. protocol: { name: "ZCode Protocol", version: 1 },
  604. session: {
  605. sessionId: "sess_compat",
  606. workspace,
  607. sessionKind: "interactive",
  608. title: "Compat",
  609. mode: "build",
  610. status: "idle",
  611. createdAt: 1,
  612. updatedAt: 1,
  613. },
  614. settings: {
  615. model: {
  616. current: { providerId: "glm", modelId: "glm-4.6" },
  617. available: [{ ref: { providerId: "glm", modelId: "glm-4.6" }, label: "GLM 4.6", properties: ${protocolModelPropertiesJson} }],
  618. },
  619. thoughtLevel: {
  620. enabled: true,
  621. current: thoughtLevel,
  622. available: [{ value: "max", label: "Max" }],
  623. },
  624. mode: { current: "build" },
  625. },
  626. projection: {
  627. sessionId: "sess_compat",
  628. status: "idle",
  629. mode: "build",
  630. turnCount: 0,
  631. totalTokenCount: 0,
  632. contextUsed: 0,
  633. contextWindow: 128000,
  634. pendingPermissions: [],
  635. activeToolCalls: [],
  636. backgroundJobs: [],
  637. },
  638. runtime: { eventSeq: 0, stateRevision: thoughtLevel ? 2 : 1, pendingRequestIds: [] },
  639. messages: [],
  640. };
  641. }
  642. function invalidParams(id, keys) {
  643. send({
  644. id,
  645. error: {
  646. code: -32602,
  647. message: "Invalid params",
  648. data: {
  649. name: "ZodError",
  650. message: JSON.stringify([
  651. {
  652. code: "unrecognized_keys",
  653. keys,
  654. path: [],
  655. message: "Unrecognized key",
  656. },
  657. ]),
  658. },
  659. },
  660. });
  661. }
  662. process.stdin.on("data", (chunk) => {
  663. buf += chunk.toString("utf8");
  664. let idx;
  665. while ((idx = buf.indexOf("\\n")) >= 0) {
  666. const line = buf.slice(0, idx);
  667. buf = buf.slice(idx + 1);
  668. if (!line.trim()) continue;
  669. let msg;
  670. try { msg = JSON.parse(line); } catch { continue; }
  671. if (msg.method === "session/create" && msg.id !== undefined) {
  672. const rejectedKeys = [];
  673. if (Object.prototype.hasOwnProperty.call(msg.params, "persistence")) {
  674. rejectedKeys.push("persistence");
  675. }
  676. if (Object.prototype.hasOwnProperty.call(msg.params, "thoughtLevel")) {
  677. rejectedKeys.push("thoughtLevel");
  678. }
  679. if (Object.prototype.hasOwnProperty.call(msg.params, "mcpServers")) {
  680. rejectedKeys.push("mcpServers");
  681. }
  682. if (rejectedKeys.length > 0) {
  683. invalidParams(msg.id, rejectedKeys);
  684. } else {
  685. currentWorkspace = msg.params.workspace;
  686. send({ id: msg.id, result: createSnapshot(msg.params.workspace, undefined) });
  687. }
  688. continue;
  689. }
  690. if (msg.method === "session/setThoughtLevel" && msg.id !== undefined) {
  691. send({ id: msg.id, result: createSnapshot(currentWorkspace, msg.params.thoughtLevel) });
  692. }
  693. }
  694. });
  695. `;
  696. const AUTOMATION_BINDING_CHECK_FAKE_AGENT = `
  697. const fs = require("node:fs");
  698. const logPath = process.argv[2];
  699. let buf = "";
  700. let requested = false;
  701. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  702. setTimeout(() => {
  703. if (requested) return;
  704. requested = true;
  705. send({
  706. id: "binding-check-1",
  707. method: "automation/checkTaskBinding",
  708. params: { targetTaskId: "session-1" },
  709. });
  710. }, 25);
  711. process.stdin.on("data", (chunk) => {
  712. buf += chunk.toString("utf8");
  713. let idx;
  714. while ((idx = buf.indexOf("\\n")) >= 0) {
  715. const line = buf.slice(0, idx);
  716. buf = buf.slice(idx + 1);
  717. if (!line.trim()) continue;
  718. let msg;
  719. try { msg = JSON.parse(line); } catch { continue; }
  720. if (msg.id === "binding-check-1" && (msg.result || msg.error)) {
  721. fs.writeFileSync(logPath, JSON.stringify(msg));
  722. }
  723. }
  724. });
  725. `;
  726. const STALE_THEN_PLUGIN_LIST_FAKE_AGENT = `
  727. const fs = require("node:fs");
  728. const markerPath = process.argv[2];
  729. const shouldHang = !fs.existsSync(markerPath);
  730. if (shouldHang) fs.writeFileSync(markerPath, "hung-once");
  731. let buf = "";
  732. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  733. process.stdin.on("data", (chunk) => {
  734. buf += chunk.toString("utf8");
  735. let idx;
  736. while ((idx = buf.indexOf("\\n")) >= 0) {
  737. const line = buf.slice(0, idx);
  738. buf = buf.slice(idx + 1);
  739. if (!line.trim()) continue;
  740. let msg;
  741. try { msg = JSON.parse(line); } catch { continue; }
  742. if (msg.method === "plugins/list" && msg.id !== undefined) {
  743. if (shouldHang) continue;
  744. send({
  745. id: msg.id,
  746. result: {
  747. plugins: [{
  748. id: "skill-creator@zcode-plugins-official",
  749. name: "skill-creator",
  750. enabled: true,
  751. source: "official",
  752. marketplace: "zcode-plugins-official",
  753. skillCount: 1,
  754. skillRootCount: 1,
  755. commandRootCount: 0,
  756. mcpServerNames: [],
  757. rootPath: "/cache/skill-creator",
  758. }],
  759. diagnostics: [],
  760. },
  761. });
  762. }
  763. }
  764. });
  765. `;
  766. const STALE_THEN_MCP_LIST_FAKE_AGENT = `
  767. const fs = require("node:fs");
  768. const markerPath = process.argv[2];
  769. const shouldHang = !fs.existsSync(markerPath);
  770. if (shouldHang) fs.writeFileSync(markerPath, "hung-once");
  771. let buf = "";
  772. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  773. process.stdin.on("data", (chunk) => {
  774. buf += chunk.toString("utf8");
  775. let idx;
  776. while ((idx = buf.indexOf("\\n")) >= 0) {
  777. const line = buf.slice(0, idx);
  778. buf = buf.slice(idx + 1);
  779. if (!line.trim()) continue;
  780. let msg;
  781. try { msg = JSON.parse(line); } catch { continue; }
  782. if (msg.method === "mcp/list" && msg.id !== undefined) {
  783. if (shouldHang) continue;
  784. send({
  785. id: msg.id,
  786. result: {
  787. statuses: {
  788. filesystem: {
  789. status: "disconnected",
  790. transport: "stdio",
  791. toolCount: 0,
  792. updatedAt: "2026-06-23T00:00:00.000Z",
  793. },
  794. },
  795. },
  796. });
  797. }
  798. }
  799. });
  800. `;
  801. const MCP_LIST_ECHO_CWD_FAKE_AGENT = `
  802. let buf = "";
  803. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  804. process.stdin.on("data", (chunk) => {
  805. buf += chunk.toString("utf8");
  806. let idx;
  807. while ((idx = buf.indexOf("\\n")) >= 0) {
  808. const line = buf.slice(0, idx);
  809. buf = buf.slice(idx + 1);
  810. if (!line.trim()) continue;
  811. let msg;
  812. try { msg = JSON.parse(line); } catch { continue; }
  813. if (msg.method === "mcp/list" && msg.id !== undefined) {
  814. send({
  815. id: msg.id,
  816. result: {
  817. statuses: {
  818. cwd: {
  819. status: "disconnected",
  820. transport: "stdio",
  821. toolCount: 0,
  822. updatedAt: "2026-06-23T00:00:00.000Z",
  823. error: msg.params.workspace.workspacePath,
  824. },
  825. },
  826. },
  827. });
  828. }
  829. }
  830. });
  831. `;
  832. const MCP_LIST_ECHO_MCP_SERVERS_FAKE_AGENT = `
  833. let buf = "";
  834. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  835. process.stdin.on("data", (chunk) => {
  836. buf += chunk.toString("utf8");
  837. let idx;
  838. while ((idx = buf.indexOf("\\n")) >= 0) {
  839. const line = buf.slice(0, idx);
  840. buf = buf.slice(idx + 1);
  841. if (!line.trim()) continue;
  842. let msg;
  843. try { msg = JSON.parse(line); } catch { continue; }
  844. if (msg.method === "mcp/list" && msg.id !== undefined) {
  845. send({
  846. id: msg.id,
  847. result: {
  848. statuses: {
  849. explicit: {
  850. status: "disconnected",
  851. transport: "stdio",
  852. toolCount: 0,
  853. updatedAt: "2026-06-23T00:00:00.000Z",
  854. error: JSON.stringify(msg.params.mcpServers ?? null),
  855. },
  856. },
  857. },
  858. });
  859. }
  860. }
  861. });
  862. `;
  863. const MCP_LIST_ECHO_MODE_FAKE_AGENT = `
  864. let buf = "";
  865. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  866. process.stdin.on("data", (chunk) => {
  867. buf += chunk.toString("utf8");
  868. let idx;
  869. while ((idx = buf.indexOf("\\n")) >= 0) {
  870. const line = buf.slice(0, idx);
  871. buf = buf.slice(idx + 1);
  872. if (!line.trim()) continue;
  873. let msg;
  874. try { msg = JSON.parse(line); } catch { continue; }
  875. if (msg.method === "mcp/list" && msg.id !== undefined) {
  876. send({
  877. id: msg.id,
  878. result: {
  879. statuses: {
  880. mode: {
  881. status: "disconnected",
  882. transport: "stdio",
  883. toolCount: 0,
  884. updatedAt: "2026-06-23T00:00:00.000Z",
  885. error: JSON.stringify(msg.params.mode ?? null),
  886. },
  887. },
  888. },
  889. });
  890. }
  891. }
  892. });
  893. `;
  894. const MCP_LIST_REJECTS_MCP_SERVERS_ONCE_FAKE_AGENT = `
  895. let buf = "";
  896. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  897. process.stdin.on("data", (chunk) => {
  898. buf += chunk.toString("utf8");
  899. let idx;
  900. while ((idx = buf.indexOf("\\n")) >= 0) {
  901. const line = buf.slice(0, idx);
  902. buf = buf.slice(idx + 1);
  903. if (!line.trim()) continue;
  904. let msg;
  905. try { msg = JSON.parse(line); } catch { continue; }
  906. if (msg.method === "mcp/list" && msg.id !== undefined) {
  907. if (msg.params.mcpServers !== undefined) {
  908. send({
  909. id: msg.id,
  910. error: {
  911. code: -32602,
  912. message: "Invalid params",
  913. data: {
  914. message: JSON.stringify([{ code: "unrecognized_keys", keys: ["mcpServers"], path: [] }]),
  915. },
  916. },
  917. });
  918. continue;
  919. }
  920. send({
  921. id: msg.id,
  922. result: {
  923. statuses: {
  924. fallback: {
  925. status: "disconnected",
  926. transport: "stdio",
  927. toolCount: 0,
  928. updatedAt: "2026-06-23T00:00:00.000Z",
  929. error: JSON.stringify(msg.params.mcpServers ?? null),
  930. },
  931. },
  932. },
  933. });
  934. }
  935. }
  936. });
  937. `;
  938. const MCP_LIST_REJECTS_MODE_ONCE_FAKE_AGENT = `
  939. let buf = "";
  940. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  941. process.stdin.on("data", (chunk) => {
  942. buf += chunk.toString("utf8");
  943. let idx;
  944. while ((idx = buf.indexOf("\\n")) >= 0) {
  945. const line = buf.slice(0, idx);
  946. buf = buf.slice(idx + 1);
  947. if (!line.trim()) continue;
  948. let msg;
  949. try { msg = JSON.parse(line); } catch { continue; }
  950. if (msg.method === "mcp/list" && msg.id !== undefined) {
  951. if (msg.params.mode !== undefined) {
  952. send({
  953. id: msg.id,
  954. error: {
  955. code: -32602,
  956. message: "Invalid params",
  957. data: {
  958. message: JSON.stringify([{ code: "unrecognized_keys", keys: ["mode"], path: [] }]),
  959. },
  960. },
  961. });
  962. continue;
  963. }
  964. send({
  965. id: msg.id,
  966. result: {
  967. statuses: {
  968. fallback: {
  969. status: "disconnected",
  970. transport: "stdio",
  971. toolCount: 0,
  972. updatedAt: "2026-06-23T00:00:00.000Z",
  973. },
  974. },
  975. },
  976. });
  977. }
  978. }
  979. });
  980. `;
  981. // 模拟真实 CLI transport 的串行队列:同一进程内 mcp/list 一直不返回,
  982. // 排在它后面的所有请求都拿不到响应(Bug:卸载插件被 30s 的 MCP 探测卡死)。
  983. const SERIAL_QUEUE_HANG_ON_MCP_LIST_FAKE_AGENT = `
  984. const fs = require("node:fs");
  985. const markerPath = process.argv[2];
  986. let buf = "";
  987. let blocked = false;
  988. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  989. process.stdin.on("data", (chunk) => {
  990. buf += chunk.toString("utf8");
  991. let idx;
  992. while ((idx = buf.indexOf("\\n")) >= 0) {
  993. const line = buf.slice(0, idx);
  994. buf = buf.slice(idx + 1);
  995. if (!line.trim()) continue;
  996. let msg;
  997. try { msg = JSON.parse(line); } catch { continue; }
  998. if (msg.id === undefined || !msg.method) continue;
  999. if (blocked) continue;
  1000. if (msg.method === "mcp/list") {
  1001. blocked = true;
  1002. fs.writeFileSync(markerPath, String(process.pid));
  1003. continue;
  1004. }
  1005. if (msg.method === "plugins/uninstall") {
  1006. send({ id: msg.id, result: { diagnostics: [] } });
  1007. }
  1008. }
  1009. });
  1010. `;
  1011. const PLUGIN_LIST_ECHO_CWD_FAKE_AGENT = `
  1012. let buf = "";
  1013. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  1014. process.stdin.on("data", (chunk) => {
  1015. buf += chunk.toString("utf8");
  1016. let idx;
  1017. while ((idx = buf.indexOf("\\n")) >= 0) {
  1018. const line = buf.slice(0, idx);
  1019. buf = buf.slice(idx + 1);
  1020. if (!line.trim()) continue;
  1021. let msg;
  1022. try { msg = JSON.parse(line); } catch { continue; }
  1023. if (msg.method === "plugins/list" && msg.id !== undefined) {
  1024. send({
  1025. id: msg.id,
  1026. result: {
  1027. plugins: [{
  1028. id: "cwd-check@zcode-plugins-official",
  1029. name: "cwd-check",
  1030. enabled: true,
  1031. source: "official",
  1032. marketplace: "zcode-plugins-official",
  1033. skillCount: 0,
  1034. skillRootCount: 0,
  1035. commandRootCount: 0,
  1036. mcpServerNames: [],
  1037. rootPath: process.cwd(),
  1038. }],
  1039. diagnostics: [{
  1040. code: "workspace-path",
  1041. message: msg.params.workspace.workspacePath,
  1042. }],
  1043. },
  1044. });
  1045. }
  1046. }
  1047. });
  1048. `;
  1049. const PLUGIN_UPDATE_ECHO_FAKE_AGENT = `
  1050. let buf = "";
  1051. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  1052. process.stdin.on("data", (chunk) => {
  1053. buf += chunk.toString("utf8");
  1054. let idx;
  1055. while ((idx = buf.indexOf("\\n")) >= 0) {
  1056. const line = buf.slice(0, idx);
  1057. buf = buf.slice(idx + 1);
  1058. if (!line.trim()) continue;
  1059. let msg;
  1060. try { msg = JSON.parse(line); } catch { continue; }
  1061. if (msg.method === "plugins/update" && msg.id !== undefined) {
  1062. send({
  1063. id: msg.id,
  1064. result: {
  1065. installedPlugins: [],
  1066. dependencyClosure: [],
  1067. diagnostics: [{
  1068. code: "echo-plugin-id",
  1069. message: String(msg.params.pluginId),
  1070. }],
  1071. },
  1072. });
  1073. }
  1074. }
  1075. });
  1076. `;
  1077. const PLUGIN_RESTORE_BUILTIN_ECHO_FAKE_AGENT = `
  1078. let buf = "";
  1079. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  1080. process.stdin.on("data", (chunk) => {
  1081. buf += chunk.toString("utf8");
  1082. let idx;
  1083. while ((idx = buf.indexOf("\\n")) >= 0) {
  1084. const line = buf.slice(0, idx);
  1085. buf = buf.slice(idx + 1);
  1086. if (!line.trim()) continue;
  1087. let msg;
  1088. try { msg = JSON.parse(line); } catch { continue; }
  1089. if (msg.method === "plugins/restoreBuiltin" && msg.id !== undefined) {
  1090. send({
  1091. id: msg.id,
  1092. result: {
  1093. pluginId: msg.params.pluginId,
  1094. diagnostics: [],
  1095. },
  1096. });
  1097. }
  1098. }
  1099. });
  1100. `;
  1101. const INTERACTION_PREFERENCES_FAKE_AGENT = `
  1102. const fs = require("node:fs");
  1103. const logPath = process.argv[2];
  1104. const failFirst = process.argv[3] === "fail-first";
  1105. const delayFirst = process.argv[3] === "delay-first";
  1106. let buf = "";
  1107. let updateCount = 0;
  1108. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  1109. process.stdin.on("data", (chunk) => {
  1110. buf += chunk.toString("utf8");
  1111. let idx;
  1112. while ((idx = buf.indexOf("\\n")) >= 0) {
  1113. const line = buf.slice(0, idx);
  1114. buf = buf.slice(idx + 1);
  1115. if (!line.trim()) continue;
  1116. let msg;
  1117. try { msg = JSON.parse(line); } catch { continue; }
  1118. if (msg.method === "workspace/updateModelIoPreferences" && msg.id !== undefined) {
  1119. fs.appendFileSync(logPath + ".model-io", JSON.stringify({
  1120. method: msg.method,
  1121. params: msg.params,
  1122. }) + "\\n");
  1123. send({
  1124. id: msg.id,
  1125. result: {
  1126. workspace: msg.params.workspace,
  1127. fullRetentionEnabled: msg.params.preferences.fullRetentionEnabled,
  1128. updatedSessionCount: 0,
  1129. },
  1130. });
  1131. continue;
  1132. }
  1133. if (msg.method !== "workspace/updateInteractionPreferences" || msg.id === undefined) {
  1134. continue;
  1135. }
  1136. updateCount += 1;
  1137. fs.appendFileSync(logPath, JSON.stringify({
  1138. method: msg.method,
  1139. params: msg.params,
  1140. updateCount,
  1141. }) + "\\n");
  1142. if (failFirst && updateCount === 1) {
  1143. send({ id: msg.id, error: { code: -32000, message: "transient sync failure" } });
  1144. continue;
  1145. }
  1146. const response = {
  1147. id: msg.id,
  1148. result: {
  1149. workspace: msg.params.workspace,
  1150. askUserQuestionAutoResolutionEnabled:
  1151. msg.params.preferences.askUserQuestionAutoResolutionEnabled,
  1152. snoozedInteractionCount: 0,
  1153. },
  1154. };
  1155. if (delayFirst && updateCount === 1) {
  1156. setTimeout(() => send(response), 100);
  1157. } else {
  1158. send(response);
  1159. }
  1160. }
  1161. });
  1162. `;
  1163. describe("createZCodeAgentService", () => {
  1164. it("资源查询仅观察就绪的现存 runtime,透传取消且不启动或等待迁移", async () => {
  1165. const request = vi.fn(async () => ({ processes: [] }));
  1166. const migratingRequest = vi.fn();
  1167. const enumeration = vi
  1168. .spyOn(ZCodeAgentProcessManager.prototype, "listManagedProcesses")
  1169. .mockReturnValue([])
  1170. .mockReturnValueOnce([
  1171. {
  1172. pid: 101,
  1173. workspacePath: "/ready",
  1174. client: {
  1175. request,
  1176. isDisposed: false,
  1177. storageStartup: { isWaiting: false },
  1178. } as unknown as ZCodeProtocolClient,
  1179. },
  1180. {
  1181. pid: 102,
  1182. workspacePath: "/migrating",
  1183. client: {
  1184. request: migratingRequest,
  1185. isDisposed: false,
  1186. storageStartup: { isWaiting: true },
  1187. } as unknown as ZCodeProtocolClient,
  1188. },
  1189. ]);
  1190. const commandResolver = vi.fn(() => null);
  1191. const service = createZCodeAgentService({ commandResolver });
  1192. const controller = new AbortController();
  1193. try {
  1194. await expect(service.collectLocalRuntimeChildProcesses(controller.signal)).resolves.toEqual([
  1195. { pid: 101, workspacePath: "/ready", provider: "glm", children: [] },
  1196. ]);
  1197. expect(request).toHaveBeenCalledWith("process/childProcesses", {}, expect.anything(), {
  1198. lifecycle: "observation",
  1199. timeoutMs: 800,
  1200. signal: controller.signal,
  1201. });
  1202. expect(migratingRequest).not.toHaveBeenCalled();
  1203. expect(commandResolver).not.toHaveBeenCalled();
  1204. } finally {
  1205. enumeration.mockRestore();
  1206. await service.disposeAllAndWait();
  1207. }
  1208. });
  1209. it("does not resolve or spawn a command while provider/model is unavailable", async () => {
  1210. const commandResolver = vi.fn(() => ({
  1211. command: process.execPath,
  1212. args: ["-e", "setInterval(() => {}, 1000);"],
  1213. }));
  1214. const processLifecycleReporter = {
  1215. onSpawn: vi.fn(),
  1216. onExit: vi.fn(),
  1217. onError: vi.fn(),
  1218. };
  1219. const service = createZCodeAgentService({
  1220. commandResolver,
  1221. processLifecycleReporter,
  1222. modelSelectionReadinessSource: {
  1223. async getView() {
  1224. return { revision: 1, providers: [] };
  1225. },
  1226. },
  1227. });
  1228. await expect(
  1229. service.initialize({ workspacePath: "/workspace/provider-waiting" }),
  1230. ).resolves.toMatchObject({
  1231. available: false,
  1232. reasonCode: "provider_not_ready",
  1233. });
  1234. expect(commandResolver).not.toHaveBeenCalled();
  1235. expect(processLifecycleReporter.onSpawn).not.toHaveBeenCalled();
  1236. expect(processLifecycleReporter.onError).not.toHaveBeenCalled();
  1237. await service.disposeAllAndWait();
  1238. });
  1239. const createdDirs: string[] = [];
  1240. afterEach(() => {
  1241. setDataBaseDir(null);
  1242. for (const dir of createdDirs.splice(0).reverse()) {
  1243. // 根因同 zcodeAgentService.v4.test.ts:Windows 上仍有打开句柄的目录删不掉,
  1244. // `force: true` 不重试,afterEach 会以 EPERM 把断言已通过的用例判成失败。
  1245. try {
  1246. rmSync(dir, {
  1247. recursive: true,
  1248. force: true,
  1249. maxRetries: 20,
  1250. retryDelay: 100,
  1251. });
  1252. } catch {
  1253. /* 清理失败不影响断言结论,交给操作系统回收临时目录。 */
  1254. }
  1255. }
  1256. });
  1257. it("caches interaction preferences without spawning and applies ordered snapshots to active/new runtimes", async () => {
  1258. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-interaction-preferences-"));
  1259. createdDirs.push(workspacePath);
  1260. const scriptPath = join(workspacePath, "interaction-preferences-agent.cjs");
  1261. const logPath = join(workspacePath, "protocol.log");
  1262. writeFileSync(scriptPath, INTERACTION_PREFERENCES_FAKE_AGENT);
  1263. const commandResolver = vi.fn(() => ({
  1264. command: process.execPath,
  1265. args: [scriptPath, logPath],
  1266. }));
  1267. const service = createReadyZCodeAgentService({ commandResolver });
  1268. try {
  1269. await service.syncAppRuntimePreferences({
  1270. askUserQuestionAutoResolutionEnabled: false,
  1271. modelIoFullRetentionEnabled: false,
  1272. });
  1273. expect(commandResolver).not.toHaveBeenCalled();
  1274. await expect(service.initialize({ workspacePath })).resolves.toMatchObject({
  1275. available: true,
  1276. });
  1277. await Promise.all([
  1278. service.syncAppRuntimePreferences({
  1279. askUserQuestionAutoResolutionEnabled: true,
  1280. modelIoFullRetentionEnabled: true,
  1281. }),
  1282. service.syncAppRuntimePreferences({
  1283. askUserQuestionAutoResolutionEnabled: false,
  1284. modelIoFullRetentionEnabled: false,
  1285. }),
  1286. ]);
  1287. const updates = readFileSync(logPath, "utf8")
  1288. .trim()
  1289. .split("\n")
  1290. .map(
  1291. (line) =>
  1292. JSON.parse(line) as {
  1293. params: {
  1294. preferences: {
  1295. askUserQuestionAutoResolutionEnabled: boolean;
  1296. };
  1297. workspace: {
  1298. workspaceKey: string;
  1299. workspacePath: string;
  1300. };
  1301. };
  1302. },
  1303. );
  1304. expect(
  1305. updates.map((entry) => entry.params.preferences.askUserQuestionAutoResolutionEnabled),
  1306. ).toEqual([false, true, false]);
  1307. expect(updates[0]?.params.workspace).toMatchObject({
  1308. workspaceKey: workspacePath,
  1309. workspacePath,
  1310. });
  1311. const modelIoUpdates = readFileSync(`${logPath}.model-io`, "utf8")
  1312. .trim()
  1313. .split("\n")
  1314. .map(
  1315. (line) =>
  1316. JSON.parse(line) as {
  1317. params: { preferences: { fullRetentionEnabled: boolean } };
  1318. },
  1319. );
  1320. expect(modelIoUpdates.map((entry) => entry.params.preferences.fullRetentionEnabled)).toEqual([
  1321. false,
  1322. true,
  1323. false,
  1324. ]);
  1325. expect(commandResolver).toHaveBeenCalledTimes(1);
  1326. await service.disposeWorkspace({ workspacePath });
  1327. await expect(service.initialize({ workspacePath })).resolves.toMatchObject({
  1328. available: true,
  1329. });
  1330. const restartedUpdates = readFileSync(logPath, "utf8")
  1331. .trim()
  1332. .split("\n")
  1333. .map((line) => JSON.parse(line) as { params: { preferences: object } });
  1334. expect(restartedUpdates).toHaveLength(4);
  1335. expect(restartedUpdates[3]?.params.preferences).toEqual({
  1336. askUserQuestionAutoResolutionEnabled: false,
  1337. });
  1338. expect(commandResolver).toHaveBeenCalledTimes(2);
  1339. } finally {
  1340. await service.disposeAllAndWait();
  1341. }
  1342. });
  1343. it("retries cached interaction preferences when a new runtime sync fails", async () => {
  1344. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-interaction-retry-"));
  1345. createdDirs.push(workspacePath);
  1346. const scriptPath = join(workspacePath, "interaction-preferences-agent.cjs");
  1347. const logPath = join(workspacePath, "protocol.log");
  1348. writeFileSync(scriptPath, INTERACTION_PREFERENCES_FAKE_AGENT);
  1349. const service = createReadyZCodeAgentService({
  1350. commandResolver: () => ({
  1351. command: process.execPath,
  1352. args: [scriptPath, logPath, "fail-first"],
  1353. }),
  1354. });
  1355. try {
  1356. await service.syncAppRuntimePreferences({
  1357. askUserQuestionAutoResolutionEnabled: false,
  1358. });
  1359. await expect(service.initialize({ workspacePath })).resolves.toMatchObject({
  1360. available: false,
  1361. });
  1362. await expect(service.initialize({ workspacePath })).resolves.toMatchObject({
  1363. available: true,
  1364. });
  1365. const updates = readFileSync(logPath, "utf8")
  1366. .trim()
  1367. .split("\n")
  1368. .map((line) => JSON.parse(line) as { updateCount: number });
  1369. expect(updates.map((entry) => entry.updateCount)).toEqual([1, 2]);
  1370. } finally {
  1371. await service.disposeAllAndWait();
  1372. }
  1373. });
  1374. it("does not lose a rapid preference toggle while a new runtime is applying its cache", async () => {
  1375. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-interaction-startup-race-"));
  1376. createdDirs.push(workspacePath);
  1377. const scriptPath = join(workspacePath, "interaction-preferences-agent.cjs");
  1378. const logPath = join(workspacePath, "protocol.log");
  1379. writeFileSync(scriptPath, INTERACTION_PREFERENCES_FAKE_AGENT);
  1380. const service = createReadyZCodeAgentService({
  1381. commandResolver: () => ({
  1382. command: process.execPath,
  1383. args: [scriptPath, logPath, "delay-first"],
  1384. }),
  1385. });
  1386. try {
  1387. await service.syncAppRuntimePreferences({
  1388. askUserQuestionAutoResolutionEnabled: false,
  1389. });
  1390. const initializing = service.initialize({ workspacePath });
  1391. await vi.waitFor(() => expect(existsSync(logPath)).toBe(true));
  1392. const enabling = service.syncAppRuntimePreferences({
  1393. askUserQuestionAutoResolutionEnabled: true,
  1394. });
  1395. await expect(initializing).resolves.toMatchObject({ available: true });
  1396. await expect(enabling).resolves.toBeUndefined();
  1397. const updates = readFileSync(logPath, "utf8")
  1398. .trim()
  1399. .split("\n")
  1400. .map(
  1401. (line) =>
  1402. JSON.parse(line) as {
  1403. params: {
  1404. preferences: {
  1405. askUserQuestionAutoResolutionEnabled: boolean;
  1406. };
  1407. };
  1408. },
  1409. );
  1410. expect(updates[0]?.params.preferences.askUserQuestionAutoResolutionEnabled).toBe(false);
  1411. expect(updates.at(-1)?.params.preferences.askUserQuestionAutoResolutionEnabled).toBe(true);
  1412. } finally {
  1413. await service.disposeAllAndWait();
  1414. }
  1415. });
  1416. it("dispatcher 缺失时 Run Now 不创建台账或占用 manual claim", async () => {
  1417. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-run-now-"));
  1418. createdDirs.push(sandboxRoot);
  1419. setDataBaseDir(sandboxRoot);
  1420. const workspacePath = "/workspace/run-now";
  1421. const serviceWithoutDispatcher = createZCodeAgentService();
  1422. const automation = await serviceWithoutDispatcher.createAutomation({
  1423. workspacePath,
  1424. title: "daily check",
  1425. cronExpr: "0 9 * * *",
  1426. prompt: "check logs",
  1427. recurring: true,
  1428. });
  1429. await expect(
  1430. serviceWithoutDispatcher.runAutomationNow({
  1431. workspacePath,
  1432. automationId: automation.automationId,
  1433. }),
  1434. ).rejects.toThrow("Automation immediate dispatcher is unavailable.");
  1435. await expect(
  1436. serviceWithoutDispatcher.listAutomationRuns({
  1437. workspacePath,
  1438. automationId: automation.automationId,
  1439. }),
  1440. ).resolves.toEqual([]);
  1441. const dispatch = vi.fn(async () => undefined);
  1442. const serviceWithDispatcher = createZCodeAgentService({
  1443. onAutomationManualRunRequested: dispatch,
  1444. });
  1445. await expect(
  1446. serviceWithDispatcher.runAutomationNow({
  1447. workspacePath,
  1448. automationId: automation.automationId,
  1449. }),
  1450. ).resolves.toEqual({ status: "queued" });
  1451. expect(dispatch).toHaveBeenCalledTimes(1);
  1452. });
  1453. it("automation/checkTaskBinding 不依赖完整列表字段,历史空 mode 仍可完成归属判断", async () => {
  1454. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-binding-check-"));
  1455. createdDirs.push(sandboxRoot);
  1456. setDataBaseDir(sandboxRoot);
  1457. const workspacePath = sandboxRoot;
  1458. const scriptPath = join(sandboxRoot, "binding-check-agent.cjs");
  1459. const logPath = join(sandboxRoot, "binding-check-response.json");
  1460. writeFileSync(scriptPath, AUTOMATION_BINDING_CHECK_FAKE_AGENT);
  1461. const service = createReadyZCodeAgentService({
  1462. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1463. });
  1464. const automation = await service.createAutomation({
  1465. workspacePath,
  1466. title: "legacy task",
  1467. cronExpr: "0 9 * * *",
  1468. prompt: "summarize",
  1469. mode: "build",
  1470. recurring: true,
  1471. });
  1472. const db = new DatabaseSync(getTasksIndexDatabasePath());
  1473. db.prepare(
  1474. "UPDATE automations SET mode = '', target_task_id = 'session-1' WHERE automation_id = ?",
  1475. ).run(automation.automationId);
  1476. db.close();
  1477. try {
  1478. await expect(service.initialize({ workspacePath })).resolves.toMatchObject({
  1479. available: true,
  1480. });
  1481. await vi.waitFor(() => expect(existsSync(logPath)).toBe(true), { timeout: 5000 });
  1482. expect(JSON.parse(readFileSync(logPath, "utf8"))).toEqual({
  1483. id: "binding-check-1",
  1484. result: { bound: true },
  1485. });
  1486. } finally {
  1487. await service.disposeAllAndWait();
  1488. }
  1489. });
  1490. it("reports unavailable without starting a process when no command is configured", async () => {
  1491. const service = createReadyZCodeAgentService({ commandResolver: () => null });
  1492. await expect(
  1493. service.initialize({
  1494. workspacePath: "/workspace/app",
  1495. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  1496. }),
  1497. ).resolves.toMatchObject({
  1498. available: false,
  1499. workspaceKey: "remote:ssh:dev:/workspace/app",
  1500. protocolName: "ZCode Protocol",
  1501. protocolVersion: 1,
  1502. });
  1503. });
  1504. it("starts stdio app-server during initialize", async () => {
  1505. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-"));
  1506. createdDirs.push(workspacePath);
  1507. const commandResolver = vi.fn(() => ({
  1508. command: process.execPath,
  1509. args: ["-e", "setInterval(() => {}, 1000);"],
  1510. }));
  1511. const processLifecycleReporter = {
  1512. onSpawn: vi.fn(),
  1513. onReady: vi.fn(),
  1514. onExit: vi.fn(),
  1515. onError: vi.fn(),
  1516. };
  1517. const service = createReadyZCodeAgentService({ commandResolver, processLifecycleReporter });
  1518. await expect(
  1519. service.initialize({
  1520. workspacePath,
  1521. }),
  1522. ).resolves.toMatchObject({
  1523. available: true,
  1524. workspaceKey: workspacePath,
  1525. protocolName: "ZCode Protocol",
  1526. protocolVersion: 1,
  1527. transportKind: "stdio",
  1528. });
  1529. expect(commandResolver).toHaveBeenCalledTimes(1);
  1530. await vi.waitFor(() => expect(processLifecycleReporter.onReady).toHaveBeenCalledTimes(1));
  1531. expect(processLifecycleReporter.onReady.mock.calls[0]![0]).toMatchObject({
  1532. pid: processLifecycleReporter.onSpawn.mock.calls[0]![0].pid,
  1533. provider: "glm",
  1534. workspacePath,
  1535. runtimeGeneration: 1,
  1536. runtimeInstanceId: processLifecycleReporter.onSpawn.mock.calls[0]![0].runtimeInstanceId,
  1537. readyAt: expect.any(Number),
  1538. startupDurationMs: expect.any(Number),
  1539. });
  1540. await expect(
  1541. service.initialize({
  1542. workspacePath,
  1543. }),
  1544. ).resolves.toMatchObject({ available: true });
  1545. expect(processLifecycleReporter.onReady).toHaveBeenCalledTimes(1);
  1546. await service.disposeAllAndWait();
  1547. await vi.waitFor(() => expect(processLifecycleReporter.onExit).toHaveBeenCalledTimes(1));
  1548. expect(processLifecycleReporter.onExit.mock.calls[0]![0]).toMatchObject({
  1549. runtimeReady: true,
  1550. runtimeInstanceId: processLifecycleReporter.onReady.mock.calls[0]![0].runtimeInstanceId,
  1551. });
  1552. });
  1553. it("routes browser discovery and browserId-aware execute with full remote context", async () => {
  1554. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-browser-"));
  1555. createdDirs.push(workspacePath);
  1556. const scriptPath = join(workspacePath, "browser-agent.cjs");
  1557. writeFileSync(scriptPath, BROWSER_DISCOVERY_FAKE_AGENT);
  1558. const list = vi.fn(async () => [
  1559. {
  1560. id: "iab-runtime-1",
  1561. generation: 1,
  1562. type: "iab" as const,
  1563. name: "ZCode In-app Browser",
  1564. capabilities: {},
  1565. },
  1566. ]);
  1567. const execute = vi.fn(async () => ({
  1568. ok: true,
  1569. state: {
  1570. url: "https://example.com",
  1571. title: "Example",
  1572. canGoBack: false,
  1573. canGoForward: false,
  1574. },
  1575. elapsedMs: 1,
  1576. }));
  1577. const service = createReadyZCodeAgentService({
  1578. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  1579. browserControlExecutor: { list, execute },
  1580. });
  1581. const subscription = service.onDynamicSessionEvent({
  1582. workspacePath,
  1583. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  1584. sessionId: "sess-browser",
  1585. deliveryKind: "web-remote-replayable",
  1586. includeSnapshot: false,
  1587. })(() => {});
  1588. await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(1), {
  1589. timeout: 5000,
  1590. interval: 25,
  1591. });
  1592. expect(list).toHaveBeenCalledWith(
  1593. expect.objectContaining({
  1594. workspaceKey: "remote:ssh:dev:/workspace/app",
  1595. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  1596. remoteSessionId: "remote-session-1",
  1597. clientMode: "web-remote-replayable",
  1598. }),
  1599. );
  1600. expect(execute).toHaveBeenCalledWith(
  1601. expect.objectContaining({
  1602. requestId: "browser-execute-request",
  1603. browserId: "iab-runtime-1",
  1604. browserGeneration: 1,
  1605. sessionId: "sess-browser",
  1606. turnId: "turn-browser-1",
  1607. workspaceKey: "remote:ssh:dev:/workspace/app",
  1608. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  1609. remoteSessionId: "remote-session-1",
  1610. clientMode: "web-remote-replayable",
  1611. command: { method: "getState" },
  1612. }),
  1613. );
  1614. subscription.dispose();
  1615. await service.disposeAllAndWait();
  1616. });
  1617. it("passes session tool lists through protocol session/create", async () => {
  1618. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-tool-list-"));
  1619. createdDirs.push(workspacePath);
  1620. const scriptPath = join(workspacePath, "tool-list-agent.cjs");
  1621. const logPath = join(workspacePath, "protocol.log");
  1622. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1623. // 修复原因:本用例只验证 session/create 的工具列表透传,不验证 provider readiness。
  1624. // 门禁启用后必须复用标准 ready registry fixture,否则测试会在协议请求前被正确拦截。
  1625. const service = createReadyZCodeAgentService({
  1626. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1627. });
  1628. try {
  1629. await service.createSession({
  1630. workspacePath,
  1631. toolAllowlist: ["mcp__zcode-cua__request_access", "mcp__zcode-cua__list_apps"],
  1632. toolDenylist: ["Bash"],
  1633. });
  1634. const createRequest = readFileSync(logPath, "utf8")
  1635. .trim()
  1636. .split("\n")
  1637. .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> })
  1638. .find((entry) => entry.method === "session/create");
  1639. expect(createRequest?.params.toolAllowlist).toEqual([
  1640. "mcp__zcode-cua__request_access",
  1641. "mcp__zcode-cua__list_apps",
  1642. ]);
  1643. expect(createRequest?.params.toolDenylist).toEqual(["Bash"]);
  1644. } finally {
  1645. await service.disposeAllAndWait();
  1646. }
  1647. });
  1648. it("resolves runtime preferences at materialization and first execution without forwarding them", async () => {
  1649. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-shell-snapshot-"));
  1650. createdDirs.push(workspacePath);
  1651. const scriptPath = join(workspacePath, "shell-settings-agent.cjs");
  1652. const logPath = join(workspacePath, "protocol.log");
  1653. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1654. const resolveSessionRuntimePreferences = vi.fn(
  1655. async (scope: ZCodeSessionRuntimePreferencesScope) => ({
  1656. askUserQuestionAutoResolutionEnabled: false,
  1657. nativeSearchEnhancementsEnabled: false,
  1658. memoryEnabled: false,
  1659. modelContextBudgetStrategy:
  1660. scope === "runtime-materialization" ? ("preflight-v1" as const) : ("legacy" as const),
  1661. ...(scope === "user-execution"
  1662. ? {
  1663. integratedTerminalShell: {
  1664. mode: "shell" as const,
  1665. dialect: "git-bash" as const,
  1666. id: "git-bash:/usr/bin/new-session-bash",
  1667. label: "Git Bash",
  1668. path: "/usr/bin/new-session-bash",
  1669. },
  1670. }
  1671. : {}),
  1672. }),
  1673. );
  1674. const service = createReadyZCodeAgentService({
  1675. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1676. resolveSessionRuntimePreferences,
  1677. });
  1678. const created = await service.createSession({ workspacePath });
  1679. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(1);
  1680. expect(resolveSessionRuntimePreferences).toHaveBeenNthCalledWith(1, "runtime-materialization");
  1681. await service.resumeSession({
  1682. workspacePath,
  1683. sessionId: created.session.sessionId,
  1684. });
  1685. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(1);
  1686. await service.sendPrompt({
  1687. workspacePath,
  1688. sessionId: created.session.sessionId,
  1689. content: "continue",
  1690. });
  1691. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(2);
  1692. expect(resolveSessionRuntimePreferences).toHaveBeenNthCalledWith(2, "user-execution");
  1693. await service.sendPrompt({
  1694. workspacePath,
  1695. sessionId: created.session.sessionId,
  1696. content: "second prompt",
  1697. modelSelection: {
  1698. providerId: "test-provider",
  1699. modelId: "test-model",
  1700. options: { reasoningLevel: "high" },
  1701. },
  1702. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  1703. });
  1704. const requests = readFileSync(logPath, "utf8")
  1705. .trim()
  1706. .split("\n")
  1707. .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> });
  1708. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(2);
  1709. expect(requests).toMatchObject([
  1710. { method: "session/create" },
  1711. { method: "session/resume" },
  1712. { method: "session/send" },
  1713. {
  1714. method: "session/send",
  1715. params: {
  1716. modelSelection: {
  1717. providerId: "test-provider",
  1718. modelId: "test-model",
  1719. options: { reasoningLevel: "high" },
  1720. },
  1721. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  1722. },
  1723. },
  1724. ]);
  1725. for (const request of requests) {
  1726. expect(request.params).not.toHaveProperty("integratedTerminalShell");
  1727. expect(request.params).not.toHaveProperty("nativeSearchEnhancementsEnabled");
  1728. expect(request.params).not.toHaveProperty("memoryEnabled");
  1729. expect(request.params).not.toHaveProperty("modelContextBudgetStrategy");
  1730. }
  1731. await service.disposeAllAndWait();
  1732. });
  1733. it("adds bounded IAB ambient context to session/send without changing prompt content", async () => {
  1734. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-browser-ambient-"));
  1735. createdDirs.push(workspacePath);
  1736. const scriptPath = join(workspacePath, "browser-ambient-agent.cjs");
  1737. const logPath = join(workspacePath, "protocol.log");
  1738. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1739. const list = vi.fn(async () => [
  1740. {
  1741. id: "iab-runtime-1",
  1742. generation: 3,
  1743. type: "iab" as const,
  1744. name: "ZCode In-app Browser",
  1745. capabilities: {},
  1746. },
  1747. ]);
  1748. const execute = vi.fn(async (input: { command: { method: string } }) =>
  1749. input.command.method === "list"
  1750. ? { ok: true, tabs: [], elapsedMs: 0 }
  1751. : {
  1752. ok: true,
  1753. userTabs: [
  1754. {
  1755. id: "user-tab-1",
  1756. title: "Current",
  1757. url: "https://example.com/current?q=1",
  1758. },
  1759. ],
  1760. elapsedMs: 0,
  1761. },
  1762. );
  1763. const service = createReadyZCodeAgentService({
  1764. commandResolver: () => ({
  1765. command: process.execPath,
  1766. args: [scriptPath, logPath],
  1767. }),
  1768. browserControlExecutor: { list, execute } as never,
  1769. });
  1770. const workspaceIdentity = "remote:ssh:dev:/workspace/app";
  1771. const created = await service.createSession({
  1772. workspacePath,
  1773. workspaceIdentity,
  1774. });
  1775. await service.sendPrompt({
  1776. workspacePath,
  1777. workspaceIdentity,
  1778. remoteSessionId: "remote-session-1",
  1779. sessionId: created.session.sessionId,
  1780. clientMode: "web-remote-replayable",
  1781. content: "continue",
  1782. });
  1783. const sendRequest = readFileSync(logPath, "utf8")
  1784. .trim()
  1785. .split("\n")
  1786. .map(
  1787. (line) =>
  1788. JSON.parse(line) as {
  1789. method: string;
  1790. params: Record<string, unknown>;
  1791. },
  1792. )
  1793. .find((request) => request.method === "session/send");
  1794. expect(sendRequest?.params).toMatchObject({
  1795. content: "continue",
  1796. browserAmbientContext: {
  1797. tabCount: 1,
  1798. currentUrl: "https://example.com/current?q=1",
  1799. },
  1800. });
  1801. expect(list).toHaveBeenCalledWith(
  1802. expect.objectContaining({
  1803. workspaceKey: workspaceIdentity,
  1804. remoteSessionId: "remote-session-1",
  1805. clientMode: "web-remote-replayable",
  1806. }),
  1807. );
  1808. expect(execute).toHaveBeenCalledTimes(2);
  1809. await service.disposeAllAndWait();
  1810. });
  1811. it("retries session/send without browser ambient context when a legacy agent returns an enhanced invalid params error", async () => {
  1812. const workspacePath = mkdtempSync(
  1813. join(tmpdir(), "zcode-agent-service-browser-ambient-compat-"),
  1814. );
  1815. createdDirs.push(workspacePath);
  1816. const scriptPath = join(workspacePath, "browser-ambient-compat-agent.cjs");
  1817. const logPath = join(workspacePath, "protocol.log");
  1818. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1819. const service = createReadyZCodeAgentService({
  1820. commandResolver: () => ({
  1821. command: process.execPath,
  1822. args: [scriptPath, logPath, "reject-browser-ambient"],
  1823. }),
  1824. browserControlExecutor: {
  1825. list: vi.fn(async () => [
  1826. {
  1827. id: "iab-runtime-legacy",
  1828. generation: 1,
  1829. type: "iab" as const,
  1830. name: "ZCode In-app Browser",
  1831. capabilities: {},
  1832. },
  1833. ]),
  1834. execute: vi.fn(async (input: { command: { method: string } }) =>
  1835. input.command.method === "list"
  1836. ? { ok: true, tabs: [], elapsedMs: 0 }
  1837. : {
  1838. ok: true,
  1839. userTabs: [
  1840. {
  1841. id: "user-tab-legacy",
  1842. title: "Current",
  1843. url: "https://example.com/current",
  1844. },
  1845. ],
  1846. elapsedMs: 0,
  1847. },
  1848. ),
  1849. } as never,
  1850. });
  1851. const created = await service.createSession({ workspacePath });
  1852. await expect(
  1853. service.sendPrompt({
  1854. workspacePath,
  1855. sessionId: created.session.sessionId,
  1856. content: "continue",
  1857. }),
  1858. ).resolves.toMatchObject({ accepted: true });
  1859. const sendRequests = readFileSync(logPath, "utf8")
  1860. .trim()
  1861. .split("\n")
  1862. .map(
  1863. (line) =>
  1864. JSON.parse(line) as {
  1865. method: string;
  1866. params: Record<string, unknown>;
  1867. },
  1868. )
  1869. .filter((request) => request.method === "session/send");
  1870. expect(sendRequests).toHaveLength(2);
  1871. expect(sendRequests[0]?.params).toHaveProperty("browserAmbientContext");
  1872. expect(sendRequests[1]?.params).not.toHaveProperty("browserAmbientContext");
  1873. expect(sendRequests[1]?.params.content).toBe("continue");
  1874. await service.disposeAllAndWait();
  1875. });
  1876. it("resolves execution preferences before a deferred draft accepts its first prompt", async () => {
  1877. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-shell-draft-"));
  1878. createdDirs.push(workspacePath);
  1879. const scriptPath = join(workspacePath, "shell-settings-agent.cjs");
  1880. const logPath = join(workspacePath, "protocol.log");
  1881. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1882. const resolveSessionRuntimePreferences = vi.fn(async () => ({
  1883. askUserQuestionAutoResolutionEnabled: true,
  1884. nativeSearchEnhancementsEnabled: true,
  1885. memoryEnabled: true,
  1886. integratedTerminalShell: {
  1887. mode: "shell" as const,
  1888. dialect: "git-bash" as const,
  1889. id: "git-bash:/usr/bin/first-send-bash",
  1890. label: "Git Bash",
  1891. path: "/usr/bin/first-send-bash",
  1892. },
  1893. }));
  1894. const service = createReadyZCodeAgentService({
  1895. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1896. resolveSessionRuntimePreferences,
  1897. });
  1898. const draft = await service.createSession({ workspacePath, persistence: "deferred" });
  1899. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(1);
  1900. await service.sendPrompt({
  1901. workspacePath,
  1902. sessionId: draft.session.sessionId,
  1903. content: "first prompt",
  1904. });
  1905. const requests = readFileSync(logPath, "utf8")
  1906. .trim()
  1907. .split("\n")
  1908. .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> });
  1909. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(2);
  1910. expect(requests).toMatchObject([
  1911. {
  1912. method: "session/create",
  1913. params: {
  1914. persistence: "deferred",
  1915. },
  1916. },
  1917. {
  1918. method: "session/send",
  1919. },
  1920. ]);
  1921. for (const request of requests) {
  1922. expect(request.params).not.toHaveProperty("integratedTerminalShell");
  1923. expect(request.params).not.toHaveProperty("nativeSearchEnhancementsEnabled");
  1924. expect(request.params).not.toHaveProperty("memoryEnabled");
  1925. }
  1926. await service.disposeAllAndWait();
  1927. });
  1928. it("answers Agent runtime preference requests from the Host resolver", async () => {
  1929. const cases: Array<{
  1930. name: string;
  1931. requestMode?: "invalid" | "valid";
  1932. resolver?: ReturnType<
  1933. typeof vi.fn<
  1934. () => Promise<{
  1935. askUserQuestionAutoResolutionEnabled: boolean;
  1936. nativeSearchEnhancementsEnabled: boolean;
  1937. memoryEnabled: boolean;
  1938. }>
  1939. >
  1940. >;
  1941. expectedResult?: {
  1942. askUserQuestionAutoResolutionEnabled: boolean;
  1943. nativeSearchEnhancementsEnabled: boolean;
  1944. subagentRuntimeConfigEnabled: boolean;
  1945. memoryEnabled: boolean;
  1946. modelContextBudgetStrategy: "legacy" | "preflight-v1";
  1947. };
  1948. expectedErrorCode?: number;
  1949. expectedResolverCalls: number;
  1950. }> = [
  1951. {
  1952. name: "current-setting",
  1953. resolver: vi.fn(async () => ({
  1954. askUserQuestionAutoResolutionEnabled: false,
  1955. nativeSearchEnhancementsEnabled: false,
  1956. memoryEnabled: false,
  1957. })),
  1958. expectedResult: {
  1959. askUserQuestionAutoResolutionEnabled: false,
  1960. nativeSearchEnhancementsEnabled: false,
  1961. subagentRuntimeConfigEnabled: false,
  1962. memoryEnabled: false,
  1963. modelContextBudgetStrategy: "preflight-v1" as const,
  1964. },
  1965. expectedResolverCalls: 1,
  1966. },
  1967. {
  1968. name: "missing-resolver",
  1969. expectedResult: {
  1970. askUserQuestionAutoResolutionEnabled: true,
  1971. nativeSearchEnhancementsEnabled: true,
  1972. subagentRuntimeConfigEnabled: false,
  1973. memoryEnabled: false,
  1974. modelContextBudgetStrategy: "preflight-v1" as const,
  1975. },
  1976. expectedResolverCalls: 0,
  1977. },
  1978. {
  1979. name: "resolver-failure",
  1980. resolver: vi.fn(async () => {
  1981. throw new Error("setting failed");
  1982. }),
  1983. expectedErrorCode: -32603,
  1984. expectedResolverCalls: 1,
  1985. },
  1986. {
  1987. name: "invalid-params",
  1988. requestMode: "invalid",
  1989. resolver: vi.fn(async () => ({
  1990. askUserQuestionAutoResolutionEnabled: false,
  1991. nativeSearchEnhancementsEnabled: false,
  1992. memoryEnabled: false,
  1993. })),
  1994. expectedErrorCode: -32602,
  1995. expectedResolverCalls: 0,
  1996. },
  1997. ];
  1998. for (const testCase of cases) {
  1999. const workspacePath = mkdtempSync(
  2000. join(tmpdir(), `zcode-agent-runtime-preferences-${testCase.name}-`),
  2001. );
  2002. createdDirs.push(workspacePath);
  2003. const scriptPath = join(workspacePath, "runtime-preferences-agent.cjs");
  2004. const logPath = join(workspacePath, "protocol.log");
  2005. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2006. const service = createReadyZCodeAgentService({
  2007. commandResolver: () => ({
  2008. command: process.execPath,
  2009. args: [scriptPath, logPath, testCase.requestMode ?? "valid"],
  2010. }),
  2011. resolveSessionRuntimePreferences: testCase.resolver,
  2012. });
  2013. try {
  2014. await service.createSession({ workspacePath });
  2015. const response = readFileSync(logPath, "utf8")
  2016. .trim()
  2017. .split("\n")
  2018. .map(
  2019. (line) =>
  2020. JSON.parse(line) as {
  2021. error?: { code: number; message: string };
  2022. method: string;
  2023. result?: {
  2024. askUserQuestionAutoResolutionEnabled: boolean;
  2025. nativeSearchEnhancementsEnabled: boolean;
  2026. subagentRuntimeConfigEnabled: boolean;
  2027. memoryEnabled: boolean;
  2028. modelContextBudgetStrategy: "legacy" | "preflight-v1";
  2029. };
  2030. },
  2031. )
  2032. .find((entry) => entry.method === "session/requestRuntimePreferences:response");
  2033. expect(response, testCase.name).toBeDefined();
  2034. if (testCase.expectedResult) {
  2035. expect(response?.result, testCase.name).toEqual(testCase.expectedResult);
  2036. expect(response?.error, testCase.name).toBeUndefined();
  2037. } else {
  2038. expect(response?.error, testCase.name).toMatchObject({
  2039. code: testCase.expectedErrorCode,
  2040. });
  2041. }
  2042. if (testCase.resolver) {
  2043. expect(testCase.resolver, testCase.name).toHaveBeenCalledTimes(
  2044. testCase.expectedResolverCalls,
  2045. );
  2046. }
  2047. } finally {
  2048. await service.disposeAllAndWait();
  2049. }
  2050. }
  2051. });
  2052. it("does not send a second runtime preference response after the Agent disconnects", async () => {
  2053. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-runtime-preferences-close-"));
  2054. createdDirs.push(workspacePath);
  2055. const scriptPath = join(workspacePath, "runtime-preferences-agent.cjs");
  2056. const logPath = join(workspacePath, "protocol.log");
  2057. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2058. let markResolverStarted!: () => void;
  2059. let releaseResolver!: () => void;
  2060. let markResolverFinished!: () => void;
  2061. const resolverStarted = new Promise<void>((resolve) => {
  2062. markResolverStarted = resolve;
  2063. });
  2064. const resolverReleased = new Promise<void>((resolve) => {
  2065. releaseResolver = resolve;
  2066. });
  2067. const resolverFinished = new Promise<void>((resolve) => {
  2068. markResolverFinished = resolve;
  2069. });
  2070. const service = createReadyZCodeAgentService({
  2071. commandResolver: () => ({
  2072. command: process.execPath,
  2073. args: [scriptPath, logPath, "disconnect"],
  2074. }),
  2075. resolveSessionRuntimePreferences: async () => {
  2076. markResolverStarted();
  2077. await resolverReleased;
  2078. markResolverFinished();
  2079. return {
  2080. askUserQuestionAutoResolutionEnabled: false,
  2081. nativeSearchEnhancementsEnabled: false,
  2082. memoryEnabled: false,
  2083. };
  2084. },
  2085. });
  2086. try {
  2087. const createResult = service.createSession({ workspacePath }).then(
  2088. () => null,
  2089. (error: unknown) => error,
  2090. );
  2091. await resolverStarted;
  2092. expect(await createResult).toBeInstanceOf(Error);
  2093. releaseResolver();
  2094. await resolverFinished;
  2095. await new Promise<void>((resolve) => setImmediate(resolve));
  2096. } finally {
  2097. await service.disposeAllAndWait();
  2098. }
  2099. });
  2100. it("routes external runtime preference requests by opaque requestId", async () => {
  2101. const fixtureDir = mkdtempSync(join(tmpdir(), "zcode-agent-external-preferences-"));
  2102. const firstWorkspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-preferences-first-"));
  2103. const secondWorkspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-preferences-second-"));
  2104. createdDirs.push(fixtureDir, firstWorkspacePath, secondWorkspacePath);
  2105. const scriptPath = join(fixtureDir, "runtime-preferences-agent.cjs");
  2106. const logPath = join(fixtureDir, "protocol.log");
  2107. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2108. const service = createReadyZCodeAgentService({
  2109. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  2110. sessionRuntimePreferencesAuthority: "external",
  2111. });
  2112. const requests: Array<{ requestId: string; sessionId: string; scope: string }> = [];
  2113. const subscription = service.onDynamicSessionRuntimePreferencesRequest()((request) => {
  2114. requests.push(request);
  2115. void service.respondSessionRuntimePreferences({
  2116. requestId: request.requestId,
  2117. resolution: {
  2118. status: "resolved",
  2119. preferences: {
  2120. askUserQuestionAutoResolutionEnabled: false,
  2121. nativeSearchEnhancementsEnabled: false,
  2122. memoryEnabled: false,
  2123. },
  2124. },
  2125. });
  2126. });
  2127. try {
  2128. await service.createSession({ workspacePath: firstWorkspacePath });
  2129. await service.createSession({ workspacePath: secondWorkspacePath });
  2130. expect(requests).toHaveLength(2);
  2131. expect(new Set(requests.map((request) => request.requestId)).size).toBe(2);
  2132. for (const request of requests) {
  2133. expect(request).toMatchObject({
  2134. sessionId: "sess_runtime_preferences",
  2135. scope: "runtime-materialization",
  2136. });
  2137. expect(request).not.toHaveProperty("workspacePath");
  2138. expect(request).not.toHaveProperty("workspaceIdentity");
  2139. }
  2140. } finally {
  2141. subscription.dispose();
  2142. await service.disposeAllAndWait();
  2143. }
  2144. });
  2145. it("expires unanswered external runtime preference requests without replaying them", async () => {
  2146. vi.useFakeTimers({ toFake: ["clearTimeout", "setTimeout"] });
  2147. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-preferences-timeout-"));
  2148. createdDirs.push(workspacePath);
  2149. const scriptPath = join(workspacePath, "runtime-preferences-agent.cjs");
  2150. const logPath = join(workspacePath, "protocol.log");
  2151. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2152. const service = createReadyZCodeAgentService({
  2153. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  2154. sessionRuntimePreferencesAuthority: "external",
  2155. });
  2156. let markRequestSeen!: () => void;
  2157. const requestSeen = new Promise<void>((resolve) => {
  2158. markRequestSeen = resolve;
  2159. });
  2160. const subscription = service.onDynamicSessionRuntimePreferencesRequest()(() => {
  2161. markRequestSeen();
  2162. });
  2163. try {
  2164. const createPromise = service.createSession({ workspacePath });
  2165. await requestSeen;
  2166. await vi.advanceTimersByTimeAsync(ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS);
  2167. await createPromise;
  2168. const response = readFileSync(logPath, "utf8")
  2169. .trim()
  2170. .split("\n")
  2171. .map(
  2172. (line) =>
  2173. JSON.parse(line) as {
  2174. error?: { code: number; data?: { timeoutMs?: number } };
  2175. method: string;
  2176. },
  2177. )
  2178. .find((entry) => entry.method === "session/requestRuntimePreferences:response");
  2179. expect(response?.error).toEqual({
  2180. code: -32022,
  2181. data: {
  2182. timeoutMs: ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS,
  2183. },
  2184. message: "Session runtime preferences request timed out",
  2185. });
  2186. subscription.dispose();
  2187. const replayedRequests: unknown[] = [];
  2188. const replaySubscription = service.onDynamicSessionRuntimePreferencesRequest()((request) => {
  2189. replayedRequests.push(request);
  2190. });
  2191. expect(replayedRequests).toEqual([]);
  2192. replaySubscription.dispose();
  2193. } finally {
  2194. subscription.dispose();
  2195. vi.useRealTimers();
  2196. await service.disposeAllAndWait();
  2197. }
  2198. });
  2199. it("uses the compact-specific request timeout for delayed compact ACKs", async () => {
  2200. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-compact-timeout-"));
  2201. createdDirs.push(workspacePath);
  2202. const scriptPath = join(workspacePath, "delayed-compact-agent.cjs");
  2203. writeFileSync(scriptPath, DELAYED_COMPACT_FAKE_AGENT);
  2204. const service = createReadyZCodeAgentService({
  2205. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2206. requestTimeoutMs: 20,
  2207. });
  2208. try {
  2209. const result = await service.compactSession({
  2210. workspacePath,
  2211. sessionId: "sess_compact_timeout",
  2212. inputId: "input_compact_timeout",
  2213. });
  2214. expect(result.compact).toMatchObject({
  2215. state: "accepted",
  2216. inputId: "input_compact_timeout",
  2217. });
  2218. } finally {
  2219. await service.disposeAllAndWait();
  2220. }
  2221. });
  2222. it("retries session subscription after a transient subscribe failure", async () => {
  2223. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-retry-"));
  2224. createdDirs.push(workspacePath);
  2225. const scriptPath = join(workspacePath, "flaky-agent.cjs");
  2226. writeFileSync(scriptPath, FLAKY_SUBSCRIBE_FAKE_AGENT);
  2227. const service = createReadyZCodeAgentService({
  2228. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2229. });
  2230. const received: ZCodeAgentServiceEvent[] = [];
  2231. const subscription = service.onDynamicSessionEvent({
  2232. workspacePath,
  2233. sessionId: "sess-1",
  2234. deliveryKind: "desktop-continuous",
  2235. includeSnapshot: false,
  2236. })((event) => received.push(event));
  2237. // 第一次 subscribe 失败后必须重试,最终把成功响应里的事件投递出来。
  2238. await vi.waitFor(
  2239. () => {
  2240. expect(received.some((event) => event.type === "session.event")).toBe(true);
  2241. },
  2242. { timeout: 5000, interval: 50 },
  2243. );
  2244. subscription.dispose();
  2245. await service.disposeAllAndWait();
  2246. });
  2247. it("delivers subscribe replay events only to the subscriber that requested them", async () => {
  2248. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-replay-"));
  2249. createdDirs.push(workspacePath);
  2250. const scriptPath = join(workspacePath, "replay-agent.cjs");
  2251. writeFileSync(scriptPath, SUBSCRIBE_REPLAY_FAKE_AGENT);
  2252. const service = createReadyZCodeAgentService({
  2253. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2254. });
  2255. const firstReceived: ZCodeAgentServiceEvent[] = [];
  2256. const firstSubscription = service.onDynamicSessionEvent({
  2257. workspacePath,
  2258. sessionId: "sess-1",
  2259. deliveryKind: "desktop-continuous",
  2260. includeSnapshot: false,
  2261. })((event) => firstReceived.push(event));
  2262. await vi.waitFor(
  2263. () => {
  2264. expect(firstReceived.filter((event) => event.type === "session.event")).toHaveLength(1);
  2265. },
  2266. { timeout: 5000, interval: 50 },
  2267. );
  2268. const secondReceived: ZCodeAgentServiceEvent[] = [];
  2269. const secondSubscription = service.onDynamicSessionEvent({
  2270. workspacePath,
  2271. sessionId: "sess-1",
  2272. deliveryKind: "desktop-continuous",
  2273. includeSnapshot: false,
  2274. })((event) => secondReceived.push(event));
  2275. await vi.waitFor(
  2276. () => {
  2277. expect(secondReceived.filter((event) => event.type === "session.event")).toHaveLength(1);
  2278. },
  2279. { timeout: 5000, interval: 50 },
  2280. );
  2281. // Bugfix: 第二个订阅者自己的 replay 缺口不能广播回第一个订阅者。
  2282. expect(firstReceived.filter((event) => event.type === "session.event")).toHaveLength(1);
  2283. firstSubscription.dispose();
  2284. secondSubscription.dispose();
  2285. await service.disposeAllAndWait();
  2286. });
  2287. it("reports only validated de-duplicated CUA sideband events without legacy session delivery", async () => {
  2288. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-cua-operation-live-"));
  2289. createdDirs.push(workspacePath);
  2290. const scriptPath = join(workspacePath, "cua-operation-live-agent.cjs");
  2291. writeFileSync(scriptPath, CUA_OPERATION_LIVE_EVENT_FAKE_AGENT);
  2292. const reportedStates: Array<{ active: boolean; sessionId: string; turnId: string }> = [];
  2293. const observedServiceActiveStates: boolean[] = [];
  2294. let service: ReturnType<typeof createReadyZCodeAgentService>;
  2295. const onStateChanged = vi.fn(
  2296. (event: { active: boolean; sessionId: string; turnId: string }) => {
  2297. reportedStates.push(event);
  2298. observedServiceActiveStates.push(service.hasActiveCuaOperationTurn());
  2299. if (event.active) throw new Error("host port closed");
  2300. },
  2301. );
  2302. service = createReadyZCodeAgentService({
  2303. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2304. cuaOperationStateReporter: { onStateChanged },
  2305. });
  2306. expect(service.hasActiveCuaOperationTurn()).toBe(false);
  2307. const received: ZCodeAgentServiceEvent[] = [];
  2308. const subscription = service.onDynamicSessionEvent({
  2309. workspacePath,
  2310. sessionId: "sess-cua-live",
  2311. deliveryKind: "desktop-continuous",
  2312. includeSnapshot: false,
  2313. })((event) => received.push(event));
  2314. try {
  2315. await vi.waitFor(
  2316. () => {
  2317. expect(reportedStates.map((event) => event.active)).toEqual([true, false]);
  2318. },
  2319. { timeout: 5_000, interval: 50 },
  2320. );
  2321. const liveEvents = received
  2322. .filter(
  2323. (event): event is Extract<ZCodeAgentServiceEvent, { type: "session.event" }> =>
  2324. event.type === "session.event",
  2325. )
  2326. .map((event) => event.event);
  2327. expect(liveEvents).toEqual([]);
  2328. expect(onStateChanged).toHaveBeenCalledTimes(2);
  2329. expect(observedServiceActiveStates).toEqual([true, false]);
  2330. } finally {
  2331. subscription.dispose();
  2332. await service.disposeAllAndWait();
  2333. }
  2334. });
  2335. it("clears CUA state when the runtime becomes unavailable without a restart", async () => {
  2336. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-cua-runtime-exit-"));
  2337. createdDirs.push(workspacePath);
  2338. const scriptPath = join(workspacePath, "cua-operation-runtime-exit-agent.cjs");
  2339. writeFileSync(scriptPath, CUA_OPERATION_RUNTIME_EXIT_FAKE_AGENT);
  2340. const reportedStates: boolean[] = [];
  2341. const service = createReadyZCodeAgentService({
  2342. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2343. cuaOperationStateReporter: {
  2344. onStateChanged: (event) => reportedStates.push(event.active),
  2345. },
  2346. });
  2347. const subscription = service.onDynamicSessionEvent({
  2348. workspacePath,
  2349. sessionId: "sess-cua-runtime-exit",
  2350. deliveryKind: "desktop-continuous",
  2351. includeSnapshot: false,
  2352. })(() => undefined);
  2353. try {
  2354. await vi.waitFor(
  2355. () => {
  2356. expect(reportedStates).toEqual([true, false]);
  2357. expect(service.hasActiveCuaOperationTurn()).toBe(false);
  2358. },
  2359. { timeout: 5_000, interval: 50 },
  2360. );
  2361. } finally {
  2362. subscription.dispose();
  2363. await service.disposeAllAndWait();
  2364. }
  2365. });
  2366. it("retries createSession without optional fields rejected by legacy agents", async () => {
  2367. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-compat-"));
  2368. createdDirs.push(workspacePath);
  2369. const scriptPath = join(workspacePath, "legacy-create-agent.cjs");
  2370. writeFileSync(scriptPath, LEGACY_CREATE_PARAMS_FAKE_AGENT);
  2371. const service = createReadyZCodeAgentService({
  2372. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2373. });
  2374. try {
  2375. const snapshot = await service.createSession({
  2376. workspacePath,
  2377. model: { providerId: "glm", modelId: "glm-4.6" },
  2378. persistence: "deferred",
  2379. thoughtLevel: "max",
  2380. mcpServers: [
  2381. {
  2382. name: "chrome-devtools",
  2383. command: "npx",
  2384. args: ["-y", "chrome-devtools-mcp@latest"],
  2385. env: [],
  2386. },
  2387. ],
  2388. });
  2389. expect(snapshot.session.sessionId).toBe("sess_compat");
  2390. expect(snapshot.settings.thoughtLevel.current).toBe("max");
  2391. } finally {
  2392. await service.disposeAllAndWait();
  2393. }
  2394. });
  2395. it("restarts a stale protocol client and retries plugin list without provider registry sync", async () => {
  2396. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugins-"));
  2397. createdDirs.push(workspacePath);
  2398. const scriptPath = join(workspacePath, "stale-plugin-agent.cjs");
  2399. const markerPath = join(workspacePath, "first-run-marker");
  2400. writeFileSync(scriptPath, STALE_THEN_PLUGIN_LIST_FAKE_AGENT);
  2401. const commandResolver = vi.fn(() => ({
  2402. command: process.execPath,
  2403. args: [scriptPath, markerPath],
  2404. }));
  2405. const service = createReadyZCodeAgentService({
  2406. commandResolver,
  2407. // Bugfix: 该用例只需要首个 fake agent 超时,full suite 并发时第二个进程启动到响应可能超过 500ms。
  2408. // 局部放宽 request timeout,避免把重启后成功恢复的路径误判成第二次 stale。
  2409. requestTimeoutMs: 1_500,
  2410. });
  2411. try {
  2412. const result = await service.listPlugins({ workspacePath });
  2413. expect(result.plugins.map((plugin) => plugin.name)).toEqual(["skill-creator"]);
  2414. expect(commandResolver).toHaveBeenCalledTimes(2);
  2415. } finally {
  2416. await service.disposeAllAndWait();
  2417. }
  2418. });
  2419. it("loads plugin list from the dedicated plugin workspace when the real workspace is missing", async () => {
  2420. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugin-cwd-"));
  2421. createdDirs.push(sandboxRoot);
  2422. setDataBaseDir(sandboxRoot);
  2423. const scriptPath = join(sandboxRoot, "plugin-cwd-agent.cjs");
  2424. writeFileSync(scriptPath, PLUGIN_LIST_ECHO_CWD_FAKE_AGENT);
  2425. const missingWorkspacePath = join(sandboxRoot, "deleted-workspace");
  2426. const pluginWorkspacePath = join(sandboxRoot, ".zcode", "plugin-workspace");
  2427. const commandResolver = vi.fn(({ workspacePath }) => ({
  2428. command: process.execPath,
  2429. args: [scriptPath],
  2430. cwd: workspacePath,
  2431. }));
  2432. const service = createReadyZCodeAgentService({ commandResolver });
  2433. try {
  2434. const result = await service.listPlugins({ workspacePath: missingWorkspacePath });
  2435. expect(existsSync(pluginWorkspacePath)).toBe(true);
  2436. expect(realpathSync(result.plugins[0]!.rootPath)).toBe(realpathSync(pluginWorkspacePath));
  2437. expect(result.diagnostics[0]?.message).toBe(missingWorkspacePath);
  2438. expect(commandResolver).toHaveBeenCalledWith({
  2439. workspacePath: pluginWorkspacePath,
  2440. workspaceKey: pluginWorkspacePath,
  2441. });
  2442. } finally {
  2443. await service.disposeAllAndWait();
  2444. }
  2445. });
  2446. it("updatePlugin issues plugins/update with the requested pluginId", async () => {
  2447. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugin-update-"));
  2448. createdDirs.push(workspacePath);
  2449. const scriptPath = join(workspacePath, "plugin-update-agent.cjs");
  2450. writeFileSync(scriptPath, PLUGIN_UPDATE_ECHO_FAKE_AGENT);
  2451. const service = createReadyZCodeAgentService({
  2452. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2453. });
  2454. try {
  2455. const result = await service.updatePlugin({
  2456. workspacePath,
  2457. pluginId: "skill-creator@zcode-plugins-official",
  2458. });
  2459. expect(result.installedPlugins).toEqual([]);
  2460. expect(result.diagnostics[0]?.code).toBe("echo-plugin-id");
  2461. expect(result.diagnostics[0]?.message).toBe("skill-creator@zcode-plugins-official");
  2462. } finally {
  2463. await service.disposeAllAndWait();
  2464. }
  2465. });
  2466. it("restoreBuiltinPlugin issues plugins/restoreBuiltin with the requested pluginId", async () => {
  2467. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugin-restore-"));
  2468. createdDirs.push(workspacePath);
  2469. const scriptPath = join(workspacePath, "plugin-restore-agent.cjs");
  2470. writeFileSync(scriptPath, PLUGIN_RESTORE_BUILTIN_ECHO_FAKE_AGENT);
  2471. const service = createReadyZCodeAgentService({
  2472. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2473. });
  2474. try {
  2475. const result = await service.restoreBuiltinPlugin({
  2476. workspacePath,
  2477. pluginId: "skill-creator@zcode-plugins-official",
  2478. });
  2479. expect(result.pluginId).toBe("skill-creator@zcode-plugins-official");
  2480. expect(result.diagnostics).toEqual([]);
  2481. } finally {
  2482. await service.disposeAllAndWait();
  2483. }
  2484. });
  2485. it("restarts a stale protocol client and retries MCP status list without provider registry sync", async () => {
  2486. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-list-"));
  2487. createdDirs.push(workspacePath);
  2488. const scriptPath = join(workspacePath, "stale-mcp-list-agent.cjs");
  2489. const markerPath = join(workspacePath, "first-run-marker");
  2490. writeFileSync(scriptPath, STALE_THEN_MCP_LIST_FAKE_AGENT);
  2491. const commandResolver = vi.fn(() => ({
  2492. command: process.execPath,
  2493. args: [scriptPath, markerPath],
  2494. }));
  2495. const service = createReadyZCodeAgentService({
  2496. commandResolver,
  2497. requestTimeoutMs: 1_500,
  2498. });
  2499. try {
  2500. const result = await service.listMcpServerStatuses({ workspacePath });
  2501. expect(result.statuses.filesystem?.status).toBe("disconnected");
  2502. expect(commandResolver).toHaveBeenCalledTimes(2);
  2503. } finally {
  2504. await service.disposeAllAndWait();
  2505. }
  2506. });
  2507. it("loads MCP status list through the dedicated plugin workspace", async () => {
  2508. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-cwd-"));
  2509. createdDirs.push(sandboxRoot);
  2510. setDataBaseDir(sandboxRoot);
  2511. const scriptPath = join(sandboxRoot, "mcp-cwd-agent.cjs");
  2512. writeFileSync(scriptPath, MCP_LIST_ECHO_CWD_FAKE_AGENT);
  2513. const missingWorkspacePath = join(sandboxRoot, "deleted-workspace");
  2514. const pluginWorkspacePath = join(sandboxRoot, ".zcode", "plugin-workspace");
  2515. const commandResolver = vi.fn(({ workspacePath }) => ({
  2516. command: process.execPath,
  2517. args: [scriptPath],
  2518. cwd: workspacePath,
  2519. }));
  2520. const service = createReadyZCodeAgentService({ commandResolver });
  2521. try {
  2522. const result = await service.listMcpServerStatuses({ workspacePath: missingWorkspacePath });
  2523. expect(existsSync(pluginWorkspacePath)).toBe(true);
  2524. expect(result.statuses.cwd?.error).toBe(missingWorkspacePath);
  2525. expect(commandResolver).toHaveBeenCalledWith({
  2526. workspacePath: pluginWorkspacePath,
  2527. workspaceKey: pluginWorkspacePath,
  2528. });
  2529. } finally {
  2530. await service.disposeAllAndWait();
  2531. }
  2532. });
  2533. it("plugins/uninstall 不会排在挂起的 mcp/list 后面:MCP 状态探测使用独立 agent 进程", async () => {
  2534. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-"));
  2535. createdDirs.push(sandboxRoot);
  2536. setDataBaseDir(sandboxRoot);
  2537. const scriptPath = join(sandboxRoot, "serial-queue-agent.cjs");
  2538. const markerPath = join(sandboxRoot, "mcp-list-received");
  2539. writeFileSync(scriptPath, SERIAL_QUEUE_HANG_ON_MCP_LIST_FAKE_AGENT);
  2540. const commandResolver = vi.fn(() => ({
  2541. command: process.execPath,
  2542. args: [scriptPath, markerPath],
  2543. }));
  2544. const service = createReadyZCodeAgentService({ commandResolver });
  2545. try {
  2546. // connect 模式的 mcp/list 在真实环境里会因坏 MCP server 吃满 30s 超时;这里让它永不返回。
  2547. const mcpListPromise = service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2548. mcpListPromise.catch(() => undefined);
  2549. await vi.waitFor(() => expect(existsSync(markerPath)).toBe(true), { timeout: 5_000 });
  2550. const result = await Promise.race([
  2551. service.uninstallPlugin({ workspacePath: sandboxRoot, pluginId: "pick-funds" }),
  2552. new Promise<never>((_, reject) =>
  2553. setTimeout(() => reject(new Error("plugins/uninstall 被 mcp/list 阻塞")), 3_000),
  2554. ),
  2555. ]);
  2556. expect(result.diagnostics).toEqual([]);
  2557. // 两类请求必须落在不同的 agent 进程上
  2558. expect(commandResolver).toHaveBeenCalledTimes(2);
  2559. } finally {
  2560. await service.disposeAllAndWait();
  2561. }
  2562. });
  2563. it("mcp-status lane 进程的 spawn/exit 会上报 processLifecycleReporter", async () => {
  2564. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-report-"));
  2565. createdDirs.push(sandboxRoot);
  2566. setDataBaseDir(sandboxRoot);
  2567. const scriptPath = join(sandboxRoot, "serial-queue-agent.cjs");
  2568. const markerPath = join(sandboxRoot, "mcp-list-received");
  2569. writeFileSync(scriptPath, SERIAL_QUEUE_HANG_ON_MCP_LIST_FAKE_AGENT);
  2570. const processLifecycleReporter = {
  2571. onSpawn: vi.fn(),
  2572. onReady: vi.fn(),
  2573. onExit: vi.fn(),
  2574. onError: vi.fn(),
  2575. };
  2576. const service = createReadyZCodeAgentService({
  2577. commandResolver: () => ({ command: process.execPath, args: [scriptPath, markerPath] }),
  2578. processLifecycleReporter,
  2579. });
  2580. try {
  2581. // 只走 mcp-status lane:该进程是本 lane 新增的长驻 agent,进程监控器必须能看到它。
  2582. const mcpListPromise = service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2583. mcpListPromise.catch(() => undefined);
  2584. await vi.waitFor(() => expect(existsSync(markerPath)).toBe(true), { timeout: 5_000 });
  2585. await vi.waitFor(() => expect(processLifecycleReporter.onSpawn).toHaveBeenCalledTimes(1));
  2586. // macOS tmpdir 会被 realpath 成 /private/var,这里不比对 workspacePath 字面值。
  2587. // 评审 SG-02:mcp-status 与 plugin lane 共用同一 workspacePath/command,事件必须带 lane 才可归因。
  2588. expect(processLifecycleReporter.onSpawn.mock.calls[0]![0]).toMatchObject({
  2589. pid: expect.any(Number),
  2590. provider: "glm",
  2591. lane: "mcp-status",
  2592. });
  2593. } finally {
  2594. await service.disposeAllAndWait();
  2595. }
  2596. await vi.waitFor(() => expect(processLifecycleReporter.onExit).toHaveBeenCalledTimes(1));
  2597. expect(processLifecycleReporter.onExit.mock.calls[0]![0]).toMatchObject({ lane: "mcp-status" });
  2598. });
  2599. it("mcp-status lane 空闲超时后回收进程并释放 MCP 连接,下次探测重新拉起", async () => {
  2600. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-idle-"));
  2601. createdDirs.push(sandboxRoot);
  2602. setDataBaseDir(sandboxRoot);
  2603. const scriptPath = join(sandboxRoot, "mcp-echo-agent.cjs");
  2604. writeFileSync(scriptPath, MCP_LIST_ECHO_MODE_FAKE_AGENT);
  2605. const commandResolver = vi.fn(() => ({ command: process.execPath, args: [scriptPath] }));
  2606. const processLifecycleReporter = {
  2607. onSpawn: vi.fn(),
  2608. onReady: vi.fn(),
  2609. onExit: vi.fn(),
  2610. onError: vi.fn(),
  2611. };
  2612. const service = createReadyZCodeAgentService({
  2613. commandResolver,
  2614. processLifecycleReporter,
  2615. mcpStatusIdleTimeoutMs: 300,
  2616. });
  2617. try {
  2618. await service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2619. expect(commandResolver).toHaveBeenCalledTimes(1);
  2620. // 探测完成后无请求在飞,超过空闲阈值必须主动回收,且以 expected/idle-timeout 归因。
  2621. await vi.waitFor(() => expect(processLifecycleReporter.onExit).toHaveBeenCalledTimes(1), {
  2622. timeout: 5_000,
  2623. });
  2624. expect(processLifecycleReporter.onExit.mock.calls[0]![0]).toMatchObject({
  2625. lane: "mcp-status",
  2626. terminationKind: "expected",
  2627. terminationReason: "idle-timeout",
  2628. });
  2629. // 回收后再次探测要透明地重新拉起进程,而不是拿到已回收的 client 报错。
  2630. await service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2631. expect(commandResolver).toHaveBeenCalledTimes(2);
  2632. } finally {
  2633. await service.disposeAllAndWait();
  2634. }
  2635. });
  2636. it("mcp/list 超时触发 watchdog 回收后重试仍落在 mcp-status lane,plugin lane 进程不受影响", async () => {
  2637. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-timeout-"));
  2638. createdDirs.push(sandboxRoot);
  2639. setDataBaseDir(sandboxRoot);
  2640. const scriptPath = join(sandboxRoot, "serial-queue-agent.cjs");
  2641. const markerPath = join(sandboxRoot, "mcp-list-received");
  2642. writeFileSync(scriptPath, SERIAL_QUEUE_HANG_ON_MCP_LIST_FAKE_AGENT);
  2643. const commandResolver = vi.fn(() => ({
  2644. command: process.execPath,
  2645. args: [scriptPath, markerPath],
  2646. }));
  2647. const processLifecycleReporter = {
  2648. onSpawn: vi.fn(),
  2649. onReady: vi.fn(),
  2650. onExit: vi.fn(),
  2651. onError: vi.fn(),
  2652. };
  2653. const service = createReadyZCodeAgentService({
  2654. commandResolver,
  2655. processLifecycleReporter,
  2656. // 覆盖 fake agent 冷启动(node 进程拉起 + 首个响应),又足够短让两次超时在秒级完成。
  2657. requestTimeoutMs: 1_500,
  2658. });
  2659. try {
  2660. // 先让 plugin lane 起一个进程,作为“不受影响”的对照(该 fake agent 只应答 plugins/uninstall)。
  2661. await service.uninstallPlugin({ workspacePath: sandboxRoot, pluginId: "pick-funds" });
  2662. expect(commandResolver).toHaveBeenCalledTimes(1);
  2663. // mcp/list 永不返回:首次超时 → watchdog 回收 mcp-status 进程 → 重试一次 → 再超时 → 抛错。
  2664. await expect(service.listMcpServerStatuses({ workspacePath: sandboxRoot })).rejects.toThrow(
  2665. /timed out/u,
  2666. );
  2667. // plugin lane 1 次 + mcp-status lane 首发 1 次 + 重试重新拉起 1 次
  2668. expect(commandResolver).toHaveBeenCalledTimes(3);
  2669. await vi.waitFor(
  2670. () =>
  2671. expect(
  2672. processLifecycleReporter.onExit.mock.calls.filter(
  2673. ([event]) =>
  2674. event.lane === "mcp-status" && event.terminationKind === "watchdog_recycle",
  2675. ),
  2676. ).toHaveLength(2),
  2677. // 修复原因:第二次 watchdog 与 mcp/list 的 reject 同 tick 触发,exit 事件要等
  2678. // Windows 进程树回收(taskkill /T + 重试)完成后才上报;vi.waitFor 默认 1000ms
  2679. // 在慢盘/高负载本机会先超时,把环境慢误报成用例失败。CI 快机器不受影响。
  2680. { timeout: 8_000 },
  2681. );
  2682. // plugin lane 进程从未被回收,且仍能正常服务。
  2683. expect(
  2684. processLifecycleReporter.onExit.mock.calls.filter(([event]) => event.lane !== "mcp-status"),
  2685. ).toHaveLength(0);
  2686. await service.uninstallPlugin({ workspacePath: sandboxRoot, pluginId: "pick-funds" });
  2687. expect(commandResolver).toHaveBeenCalledTimes(3);
  2688. } finally {
  2689. await service.disposeAllAndWait();
  2690. }
  2691. });
  2692. it("passes UI-resolved MCP servers to mcp/list", async () => {
  2693. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-explicit-"));
  2694. createdDirs.push(workspacePath);
  2695. const scriptPath = join(workspacePath, "mcp-explicit-agent.cjs");
  2696. writeFileSync(scriptPath, MCP_LIST_ECHO_MCP_SERVERS_FAKE_AGENT);
  2697. const service = createReadyZCodeAgentService({
  2698. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2699. });
  2700. try {
  2701. const result = await service.listMcpServerStatuses({
  2702. workspacePath,
  2703. mcpServers: [
  2704. {
  2705. name: "agents-fallback",
  2706. command: "node",
  2707. args: ["server.mjs"],
  2708. env: [{ name: "TOKEN", value: "secret" }],
  2709. timeoutMs: 3000,
  2710. },
  2711. ],
  2712. });
  2713. expect(JSON.parse(result.statuses.explicit?.error ?? "null")).toEqual([
  2714. {
  2715. name: "agents-fallback",
  2716. command: "node",
  2717. args: ["server.mjs"],
  2718. env: [{ name: "TOKEN", value: "secret" }],
  2719. timeoutMs: 3000,
  2720. },
  2721. ]);
  2722. } finally {
  2723. await service.disposeAllAndWait();
  2724. }
  2725. });
  2726. it("passes status mode to mcp/list", async () => {
  2727. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-mode-"));
  2728. createdDirs.push(workspacePath);
  2729. const scriptPath = join(workspacePath, "mcp-mode-agent.cjs");
  2730. writeFileSync(scriptPath, MCP_LIST_ECHO_MODE_FAKE_AGENT);
  2731. const service = createZCodeAgentService({
  2732. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2733. });
  2734. try {
  2735. const result = await service.listMcpServerStatuses({
  2736. workspacePath,
  2737. mode: "status",
  2738. });
  2739. expect(JSON.parse(result.statuses.mode?.error ?? "null")).toBe("status");
  2740. } finally {
  2741. await service.disposeAllAndWait();
  2742. }
  2743. });
  2744. it("retries mcp/list without explicit MCP servers for legacy agents", async () => {
  2745. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-compat-"));
  2746. createdDirs.push(workspacePath);
  2747. const scriptPath = join(workspacePath, "mcp-compat-agent.cjs");
  2748. writeFileSync(scriptPath, MCP_LIST_REJECTS_MCP_SERVERS_ONCE_FAKE_AGENT);
  2749. const service = createReadyZCodeAgentService({
  2750. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2751. });
  2752. try {
  2753. const result = await service.listMcpServerStatuses({
  2754. workspacePath,
  2755. mcpServers: [],
  2756. });
  2757. expect(result.statuses.fallback?.status).toBe("disconnected");
  2758. } finally {
  2759. await service.disposeAllAndWait();
  2760. }
  2761. });
  2762. it("retries connect-mode mcp/list without mode for legacy agents", async () => {
  2763. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-mode-compat-"));
  2764. createdDirs.push(workspacePath);
  2765. const scriptPath = join(workspacePath, "mcp-mode-compat-agent.cjs");
  2766. writeFileSync(scriptPath, MCP_LIST_REJECTS_MODE_ONCE_FAKE_AGENT);
  2767. const service = createZCodeAgentService({
  2768. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2769. });
  2770. try {
  2771. const result = await service.listMcpServerStatuses({
  2772. workspacePath,
  2773. mode: "connect",
  2774. });
  2775. expect(result.statuses.fallback?.status).toBe("disconnected");
  2776. expect(JSON.parse(result.statuses.fallback?.error ?? "null")).toBeNull();
  2777. } finally {
  2778. await service.disposeAllAndWait();
  2779. }
  2780. });
  2781. it("does not retry status-only mcp/list as connect for legacy agents", async () => {
  2782. const workspacePath = mkdtempSync(
  2783. join(tmpdir(), "zcode-agent-service-mcp-mode-subset-compat-"),
  2784. );
  2785. createdDirs.push(workspacePath);
  2786. const scriptPath = join(workspacePath, "mcp-mode-subset-compat-agent.cjs");
  2787. writeFileSync(scriptPath, MCP_LIST_REJECTS_MODE_ONCE_FAKE_AGENT);
  2788. const service = createZCodeAgentService({
  2789. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2790. });
  2791. try {
  2792. await expect(
  2793. service.listMcpServerStatuses({
  2794. workspacePath,
  2795. mode: "status",
  2796. mcpServers: [
  2797. {
  2798. name: "plugin:canva:canva",
  2799. type: "http",
  2800. url: "https://mcp.canva.example.test/mcp",
  2801. headers: [],
  2802. },
  2803. ],
  2804. }),
  2805. ).rejects.toMatchObject({
  2806. code: ZCODE_AGENT_MCP_STATUS_MODE_UNSUPPORTED_ERROR_CODE,
  2807. name: "ZCodeAgentMcpStatusModeUnsupportedError",
  2808. });
  2809. } finally {
  2810. await service.disposeAllAndWait();
  2811. }
  2812. });
  2813. });