services.test.ts 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306
  1. import { createRequire } from "node:module";
  2. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  3. import type {
  4. LLMRetryEvent,
  5. RunTurnInput,
  6. } from "@mavis/agent-core/pi-turn-runner";
  7. import { createAgentRuntime, type AgentExtension } from "@mavis/agent-runtime";
  8. import { baseCtx } from "../../agent-runtime/src/testing/fixtures.js";
  9. import type { RuntimeTool } from "@mavis/agent-core/tools";
  10. import { LocalSkillToolDef } from "@mavis/agent-tools/desktop";
  11. import type {
  12. DatabaseLike,
  13. QuestionnaireOwnedActionHandler,
  14. } from "@mavis/local-runtime";
  15. import type {
  16. GlobalEvent,
  17. GlobalEventInput,
  18. } from "@mavis/shared/global-events";
  19. import { createRuntimeSourceReferenceExtension } from "./application/agent/source-reference-extension.js";
  20. import type { V1ServiceCompatibility } from "./compat/v1/runtime.js";
  21. import type { AppDb } from "./infra/db/client.js";
  22. import { readPreferenceValue } from "./infra/db/preference-values.js";
  23. import { migratePluginTestDatabase } from "../test/helpers/plugin-database.js";
  24. import { EventBus } from "./infra/event-bus/index.js";
  25. import type { SchedulerClient } from "./infra/scheduler/index.js";
  26. import type { LocalAgentService } from "./service/agent/index.js";
  27. import { resolveAgentPromptSurface } from "./service/turn-system/agent-host/preparation/agent-prompt-surface.js";
  28. import type { InitializeTurnSystemOptions } from "./service/turn-system/index.js";
  29. import {
  30. requireAgentRuntime,
  31. requireTurnSystem,
  32. } from "./service/turn-system/lifecycle/runtime-initialization-guards.js";
  33. import {
  34. createRuntimeServices as createRuntimeServicesGraph,
  35. type CreateRuntimeServicesOptions,
  36. type RuntimeServices,
  37. } from "./services.js";
  38. type QueueClassifier = NonNullable<
  39. InitializeTurnSystemOptions["classifyQueuedItem"]
  40. >;
  41. type QueueFifoYieldPolicy = NonNullable<
  42. InitializeTurnSystemOptions["shouldYieldFifoPosition"]
  43. >;
  44. type CapturedTurnOptions = {
  45. readonly disposeRuntimeSession?: InitializeTurnSystemOptions["disposeRuntimeSession"];
  46. readonly processStartedAtMs: number;
  47. readonly classifyQueuedItem?: QueueClassifier;
  48. readonly shouldYieldFifoPosition?: QueueFifoYieldPolicy;
  49. readonly resumeSessionDeletion?: NonNullable<
  50. InitializeTurnSystemOptions["resumeSessionDeletion"]
  51. >;
  52. readonly turnSettlement?: InitializeTurnSystemOptions["turnSettlement"];
  53. };
  54. type QueryCollapseStartInput = {
  55. readonly sessionId: string;
  56. readonly queryKey: string;
  57. readonly currentTurnId: string;
  58. };
  59. const queryCollapseMocked = vi.hoisted(() => ({
  60. keyResolverOptions: undefined as Record<string, unknown> | undefined,
  61. deliveryOptions: undefined as Record<string, unknown> | undefined,
  62. keys: {
  63. queryKeyForTurn: vi.fn(
  64. async (_sessionId: string, turnId: string) => `turn:${turnId}`,
  65. ),
  66. queryKeyForContinuation: vi.fn(
  67. async (_sessionId: string, turnId: string) => `turn:${turnId}`,
  68. ),
  69. },
  70. }));
  71. const runtimeOwnerIdentity: CreateRuntimeServicesOptions["runtimeOwnerIdentity"] =
  72. {
  73. instanceId: "runtime-test",
  74. recoveryRetryMs: 10_000,
  75. createOwnerId: (kind) => `${kind}:1:runtime-test.operation`,
  76. ownsOwnerId: (ownerId) => ownerId.includes(":1:runtime-test."),
  77. isOwnerAlive: () => false,
  78. onCompromised: () => () => undefined,
  79. close: async () => undefined,
  80. };
  81. const require = createRequire(import.meta.url);
  82. const Database = require("better-sqlite3") as new (
  83. filename: string,
  84. ) => DatabaseLike;
  85. function createRuntimeServices(
  86. options: Omit<CreateRuntimeServicesOptions, "runtimeOwnerIdentity">,
  87. ) {
  88. return createRuntimeServicesGraph({
  89. ...options,
  90. runtimeOwnerIdentity,
  91. });
  92. }
  93. function createAgentServiceMock(vitest: Pick<typeof vi, "fn">) {
  94. return {
  95. ensureBuiltinRows: vitest.fn(async () => []),
  96. list: vitest.fn(async () => []),
  97. get: vitest.fn(async () => undefined as never),
  98. create: vitest.fn(async () => undefined as never),
  99. update: vitest.fn(async () => undefined as never),
  100. delete: vitest.fn(async () => undefined),
  101. resolveAgentReadScope: vitest.fn(async (requestedName: string) => ({
  102. requestedName,
  103. canonicalName: requestedName,
  104. primaryName: "mavis",
  105. compatibleNames: [requestedName],
  106. exact: true,
  107. source: "stable_name" as const,
  108. exactOwnerName: requestedName,
  109. })),
  110. resolveAgentWriteTarget: vitest.fn(
  111. async (requestedName: string) => requestedName,
  112. ),
  113. resolveAgentExecutionTarget: vitest.fn(
  114. async (exactOwnerName: string) => exactOwnerName,
  115. ),
  116. requireExactAgentKey: vitest.fn(async (name: string) =>
  117. name.replace(/^agent:/u, ""),
  118. ),
  119. clearRootSession: vi.fn(async () => true),
  120. setRootSession: vitest.fn(async () => true),
  121. getPersistedOwner: vitest.fn(
  122. async (_exactOwnerName: string) =>
  123. undefined as
  124. | {
  125. readonly exactOwnerName: string;
  126. readonly requestRef: string;
  127. readonly canonicalViewName: string;
  128. readonly resolvedAgentName: string;
  129. readonly agentRole: string;
  130. readonly creationSource: "builtin" | "manual" | "auto";
  131. readonly displayName: string;
  132. }
  133. | undefined,
  134. ),
  135. getPersistedOwnerForFrozenTask: vitest.fn(
  136. async (_exactOwnerName: string) =>
  137. undefined as
  138. | {
  139. readonly exactOwnerName: string;
  140. readonly requestRef: string;
  141. readonly canonicalViewName: string;
  142. readonly resolvedAgentName: string;
  143. readonly agentRole: string;
  144. readonly creationSource: "builtin" | "manual" | "auto";
  145. readonly displayName: string;
  146. }
  147. | undefined,
  148. ),
  149. resolvePrimaryExecutionIdentity: vitest.fn(
  150. async (_storageOwnerName: string) =>
  151. undefined as
  152. | {
  153. readonly storageOwnerName: string;
  154. readonly executionOwnerName: string;
  155. readonly outcome: "canonical" | "legacy_fallback" | "conflict";
  156. }
  157. | undefined,
  158. ),
  159. setRootSessionByExactOwner: vitest.fn(async () => true),
  160. renderProfile: vitest.fn(
  161. async (_input: {
  162. readonly exactOwnerName: string;
  163. readonly surface?: string;
  164. }) => undefined as never,
  165. ),
  166. listBuiltinDefinitions: vitest.fn(async () => []),
  167. listLegacyPinnedAgentRefs: vitest.fn(async () => []),
  168. getGreetingState: vitest.fn(async () => undefined),
  169. markGreetingSent: vitest.fn(async () => true),
  170. buildGreetingReminder: vitest.fn(async () => ""),
  171. bindBuiltinModelGroupResolver: vitest.fn(),
  172. bindPromptConfig: vitest.fn(),
  173. bindConfigPreviewDiagnostics: vitest.fn(),
  174. bindEffectiveConfigResolver: vitest.fn(),
  175. bindCandidateModelValidator: vitest.fn(),
  176. close: vitest.fn(),
  177. };
  178. }
  179. function createSessionAndTurnSystemMocks(
  180. vitest: Pick<typeof vi, "fn">,
  181. events: string[],
  182. ) {
  183. return {
  184. sessionSystem: {
  185. repositories: {
  186. sessions: { get: vitest.fn(), list: vitest.fn(), update: vitest.fn() },
  187. projects: {
  188. listPage: vitest.fn(async () => ({ projects: [], hasMore: false })),
  189. setPinned: vitest.fn(),
  190. putOrder: vitest.fn(),
  191. },
  192. },
  193. projects: { service: { resolve: vitest.fn() } },
  194. sessions: {
  195. repository: { get: vitest.fn(), has: vitest.fn() },
  196. query: { find: vitest.fn() },
  197. records: {
  198. ensureSessionAgentDefinition: vitest.fn(),
  199. createInternalSession: vitest.fn(),
  200. bindTaskAgentBindingCapture: vitest.fn(),
  201. backfillAllSessionAgentDefinitions: vitest.fn(async () => undefined),
  202. },
  203. interactionMode: {
  204. get: vitest.fn(async () => "default" as const),
  205. setPlan: vitest.fn(async () => "updated" as const),
  206. ensureDefault: vitest.fn(async () => "updated" as const),
  207. },
  208. },
  209. messages: {
  210. query: {},
  211. repository: { get: vitest.fn(), listTurn: vitest.fn() },
  212. userMessages: {
  213. commit: vitest.fn(
  214. async (input: {
  215. sessionId: string;
  216. turnId: string;
  217. messageKey: string;
  218. content?: string;
  219. }) => ({
  220. sessionId: input.sessionId,
  221. turnId: input.turnId,
  222. messageKey: input.messageKey,
  223. created: true,
  224. firstUserMessageForSession: true,
  225. message: {
  226. msg_id: "message-1",
  227. role: "user",
  228. msg_content: input.content ?? "",
  229. timestamp: 1,
  230. },
  231. }),
  232. ),
  233. },
  234. },
  235. titles: {
  236. generate: vitest.fn(),
  237. generateAfterAcceptedUserMessage: vitest.fn(),
  238. },
  239. queue: {
  240. committed: {
  241. listPendingSessionIds: vitest.fn(async () => []),
  242. list: vitest.fn(async () => []),
  243. requireMutableSession: vitest.fn(),
  244. findByClientRequestId: vitest.fn(),
  245. enqueue: vitest.fn(),
  246. },
  247. },
  248. planDocuments: {
  249. resolveAndEnsure: vitest.fn(async () => ({
  250. canonicalPath: "/history/session-1/artifacts/plan.md",
  251. })),
  252. prepareNewDraft: vitest.fn(),
  253. readFrozenSnapshot: vitest.fn(),
  254. copyForFork: vitest.fn(async () => ({
  255. canonicalPath: "/history/child/artifacts/plan.md",
  256. copied: true,
  257. })),
  258. reconcilePreparedDrafts: vitest.fn(async () => {
  259. events.push("plan-documents:reconcile");
  260. }),
  261. },
  262. files: {},
  263. usage: { repository: {} },
  264. canonicalHistory: { inspectActive: vitest.fn() },
  265. fork: {
  266. sessionDataVersion: 4,
  267. boundary: { resolve: vitest.fn() },
  268. sessions: {
  269. get: vitest.fn(),
  270. create: vitest.fn(),
  271. update: vitest.fn(),
  272. delete: vitest.fn(),
  273. },
  274. display: {
  275. list: vitest.fn(),
  276. probePrefix: vitest.fn(),
  277. copyPrefix: vitest.fn(),
  278. copyPrefixAndAppendForkOrigin: vitest.fn(),
  279. appendForkOrigin: vitest.fn(),
  280. latestRevision: vitest.fn(),
  281. deleteSession: vitest.fn(),
  282. },
  283. assets: {
  284. copyPrefix: vitest.fn(),
  285. probe: vitest.fn(),
  286. compensate: vitest.fn(),
  287. },
  288. },
  289. conversationMutationState: {
  290. isActive: vitest.fn(() => false),
  291. readPlanState: vitest.fn(async () => ({
  292. active: false,
  293. interactionMode: "default" as const,
  294. lifecycleActive: false,
  295. })),
  296. bindPlanStateReader: vitest.fn(),
  297. },
  298. stream: {
  299. resume: vitest.fn(),
  300. write: vitest.fn(),
  301. deleteSession: vitest.fn(),
  302. },
  303. queryCollapse: {
  304. state: {
  305. start: vitest.fn(async (input: QueryCollapseStartInput) => ({
  306. ...input,
  307. forceExpanded: false,
  308. processingStartedAtMs: 1,
  309. updatedAtMs: 1,
  310. })),
  311. finish: vitest.fn(),
  312. findByCurrentTurn: vitest.fn(),
  313. findProcessingByCurrentTurn: vitest.fn(),
  314. findByKey: vitest.fn(),
  315. },
  316. },
  317. ready: vitest.fn(async () => {
  318. events.push("session:ready");
  319. }),
  320. runStorageMaintenance: vitest.fn(async () => undefined),
  321. close: vitest.fn(async () => {
  322. events.push("session:close");
  323. }),
  324. },
  325. turnSystem: {
  326. turns: {
  327. submit: vitest.fn(),
  328. steer: vitest.fn(),
  329. abort: vitest.fn(),
  330. requestCompaction: vitest.fn(),
  331. dispatchQueue: vitest.fn(),
  332. sessionDeletion: vitest.fn(),
  333. },
  334. sessionLifecycle: {
  335. runExclusive: vitest.fn((_sessionId, operation) => operation()),
  336. tryRunExclusive: vitest.fn(
  337. async (
  338. _sessionId,
  339. operation: (signal?: AbortSignal) => Promise<unknown>,
  340. ) => ({
  341. acquired: true as const,
  342. value: await operation(new AbortController().signal),
  343. }),
  344. ),
  345. },
  346. pluginHookSessionOwnership: {
  347. latest: vitest.fn(async () => ({
  348. ownershipClaimId: "owner-turn-1",
  349. turnId: "turn-owner",
  350. claimedAtMs: 100,
  351. })),
  352. tryClaimSessionEnd: vitest.fn(async () => ({
  353. status: "claimed" as const,
  354. })),
  355. completeSessionEnd: vitest.fn(async () => true),
  356. },
  357. inspection: {
  358. activeTurnId: vitest.fn(),
  359. activeTurn: vitest.fn(async () => undefined),
  360. latestTurnActivity: vitest.fn(async () => undefined),
  361. },
  362. queueSteer: { pause: vitest.fn() },
  363. maintenance: {
  364. tryAcquireSessionMaintenance: vitest.fn(),
  365. renewSessionMaintenance: vitest.fn(),
  366. releaseSessionMaintenance: vitest.fn(),
  367. },
  368. receipts: { findReceipt: vitest.fn() },
  369. ready: vitest.fn(async () => {
  370. events.push("turn:ready");
  371. }),
  372. close: vitest.fn(async () => {
  373. events.push("turn:close");
  374. }),
  375. },
  376. };
  377. }
  378. const mocked = vi.hoisted(() => {
  379. const events: string[] = [];
  380. return {
  381. events,
  382. cronOptions: undefined as Record<string, unknown> | undefined,
  383. channelOptions: undefined as Record<string, unknown> | undefined,
  384. agentHostOptions: undefined as Record<string, unknown> | undefined,
  385. sessionTitleOptions: undefined as Record<string, unknown> | undefined,
  386. sessionOptions: undefined as Record<string, unknown> | undefined,
  387. sessionApplicationOptions: undefined as Record<string, unknown> | undefined,
  388. conversationApplicationOptions: undefined as
  389. | Record<string, unknown>
  390. | undefined,
  391. turnOptions: undefined as CapturedTurnOptions | undefined,
  392. initializedSessionApplicationSystem: {
  393. marker: "session-application-system",
  394. session: { lifecycle: { marker: "session-lifecycle" } },
  395. },
  396. applicationOptions: undefined as Record<string, unknown> | undefined,
  397. processLocalApplicationOptions: undefined as
  398. | Record<string, unknown>
  399. | undefined,
  400. conversationApplication: { marker: "conversation-application" },
  401. applicationFactOptions: undefined as Record<string, unknown> | undefined,
  402. runtimeRegion: "cn" as "cn" | "en",
  403. applicationFactPorts: {
  404. session: { handle: vi.fn() },
  405. queue: { handle: vi.fn() },
  406. archiveTitle: { observe: vi.fn() },
  407. },
  408. runtimeApplications: {
  409. marker: "runtime-applications",
  410. session: {
  411. lifecycle: { deleteSessionById: vi.fn(async () => undefined) },
  412. root: { replaceRootSessionWithResult: vi.fn() },
  413. },
  414. },
  415. processLocalApplication: { marker: "process-local-application" },
  416. service: { marker: "cron-service" },
  417. cleanupServices: [] as unknown[],
  418. defaultDelivery: { deliver: async () => ({ delivered: true as const }) },
  419. readyError: undefined as Error | undefined,
  420. closeError: undefined as Error | undefined,
  421. turnInitializationError: undefined as Error | undefined,
  422. conversationBindings: [] as unknown[],
  423. conversationShutdowns: [] as unknown[],
  424. conversationOptions: undefined as Record<string, unknown> | undefined,
  425. attachmentMaterializerOptions: undefined as
  426. | Record<string, unknown>
  427. | undefined,
  428. conversationService: { marker: "v1-conversation-compatibility" },
  429. attachmentMaterializer: { materialize: vi.fn() },
  430. questionnaireActionBindings: [] as unknown[],
  431. questionnaireService: {
  432. beginOwned: vi.fn(),
  433. reconcileOwnedActions: vi.fn(async (dispatch: boolean) => {
  434. events.push(`questionnaire:plan-reconcile:${String(dispatch)}`);
  435. return 0;
  436. }),
  437. recoverOnStartup: vi.fn(async () => {
  438. events.push("questionnaire:recover");
  439. return { expired: 0, reinjected: 0, reemitted: 0 };
  440. }),
  441. },
  442. v1Submission: { submit: vi.fn() },
  443. sessionTitleModel: { summarize: vi.fn() },
  444. archiveTitleOptions: undefined as Record<string, unknown> | undefined,
  445. agentPreparationOptions: undefined as Record<string, unknown> | undefined,
  446. agentPreparation: {
  447. marker: "shared-agent-preparation",
  448. bindSessionModelRepair: vi.fn(),
  449. bindTaskSessionBindings: vi.fn(),
  450. },
  451. createSessionModelRepair: vi.fn(() => ({ repairSessionModel: vi.fn() })),
  452. agentService: createAgentServiceMock(vi),
  453. agentRuntimeLifecycle: { disposeSession: vi.fn(async () => undefined) },
  454. channelSystem: {
  455. terminalReplies: { observeRuntimeEvent: vi.fn() },
  456. turnLifecycle: { beforeExecution: vi.fn(), end: vi.fn() },
  457. },
  458. ...createSessionAndTurnSystemMocks(vi, events),
  459. plugin: { marker: "plugin-service" },
  460. hostConnectorGateway: { marker: "host-connector-gateway" },
  461. mcp: {
  462. marker: "mcp-service",
  463. disposeSession: vi.fn(async () => undefined),
  464. },
  465. mcpSettings: { marker: "mcp-settings-service" },
  466. skill: { marker: "skill-service" },
  467. runtimeSkillApplication: {
  468. listRuntimeSkills: vi.fn(),
  469. setSkillEnabled: vi.fn(),
  470. },
  471. pluginTurnCapabilities: undefined as unknown,
  472. pluginHookSessionEndFence: undefined as
  473. | { run(input: Record<string, unknown>): Promise<unknown> }
  474. | undefined,
  475. hostPluginHookSessionOwnership: undefined as unknown,
  476. miniAppOptions: undefined as Record<string, unknown> | undefined,
  477. materializeMiniAppRuntimePackage: vi.fn(async () => undefined),
  478. miniAppSupervisor: {
  479. ready: vi.fn(async () => {
  480. events.push("miniapp:ready");
  481. }),
  482. close: vi.fn(async () => {
  483. events.push("miniapp:close");
  484. }),
  485. },
  486. modelConfig: {
  487. provider: {},
  488. dataDir: "/data",
  489. custom_provider: { "openai-work": {} },
  490. },
  491. };
  492. });
  493. const localAgentService = mocked.agentService as unknown as LocalAgentService;
  494. vi.mock("./service/cron/index.js", async (importOriginal) => {
  495. const actual =
  496. await importOriginal<typeof import("./service/cron/index.js")>();
  497. return {
  498. ...actual,
  499. createHostCronSessionCreation: (host: unknown) => ({
  500. create: vi.fn(),
  501. host,
  502. }),
  503. initializeCronService: (options: Record<string, unknown>) => {
  504. mocked.events.push("cron:create");
  505. mocked.cronOptions = options;
  506. return {
  507. service: mocked.service,
  508. ready: async () => {
  509. mocked.events.push("cron:ready");
  510. if (mocked.readyError) throw mocked.readyError;
  511. },
  512. close: async () => {
  513. mocked.events.push("cron:close");
  514. if (mocked.closeError) throw mocked.closeError;
  515. },
  516. };
  517. },
  518. };
  519. });
  520. vi.mock("./service/channel-system/index.js", async (importOriginal) => ({
  521. ...(await importOriginal<
  522. typeof import("./service/channel-system/index.js")
  523. >()),
  524. initializeOptionalChannelSystem: (
  525. enabled: boolean,
  526. options: Record<string, unknown>,
  527. ) => {
  528. if (!enabled) return undefined;
  529. mocked.events.push("channel:create");
  530. mocked.channelOptions = options;
  531. return mocked.channelSystem;
  532. },
  533. }));
  534. vi.mock("./service/plugin-system/index.js", async (importOriginal) => ({
  535. ...(await importOriginal<
  536. typeof import("./service/plugin-system/index.js")
  537. >()),
  538. initializePluginService: (
  539. options: Record<string, unknown>,
  540. turnCapabilities: unknown,
  541. ) => {
  542. mocked.events.push("plugin:create");
  543. mocked.pluginTurnCapabilities = turnCapabilities;
  544. return {
  545. plugin: mocked.plugin,
  546. mcp: mocked.mcp,
  547. skill: mocked.skill,
  548. hostConnectorGateway: mocked.hostConnectorGateway,
  549. attachMiniAppPublication: () =>
  550. mocked.events.push("plugin:attach-miniapp"),
  551. restartMiniApp: async () => mocked.events.push("plugin:restart-miniapp"),
  552. verifyMiniAppCandidate: async () => true,
  553. materializeMiniAppRuntimePackage: mocked.materializeMiniAppRuntimePackage,
  554. listAvailableMiniApps: async () => [],
  555. listAcceptedMiniApps: () => [],
  556. isAcceptedMiniAppRunning: () => false,
  557. publishWorkspaceMiniApp: async () => undefined as never,
  558. initializeWorkspaceMiniApp: async () => undefined as never,
  559. activateMiniApp: async () => undefined,
  560. stopMiniApp: async () => undefined,
  561. authContextChanged: () =>
  562. mocked.events.push("plugin:auth-context-changed"),
  563. enabledHookPluginNames: () => new Set<string>(),
  564. ready: async () => mocked.events.push("plugin:ready"),
  565. close: async () => mocked.events.push("plugin:close"),
  566. options,
  567. };
  568. },
  569. }));
  570. vi.mock("./service/mcp/index.js", () => ({
  571. initializeMcpService: (options: Record<string, unknown>) => {
  572. mocked.events.push("mcp:create");
  573. return {
  574. service: mocked.mcpSettings,
  575. runtime: mocked.mcp,
  576. public: mocked.mcp,
  577. ready: async () => mocked.events.push("mcp:ready"),
  578. close: async () => mocked.events.push("mcp:close"),
  579. options,
  580. };
  581. },
  582. }));
  583. vi.mock("./service/miniapp/initialize.js", async (importOriginal) => {
  584. const actual =
  585. await importOriginal<typeof import("./service/miniapp/initialize.js")>();
  586. return {
  587. ...actual,
  588. initializeMiniAppSupervisor: (options: Record<string, unknown>) => {
  589. mocked.events.push("miniapp:create");
  590. mocked.miniAppOptions = options;
  591. return mocked.miniAppSupervisor;
  592. },
  593. };
  594. });
  595. const noopLogger = {
  596. info: () => undefined,
  597. warn: () => undefined,
  598. error: () => undefined,
  599. };
  600. vi.mock("./service/session-system/index.js", async (importOriginal) => {
  601. const actual =
  602. await importOriginal<typeof import("./service/session-system/index.js")>();
  603. return {
  604. isCurrentSessionAgentDefinition: actual.isCurrentSessionAgentDefinition,
  605. isTaskSession: actual.isTaskSession,
  606. ComposerSendBehaviorPreference: actual.ComposerSendBehaviorPreference,
  607. retryUserMessageCommit: <T>(operation: () => Promise<T>) => operation(),
  608. createCanonicalRecoveryLoggerAdapter:
  609. (logger: {
  610. info(fields: Record<string, unknown>, message: string): void;
  611. }) =>
  612. (event: Record<string, unknown>) =>
  613. logger.info(
  614. { ...event },
  615. "[local-runtime-v2] legacy Session canonical recovery",
  616. ),
  617. initializeSessionSystem: (options: Record<string, unknown>) => {
  618. mocked.events.push("session:create");
  619. mocked.sessionOptions = options;
  620. return mocked.sessionSystem;
  621. },
  622. initializeSessionApplicationSystem: (options: Record<string, unknown>) => {
  623. mocked.events.push("session-applications:create");
  624. mocked.sessionApplicationOptions = options;
  625. return mocked.initializedSessionApplicationSystem;
  626. },
  627. };
  628. });
  629. vi.mock("@mavis/config", async (importOriginal) => ({
  630. ...(await importOriginal<typeof import("@mavis/config")>()),
  631. allowsManagedMinimaxProviderOverride: () => false,
  632. getRuntimeRegion: () => mocked.runtimeRegion,
  633. }));
  634. vi.mock("./service/model-system/index.js", async (importOriginal) => ({
  635. ...(await importOriginal<typeof import("./service/model-system/index.js")>()),
  636. createLocalModelSystemConfigPort: () => ({
  637. read: () => mocked.modelConfig,
  638. updateByok: vi.fn(async () => undefined),
  639. compareAndSetModelContext: vi.fn(async () => true),
  640. setDefaultModel: vi.fn(async () => undefined),
  641. removeProvider: vi.fn(async () => undefined),
  642. }),
  643. }));
  644. vi.mock("./application/session/fact-ports.js", async (importOriginal) => ({
  645. ...(await importOriginal<
  646. typeof import("./application/session/fact-ports.js")
  647. >()),
  648. createApplicationFactPorts: (options: Record<string, unknown>) => {
  649. mocked.applicationFactOptions = options;
  650. return mocked.applicationFactPorts;
  651. },
  652. }));
  653. vi.mock("./application/index.js", async (importOriginal) => {
  654. class TestAgentApplication {
  655. constructor(
  656. private readonly options: { service: typeof mocked.agentService },
  657. ) {}
  658. ensureBuiltinDefinitionsForPhase2() {
  659. mocked.events.push("agent:ensure");
  660. return this.options.service
  661. .ensureBuiltinRows()
  662. .then(() => this.options.service.list());
  663. }
  664. materializeLegacyCustomAgents() {
  665. return Promise.resolve({
  666. materialized: 0,
  667. alreadyCanonical: 0,
  668. notLegacy: 0,
  669. });
  670. }
  671. close() {
  672. this.options.service.close();
  673. }
  674. notifyGreetingTurnTerminal = vi.fn(async () => undefined);
  675. resolveAgentWriteTarget(requestRef: string) {
  676. return this.options.service.resolveAgentWriteTarget(requestRef);
  677. }
  678. }
  679. return {
  680. ...(await importOriginal<typeof import("./application/index.js")>()),
  681. AgentApplication: TestAgentApplication,
  682. createRuntimeAgentApplication: (input: {
  683. agentService: typeof mocked.agentService;
  684. }) => new TestAgentApplication({ service: input.agentService }),
  685. createAgentSessionPorts: () => ({
  686. directory: { get: vi.fn() },
  687. clearRootSession: vi.fn(async () => true),
  688. roots: { get: vi.fn(), setRootSession: vi.fn() },
  689. resolveWriteTarget: vi.fn(async (requestRef: string) => requestRef),
  690. }),
  691. initializeApplications: (options: Record<string, unknown>) => {
  692. mocked.events.push("applications:create");
  693. mocked.applicationOptions = options;
  694. return mocked.runtimeApplications;
  695. },
  696. createProcessLocalApplication: (options: Record<string, unknown>) => {
  697. mocked.processLocalApplicationOptions = options;
  698. return mocked.processLocalApplication;
  699. },
  700. createRuntimeSkillApplication: () => mocked.runtimeSkillApplication,
  701. };
  702. });
  703. vi.mock("./application/conversation/index.js", async (importOriginal) => {
  704. const original =
  705. await importOriginal<
  706. typeof import("./application/conversation/index.js")
  707. >();
  708. return {
  709. ...original,
  710. createQueryCollapseKeyResolver: (options: Record<string, unknown>) => {
  711. queryCollapseMocked.keyResolverOptions = options;
  712. return queryCollapseMocked.keys;
  713. },
  714. UserMessageTurnDeliveryService: class extends original.UserMessageTurnDeliveryService {
  715. constructor(
  716. options: ConstructorParameters<
  717. typeof original.UserMessageTurnDeliveryService
  718. >[0],
  719. ) {
  720. queryCollapseMocked.deliveryOptions = options as unknown as Record<
  721. string,
  722. unknown
  723. >;
  724. super(options);
  725. }
  726. },
  727. createConversationApplication: (options: Record<string, unknown>) => {
  728. mocked.conversationApplicationOptions = options;
  729. return mocked.conversationApplication;
  730. },
  731. };
  732. });
  733. vi.mock("./service/turn-system/index.js", async (importOriginal) => ({
  734. ...(await importOriginal<typeof import("./service/turn-system/index.js")>()),
  735. AgentHostTurnCapabilityLifecycle: class AgentHostTurnCapabilityLifecycle {},
  736. composeTurnAdmissionPolicies: (...policies: unknown[]) => ({ policies }),
  737. configureLocalPluginHookEnabledResolver: vi.fn(),
  738. configureLocalPluginHookSessionEndFence: vi.fn((fence: unknown) => {
  739. mocked.pluginHookSessionEndFence =
  740. fence as typeof mocked.pluginHookSessionEndFence;
  741. }),
  742. configureLocalPluginHookObservability: vi.fn(),
  743. deactivateLocalPluginHooks: vi.fn(),
  744. disposeLocalPluginHookSessions: vi.fn(),
  745. endAllLocalPluginHookSessionsForLogout: vi.fn(async () => undefined),
  746. endLocalPluginHookSession: vi.fn(async () => undefined),
  747. isUserSteeringProducer: (producerId: string) =>
  748. producerId === "queue-immediate-send" ||
  749. producerId === "composer-steer" ||
  750. producerId === "paused-queue-composer",
  751. requireAgentRuntime,
  752. requireTurnSystem,
  753. resolveAgentPromptSurface,
  754. composeTurnSubmissionPreparations: (...candidates: unknown[]) =>
  755. candidates.find((candidate) => candidate !== undefined),
  756. createGoalTurnSubmissionPreparation: (input: {
  757. prepare?: (candidate: Record<string, unknown>) => unknown;
  758. hasPendingPlan: (sessionId: string) => unknown;
  759. hasPriorityMailboxWork: (sessionId: string) => unknown;
  760. }) =>
  761. input.prepare
  762. ? {
  763. prepare: (candidate: Record<string, unknown>) =>
  764. input.prepare?.({
  765. ...candidate,
  766. hasPendingPlan: input.hasPendingPlan,
  767. hasPriorityMailboxWork: input.hasPriorityMailboxWork,
  768. }),
  769. }
  770. : undefined,
  771. hasPriorityUserQueueItem: (items: readonly { readonly source: string }[]) =>
  772. items.some(
  773. ({ source }) =>
  774. source === "api" ||
  775. source === "questionnaire" ||
  776. source === "communication" ||
  777. source === "code_review" ||
  778. source.startsWith("channel:"),
  779. ),
  780. initializeTurnSystem: async (options: {
  781. disposeRuntimeSession?: InitializeTurnSystemOptions["disposeRuntimeSession"];
  782. processStartedAtMs: number;
  783. classifyQueuedItem?: QueueClassifier;
  784. shouldYieldFifoPosition?: QueueFifoYieldPolicy;
  785. resumeSessionDeletion?: InitializeTurnSystemOptions["resumeSessionDeletion"];
  786. turnSettlement?: InitializeTurnSystemOptions["turnSettlement"];
  787. createHost(input: {
  788. turnControl: unknown;
  789. turnFacts: unknown;
  790. pluginHookSessionOwnership: unknown;
  791. }): Promise<unknown>;
  792. }) => {
  793. mocked.events.push("turn:create");
  794. if (mocked.turnInitializationError) throw mocked.turnInitializationError;
  795. mocked.turnOptions = {
  796. disposeRuntimeSession: options.disposeRuntimeSession,
  797. processStartedAtMs: options.processStartedAtMs,
  798. ...(options.classifyQueuedItem
  799. ? { classifyQueuedItem: options.classifyQueuedItem }
  800. : {}),
  801. ...(options.shouldYieldFifoPosition
  802. ? { shouldYieldFifoPosition: options.shouldYieldFifoPosition }
  803. : {}),
  804. ...(options.resumeSessionDeletion
  805. ? { resumeSessionDeletion: options.resumeSessionDeletion }
  806. : {}),
  807. ...(options.turnSettlement
  808. ? { turnSettlement: options.turnSettlement }
  809. : {}),
  810. };
  811. const pluginHookSessionOwnership = {
  812. prepare: vi.fn(async () => undefined),
  813. activate: vi.fn(async () => undefined),
  814. };
  815. mocked.hostPluginHookSessionOwnership = pluginHookSessionOwnership;
  816. await options.createHost({
  817. turnControl: {},
  818. turnFacts: {},
  819. pluginHookSessionOwnership,
  820. });
  821. return mocked.turnSystem;
  822. },
  823. createProductionAgentPreparation: vi.fn(
  824. (options: Record<string, unknown>) => {
  825. mocked.agentPreparationOptions = options;
  826. return mocked.agentPreparation;
  827. },
  828. ),
  829. createSessionModelRepair: mocked.createSessionModelRepair,
  830. combineAgentEventObservers: vi.fn((...observers: unknown[]) => ({
  831. observers,
  832. })),
  833. createSessionLLMRetryEventObserver:
  834. (publish: (event: GlobalEventInput<"session.llm_retry">) => void) =>
  835. (event: LLMRetryEvent) => {
  836. if (event.scope === "title") return;
  837. publish({
  838. type: "session.llm_retry",
  839. payload: { schemaVersion: 1, ...event },
  840. });
  841. },
  842. createLocalAgentHost: vi.fn(async (options: Record<string, unknown>) => {
  843. mocked.agentHostOptions = options;
  844. return {
  845. host: {},
  846. lifecycle: mocked.agentRuntimeLifecycle,
  847. };
  848. }),
  849. createProductionSessionTitleModel: vi.fn(
  850. (options: Record<string, unknown>) => {
  851. mocked.sessionTitleOptions = options;
  852. return mocked.sessionTitleModel;
  853. },
  854. ),
  855. createProductionRootArchiveTitleModel: vi.fn(
  856. (options: Record<string, unknown>) => {
  857. mocked.archiveTitleOptions = options;
  858. return {
  859. summarize: vi.fn(async () => null),
  860. };
  861. },
  862. ),
  863. }));
  864. vi.mock("./application/session/fact-ports.js", async (importOriginal) => ({
  865. ...(await importOriginal<
  866. typeof import("./application/session/fact-ports.js")
  867. >()),
  868. createApplicationFactPorts: (options: Record<string, unknown>) => {
  869. mocked.applicationFactOptions = options;
  870. return mocked.applicationFactPorts;
  871. },
  872. }));
  873. // The composition root now assembles the v1 Conversation surface through the
  874. // real `composeV1Conversation`, so the leaf factories are what gets stubbed —
  875. // the assertions below still observe exactly what that composition hands over.
  876. vi.mock("./service/v1-conversation-compat/attachments/index.js", () => ({
  877. createV1ConversationAttachmentMaterializer: vi.fn(
  878. (options: Record<string, unknown>) => {
  879. mocked.attachmentMaterializerOptions = options;
  880. return mocked.attachmentMaterializer;
  881. },
  882. ),
  883. }));
  884. vi.mock(
  885. "./service/v1-conversation-compat/v1-compatible-turn-submission.service.js",
  886. () => ({
  887. createV1CompatibleTurnSubmission: vi.fn(() => mocked.v1Submission),
  888. }),
  889. );
  890. vi.mock("./service/v1-conversation-compat/initialize.js", () => ({
  891. createV1ConversationCompatibility: vi.fn(
  892. (options: Record<string, unknown>) => {
  893. mocked.conversationOptions = options;
  894. return mocked.conversationService;
  895. },
  896. ),
  897. }));
  898. afterEach(() => vi.unstubAllEnvs());
  899. beforeEach(() => {
  900. mocked.agentRuntimeLifecycle.disposeSession.mockReset();
  901. mocked.mcp.disposeSession.mockClear();
  902. mocked.events.length = 0;
  903. mocked.cronOptions = undefined;
  904. mocked.channelOptions = undefined;
  905. mocked.agentHostOptions = undefined;
  906. mocked.sessionTitleOptions = undefined;
  907. mocked.sessionOptions = undefined;
  908. mocked.sessionApplicationOptions = undefined;
  909. mocked.conversationApplicationOptions = undefined;
  910. mocked.turnOptions = undefined;
  911. queryCollapseMocked.keyResolverOptions = undefined;
  912. queryCollapseMocked.deliveryOptions = undefined;
  913. queryCollapseMocked.keys.queryKeyForTurn.mockClear();
  914. queryCollapseMocked.keys.queryKeyForContinuation.mockClear();
  915. mocked.applicationOptions = undefined;
  916. mocked.processLocalApplicationOptions = undefined;
  917. mocked.applicationFactOptions = undefined;
  918. mocked.runtimeRegion = "cn";
  919. mocked.archiveTitleOptions = undefined;
  920. mocked.agentPreparationOptions = undefined;
  921. mocked.createSessionModelRepair.mockClear();
  922. mocked.agentPreparation.bindSessionModelRepair.mockClear();
  923. mocked.agentPreparation.bindTaskSessionBindings.mockClear();
  924. mocked.readyError = undefined;
  925. mocked.closeError = undefined;
  926. mocked.turnInitializationError = undefined;
  927. mocked.cleanupServices.length = 0;
  928. mocked.pluginTurnCapabilities = undefined;
  929. mocked.pluginHookSessionEndFence = undefined;
  930. mocked.hostPluginHookSessionOwnership = undefined;
  931. mocked.miniAppOptions = undefined;
  932. mocked.materializeMiniAppRuntimePackage.mockClear();
  933. mocked.miniAppSupervisor.ready.mockClear();
  934. mocked.miniAppSupervisor.close.mockClear();
  935. mocked.conversationBindings.length = 0;
  936. mocked.conversationShutdowns.length = 0;
  937. mocked.conversationOptions = undefined;
  938. mocked.agentService.ensureBuiltinRows.mockClear();
  939. mocked.agentService.bindBuiltinModelGroupResolver.mockClear();
  940. mocked.agentService.bindPromptConfig.mockClear();
  941. mocked.agentService.bindConfigPreviewDiagnostics.mockClear();
  942. mocked.agentService.bindEffectiveConfigResolver.mockClear();
  943. mocked.agentService.bindCandidateModelValidator.mockClear();
  944. mocked.agentService.list.mockClear();
  945. mocked.agentService.close.mockClear();
  946. mocked.agentService.renderProfile.mockReset();
  947. mocked.agentService.renderProfile.mockResolvedValue(undefined as never);
  948. mocked.agentService.getPersistedOwner.mockReset();
  949. mocked.agentService.getPersistedOwner.mockResolvedValue(undefined);
  950. mocked.agentService.resolvePrimaryExecutionIdentity.mockReset();
  951. mocked.agentService.resolvePrimaryExecutionIdentity.mockResolvedValue(
  952. undefined,
  953. );
  954. mocked.attachmentMaterializerOptions = undefined;
  955. mocked.questionnaireActionBindings.length = 0;
  956. mocked.turnSystem.turns.steer.mockReset();
  957. mocked.turnSystem.turns.steer.mockResolvedValue({
  958. delivered: true,
  959. mode: "activated",
  960. turnId: "turn-1",
  961. });
  962. mocked.turnSystem.sessionLifecycle.tryRunExclusive?.mockReset();
  963. mocked.turnSystem.sessionLifecycle.tryRunExclusive?.mockImplementation(
  964. async (
  965. _sessionId: string,
  966. operation: (signal?: AbortSignal) => Promise<unknown>,
  967. ) => ({
  968. acquired: true as const,
  969. value: await operation(new AbortController().signal),
  970. }),
  971. );
  972. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd.mockReset();
  973. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd.mockResolvedValue(
  974. {
  975. status: "claimed",
  976. },
  977. );
  978. mocked.turnSystem.pluginHookSessionOwnership.completeSessionEnd.mockReset();
  979. mocked.turnSystem.pluginHookSessionOwnership.completeSessionEnd.mockResolvedValue(
  980. true,
  981. );
  982. mocked.turnSystem.pluginHookSessionOwnership.latest.mockReset();
  983. mocked.turnSystem.pluginHookSessionOwnership.latest.mockResolvedValue({
  984. ownershipClaimId: "owner-turn-1",
  985. turnId: "turn-owner",
  986. claimedAtMs: 100,
  987. });
  988. mocked.turnSystem.inspection.latestTurnActivity.mockReset();
  989. mocked.turnSystem.inspection.latestTurnActivity.mockResolvedValue(undefined);
  990. mocked.sessionSystem.canonicalHistory.inspectActive.mockReset();
  991. mocked.sessionSystem.messages.repository.get.mockReset();
  992. mocked.sessionSystem.messages.repository.listTurn.mockReset();
  993. mocked.sessionSystem.sessions.repository.get.mockReset();
  994. mocked.sessionSystem.titles.generate.mockReset();
  995. mocked.sessionSystem.messages.userMessages.commit.mockClear();
  996. mocked.sessionSystem.stream.write.mockClear();
  997. mocked.runtimeApplications.session.lifecycle.deleteSessionById.mockClear();
  998. mocked.sessionSystem.queryCollapse.state.start.mockClear();
  999. mocked.sessionSystem.queryCollapse.state.finish.mockClear();
  1000. mocked.sessionSystem.queryCollapse.state.findByCurrentTurn.mockClear();
  1001. mocked.sessionSystem.queryCollapse.state.findProcessingByCurrentTurn.mockClear();
  1002. mocked.sessionSystem.queryCollapse.state.findByKey.mockClear();
  1003. });
  1004. type InputReviewResolved = (input: {
  1005. readonly sessionId: string;
  1006. readonly turnId: string;
  1007. readonly userInput: string;
  1008. readonly rejected: boolean;
  1009. }) => void;
  1010. async function assertInputReviewTitlePolicy(
  1011. reportFailure: NonNullable<
  1012. V1ServiceCompatibility["agentHost"]["executor"]["reportFailure"]
  1013. >,
  1014. ): Promise<void> {
  1015. mocked.sessionSystem.messages.repository.listTurn.mockResolvedValue([
  1016. { msg_id: "message-safe", role: "user", msg_content: "Ship the objective" },
  1017. ]);
  1018. const onInputReviewResolved = mocked.agentHostOptions?.[
  1019. "onInputReviewResolved"
  1020. ] as InputReviewResolved;
  1021. onInputReviewResolved({
  1022. sessionId: "session-1",
  1023. turnId: "turn-safe",
  1024. userInput: "<internal-goal-prompt />",
  1025. rejected: false,
  1026. });
  1027. onInputReviewResolved({
  1028. sessionId: "session-1",
  1029. turnId: "turn-blocked",
  1030. userInput: "blocked input",
  1031. rejected: true,
  1032. });
  1033. await vi.waitFor(() =>
  1034. expect(mocked.sessionSystem.titles.generate).toHaveBeenCalledOnce(),
  1035. );
  1036. expect(
  1037. mocked.sessionSystem.messages.repository.listTurn,
  1038. ).toHaveBeenCalledOnce();
  1039. expect(
  1040. mocked.sessionSystem.messages.repository.listTurn,
  1041. ).toHaveBeenCalledWith("session-1", "turn-safe");
  1042. expect(mocked.sessionSystem.titles.generate).toHaveBeenCalledWith(
  1043. "session-1",
  1044. "Ship the objective",
  1045. );
  1046. mocked.sessionSystem.messages.repository.listTurn.mockRejectedValueOnce(
  1047. new Error("message read unavailable"),
  1048. );
  1049. onInputReviewResolved({
  1050. sessionId: "session-1",
  1051. turnId: "turn-read-failed",
  1052. userInput: "approved input",
  1053. rejected: false,
  1054. });
  1055. await vi.waitFor(() =>
  1056. expect(reportFailure).toHaveBeenCalledWith(
  1057. "session-1",
  1058. "session_title_source_resolution_failed:message read unavailable",
  1059. ),
  1060. );
  1061. expect(mocked.sessionSystem.titles.generate).toHaveBeenCalledOnce();
  1062. }
  1063. async function assertSessionCompositionPolicies(input: {
  1064. readonly compatibility: V1ServiceCompatibility;
  1065. readonly metricsCounter: ReturnType<typeof vi.fn>;
  1066. readonly projectedEvents: readonly GlobalEvent[];
  1067. }): Promise<void> {
  1068. const reportFailure = input.compatibility.agentHost.executor.reportFailure;
  1069. if (!reportFailure)
  1070. throw new Error("test compatibility requires failure reporting");
  1071. await assertInputReviewTitlePolicy(reportFailure);
  1072. const titlePolicy = mocked.sessionOptions?.["titlePolicy"] as {
  1073. blocks(title: string): Promise<boolean>;
  1074. };
  1075. await expect(titlePolicy.blocks("generated title")).resolves.toBe(false);
  1076. expect(input.compatibility.safety.review).toHaveBeenCalledWith(
  1077. "generated title",
  1078. 205,
  1079. );
  1080. const title = mocked.sessionOptions?.["title"] as {
  1081. readonly onOutcome: (outcome: string) => void;
  1082. readonly onFailure: (input: {
  1083. readonly stage: string;
  1084. readonly sessionId: string;
  1085. readonly error: unknown;
  1086. }) => void;
  1087. };
  1088. title.onOutcome("success");
  1089. const warn = vi.spyOn(noopLogger, "warn");
  1090. title.onFailure({
  1091. stage: "model",
  1092. sessionId: "session-1",
  1093. error: new Error("provider failed"),
  1094. });
  1095. expect(input.metricsCounter).toHaveBeenCalledWith(
  1096. "session_title_generation_total",
  1097. 1,
  1098. {
  1099. outcome: "success",
  1100. },
  1101. );
  1102. // A title helper failure is a Session-scoped diagnostic; it must not enter the
  1103. // runtime turn failure channel that surfaces as a generic model-service error.
  1104. expect(warn).toHaveBeenCalledWith(
  1105. {
  1106. sessionId: "session-1",
  1107. stage: "model",
  1108. reason: "session_title_model_failed:provider failed",
  1109. },
  1110. "session title generation failed",
  1111. );
  1112. expect(
  1113. input.compatibility.agentHost.executor.reportFailure,
  1114. ).not.toHaveBeenCalledWith(
  1115. "session-1",
  1116. expect.stringContaining("session_title_model_failed"),
  1117. );
  1118. warn.mockRestore();
  1119. assertCompactionFacts(input.projectedEvents);
  1120. }
  1121. function assertCompactionFacts(projectedEvents: readonly GlobalEvent[]): void {
  1122. const compactionFacts = mocked.sessionOptions?.["compactionFacts"] as {
  1123. readonly handle: (fact: Record<string, unknown>) => void;
  1124. };
  1125. expect(
  1126. compactionFacts.handle({
  1127. kind: "started",
  1128. sessionId: "session-1",
  1129. attemptId: "attempt-1",
  1130. }),
  1131. ).toBeUndefined();
  1132. expect(
  1133. compactionFacts.handle({
  1134. kind: "completed",
  1135. sessionId: "session-1",
  1136. attemptId: "attempt-1",
  1137. messagesBefore: 10,
  1138. messagesAfter: 2,
  1139. tokensBefore: 1_000,
  1140. tokensAfter: 200,
  1141. }),
  1142. ).toBeUndefined();
  1143. expect(
  1144. compactionFacts.handle({
  1145. kind: "failed",
  1146. sessionId: "session-2",
  1147. attemptId: "attempt-2",
  1148. }),
  1149. ).toBeUndefined();
  1150. expect(projectedEvents).toEqual([
  1151. {
  1152. type: "session.compaction.started",
  1153. timestamp: 1_700_000_000_000,
  1154. source: "local-runtime",
  1155. payload: { sessionId: "session-1", compactionId: "attempt-1" },
  1156. },
  1157. {
  1158. type: "session.compaction.completed",
  1159. timestamp: 1_700_000_000_000,
  1160. source: "local-runtime",
  1161. payload: {
  1162. sessionId: "session-1",
  1163. compactionId: "attempt-1",
  1164. messagesBefore: 10,
  1165. messagesAfter: 2,
  1166. tokensBefore: 1_000,
  1167. tokensAfter: 200,
  1168. },
  1169. },
  1170. {
  1171. type: "session.compaction.failed",
  1172. timestamp: 1_700_000_000_000,
  1173. source: "local-runtime",
  1174. payload: { sessionId: "session-2", compactionId: "attempt-2" },
  1175. },
  1176. ]);
  1177. }
  1178. async function assertMiniAppStartupFailureCleanup(): Promise<void> {
  1179. const failure = new Error("turn initialization failed");
  1180. mocked.turnInitializationError = failure;
  1181. await expect(
  1182. createRuntimeServices({
  1183. db: {} as AppDb,
  1184. dataDir: "/data",
  1185. scheduler: {} as SchedulerClient,
  1186. eventBus: new EventBus<GlobalEvent>(),
  1187. compatibility: defaultCompatibility(),
  1188. agentService: localAgentService,
  1189. runtimeOwnerKind: "electron",
  1190. promptConfigKey: new Uint8Array(32).fill(7),
  1191. }),
  1192. ).rejects.toBe(failure);
  1193. expect(mocked.events).toContain("miniapp:create");
  1194. expect(mocked.events.filter((event) => event.endsWith(":close"))).toEqual([
  1195. "plugin:close",
  1196. "mcp:close",
  1197. "session:close",
  1198. "miniapp:close",
  1199. ]);
  1200. }
  1201. async function assertGoalQueueReadsPlanFence(): Promise<void> {
  1202. const compatibility = defaultCompatibility();
  1203. const getPending = vi.fn(async () => undefined as never);
  1204. const classifyGoalItem = vi.mocked(
  1205. compatibility.sessionV2.goals.classifyQueuedItem,
  1206. );
  1207. const planFenceReads: string[] = [];
  1208. const services = await createRuntimeServices({
  1209. db: {
  1210. select: () => ({
  1211. from: () => ({
  1212. where: () => ({ limit: () => ({ get: () => undefined }) }),
  1213. }),
  1214. }),
  1215. } as unknown as AppDb,
  1216. dataDir: "/data",
  1217. scheduler: {} as SchedulerClient,
  1218. eventBus: new EventBus<GlobalEvent>(),
  1219. compatibility: {
  1220. ...compatibility,
  1221. peripherals: { questionnaires: { getPending } } as never,
  1222. },
  1223. agentService: localAgentService,
  1224. });
  1225. const classifier = mocked.turnOptions?.classifyQueuedItem;
  1226. if (!classifier)
  1227. throw new Error("Turn System queue classifier was not composed");
  1228. const item = {
  1229. itemId: "goal-queue-1",
  1230. sessionId: "session-1",
  1231. agentName: "mavis",
  1232. source: "thread-goal" as const,
  1233. status: "queued" as const,
  1234. clientRequestId: "thread-goal-followup:turn-1",
  1235. message: { content: "continue goal", attachments: [] },
  1236. createdAt: 1,
  1237. };
  1238. classifyGoalItem.mockImplementation(async (_item, hasPendingPlan) => {
  1239. if (hasPendingPlan)
  1240. planFenceReads.push(await hasPendingPlan("session-1").then(String));
  1241. return "ready" as const;
  1242. });
  1243. await expect(classifier(item)).resolves.toBe("ready");
  1244. // The Plan fence reader is handed to Goal selection so a Plan-blocked Goal can
  1245. // name `plan` as its wait reason. It is an addition, not a replacement: the
  1246. // shared questionnaire precheck and the outer Plan fence both still run for
  1247. // Goal items, so nothing (budget-limit continuations included) can be admitted
  1248. // by skipping them.
  1249. expect(getPending).toHaveBeenCalledWith({
  1250. agentName: "mavis",
  1251. sessionId: "session-1",
  1252. });
  1253. expect(classifyGoalItem).toHaveBeenCalledWith(item, expect.any(Function));
  1254. expect(planFenceReads).toEqual(["false"]);
  1255. await services.close();
  1256. }
  1257. async function assertGoalQueueYieldsToUserWork(): Promise<void> {
  1258. const services = await createRuntimeServices({
  1259. db: {} as AppDb,
  1260. dataDir: "/data",
  1261. scheduler: {} as SchedulerClient,
  1262. eventBus: new EventBus<GlobalEvent>(),
  1263. compatibility: defaultCompatibility(),
  1264. agentService: localAgentService,
  1265. });
  1266. const yields = mocked.turnOptions?.shouldYieldFifoPosition;
  1267. if (!yields) throw new Error("Queue FIFO yield policy was not composed");
  1268. const list = vi.mocked(mocked.sessionSystem.queue.committed.list);
  1269. const queueItem = (source: string) => ({
  1270. itemId: `item-${source}`,
  1271. sessionId: "session-1",
  1272. agentName: "mavis",
  1273. source,
  1274. status: "queued" as const,
  1275. message: { content: "queued", attachments: [] },
  1276. createdAt: 1,
  1277. });
  1278. const goalItem = queueItem("thread-goal");
  1279. const userItem = queueItem("api");
  1280. list.mockResolvedValueOnce([queueItem("api")] as never);
  1281. await expect(yields(goalItem as never)).resolves.toBe(true);
  1282. // A queued questionnaire reply is user work too: it is what unblocks the very
  1283. // gate the Goal is waiting on.
  1284. list.mockResolvedValueOnce([queueItem("questionnaire")] as never);
  1285. await expect(yields(goalItem as never)).resolves.toBe(true);
  1286. // Autonomous work behind an autonomous head never preempts it.
  1287. list.mockResolvedValueOnce([queueItem("thread-goal")] as never);
  1288. await expect(yields(goalItem as never)).resolves.toBe(false);
  1289. // Only the Goal source yields: an ordinary user item that a gate defers keeps
  1290. // blocking the queue, so nothing bypasses the questionnaire gate.
  1291. list.mockResolvedValueOnce([queueItem("api")] as never);
  1292. await expect(yields(userItem as never)).resolves.toBe(false);
  1293. expect(list).toHaveBeenCalledWith("session-1");
  1294. await services.close();
  1295. }
  1296. async function assertAskUserGateDefersQueueClassification(): Promise<void> {
  1297. const compatibility = defaultCompatibility();
  1298. const getPending = vi
  1299. .fn()
  1300. .mockResolvedValueOnce({ id: "question-1" } as never)
  1301. .mockResolvedValueOnce(undefined as never);
  1302. const classifyGoalItem = vi.mocked(
  1303. compatibility.sessionV2.goals.classifyQueuedItem,
  1304. );
  1305. const services = await createRuntimeServices({
  1306. db: {
  1307. select: () => ({
  1308. from: () => ({
  1309. where: () => ({ limit: () => ({ get: () => undefined }) }),
  1310. }),
  1311. }),
  1312. } as unknown as AppDb,
  1313. dataDir: "/data",
  1314. scheduler: {} as SchedulerClient,
  1315. eventBus: new EventBus<GlobalEvent>(),
  1316. compatibility: {
  1317. ...compatibility,
  1318. peripherals: { questionnaires: { getPending } } as never,
  1319. },
  1320. agentService: localAgentService,
  1321. });
  1322. const classifier = mocked.turnOptions?.classifyQueuedItem;
  1323. if (!classifier)
  1324. throw new Error("Turn System queue classifier was not composed");
  1325. const item = {
  1326. itemId: "queue-1",
  1327. sessionId: "session-1",
  1328. agentName: "mavis",
  1329. source: "api" as const,
  1330. status: "queued" as const,
  1331. message: { content: "send after AskUser", attachments: [] },
  1332. createdAt: 1,
  1333. };
  1334. await expect(classifier(item)).resolves.toBe("defer");
  1335. expect(getPending).toHaveBeenCalledWith({
  1336. agentName: "mavis",
  1337. sessionId: "session-1",
  1338. });
  1339. expect(classifyGoalItem).not.toHaveBeenCalled();
  1340. await expect(classifier(item)).resolves.toBe("ready");
  1341. expect(classifyGoalItem).toHaveBeenCalledWith(item, expect.any(Function));
  1342. await services.close();
  1343. }
  1344. async function assertQuestionnaireReplyBypassesAskUserGates(): Promise<void> {
  1345. const compatibility = defaultCompatibility();
  1346. const getPending = vi.fn(async () => ({ id: "question-1" }) as never);
  1347. const classifyGoalItem = vi.mocked(
  1348. compatibility.sessionV2.goals.classifyQueuedItem,
  1349. );
  1350. const services = await createRuntimeServices({
  1351. db: {
  1352. select: () => ({
  1353. from: () => ({
  1354. where: () => ({ limit: () => ({ get: () => undefined }) }),
  1355. }),
  1356. }),
  1357. } as unknown as AppDb,
  1358. dataDir: "/data",
  1359. scheduler: {} as SchedulerClient,
  1360. eventBus: new EventBus<GlobalEvent>(),
  1361. compatibility: {
  1362. ...compatibility,
  1363. peripherals: { questionnaires: { getPending } } as never,
  1364. },
  1365. agentService: localAgentService,
  1366. });
  1367. const classifier = mocked.turnOptions?.classifyQueuedItem;
  1368. if (!classifier)
  1369. throw new Error("Turn System queue classifier was not composed");
  1370. // The queued reply is the message that resolves the questionnaire the
  1371. // gates wait on: even with a pending AskUser reported, it must dispatch.
  1372. const item = {
  1373. itemId: "queue-reply-1",
  1374. sessionId: "session-1",
  1375. agentName: "mavis",
  1376. source: "questionnaire" as const,
  1377. status: "queued" as const,
  1378. message: {
  1379. content: "<questionnaire-response />",
  1380. attachments: [],
  1381. origin: {
  1382. kind: "questionnaire-response",
  1383. requestId: "request-1",
  1384. mode: "questionnaire",
  1385. purpose: "ordinary",
  1386. },
  1387. },
  1388. createdAt: 1,
  1389. };
  1390. await expect(classifier(item)).resolves.toBe("ready");
  1391. expect(getPending).not.toHaveBeenCalled();
  1392. expect(classifyGoalItem).not.toHaveBeenCalled();
  1393. await services.close();
  1394. }
  1395. async function assertImportedSessionPinBinding(): Promise<void> {
  1396. const raw = new Database(":memory:");
  1397. const db = migratePluginTestDatabase(raw);
  1398. const services = await createRuntimeServices({
  1399. db,
  1400. dataDir: "/data",
  1401. scheduler: {} as SchedulerClient,
  1402. eventBus: new EventBus<GlobalEvent>(),
  1403. compatibility: defaultCompatibility(),
  1404. agentService: localAgentService,
  1405. });
  1406. try {
  1407. const onImported = mocked.sessionOptions?.["onPinnedSessionImported"] as
  1408. | ((sessionId: string) => Promise<void>)
  1409. | undefined;
  1410. if (!onImported)
  1411. throw new Error("Imported Session Pin callback was not composed");
  1412. await onImported("recovered-session");
  1413. expect(readPreferenceValue(db, "pinned-items-order")).toEqual([
  1414. { type: "session", id: "recovered-session" },
  1415. ]);
  1416. } finally {
  1417. await services.close();
  1418. raw.close();
  1419. }
  1420. }
  1421. async function assertCanonicalSessionRecoveryLogging(): Promise<void> {
  1422. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1423. await createRuntimeServices({
  1424. db: {} as AppDb,
  1425. dataDir: "/data",
  1426. logger,
  1427. scheduler: {} as SchedulerClient,
  1428. eventBus: new EventBus<GlobalEvent>(),
  1429. compatibility: defaultCompatibility(),
  1430. agentService: localAgentService,
  1431. });
  1432. const onCanonicalRecovery = (
  1433. mocked.sessionOptions?.["legacyMigration"] as {
  1434. readonly onCanonicalRecovery: (event: Record<string, unknown>) => void;
  1435. }
  1436. ).onCanonicalRecovery;
  1437. const event = {
  1438. session_id: "session-1",
  1439. trigger: "source_missing",
  1440. result: "recovered",
  1441. };
  1442. onCanonicalRecovery(event);
  1443. expect(logger.info).toHaveBeenCalledWith(
  1444. event,
  1445. "[local-runtime-v2] legacy Session canonical recovery",
  1446. );
  1447. }
  1448. describe("runtime services composition", () => {
  1449. it.each([false, true])(
  1450. "keeps source hooks and projection disabled for every build identity (internal=%s)",
  1451. async (internal) => {
  1452. vi.stubEnv("__MAVIS_BUILD_INTERNAL", String(internal));
  1453. vi.stubEnv("__MAVIS_BUILD_INSIDE", "false");
  1454. const services = await createRuntimeServices({
  1455. db: {} as AppDb,
  1456. dataDir: "/data",
  1457. scheduler: {} as SchedulerClient,
  1458. eventBus: new EventBus<GlobalEvent>(),
  1459. compatibility: defaultCompatibility(),
  1460. agentService: localAgentService,
  1461. runtimeOwnerKind: "electron",
  1462. promptConfigKey: new Uint8Array(32).fill(7),
  1463. });
  1464. const extensions = mocked.agentHostOptions?.[
  1465. "normalExtensions"
  1466. ] as readonly AgentExtension[];
  1467. expect(extensions.some(({ id }) => id === "source-reference")).toBe(
  1468. false,
  1469. );
  1470. expect(mocked.sessionOptions?.["sourceProjectionEnabled"]).toBe(false);
  1471. await services.close();
  1472. },
  1473. );
  1474. it(
  1475. "assembles the owner graph and exposes a read-only global event facade",
  1476. assertRuntimeServicesComposition,
  1477. );
  1478. it(
  1479. "resolves workspace bash file sources",
  1480. assertWorkspaceBashFileSourceResolution,
  1481. );
  1482. it(
  1483. "binds imported Session Pin recovery before the service graph is returned",
  1484. assertImportedSessionPinBinding,
  1485. );
  1486. it(
  1487. "routes canonical Session recovery events through the runtime logger",
  1488. assertCanonicalSessionRecoveryLogging,
  1489. );
  1490. it("owns an explicitly provided MiniApp Host capability without changing the default graph", async () => {
  1491. const services = await createRuntimeServices({
  1492. db: {} as AppDb,
  1493. dataDir: "/data",
  1494. scheduler: {} as SchedulerClient,
  1495. eventBus: new EventBus<GlobalEvent>(),
  1496. compatibility: defaultCompatibility(),
  1497. agentService: localAgentService,
  1498. miniApp: {},
  1499. });
  1500. expect(services.miniApp).toBe(mocked.miniAppSupervisor);
  1501. assertProcessLocalMiniAppComposition();
  1502. expect(mocked.miniAppOptions).toMatchObject({
  1503. db: {},
  1504. connectorGateway: mocked.hostConnectorGateway,
  1505. verifyCandidate: expect.any(Function),
  1506. materializePackage: expect.any(Function),
  1507. resolvePluginDataDir: expect.any(Function),
  1508. });
  1509. expect(mocked.events).toContain("plugin:attach-miniapp");
  1510. expect(mocked.events.indexOf("plugin:attach-miniapp")).toBeLessThan(
  1511. mocked.events.indexOf("turn:create"),
  1512. );
  1513. expect(
  1514. (
  1515. mocked.agentHostOptions?.["normalExtensions"] as readonly {
  1516. readonly id: string;
  1517. }[]
  1518. ).map(({ id }) => id),
  1519. ).toContain("miniapp-control");
  1520. expect(
  1521. (
  1522. mocked.agentHostOptions?.["product"] as {
  1523. readonly preparation: {
  1524. readonly configBuilder: { readonly miniappAvailable: boolean };
  1525. };
  1526. }
  1527. ).preparation.configBuilder.miniappAvailable,
  1528. ).toBe(true);
  1529. const materializePackage = mocked.miniAppOptions?.[
  1530. "materializePackage"
  1531. ] as (input: {
  1532. readonly sourceRoot: string;
  1533. readonly targetRoot: string;
  1534. }) => Promise<void>;
  1535. await materializePackage({
  1536. sourceRoot: "/workspace",
  1537. targetRoot: "/runtime",
  1538. });
  1539. expect(mocked.materializeMiniAppRuntimePackage).toHaveBeenCalledWith({
  1540. sourceRoot: "/workspace",
  1541. targetRoot: "/runtime",
  1542. });
  1543. mocked.events.length = 0;
  1544. await services.ready();
  1545. expect(mocked.miniAppSupervisor.ready).toHaveBeenCalledOnce();
  1546. expect(mocked.events.indexOf("miniapp:ready")).toBeGreaterThan(
  1547. mocked.events.indexOf("plugin:ready"),
  1548. );
  1549. mocked.events.length = 0;
  1550. await services.close();
  1551. expect(mocked.events).toContain("plugin:close");
  1552. expect(mocked.events).toContain("session:close");
  1553. expect(mocked.events.indexOf("miniapp:close")).toBeGreaterThan(
  1554. mocked.events.indexOf("plugin:close"),
  1555. );
  1556. expect(mocked.events.indexOf("miniapp:close")).toBeGreaterThan(
  1557. mocked.events.indexOf("session:close"),
  1558. );
  1559. });
  1560. it(
  1561. "preserves startup failure while draining PluginSystem before the Electron Supervisor",
  1562. assertMiniAppStartupFailureCleanup,
  1563. );
  1564. it(
  1565. "defers queue classification during AskUser and resumes it once clear",
  1566. assertAskUserGateDefersQueueClassification,
  1567. );
  1568. it(
  1569. "admits a queued questionnaire reply without consulting the AskUser gates",
  1570. assertQuestionnaireReplyBypassesAskUserGates,
  1571. );
  1572. it("generates a session title when sessionTitle.enabled is true (default)", async () => {
  1573. const services = await createRuntimeServices({
  1574. db: {} as AppDb,
  1575. dataDir: "/data",
  1576. scheduler: {} as SchedulerClient,
  1577. eventBus: new EventBus<GlobalEvent>(),
  1578. compatibility: defaultCompatibility(),
  1579. agentService: localAgentService,
  1580. });
  1581. mocked.sessionSystem.messages.repository.listTurn.mockResolvedValue([
  1582. { msg_id: "m1", role: "user", msg_content: "Ship the objective" },
  1583. ]);
  1584. const onInputReviewResolved = mocked.agentHostOptions?.[
  1585. "onInputReviewResolved"
  1586. ] as InputReviewResolved;
  1587. onInputReviewResolved({
  1588. sessionId: "session-1",
  1589. turnId: "turn-1",
  1590. userInput: "approved input",
  1591. rejected: false,
  1592. });
  1593. await vi.waitFor(() =>
  1594. expect(mocked.sessionSystem.titles.generate).toHaveBeenCalledOnce(),
  1595. );
  1596. await services.close();
  1597. });
  1598. it("wires a no-op title handler when the injected sessionTitle.enabled is false", async () => {
  1599. (
  1600. mocked.modelConfig as { sessionTitle?: { enabled: boolean } }
  1601. ).sessionTitle = {
  1602. enabled: false,
  1603. };
  1604. try {
  1605. const services = await createRuntimeServices({
  1606. db: {} as AppDb,
  1607. dataDir: "/data",
  1608. scheduler: {} as SchedulerClient,
  1609. eventBus: new EventBus<GlobalEvent>(),
  1610. compatibility: defaultCompatibility(),
  1611. agentService: localAgentService,
  1612. });
  1613. mocked.sessionSystem.messages.repository.listTurn.mockResolvedValue([
  1614. { msg_id: "m1", role: "user", msg_content: "Ship the objective" },
  1615. ]);
  1616. const onInputReviewResolved = mocked.agentHostOptions?.[
  1617. "onInputReviewResolved"
  1618. ] as InputReviewResolved;
  1619. onInputReviewResolved({
  1620. sessionId: "session-1",
  1621. turnId: "turn-1",
  1622. userInput: "approved input",
  1623. rejected: false,
  1624. });
  1625. // No-op handler: the title model request and the message read must never fire.
  1626. await new Promise((resolve) => setTimeout(resolve, 20));
  1627. expect(mocked.sessionSystem.titles.generate).not.toHaveBeenCalled();
  1628. expect(
  1629. mocked.sessionSystem.messages.repository.listTurn,
  1630. ).not.toHaveBeenCalled();
  1631. await services.close();
  1632. } finally {
  1633. delete (mocked.modelConfig as { sessionTitle?: { enabled: boolean } })
  1634. .sessionTitle;
  1635. }
  1636. });
  1637. });
  1638. describe("runtime services Goal queue composition", () => {
  1639. it(
  1640. "hands the Plan fence reader to Goal queue classification without replacing the shared gates",
  1641. assertGoalQueueReadsPlanFence,
  1642. );
  1643. it(
  1644. "lets a blocked Goal item yield the FIFO head to queued user work only",
  1645. assertGoalQueueYieldsToUserWork,
  1646. );
  1647. });
  1648. async function assertRuntimeServicesComposition() {
  1649. const db = {} as AppDb;
  1650. const scheduler = {} as SchedulerClient;
  1651. const metrics = { counter: vi.fn(), histogram: vi.fn() };
  1652. const eventBus = new EventBus<GlobalEvent>();
  1653. const compatibility = defaultCompatibility();
  1654. const nowMs = () => 1_700_000_000_000;
  1655. const services = await createRuntimeServices({
  1656. db,
  1657. dataDir: "/data",
  1658. logger: noopLogger,
  1659. scheduler,
  1660. metrics,
  1661. eventBus,
  1662. compatibility,
  1663. agentService: localAgentService,
  1664. nowMs,
  1665. });
  1666. const projectedEvents: GlobalEvent[] = [];
  1667. services.globalEvents.subscribe({
  1668. next: (event) => projectedEvents.push(event),
  1669. });
  1670. expect(mocked.events).toEqual([
  1671. "session:create",
  1672. "channel:create",
  1673. "mcp:create",
  1674. "plugin:create",
  1675. "turn:create",
  1676. "session-applications:create",
  1677. "applications:create",
  1678. "cron:create",
  1679. ]);
  1680. expect(mocked.channelOptions).toEqual({
  1681. messages: mocked.sessionSystem.messages.repository,
  1682. sessions: mocked.sessionSystem.sessions.repository,
  1683. product: compatibility.channel,
  1684. });
  1685. expect(mocked.agentHostOptions).toMatchObject({
  1686. preparation: mocked.agentPreparation,
  1687. sessions: mocked.sessionSystem,
  1688. safety: services.safety,
  1689. turnCapabilities: mocked.pluginTurnCapabilities,
  1690. onInputReviewResolved: expect.any(Function),
  1691. eventObserver: {
  1692. observers: [
  1693. mocked.channelSystem.terminalReplies,
  1694. expect.objectContaining({ observeRuntimeEvent: expect.any(Function) }),
  1695. ],
  1696. },
  1697. });
  1698. expect(mocked.agentHostOptions).not.toHaveProperty("contentReviewEnabled");
  1699. expect(mocked.agentHostOptions).not.toHaveProperty("tuiProductPolicy");
  1700. expect(mocked.agentHostOptions).not.toHaveProperty("cliProductPolicy");
  1701. const composedProduct = mocked.agentHostOptions?.["product"] as {
  1702. readonly agents: { readonly getExecutionSnapshot: unknown };
  1703. readonly preparation: {
  1704. readonly configBuilder: {
  1705. readonly nowMs?: () => number;
  1706. readonly profile?: { readonly render: unknown };
  1707. };
  1708. };
  1709. };
  1710. expect(composedProduct).not.toBe(compatibility.agentHost);
  1711. expect(composedProduct.agents.getExecutionSnapshot).toEqual(
  1712. expect.any(Function),
  1713. );
  1714. expect(composedProduct.preparation.configBuilder.nowMs).toBe(nowMs);
  1715. expect(composedProduct.preparation.configBuilder.profile?.render).toEqual(
  1716. expect.any(Function),
  1717. );
  1718. expect(mocked.turnOptions).toMatchObject({
  1719. processStartedAtMs: 1_700_000_000_000,
  1720. });
  1721. expect(queryCollapseMocked.keyResolverOptions).toEqual({
  1722. state: mocked.sessionSystem.queryCollapse.state,
  1723. messages: mocked.sessionSystem.messages.repository,
  1724. getGoalBySession: compatibility.sessionV2.goals.getBySession,
  1725. });
  1726. expect(queryCollapseMocked.deliveryOptions).toMatchObject({
  1727. messages: mocked.sessionSystem.messages.userMessages,
  1728. stream: mocked.sessionSystem.stream,
  1729. queryCollapse: {
  1730. resolveQueryKey: expect.any(Function),
  1731. start: expect.any(Function),
  1732. },
  1733. });
  1734. const queryCollapse = queryCollapseMocked.deliveryOptions?.[
  1735. "queryCollapse"
  1736. ] as {
  1737. readonly resolveQueryKey: (
  1738. sessionId: string,
  1739. turnId: string,
  1740. input?: { readonly reuseLatestVisibleQuery?: boolean },
  1741. ) => Promise<string>;
  1742. readonly start: (input: QueryCollapseStartInput) => Promise<unknown>;
  1743. };
  1744. await expect(
  1745. queryCollapse.resolveQueryKey("session-1", "turn-1"),
  1746. ).resolves.toBe("turn:turn-1");
  1747. await expect(
  1748. queryCollapse.resolveQueryKey("session-1", "turn-2", {
  1749. reuseLatestVisibleQuery: true,
  1750. }),
  1751. ).resolves.toBe("turn:turn-2");
  1752. const queryCollapseState = mocked.sessionSystem.queryCollapse.state;
  1753. await queryCollapse.start({
  1754. sessionId: "session-1",
  1755. queryKey: "turn:turn-1",
  1756. currentTurnId: "turn-1",
  1757. });
  1758. expect(queryCollapseMocked.keys.queryKeyForTurn).toHaveBeenCalledWith(
  1759. "session-1",
  1760. "turn-1",
  1761. );
  1762. expect(queryCollapseMocked.keys.queryKeyForContinuation).toHaveBeenCalledWith(
  1763. "session-1",
  1764. "turn-2",
  1765. );
  1766. expect(queryCollapseState.start).toHaveBeenCalledWith({
  1767. sessionId: "session-1",
  1768. queryKey: "turn:turn-1",
  1769. currentTurnId: "turn-1",
  1770. });
  1771. expect(mocked.sessionTitleOptions).toEqual({
  1772. agents: composedProduct.agents,
  1773. preparation: mocked.agentPreparation,
  1774. });
  1775. expect(mocked.archiveTitleOptions).toMatchObject({
  1776. safety: services.safety,
  1777. });
  1778. expect(mocked.createSessionModelRepair).toHaveBeenCalledWith(
  1779. mocked.sessionSystem.sessions.records,
  1780. noopLogger,
  1781. );
  1782. expect(mocked.cronOptions).toEqual({
  1783. db,
  1784. scheduler,
  1785. metrics,
  1786. sessionPorts: expect.any(Object),
  1787. modelSelection: { resolve: expect.any(Function) },
  1788. nowMs,
  1789. recoverPendingRuns: true,
  1790. });
  1791. expect(mocked.sessionOptions).toMatchObject({
  1792. facts: mocked.applicationFactPorts.session,
  1793. queueFacts: mocked.applicationFactPorts.queue,
  1794. compactionFacts: { handle: expect.any(Function) },
  1795. title: {
  1796. model: mocked.sessionTitleModel,
  1797. onOutcome: expect.any(Function),
  1798. onFailure: expect.any(Function),
  1799. },
  1800. });
  1801. expect(mocked.applicationOptions).toMatchObject({
  1802. metrics,
  1803. attachmentRegistration: compatibility.attachmentRegistration,
  1804. });
  1805. const directSend = mocked.conversationApplicationOptions?.["directSend"] as {
  1806. readonly options: Record<string, unknown>;
  1807. };
  1808. expect(directSend.options).not.toHaveProperty("workspaceGate");
  1809. // preview_train moved content-safety review out of ConversationApplication into
  1810. // the turn-system production composition; this guard keeps it from creeping back.
  1811. expect(mocked.conversationApplicationOptions).not.toHaveProperty("safety");
  1812. expect(mocked.conversationApplicationOptions).toMatchObject({
  1813. attachmentRegistration: compatibility.attachmentRegistration,
  1814. threadGoal: {
  1815. pauseActiveForAbort: compatibility.sessionV2.goals.pauseActiveForAbort,
  1816. },
  1817. });
  1818. expect(mocked.conversationApplicationOptions).not.toHaveProperty(
  1819. "workspaceGate",
  1820. );
  1821. expect(mocked.attachmentMaterializerOptions).toEqual({
  1822. registration: compatibility.attachmentRegistration,
  1823. });
  1824. expect(mocked.conversationOptions).toMatchObject({
  1825. attachmentMaterializer: mocked.attachmentMaterializer,
  1826. submission: mocked.v1Submission,
  1827. });
  1828. await assertSessionCompositionPolicies({
  1829. compatibility,
  1830. metricsCounter: metrics.counter,
  1831. projectedEvents,
  1832. });
  1833. expect(services.cron).toBe(mocked.service);
  1834. expect(services.channelSystem).toBe(mocked.channelSystem);
  1835. expect(services.cronDelivery?.deliver).toEqual(expect.any(Function));
  1836. expect(services.plugin).toBe(mocked.plugin);
  1837. expect(services.mcp).toBe(mocked.mcpSettings);
  1838. await assertModelProviderComposition(services, compatibility);
  1839. expect(services.skill).toBe(mocked.runtimeSkillApplication);
  1840. expect(mocked.cleanupServices).toEqual([mocked.service]);
  1841. expect(mocked.conversationBindings).toEqual([]);
  1842. expect(services.safety).toEqual(expect.any(Object));
  1843. expect(services.conversation).toBe(mocked.conversationApplication);
  1844. expect(services.globalEvents.subscribe).toEqual(expect.any(Function));
  1845. expect(services.globalEvents).not.toHaveProperty("write");
  1846. expect(services.applications).toBe(mocked.runtimeApplications);
  1847. await assertRuntimeReadyAndAuth(services);
  1848. }
  1849. async function assertRuntimeReadyAndAuth(
  1850. services: RuntimeServices,
  1851. ): Promise<void> {
  1852. services.notifyAuthContextChanged();
  1853. expect(mocked.events).toContain("plugin:auth-context-changed");
  1854. await services.ready();
  1855. expect(mocked.conversationBindings).toEqual([mocked.conversationService]);
  1856. }
  1857. async function assertModelProviderComposition(
  1858. services: RuntimeServices,
  1859. compatibility: V1ServiceCompatibility,
  1860. ): Promise<void> {
  1861. expect(services.modelSystem.resolver).toEqual(expect.any(Object));
  1862. expect(services.modelSystem.providers).toEqual(expect.any(Object));
  1863. expect(services.modelSystem.oauth).toEqual(expect.any(Object));
  1864. expect(services.modelProviderApplication).toEqual(expect.any(Object));
  1865. await services.modelProviderApplication.refresh();
  1866. expect(
  1867. compatibility.modelProvider?.refreshOfficialModels,
  1868. ).toHaveBeenCalledOnce();
  1869. expect(mocked.agentPreparationOptions?.modelResolver).toBe(
  1870. services.modelSystem.resolver,
  1871. );
  1872. expect(mocked.processLocalApplicationOptions).toMatchObject({
  1873. modelProvider: {
  1874. application: services.modelProviderApplication,
  1875. providers: services.modelSystem.providers,
  1876. listProviderPresets: services.modelSystem.listProviderPresets,
  1877. oauth: services.modelSystem.oauth,
  1878. },
  1879. });
  1880. }
  1881. function assertProcessLocalMiniAppComposition(): void {
  1882. expect(mocked.processLocalApplicationOptions).toMatchObject({
  1883. miniApps: {
  1884. list: expect.any(Function),
  1885. open: expect.any(Function),
  1886. stop: expect.any(Function),
  1887. },
  1888. });
  1889. }
  1890. describe("runtime services CLI composition", () => {
  1891. it.each([true, false])(
  1892. "keeps Electron prompts local with autoUpdate=%s",
  1893. async (autoUpdate) => {
  1894. const compatibility = defaultCompatibility();
  1895. Object.assign(compatibility, { promptConfig: { autoUpdate } });
  1896. const services = await createRuntimeServices({
  1897. db: {} as AppDb,
  1898. dataDir: "/data/prompt-update-disabled",
  1899. logger: noopLogger,
  1900. scheduler: {} as SchedulerClient,
  1901. eventBus: new EventBus<GlobalEvent>(),
  1902. compatibility,
  1903. agentService: localAgentService,
  1904. runtimeOwnerKind: "electron",
  1905. });
  1906. expect(mocked.agentService.bindPromptConfig).not.toHaveBeenCalled();
  1907. expect(compatibility.promptSnapshots.bind).toHaveBeenCalledWith(
  1908. undefined,
  1909. );
  1910. await services.close();
  1911. },
  1912. );
  1913. it("composes the CLI core without Channel or Cron owners and keeps ready ordering explicit", async () => {
  1914. const services = await createRuntimeServices({
  1915. db: {} as AppDb,
  1916. dataDir: "/data/cli",
  1917. logger: noopLogger,
  1918. eventBus: new EventBus<GlobalEvent>(),
  1919. compatibility: defaultCompatibility(),
  1920. agentService: localAgentService,
  1921. runtimeOwnerKind: "cli",
  1922. capabilityProfile: "cli",
  1923. });
  1924. expect(mocked.events).toEqual([
  1925. "session:create",
  1926. "mcp:create",
  1927. "plugin:create",
  1928. "turn:create",
  1929. "session-applications:create",
  1930. "applications:create",
  1931. ]);
  1932. expect(services.channelSystem).toBeUndefined();
  1933. expect(services.cron).toBeUndefined();
  1934. expect(services.cronDelivery).toBeUndefined();
  1935. expect(mocked.agentService.bindPromptConfig).not.toHaveBeenCalled();
  1936. expect(services.plugin).toBe(mocked.plugin);
  1937. expect(services.mcp).toBe(mocked.mcpSettings);
  1938. expect(services.skill).toBe(mocked.runtimeSkillApplication);
  1939. const processLocalSkills = mocked.processLocalApplicationOptions?.[
  1940. "skills"
  1941. ] as
  1942. | {
  1943. listRuntimeSkills(input: {
  1944. agentName?: string;
  1945. includePluginSkills?: boolean;
  1946. }): Promise<unknown>;
  1947. }
  1948. | undefined;
  1949. await processLocalSkills?.listRuntimeSkills({
  1950. agentName: "mavis",
  1951. includePluginSkills: true,
  1952. });
  1953. expect(
  1954. mocked.runtimeSkillApplication.listRuntimeSkills,
  1955. ).toHaveBeenCalledWith({
  1956. agentName: "mavis",
  1957. includePluginSkills: true,
  1958. });
  1959. expect(mocked.agentHostOptions).toMatchObject({
  1960. cliProductPolicy: true,
  1961. });
  1962. expect(mocked.agentHostOptions).not.toHaveProperty("tuiProductPolicy");
  1963. expect(mocked.agentHostOptions).not.toHaveProperty("contentReviewEnabled");
  1964. mocked.events.length = 0;
  1965. await services.ready();
  1966. expect(mocked.events).toEqual([
  1967. "session:ready",
  1968. "plan-documents:reconcile",
  1969. "mcp:ready",
  1970. "plugin:ready",
  1971. "turn:ready",
  1972. "conversation:bind",
  1973. "questionnaire:recover",
  1974. "questionnaire:plan-reconcile:true",
  1975. ]);
  1976. await expect(services.builtinAgentDefinitionsReady).resolves.toBe(true);
  1977. expect(mocked.events.at(-1)).toBe("agent:ensure");
  1978. });
  1979. /**
  1980. * The Inspector is composed on a test build, so composition must tolerate a
  1981. * product that carries no model resolver at all. Reading `.fetchImpl` off an
  1982. * absent resolver used to throw and take the whole runtime graph down, and
  1983. * skipping the wrapper entirely left hosts without a resolved transport (TUI)
  1984. * publishing every captured Call with a missing request payload.
  1985. */
  1986. it("composes without a model resolver and captures through the global transport", async () => {
  1987. const compatibility = defaultCompatibility();
  1988. const globalFetch = vi.fn(async () => new Response("{}"));
  1989. const originalFetch = globalThis.fetch;
  1990. globalThis.fetch = globalFetch as unknown as typeof fetch;
  1991. try {
  1992. const services = await createRuntimeServices({
  1993. db: {} as AppDb,
  1994. dataDir: "/data/no-resolver",
  1995. logger: noopLogger,
  1996. scheduler: {} as SchedulerClient,
  1997. eventBus: new EventBus<GlobalEvent>(),
  1998. compatibility,
  1999. agentService: localAgentService,
  2000. runtimeOwnerKind: "electron",
  2001. promptConfigKey: new Uint8Array(32).fill(7),
  2002. });
  2003. expect(services).toBeDefined();
  2004. expect(mocked.agentService.bindPromptConfig).not.toHaveBeenCalled();
  2005. const composedProduct = mocked.agentHostOptions?.["product"] as {
  2006. readonly preparation: {
  2007. readonly modelResolver?: { readonly fetchImpl?: typeof fetch };
  2008. };
  2009. };
  2010. const composedFetch =
  2011. composedProduct.preparation.modelResolver?.fetchImpl;
  2012. // No host transport, but the provider SDK would still reach the global
  2013. // fetch, so capture has to observe that request rather than skip it.
  2014. expect(composedFetch).toBeTypeOf("function");
  2015. await composedFetch?.("https://example.invalid/v1/messages");
  2016. // Verify provider capture independently of the disabled prompt control plane.
  2017. expect(
  2018. vi
  2019. .mocked(globalThis.fetch)
  2020. .mock.calls.filter(
  2021. ([request]) => request === "https://example.invalid/v1/messages",
  2022. ),
  2023. ).toHaveLength(1);
  2024. } finally {
  2025. globalThis.fetch = originalFetch;
  2026. }
  2027. });
  2028. it("decorates the host transport for capture rather than replacing it", async () => {
  2029. const compatibility = defaultCompatibility();
  2030. const hostFetch = vi.fn(async () => new Response("{}"));
  2031. (
  2032. compatibility.agentHost.preparation as unknown as {
  2033. modelResolver: { fetchImpl: typeof hostFetch };
  2034. }
  2035. ).modelResolver = { fetchImpl: hostFetch };
  2036. await createRuntimeServices({
  2037. db: {} as AppDb,
  2038. dataDir: "/data/with-resolver",
  2039. logger: noopLogger,
  2040. scheduler: {} as SchedulerClient,
  2041. eventBus: new EventBus<GlobalEvent>(),
  2042. compatibility,
  2043. agentService: localAgentService,
  2044. runtimeOwnerKind: "electron",
  2045. promptConfigKey: new Uint8Array(32).fill(7),
  2046. });
  2047. const composedProduct = mocked.agentHostOptions?.["product"] as {
  2048. readonly preparation: {
  2049. readonly modelResolver: { readonly fetchImpl: typeof fetch };
  2050. };
  2051. };
  2052. const composedFetch = composedProduct.preparation.modelResolver.fetchImpl;
  2053. // A wrapper, not the original — and the original still performs the request,
  2054. // so the Electron proxy/net fetch is never discarded.
  2055. expect(composedFetch).not.toBe(hostFetch);
  2056. await composedFetch("https://example.invalid/v1/messages");
  2057. expect(hostFetch).toHaveBeenCalledTimes(1);
  2058. });
  2059. /**
  2060. * TUI opts into capture through the environment variable but composes no host
  2061. * transport. A wrapper that only decorated an existing transport left every
  2062. * captured Call publishing `CAPTURE_FAILED` for its request while the
  2063. * reassembled response still landed, which is not an observable failure the
  2064. * Inspector can explain to the developer reading it.
  2065. */
  2066. it("captures TUI requests even though the host composes no transport", async () => {
  2067. const compatibility = defaultCompatibility();
  2068. const globalFetch = vi.fn(async () => new Response("{}"));
  2069. const originalFetch = globalThis.fetch;
  2070. const originalOptIn = process.env.MAVIS_TUI_LLM_CONTEXT_INSPECTOR;
  2071. globalThis.fetch = globalFetch as unknown as typeof fetch;
  2072. process.env.MAVIS_TUI_LLM_CONTEXT_INSPECTOR = "1";
  2073. try {
  2074. await createRuntimeServices({
  2075. db: {} as AppDb,
  2076. dataDir: "/data/tui-inspector",
  2077. logger: noopLogger,
  2078. scheduler: {} as SchedulerClient,
  2079. eventBus: new EventBus<GlobalEvent>(),
  2080. compatibility,
  2081. agentService: localAgentService,
  2082. runtimeOwnerKind: "tui",
  2083. capabilityProfile: "cli",
  2084. promptConfigKey: new Uint8Array(32).fill(7),
  2085. });
  2086. // Provider-preset refresh owns its own best-effort background request.
  2087. // Count it separately so this contract stays about the captured provider
  2088. // request composed below.
  2089. const startupFetchCount = globalFetch.mock.calls.length;
  2090. const composedProduct = mocked.agentHostOptions?.["product"] as {
  2091. readonly preparation: {
  2092. readonly modelResolver?: { readonly fetchImpl?: typeof fetch };
  2093. };
  2094. };
  2095. const composedFetch =
  2096. composedProduct.preparation.modelResolver?.fetchImpl;
  2097. expect(composedFetch).toBeTypeOf("function");
  2098. await composedFetch?.("https://example.invalid/v1/messages");
  2099. expect(globalFetch).toHaveBeenCalledTimes(startupFetchCount + 1);
  2100. expect(globalFetch).toHaveBeenLastCalledWith(
  2101. "https://example.invalid/v1/messages",
  2102. undefined,
  2103. );
  2104. } finally {
  2105. globalThis.fetch = originalFetch;
  2106. if (originalOptIn === undefined)
  2107. delete process.env.MAVIS_TUI_LLM_CONTEXT_INSPECTOR;
  2108. else process.env.MAVIS_TUI_LLM_CONTEXT_INSPECTOR = originalOptIn;
  2109. }
  2110. });
  2111. });
  2112. describe("runtime services agent profile composition", () => {
  2113. it("selects task-child prompts only for hidden task-purpose branches and preserves frozen read refs", async () => {
  2114. mocked.agentService.renderProfile.mockImplementation(
  2115. async (input: {
  2116. readonly exactOwnerName: string;
  2117. readonly surface?: string;
  2118. }) =>
  2119. ({
  2120. requestRef: "main",
  2121. resourceReadRef: "mavis",
  2122. exactOwnerName: input.exactOwnerName,
  2123. canonicalViewName: "mavis",
  2124. resolvedAgentName: "mavis",
  2125. agentRole: "orchestrator",
  2126. creationSource: "builtin",
  2127. surface: input.surface ?? "interactive",
  2128. memoryReadAgentNames: ["mavis", "main"],
  2129. corePrompt: "core",
  2130. surfacePrompt: "surface",
  2131. capabilityCeiling: {
  2132. personaEnabled: true,
  2133. features: { mavis: false, delegation: false, webSearch: false },
  2134. },
  2135. provenance: {
  2136. source: "legacy-read-through",
  2137. assetAgentName: "mavis",
  2138. locale: "en-US",
  2139. },
  2140. }) as never,
  2141. );
  2142. await createRuntimeServices({
  2143. db: {} as AppDb,
  2144. dataDir: "/data",
  2145. eventBus: new EventBus<GlobalEvent>(),
  2146. compatibility: defaultCompatibility(),
  2147. agentService: localAgentService,
  2148. runtimeOwnerKind: "cli",
  2149. capabilityProfile: "cli",
  2150. });
  2151. const profile = (
  2152. mocked.agentHostOptions?.["product"] as {
  2153. readonly preparation: {
  2154. readonly configBuilder: {
  2155. readonly profile: {
  2156. render(input: {
  2157. readonly session: unknown;
  2158. readonly agent: unknown;
  2159. }): Promise<{
  2160. readonly resourceReadRef: string;
  2161. readonly memoryReadAgentNames: readonly string[];
  2162. }>;
  2163. };
  2164. };
  2165. };
  2166. }
  2167. ).preparation.configBuilder.profile;
  2168. const agent = {
  2169. agentName: "main",
  2170. metadata: { requestRef: "main" },
  2171. };
  2172. const cases = [
  2173. {
  2174. sessionType: "branch",
  2175. sessionKind: "task",
  2176. parentSessionId: "parent",
  2177. visibility: "hidden",
  2178. purpose: "local-task:turn:tool",
  2179. expected: "task-child",
  2180. },
  2181. {
  2182. sessionType: "branch",
  2183. sessionKind: "task",
  2184. parentSessionId: "parent",
  2185. visibility: "hidden",
  2186. purpose: "local-background-task:task:delivery",
  2187. expected: "task-child",
  2188. },
  2189. {
  2190. sessionType: "branch",
  2191. sessionKind: "task",
  2192. parentSessionId: "parent",
  2193. visibility: "hidden",
  2194. purpose: "team-plan:plan:task",
  2195. expected: "task-child",
  2196. },
  2197. {
  2198. sessionType: "branch",
  2199. sessionKind: "conversation",
  2200. parentSessionId: "parent",
  2201. visibility: "visible",
  2202. purpose: "local-task:turn:tool",
  2203. expected: "cli",
  2204. },
  2205. {
  2206. sessionType: "branch",
  2207. sessionKind: "task",
  2208. parentSessionId: "parent",
  2209. visibility: "visible",
  2210. purpose: "direct-child",
  2211. expected: "task-child",
  2212. },
  2213. {
  2214. sessionType: "root",
  2215. sessionKind: "cron",
  2216. parentSessionId: null,
  2217. visibility: "visible",
  2218. purpose: "cron:run",
  2219. expected: "cli",
  2220. },
  2221. {
  2222. sessionType: "branch",
  2223. sessionKind: "channel",
  2224. parentSessionId: "parent",
  2225. visibility: "hidden",
  2226. purpose: "channel:message",
  2227. expected: "cli",
  2228. },
  2229. ] as const;
  2230. for (const entry of cases) {
  2231. const rendered = await profile.render({
  2232. session: {
  2233. sessionId: `session-${entry.sessionKind}-${entry.expected}`,
  2234. agentName: "main",
  2235. workspaceDir: "/workspace",
  2236. runtime: "pi-agent",
  2237. archived: false,
  2238. status: "idle",
  2239. createdAtMs: 1,
  2240. updatedAtMs: 1,
  2241. ...entry,
  2242. },
  2243. agent,
  2244. });
  2245. expect(rendered).toMatchObject({
  2246. resourceReadRef: "mavis",
  2247. memoryReadAgentNames: ["mavis", "main"],
  2248. });
  2249. }
  2250. expect(
  2251. mocked.agentService.renderProfile.mock.calls.map(
  2252. ([input]) => input.surface,
  2253. ),
  2254. ).toEqual(cases.map((entry) => entry.expected));
  2255. expect(mocked.agentService.renderProfile.mock.calls).toEqual(
  2256. cases.map(() => [
  2257. expect.objectContaining({
  2258. memoryEnabled: false,
  2259. cronEnabled: false,
  2260. capabilities: expect.objectContaining({
  2261. features: expect.objectContaining({ mavis: false }),
  2262. }),
  2263. }),
  2264. ]),
  2265. );
  2266. });
  2267. });
  2268. describe("runtime startup preserves Session model selections", () => {
  2269. it.each(["tui", "electron"] as const)(
  2270. "does not scan or rewrite shared Sessions for %s",
  2271. async (runtimeOwnerKind) => {
  2272. await createRuntimeServices({
  2273. db: {} as AppDb,
  2274. dataDir: "/data/shared",
  2275. logger: noopLogger,
  2276. scheduler: {} as SchedulerClient,
  2277. eventBus: new EventBus<GlobalEvent>(),
  2278. compatibility: defaultCompatibility(),
  2279. agentService: localAgentService,
  2280. runtimeOwnerKind,
  2281. capabilityProfile: "cli",
  2282. promptConfigKey: new Uint8Array(32).fill(7),
  2283. });
  2284. expect(
  2285. mocked.sessionSystem.repositories.sessions.list,
  2286. ).not.toHaveBeenCalled();
  2287. expect(
  2288. mocked.sessionSystem.repositories.sessions.update,
  2289. ).not.toHaveBeenCalled();
  2290. },
  2291. );
  2292. });
  2293. describe("runtime services LLM retry progress projection", () => {
  2294. it("wires the product retry observer into the production AgentHost", async () => {
  2295. const eventBus = new EventBus<GlobalEvent>();
  2296. const events: GlobalEvent[] = [];
  2297. eventBus.subscribe({ next: (event) => events.push(event) });
  2298. await createRuntimeServices({
  2299. db: {} as AppDb,
  2300. dataDir: "/data/tui-retry-visibility",
  2301. logger: noopLogger,
  2302. eventBus,
  2303. compatibility: defaultCompatibility(),
  2304. agentService: localAgentService,
  2305. runtimeOwnerKind: "tui",
  2306. capabilityProfile: "cli",
  2307. nowMs: () => 123,
  2308. });
  2309. const resolveLlmRetry = mocked.agentHostOptions?.["resolveLlmRetry"] as
  2310. | ((
  2311. input: unknown,
  2312. ) =>
  2313. | NonNullable<RunTurnInput["llmRetry"]>
  2314. | Promise<NonNullable<RunTurnInput["llmRetry"]>>)
  2315. | undefined;
  2316. expect(resolveLlmRetry).toEqual(expect.any(Function));
  2317. const retryOptions = await resolveLlmRetry?.({});
  2318. const waiting: LLMRetryEvent = {
  2319. sessionId: "session-1",
  2320. turnId: "turn-1",
  2321. callId: "call-1",
  2322. scope: "agent",
  2323. status: "waiting",
  2324. retryAttempt: 1,
  2325. maxRetries: 5,
  2326. requestAttempt: 2,
  2327. delayMs: 1_000,
  2328. nextRetryAtMs: 2_000,
  2329. error: {
  2330. reason: "network",
  2331. message: "LLM provider network request failed",
  2332. },
  2333. };
  2334. await retryOptions?.observer?.(waiting);
  2335. expect(events).toContainEqual({
  2336. type: "session.llm_retry",
  2337. timestamp: 123,
  2338. source: "local-runtime",
  2339. payload: { schemaVersion: 1, ...waiting },
  2340. });
  2341. });
  2342. });
  2343. describe("runtime services region content-review policy", () => {
  2344. it("disables content review only for the overseas TUI runtime", async () => {
  2345. mocked.runtimeRegion = "en";
  2346. await createRuntimeServices({
  2347. db: {} as AppDb,
  2348. dataDir: "/data/tui-overseas",
  2349. logger: noopLogger,
  2350. eventBus: new EventBus<GlobalEvent>(),
  2351. compatibility: defaultCompatibility(),
  2352. agentService: localAgentService,
  2353. runtimeOwnerKind: "tui",
  2354. capabilityProfile: "cli",
  2355. });
  2356. expect(mocked.agentHostOptions).toMatchObject({
  2357. cliProductPolicy: true,
  2358. tuiProductPolicy: true,
  2359. contentReviewEnabled: false,
  2360. });
  2361. });
  2362. it("does not apply the TUI region policy to the legacy CLI runtime", async () => {
  2363. mocked.runtimeRegion = "en";
  2364. await createRuntimeServices({
  2365. db: {} as AppDb,
  2366. dataDir: "/data/cli-overseas",
  2367. logger: noopLogger,
  2368. eventBus: new EventBus<GlobalEvent>(),
  2369. compatibility: defaultCompatibility(),
  2370. agentService: localAgentService,
  2371. runtimeOwnerKind: "cli",
  2372. capabilityProfile: "cli",
  2373. });
  2374. expect(mocked.agentHostOptions).toMatchObject({ cliProductPolicy: true });
  2375. expect(mocked.agentHostOptions).not.toHaveProperty("tuiProductPolicy");
  2376. expect(mocked.agentHostOptions).not.toHaveProperty("contentReviewEnabled");
  2377. });
  2378. });
  2379. describe("runtime active-steer consumption", () => {
  2380. it("publishes Message SSE and wakes the frontend resume path", async () => {
  2381. const eventBus = new EventBus<GlobalEvent>();
  2382. const events: GlobalEvent[] = [];
  2383. eventBus.subscribe({ next: (event) => events.push(event) });
  2384. mocked.sessionSystem.sessions.repository.get.mockResolvedValue({
  2385. sessionId: "session-1",
  2386. agentName: "mavis",
  2387. });
  2388. await createRuntimeServices({
  2389. db: {} as AppDb,
  2390. dataDir: "/data",
  2391. scheduler: {} as SchedulerClient,
  2392. eventBus,
  2393. compatibility: defaultCompatibility(),
  2394. agentService: localAgentService,
  2395. nowMs: () => 100,
  2396. });
  2397. const onSteeringConsumed = mocked.agentHostOptions?.[
  2398. "onSteeringConsumed"
  2399. ] as (input: Record<string, unknown>) => Promise<void>;
  2400. await onSteeringConsumed({
  2401. sessionId: "session-1",
  2402. turnId: "turn-active",
  2403. message: {
  2404. producerId: "communication",
  2405. idempotencyKey: "message-1",
  2406. message: { text: "hello" },
  2407. provenance: {
  2408. source: "communication",
  2409. routingFingerprint: "communication:message-1",
  2410. },
  2411. },
  2412. });
  2413. expect(
  2414. mocked.sessionSystem.messages.userMessages.commit,
  2415. ).toHaveBeenCalledOnce();
  2416. expect(mocked.sessionSystem.stream.write).toHaveBeenCalledWith(
  2417. expect.objectContaining({
  2418. kind: "message-committed",
  2419. turnId: "turn-active",
  2420. }),
  2421. );
  2422. expect(events).toContainEqual({
  2423. type: "session.start",
  2424. timestamp: 100,
  2425. source: "local-runtime",
  2426. payload: {
  2427. sessionId: "session-1",
  2428. agentName: "mavis",
  2429. turnId: "turn-active",
  2430. },
  2431. });
  2432. });
  2433. });
  2434. describe("runtime services Plugin Hook durable fence composition", () => {
  2435. type CapturedFence = {
  2436. run(input: {
  2437. readonly sessionId: string;
  2438. readonly reason: "archive" | "idle_timeout";
  2439. readonly idleSinceMs?: number;
  2440. readonly sessionOwnershipClaim?: string;
  2441. readonly operation: (signal?: AbortSignal) => Promise<unknown>;
  2442. }): Promise<unknown>;
  2443. };
  2444. async function configureFence(): Promise<CapturedFence> {
  2445. await createRuntimeServices({
  2446. db: {} as AppDb,
  2447. dataDir: "/data",
  2448. scheduler: {} as SchedulerClient,
  2449. eventBus: new EventBus<GlobalEvent>(),
  2450. compatibility: defaultCompatibility(),
  2451. agentService: localAgentService,
  2452. });
  2453. return mocked.pluginHookSessionEndFence as CapturedFence;
  2454. }
  2455. it("wires durable ownership into AgentHost and fences SessionEnd by Hook claim", async () => {
  2456. mocked.turnSystem.inspection.latestTurnActivity.mockResolvedValue({
  2457. turnId: "newer-admitted-without-hook-claim",
  2458. acceptedAtMs: 200,
  2459. activityAtMs: 200,
  2460. } as never);
  2461. const fence = await configureFence();
  2462. expect(mocked.agentHostOptions?.["pluginHookSessionOwnership"]).toBe(
  2463. mocked.hostPluginHookSessionOwnership,
  2464. );
  2465. const operation = vi.fn(async (signal?: AbortSignal) => ({ signal }));
  2466. await expect(
  2467. fence.run({
  2468. sessionId: "session-1",
  2469. reason: "archive",
  2470. sessionOwnershipClaim: "owner-turn-1",
  2471. operation,
  2472. }),
  2473. ).resolves.toMatchObject({ status: "executed" });
  2474. expect(operation).toHaveBeenCalledWith(expect.any(AbortSignal));
  2475. expect(
  2476. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd,
  2477. ).toHaveBeenCalledWith({
  2478. sessionId: "session-1",
  2479. ownershipClaimId: "owner-turn-1",
  2480. sessionEndClaimId: "owner-turn-1:session-end",
  2481. reason: "archive",
  2482. });
  2483. expect(
  2484. mocked.turnSystem.pluginHookSessionOwnership.completeSessionEnd,
  2485. ).toHaveBeenCalledOnce();
  2486. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd.mockResolvedValueOnce(
  2487. {
  2488. status: "already-claimed",
  2489. } as never,
  2490. );
  2491. const duplicate = vi.fn(async () => undefined);
  2492. await expect(
  2493. fence.run({
  2494. sessionId: "session-1",
  2495. reason: "archive",
  2496. sessionOwnershipClaim: "owner-turn-1",
  2497. operation: duplicate,
  2498. }),
  2499. ).resolves.toEqual({ status: "superseded" });
  2500. expect(duplicate).not.toHaveBeenCalled();
  2501. });
  2502. it("executes SessionEnd without a maintenance signal when exclusive fencing is unavailable", async () => {
  2503. const tryRunExclusive = mocked.turnSystem.sessionLifecycle.tryRunExclusive;
  2504. const sessionLifecycle = mocked.turnSystem.sessionLifecycle as {
  2505. tryRunExclusive?: typeof tryRunExclusive;
  2506. };
  2507. sessionLifecycle.tryRunExclusive = undefined;
  2508. try {
  2509. const fence = await configureFence();
  2510. const operation = vi.fn(async () => "completed");
  2511. await expect(
  2512. fence.run({
  2513. sessionId: "session-1",
  2514. reason: "archive",
  2515. sessionOwnershipClaim: "owner-turn-1",
  2516. operation,
  2517. }),
  2518. ).resolves.toEqual({ status: "executed", result: "completed" });
  2519. expect(operation).toHaveBeenCalledWith();
  2520. expect(
  2521. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd,
  2522. ).not.toHaveBeenCalled();
  2523. } finally {
  2524. sessionLifecycle.tryRunExclusive = tryRunExclusive;
  2525. }
  2526. });
  2527. it("supersedes SessionEnd when the durable ownership claim is absent or stale", async () => {
  2528. const fence = await configureFence();
  2529. const operation = vi.fn(async () => undefined);
  2530. mocked.turnSystem.pluginHookSessionOwnership.latest
  2531. .mockResolvedValueOnce(undefined as never)
  2532. .mockResolvedValueOnce({ ownershipClaimId: "owner-turn-2" } as never);
  2533. for (const sessionId of ["missing-owner", "stale-owner"]) {
  2534. await expect(
  2535. fence.run({
  2536. sessionId,
  2537. reason: "archive",
  2538. sessionOwnershipClaim: "owner-turn-1",
  2539. operation,
  2540. }),
  2541. ).resolves.toEqual({ status: "superseded" });
  2542. }
  2543. expect(operation).not.toHaveBeenCalled();
  2544. expect(
  2545. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd,
  2546. ).not.toHaveBeenCalled();
  2547. });
  2548. it("defers a stale idle sweep but executes after activity remains at the observed boundary", async () => {
  2549. const fence = await configureFence();
  2550. const operation = vi.fn(async () => "completed");
  2551. mocked.turnSystem.inspection.latestTurnActivity
  2552. .mockResolvedValueOnce({ activityAtMs: 201 } as never)
  2553. .mockResolvedValueOnce({ activityAtMs: 200 } as never);
  2554. await expect(
  2555. fence.run({
  2556. sessionId: "session-1",
  2557. reason: "idle_timeout",
  2558. idleSinceMs: 200,
  2559. sessionOwnershipClaim: "owner-turn-1",
  2560. operation,
  2561. }),
  2562. ).resolves.toEqual({ status: "deferred", latestActivityAtMs: 201 });
  2563. expect(operation).not.toHaveBeenCalled();
  2564. await expect(
  2565. fence.run({
  2566. sessionId: "session-1",
  2567. reason: "idle_timeout",
  2568. idleSinceMs: 200,
  2569. sessionOwnershipClaim: "owner-turn-1",
  2570. operation,
  2571. }),
  2572. ).resolves.toEqual({ status: "executed", result: "completed" });
  2573. expect(operation).toHaveBeenCalledWith(expect.any(AbortSignal));
  2574. });
  2575. });
  2576. describe("runtime services Cron composition", () => {
  2577. it("keeps Cron-specific test overrides inside service composition", async () => {
  2578. const customDelivery = {
  2579. deliver: async () => ({ delivered: true as const }),
  2580. };
  2581. const sessionPorts = {
  2582. sessionCreation: {},
  2583. delivery: mocked.defaultDelivery,
  2584. };
  2585. const services = await createRuntimeServices({
  2586. db: {} as AppDb,
  2587. dataDir: "/data",
  2588. logger: noopLogger,
  2589. scheduler: {} as SchedulerClient,
  2590. eventBus: new EventBus<GlobalEvent>(),
  2591. compatibility: defaultCompatibility(),
  2592. agentService: localAgentService,
  2593. overrides: {
  2594. cron: {
  2595. sessionPorts: sessionPorts as never,
  2596. turnDelivery: customDelivery,
  2597. },
  2598. },
  2599. });
  2600. expect(mocked.events).toEqual([
  2601. "session:create",
  2602. "channel:create",
  2603. "mcp:create",
  2604. "plugin:create",
  2605. "turn:create",
  2606. "session-applications:create",
  2607. "applications:create",
  2608. "cron:create",
  2609. ]);
  2610. expect(mocked.cronOptions).toMatchObject({
  2611. sessionPorts,
  2612. });
  2613. expect(mocked.cronOptions).not.toHaveProperty("turnDelivery");
  2614. expect(services.cronDelivery).toBe(customDelivery);
  2615. });
  2616. it("routes scheduled and generated Cron delivery through the same steer-or-activate port", async () => {
  2617. const compatibility = defaultCompatibility();
  2618. const services = await createRuntimeServices({
  2619. db: {} as AppDb,
  2620. dataDir: "/data",
  2621. scheduler: {} as SchedulerClient,
  2622. eventBus: new EventBus<GlobalEvent>(),
  2623. compatibility,
  2624. agentService: localAgentService,
  2625. });
  2626. const scheduledDelivery = (
  2627. mocked.cronOptions?.["sessionPorts"] as {
  2628. readonly delivery: {
  2629. deliver(input: CronDeliveryInput): Promise<unknown>;
  2630. };
  2631. }
  2632. ).delivery;
  2633. const request: CronDeliveryInput = {
  2634. cronId: "cron-1",
  2635. runId: "run-1",
  2636. sessionId: "session-1",
  2637. text: "inspect the build",
  2638. };
  2639. await expect(scheduledDelivery.deliver(request)).resolves.toEqual({
  2640. delivered: true,
  2641. });
  2642. await expect(services.cronDelivery?.deliver(request)).resolves.toEqual({
  2643. delivered: true,
  2644. });
  2645. expect(mocked.turnSystem.turns.steer).toHaveBeenCalledTimes(2);
  2646. expect(mocked.turnSystem.turns.steer).toHaveBeenNthCalledWith(1, {
  2647. sessionId: "session-1",
  2648. input: { text: "inspect the build" },
  2649. producerId: "cron:cron-1",
  2650. idempotencyKey: "run-1",
  2651. provenance: {
  2652. source: "cron",
  2653. routingFingerprint: "cron:cron-1:run-1",
  2654. sourceContext: { cronId: "cron-1", runId: "run-1" },
  2655. },
  2656. });
  2657. expect(mocked.turnSystem.turns.steer).toHaveBeenNthCalledWith(
  2658. 2,
  2659. expect.objectContaining({
  2660. producerId: "cron:cron-1",
  2661. idempotencyKey: "run-1",
  2662. }),
  2663. );
  2664. });
  2665. it("disables persisted Cron recovery for a quarantined runtime clone", async () => {
  2666. await createRuntimeServices({
  2667. db: {} as AppDb,
  2668. dataDir: "/data",
  2669. scheduler: {} as SchedulerClient,
  2670. eventBus: new EventBus<GlobalEvent>(),
  2671. compatibility: defaultCompatibility(),
  2672. agentService: localAgentService,
  2673. recoverPersistedState: false,
  2674. });
  2675. expect(mocked.cronOptions).toMatchObject({ recoverPendingRuns: false });
  2676. });
  2677. });
  2678. describe("runtime Root lifecycle diagnostics", () => {
  2679. it("routes v2 Root participant failures through the production reporter", async () => {
  2680. const compatibility = defaultCompatibility();
  2681. await createRuntimeServices({
  2682. db: {} as AppDb,
  2683. dataDir: "/data",
  2684. scheduler: {} as SchedulerClient,
  2685. eventBus: new EventBus<GlobalEvent>(),
  2686. compatibility,
  2687. agentService: localAgentService,
  2688. });
  2689. const rootDiagnostics = mocked.applicationOptions as {
  2690. readonly onRootBestEffortFailure: (input: {
  2691. readonly stage: "turn-abort";
  2692. readonly sessionId: string;
  2693. readonly error: unknown;
  2694. }) => void;
  2695. };
  2696. rootDiagnostics.onRootBestEffortFailure({
  2697. stage: "turn-abort",
  2698. sessionId: "root-1",
  2699. error: new Error("abort failed"),
  2700. });
  2701. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  2702. "root-1",
  2703. "root_replacement_abort_failed:abort failed",
  2704. );
  2705. });
  2706. });
  2707. describe("runtime Session Application composition", () => {
  2708. it.each([false, true])(
  2709. "cleans both MCP scopes when disposing a session (agent failure: %s)",
  2710. async (fails) => {
  2711. const services = await createRuntimeServices({
  2712. db: {} as AppDb,
  2713. dataDir: "/data",
  2714. scheduler: {} as SchedulerClient,
  2715. eventBus: new EventBus<GlobalEvent>(),
  2716. compatibility: defaultCompatibility(),
  2717. agentService: localAgentService,
  2718. });
  2719. const dispose = mocked.turnOptions?.disposeRuntimeSession;
  2720. if (!dispose)
  2721. throw new Error("Runtime session disposal was not composed");
  2722. if (fails)
  2723. mocked.agentRuntimeLifecycle.disposeSession.mockRejectedValueOnce(
  2724. new Error("agent disposal failed"),
  2725. );
  2726. const disposing = dispose("session-mcp");
  2727. if (fails)
  2728. await expect(disposing).rejects.toThrow("agent disposal failed");
  2729. else await disposing;
  2730. expect(mocked.agentRuntimeLifecycle.disposeSession).toHaveBeenCalledWith(
  2731. "session-mcp",
  2732. );
  2733. expect(mocked.mcp.disposeSession).toHaveBeenCalledWith("session-mcp");
  2734. await services.close();
  2735. },
  2736. );
  2737. it("resumes Session deletion through the bound Application lifecycle", async () => {
  2738. const services = await createRuntimeServices({
  2739. db: {} as AppDb,
  2740. dataDir: "/data",
  2741. scheduler: {} as SchedulerClient,
  2742. eventBus: new EventBus<GlobalEvent>(),
  2743. compatibility: defaultCompatibility(),
  2744. agentService: localAgentService,
  2745. });
  2746. const resumeSessionDeletion = mocked.turnOptions?.resumeSessionDeletion;
  2747. if (!resumeSessionDeletion)
  2748. throw new Error("Session deletion recovery was not composed");
  2749. await resumeSessionDeletion("session-deleting");
  2750. expect(
  2751. mocked.runtimeApplications.session.lifecycle.deleteSessionById,
  2752. ).toHaveBeenCalledWith("session-deleting");
  2753. await services.close();
  2754. });
  2755. it("always composes Applications over the main SessionSystem owner graph", async () => {
  2756. const db = {} as AppDb;
  2757. const compatibility = defaultCompatibility();
  2758. const services = await createRuntimeServices({
  2759. db,
  2760. dataDir: "/data",
  2761. scheduler: {} as SchedulerClient,
  2762. eventBus: new EventBus<GlobalEvent>(),
  2763. compatibility,
  2764. agentService: localAgentService,
  2765. });
  2766. expect(mocked.sessionApplicationOptions).toMatchObject({
  2767. owner: mocked.sessionSystem,
  2768. canvas: services.canvas,
  2769. compatibility: compatibility.sessionV2,
  2770. maintenance: mocked.turnSystem.maintenance,
  2771. facts: mocked.applicationFactPorts,
  2772. });
  2773. expect(mocked.applicationFactOptions).toEqual({
  2774. publish: expect.any(Function),
  2775. });
  2776. expect(mocked.applicationOptions).toMatchObject({
  2777. sessionSystem: mocked.initializedSessionApplicationSystem,
  2778. compatibility: compatibility.sessionV2,
  2779. turn: mocked.turnSystem.turns,
  2780. });
  2781. expect(services.applications).toBe(mocked.runtimeApplications);
  2782. mocked.events.length = 0;
  2783. await services.ready();
  2784. expect(mocked.events).toEqual([
  2785. "session:ready",
  2786. "plan-documents:reconcile",
  2787. "mcp:ready",
  2788. "plugin:ready",
  2789. "turn:ready",
  2790. "conversation:bind",
  2791. "questionnaire:recover",
  2792. "questionnaire:plan-reconcile:true",
  2793. "cron:ready",
  2794. ]);
  2795. await expect(services.builtinAgentDefinitionsReady).resolves.toBe(true);
  2796. expect(mocked.events.at(-1)).toBe("agent:ensure");
  2797. expect(mocked.agentService.ensureBuiltinRows).toHaveBeenCalledOnce();
  2798. expect(
  2799. mocked.agentService.bindBuiltinModelGroupResolver,
  2800. ).toHaveBeenCalledWith(expect.any(Function));
  2801. expect(
  2802. mocked.agentService.bindConfigPreviewDiagnostics,
  2803. ).toHaveBeenCalledWith(expect.any(Function));
  2804. expect(
  2805. mocked.agentService.bindEffectiveConfigResolver,
  2806. ).toHaveBeenCalledWith(expect.any(Function));
  2807. expect(
  2808. mocked.agentService.bindCandidateModelValidator,
  2809. ).toHaveBeenCalledWith(expect.any(Function));
  2810. mocked.events.length = 0;
  2811. await services.close();
  2812. expect(mocked.events).toEqual([
  2813. "cron:close",
  2814. "turn:close",
  2815. "plugin:close",
  2816. "mcp:close",
  2817. "session:close",
  2818. ]);
  2819. });
  2820. });
  2821. describe("runtime persisted-state recovery policy", () => {
  2822. it("skips persisted Questionnaire and Plan recovery for a quarantined runtime clone", async () => {
  2823. const services = await createRuntimeServices({
  2824. db: {} as AppDb,
  2825. dataDir: "/data",
  2826. scheduler: {} as SchedulerClient,
  2827. eventBus: new EventBus<GlobalEvent>(),
  2828. compatibility: defaultCompatibility(),
  2829. recoverPersistedState: false,
  2830. agentService: localAgentService,
  2831. });
  2832. mocked.events.length = 0;
  2833. await services.ready();
  2834. expect(mocked.events).toEqual([
  2835. "session:ready",
  2836. "mcp:ready",
  2837. "plugin:ready",
  2838. "turn:ready",
  2839. "conversation:bind",
  2840. "cron:ready",
  2841. ]);
  2842. await expect(services.builtinAgentDefinitionsReady).resolves.toBe(true);
  2843. expect(mocked.events.at(-1)).toBe("agent:ensure");
  2844. });
  2845. });
  2846. describe("Goal verifier service binding", () => {
  2847. it("binds both backends, immutable transcript capture, and the readonly child extension", async () => {
  2848. const bindVerifier =
  2849. vi.fn<
  2850. NonNullable<
  2851. V1ServiceCompatibility["sessionV2"]["goals"]["bindVerifier"]
  2852. >
  2853. >();
  2854. const compatibility = defaultCompatibility();
  2855. Object.assign(compatibility.sessionV2.goals, { bindVerifier });
  2856. const canonicalMessage = { role: "user", content: "fixed evidence" };
  2857. mocked.sessionSystem.canonicalHistory.inspectActive.mockResolvedValue({
  2858. revision: "sha256:goal-evaluator",
  2859. messages: [canonicalMessage],
  2860. });
  2861. const services = await createRuntimeServices({
  2862. db: {} as AppDb,
  2863. dataDir: "/data",
  2864. scheduler: {} as SchedulerClient,
  2865. eventBus: new EventBus<GlobalEvent>(),
  2866. compatibility,
  2867. agentService: localAgentService,
  2868. });
  2869. expect(bindVerifier).toHaveBeenCalledOnce();
  2870. const [verifier, reader] = bindVerifier.mock.calls[0] ?? [];
  2871. expect(verifier?.dispatch).toEqual(expect.any(Function));
  2872. expect(mocked.agentHostOptions?.["normalExtensions"]).toEqual(
  2873. expect.arrayContaining([
  2874. expect.objectContaining({ id: "local-goal-verifier-readonly" }),
  2875. expect.objectContaining({ id: "local-goal-budget-summary" }),
  2876. ]),
  2877. );
  2878. // Without this the child's per-request cap would never reach the Turn, and
  2879. // only the coordinator's cumulative check would remain.
  2880. const outputTokenCap = mocked.agentHostOptions?.["outputTokenCap"] as
  2881. | { resolveOutputTokenCap: (input: unknown) => number | undefined }
  2882. | undefined;
  2883. expect(outputTokenCap?.resolveOutputTokenCap).toEqual(expect.any(Function));
  2884. expect(outputTokenCap?.resolveOutputTokenCap({})).toBeUndefined();
  2885. const captured = await reader?.capture("session-goal");
  2886. canonicalMessage.content = "concurrent mutation";
  2887. expect(captured).toEqual({
  2888. messages: [{ role: "user", content: "fixed evidence" }],
  2889. truncated: false,
  2890. });
  2891. expect(
  2892. mocked.sessionSystem.canonicalHistory.inspectActive,
  2893. ).toHaveBeenCalledWith("session-goal");
  2894. await services.close();
  2895. });
  2896. it("captures only the newest bounded Goal verifier transcript and reports truncation", async () => {
  2897. const bindVerifier =
  2898. vi.fn<
  2899. NonNullable<
  2900. V1ServiceCompatibility["sessionV2"]["goals"]["bindVerifier"]
  2901. >
  2902. >();
  2903. const compatibility = defaultCompatibility();
  2904. Object.assign(compatibility.sessionV2.goals, { bindVerifier });
  2905. const canonicalMessages = Array.from({ length: 201 }, (_, index) => ({
  2906. role: "user",
  2907. content: `evidence-${index}`,
  2908. }));
  2909. mocked.sessionSystem.canonicalHistory.inspectActive.mockResolvedValue({
  2910. revision: "sha256:goal-evaluator-bounded",
  2911. messages: canonicalMessages,
  2912. });
  2913. const services = await createRuntimeServices({
  2914. db: {} as AppDb,
  2915. dataDir: "/data",
  2916. scheduler: {} as SchedulerClient,
  2917. eventBus: new EventBus<GlobalEvent>(),
  2918. compatibility,
  2919. agentService: localAgentService,
  2920. });
  2921. const [, reader] = bindVerifier.mock.calls[0] ?? [];
  2922. const captured = await reader?.capture("session-goal-bounded");
  2923. const newestCanonicalMessage = canonicalMessages.at(-1);
  2924. if (!newestCanonicalMessage)
  2925. throw new Error("expected bounded canonical transcript");
  2926. newestCanonicalMessage.content = "concurrent mutation";
  2927. expect(captured).toMatchObject({
  2928. truncated: true,
  2929. truncationNote: expect.stringContaining("newest 200 messages"),
  2930. });
  2931. expect(captured?.messages).toHaveLength(200);
  2932. expect(captured?.messages[0]).toEqual({
  2933. role: "user",
  2934. content: "evidence-1",
  2935. });
  2936. expect(captured?.messages[199]).toEqual({
  2937. role: "user",
  2938. content: "evidence-200",
  2939. });
  2940. await services.close();
  2941. });
  2942. });
  2943. describe("runtime Browser services lifecycle", () => {
  2944. it("treats an unspecified runtime owner as Desktop Plugin-managed Browser activation", async () => {
  2945. const compatibility = defaultCompatibility();
  2946. Object.assign(compatibility.agentHost.preparation.configBuilder, {
  2947. config: () => ({
  2948. provider: {},
  2949. dataDir: "/data",
  2950. custom_provider: { "openai-work": {} },
  2951. beta: { filePanelBrowser: true, browserUseTooling: true },
  2952. }),
  2953. });
  2954. const services = await createRuntimeServices({
  2955. db: {} as AppDb,
  2956. dataDir: "/data",
  2957. scheduler: {} as SchedulerClient,
  2958. eventBus: new EventBus<GlobalEvent>(),
  2959. compatibility,
  2960. browserUse: { adapter: { execute: vi.fn() } },
  2961. agentService: localAgentService,
  2962. });
  2963. expect(services.browserUse.builtinSkillDescriptor()).toBeUndefined();
  2964. expect(
  2965. services.browserUse.admitQuestionnaireRequest({
  2966. request: {
  2967. mode: "feature-enable",
  2968. modePayload: { featureKey: "browser-use" },
  2969. },
  2970. }),
  2971. ).toMatchObject({ status: 403, code: "BROWSER_PLUGIN_MANAGED" });
  2972. await services.close();
  2973. });
  2974. it("clears V2 Browser receipts only for committed context-reset rewinds", async () => {
  2975. const compatibility = defaultCompatibility();
  2976. Object.assign(compatibility.agentHost.preparation.configBuilder, {
  2977. config: () => ({
  2978. provider: {},
  2979. dataDir: "/data",
  2980. custom_provider: { "openai-work": {} },
  2981. beta: { filePanelBrowser: true, browserUseTooling: true },
  2982. }),
  2983. });
  2984. const services = await createRuntimeServices({
  2985. db: {} as AppDb,
  2986. dataDir: "/data",
  2987. scheduler: {} as SchedulerClient,
  2988. eventBus: new EventBus<GlobalEvent>(),
  2989. compatibility,
  2990. browserUse: { adapter: { execute: vi.fn() } },
  2991. agentService: localAgentService,
  2992. runtimeOwnerKind: "cli",
  2993. });
  2994. const publish = mocked.applicationFactOptions?.["publish"] as (
  2995. event: GlobalEventInput,
  2996. ) => void;
  2997. const baseSkill = {
  2998. def: LocalSkillToolDef,
  2999. impl: { execute: vi.fn(async () => ({ content: [] })) },
  3000. } as unknown as RuntimeTool;
  3001. const browserCapability = services.browserUse.resolveTurnCapability({
  3002. sessionId: "assembly-session",
  3003. turnId: "assembly-turn",
  3004. surface: "interactive",
  3005. workspaceRoot: "/data",
  3006. baseTools: [baseSkill],
  3007. });
  3008. const skill = browserCapability.tools.find(
  3009. (candidate) => candidate.def.name === "skill",
  3010. );
  3011. const browser = browserCapability.tools.find(
  3012. (candidate) => candidate.def.name === "browser",
  3013. );
  3014. if (!skill || !browser) throw new Error("expected Browser tools");
  3015. for (const sessionId of [
  3016. "session-reset",
  3017. "session-ui-only",
  3018. "session-deleted",
  3019. ]) {
  3020. await skill.impl.execute(
  3021. { sessionId, turnId: "turn-a" },
  3022. {
  3023. name: "control-in-app-browser",
  3024. },
  3025. );
  3026. }
  3027. services.browserUse.turnContext.record({
  3028. sessionId: "session-reset",
  3029. turnId: "turn-reset",
  3030. inAppBrowser: { visible: true, selectedTab: true },
  3031. });
  3032. services.browserUse.turnContext.record({
  3033. sessionId: "session-deleted",
  3034. turnId: "turn-deleted",
  3035. inAppBrowser: { visible: true, selectedTab: false },
  3036. });
  3037. publish({
  3038. type: "message.rewind",
  3039. payload: { sessionId: "session-reset", contextReset: true },
  3040. });
  3041. publish({
  3042. type: "message.rewind",
  3043. payload: { sessionId: "session-ui-only", contextReset: false },
  3044. });
  3045. publish({
  3046. type: "content.retry.exceeded",
  3047. payload: { sessionId: "session-retry", variant: "content" },
  3048. });
  3049. publish({
  3050. type: "session.deleted",
  3051. payload: { sessionId: "session-deleted" },
  3052. });
  3053. await expect(
  3054. browser.impl.execute(
  3055. { sessionId: "session-reset", turnId: "turn-a" },
  3056. {
  3057. action: "inspect",
  3058. input: {},
  3059. },
  3060. ),
  3061. ).resolves.toMatchObject({
  3062. isError: true,
  3063. details: { code: "SKILL_REQUIRED" },
  3064. });
  3065. await expect(
  3066. browser.impl.execute(
  3067. { sessionId: "session-ui-only", turnId: "turn-a" },
  3068. {
  3069. action: "inspect",
  3070. input: {},
  3071. },
  3072. ),
  3073. ).resolves.toMatchObject({ details: { action: "inspect" } });
  3074. expect(
  3075. services.browserUse.turnContext.read("session-reset", "turn-reset"),
  3076. ).toEqual({
  3077. visible: true,
  3078. selectedTab: true,
  3079. });
  3080. await expect(
  3081. browser.impl.execute(
  3082. { sessionId: "session-deleted", turnId: "turn-a" },
  3083. {
  3084. action: "inspect",
  3085. input: {},
  3086. },
  3087. ),
  3088. ).resolves.toMatchObject({
  3089. isError: true,
  3090. details: { code: "SKILL_REQUIRED" },
  3091. });
  3092. expect(
  3093. services.browserUse.turnContext.read("session-deleted", "turn-deleted"),
  3094. ).toBeUndefined();
  3095. await services.close();
  3096. });
  3097. });
  3098. describe("runtime services lifecycle", () => {
  3099. it("keeps startup available when ordinary Questionnaire recovery fails", async () => {
  3100. const failure = new Error("Questionnaire query failed");
  3101. mocked.questionnaireService.recoverOnStartup.mockRejectedValueOnce(failure);
  3102. const compatibility = defaultCompatibility();
  3103. const services = await createRuntimeServices({
  3104. db: {} as AppDb,
  3105. dataDir: "/data",
  3106. scheduler: {} as SchedulerClient,
  3107. eventBus: new EventBus<GlobalEvent>(),
  3108. compatibility,
  3109. agentService: localAgentService,
  3110. });
  3111. await expect(services.ready()).resolves.toBeUndefined();
  3112. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  3113. "questionnaire-recovery",
  3114. "owner=questionnaire;stage=startup-recovery;error=Questionnaire query failed",
  3115. );
  3116. });
  3117. it("keeps startup available when Plan draft recovery reports isolated failures", async () => {
  3118. const failure = new AggregateError(
  3119. [new Error("bad manifest")],
  3120. "draft recovery failed",
  3121. );
  3122. mocked.sessionSystem.planDocuments.reconcilePreparedDrafts.mockRejectedValueOnce(
  3123. failure,
  3124. );
  3125. const compatibility = defaultCompatibility();
  3126. const services = await createRuntimeServices({
  3127. db: {} as AppDb,
  3128. dataDir: "/data",
  3129. scheduler: {} as SchedulerClient,
  3130. eventBus: new EventBus<GlobalEvent>(),
  3131. compatibility,
  3132. agentService: localAgentService,
  3133. });
  3134. await expect(services.ready()).resolves.toBeUndefined();
  3135. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  3136. "plan-document-recovery",
  3137. "owner=session-system;component=plan-document;stage=startup-reconcile;error=draft recovery failed",
  3138. );
  3139. });
  3140. it("accepts v1 events through the injected write port once and detaches on close", async () => {
  3141. let publish:
  3142. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3143. | undefined;
  3144. const unbind = vi.fn();
  3145. const bindPublisher = vi.fn<
  3146. V1ServiceCompatibility["events"]["bindPublisher"]
  3147. >((publisher) => {
  3148. publish = publisher;
  3149. return unbind;
  3150. });
  3151. const eventBus = new EventBus<GlobalEvent>();
  3152. const compatibility = defaultCompatibility({ bindPublisher });
  3153. const services = await createRuntimeServices({
  3154. db: {} as AppDb,
  3155. dataDir: "/data",
  3156. scheduler: {} as SchedulerClient,
  3157. eventBus,
  3158. compatibility,
  3159. agentService: localAgentService,
  3160. nowMs: () => 1_700_000_000_000,
  3161. });
  3162. const received: GlobalEvent[] = [];
  3163. services.globalEvents.subscribe({ next: (event) => received.push(event) });
  3164. expect(publish).toBeUndefined();
  3165. await services.ready();
  3166. publish?.({ type: "agent.created", payload: { agentName: "mavis" } });
  3167. expect(received).toEqual([
  3168. {
  3169. type: "agent.created",
  3170. timestamp: 1_700_000_000_000,
  3171. source: "local-runtime",
  3172. payload: { agentName: "mavis" },
  3173. },
  3174. ]);
  3175. publish?.({
  3176. type: "session.finish",
  3177. payload: {
  3178. sessionId: "session-1",
  3179. agentName: "mavis",
  3180. turnId: "turn-greeting",
  3181. status: "finished",
  3182. },
  3183. });
  3184. expect(received[1]).toMatchObject({
  3185. type: "session.finish",
  3186. payload: { turnId: "turn-greeting" },
  3187. });
  3188. publish?.({
  3189. type: "session.error",
  3190. payload: {
  3191. sessionId: "session-1",
  3192. agentName: "mavis",
  3193. turnId: "turn-failed-greeting",
  3194. status: "error",
  3195. },
  3196. });
  3197. publish?.({
  3198. type: "session.abort",
  3199. payload: {
  3200. sessionId: "session-1",
  3201. agentName: "mavis",
  3202. turnId: "turn-cancelled-greeting",
  3203. status: "aborted",
  3204. },
  3205. });
  3206. await services.close();
  3207. expect(bindPublisher).toHaveBeenCalledOnce();
  3208. expect(unbind).toHaveBeenCalledOnce();
  3209. expect(mocked.conversationShutdowns).toHaveLength(1);
  3210. publish?.({ type: "agent.created", payload: { agentName: "late-event" } });
  3211. expect(received).toHaveLength(4);
  3212. });
  3213. });
  3214. describe("runtime services readiness and shutdown", () => {
  3215. it("swallows greeting terminal persistence failures without leaking a rejection", async () => {
  3216. let publish:
  3217. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3218. | undefined;
  3219. const bindPublisher = vi.fn<
  3220. V1ServiceCompatibility["events"]["bindPublisher"]
  3221. >((publisher) => {
  3222. publish = publisher;
  3223. return () => undefined;
  3224. });
  3225. const compatibility = defaultCompatibility({ bindPublisher });
  3226. const services = await createRuntimeServices({
  3227. db: {} as AppDb,
  3228. dataDir: "/data",
  3229. scheduler: {} as SchedulerClient,
  3230. eventBus: new EventBus<GlobalEvent>(),
  3231. compatibility,
  3232. agentService: localAgentService,
  3233. greetingEnabled: true,
  3234. });
  3235. await services.ready();
  3236. const notification = vi.mocked(services.agent.notifyGreetingTurnTerminal);
  3237. notification.mockRejectedValueOnce(
  3238. new Error("greeting state write failed"),
  3239. );
  3240. publish?.({
  3241. type: "session.finish",
  3242. payload: {
  3243. sessionId: "session-1",
  3244. agentName: "mavis",
  3245. turnId: "turn-greeting-persistence-failure",
  3246. status: "finished",
  3247. },
  3248. });
  3249. await Promise.resolve();
  3250. expect(notification).toHaveBeenCalledOnce();
  3251. await services.close();
  3252. });
  3253. });
  3254. describe("runtime services ready and close", () => {
  3255. it("runs post-infra service readiness once and preserves its failure", async () => {
  3256. const failure = new Error("Cron recovery failed");
  3257. mocked.readyError = failure;
  3258. const services = await createRuntimeServices({
  3259. db: {} as AppDb,
  3260. dataDir: "/data",
  3261. logger: noopLogger,
  3262. scheduler: {} as SchedulerClient,
  3263. eventBus: new EventBus<GlobalEvent>(),
  3264. compatibility: defaultCompatibility(),
  3265. agentService: localAgentService,
  3266. });
  3267. const first = services.ready();
  3268. const second = services.ready();
  3269. expect(second).toBe(first);
  3270. await expect(first).rejects.toBe(failure);
  3271. expect(mocked.conversationBindings).toEqual([mocked.conversationService]);
  3272. expect(mocked.events).toEqual([
  3273. "session:create",
  3274. "channel:create",
  3275. "mcp:create",
  3276. "plugin:create",
  3277. "turn:create",
  3278. "session-applications:create",
  3279. "applications:create",
  3280. "cron:create",
  3281. "session:ready",
  3282. "plan-documents:reconcile",
  3283. "mcp:ready",
  3284. "plugin:ready",
  3285. "turn:ready",
  3286. "conversation:bind",
  3287. "questionnaire:recover",
  3288. "questionnaire:plan-reconcile:true",
  3289. "cron:ready",
  3290. ]);
  3291. });
  3292. it("keeps runtime startup available while a failed Plan recovery retries after Queue readiness", async () => {
  3293. const failure = new Error("Plan recovery temporarily unavailable");
  3294. mocked.questionnaireService.reconcileOwnedActions.mockRejectedValueOnce(
  3295. failure,
  3296. );
  3297. const compatibility = defaultCompatibility();
  3298. const services = await createRuntimeServices({
  3299. db: {} as AppDb,
  3300. dataDir: "/data",
  3301. scheduler: {} as SchedulerClient,
  3302. eventBus: new EventBus<GlobalEvent>(),
  3303. compatibility,
  3304. agentService: localAgentService,
  3305. });
  3306. await expect(services.ready()).resolves.toBeUndefined();
  3307. await vi.waitFor(() => {
  3308. expect(mocked.events).toContain("questionnaire:plan-reconcile:true");
  3309. });
  3310. await expect(services.builtinAgentDefinitionsReady).resolves.toBe(true);
  3311. expect(mocked.events.filter((event) => event !== "agent:ensure")).toEqual([
  3312. "session:create",
  3313. "channel:create",
  3314. "mcp:create",
  3315. "plugin:create",
  3316. "turn:create",
  3317. "session-applications:create",
  3318. "applications:create",
  3319. "cron:create",
  3320. "session:ready",
  3321. "plan-documents:reconcile",
  3322. "mcp:ready",
  3323. "plugin:ready",
  3324. "turn:ready",
  3325. "conversation:bind",
  3326. "questionnaire:recover",
  3327. "cron:ready",
  3328. "questionnaire:plan-reconcile:true",
  3329. ]);
  3330. expect(
  3331. mocked.events.filter((event) => event === "agent:ensure"),
  3332. ).toHaveLength(1);
  3333. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  3334. "plan-lifecycle",
  3335. "owner=plan;stage=lifecycle-reconcile;error=Plan recovery temporarily unavailable",
  3336. );
  3337. await services.close();
  3338. });
  3339. it("shares close, closes Cron once, and cannot become ready afterwards", async () => {
  3340. const bindPublisher = vi.fn(() => () => undefined);
  3341. const services = await createRuntimeServices({
  3342. db: {} as AppDb,
  3343. dataDir: "/data",
  3344. logger: noopLogger,
  3345. scheduler: {} as SchedulerClient,
  3346. eventBus: new EventBus<GlobalEvent>(),
  3347. compatibility: defaultCompatibility({ bindPublisher }),
  3348. agentService: localAgentService,
  3349. });
  3350. mocked.events.length = 0;
  3351. const closePreview = vi.spyOn(services.workspace.htmlPreview, "close");
  3352. const first = services.close();
  3353. const second = services.close();
  3354. expect(second).toBe(first);
  3355. await first;
  3356. expect(closePreview).toHaveBeenCalledTimes(1);
  3357. await services.ready();
  3358. expect(mocked.events).toEqual([
  3359. "cron:close",
  3360. "turn:close",
  3361. "plugin:close",
  3362. "mcp:close",
  3363. "session:close",
  3364. ]);
  3365. expect(bindPublisher).not.toHaveBeenCalled();
  3366. expect(mocked.conversationShutdowns).toHaveLength(1);
  3367. });
  3368. it("closes Cron when publisher cleanup fails and preserves the first failure", async () => {
  3369. const failure = new Error("global events close failed");
  3370. const compatibility = defaultCompatibility({
  3371. bindPublisher: () => () => {
  3372. throw failure;
  3373. },
  3374. });
  3375. const services = await createRuntimeServices({
  3376. db: {} as AppDb,
  3377. dataDir: "/data",
  3378. scheduler: {} as SchedulerClient,
  3379. eventBus: new EventBus<GlobalEvent>(),
  3380. compatibility,
  3381. agentService: localAgentService,
  3382. });
  3383. await services.ready();
  3384. mocked.events.length = 0;
  3385. const closePreview = vi.spyOn(services.workspace.htmlPreview, "close");
  3386. await expect(services.close()).rejects.toBe(failure);
  3387. expect(closePreview).toHaveBeenCalledTimes(1);
  3388. expect(mocked.events).toEqual([
  3389. "cron:close",
  3390. "turn:close",
  3391. "plugin:close",
  3392. "mcp:close",
  3393. "session:close",
  3394. ]);
  3395. });
  3396. });
  3397. describe("runtime services greeting terminal timing", () => {
  3398. it("invokes greeting terminal observation before publishing the terminal event", async () => {
  3399. let publish:
  3400. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3401. | undefined;
  3402. const bindPublisher = vi.fn<
  3403. V1ServiceCompatibility["events"]["bindPublisher"]
  3404. >((publisher) => {
  3405. publish = publisher;
  3406. return () => undefined;
  3407. });
  3408. const eventBus = new EventBus<GlobalEvent>();
  3409. const order: string[] = [];
  3410. eventBus.subscribe({ next: () => order.push("event") });
  3411. const services = await createRuntimeServices({
  3412. db: {} as AppDb,
  3413. dataDir: "/data",
  3414. scheduler: {} as SchedulerClient,
  3415. eventBus,
  3416. compatibility: defaultCompatibility({ bindPublisher }),
  3417. agentService: localAgentService,
  3418. greetingEnabled: true,
  3419. });
  3420. await services.ready();
  3421. const notification = vi.mocked(services.agent.notifyGreetingTurnTerminal);
  3422. notification.mockImplementationOnce(() => {
  3423. order.push("notify");
  3424. return Promise.resolve();
  3425. });
  3426. publish?.({
  3427. type: "session.finish",
  3428. payload: {
  3429. sessionId: "session-1",
  3430. agentName: "mavis",
  3431. turnId: "turn-greeting-order",
  3432. status: "finished",
  3433. },
  3434. });
  3435. expect(order).toEqual(["notify", "event"]);
  3436. await services.close();
  3437. });
  3438. it("swallows synchronous greeting terminal observer failures", async () => {
  3439. let publish:
  3440. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3441. | undefined;
  3442. const bindPublisher = vi.fn<
  3443. V1ServiceCompatibility["events"]["bindPublisher"]
  3444. >((publisher) => {
  3445. publish = publisher;
  3446. return () => undefined;
  3447. });
  3448. const services = await createRuntimeServices({
  3449. db: {} as AppDb,
  3450. dataDir: "/data",
  3451. scheduler: {} as SchedulerClient,
  3452. eventBus: new EventBus<GlobalEvent>(),
  3453. compatibility: defaultCompatibility({ bindPublisher }),
  3454. agentService: localAgentService,
  3455. greetingEnabled: true,
  3456. });
  3457. await services.ready();
  3458. const notification = vi.mocked(services.agent.notifyGreetingTurnTerminal);
  3459. notification.mockImplementationOnce(() => {
  3460. throw new Error("synchronous greeting observer failure");
  3461. });
  3462. publish?.({
  3463. type: "session.finish",
  3464. payload: {
  3465. sessionId: "session-1",
  3466. agentName: "mavis",
  3467. turnId: "turn-greeting-sync-failure",
  3468. status: "finished",
  3469. },
  3470. });
  3471. expect(notification).toHaveBeenCalledOnce();
  3472. await services.close();
  3473. });
  3474. });
  3475. describe("runtime Plan lifecycle recovery", () => {
  3476. it("releases recovered Plan review Queue work only after TurnSystem is ready", async () => {
  3477. mocked.questionnaireService.reconcileOwnedActions.mockImplementationOnce(
  3478. async (dispatch: boolean) => {
  3479. mocked.events.push(`questionnaire:plan-reconcile:${String(dispatch)}`);
  3480. const binding = mocked.questionnaireActionBindings[0] as {
  3481. readonly handler: QuestionnaireOwnedActionHandler;
  3482. };
  3483. await binding.handler.afterConsumed?.({
  3484. record: {
  3485. requestId: "plan-review-request",
  3486. sessionId: "session-plan-review",
  3487. request: {
  3488. mode: "plan",
  3489. modePayload: {
  3490. planReview: {
  3491. markdown: "# Frozen plan",
  3492. path: "/history/session-1/artifacts/plan.md",
  3493. },
  3494. },
  3495. },
  3496. } as never,
  3497. action: {
  3498. kind: "reply",
  3499. reply: {
  3500. schemaVersion: 2,
  3501. requestId: "plan-review-request",
  3502. answers: [
  3503. {
  3504. stepId: "plan-review-decision",
  3505. selectedOptionIds: ["approve"],
  3506. selectedOther: false,
  3507. },
  3508. ],
  3509. submittedAt: 1_700_000_000_000,
  3510. },
  3511. },
  3512. dispatch,
  3513. });
  3514. return 1;
  3515. },
  3516. );
  3517. mocked.turnSystem.turns.dispatchQueue.mockImplementationOnce(
  3518. async (sessionId: string) => {
  3519. mocked.events.push(`queue:dispatch:${sessionId}`);
  3520. },
  3521. );
  3522. const services = await createRuntimeServices({
  3523. db: {} as AppDb,
  3524. dataDir: "/data",
  3525. scheduler: {} as SchedulerClient,
  3526. eventBus: new EventBus<GlobalEvent>(),
  3527. compatibility: defaultCompatibility(),
  3528. agentService: localAgentService,
  3529. });
  3530. await services.ready();
  3531. await vi.waitFor(() => {
  3532. expect(mocked.events).toContain("queue:dispatch:session-plan-review");
  3533. });
  3534. expect(
  3535. mocked.events.indexOf("queue:dispatch:session-plan-review"),
  3536. ).toBeGreaterThan(mocked.events.indexOf("turn:ready"));
  3537. await services.close();
  3538. });
  3539. });
  3540. async function assertWorkspaceBashFileSourceResolution(): Promise<void> {
  3541. // The rollout kill switch keeps the extension out of every composed runtime,
  3542. // so exercise the retained implementation directly for future re-enable.
  3543. const compatibility = defaultCompatibility();
  3544. const extension = createRuntimeSourceReferenceExtension(
  3545. compatibility.attachmentRegistration,
  3546. );
  3547. const runtime = await createAgentRuntime({ base: [extension] });
  3548. const turn = baseCtx({
  3549. sessionId: "session-workspace-source",
  3550. turnId: "turn-workspace-source",
  3551. workspaceDir: "/workspace/project",
  3552. });
  3553. const assembly = await runtime.assembleTurn(turn);
  3554. const afterToolCall = assembly.hooks.afterToolCallHook?.[0];
  3555. if (!afterToolCall)
  3556. throw new Error("source-reference tool hook was not registered");
  3557. const insidePatch = await afterToolCall({
  3558. assistantMessage: {} as never,
  3559. toolCall: { id: "bash-inside", name: "bash" } as never,
  3560. args: {
  3561. command: "unzip -q /workspace/project/demo.docx -d /tmp/docx_extract",
  3562. },
  3563. result: { content: [{ type: "text", text: "document body" }], details: {} },
  3564. isError: false,
  3565. context: {} as never,
  3566. });
  3567. const outsidePatch = await afterToolCall({
  3568. assistantMessage: {} as never,
  3569. toolCall: { id: "bash-outside", name: "bash" } as never,
  3570. args: { command: "unzip -q /outside/private.docx -d /tmp/docx_extract" },
  3571. result: { content: [{ type: "text", text: "private body" }], details: {} },
  3572. isError: false,
  3573. context: {} as never,
  3574. });
  3575. expect(insidePatch?.content?.at(-1)).toEqual({
  3576. type: "text",
  3577. text: expect.stringContaining(
  3578. "Citation candidate: [demo.docx](#mavis-source=file:L3dvcmtzcGFjZS9wcm9qZWN0L2RlbW8uZG9jeA)",
  3579. ),
  3580. });
  3581. expect(insidePatch?.details).toMatchObject({
  3582. source_references: [
  3583. expect.objectContaining({
  3584. type: "file",
  3585. path: "/workspace/project/demo.docx",
  3586. name: "demo.docx",
  3587. }),
  3588. ],
  3589. });
  3590. expect(outsidePatch).toBeUndefined();
  3591. expect(
  3592. compatibility.attachmentRegistration.resolveSource,
  3593. ).toHaveBeenCalledTimes(2);
  3594. }
  3595. function defaultCompatibility(
  3596. events: V1ServiceCompatibility["events"] = {
  3597. bindPublisher: () => () => undefined,
  3598. },
  3599. generatedAssets: Partial<V1ServiceCompatibility["generatedAssets"]> = {},
  3600. ): V1ServiceCompatibility {
  3601. return {
  3602. sandbox: { writeConfig: vi.fn(async () => undefined) },
  3603. modelProvider: { refreshOfficialModels: vi.fn(async () => undefined) },
  3604. peripherals: {} as never,
  3605. skills: {
  3606. listSkills: vi.fn(async () => ({ skills: [], hasMore: false })),
  3607. } as never,
  3608. managedWorktrees: {
  3609. list: vi.fn(async () => ({ success: true, worktrees: [] })),
  3610. remove: vi.fn(async () => ({ status: 200, body: { success: true } })),
  3611. removeBatch: vi.fn(async () => ({
  3612. success: true,
  3613. removedPaths: [],
  3614. failedItems: [],
  3615. })),
  3616. },
  3617. agentReferences: {
  3618. resolveDelegatable: vi.fn(
  3619. async (): Promise<"authorized"> => "authorized",
  3620. ),
  3621. },
  3622. cron: {
  3623. bindAgentCleanup: (service) => mocked.cleanupServices.push(service),
  3624. deleteAgentTasks: vi.fn(async () => undefined),
  3625. },
  3626. agentHost: {
  3627. preparation: {
  3628. configBuilder: {
  3629. config: () => ({
  3630. provider: {},
  3631. dataDir: "/data",
  3632. custom_provider: { "openai-work": {} },
  3633. }),
  3634. skills: {
  3635. listRuntimeSkills: vi.fn(async () => ({
  3636. skills: [],
  3637. refreshedAt: 0,
  3638. })),
  3639. renderCatalog: vi.fn(async () => ""),
  3640. },
  3641. },
  3642. },
  3643. toolSources: {
  3644. resolve: vi.fn(async () => ({
  3645. nativeTools: [],
  3646. mcpEntries: [],
  3647. threadGoalTools: [],
  3648. cuRuntimeAvailable: false,
  3649. })),
  3650. },
  3651. inputPreparation: {
  3652. reminders: {
  3653. buildSystem: vi.fn(async () => ({ content: "" })),
  3654. },
  3655. },
  3656. runner: {},
  3657. executor: { reportFailure: vi.fn() },
  3658. } as never,
  3659. generatedAssets: {
  3660. compressModelImage: vi.fn(() => undefined),
  3661. registerGeneratedAsset: vi.fn(),
  3662. ...generatedAssets,
  3663. },
  3664. promptConfig: { autoUpdate: true },
  3665. promptSnapshots: {
  3666. bind: vi.fn(),
  3667. },
  3668. internalTurnPromptReads: {
  3669. bind: vi.fn(),
  3670. },
  3671. attachmentRegistration: {
  3672. register: vi.fn(async ({ attachments }) => attachments),
  3673. discard: vi.fn(async () => undefined),
  3674. resolveSource: vi.fn(() => undefined),
  3675. },
  3676. channel: {
  3677. finalReplies: { deliver: vi.fn() },
  3678. typing: { start: vi.fn(), end: vi.fn() },
  3679. },
  3680. backgroundTasks: {
  3681. bindRuntimeOwner: vi.fn(),
  3682. recover: vi.fn(async () => undefined),
  3683. pollRecovery: vi.fn(async () => false),
  3684. },
  3685. conversation: {
  3686. bind: async (service) => {
  3687. mocked.conversationBindings.push(service);
  3688. mocked.events.push("conversation:bind");
  3689. },
  3690. fail: vi.fn(),
  3691. shutdown: (error) => mocked.conversationShutdowns.push(error),
  3692. },
  3693. events,
  3694. safety: {
  3695. review: vi.fn(async () => ({ pass: true })),
  3696. },
  3697. greeting: {
  3698. canSend: vi.fn(() => false),
  3699. sendSystemReminder: vi.fn(),
  3700. },
  3701. questionnaires: {
  3702. resolveLocale: vi.fn(() => "en-US"),
  3703. createService: () => mocked.questionnaireService as never,
  3704. bindOwnedAction: (handler, onFailure) => {
  3705. mocked.questionnaireActionBindings.push({ handler, onFailure });
  3706. },
  3707. bindRequestAdmission: vi.fn(),
  3708. },
  3709. sessionV2: {
  3710. bindSessionPinReader: vi.fn(),
  3711. legacyMigration: {
  3712. primaryAgentName: "mavis",
  3713. assets: {
  3714. register: vi.fn(),
  3715. },
  3716. },
  3717. canvasAssets: {
  3718. importDeliverable: vi.fn(async () => undefined),
  3719. importExternal: vi.fn(async () => undefined),
  3720. resolve: vi.fn(async () => undefined),
  3721. },
  3722. diff: {
  3723. capability: {} as never,
  3724. rewind: {} as never,
  3725. inputNavigation: {
  3726. listSessionDiffs: vi.fn(async () => []),
  3727. },
  3728. pruneExpired: vi.fn(async () => undefined),
  3729. deleteSession: vi.fn(async () => undefined),
  3730. },
  3731. communication: {
  3732. deleteSession: vi.fn(async () => undefined),
  3733. },
  3734. channelBindings: {
  3735. listSessionIds: vi.fn(async () => []),
  3736. deleteSession: vi.fn(async () => undefined),
  3737. },
  3738. questionnaires: {
  3739. copyPendingForFork: vi.fn(async () => undefined),
  3740. deleteSession: vi.fn(async () => undefined),
  3741. },
  3742. permissions: {
  3743. copyForFork: vi.fn(async () => undefined),
  3744. deleteSession: vi.fn(async () => undefined),
  3745. },
  3746. goals: {
  3747. deleteSession: vi.fn(async () => undefined),
  3748. getBySession: vi.fn(async () => undefined),
  3749. classifyQueuedItem: vi.fn(async () => "ready" as const),
  3750. pauseActiveForAbort: vi.fn(async () => undefined),
  3751. },
  3752. workspace: {
  3753. defaultDirectory: () => "/workspace",
  3754. },
  3755. },
  3756. mcp: {
  3757. enableLiveMcp: false,
  3758. builtinMatrix: false,
  3759. matrixWebSearchOnly: false,
  3760. },
  3761. plugin: {
  3762. dataDir: "/tmp/plugin",
  3763. authContextGetter: () => undefined,
  3764. fetchImpl: globalThis.fetch,
  3765. metrics: {} as never,
  3766. skill: {} as never,
  3767. standaloneSkillIdentities: async () => ({
  3768. names: new Set(),
  3769. sourceUrls: new Set(),
  3770. }),
  3771. },
  3772. };
  3773. }
  3774. interface CronDeliveryInput {
  3775. readonly cronId: string;
  3776. readonly runId: string;
  3777. readonly sessionId: string;
  3778. readonly text: string;
  3779. }
  3780. describe("runtime services Agent reference projection", () => {
  3781. type AgentReferenceResolver = (requestRef: string) => Promise<unknown>;
  3782. const resetAgentGet = () => {
  3783. mocked.agentService.get.mockReset();
  3784. mocked.agentService.get.mockResolvedValue(undefined as never);
  3785. };
  3786. beforeEach(resetAgentGet);
  3787. afterEach(resetAgentGet);
  3788. async function composeAgentReferenceResolver(
  3789. compatibility: V1ServiceCompatibility,
  3790. ): Promise<{
  3791. readonly services: RuntimeServices;
  3792. readonly resolve: AgentReferenceResolver;
  3793. }> {
  3794. const services = await createRuntimeServices({
  3795. db: {} as AppDb,
  3796. dataDir: "/data",
  3797. scheduler: {} as SchedulerClient,
  3798. eventBus: new EventBus<GlobalEvent>(),
  3799. compatibility,
  3800. agentService: localAgentService,
  3801. });
  3802. const product = mocked.agentHostOptions?.["product"] as
  3803. | {
  3804. readonly inputPreparation: {
  3805. readonly agentReferenceProjection: {
  3806. readonly resolveAgentReference: AgentReferenceResolver;
  3807. };
  3808. };
  3809. }
  3810. | undefined;
  3811. if (!product) {
  3812. await services.close();
  3813. throw new Error("Agent reference projection was not composed.");
  3814. }
  3815. return {
  3816. services,
  3817. resolve:
  3818. product.inputPreparation.agentReferenceProjection.resolveAgentReference,
  3819. };
  3820. }
  3821. it("reads a trusted display name only after authorization", async () => {
  3822. const compatibility = defaultCompatibility();
  3823. const resolveDelegatable = vi.mocked(
  3824. compatibility.agentReferences.resolveDelegatable,
  3825. );
  3826. const order: string[] = [];
  3827. resolveDelegatable.mockImplementation(async (requestRef) => {
  3828. order.push(`authorize:${requestRef}`);
  3829. return "authorized";
  3830. });
  3831. mocked.agentService.get.mockImplementation(async () => {
  3832. order.push("read");
  3833. return { displayName: "马来 / 两个圈" } as never;
  3834. });
  3835. const { services, resolve } =
  3836. await composeAgentReferenceResolver(compatibility);
  3837. try {
  3838. await expect(resolve("agent:9007199254740993123")).resolves.toEqual({
  3839. status: "authorized",
  3840. trustedDisplayName: "马来 / 两个圈",
  3841. });
  3842. expect(order).toEqual(["authorize:agent:9007199254740993123", "read"]);
  3843. expect(mocked.agentService.get).toHaveBeenCalledWith(
  3844. "agent:9007199254740993123",
  3845. );
  3846. } finally {
  3847. await services.close();
  3848. }
  3849. });
  3850. it("does not read an Agent when delegation is denied", async () => {
  3851. const compatibility = defaultCompatibility();
  3852. vi.mocked(
  3853. compatibility.agentReferences.resolveDelegatable,
  3854. ).mockResolvedValue("unauthorized");
  3855. const { services, resolve } =
  3856. await composeAgentReferenceResolver(compatibility);
  3857. try {
  3858. await expect(resolve("agent:9007199254740993123")).resolves.toBe(
  3859. "unauthorized",
  3860. );
  3861. expect(mocked.agentService.get).not.toHaveBeenCalled();
  3862. } finally {
  3863. await services.close();
  3864. }
  3865. });
  3866. it("keeps authorization when the trusted Agent read fails", async () => {
  3867. const compatibility = defaultCompatibility();
  3868. mocked.agentService.get.mockRejectedValue(new Error("Agent read failed"));
  3869. const { services, resolve } =
  3870. await composeAgentReferenceResolver(compatibility);
  3871. try {
  3872. await expect(resolve("agent:9007199254740993123")).resolves.toEqual({
  3873. status: "authorized",
  3874. });
  3875. } finally {
  3876. await services.close();
  3877. }
  3878. });
  3879. it("keeps authorization when the trusted display name is blank", async () => {
  3880. const compatibility = defaultCompatibility();
  3881. mocked.agentService.get.mockResolvedValue({ displayName: " " } as never);
  3882. const { services, resolve } =
  3883. await composeAgentReferenceResolver(compatibility);
  3884. try {
  3885. await expect(resolve("agent:9007199254740993123")).resolves.toEqual({
  3886. status: "authorized",
  3887. });
  3888. } finally {
  3889. await services.close();
  3890. }
  3891. });
  3892. });
  3893. describe("runtime services primary family execution identity", () => {
  3894. interface ComposedAgentSources {
  3895. readonly agents: {
  3896. getExecutionSnapshot(
  3897. agentName: string,
  3898. context?: { sessionId: string; sessionKind?: "task" },
  3899. ): Promise<
  3900. | {
  3901. readonly agentName: string;
  3902. readonly executionOwnerName?: string;
  3903. readonly resourceAgentName?: string;
  3904. readonly displayName?: string;
  3905. readonly agentRole?: string;
  3906. readonly metadata?: Record<string, unknown>;
  3907. }
  3908. | undefined
  3909. >;
  3910. };
  3911. readonly preparation: {
  3912. readonly configBuilder: {
  3913. readonly profile: {
  3914. render(input: {
  3915. readonly session: unknown;
  3916. readonly agent: unknown;
  3917. readonly isSessionFirstTurn: boolean;
  3918. }): Promise<unknown>;
  3919. };
  3920. };
  3921. };
  3922. }
  3923. function view(
  3924. name: string,
  3925. displayName: string,
  3926. canonicalViewName = "mavis",
  3927. ) {
  3928. return {
  3929. exactOwnerName: name,
  3930. requestRef: canonicalViewName,
  3931. canonicalViewName,
  3932. resolvedAgentName: canonicalViewName,
  3933. agentRole: "orchestrator",
  3934. creationSource: "builtin" as const,
  3935. displayName,
  3936. };
  3937. }
  3938. async function composeAgentSources(
  3939. logger = noopLogger,
  3940. ): Promise<ComposedAgentSources> {
  3941. await createRuntimeServices({
  3942. db: {} as AppDb,
  3943. dataDir: "/data",
  3944. logger,
  3945. scheduler: {} as SchedulerClient,
  3946. eventBus: new EventBus<GlobalEvent>(),
  3947. compatibility: defaultCompatibility(),
  3948. agentService: localAgentService,
  3949. });
  3950. return mocked.agentHostOptions?.[
  3951. "product"
  3952. ] as unknown as ComposedAgentSources;
  3953. }
  3954. function primaryFamilyViews(canonicalDisplayName: string): void {
  3955. mocked.agentService.getPersistedOwnerForFrozenTask.mockImplementation(
  3956. async (name) =>
  3957. name === "mavis"
  3958. ? view("mavis", canonicalDisplayName)
  3959. : name === "main"
  3960. ? view("main", "Legacy Main")
  3961. : undefined,
  3962. );
  3963. mocked.agentService.resolvePrimaryExecutionIdentity.mockImplementation(
  3964. async (name) => ({
  3965. storageOwnerName: name,
  3966. executionOwnerName: "mavis",
  3967. outcome: "canonical" as const,
  3968. }),
  3969. );
  3970. }
  3971. it("binds Task Session definition reads into the production execution source", async () => {
  3972. mocked.sessionSystem.sessions.records.ensureSessionAgentDefinition.mockResolvedValueOnce(
  3973. {
  3974. sessionId: "saved-session",
  3975. definition: {
  3976. definitionVersion: 2,
  3977. exactOwnerName: "deleted-agent",
  3978. ownerInstanceId: "old-instance",
  3979. systemPrompt: "saved prompt",
  3980. capabilities: {
  3981. tools: [],
  3982. mcpServers: [],
  3983. skills: [],
  3984. extensionSkills: [],
  3985. },
  3986. model: { providerId: "minimax", modelId: "MiniMax-M3" },
  3987. project: { workspaceDir: "/workspace", isDefaultWorkspace: false },
  3988. },
  3989. },
  3990. );
  3991. const sources = await composeAgentSources();
  3992. await expect(
  3993. sources.agents.getExecutionSnapshot("deleted-agent", {
  3994. sessionId: "saved-session",
  3995. sessionKind: "task",
  3996. }),
  3997. ).resolves.toMatchObject({
  3998. agentName: "deleted-agent",
  3999. systemPrompt: "saved prompt",
  4000. });
  4001. expect(
  4002. mocked.sessionSystem.sessions.records.ensureSessionAgentDefinition,
  4003. ).toHaveBeenCalledWith("saved-session");
  4004. expect(
  4005. mocked.agentService.getPersistedOwnerForFrozenTask,
  4006. ).not.toHaveBeenCalled();
  4007. });
  4008. it("keeps the main storage owner while sourcing identity from canonical mavis", async () => {
  4009. primaryFamilyViews("Mavis Canonical");
  4010. const info = vi.fn();
  4011. const sources = await composeAgentSources({ ...noopLogger, info });
  4012. await expect(
  4013. sources.agents.getExecutionSnapshot("main"),
  4014. ).resolves.toMatchObject({
  4015. agentName: "main",
  4016. executionOwnerName: "mavis",
  4017. resourceAgentName: "mavis",
  4018. displayName: "Mavis Canonical",
  4019. metadata: { requestRef: "mavis", canonicalViewName: "mavis" },
  4020. });
  4021. await expect(
  4022. sources.agents.getExecutionSnapshot("mavis"),
  4023. ).resolves.toMatchObject({
  4024. agentName: "mavis",
  4025. executionOwnerName: "mavis",
  4026. resourceAgentName: "mavis",
  4027. displayName: "Mavis Canonical",
  4028. });
  4029. expect(info).toHaveBeenCalledWith(
  4030. { storage_owner: "main", execution_owner: "mavis", outcome: "canonical" },
  4031. "primary_agent_execution_identity",
  4032. );
  4033. });
  4034. it("renders the Turn profile from the resolved execution owner, not the storage owner", async () => {
  4035. primaryFamilyViews("Mavis Canonical");
  4036. mocked.agentService.renderProfile.mockResolvedValue({
  4037. requestRef: "mavis",
  4038. resourceReadRef: "mavis",
  4039. exactOwnerName: "mavis",
  4040. canonicalViewName: "mavis",
  4041. resolvedAgentName: "mavis",
  4042. agentRole: "orchestrator",
  4043. creationSource: "builtin",
  4044. surface: "interactive",
  4045. memoryReadAgentNames: ["mavis", "main"],
  4046. corePrompt: "core",
  4047. surfacePrompt: "surface",
  4048. capabilityCeiling: {
  4049. personaEnabled: true,
  4050. features: { mavis: true, delegation: true, webSearch: true },
  4051. },
  4052. provenance: {
  4053. source: "builtin",
  4054. assetAgentName: "mavis",
  4055. locale: "en-US",
  4056. },
  4057. } as never);
  4058. const sources = await composeAgentSources();
  4059. const snapshot = await sources.agents.getExecutionSnapshot("main");
  4060. await expect(
  4061. sources.preparation.configBuilder.profile.render({
  4062. session: {
  4063. sessionId: "session-1",
  4064. sessionType: "root",
  4065. sessionKind: "conversation",
  4066. },
  4067. agent: snapshot,
  4068. isSessionFirstTurn: true,
  4069. }),
  4070. // Memory keeps reading the whole trusted family; behaviour does not.
  4071. ).resolves.toMatchObject({ memoryReadAgentNames: ["mavis", "main"] });
  4072. expect(mocked.agentService.renderProfile).toHaveBeenCalledWith(
  4073. expect.objectContaining({
  4074. exactOwnerName: "mavis",
  4075. requestRef: "mavis",
  4076. capabilities: undefined,
  4077. }),
  4078. );
  4079. });
  4080. it("leaves every non-primary Agent executing as its own persisted row", async () => {
  4081. mocked.agentService.getPersistedOwnerForFrozenTask.mockImplementation(
  4082. async (name) =>
  4083. name === "explore" ? view("explore", "Explore", "explore") : undefined,
  4084. );
  4085. const info = vi.fn();
  4086. const sources = await composeAgentSources({ ...noopLogger, info });
  4087. await expect(
  4088. sources.agents.getExecutionSnapshot("explore"),
  4089. ).resolves.toMatchObject({
  4090. agentName: "explore",
  4091. executionOwnerName: "explore",
  4092. });
  4093. expect(info).not.toHaveBeenCalled();
  4094. });
  4095. });