zcodeAgentService.test.ts 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013
  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("reserves native create ownership before sending the assigned session ID", async () => {
  1618. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-native-project-"));
  1619. createdDirs.push(workspacePath);
  1620. const scriptPath = join(workspacePath, "agent.cjs");
  1621. const logPath = join(workspacePath, "protocol.log");
  1622. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1623. const prepareSessionCreation = vi.fn(async () => ["/extra"]);
  1624. const service = createReadyZCodeAgentService({
  1625. prepareSessionCreation,
  1626. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1627. });
  1628. try {
  1629. await service.createSession({ workspacePath, projectId: "p" });
  1630. const create = readFileSync(logPath, "utf8")
  1631. .trim()
  1632. .split("\n")
  1633. .map((line) => JSON.parse(line))
  1634. .find((entry) => entry.method === "session/create");
  1635. expect(prepareSessionCreation).toHaveBeenCalledWith(
  1636. expect.objectContaining({ projectId: "p", sessionId: create.params.sessionId }),
  1637. );
  1638. expect(create.params.sessionId).toBeTypeOf("string");
  1639. expect(create.params.additionalDirectories).toEqual(["/extra"]);
  1640. expect(create.params).not.toHaveProperty("projectId");
  1641. prepareSessionCreation.mockRejectedValueOnce(new Error("storage failed"));
  1642. await expect(service.createSession({ workspacePath })).rejects.toThrow("storage failed");
  1643. expect(
  1644. readFileSync(logPath, "utf8")
  1645. .trim()
  1646. .split("\n")
  1647. .map((line) => JSON.parse(line))
  1648. .filter((entry) => entry.method === "session/create"),
  1649. ).toHaveLength(1);
  1650. } finally {
  1651. await service.disposeAllAndWait();
  1652. }
  1653. });
  1654. it("passes session tool lists through protocol session/create", async () => {
  1655. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-tool-list-"));
  1656. createdDirs.push(workspacePath);
  1657. const scriptPath = join(workspacePath, "tool-list-agent.cjs");
  1658. const logPath = join(workspacePath, "protocol.log");
  1659. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1660. // 修复原因:本用例只验证 session/create 的工具列表透传,不验证 provider readiness。
  1661. // 门禁启用后必须复用标准 ready registry fixture,否则测试会在协议请求前被正确拦截。
  1662. const service = createReadyZCodeAgentService({
  1663. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1664. });
  1665. try {
  1666. await service.createSession({
  1667. workspacePath,
  1668. toolAllowlist: ["mcp__zcode-cua__request_access", "mcp__zcode-cua__list_apps"],
  1669. toolDenylist: ["Bash"],
  1670. });
  1671. const createRequest = readFileSync(logPath, "utf8")
  1672. .trim()
  1673. .split("\n")
  1674. .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> })
  1675. .find((entry) => entry.method === "session/create");
  1676. expect(createRequest?.params.toolAllowlist).toEqual([
  1677. "mcp__zcode-cua__request_access",
  1678. "mcp__zcode-cua__list_apps",
  1679. ]);
  1680. expect(createRequest?.params.toolDenylist).toEqual(["Bash"]);
  1681. } finally {
  1682. await service.disposeAllAndWait();
  1683. }
  1684. });
  1685. it("resolves runtime preferences at materialization and first execution without forwarding them", async () => {
  1686. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-shell-snapshot-"));
  1687. createdDirs.push(workspacePath);
  1688. const scriptPath = join(workspacePath, "shell-settings-agent.cjs");
  1689. const logPath = join(workspacePath, "protocol.log");
  1690. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1691. const resolveSessionRuntimePreferences = vi.fn(
  1692. async (scope: ZCodeSessionRuntimePreferencesScope) => ({
  1693. askUserQuestionAutoResolutionEnabled: false,
  1694. nativeSearchEnhancementsEnabled: false,
  1695. memoryEnabled: false,
  1696. modelContextBudgetStrategy:
  1697. scope === "runtime-materialization" ? ("preflight-v1" as const) : ("legacy" as const),
  1698. ...(scope === "user-execution"
  1699. ? {
  1700. integratedTerminalShell: {
  1701. mode: "shell" as const,
  1702. dialect: "git-bash" as const,
  1703. id: "git-bash:/usr/bin/new-session-bash",
  1704. label: "Git Bash",
  1705. path: "/usr/bin/new-session-bash",
  1706. },
  1707. }
  1708. : {}),
  1709. }),
  1710. );
  1711. const service = createReadyZCodeAgentService({
  1712. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1713. resolveSessionRuntimePreferences,
  1714. });
  1715. const created = await service.createSession({ workspacePath });
  1716. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(1);
  1717. expect(resolveSessionRuntimePreferences).toHaveBeenNthCalledWith(1, "runtime-materialization");
  1718. await service.resumeSession({
  1719. workspacePath,
  1720. sessionId: created.session.sessionId,
  1721. });
  1722. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(1);
  1723. await service.sendPrompt({
  1724. workspacePath,
  1725. sessionId: created.session.sessionId,
  1726. content: "continue",
  1727. });
  1728. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(2);
  1729. expect(resolveSessionRuntimePreferences).toHaveBeenNthCalledWith(2, "user-execution");
  1730. await service.sendPrompt({
  1731. workspacePath,
  1732. sessionId: created.session.sessionId,
  1733. content: "second prompt",
  1734. modelSelection: {
  1735. providerId: "test-provider",
  1736. modelId: "test-model",
  1737. options: { reasoningLevel: "high" },
  1738. },
  1739. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  1740. });
  1741. const requests = readFileSync(logPath, "utf8")
  1742. .trim()
  1743. .split("\n")
  1744. .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> });
  1745. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(2);
  1746. expect(requests).toMatchObject([
  1747. { method: "session/create" },
  1748. { method: "session/resume" },
  1749. { method: "session/send" },
  1750. {
  1751. method: "session/send",
  1752. params: {
  1753. modelSelection: {
  1754. providerId: "test-provider",
  1755. modelId: "test-model",
  1756. options: { reasoningLevel: "high" },
  1757. },
  1758. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  1759. },
  1760. },
  1761. ]);
  1762. for (const request of requests) {
  1763. expect(request.params).not.toHaveProperty("integratedTerminalShell");
  1764. expect(request.params).not.toHaveProperty("nativeSearchEnhancementsEnabled");
  1765. expect(request.params).not.toHaveProperty("memoryEnabled");
  1766. expect(request.params).not.toHaveProperty("modelContextBudgetStrategy");
  1767. }
  1768. await service.disposeAllAndWait();
  1769. });
  1770. it("adds bounded IAB ambient context to session/send without changing prompt content", async () => {
  1771. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-browser-ambient-"));
  1772. createdDirs.push(workspacePath);
  1773. const scriptPath = join(workspacePath, "browser-ambient-agent.cjs");
  1774. const logPath = join(workspacePath, "protocol.log");
  1775. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1776. const list = vi.fn(async () => [
  1777. {
  1778. id: "iab-runtime-1",
  1779. generation: 3,
  1780. type: "iab" as const,
  1781. name: "ZCode In-app Browser",
  1782. capabilities: {},
  1783. },
  1784. ]);
  1785. const execute = vi.fn(async (input: { command: { method: string } }) =>
  1786. input.command.method === "list"
  1787. ? { ok: true, tabs: [], elapsedMs: 0 }
  1788. : {
  1789. ok: true,
  1790. userTabs: [
  1791. {
  1792. id: "user-tab-1",
  1793. title: "Current",
  1794. url: "https://example.com/current?q=1",
  1795. },
  1796. ],
  1797. elapsedMs: 0,
  1798. },
  1799. );
  1800. const service = createReadyZCodeAgentService({
  1801. commandResolver: () => ({
  1802. command: process.execPath,
  1803. args: [scriptPath, logPath],
  1804. }),
  1805. browserControlExecutor: { list, execute } as never,
  1806. });
  1807. const workspaceIdentity = "remote:ssh:dev:/workspace/app";
  1808. const created = await service.createSession({
  1809. workspacePath,
  1810. workspaceIdentity,
  1811. });
  1812. await service.sendPrompt({
  1813. workspacePath,
  1814. workspaceIdentity,
  1815. remoteSessionId: "remote-session-1",
  1816. sessionId: created.session.sessionId,
  1817. clientMode: "web-remote-replayable",
  1818. content: "continue",
  1819. });
  1820. const sendRequest = readFileSync(logPath, "utf8")
  1821. .trim()
  1822. .split("\n")
  1823. .map(
  1824. (line) =>
  1825. JSON.parse(line) as {
  1826. method: string;
  1827. params: Record<string, unknown>;
  1828. },
  1829. )
  1830. .find((request) => request.method === "session/send");
  1831. expect(sendRequest?.params).toMatchObject({
  1832. content: "continue",
  1833. browserAmbientContext: {
  1834. tabCount: 1,
  1835. currentUrl: "https://example.com/current?q=1",
  1836. },
  1837. });
  1838. expect(list).toHaveBeenCalledWith(
  1839. expect.objectContaining({
  1840. workspaceKey: workspaceIdentity,
  1841. remoteSessionId: "remote-session-1",
  1842. clientMode: "web-remote-replayable",
  1843. }),
  1844. );
  1845. expect(execute).toHaveBeenCalledTimes(2);
  1846. await service.disposeAllAndWait();
  1847. });
  1848. it("retries session/send without browser ambient context when a legacy agent returns an enhanced invalid params error", async () => {
  1849. const workspacePath = mkdtempSync(
  1850. join(tmpdir(), "zcode-agent-service-browser-ambient-compat-"),
  1851. );
  1852. createdDirs.push(workspacePath);
  1853. const scriptPath = join(workspacePath, "browser-ambient-compat-agent.cjs");
  1854. const logPath = join(workspacePath, "protocol.log");
  1855. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1856. const service = createReadyZCodeAgentService({
  1857. commandResolver: () => ({
  1858. command: process.execPath,
  1859. args: [scriptPath, logPath, "reject-browser-ambient"],
  1860. }),
  1861. browserControlExecutor: {
  1862. list: vi.fn(async () => [
  1863. {
  1864. id: "iab-runtime-legacy",
  1865. generation: 1,
  1866. type: "iab" as const,
  1867. name: "ZCode In-app Browser",
  1868. capabilities: {},
  1869. },
  1870. ]),
  1871. execute: vi.fn(async (input: { command: { method: string } }) =>
  1872. input.command.method === "list"
  1873. ? { ok: true, tabs: [], elapsedMs: 0 }
  1874. : {
  1875. ok: true,
  1876. userTabs: [
  1877. {
  1878. id: "user-tab-legacy",
  1879. title: "Current",
  1880. url: "https://example.com/current",
  1881. },
  1882. ],
  1883. elapsedMs: 0,
  1884. },
  1885. ),
  1886. } as never,
  1887. });
  1888. const created = await service.createSession({ workspacePath });
  1889. await expect(
  1890. service.sendPrompt({
  1891. workspacePath,
  1892. sessionId: created.session.sessionId,
  1893. content: "continue",
  1894. }),
  1895. ).resolves.toMatchObject({ accepted: true });
  1896. const sendRequests = readFileSync(logPath, "utf8")
  1897. .trim()
  1898. .split("\n")
  1899. .map(
  1900. (line) =>
  1901. JSON.parse(line) as {
  1902. method: string;
  1903. params: Record<string, unknown>;
  1904. },
  1905. )
  1906. .filter((request) => request.method === "session/send");
  1907. expect(sendRequests).toHaveLength(2);
  1908. expect(sendRequests[0]?.params).toHaveProperty("browserAmbientContext");
  1909. expect(sendRequests[1]?.params).not.toHaveProperty("browserAmbientContext");
  1910. expect(sendRequests[1]?.params.content).toBe("continue");
  1911. await service.disposeAllAndWait();
  1912. });
  1913. it("resolves execution preferences before a deferred draft accepts its first prompt", async () => {
  1914. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-shell-draft-"));
  1915. createdDirs.push(workspacePath);
  1916. const scriptPath = join(workspacePath, "shell-settings-agent.cjs");
  1917. const logPath = join(workspacePath, "protocol.log");
  1918. writeFileSync(scriptPath, SHELL_SETTINGS_SNAPSHOT_FAKE_AGENT);
  1919. const resolveSessionRuntimePreferences = vi.fn(async () => ({
  1920. askUserQuestionAutoResolutionEnabled: true,
  1921. nativeSearchEnhancementsEnabled: true,
  1922. memoryEnabled: true,
  1923. integratedTerminalShell: {
  1924. mode: "shell" as const,
  1925. dialect: "git-bash" as const,
  1926. id: "git-bash:/usr/bin/first-send-bash",
  1927. label: "Git Bash",
  1928. path: "/usr/bin/first-send-bash",
  1929. },
  1930. }));
  1931. const service = createReadyZCodeAgentService({
  1932. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  1933. resolveSessionRuntimePreferences,
  1934. });
  1935. const draft = await service.createSession({ workspacePath, persistence: "deferred" });
  1936. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(1);
  1937. await service.sendPrompt({
  1938. workspacePath,
  1939. sessionId: draft.session.sessionId,
  1940. content: "first prompt",
  1941. });
  1942. const requests = readFileSync(logPath, "utf8")
  1943. .trim()
  1944. .split("\n")
  1945. .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> });
  1946. expect(resolveSessionRuntimePreferences).toHaveBeenCalledTimes(2);
  1947. expect(requests).toMatchObject([
  1948. {
  1949. method: "session/create",
  1950. params: {
  1951. persistence: "deferred",
  1952. },
  1953. },
  1954. {
  1955. method: "session/send",
  1956. },
  1957. ]);
  1958. for (const request of requests) {
  1959. expect(request.params).not.toHaveProperty("integratedTerminalShell");
  1960. expect(request.params).not.toHaveProperty("nativeSearchEnhancementsEnabled");
  1961. expect(request.params).not.toHaveProperty("memoryEnabled");
  1962. }
  1963. await service.disposeAllAndWait();
  1964. });
  1965. it("answers Agent runtime preference requests from the Host resolver", async () => {
  1966. const cases: Array<{
  1967. name: string;
  1968. requestMode?: "invalid" | "valid";
  1969. resolver?: ReturnType<
  1970. typeof vi.fn<
  1971. () => Promise<{
  1972. askUserQuestionAutoResolutionEnabled: boolean;
  1973. nativeSearchEnhancementsEnabled: boolean;
  1974. memoryEnabled: boolean;
  1975. toolSearchMode?: "auto" | "local" | "off";
  1976. }>
  1977. >
  1978. >;
  1979. expectedResult?: {
  1980. askUserQuestionAutoResolutionEnabled: boolean;
  1981. nativeSearchEnhancementsEnabled: boolean;
  1982. subagentRuntimeConfigEnabled: boolean;
  1983. memoryEnabled: boolean;
  1984. toolSearchMode?: "auto" | "local" | "off";
  1985. modelContextBudgetStrategy: "legacy" | "preflight-v1";
  1986. };
  1987. expectedErrorCode?: number;
  1988. expectedResolverCalls: number;
  1989. }> = [
  1990. {
  1991. name: "current-setting",
  1992. resolver: vi.fn(async () => ({
  1993. toolSearchMode: "auto",
  1994. askUserQuestionAutoResolutionEnabled: false,
  1995. nativeSearchEnhancementsEnabled: false,
  1996. memoryEnabled: false,
  1997. })),
  1998. expectedResult: {
  1999. toolSearchMode: "auto",
  2000. askUserQuestionAutoResolutionEnabled: false,
  2001. nativeSearchEnhancementsEnabled: false,
  2002. subagentRuntimeConfigEnabled: false,
  2003. memoryEnabled: false,
  2004. modelContextBudgetStrategy: "preflight-v1" as const,
  2005. },
  2006. expectedResolverCalls: 1,
  2007. },
  2008. {
  2009. name: "missing-resolver",
  2010. expectedResult: {
  2011. toolSearchMode: "off",
  2012. askUserQuestionAutoResolutionEnabled: true,
  2013. nativeSearchEnhancementsEnabled: true,
  2014. subagentRuntimeConfigEnabled: false,
  2015. memoryEnabled: false,
  2016. modelContextBudgetStrategy: "preflight-v1" as const,
  2017. },
  2018. expectedResolverCalls: 0,
  2019. },
  2020. {
  2021. name: "resolver-failure",
  2022. resolver: vi.fn(async () => {
  2023. throw new Error("setting failed");
  2024. }),
  2025. expectedErrorCode: -32603,
  2026. expectedResolverCalls: 1,
  2027. },
  2028. {
  2029. name: "invalid-params",
  2030. requestMode: "invalid",
  2031. resolver: vi.fn(async () => ({
  2032. askUserQuestionAutoResolutionEnabled: false,
  2033. nativeSearchEnhancementsEnabled: false,
  2034. memoryEnabled: false,
  2035. })),
  2036. expectedErrorCode: -32602,
  2037. expectedResolverCalls: 0,
  2038. },
  2039. ];
  2040. for (const testCase of cases) {
  2041. const workspacePath = mkdtempSync(
  2042. join(tmpdir(), `zcode-agent-runtime-preferences-${testCase.name}-`),
  2043. );
  2044. createdDirs.push(workspacePath);
  2045. const scriptPath = join(workspacePath, "runtime-preferences-agent.cjs");
  2046. const logPath = join(workspacePath, "protocol.log");
  2047. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2048. const service = createReadyZCodeAgentService({
  2049. commandResolver: () => ({
  2050. command: process.execPath,
  2051. args: [scriptPath, logPath, testCase.requestMode ?? "valid"],
  2052. }),
  2053. resolveSessionRuntimePreferences: testCase.resolver,
  2054. });
  2055. try {
  2056. await service.createSession({ workspacePath });
  2057. const response = readFileSync(logPath, "utf8")
  2058. .trim()
  2059. .split("\n")
  2060. .map(
  2061. (line) =>
  2062. JSON.parse(line) as {
  2063. error?: { code: number; message: string };
  2064. method: string;
  2065. result?: {
  2066. askUserQuestionAutoResolutionEnabled: boolean;
  2067. nativeSearchEnhancementsEnabled: boolean;
  2068. subagentRuntimeConfigEnabled: boolean;
  2069. memoryEnabled: boolean;
  2070. toolSearchMode?: "auto" | "local" | "off";
  2071. modelContextBudgetStrategy: "legacy" | "preflight-v1";
  2072. };
  2073. },
  2074. )
  2075. .find((entry) => entry.method === "session/requestRuntimePreferences:response");
  2076. if (testCase.expectedResult) {
  2077. expect(response?.result, testCase.name).toEqual(testCase.expectedResult);
  2078. expect(response?.error, testCase.name).toBeUndefined();
  2079. } else {
  2080. expect(response?.error, testCase.name).toMatchObject({
  2081. code: testCase.expectedErrorCode,
  2082. });
  2083. }
  2084. if (testCase.resolver) {
  2085. expect(testCase.resolver, testCase.name).toHaveBeenCalledTimes(
  2086. testCase.expectedResolverCalls,
  2087. );
  2088. }
  2089. } finally {
  2090. await service.disposeAllAndWait();
  2091. }
  2092. }
  2093. });
  2094. it("does not send a second runtime preference response after the Agent disconnects", async () => {
  2095. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-runtime-preferences-close-"));
  2096. createdDirs.push(workspacePath);
  2097. const scriptPath = join(workspacePath, "runtime-preferences-agent.cjs");
  2098. const logPath = join(workspacePath, "protocol.log");
  2099. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2100. let markResolverStarted!: () => void;
  2101. let releaseResolver!: () => void;
  2102. let markResolverFinished!: () => void;
  2103. const resolverStarted = new Promise<void>((resolve) => {
  2104. markResolverStarted = resolve;
  2105. });
  2106. const resolverReleased = new Promise<void>((resolve) => {
  2107. releaseResolver = resolve;
  2108. });
  2109. const resolverFinished = new Promise<void>((resolve) => {
  2110. markResolverFinished = resolve;
  2111. });
  2112. const service = createReadyZCodeAgentService({
  2113. commandResolver: () => ({
  2114. command: process.execPath,
  2115. args: [scriptPath, logPath, "disconnect"],
  2116. }),
  2117. resolveSessionRuntimePreferences: async () => {
  2118. markResolverStarted();
  2119. await resolverReleased;
  2120. markResolverFinished();
  2121. return {
  2122. askUserQuestionAutoResolutionEnabled: false,
  2123. nativeSearchEnhancementsEnabled: false,
  2124. memoryEnabled: false,
  2125. };
  2126. },
  2127. });
  2128. try {
  2129. const createResult = service.createSession({ workspacePath }).then(
  2130. () => null,
  2131. (error: unknown) => error,
  2132. );
  2133. await resolverStarted;
  2134. expect(await createResult).toBeInstanceOf(Error);
  2135. releaseResolver();
  2136. await resolverFinished;
  2137. await new Promise<void>((resolve) => setImmediate(resolve));
  2138. } finally {
  2139. await service.disposeAllAndWait();
  2140. }
  2141. });
  2142. it("routes external runtime preference requests by opaque requestId", async () => {
  2143. const fixtureDir = mkdtempSync(join(tmpdir(), "zcode-agent-external-preferences-"));
  2144. const firstWorkspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-preferences-first-"));
  2145. const secondWorkspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-preferences-second-"));
  2146. createdDirs.push(fixtureDir, firstWorkspacePath, secondWorkspacePath);
  2147. const scriptPath = join(fixtureDir, "runtime-preferences-agent.cjs");
  2148. const logPath = join(fixtureDir, "protocol.log");
  2149. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2150. const service = createReadyZCodeAgentService({
  2151. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  2152. sessionRuntimePreferencesAuthority: "external",
  2153. });
  2154. const requests: Array<{ requestId: string; sessionId: string; scope: string }> = [];
  2155. const subscription = service.onDynamicSessionRuntimePreferencesRequest()((request) => {
  2156. requests.push(request);
  2157. void service.respondSessionRuntimePreferences({
  2158. requestId: request.requestId,
  2159. resolution: {
  2160. status: "resolved",
  2161. preferences: {
  2162. askUserQuestionAutoResolutionEnabled: false,
  2163. nativeSearchEnhancementsEnabled: false,
  2164. memoryEnabled: false,
  2165. },
  2166. },
  2167. });
  2168. });
  2169. try {
  2170. await service.createSession({ workspacePath: firstWorkspacePath });
  2171. await service.createSession({ workspacePath: secondWorkspacePath });
  2172. expect(requests).toHaveLength(2);
  2173. expect(new Set(requests.map((request) => request.requestId)).size).toBe(2);
  2174. for (const request of requests) {
  2175. expect(request).toMatchObject({
  2176. sessionId: "sess_runtime_preferences",
  2177. scope: "runtime-materialization",
  2178. });
  2179. expect(request).not.toHaveProperty("workspacePath");
  2180. expect(request).not.toHaveProperty("workspaceIdentity");
  2181. }
  2182. } finally {
  2183. subscription.dispose();
  2184. await service.disposeAllAndWait();
  2185. }
  2186. });
  2187. it("expires unanswered external runtime preference requests without replaying them", async () => {
  2188. vi.useFakeTimers({ toFake: ["clearTimeout", "setTimeout"] });
  2189. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-preferences-timeout-"));
  2190. createdDirs.push(workspacePath);
  2191. const scriptPath = join(workspacePath, "runtime-preferences-agent.cjs");
  2192. const logPath = join(workspacePath, "protocol.log");
  2193. writeFileSync(scriptPath, RUNTIME_PREFERENCES_FAKE_AGENT);
  2194. const service = createReadyZCodeAgentService({
  2195. commandResolver: () => ({ command: process.execPath, args: [scriptPath, logPath] }),
  2196. sessionRuntimePreferencesAuthority: "external",
  2197. });
  2198. let markRequestSeen!: () => void;
  2199. const requestSeen = new Promise<void>((resolve) => {
  2200. markRequestSeen = resolve;
  2201. });
  2202. const subscription = service.onDynamicSessionRuntimePreferencesRequest()(() => {
  2203. markRequestSeen();
  2204. });
  2205. try {
  2206. const createPromise = service.createSession({ workspacePath });
  2207. await requestSeen;
  2208. await vi.advanceTimersByTimeAsync(ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS);
  2209. await createPromise;
  2210. const response = readFileSync(logPath, "utf8")
  2211. .trim()
  2212. .split("\n")
  2213. .map(
  2214. (line) =>
  2215. JSON.parse(line) as {
  2216. error?: { code: number; data?: { timeoutMs?: number } };
  2217. method: string;
  2218. },
  2219. )
  2220. .find((entry) => entry.method === "session/requestRuntimePreferences:response");
  2221. expect(response?.error).toEqual({
  2222. code: -32022,
  2223. data: {
  2224. timeoutMs: ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS,
  2225. },
  2226. message: "Session runtime preferences request timed out",
  2227. });
  2228. subscription.dispose();
  2229. const replayedRequests: unknown[] = [];
  2230. const replaySubscription = service.onDynamicSessionRuntimePreferencesRequest()((request) => {
  2231. replayedRequests.push(request);
  2232. });
  2233. expect(replayedRequests).toEqual([]);
  2234. replaySubscription.dispose();
  2235. } finally {
  2236. subscription.dispose();
  2237. vi.useRealTimers();
  2238. await service.disposeAllAndWait();
  2239. }
  2240. });
  2241. it("uses the compact-specific request timeout for delayed compact ACKs", async () => {
  2242. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-compact-timeout-"));
  2243. createdDirs.push(workspacePath);
  2244. const scriptPath = join(workspacePath, "delayed-compact-agent.cjs");
  2245. writeFileSync(scriptPath, DELAYED_COMPACT_FAKE_AGENT);
  2246. const service = createReadyZCodeAgentService({
  2247. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2248. requestTimeoutMs: 20,
  2249. });
  2250. try {
  2251. const result = await service.compactSession({
  2252. workspacePath,
  2253. sessionId: "sess_compact_timeout",
  2254. inputId: "input_compact_timeout",
  2255. });
  2256. expect(result.compact).toMatchObject({
  2257. state: "accepted",
  2258. inputId: "input_compact_timeout",
  2259. });
  2260. } finally {
  2261. await service.disposeAllAndWait();
  2262. }
  2263. });
  2264. it("retries session subscription after a transient subscribe failure", async () => {
  2265. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-retry-"));
  2266. createdDirs.push(workspacePath);
  2267. const scriptPath = join(workspacePath, "flaky-agent.cjs");
  2268. writeFileSync(scriptPath, FLAKY_SUBSCRIBE_FAKE_AGENT);
  2269. const service = createReadyZCodeAgentService({
  2270. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2271. });
  2272. const received: ZCodeAgentServiceEvent[] = [];
  2273. const subscription = service.onDynamicSessionEvent({
  2274. workspacePath,
  2275. sessionId: "sess-1",
  2276. deliveryKind: "desktop-continuous",
  2277. includeSnapshot: false,
  2278. })((event) => received.push(event));
  2279. // 第一次 subscribe 失败后必须重试,最终把成功响应里的事件投递出来。
  2280. await vi.waitFor(
  2281. () => {
  2282. expect(received.some((event) => event.type === "session.event")).toBe(true);
  2283. },
  2284. { timeout: 5000, interval: 50 },
  2285. );
  2286. subscription.dispose();
  2287. await service.disposeAllAndWait();
  2288. });
  2289. it("delivers subscribe replay events only to the subscriber that requested them", async () => {
  2290. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-replay-"));
  2291. createdDirs.push(workspacePath);
  2292. const scriptPath = join(workspacePath, "replay-agent.cjs");
  2293. writeFileSync(scriptPath, SUBSCRIBE_REPLAY_FAKE_AGENT);
  2294. const service = createReadyZCodeAgentService({
  2295. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2296. });
  2297. const firstReceived: ZCodeAgentServiceEvent[] = [];
  2298. const firstSubscription = service.onDynamicSessionEvent({
  2299. workspacePath,
  2300. sessionId: "sess-1",
  2301. deliveryKind: "desktop-continuous",
  2302. includeSnapshot: false,
  2303. })((event) => firstReceived.push(event));
  2304. await vi.waitFor(
  2305. () => {
  2306. expect(firstReceived.filter((event) => event.type === "session.event")).toHaveLength(1);
  2307. },
  2308. { timeout: 5000, interval: 50 },
  2309. );
  2310. const secondReceived: ZCodeAgentServiceEvent[] = [];
  2311. const secondSubscription = service.onDynamicSessionEvent({
  2312. workspacePath,
  2313. sessionId: "sess-1",
  2314. deliveryKind: "desktop-continuous",
  2315. includeSnapshot: false,
  2316. })((event) => secondReceived.push(event));
  2317. await vi.waitFor(
  2318. () => {
  2319. expect(secondReceived.filter((event) => event.type === "session.event")).toHaveLength(1);
  2320. },
  2321. { timeout: 5000, interval: 50 },
  2322. );
  2323. // Bugfix: 第二个订阅者自己的 replay 缺口不能广播回第一个订阅者。
  2324. expect(firstReceived.filter((event) => event.type === "session.event")).toHaveLength(1);
  2325. firstSubscription.dispose();
  2326. secondSubscription.dispose();
  2327. await service.disposeAllAndWait();
  2328. });
  2329. it("reports only validated de-duplicated CUA sideband events without legacy session delivery", async () => {
  2330. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-cua-operation-live-"));
  2331. createdDirs.push(workspacePath);
  2332. const scriptPath = join(workspacePath, "cua-operation-live-agent.cjs");
  2333. writeFileSync(scriptPath, CUA_OPERATION_LIVE_EVENT_FAKE_AGENT);
  2334. const reportedStates: Array<{ active: boolean; sessionId: string; turnId: string }> = [];
  2335. const observedServiceActiveStates: boolean[] = [];
  2336. let service: ReturnType<typeof createReadyZCodeAgentService>;
  2337. const onStateChanged = vi.fn(
  2338. (event: { active: boolean; sessionId: string; turnId: string }) => {
  2339. reportedStates.push(event);
  2340. observedServiceActiveStates.push(service.hasActiveCuaOperationTurn());
  2341. if (event.active) throw new Error("host port closed");
  2342. },
  2343. );
  2344. service = createReadyZCodeAgentService({
  2345. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2346. cuaOperationStateReporter: { onStateChanged },
  2347. });
  2348. expect(service.hasActiveCuaOperationTurn()).toBe(false);
  2349. const received: ZCodeAgentServiceEvent[] = [];
  2350. const subscription = service.onDynamicSessionEvent({
  2351. workspacePath,
  2352. sessionId: "sess-cua-live",
  2353. deliveryKind: "desktop-continuous",
  2354. includeSnapshot: false,
  2355. })((event) => received.push(event));
  2356. try {
  2357. await vi.waitFor(
  2358. () => {
  2359. expect(reportedStates.map((event) => event.active)).toEqual([true, false]);
  2360. },
  2361. { timeout: 5_000, interval: 50 },
  2362. );
  2363. const liveEvents = received
  2364. .filter(
  2365. (event): event is Extract<ZCodeAgentServiceEvent, { type: "session.event" }> =>
  2366. event.type === "session.event",
  2367. )
  2368. .map((event) => event.event);
  2369. expect(liveEvents).toEqual([]);
  2370. expect(onStateChanged).toHaveBeenCalledTimes(2);
  2371. expect(observedServiceActiveStates).toEqual([true, false]);
  2372. } finally {
  2373. subscription.dispose();
  2374. await service.disposeAllAndWait();
  2375. }
  2376. });
  2377. it("clears CUA state when the runtime becomes unavailable without a restart", async () => {
  2378. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-cua-runtime-exit-"));
  2379. createdDirs.push(workspacePath);
  2380. const scriptPath = join(workspacePath, "cua-operation-runtime-exit-agent.cjs");
  2381. writeFileSync(scriptPath, CUA_OPERATION_RUNTIME_EXIT_FAKE_AGENT);
  2382. const reportedStates: boolean[] = [];
  2383. const service = createReadyZCodeAgentService({
  2384. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2385. cuaOperationStateReporter: {
  2386. onStateChanged: (event) => reportedStates.push(event.active),
  2387. },
  2388. });
  2389. const subscription = service.onDynamicSessionEvent({
  2390. workspacePath,
  2391. sessionId: "sess-cua-runtime-exit",
  2392. deliveryKind: "desktop-continuous",
  2393. includeSnapshot: false,
  2394. })(() => undefined);
  2395. try {
  2396. await vi.waitFor(
  2397. () => {
  2398. expect(reportedStates).toEqual([true, false]);
  2399. expect(service.hasActiveCuaOperationTurn()).toBe(false);
  2400. },
  2401. { timeout: 5_000, interval: 50 },
  2402. );
  2403. } finally {
  2404. subscription.dispose();
  2405. await service.disposeAllAndWait();
  2406. }
  2407. });
  2408. it("retries createSession without optional fields rejected by legacy agents", async () => {
  2409. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-compat-"));
  2410. createdDirs.push(workspacePath);
  2411. const scriptPath = join(workspacePath, "legacy-create-agent.cjs");
  2412. writeFileSync(scriptPath, LEGACY_CREATE_PARAMS_FAKE_AGENT);
  2413. const service = createReadyZCodeAgentService({
  2414. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2415. });
  2416. try {
  2417. const snapshot = await service.createSession({
  2418. workspacePath,
  2419. model: { providerId: "glm", modelId: "glm-4.6" },
  2420. persistence: "deferred",
  2421. thoughtLevel: "max",
  2422. mcpServers: [
  2423. {
  2424. name: "chrome-devtools",
  2425. command: "npx",
  2426. args: ["-y", "chrome-devtools-mcp@latest"],
  2427. env: [],
  2428. },
  2429. ],
  2430. });
  2431. expect(snapshot.session.sessionId).toBe("sess_compat");
  2432. expect(snapshot.settings.thoughtLevel.current).toBe("max");
  2433. } finally {
  2434. await service.disposeAllAndWait();
  2435. }
  2436. });
  2437. it("restarts a stale protocol client and retries plugin list without provider registry sync", async () => {
  2438. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugins-"));
  2439. createdDirs.push(workspacePath);
  2440. const scriptPath = join(workspacePath, "stale-plugin-agent.cjs");
  2441. const markerPath = join(workspacePath, "first-run-marker");
  2442. writeFileSync(scriptPath, STALE_THEN_PLUGIN_LIST_FAKE_AGENT);
  2443. const commandResolver = vi.fn(() => ({
  2444. command: process.execPath,
  2445. args: [scriptPath, markerPath],
  2446. }));
  2447. const service = createReadyZCodeAgentService({
  2448. commandResolver,
  2449. // Bugfix: 该用例只需要首个 fake agent 超时,full suite 并发时第二个进程启动到响应可能超过 500ms。
  2450. // 局部放宽 request timeout,避免把重启后成功恢复的路径误判成第二次 stale。
  2451. requestTimeoutMs: 1_500,
  2452. });
  2453. try {
  2454. const result = await service.listPlugins({ workspacePath });
  2455. expect(result.plugins.map((plugin) => plugin.name)).toEqual(["skill-creator"]);
  2456. expect(commandResolver).toHaveBeenCalledTimes(2);
  2457. } finally {
  2458. await service.disposeAllAndWait();
  2459. }
  2460. });
  2461. it("loads plugin list from the dedicated plugin workspace when the real workspace is missing", async () => {
  2462. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugin-cwd-"));
  2463. createdDirs.push(sandboxRoot);
  2464. setDataBaseDir(sandboxRoot);
  2465. const scriptPath = join(sandboxRoot, "plugin-cwd-agent.cjs");
  2466. writeFileSync(scriptPath, PLUGIN_LIST_ECHO_CWD_FAKE_AGENT);
  2467. const missingWorkspacePath = join(sandboxRoot, "deleted-workspace");
  2468. const pluginWorkspacePath = join(sandboxRoot, ".zcode", "plugin-workspace");
  2469. const commandResolver = vi.fn(({ workspacePath }) => ({
  2470. command: process.execPath,
  2471. args: [scriptPath],
  2472. cwd: workspacePath,
  2473. }));
  2474. const service = createReadyZCodeAgentService({ commandResolver });
  2475. try {
  2476. const result = await service.listPlugins({ workspacePath: missingWorkspacePath });
  2477. expect(existsSync(pluginWorkspacePath)).toBe(true);
  2478. expect(realpathSync(result.plugins[0]!.rootPath)).toBe(realpathSync(pluginWorkspacePath));
  2479. expect(result.diagnostics[0]?.message).toBe(missingWorkspacePath);
  2480. expect(commandResolver).toHaveBeenCalledWith({
  2481. workspacePath: pluginWorkspacePath,
  2482. workspaceKey: pluginWorkspacePath,
  2483. });
  2484. } finally {
  2485. await service.disposeAllAndWait();
  2486. }
  2487. });
  2488. it("updatePlugin issues plugins/update with the requested pluginId", async () => {
  2489. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugin-update-"));
  2490. createdDirs.push(workspacePath);
  2491. const scriptPath = join(workspacePath, "plugin-update-agent.cjs");
  2492. writeFileSync(scriptPath, PLUGIN_UPDATE_ECHO_FAKE_AGENT);
  2493. const service = createReadyZCodeAgentService({
  2494. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2495. });
  2496. try {
  2497. const result = await service.updatePlugin({
  2498. workspacePath,
  2499. pluginId: "skill-creator@zcode-plugins-official",
  2500. });
  2501. expect(result.installedPlugins).toEqual([]);
  2502. expect(result.diagnostics[0]?.code).toBe("echo-plugin-id");
  2503. expect(result.diagnostics[0]?.message).toBe("skill-creator@zcode-plugins-official");
  2504. } finally {
  2505. await service.disposeAllAndWait();
  2506. }
  2507. });
  2508. it("restoreBuiltinPlugin issues plugins/restoreBuiltin with the requested pluginId", async () => {
  2509. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-plugin-restore-"));
  2510. createdDirs.push(workspacePath);
  2511. const scriptPath = join(workspacePath, "plugin-restore-agent.cjs");
  2512. writeFileSync(scriptPath, PLUGIN_RESTORE_BUILTIN_ECHO_FAKE_AGENT);
  2513. const service = createReadyZCodeAgentService({
  2514. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2515. });
  2516. try {
  2517. const result = await service.restoreBuiltinPlugin({
  2518. workspacePath,
  2519. pluginId: "skill-creator@zcode-plugins-official",
  2520. });
  2521. expect(result.pluginId).toBe("skill-creator@zcode-plugins-official");
  2522. expect(result.diagnostics).toEqual([]);
  2523. } finally {
  2524. await service.disposeAllAndWait();
  2525. }
  2526. });
  2527. it("restarts a stale protocol client and retries MCP status list without provider registry sync", async () => {
  2528. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-list-"));
  2529. createdDirs.push(workspacePath);
  2530. const scriptPath = join(workspacePath, "stale-mcp-list-agent.cjs");
  2531. const markerPath = join(workspacePath, "first-run-marker");
  2532. writeFileSync(scriptPath, STALE_THEN_MCP_LIST_FAKE_AGENT);
  2533. const commandResolver = vi.fn(() => ({
  2534. command: process.execPath,
  2535. args: [scriptPath, markerPath],
  2536. }));
  2537. const service = createReadyZCodeAgentService({
  2538. commandResolver,
  2539. requestTimeoutMs: 1_500,
  2540. });
  2541. try {
  2542. const result = await service.listMcpServerStatuses({ workspacePath });
  2543. expect(result.statuses.filesystem?.status).toBe("disconnected");
  2544. expect(commandResolver).toHaveBeenCalledTimes(2);
  2545. } finally {
  2546. await service.disposeAllAndWait();
  2547. }
  2548. });
  2549. it("loads MCP status list through the dedicated plugin workspace", async () => {
  2550. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-cwd-"));
  2551. createdDirs.push(sandboxRoot);
  2552. setDataBaseDir(sandboxRoot);
  2553. const scriptPath = join(sandboxRoot, "mcp-cwd-agent.cjs");
  2554. writeFileSync(scriptPath, MCP_LIST_ECHO_CWD_FAKE_AGENT);
  2555. const missingWorkspacePath = join(sandboxRoot, "deleted-workspace");
  2556. const pluginWorkspacePath = join(sandboxRoot, ".zcode", "plugin-workspace");
  2557. const commandResolver = vi.fn(({ workspacePath }) => ({
  2558. command: process.execPath,
  2559. args: [scriptPath],
  2560. cwd: workspacePath,
  2561. }));
  2562. const service = createReadyZCodeAgentService({ commandResolver });
  2563. try {
  2564. const result = await service.listMcpServerStatuses({ workspacePath: missingWorkspacePath });
  2565. expect(existsSync(pluginWorkspacePath)).toBe(true);
  2566. expect(result.statuses.cwd?.error).toBe(missingWorkspacePath);
  2567. expect(commandResolver).toHaveBeenCalledWith({
  2568. workspacePath: pluginWorkspacePath,
  2569. workspaceKey: pluginWorkspacePath,
  2570. });
  2571. } finally {
  2572. await service.disposeAllAndWait();
  2573. }
  2574. });
  2575. it("plugins/uninstall 不会排在挂起的 mcp/list 后面:MCP 状态探测使用独立 agent 进程", async () => {
  2576. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-"));
  2577. createdDirs.push(sandboxRoot);
  2578. setDataBaseDir(sandboxRoot);
  2579. const scriptPath = join(sandboxRoot, "serial-queue-agent.cjs");
  2580. const markerPath = join(sandboxRoot, "mcp-list-received");
  2581. writeFileSync(scriptPath, SERIAL_QUEUE_HANG_ON_MCP_LIST_FAKE_AGENT);
  2582. const commandResolver = vi.fn(() => ({
  2583. command: process.execPath,
  2584. args: [scriptPath, markerPath],
  2585. }));
  2586. const service = createReadyZCodeAgentService({ commandResolver });
  2587. try {
  2588. // connect 模式的 mcp/list 在真实环境里会因坏 MCP server 吃满 30s 超时;这里让它永不返回。
  2589. const mcpListPromise = service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2590. mcpListPromise.catch(() => undefined);
  2591. await vi.waitFor(() => expect(existsSync(markerPath)).toBe(true), { timeout: 5_000 });
  2592. const result = await Promise.race([
  2593. service.uninstallPlugin({ workspacePath: sandboxRoot, pluginId: "pick-funds" }),
  2594. new Promise<never>((_, reject) =>
  2595. setTimeout(() => reject(new Error("plugins/uninstall 被 mcp/list 阻塞")), 3_000),
  2596. ),
  2597. ]);
  2598. expect(result.diagnostics).toEqual([]);
  2599. // 两类请求必须落在不同的 agent 进程上
  2600. expect(commandResolver).toHaveBeenCalledTimes(2);
  2601. } finally {
  2602. await service.disposeAllAndWait();
  2603. }
  2604. });
  2605. it("mcp-status lane 进程的 spawn/exit 会上报 processLifecycleReporter", async () => {
  2606. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-report-"));
  2607. createdDirs.push(sandboxRoot);
  2608. setDataBaseDir(sandboxRoot);
  2609. const scriptPath = join(sandboxRoot, "serial-queue-agent.cjs");
  2610. const markerPath = join(sandboxRoot, "mcp-list-received");
  2611. writeFileSync(scriptPath, SERIAL_QUEUE_HANG_ON_MCP_LIST_FAKE_AGENT);
  2612. const processLifecycleReporter = {
  2613. onSpawn: vi.fn(),
  2614. onReady: vi.fn(),
  2615. onExit: vi.fn(),
  2616. onError: vi.fn(),
  2617. };
  2618. const service = createReadyZCodeAgentService({
  2619. commandResolver: () => ({ command: process.execPath, args: [scriptPath, markerPath] }),
  2620. processLifecycleReporter,
  2621. });
  2622. try {
  2623. // 只走 mcp-status lane:该进程是本 lane 新增的长驻 agent,进程监控器必须能看到它。
  2624. const mcpListPromise = service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2625. mcpListPromise.catch(() => undefined);
  2626. await vi.waitFor(() => expect(existsSync(markerPath)).toBe(true), { timeout: 5_000 });
  2627. await vi.waitFor(() => expect(processLifecycleReporter.onSpawn).toHaveBeenCalledTimes(1));
  2628. // macOS tmpdir 会被 realpath 成 /private/var,这里不比对 workspacePath 字面值。
  2629. // 评审 SG-02:mcp-status 与 plugin lane 共用同一 workspacePath/command,事件必须带 lane 才可归因。
  2630. expect(processLifecycleReporter.onSpawn.mock.calls[0]![0]).toMatchObject({
  2631. pid: expect.any(Number),
  2632. provider: "glm",
  2633. lane: "mcp-status",
  2634. });
  2635. } finally {
  2636. await service.disposeAllAndWait();
  2637. }
  2638. await vi.waitFor(() => expect(processLifecycleReporter.onExit).toHaveBeenCalledTimes(1));
  2639. expect(processLifecycleReporter.onExit.mock.calls[0]![0]).toMatchObject({ lane: "mcp-status" });
  2640. });
  2641. it("mcp-status lane 空闲超时后回收进程并释放 MCP 连接,下次探测重新拉起", async () => {
  2642. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-idle-"));
  2643. createdDirs.push(sandboxRoot);
  2644. setDataBaseDir(sandboxRoot);
  2645. const scriptPath = join(sandboxRoot, "mcp-echo-agent.cjs");
  2646. writeFileSync(scriptPath, MCP_LIST_ECHO_MODE_FAKE_AGENT);
  2647. const commandResolver = vi.fn(() => ({ command: process.execPath, args: [scriptPath] }));
  2648. const processLifecycleReporter = {
  2649. onSpawn: vi.fn(),
  2650. onReady: vi.fn(),
  2651. onExit: vi.fn(),
  2652. onError: vi.fn(),
  2653. };
  2654. const service = createReadyZCodeAgentService({
  2655. commandResolver,
  2656. processLifecycleReporter,
  2657. mcpStatusIdleTimeoutMs: 300,
  2658. });
  2659. try {
  2660. await service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2661. expect(commandResolver).toHaveBeenCalledTimes(1);
  2662. // 探测完成后无请求在飞,超过空闲阈值必须主动回收,且以 expected/idle-timeout 归因。
  2663. await vi.waitFor(() => expect(processLifecycleReporter.onExit).toHaveBeenCalledTimes(1), {
  2664. timeout: 5_000,
  2665. });
  2666. expect(processLifecycleReporter.onExit.mock.calls[0]![0]).toMatchObject({
  2667. lane: "mcp-status",
  2668. terminationKind: "expected",
  2669. terminationReason: "idle-timeout",
  2670. });
  2671. // 回收后再次探测要透明地重新拉起进程,而不是拿到已回收的 client 报错。
  2672. await service.listMcpServerStatuses({ workspacePath: sandboxRoot });
  2673. expect(commandResolver).toHaveBeenCalledTimes(2);
  2674. } finally {
  2675. await service.disposeAllAndWait();
  2676. }
  2677. });
  2678. it("mcp/list 超时触发 watchdog 回收后重试仍落在 mcp-status lane,plugin lane 进程不受影响", async () => {
  2679. const sandboxRoot = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-lane-timeout-"));
  2680. createdDirs.push(sandboxRoot);
  2681. setDataBaseDir(sandboxRoot);
  2682. const scriptPath = join(sandboxRoot, "serial-queue-agent.cjs");
  2683. const markerPath = join(sandboxRoot, "mcp-list-received");
  2684. writeFileSync(scriptPath, SERIAL_QUEUE_HANG_ON_MCP_LIST_FAKE_AGENT);
  2685. const commandResolver = vi.fn(() => ({
  2686. command: process.execPath,
  2687. args: [scriptPath, markerPath],
  2688. }));
  2689. const processLifecycleReporter = {
  2690. onSpawn: vi.fn(),
  2691. onReady: vi.fn(),
  2692. onExit: vi.fn(),
  2693. onError: vi.fn(),
  2694. };
  2695. const service = createReadyZCodeAgentService({
  2696. commandResolver,
  2697. processLifecycleReporter,
  2698. // 覆盖 fake agent 冷启动(node 进程拉起 + 首个响应),又足够短让两次超时在秒级完成。
  2699. requestTimeoutMs: 1_500,
  2700. });
  2701. try {
  2702. // 先让 plugin lane 起一个进程,作为“不受影响”的对照(该 fake agent 只应答 plugins/uninstall)。
  2703. await service.uninstallPlugin({ workspacePath: sandboxRoot, pluginId: "pick-funds" });
  2704. expect(commandResolver).toHaveBeenCalledTimes(1);
  2705. // mcp/list 永不返回:首次超时 → watchdog 回收 mcp-status 进程 → 重试一次 → 再超时 → 抛错。
  2706. await expect(service.listMcpServerStatuses({ workspacePath: sandboxRoot })).rejects.toThrow(
  2707. /timed out/u,
  2708. );
  2709. // plugin lane 1 次 + mcp-status lane 首发 1 次 + 重试重新拉起 1 次
  2710. expect(commandResolver).toHaveBeenCalledTimes(3);
  2711. await vi.waitFor(
  2712. () =>
  2713. expect(
  2714. processLifecycleReporter.onExit.mock.calls.filter(
  2715. ([event]) =>
  2716. event.lane === "mcp-status" && event.terminationKind === "watchdog_recycle",
  2717. ),
  2718. ).toHaveLength(2),
  2719. // 修复原因:第二次 watchdog 与 mcp/list 的 reject 同 tick 触发,exit 事件要等
  2720. // Windows 进程树回收(taskkill /T + 重试)完成后才上报;vi.waitFor 默认 1000ms
  2721. // 在慢盘/高负载本机会先超时,把环境慢误报成用例失败。CI 快机器不受影响。
  2722. { timeout: 8_000 },
  2723. );
  2724. // plugin lane 进程从未被回收,且仍能正常服务。
  2725. expect(
  2726. processLifecycleReporter.onExit.mock.calls.filter(([event]) => event.lane !== "mcp-status"),
  2727. ).toHaveLength(0);
  2728. await service.uninstallPlugin({ workspacePath: sandboxRoot, pluginId: "pick-funds" });
  2729. expect(commandResolver).toHaveBeenCalledTimes(3);
  2730. } finally {
  2731. await service.disposeAllAndWait();
  2732. }
  2733. });
  2734. it("passes UI-resolved MCP servers to mcp/list", async () => {
  2735. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-explicit-"));
  2736. createdDirs.push(workspacePath);
  2737. const scriptPath = join(workspacePath, "mcp-explicit-agent.cjs");
  2738. writeFileSync(scriptPath, MCP_LIST_ECHO_MCP_SERVERS_FAKE_AGENT);
  2739. const service = createReadyZCodeAgentService({
  2740. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2741. });
  2742. try {
  2743. const result = await service.listMcpServerStatuses({
  2744. workspacePath,
  2745. mcpServers: [
  2746. {
  2747. name: "agents-fallback",
  2748. command: "node",
  2749. args: ["server.mjs"],
  2750. env: [{ name: "TOKEN", value: "secret" }],
  2751. timeoutMs: 3000,
  2752. },
  2753. ],
  2754. });
  2755. expect(JSON.parse(result.statuses.explicit?.error ?? "null")).toEqual([
  2756. {
  2757. name: "agents-fallback",
  2758. command: "node",
  2759. args: ["server.mjs"],
  2760. env: [{ name: "TOKEN", value: "secret" }],
  2761. timeoutMs: 3000,
  2762. },
  2763. ]);
  2764. } finally {
  2765. await service.disposeAllAndWait();
  2766. }
  2767. });
  2768. it("passes status mode to mcp/list", async () => {
  2769. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-mode-"));
  2770. createdDirs.push(workspacePath);
  2771. const scriptPath = join(workspacePath, "mcp-mode-agent.cjs");
  2772. writeFileSync(scriptPath, MCP_LIST_ECHO_MODE_FAKE_AGENT);
  2773. const service = createZCodeAgentService({
  2774. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2775. });
  2776. try {
  2777. const result = await service.listMcpServerStatuses({
  2778. workspacePath,
  2779. mode: "status",
  2780. });
  2781. expect(JSON.parse(result.statuses.mode?.error ?? "null")).toBe("status");
  2782. } finally {
  2783. await service.disposeAllAndWait();
  2784. }
  2785. });
  2786. it("retries mcp/list without explicit MCP servers for legacy agents", async () => {
  2787. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-compat-"));
  2788. createdDirs.push(workspacePath);
  2789. const scriptPath = join(workspacePath, "mcp-compat-agent.cjs");
  2790. writeFileSync(scriptPath, MCP_LIST_REJECTS_MCP_SERVERS_ONCE_FAKE_AGENT);
  2791. const service = createReadyZCodeAgentService({
  2792. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2793. });
  2794. try {
  2795. const result = await service.listMcpServerStatuses({
  2796. workspacePath,
  2797. mcpServers: [],
  2798. });
  2799. expect(result.statuses.fallback?.status).toBe("disconnected");
  2800. } finally {
  2801. await service.disposeAllAndWait();
  2802. }
  2803. });
  2804. it("retries connect-mode mcp/list without mode for legacy agents", async () => {
  2805. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-service-mcp-mode-compat-"));
  2806. createdDirs.push(workspacePath);
  2807. const scriptPath = join(workspacePath, "mcp-mode-compat-agent.cjs");
  2808. writeFileSync(scriptPath, MCP_LIST_REJECTS_MODE_ONCE_FAKE_AGENT);
  2809. const service = createZCodeAgentService({
  2810. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2811. });
  2812. try {
  2813. const result = await service.listMcpServerStatuses({
  2814. workspacePath,
  2815. mode: "connect",
  2816. });
  2817. expect(result.statuses.fallback?.status).toBe("disconnected");
  2818. expect(JSON.parse(result.statuses.fallback?.error ?? "null")).toBeNull();
  2819. } finally {
  2820. await service.disposeAllAndWait();
  2821. }
  2822. });
  2823. it("does not retry status-only mcp/list as connect for legacy agents", async () => {
  2824. const workspacePath = mkdtempSync(
  2825. join(tmpdir(), "zcode-agent-service-mcp-mode-subset-compat-"),
  2826. );
  2827. createdDirs.push(workspacePath);
  2828. const scriptPath = join(workspacePath, "mcp-mode-subset-compat-agent.cjs");
  2829. writeFileSync(scriptPath, MCP_LIST_REJECTS_MODE_ONCE_FAKE_AGENT);
  2830. const service = createZCodeAgentService({
  2831. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  2832. });
  2833. try {
  2834. await expect(
  2835. service.listMcpServerStatuses({
  2836. workspacePath,
  2837. mode: "status",
  2838. mcpServers: [
  2839. {
  2840. name: "plugin:canva:canva",
  2841. type: "http",
  2842. url: "https://mcp.canva.example.test/mcp",
  2843. headers: [],
  2844. },
  2845. ],
  2846. }),
  2847. ).rejects.toMatchObject({
  2848. code: ZCODE_AGENT_MCP_STATUS_MODE_UNSUPPORTED_ERROR_CODE,
  2849. name: "ZCodeAgentMcpStatusModeUnsupportedError",
  2850. });
  2851. } finally {
  2852. await service.disposeAllAndWait();
  2853. }
  2854. });
  2855. });