runtime.test.ts 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. import {
  2. type CreateLocalRuntimeHostOptions,
  3. type CreatedLocalRuntimeHost,
  4. } from "@mavis/local-runtime";
  5. import { DeferredRuntimeConversation } from "@mavis/conversation-contract";
  6. import type { ThreadGoalState, ThreadGoalStore } from "@mavis/goal";
  7. import type { AgentReferenceResolver } from "@mavis/shared";
  8. import { beforeEach, describe, expect, it, vi } from "vitest";
  9. import {
  10. cleanupFailedV1Startup,
  11. createDeferredAgentRuntimeTelemetry,
  12. createV1RuntimeCompatibility,
  13. withAgentStorageLock,
  14. } from "../../../../src/compat/v1/runtime.js";
  15. type ThreadGoalIntegration = CreatedLocalRuntimeHost["apiHost"]["threadGoal"];
  16. const mocked = vi.hoisted(() => ({
  17. adapter: { marker: "adapter" },
  18. agentHost: { marker: "agent-host-capabilities" },
  19. attachmentRegistration: { marker: "attachment-registration" },
  20. channel: { marker: "channel-capabilities" },
  21. bindCalls: [] as unknown[],
  22. cleanupBindCalls: [] as unknown[],
  23. deleteAgentCronTasks: vi.fn(async () => undefined),
  24. sessionCompatibility: { marker: "session-v2" },
  25. sessionCompatibilityHosts: [] as unknown[],
  26. agentResolver: {
  27. marker: "agent-resolver",
  28. } as unknown as AgentReferenceResolver,
  29. closeAgentDb: vi.fn(),
  30. inspectCollision: vi.fn(),
  31. applyCollision: vi.fn(),
  32. }));
  33. vi.mock("@mavis/local-runtime", async () => {
  34. const actual = await vi.importActual<Record<string, unknown>>(
  35. "@mavis/local-runtime",
  36. );
  37. return {
  38. ...actual,
  39. closeAgentDb: mocked.closeAgentDb,
  40. withAgentNameConflictMigrationLock: async (
  41. _dataDir: string,
  42. operation: (scope: {
  43. inspectCollision: () => unknown;
  44. applyCollision: (nowMs?: () => number) => unknown;
  45. }) => unknown,
  46. ) =>
  47. operation({
  48. inspectCollision: mocked.inspectCollision,
  49. applyCollision: mocked.applyCollision,
  50. }),
  51. };
  52. });
  53. vi.mock("../../../../src/compat/v1/cron.js", () => ({
  54. createV1MavisCronAdapterBridge: () => ({
  55. adapter: mocked.adapter,
  56. bindHandleRequest: (handleRequest: unknown) =>
  57. mocked.bindCalls.push(handleRequest),
  58. }),
  59. createV1CronAgentCleanupBridge: () => ({
  60. deleteAgentCronTasks: mocked.deleteAgentCronTasks,
  61. bind: (service: unknown) => mocked.cleanupBindCalls.push(service),
  62. }),
  63. }));
  64. vi.mock("../../../../src/compat/v1/agent-host.js", () => ({
  65. createV1AttachmentRegistration: () => mocked.attachmentRegistration,
  66. createV1AgentHostProductCapabilities: () => mocked.agentHost,
  67. createV1ChannelProductCapabilities: () => mocked.channel,
  68. }));
  69. vi.mock("../../../../src/compat/v1/session.js", () => ({
  70. createV1SessionCompatibility: (host: unknown) => {
  71. mocked.sessionCompatibilityHosts.push(host);
  72. return mocked.sessionCompatibility;
  73. },
  74. }));
  75. function resetRuntimeCompatibilityMocks(): void {
  76. mocked.bindCalls.length = 0;
  77. mocked.cleanupBindCalls.length = 0;
  78. mocked.deleteAgentCronTasks.mockClear();
  79. mocked.sessionCompatibilityHosts.length = 0;
  80. }
  81. describe("v1 runtime compatibility", () => {
  82. beforeEach(() => {
  83. resetRuntimeCompatibilityMocks();
  84. mocked.closeAgentDb.mockReset();
  85. mocked.inspectCollision.mockReset();
  86. mocked.applyCollision.mockReset();
  87. });
  88. it.each([true, false])(
  89. "passes resolved prompt autoUpdate=%s into service compatibility",
  90. (autoUpdate) => {
  91. const services = createCompatibility().createServiceCompatibility(
  92. createdHost({ configGetter: () => ({ promptConfig: { autoUpdate } }) }),
  93. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  94. );
  95. expect(services.promptConfig).toEqual({ autoUpdate });
  96. },
  97. );
  98. it("revokes an escaped storage callback without closing a later cached connection", async () => {
  99. const laterCachedConnection = { closed: false };
  100. mocked.closeAgentDb.mockImplementation(() => {
  101. laterCachedConnection.closed = true;
  102. });
  103. mocked.applyCollision.mockImplementation(() => {
  104. throw new Error("underlying scope should not be reached after revoke");
  105. });
  106. let escaped: (() => unknown) | undefined;
  107. await withAgentStorageLock("/tmp/runtime", async (scope) => {
  108. escaped = scope.applyLegacyAgentStorage;
  109. });
  110. const escapedCallback = escaped;
  111. if (!escapedCallback) throw new Error("storage callback was not captured");
  112. expect(() => escapedCallback()).toThrow(
  113. "Agent storage lock scope is no longer active",
  114. );
  115. expect(mocked.applyCollision).not.toHaveBeenCalled();
  116. expect(mocked.closeAgentDb).not.toHaveBeenCalled();
  117. expect(laterCachedConnection.closed).toBe(false);
  118. });
  119. it("exposes the scan/apply seam and closes the cached Agent DB after apply", async () => {
  120. const inspection = {
  121. status: "skipped" as const,
  122. sourceKind: "legacy-agent-sqlite" as const,
  123. targetKind: "legacy-runtime-references" as const,
  124. sourceRowCount: 0,
  125. conflictCount: 0,
  126. mappings: [],
  127. referenceCounts: {
  128. primaryDatabase: 0,
  129. runtimeDatabase: 0,
  130. yamlFiles: 0,
  131. planFiles: 0,
  132. legacyUnclassified: 0,
  133. },
  134. skipCode: "source_missing" as const,
  135. };
  136. mocked.inspectCollision.mockReturnValue(inspection);
  137. mocked.applyCollision.mockReturnValue({
  138. status: "completed",
  139. mappings: [],
  140. });
  141. await withAgentStorageLock("/tmp/runtime", async (scope) => {
  142. expect(scope.inspectLegacyAgentStorage()).toBe(inspection);
  143. expect(scope.applyLegacyAgentStorage()).toEqual({
  144. status: "completed",
  145. mappings: [],
  146. });
  147. expect(scope).not.toHaveProperty("reportCutover");
  148. });
  149. expect(mocked.inspectCollision).toHaveBeenCalledOnce();
  150. expect(mocked.applyCollision).toHaveBeenCalledOnce();
  151. expect(mocked.closeAgentDb).toHaveBeenCalledWith("/tmp/runtime");
  152. });
  153. it("closes the cached Agent DB when apply throws", async () => {
  154. mocked.applyCollision.mockImplementation(() => {
  155. throw new Error("rewrite failed");
  156. });
  157. await expect(
  158. withAgentStorageLock("/tmp/runtime", async (scope) =>
  159. scope.applyLegacyAgentStorage(),
  160. ),
  161. ).rejects.toThrow("rewrite failed");
  162. expect(mocked.applyCollision).toHaveBeenCalledOnce();
  163. expect(mocked.closeAgentDb).toHaveBeenCalledWith("/tmp/runtime");
  164. });
  165. it("keeps the apply error primary when cached Agent DB cleanup also fails", async () => {
  166. const applyError = Object.assign(new Error("rewrite failed"), {
  167. failureStep: "primary_rewrite",
  168. migrationId: "agent-name-conflicts-17",
  169. });
  170. const closeError = new Error("close failed");
  171. mocked.applyCollision.mockImplementation(() => {
  172. throw applyError;
  173. });
  174. mocked.closeAgentDb.mockImplementation(() => {
  175. throw closeError;
  176. });
  177. let error: unknown;
  178. try {
  179. await withAgentStorageLock("/tmp/runtime", async (scope) =>
  180. scope.applyLegacyAgentStorage(),
  181. );
  182. } catch (caught) {
  183. error = caught;
  184. }
  185. expect(error).toMatchObject({
  186. failureStep: "primary_rewrite",
  187. migrationId: "agent-name-conflicts-17",
  188. });
  189. expect(error).toBeInstanceOf(AggregateError);
  190. const aggregate = error as AggregateError & { cause?: unknown };
  191. expect(aggregate.cause).toBe(applyError);
  192. expect(aggregate.errors).toEqual([applyError, closeError]);
  193. });
  194. it("retains the completed migration correlation id when cached Agent DB cleanup fails", async () => {
  195. const closeError = new Error("close failed");
  196. mocked.applyCollision.mockReturnValue({
  197. status: "completed",
  198. mappings: [],
  199. migrationId: "agent-name-conflicts-18",
  200. });
  201. mocked.closeAgentDb.mockImplementation(() => {
  202. throw closeError;
  203. });
  204. let error: unknown;
  205. try {
  206. await withAgentStorageLock("/tmp/runtime", async (scope) =>
  207. scope.applyLegacyAgentStorage(),
  208. );
  209. } catch (caught) {
  210. error = caught;
  211. }
  212. expect(error).toMatchObject({ migrationId: "agent-name-conflicts-18" });
  213. expect(error).toBeInstanceOf(AggregateError);
  214. expect((error as AggregateError & { cause?: unknown }).cause).toBe(
  215. closeError,
  216. );
  217. });
  218. });
  219. describe("v1 Agent reference compatibility", () => {
  220. function resolver(
  221. overrides: Partial<AgentReferenceResolver> = {},
  222. ): AgentReferenceResolver {
  223. return {
  224. resolveAgentReadScope: vi.fn(async (requestedName: string) => ({
  225. requestedName,
  226. canonicalName: "coder",
  227. primaryName: "mavis",
  228. compatibleNames: ["coder"],
  229. exact: true,
  230. source: "explicit_agent" as const,
  231. exactOwnerName: "coder",
  232. })),
  233. resolveAgentWriteTarget: vi.fn(async () => "coder"),
  234. requireExactAgentKey: vi.fn(async () => "coder"),
  235. resolveAgentExecutionTarget: vi.fn(async () => "coder"),
  236. ...overrides,
  237. };
  238. }
  239. function resolveDelegatable(
  240. targetResolver: AgentReferenceResolver,
  241. requestRef: string,
  242. ) {
  243. return createCompatibility()
  244. .createServiceCompatibility(
  245. createdHost({ agentResolver: targetResolver }),
  246. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  247. )
  248. .agentReferences.resolveDelegatable(requestRef);
  249. }
  250. it("uses the complete Task resolver chain for a delegatable roster target", async () => {
  251. const targetResolver = resolver();
  252. await expect(
  253. resolveDelegatable(targetResolver, "agent:coder"),
  254. ).resolves.toBe("authorized");
  255. expect(targetResolver.resolveAgentReadScope).toHaveBeenCalledWith(
  256. "agent:coder",
  257. );
  258. expect(targetResolver.resolveAgentWriteTarget).toHaveBeenCalledWith(
  259. "agent:coder",
  260. );
  261. expect(targetResolver.requireExactAgentKey).toHaveBeenCalledWith("coder");
  262. expect(targetResolver.resolveAgentExecutionTarget).toHaveBeenCalledWith(
  263. "coder",
  264. );
  265. });
  266. it("rejects the canonical primary/self target before Task resolution", async () => {
  267. const targetResolver = resolver({
  268. resolveAgentReadScope: vi.fn(async (requestedName: string) => ({
  269. requestedName,
  270. canonicalName: "mavis",
  271. primaryName: "mavis",
  272. compatibleNames: ["mavis", "main"],
  273. exact: true,
  274. source: "explicit_agent" as const,
  275. exactOwnerName: "mavis",
  276. })),
  277. });
  278. await expect(
  279. resolveDelegatable(targetResolver, "agent:mavis"),
  280. ).resolves.toBe("unauthorized");
  281. expect(targetResolver.resolveAgentWriteTarget).not.toHaveBeenCalled();
  282. expect(targetResolver.requireExactAgentKey).not.toHaveBeenCalled();
  283. expect(targetResolver.resolveAgentExecutionTarget).not.toHaveBeenCalled();
  284. });
  285. it("fails closed when the trusted roster resolver cannot resolve a target", async () => {
  286. const targetResolver = resolver({
  287. resolveAgentReadScope: vi.fn(async () => {
  288. throw Object.assign(new Error("missing"), { code: "AGENT_NOT_FOUND" });
  289. }),
  290. });
  291. await expect(
  292. resolveDelegatable(targetResolver, "agent:missing"),
  293. ).resolves.toBe("unknown");
  294. expect(targetResolver.resolveAgentWriteTarget).not.toHaveBeenCalled();
  295. });
  296. });
  297. describe("v1 runtime compatibility Task recovery", () => {
  298. beforeEach(() => {
  299. resetRuntimeCompatibilityMocks();
  300. mocked.closeAgentDb.mockReset();
  301. mocked.inspectCollision.mockReset();
  302. mocked.applyCollision.mockReset();
  303. });
  304. it("binds task ownership and forwards exact recovered Turn evidence to the Task service", async () => {
  305. const bindRuntimeOwner = vi.fn();
  306. const reconcileStartupLostTasks = vi.fn(async () => []);
  307. const compatibility = createCompatibility();
  308. const host = createdHost({
  309. backgroundTaskService: {
  310. bindRuntimeOwner,
  311. reconcileStartupLostTasks,
  312. hasPendingStartupRecovery: () => true,
  313. pollStartupLostTasks: async () => false,
  314. },
  315. });
  316. const service = compatibility.createServiceCompatibility(host, {
  317. dataDir: "/tmp/runtime",
  318. runtimeOwnerKind: "tui",
  319. });
  320. const owner = {
  321. ownerId: "background-task:current",
  322. isOwnerAlive: () => true,
  323. };
  324. service.backgroundTasks.bindRuntimeOwner(owner);
  325. await expect(
  326. service.backgroundTasks.recover(["turn-recovered"]),
  327. ).resolves.toBe(true);
  328. await expect(service.backgroundTasks.pollRecovery()).resolves.toBe(false);
  329. expect(bindRuntimeOwner).toHaveBeenCalledWith(owner);
  330. expect(reconcileStartupLostTasks).toHaveBeenCalledWith({
  331. recoveredTurnIds: ["turn-recovered"],
  332. });
  333. });
  334. });
  335. describe("v1 runtime compatibility host composition", () => {
  336. beforeEach(() => {
  337. resetRuntimeCompatibilityMocks();
  338. mocked.closeAgentDb.mockReset();
  339. mocked.inspectCollision.mockReset();
  340. mocked.applyCollision.mockReset();
  341. });
  342. it.each([
  343. { kind: "cli", embedded: true, enabled: false },
  344. { kind: "tui", embedded: true, enabled: false },
  345. { kind: "cli", embedded: false, enabled: false },
  346. { kind: "tui", embedded: false, enabled: false },
  347. { kind: "electron", embedded: true, enabled: false },
  348. { kind: "diagnostic", embedded: true, enabled: false },
  349. ] as const)(
  350. "disables built-in Matrix while retaining configured MCP for $kind / embedded=$embedded",
  351. ({ kind, embedded, enabled }) => {
  352. const compatibility = createCompatibility();
  353. const host = createdHost({
  354. configGetter: () => ({ beta: { mcodeTools: true } }),
  355. });
  356. const services = compatibility.createServiceCompatibility(host, {
  357. dataDir: "/tmp/runtime",
  358. runtimeOwnerKind: kind,
  359. capabilities: { cliEmbedded: embedded },
  360. enableLiveMcp: true,
  361. });
  362. expect(services.mcp).toMatchObject({
  363. enableLiveMcp: true,
  364. builtinMatrix: enabled,
  365. matrixWebSearchOnly: false,
  366. });
  367. },
  368. );
  369. it("caps the background task listing at 100 results", async () => {
  370. const tasks = Array.from({ length: 101 }, (_, index) => ({
  371. taskId: `bg-${index}`,
  372. kind: "bash" as const,
  373. status: "running" as const,
  374. ownerSessionId: "session-1",
  375. createdAt: 100,
  376. updatedAt: 200,
  377. }));
  378. const services = createCompatibility().createServiceCompatibility(
  379. createdHost({
  380. backgroundTaskService: {
  381. list: async ({ limit }: { limit: number }) => ({
  382. items: tasks.slice(0, limit),
  383. }),
  384. },
  385. }),
  386. { dataDir: "/tmp/runtime", runtimeOwnerKind: "cli" },
  387. );
  388. await expect(
  389. services.peripherals.backgroundTasks.list({
  390. ownerSessionId: "session-1",
  391. limit: 200,
  392. }),
  393. ).resolves.toEqual(tasks.slice(0, 100));
  394. });
  395. it("routes Agent cleanup through the bound V2 Cron owner", async () => {
  396. const compatibility = createCompatibility();
  397. const configured = compatibility.configureHostOptions(
  398. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  399. mocked.agentResolver,
  400. preparedPorts(),
  401. );
  402. const services = compatibility.createServiceCompatibility(createdHost({}), {
  403. dataDir: "/tmp/runtime",
  404. } as CreateLocalRuntimeHostOptions);
  405. const cron = { deleteDefinitionsByAgent: vi.fn() };
  406. services.cron.bindAgentCleanup(cron);
  407. await configured.deleteAgentCronTasks?.("coder");
  408. expect(mocked.cleanupBindCalls).toEqual([cron]);
  409. expect(mocked.deleteAgentCronTasks).toHaveBeenCalledWith("coder");
  410. });
  411. });
  412. describe("v1 runtime compatibility seams", () => {
  413. beforeEach(() => {
  414. resetRuntimeCompatibilityMocks();
  415. mocked.closeAgentDb.mockReset();
  416. mocked.inspectCollision.mockReset();
  417. mocked.applyCollision.mockReset();
  418. });
  419. it("shares one deferred conversation bridge across host options and service binding", async () => {
  420. const compatibility = createCompatibility();
  421. const configured = compatibility.configureHostOptions(
  422. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  423. mocked.agentResolver,
  424. preparedPorts(),
  425. );
  426. const serviceCompatibility = compatibility.createServiceCompatibility(
  427. createdHost({
  428. subscribeGlobalEvents: vi.fn(() => () => undefined),
  429. }),
  430. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  431. );
  432. const pending =
  433. configured.runtimeConversation?.query.getSession("session-1");
  434. const provider = {
  435. query: {
  436. getSession: vi.fn(async () => undefined),
  437. listSessions: vi.fn(async () => []),
  438. listMessages: vi.fn(async () => ({ messages: [], hasMore: false })),
  439. },
  440. lifecycle: {},
  441. ingress: {},
  442. maintenance: {},
  443. } as never;
  444. await serviceCompatibility.conversation.bind(provider);
  445. await expect(pending).resolves.toBeUndefined();
  446. compatibility.shutdownConversation(new Error("runtime close"));
  447. await expect(
  448. configured.runtimeConversation?.query.listSessions(),
  449. ).rejects.toMatchObject({
  450. code: "RUNTIME_CONVERSATION_SHUTDOWN",
  451. });
  452. });
  453. it("reconciles persisted Goal kickoffs before exposing the conversation provider", async () => {
  454. const compatibility = createCompatibility();
  455. const configured = compatibility.configureHostOptions(
  456. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  457. mocked.agentResolver,
  458. preparedPorts(),
  459. );
  460. const recovery = deferred();
  461. const recoverThreadGoalKickoffs = vi.fn(async () => recovery.promise);
  462. const serviceCompatibility = compatibility.createServiceCompatibility(
  463. createdHost({
  464. subscribeGlobalEvents: vi.fn(() => () => undefined),
  465. recoverThreadGoalKickoffs,
  466. }),
  467. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  468. );
  469. const getSession = vi.fn(async () => undefined);
  470. const provider = {
  471. query: {
  472. getSession,
  473. listSessions: vi.fn(async () => []),
  474. listMessages: vi.fn(async () => ({ messages: [], hasMore: false })),
  475. },
  476. lifecycle: {},
  477. ingress: {},
  478. maintenance: {},
  479. } as never;
  480. const pendingQuery =
  481. configured.runtimeConversation?.query.getSession("session-1");
  482. const binding = serviceCompatibility.conversation.bind(provider);
  483. await Promise.resolve();
  484. expect(recoverThreadGoalKickoffs).toHaveBeenCalledWith(provider);
  485. expect(getSession).not.toHaveBeenCalled();
  486. recovery.resolve();
  487. await binding;
  488. await expect(pendingQuery).resolves.toBeUndefined();
  489. expect(getSession).toHaveBeenCalledWith("session-1");
  490. });
  491. it("does not expose model catalog or provider ownership through v1 compatibility", () => {
  492. const services = createCompatibility().createServiceCompatibility(
  493. createdHost({}),
  494. {
  495. dataDir: "/tmp/runtime",
  496. } as CreateLocalRuntimeHostOptions,
  497. );
  498. expect(services.peripherals).not.toHaveProperty("models");
  499. expect(services.peripherals).not.toHaveProperty("modelProviders");
  500. });
  501. });
  502. describe("v1 runtime compatibility adapters and cleanup", () => {
  503. beforeEach(resetRuntimeCompatibilityMocks);
  504. it("injects a write-only global event publisher and detaches it without subscribing to v1", () => {
  505. const compatibility = createCompatibility();
  506. const configured = compatibility.configureHostOptions(
  507. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  508. mocked.agentResolver,
  509. preparedPorts(),
  510. );
  511. const apiHost = { subscribeGlobalEvents: vi.fn(() => () => undefined) };
  512. const host = createdHost(apiHost);
  513. const publish = vi.fn();
  514. const event = {
  515. type: "session.deleted" as const,
  516. payload: { sessionId: "session-1" },
  517. };
  518. const events = compatibility.createServiceCompatibility(host, {
  519. dataDir: "/tmp/runtime",
  520. } as CreateLocalRuntimeHostOptions).events;
  521. const unbind = events.bindPublisher(publish);
  522. configured.globalEventPublisher?.(event);
  523. unbind();
  524. configured.globalEventPublisher?.({
  525. type: "session.deleted",
  526. payload: { sessionId: "late-session" },
  527. });
  528. expect(apiHost.subscribeGlobalEvents).not.toHaveBeenCalled();
  529. expect(publish).toHaveBeenCalledOnce();
  530. expect(publish).toHaveBeenCalledWith(event);
  531. });
  532. });
  533. describe("v1 safety compatibility", () => {
  534. it("keeps the concrete content-safety transport in the v1 compatibility seam", () => {
  535. const compatibility = createCompatibility();
  536. const contentSafetyChecker = vi.fn(async () => ({ pass: true as const }));
  537. const services = compatibility.createServiceCompatibility(
  538. createdHost({ contentSafetyChecker }),
  539. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  540. );
  541. expect(services.safety.review).toBe(contentSafetyChecker);
  542. });
  543. });
  544. describe("v1 runtime cleanup", () => {
  545. it("best-effort cleans every acquired v1 resource in dependency order", async () => {
  546. const events: string[] = [];
  547. const warnings: string[] = [];
  548. const v1 = {
  549. apiHost: {
  550. cronRuntime: { stop: () => events.push("cron") },
  551. shutdownChannelSubsystem: () => {
  552. events.push("channels");
  553. throw new Error("channel cleanup failed");
  554. },
  555. },
  556. metricsClient: { close: () => events.push("metrics") },
  557. } as unknown as CreatedLocalRuntimeHost;
  558. await cleanupFailedV1Startup(
  559. v1,
  560. async () => {
  561. events.push("close");
  562. },
  563. (step) => warnings.push(step),
  564. );
  565. expect(events).toEqual(["cron", "channels", "close", "metrics"]);
  566. expect(warnings).toEqual(["stop_channels"]);
  567. });
  568. it("continues cleanup when the warning reporter throws", async () => {
  569. const events: string[] = [];
  570. const v1 = {
  571. apiHost: {
  572. cronRuntime: {
  573. stop: () => {
  574. events.push("cron");
  575. throw new Error("cron cleanup failed");
  576. },
  577. },
  578. shutdownChannelSubsystem: () => events.push("channels"),
  579. },
  580. metricsClient: { close: () => events.push("metrics") },
  581. } as unknown as CreatedLocalRuntimeHost;
  582. await cleanupFailedV1Startup(
  583. v1,
  584. async () => {
  585. events.push("close");
  586. },
  587. () => {
  588. throw new Error("warning reporter failed");
  589. },
  590. );
  591. expect(events).toEqual(["cron", "channels", "close", "metrics"]);
  592. });
  593. });
  594. describe("v1 Agent telemetry compatibility", () => {
  595. it("bridges Agent facts to v1 telemetry and remains fail-open", () => {
  596. const counter = vi.fn();
  597. const gauge = vi.fn();
  598. const histogram = vi.fn();
  599. const emitBusEvent = vi.fn();
  600. const telemetry = createDeferredAgentRuntimeTelemetry();
  601. telemetry.bind({
  602. metricsClient: { counter, gauge, histogram },
  603. emitBusEvent,
  604. });
  605. telemetry.facts.onNameCompatResolve?.({
  606. intent: "read",
  607. canonicalClass: "worker",
  608. source: "canonical_name",
  609. success: true,
  610. memberCountBucket: "2",
  611. });
  612. telemetry.facts.onAgentRoleObservation?.({
  613. status: "unsupported",
  614. source: "sqlite_decode",
  615. role: "worker",
  616. });
  617. expect(counter).toHaveBeenCalledWith("agent_name_compat_resolve_total", 1, {
  618. intent: "read",
  619. canonical_class: "worker",
  620. source: "canonical_name",
  621. success: "true",
  622. member_count_bucket: "2",
  623. });
  624. expect(counter).toHaveBeenCalledWith("agent_role_observation_total", 1, {
  625. status: "unsupported",
  626. source: "sqlite_decode",
  627. role_class: "worker",
  628. });
  629. expect(emitBusEvent).toHaveBeenCalledWith("agent_name_compat.resolve", {
  630. intent: "read",
  631. canonical_class: "worker",
  632. source: "canonical_name",
  633. success: true,
  634. member_count_bucket: "2",
  635. });
  636. const failingTelemetry = createDeferredAgentRuntimeTelemetry();
  637. failingTelemetry.bind({
  638. metricsClient: {
  639. counter: () => {
  640. throw new Error("metrics unavailable");
  641. },
  642. gauge: () => {
  643. throw new Error("metrics unavailable");
  644. },
  645. histogram: () => {
  646. throw new Error("metrics unavailable");
  647. },
  648. },
  649. emitBusEvent: () => {
  650. throw new Error("event bus unavailable");
  651. },
  652. });
  653. expect(() => {
  654. failingTelemetry.facts.onNameCompatResolve?.({
  655. intent: "write",
  656. canonicalClass: "other",
  657. source: "explicit_agent",
  658. success: false,
  659. });
  660. failingTelemetry.facts.onAgentRoleObservation?.({
  661. status: "missing",
  662. source: "builtin_seed",
  663. role: undefined,
  664. });
  665. failingTelemetry.close();
  666. failingTelemetry.facts.onNameCompatResolve?.({
  667. intent: "read",
  668. canonicalClass: "other",
  669. source: "stable_name",
  670. success: true,
  671. });
  672. }).not.toThrow();
  673. });
  674. });
  675. const goal: ThreadGoalState = {
  676. goalId: "goal-1",
  677. sessionId: "session-1",
  678. objective: "Ship Goal support",
  679. status: "active",
  680. createdAt: 10,
  681. updatedAt: 20,
  682. tokensUsed: 4,
  683. turnsUsed: 1,
  684. timeUsedSeconds: 2,
  685. tokenBudget: null,
  686. replyFingerprint: "reply-fingerprint",
  687. noProgressStreak: 0,
  688. noToolStreak: 0,
  689. lastVerification: {
  690. v: 1,
  691. backend: "evaluator",
  692. verdict: "not_met",
  693. reason: "Acceptance evidence is still missing.",
  694. missing: ["focused test evidence"],
  695. notMetStreak: 1,
  696. turnId: "turn-1",
  697. objectiveDigest: "objective-digest",
  698. at: 20,
  699. },
  700. statusReason: null,
  701. kickoffAttachments: [],
  702. kickoffState: "consumed",
  703. executionWait: null,
  704. };
  705. function createThreadGoalFixture() {
  706. const isReadOnlyLegacySession = vi.fn(async () => false);
  707. const store = {
  708. create: vi.fn(
  709. async (_input: Parameters<ThreadGoalStore["create"]>[0]) => goal,
  710. ),
  711. getBySession: vi.fn(async () => goal),
  712. patch: vi.fn(async (_goalId: string, patch: Partial<ThreadGoalState>) => ({
  713. ...goal,
  714. ...patch,
  715. })),
  716. delete: vi.fn(async () => undefined),
  717. };
  718. const integration = {
  719. isEnabled: vi.fn(() => true),
  720. store,
  721. getGoalForResponse: vi.fn<ThreadGoalIntegration["getGoalForResponse"]>(
  722. async () => goal,
  723. ),
  724. createGoal: vi.fn(
  725. async (
  726. input: Parameters<ThreadGoalStore["create"]>[0],
  727. _options?: { readonly requireKickoffAdmission?: boolean },
  728. ) => store.create(input),
  729. ),
  730. patchGoal: vi.fn<ThreadGoalIntegration["patchGoal"]>(
  731. async (_sessionId: string, patch: Partial<ThreadGoalState>) => ({
  732. ...goal,
  733. ...patch,
  734. }),
  735. ),
  736. deleteGoal: vi.fn(async (_sessionId: string) => true),
  737. handleChanged: vi.fn(),
  738. };
  739. const application = createCompatibility().createServiceCompatibility(
  740. createdHost(
  741. {
  742. threadGoal: integration,
  743. isReadOnlyLegacySession,
  744. skillService: { listRuntimeSkills: async () => ({ skills: [] }) },
  745. skillHubStore: {
  746. getInstalledIdentities: async () => ({
  747. names: new Set<string>(),
  748. sourceUrls: new Set<string>(),
  749. }),
  750. },
  751. },
  752. {
  753. metricsClient: {},
  754. mcpService: { listServers: async () => [] },
  755. },
  756. ),
  757. { dataDir: "/tmp/runtime" } as CreateLocalRuntimeHostOptions,
  758. ).peripherals.goals;
  759. return {
  760. application,
  761. integration,
  762. isReadOnlyLegacySession,
  763. store,
  764. };
  765. }
  766. describe("createThreadGoalApplication", () => {
  767. it("creates and reads the Runtime-owned Goal without a transport hop", async () => {
  768. const fixture = createThreadGoalFixture();
  769. await expect(
  770. fixture.application.create({
  771. sessionId: " session-1 ",
  772. objective: " Ship Goal support ",
  773. tokenBudget: 50_000,
  774. kickoffAttachments: [
  775. {
  776. type: "file",
  777. filePath: "/repo/spec.md",
  778. fileName: "spec.md",
  779. mimeType: "text/markdown",
  780. },
  781. ],
  782. }),
  783. ).resolves.toMatchObject({
  784. goalId: "goal-1",
  785. status: "active",
  786. turnsUsed: 1,
  787. statusReason: null,
  788. lastVerification: {
  789. backend: "evaluator",
  790. verdict: "not_met",
  791. missing: ["focused test evidence"],
  792. },
  793. });
  794. expect(fixture.store.create).toHaveBeenCalledWith({
  795. sessionId: "session-1",
  796. objective: "Ship Goal support",
  797. tokenBudget: 50_000,
  798. kickoffAttachments: [expect.objectContaining({ fileName: "spec.md" })],
  799. });
  800. expect(fixture.integration.createGoal).toHaveBeenCalledWith(
  801. {
  802. sessionId: "session-1",
  803. objective: "Ship Goal support",
  804. tokenBudget: 50_000,
  805. kickoffAttachments: [expect.objectContaining({ fileName: "spec.md" })],
  806. },
  807. { requireKickoffAdmission: true },
  808. );
  809. await expect(fixture.application.get("session-1")).resolves.toMatchObject({
  810. objective: "Ship Goal support",
  811. hasKickoffAttachments: false,
  812. });
  813. });
  814. it("omits the verification result until the Runtime has produced one", async () => {
  815. const fixture = createThreadGoalFixture();
  816. fixture.integration.getGoalForResponse
  817. .mockResolvedValueOnce({ ...goal, lastVerification: undefined })
  818. .mockResolvedValueOnce(undefined);
  819. const projected = await fixture.application.get("session-1");
  820. expect(projected).not.toHaveProperty("lastVerification");
  821. await expect(fixture.application.get("session-1")).resolves.toBeUndefined();
  822. });
  823. it("rejects an empty Goal session id before reaching the Runtime integration", async () => {
  824. const fixture = createThreadGoalFixture();
  825. await expect(fixture.application.get(" ")).rejects.toThrow(
  826. "sessionId is required.",
  827. );
  828. expect(fixture.integration.getGoalForResponse).not.toHaveBeenCalled();
  829. });
  830. it("uses Desktop soft-fail kickoff admission for a text-only Goal", async () => {
  831. const fixture = createThreadGoalFixture();
  832. await expect(
  833. fixture.application.create({
  834. sessionId: "session-1",
  835. objective: "Ship without attachments",
  836. }),
  837. ).resolves.toMatchObject({ goalId: "goal-1", status: "active" });
  838. expect(fixture.integration.createGoal).toHaveBeenCalledWith({
  839. sessionId: "session-1",
  840. objective: "Ship without attachments",
  841. });
  842. });
  843. it("uses live projection for resume and publishes edit and clear changes", async () => {
  844. const fixture = createThreadGoalFixture();
  845. const resumed = { ...goal, status: "active" as const, timeUsedSeconds: 12 };
  846. fixture.integration.patchGoal.mockResolvedValueOnce(resumed);
  847. await expect(
  848. fixture.application.patch("session-1", { status: "active" }),
  849. ).resolves.toMatchObject({
  850. status: "active",
  851. timeUsedSeconds: 12,
  852. });
  853. expect(fixture.integration.patchGoal).toHaveBeenCalledWith("session-1", {
  854. status: "active",
  855. });
  856. await fixture.application.patch("session-1", {
  857. objective: "New objective",
  858. tokenBudget: null,
  859. });
  860. expect(fixture.integration.patchGoal).toHaveBeenLastCalledWith(
  861. "session-1",
  862. {
  863. objective: "New objective",
  864. tokenBudget: null,
  865. },
  866. );
  867. await fixture.application.patch("session-1", { tokenBudget: 75_000 });
  868. expect(fixture.integration.patchGoal).toHaveBeenLastCalledWith(
  869. "session-1",
  870. {
  871. tokenBudget: 75_000,
  872. },
  873. );
  874. await expect(fixture.application.clear("session-1")).resolves.toBe(true);
  875. expect(fixture.integration.deleteGoal).toHaveBeenCalledWith("session-1");
  876. });
  877. it("rejects a Goal patch after all mutable fields are omitted", async () => {
  878. const fixture = createThreadGoalFixture();
  879. await expect(fixture.application.patch("session-1", {})).rejects.toThrow(
  880. "Goal patch must include status, objective, or tokenBudget.",
  881. );
  882. expect(fixture.integration.patchGoal).not.toHaveBeenCalled();
  883. });
  884. it("preserves objective validation and the missing-Goal patch contract", async () => {
  885. const fixture = createThreadGoalFixture();
  886. await expect(
  887. fixture.application.patch("session-1", { objective: " " }),
  888. ).rejects.toThrow("goal objective must not be empty");
  889. fixture.integration.patchGoal.mockResolvedValueOnce(undefined);
  890. await expect(
  891. fixture.application.patch("session-1", { objective: "still shipping" }),
  892. ).rejects.toMatchObject({
  893. status: 404,
  894. code: "GOAL_NOT_FOUND",
  895. message: "Goal not found for session: session-1",
  896. });
  897. });
  898. it("reports the Desktop GOAL_NOT_FOUND contract when clear loses the Goal race", async () => {
  899. const fixture = createThreadGoalFixture();
  900. fixture.integration.deleteGoal.mockResolvedValue(false);
  901. await expect(fixture.application.clear("session-1")).rejects.toMatchObject({
  902. status: 404,
  903. code: "GOAL_NOT_FOUND",
  904. message: "Goal not found for session: session-1",
  905. });
  906. });
  907. it("rejects every Goal mutation for a read-only legacy session", async () => {
  908. const fixture = createThreadGoalFixture();
  909. fixture.isReadOnlyLegacySession.mockResolvedValue(true);
  910. await expect(
  911. fixture.application.create({
  912. sessionId: "session-1",
  913. objective: "Do not mutate legacy state",
  914. }),
  915. ).rejects.toThrow("read-only");
  916. await expect(
  917. fixture.application.patch("session-1", { status: "paused" }),
  918. ).rejects.toThrow("read-only");
  919. await expect(fixture.application.clear("session-1")).rejects.toThrow(
  920. "read-only",
  921. );
  922. expect(fixture.isReadOnlyLegacySession).toHaveBeenCalledTimes(3);
  923. expect(fixture.integration.createGoal).not.toHaveBeenCalled();
  924. expect(fixture.integration.patchGoal).not.toHaveBeenCalled();
  925. expect(fixture.integration.deleteGoal).not.toHaveBeenCalled();
  926. });
  927. it("fails closed when Thread Goal is disabled", async () => {
  928. const fixture = createThreadGoalFixture();
  929. fixture.integration.isEnabled.mockReturnValue(false);
  930. expect(fixture.application.isEnabled()).toBe(false);
  931. await expect(fixture.application.get("session-1")).rejects.toThrow(
  932. "disabled",
  933. );
  934. expect(fixture.integration.getGoalForResponse).not.toHaveBeenCalled();
  935. });
  936. });
  937. function createCompatibility() {
  938. const compatibility = createV1RuntimeCompatibility(
  939. new DeferredRuntimeConversation(),
  940. {
  941. createQuestionnaireService: () =>
  942. ({ marker: "questionnaire-service" }) as never,
  943. },
  944. );
  945. return {
  946. ...compatibility,
  947. createServiceCompatibility: (
  948. host: CreatedLocalRuntimeHost,
  949. options: CreateLocalRuntimeHostOptions,
  950. ) => compatibility.createServiceCompatibility(host, options),
  951. };
  952. }
  953. function preparedPorts() {
  954. return {
  955. skillEnabledState: {
  956. getDisabledLocationUris: vi.fn(async () => new Set<string>()),
  957. setEnabled: vi.fn(async () => undefined),
  958. forget: vi.fn(async () => undefined),
  959. },
  960. runLegacyImCredentialMigration: vi.fn(async (action: () => Promise<void>) =>
  961. action(),
  962. ),
  963. cliSunsetNotice: {
  964. evaluate: vi.fn(async () => undefined),
  965. },
  966. };
  967. }
  968. function createdHost(
  969. apiHost: object,
  970. host: object = {},
  971. ): CreatedLocalRuntimeHost {
  972. return {
  973. dataDir: "/tmp/runtime",
  974. apiHost: {
  975. configGetter: () => ({ promptConfig: { autoUpdate: false } }),
  976. recoverThreadGoalKickoffs: async () => undefined,
  977. contentSafetyChecker: vi.fn(async () => ({ pass: true })),
  978. bindQuestionnaireOwnedActionHandler: vi.fn(),
  979. questionnaireServiceDeps: () => ({
  980. store: {},
  981. nowMs: Date.now,
  982. primaryAgentName: "mavis",
  983. configGetter: () => ({}),
  984. getSessionById: vi.fn(),
  985. startUserMessageTurn: vi.fn(),
  986. emitBusEvent: vi.fn(),
  987. publishGlobalEvent: vi.fn(),
  988. }),
  989. ...apiHost,
  990. },
  991. ...host,
  992. } as unknown as CreatedLocalRuntimeHost;
  993. }
  994. function deferred() {
  995. let resolvePromise: (() => void) | undefined;
  996. const promise = new Promise<void>((resolve) => {
  997. resolvePromise = resolve;
  998. });
  999. return { promise, resolve: () => resolvePromise?.() };
  1000. }