standalone-bootstrap.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. import { mkdtemp, readFile, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { createSessionId, type PermissionBrokerRequest, type SessionId } from "@zcode/contracts";
  6. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  7. import { createRegistryBackedTestApp } from "../helpers/registry-backed-test-app.js";
  8. const CLI_TOOLS = [
  9. "ListSessions",
  10. "ReadSession",
  11. "CreateSession",
  12. "ForkSession",
  13. "SendToSession",
  14. "WaitSessions",
  15. "InterruptSession",
  16. "RenameSession",
  17. ];
  18. const APP_ONLY_TOOLS = ["ListProjects", "OpenSession", "SetSessionArchived", "SetSessionPinned"];
  19. const cleanups: Array<() => Promise<void>> = [];
  20. afterEach(async () => {
  21. for (const close of cleanups.splice(0).reverse()) await close();
  22. });
  23. describe("standalone session tools bootstrap", () => {
  24. it("only registers CLI tools at explicit standalone startup and reaches the real root manager", async () => {
  25. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-bootstrap-"));
  26. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  27. cleanups.push(async () => {
  28. store.close();
  29. await rm(cwd, { recursive: true, force: true });
  30. });
  31. const sessionId = createSessionId("standalone-root");
  32. let calls = 0;
  33. const root = await createRegistryBackedTestApp({
  34. standaloneSessionControl: true,
  35. sessionId,
  36. sessionStore: store,
  37. skipUserConfig: true,
  38. env: { ZCODE_STORAGE_DIR: cwd },
  39. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  40. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  41. modelExecutor: {
  42. generateText: async () => {
  43. if (calls++ === 0)
  44. return {
  45. text: "",
  46. finishReason: "tool-calls",
  47. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  48. toolCalls: [
  49. {
  50. id: "rename-root",
  51. name: "RenameSession",
  52. input: {
  53. sessionId,
  54. title: "Renamed through owner",
  55. },
  56. },
  57. ],
  58. };
  59. return {
  60. text: "done",
  61. finishReason: "stop",
  62. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  63. };
  64. },
  65. },
  66. });
  67. cleanups.push(async () => {
  68. await root.close?.();
  69. });
  70. const registry = root.runtime.getToolRegistry();
  71. // 工具名统一后没有前缀:独立 CLI 只注册共有 8 个,App 独有的 4 个不出现。
  72. const registered = registry.list();
  73. expect(CLI_TOOLS.filter((name) => registered.includes(name))).toEqual(CLI_TOOLS);
  74. expect(APP_ONLY_TOOLS.some((name) => registered.includes(name))).toBe(false);
  75. await root.submitPrompt("Rename this session");
  76. expect(calls).toBeGreaterThanOrEqual(2);
  77. expect((await store.getSession(sessionId))?.title).toBe("Renamed through owner");
  78. expect(
  79. (await store.messages({ sessionID: sessionId }))
  80. .flatMap((message) => message.parts)
  81. .some((part) => part.type === "tool" && part.tool === "RenameSession"),
  82. ).toBe(true);
  83. await root.close?.();
  84. });
  85. it.each([true, false])(
  86. "does not grant target write access to persisted history (resume=%s)",
  87. async (resume) => {
  88. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-resume-scope-"));
  89. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  90. cleanups.push(async () => {
  91. store.close();
  92. await rm(cwd, { recursive: true, force: true });
  93. });
  94. const sessionId = createSessionId("resumed-root");
  95. const original = await createRegistryBackedTestApp({
  96. sessionId,
  97. sessionStore: store,
  98. skipUserConfig: true,
  99. env: { ZCODE_STORAGE_DIR: cwd },
  100. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  101. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  102. modelExecutor: {
  103. generateText: async () => ({
  104. text: "seeded",
  105. finishReason: "stop",
  106. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  107. }),
  108. },
  109. });
  110. cleanups.push(async () => {
  111. await original.close?.();
  112. });
  113. await original.submitPrompt("Preserve this independent history");
  114. await original.setCustomSessionTitle({ title: "Original history" });
  115. await original.close?.();
  116. let calls = 0;
  117. const resumed = await createRegistryBackedTestApp({
  118. standaloneSessionControl: true,
  119. resume,
  120. sessionId,
  121. sessionStore: store,
  122. skipUserConfig: true,
  123. env: { ZCODE_STORAGE_DIR: cwd },
  124. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  125. modelExecutor: {
  126. generateText: async () => {
  127. if (calls++ === 0)
  128. return {
  129. text: "",
  130. finishReason: "tool-calls",
  131. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  132. toolCalls: [
  133. {
  134. id: "rename-unverified",
  135. name: "RenameSession",
  136. input: {
  137. sessionId,
  138. title: "Must not rename",
  139. },
  140. },
  141. ],
  142. };
  143. return {
  144. text: "not renamed",
  145. finishReason: "stop",
  146. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  147. };
  148. },
  149. },
  150. });
  151. cleanups.push(async () => {
  152. await resumed.close?.();
  153. });
  154. await resumed.submitPrompt("Try session-control rename without owner provenance");
  155. expect(calls).toBeGreaterThanOrEqual(2);
  156. const finalTitle = (await store.getSession(sessionId))?.title;
  157. expect(finalTitle).not.toBe("Must not rename");
  158. if (resume) expect(finalTitle).toBe("Original history");
  159. const attempted = (await store.messages({ sessionID: sessionId }))
  160. .flatMap((message) => message.parts)
  161. .find((part) => part.type === "tool" && part.callID === "rename-unverified");
  162. expect(attempted).toMatchObject({
  163. type: "tool",
  164. tool: "RenameSession",
  165. state: { status: "error" },
  166. });
  167. },
  168. );
  169. it("creates a real independent root in build mode from a yolo actor and interrupts it on owner close", async () => {
  170. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-life-"));
  171. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  172. cleanups.push(async () => {
  173. store.close();
  174. await rm(cwd, { recursive: true, force: true });
  175. });
  176. const sessionId = createSessionId("actor-yolo");
  177. let actorCalls = 0;
  178. let childSessionId: string | undefined;
  179. let childStarted!: () => void;
  180. const started = new Promise<void>((resolve) => {
  181. childStarted = resolve;
  182. });
  183. const root = await createRegistryBackedTestApp({
  184. standaloneSessionControl: true,
  185. sessionId,
  186. sessionStore: store,
  187. skipUserConfig: true,
  188. env: { ZCODE_STORAGE_DIR: cwd },
  189. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  190. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  191. modelExecutor: {
  192. generateText: async (request) => {
  193. if (
  194. request.messages.some(
  195. (message) => message.role === "user" && message.content === "run background work",
  196. )
  197. ) {
  198. childSessionId = (await store.listSessions()).find(
  199. (session) => session.id !== sessionId,
  200. )?.id;
  201. childStarted();
  202. return new Promise((_resolve, reject) => {
  203. if (request.abortSignal?.aborted) reject(request.abortSignal.reason);
  204. else
  205. request.abortSignal?.addEventListener(
  206. "abort",
  207. () => reject(request.abortSignal?.reason),
  208. { once: true },
  209. );
  210. });
  211. }
  212. if (actorCalls++ === 0)
  213. return {
  214. text: "",
  215. finishReason: "tool-calls",
  216. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  217. toolCalls: [
  218. {
  219. id: "create-root",
  220. name: "CreateSession",
  221. input: { prompt: "run background work" },
  222. },
  223. ],
  224. };
  225. return {
  226. text: "created",
  227. finishReason: "stop",
  228. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  229. };
  230. },
  231. },
  232. });
  233. cleanups.push(async () => {
  234. await root.close?.();
  235. });
  236. await root.submitPrompt("Create another root session");
  237. await started;
  238. const child = await store.getSession(childSessionId as SessionId);
  239. expect(child?.taskType).toBe("interactive");
  240. expect(child?.parentID).toBeUndefined();
  241. await root.close?.();
  242. expect((await store.getSession(childSessionId as SessionId))?.lastOutcome).toBe("interrupted");
  243. const assistantMessages = (
  244. await store.messages({ sessionID: childSessionId as SessionId })
  245. ).filter((message) => message.info.role === "assistant");
  246. expect(assistantMessages.length).toBeGreaterThan(0);
  247. expect(
  248. assistantMessages.every(
  249. (message) => message.info.role === "assistant" && message.info.mode === "build",
  250. ),
  251. ).toBe(true);
  252. });
  253. // 回归(会话工具设计 0.5):后台根原先不接启动方的 broker,需要审批的工具被 Core 的拒绝 broker
  254. // 直接拒绝。现在询问进入同一个 broker,带后台会话自己的 sessionId;发起者的 yolo 不传给后台根。
  255. it.each(["allow", "deny"] as const)(
  256. "routes a background root approval to the launcher broker (%s)",
  257. async (decision) => {
  258. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-approval-"));
  259. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  260. cleanups.push(async () => {
  261. store.close();
  262. await rm(cwd, { recursive: true, force: true });
  263. });
  264. const actorId = createSessionId("actor-approval");
  265. const target = join(cwd, "background.txt");
  266. const asked: PermissionBrokerRequest[] = [];
  267. const backgroundDone = Promise.withResolvers<string>();
  268. let actorCalls = 0;
  269. let backgroundCalls = 0;
  270. const root = await createRegistryBackedTestApp({
  271. standaloneSessionControl: true,
  272. sessionId: actorId,
  273. sessionStore: store,
  274. skipUserConfig: true,
  275. env: { ZCODE_STORAGE_DIR: cwd },
  276. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  277. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  278. permissionBroker: {
  279. requestPermission: async (request) => {
  280. asked.push(request);
  281. return { decision, reason: `${decision} by launcher test`, resolvedAt: new Date() };
  282. },
  283. },
  284. modelExecutor: {
  285. generateText: async (request) => {
  286. // 只按用户输入区分会话:发起者的 CreateSession 参数里也带标记,不能按整份请求匹配。
  287. const background = request.messages.some(
  288. (message) =>
  289. message.role === "user" &&
  290. JSON.stringify(message.content).includes("E2E_BACKGROUND_WRITE"),
  291. );
  292. if (background) {
  293. if (backgroundCalls++ === 0)
  294. return {
  295. text: "",
  296. finishReason: "tool-calls",
  297. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  298. toolCalls: [
  299. {
  300. id: "background-write",
  301. name: "Write",
  302. input: { file_path: target, content: "written after approval" },
  303. },
  304. ],
  305. };
  306. const result = request.messages.find(
  307. (message) => message.role === "tool" && message.toolCallId === "background-write",
  308. );
  309. backgroundDone.resolve(JSON.stringify(result?.content ?? ""));
  310. return {
  311. text: "background done",
  312. finishReason: "stop",
  313. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  314. };
  315. }
  316. if (actorCalls++ === 0)
  317. return {
  318. text: "",
  319. finishReason: "tool-calls",
  320. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  321. toolCalls: [
  322. {
  323. id: "create-background",
  324. name: "CreateSession",
  325. input: { prompt: "E2E_BACKGROUND_WRITE" },
  326. },
  327. ],
  328. };
  329. return {
  330. text: "created",
  331. finishReason: "stop",
  332. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  333. };
  334. },
  335. },
  336. });
  337. cleanups.push(async () => {
  338. await root.close?.();
  339. });
  340. // 发起者是 yolo,自己的 CreateSession 不询问;询问只来自后台根。
  341. await root.submitPrompt("Create a background writer");
  342. const toolResult = await backgroundDone.promise;
  343. expect(asked).toHaveLength(1);
  344. expect(asked[0]).toMatchObject({ toolName: "Write", mode: "build" });
  345. expect(asked[0]!.sessionId).not.toBe(actorId);
  346. const background = await store.getSession(asked[0]!.sessionId);
  347. expect(background?.parentID).toBeUndefined();
  348. if (decision === "allow") {
  349. expect(await readFile(target, "utf8")).toBe("written after approval");
  350. } else {
  351. await expect(readFile(target, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  352. expect(toolResult).toContain("deny by launcher test");
  353. }
  354. },
  355. );
  356. // SCT08:后台根等待审批时,发起者的 wait 只看到 needs_attention,不能代答;用户回答后后台根继续。
  357. it("reports needs_attention to the actor while the user has not answered", async () => {
  358. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-attention-"));
  359. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  360. cleanups.push(async () => {
  361. store.close();
  362. await rm(cwd, { recursive: true, force: true });
  363. });
  364. const target = join(cwd, "attention.txt");
  365. const asked = Promise.withResolvers<PermissionBrokerRequest>();
  366. const answer = Promise.withResolvers<"allow">();
  367. const backgroundDone = Promise.withResolvers<void>();
  368. const waited: unknown[] = [];
  369. let backgroundCalls = 0;
  370. const toolText = (
  371. request: { messages: { role: string; toolCallId?: string; content: unknown }[] },
  372. id: string,
  373. ) => {
  374. const content = request.messages.find(
  375. (message) => message.role === "tool" && message.toolCallId === id,
  376. )?.content;
  377. const text =
  378. typeof content === "string"
  379. ? content
  380. : ((content as { type: string; text?: string }[] | undefined) ?? [])
  381. .filter((block) => block.type === "text")
  382. .map((block) => block.text)
  383. .join("\n");
  384. const reminder = text.indexOf("\n\n<system-reminder>");
  385. return reminder < 0 ? text : text.slice(0, reminder);
  386. };
  387. const root = await createRegistryBackedTestApp({
  388. standaloneSessionControl: true,
  389. sessionStore: store,
  390. skipUserConfig: true,
  391. env: { ZCODE_STORAGE_DIR: cwd },
  392. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  393. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  394. permissionBroker: {
  395. requestPermission: async (request) => {
  396. asked.resolve(request);
  397. return {
  398. decision: await answer.promise,
  399. reason: "user answered",
  400. resolvedAt: new Date(),
  401. };
  402. },
  403. },
  404. modelExecutor: {
  405. generateText: async (request) => {
  406. const background = request.messages.some(
  407. (message) =>
  408. message.role === "user" &&
  409. JSON.stringify(message.content).includes("E2E_ATTENTION_WRITE"),
  410. );
  411. if (background) {
  412. if (backgroundCalls++ === 0)
  413. return {
  414. text: "",
  415. finishReason: "tool-calls",
  416. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  417. toolCalls: [
  418. {
  419. id: "attention-write",
  420. name: "Write",
  421. input: { file_path: target, content: "written after the user answered" },
  422. },
  423. ],
  424. };
  425. backgroundDone.resolve();
  426. return {
  427. text: "background done",
  428. finishReason: "stop",
  429. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  430. };
  431. }
  432. if (!request.messages.some((message) => message.toolCallId === "create-attention"))
  433. return {
  434. text: "",
  435. finishReason: "tool-calls",
  436. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  437. toolCalls: [
  438. {
  439. id: "create-attention",
  440. name: "CreateSession",
  441. input: { prompt: "E2E_ATTENTION_WRITE" },
  442. },
  443. ],
  444. };
  445. if (!request.messages.some((message) => message.toolCallId === "wait-attention")) {
  446. // operation 只取自真实 CreateSession 回执;工具面只收 sessionId + commandId(规格 0.11)。
  447. const created = JSON.parse(toolText(request, "create-attention")) as {
  448. operation: { session: { sessionId: string }; commandId: string };
  449. };
  450. return {
  451. text: "",
  452. finishReason: "tool-calls",
  453. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  454. toolCalls: [
  455. {
  456. id: "wait-attention",
  457. name: "WaitSessions",
  458. input: {
  459. operations: [
  460. {
  461. sessionId: created.operation.session.sessionId,
  462. commandId: created.operation.commandId,
  463. },
  464. ],
  465. mode: "any",
  466. timeoutMs: 30_000,
  467. },
  468. },
  469. ],
  470. };
  471. }
  472. waited.push(JSON.parse(toolText(request, "wait-attention")));
  473. return {
  474. text: "observed",
  475. finishReason: "stop",
  476. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  477. };
  478. },
  479. },
  480. });
  481. cleanups.push(async () => {
  482. await root.close?.();
  483. });
  484. await root.submitPrompt("Create a background writer and wait for it");
  485. const request = await asked.promise;
  486. // 发起者的这一轮已经结束,用户仍未回答:wait 只报告 needs_attention,文件尚未写入。
  487. expect(waited).toHaveLength(1);
  488. expect(waited[0]).toMatchObject({
  489. status: "completed",
  490. operations: [{ status: "needs_attention", attention: { kind: "approval" } }],
  491. });
  492. expect(request).toMatchObject({ toolName: "Write", mode: "build" });
  493. await expect(readFile(target, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  494. answer.resolve("allow");
  495. await backgroundDone.promise;
  496. expect(await readFile(target, "utf8")).toBe("written after the user answered");
  497. });
  498. // 规格 0.5:用户切换主会话或进程退出时 owner 关闭后台根,等待中的询问必须被取消,不能悬挂。
  499. it("cancels a pending background approval when the owner closes", async () => {
  500. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-approval-close-"));
  501. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  502. cleanups.push(async () => {
  503. store.close();
  504. await rm(cwd, { recursive: true, force: true });
  505. });
  506. const target = join(cwd, "cancelled.txt");
  507. const asked = Promise.withResolvers<PermissionBrokerRequest>();
  508. let actorCalls = 0;
  509. let cancelled = false;
  510. const root = await createRegistryBackedTestApp({
  511. standaloneSessionControl: true,
  512. sessionStore: store,
  513. skipUserConfig: true,
  514. env: { ZCODE_STORAGE_DIR: cwd },
  515. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  516. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  517. permissionBroker: {
  518. requestPermission: (request, options) =>
  519. new Promise((_resolve, reject) => {
  520. options?.signal?.addEventListener(
  521. "abort",
  522. () => {
  523. cancelled = true;
  524. reject(new Error("Permission request cancelled"));
  525. },
  526. { once: true },
  527. );
  528. asked.resolve(request);
  529. }),
  530. },
  531. modelExecutor: {
  532. generateText: async (request) => {
  533. const background = request.messages.some(
  534. (message) =>
  535. message.role === "user" &&
  536. JSON.stringify(message.content).includes("E2E_CANCEL_WRITE"),
  537. );
  538. if (background)
  539. return {
  540. text: "",
  541. finishReason: "tool-calls",
  542. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  543. toolCalls: [
  544. { id: "cancel-write", name: "Write", input: { file_path: target, content: "no" } },
  545. ],
  546. };
  547. if (actorCalls++ === 0)
  548. return {
  549. text: "",
  550. finishReason: "tool-calls",
  551. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  552. toolCalls: [
  553. {
  554. id: "create-cancel",
  555. name: "CreateSession",
  556. input: { prompt: "E2E_CANCEL_WRITE" },
  557. },
  558. ],
  559. };
  560. return {
  561. text: "created",
  562. finishReason: "stop",
  563. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  564. };
  565. },
  566. },
  567. });
  568. cleanups.push(async () => {
  569. await root.close?.();
  570. });
  571. await root.submitPrompt("Create a background writer");
  572. const request = await asked.promise;
  573. await root.close?.();
  574. expect(cancelled).toBe(true);
  575. expect((await store.getSession(request.sessionId))?.lastOutcome).toBe("interrupted");
  576. await expect(readFile(target, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  577. });
  578. it("closing a rejected background root does not dispose the actor model adapter", async () => {
  579. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-close-isolation-"));
  580. cleanups.push(async () => rm(cwd, { recursive: true, force: true }));
  581. let calls = 0;
  582. const root = await createRegistryBackedTestApp({
  583. standaloneSessionControl: true,
  584. skipUserConfig: true,
  585. env: { ZCODE_STORAGE_DIR: cwd },
  586. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  587. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  588. modelExecutor: {
  589. generateText: async () => {
  590. if (calls++ === 0)
  591. return {
  592. text: "",
  593. finishReason: "tool-calls",
  594. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  595. toolCalls: [
  596. {
  597. id: "invalid-target-model",
  598. name: "CreateSession",
  599. input: {
  600. prompt: "unstarted",
  601. model: "unavailable/model",
  602. },
  603. },
  604. ],
  605. };
  606. return {
  607. text: "actor still running",
  608. finishReason: "stop",
  609. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  610. };
  611. },
  612. },
  613. });
  614. cleanups.push(async () => {
  615. await root.close?.();
  616. });
  617. expect((await root.submitPrompt("Try an unavailable target model")).response).toBe(
  618. "actor still running",
  619. );
  620. expect((await root.submitPrompt("Continue after target close")).response).toBe(
  621. "actor still running",
  622. );
  623. expect(calls).toBe(3);
  624. });
  625. it("leaves an ordinary embedded runtime without either surface", async () => {
  626. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-embedded-"));
  627. cleanups.push(async () => rm(cwd, { recursive: true, force: true }));
  628. const root = await createRegistryBackedTestApp({
  629. skipUserConfig: true,
  630. env: { ZCODE_STORAGE_DIR: cwd },
  631. runtimeConfig: { workingDirectory: cwd },
  632. modelExecutor: {
  633. generateText: async () => ({
  634. text: "done",
  635. finishReason: "stop",
  636. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  637. }),
  638. },
  639. });
  640. cleanups.push(async () => {
  641. await root.close?.();
  642. });
  643. const registered = root.runtime.getToolRegistry().list();
  644. expect([...CLI_TOOLS, ...APP_ONLY_TOOLS].some((name) => registered.includes(name))).toBe(false);
  645. });
  646. });