services.test.ts 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331
  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("production Session title policy wiring", () => {
  2269. it("skips the signed-out gateway only for the selected BYOK Session", async () => {
  2270. const compatibility = defaultCompatibility();
  2271. const review = vi.mocked(compatibility.safety.review);
  2272. review.mockResolvedValue({ pass: false, errorKind: "auth_error" });
  2273. await createRuntimeServices({
  2274. db: {} as AppDb, dataDir: "/data", logger: noopLogger,
  2275. eventBus: new EventBus<GlobalEvent>(), compatibility,
  2276. agentService: localAgentService, runtimeOwnerKind: "tui", capabilityProfile: "cli",
  2277. });
  2278. const policy = mocked.sessionOptions?.["titlePolicy"] as import("./service/session-system/index.js").SessionRecordServiceDeps["titlePolicy"];
  2279. const session: import("./service/session-system/index.js").SessionRecord = {
  2280. sessionId: "rename", agentName: "test", workspaceDir: "/data",
  2281. runtime: "pi-agent", sessionType: "branch", sessionKind: "conversation",
  2282. archived: false, status: "idle", createdAtMs: 1, updatedAtMs: 1,
  2283. effectiveModel: "custom_provider:openai-work/test-model",
  2284. };
  2285. review.mockClear();
  2286. await expect(policy.blocks("Local rename", session)).resolves.toBe(false);
  2287. expect(review).not.toHaveBeenCalled();
  2288. await expect(policy.blocks("Managed rename", { ...session, effectiveModel: "minimax/MiniMax-M3" })).resolves.toBe(true);
  2289. expect(review).toHaveBeenCalledWith("Managed rename", 205);
  2290. });
  2291. });
  2292. describe("runtime startup preserves Session model selections", () => {
  2293. it.each(["tui", "electron"] as const)(
  2294. "does not scan or rewrite shared Sessions for %s",
  2295. async (runtimeOwnerKind) => {
  2296. await createRuntimeServices({
  2297. db: {} as AppDb,
  2298. dataDir: "/data/shared",
  2299. logger: noopLogger,
  2300. scheduler: {} as SchedulerClient,
  2301. eventBus: new EventBus<GlobalEvent>(),
  2302. compatibility: defaultCompatibility(),
  2303. agentService: localAgentService,
  2304. runtimeOwnerKind,
  2305. capabilityProfile: "cli",
  2306. promptConfigKey: new Uint8Array(32).fill(7),
  2307. });
  2308. expect(
  2309. mocked.sessionSystem.repositories.sessions.list,
  2310. ).not.toHaveBeenCalled();
  2311. expect(
  2312. mocked.sessionSystem.repositories.sessions.update,
  2313. ).not.toHaveBeenCalled();
  2314. },
  2315. );
  2316. });
  2317. describe("runtime services LLM retry progress projection", () => {
  2318. it("wires the product retry observer into the production AgentHost", async () => {
  2319. const eventBus = new EventBus<GlobalEvent>();
  2320. const events: GlobalEvent[] = [];
  2321. eventBus.subscribe({ next: (event) => events.push(event) });
  2322. await createRuntimeServices({
  2323. db: {} as AppDb,
  2324. dataDir: "/data/tui-retry-visibility",
  2325. logger: noopLogger,
  2326. eventBus,
  2327. compatibility: defaultCompatibility(),
  2328. agentService: localAgentService,
  2329. runtimeOwnerKind: "tui",
  2330. capabilityProfile: "cli",
  2331. nowMs: () => 123,
  2332. });
  2333. const resolveLlmRetry = mocked.agentHostOptions?.["resolveLlmRetry"] as
  2334. | ((
  2335. input: unknown,
  2336. ) =>
  2337. | NonNullable<RunTurnInput["llmRetry"]>
  2338. | Promise<NonNullable<RunTurnInput["llmRetry"]>>)
  2339. | undefined;
  2340. expect(resolveLlmRetry).toEqual(expect.any(Function));
  2341. const retryOptions = await resolveLlmRetry?.({});
  2342. const waiting: LLMRetryEvent = {
  2343. sessionId: "session-1",
  2344. turnId: "turn-1",
  2345. callId: "call-1",
  2346. scope: "agent",
  2347. status: "waiting",
  2348. retryAttempt: 1,
  2349. maxRetries: 5,
  2350. requestAttempt: 2,
  2351. delayMs: 1_000,
  2352. nextRetryAtMs: 2_000,
  2353. error: {
  2354. reason: "network",
  2355. message: "LLM provider network request failed",
  2356. },
  2357. };
  2358. await retryOptions?.observer?.(waiting);
  2359. expect(events).toContainEqual({
  2360. type: "session.llm_retry",
  2361. timestamp: 123,
  2362. source: "local-runtime",
  2363. payload: { schemaVersion: 1, ...waiting },
  2364. });
  2365. });
  2366. });
  2367. describe("runtime services region content-review policy", () => {
  2368. it("disables content review only for the overseas TUI runtime", async () => {
  2369. mocked.runtimeRegion = "en";
  2370. await createRuntimeServices({
  2371. db: {} as AppDb,
  2372. dataDir: "/data/tui-overseas",
  2373. logger: noopLogger,
  2374. eventBus: new EventBus<GlobalEvent>(),
  2375. compatibility: defaultCompatibility(),
  2376. agentService: localAgentService,
  2377. runtimeOwnerKind: "tui",
  2378. capabilityProfile: "cli",
  2379. });
  2380. expect(mocked.agentHostOptions).toMatchObject({
  2381. cliProductPolicy: true,
  2382. tuiProductPolicy: true,
  2383. contentReviewEnabled: false,
  2384. });
  2385. });
  2386. it("does not apply the TUI region policy to the legacy CLI runtime", async () => {
  2387. mocked.runtimeRegion = "en";
  2388. await createRuntimeServices({
  2389. db: {} as AppDb,
  2390. dataDir: "/data/cli-overseas",
  2391. logger: noopLogger,
  2392. eventBus: new EventBus<GlobalEvent>(),
  2393. compatibility: defaultCompatibility(),
  2394. agentService: localAgentService,
  2395. runtimeOwnerKind: "cli",
  2396. capabilityProfile: "cli",
  2397. });
  2398. expect(mocked.agentHostOptions).toMatchObject({ cliProductPolicy: true });
  2399. expect(mocked.agentHostOptions).not.toHaveProperty("tuiProductPolicy");
  2400. expect(mocked.agentHostOptions).not.toHaveProperty("contentReviewEnabled");
  2401. });
  2402. });
  2403. describe("runtime active-steer consumption", () => {
  2404. it("publishes Message SSE and wakes the frontend resume path", async () => {
  2405. const eventBus = new EventBus<GlobalEvent>();
  2406. const events: GlobalEvent[] = [];
  2407. eventBus.subscribe({ next: (event) => events.push(event) });
  2408. mocked.sessionSystem.sessions.repository.get.mockResolvedValue({
  2409. sessionId: "session-1",
  2410. agentName: "mavis",
  2411. });
  2412. await createRuntimeServices({
  2413. db: {} as AppDb,
  2414. dataDir: "/data",
  2415. scheduler: {} as SchedulerClient,
  2416. eventBus,
  2417. compatibility: defaultCompatibility(),
  2418. agentService: localAgentService,
  2419. nowMs: () => 100,
  2420. });
  2421. const onSteeringConsumed = mocked.agentHostOptions?.[
  2422. "onSteeringConsumed"
  2423. ] as (input: Record<string, unknown>) => Promise<void>;
  2424. await onSteeringConsumed({
  2425. sessionId: "session-1",
  2426. turnId: "turn-active",
  2427. message: {
  2428. producerId: "communication",
  2429. idempotencyKey: "message-1",
  2430. message: { text: "hello" },
  2431. provenance: {
  2432. source: "communication",
  2433. routingFingerprint: "communication:message-1",
  2434. },
  2435. },
  2436. });
  2437. expect(
  2438. mocked.sessionSystem.messages.userMessages.commit,
  2439. ).toHaveBeenCalledOnce();
  2440. expect(mocked.sessionSystem.stream.write).toHaveBeenCalledWith(
  2441. expect.objectContaining({
  2442. kind: "message-committed",
  2443. turnId: "turn-active",
  2444. }),
  2445. );
  2446. expect(events).toContainEqual({
  2447. type: "session.start",
  2448. timestamp: 100,
  2449. source: "local-runtime",
  2450. payload: {
  2451. sessionId: "session-1",
  2452. agentName: "mavis",
  2453. turnId: "turn-active",
  2454. },
  2455. });
  2456. });
  2457. });
  2458. describe("runtime services Plugin Hook durable fence composition", () => {
  2459. type CapturedFence = {
  2460. run(input: {
  2461. readonly sessionId: string;
  2462. readonly reason: "archive" | "idle_timeout";
  2463. readonly idleSinceMs?: number;
  2464. readonly sessionOwnershipClaim?: string;
  2465. readonly operation: (signal?: AbortSignal) => Promise<unknown>;
  2466. }): Promise<unknown>;
  2467. };
  2468. async function configureFence(): Promise<CapturedFence> {
  2469. await createRuntimeServices({
  2470. db: {} as AppDb,
  2471. dataDir: "/data",
  2472. scheduler: {} as SchedulerClient,
  2473. eventBus: new EventBus<GlobalEvent>(),
  2474. compatibility: defaultCompatibility(),
  2475. agentService: localAgentService,
  2476. });
  2477. return mocked.pluginHookSessionEndFence as CapturedFence;
  2478. }
  2479. it("wires durable ownership into AgentHost and fences SessionEnd by Hook claim", async () => {
  2480. mocked.turnSystem.inspection.latestTurnActivity.mockResolvedValue({
  2481. turnId: "newer-admitted-without-hook-claim",
  2482. acceptedAtMs: 200,
  2483. activityAtMs: 200,
  2484. } as never);
  2485. const fence = await configureFence();
  2486. expect(mocked.agentHostOptions?.["pluginHookSessionOwnership"]).toBe(
  2487. mocked.hostPluginHookSessionOwnership,
  2488. );
  2489. const operation = vi.fn(async (signal?: AbortSignal) => ({ signal }));
  2490. await expect(
  2491. fence.run({
  2492. sessionId: "session-1",
  2493. reason: "archive",
  2494. sessionOwnershipClaim: "owner-turn-1",
  2495. operation,
  2496. }),
  2497. ).resolves.toMatchObject({ status: "executed" });
  2498. expect(operation).toHaveBeenCalledWith(expect.any(AbortSignal));
  2499. expect(
  2500. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd,
  2501. ).toHaveBeenCalledWith({
  2502. sessionId: "session-1",
  2503. ownershipClaimId: "owner-turn-1",
  2504. sessionEndClaimId: "owner-turn-1:session-end",
  2505. reason: "archive",
  2506. });
  2507. expect(
  2508. mocked.turnSystem.pluginHookSessionOwnership.completeSessionEnd,
  2509. ).toHaveBeenCalledOnce();
  2510. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd.mockResolvedValueOnce(
  2511. {
  2512. status: "already-claimed",
  2513. } as never,
  2514. );
  2515. const duplicate = vi.fn(async () => undefined);
  2516. await expect(
  2517. fence.run({
  2518. sessionId: "session-1",
  2519. reason: "archive",
  2520. sessionOwnershipClaim: "owner-turn-1",
  2521. operation: duplicate,
  2522. }),
  2523. ).resolves.toEqual({ status: "superseded" });
  2524. expect(duplicate).not.toHaveBeenCalled();
  2525. });
  2526. it("executes SessionEnd without a maintenance signal when exclusive fencing is unavailable", async () => {
  2527. const tryRunExclusive = mocked.turnSystem.sessionLifecycle.tryRunExclusive;
  2528. const sessionLifecycle = mocked.turnSystem.sessionLifecycle as {
  2529. tryRunExclusive?: typeof tryRunExclusive;
  2530. };
  2531. sessionLifecycle.tryRunExclusive = undefined;
  2532. try {
  2533. const fence = await configureFence();
  2534. const operation = vi.fn(async () => "completed");
  2535. await expect(
  2536. fence.run({
  2537. sessionId: "session-1",
  2538. reason: "archive",
  2539. sessionOwnershipClaim: "owner-turn-1",
  2540. operation,
  2541. }),
  2542. ).resolves.toEqual({ status: "executed", result: "completed" });
  2543. expect(operation).toHaveBeenCalledWith();
  2544. expect(
  2545. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd,
  2546. ).not.toHaveBeenCalled();
  2547. } finally {
  2548. sessionLifecycle.tryRunExclusive = tryRunExclusive;
  2549. }
  2550. });
  2551. it("supersedes SessionEnd when the durable ownership claim is absent or stale", async () => {
  2552. const fence = await configureFence();
  2553. const operation = vi.fn(async () => undefined);
  2554. mocked.turnSystem.pluginHookSessionOwnership.latest
  2555. .mockResolvedValueOnce(undefined as never)
  2556. .mockResolvedValueOnce({ ownershipClaimId: "owner-turn-2" } as never);
  2557. for (const sessionId of ["missing-owner", "stale-owner"]) {
  2558. await expect(
  2559. fence.run({
  2560. sessionId,
  2561. reason: "archive",
  2562. sessionOwnershipClaim: "owner-turn-1",
  2563. operation,
  2564. }),
  2565. ).resolves.toEqual({ status: "superseded" });
  2566. }
  2567. expect(operation).not.toHaveBeenCalled();
  2568. expect(
  2569. mocked.turnSystem.pluginHookSessionOwnership.tryClaimSessionEnd,
  2570. ).not.toHaveBeenCalled();
  2571. });
  2572. it("defers a stale idle sweep but executes after activity remains at the observed boundary", async () => {
  2573. const fence = await configureFence();
  2574. const operation = vi.fn(async () => "completed");
  2575. mocked.turnSystem.inspection.latestTurnActivity
  2576. .mockResolvedValueOnce({ activityAtMs: 201 } as never)
  2577. .mockResolvedValueOnce({ activityAtMs: 200 } as never);
  2578. await expect(
  2579. fence.run({
  2580. sessionId: "session-1",
  2581. reason: "idle_timeout",
  2582. idleSinceMs: 200,
  2583. sessionOwnershipClaim: "owner-turn-1",
  2584. operation,
  2585. }),
  2586. ).resolves.toEqual({ status: "deferred", latestActivityAtMs: 201 });
  2587. expect(operation).not.toHaveBeenCalled();
  2588. await expect(
  2589. fence.run({
  2590. sessionId: "session-1",
  2591. reason: "idle_timeout",
  2592. idleSinceMs: 200,
  2593. sessionOwnershipClaim: "owner-turn-1",
  2594. operation,
  2595. }),
  2596. ).resolves.toEqual({ status: "executed", result: "completed" });
  2597. expect(operation).toHaveBeenCalledWith(expect.any(AbortSignal));
  2598. });
  2599. });
  2600. describe("runtime services Cron composition", () => {
  2601. it("keeps Cron-specific test overrides inside service composition", async () => {
  2602. const customDelivery = {
  2603. deliver: async () => ({ delivered: true as const }),
  2604. };
  2605. const sessionPorts = {
  2606. sessionCreation: {},
  2607. delivery: mocked.defaultDelivery,
  2608. };
  2609. const services = await createRuntimeServices({
  2610. db: {} as AppDb,
  2611. dataDir: "/data",
  2612. logger: noopLogger,
  2613. scheduler: {} as SchedulerClient,
  2614. eventBus: new EventBus<GlobalEvent>(),
  2615. compatibility: defaultCompatibility(),
  2616. agentService: localAgentService,
  2617. overrides: {
  2618. cron: {
  2619. sessionPorts: sessionPorts as never,
  2620. turnDelivery: customDelivery,
  2621. },
  2622. },
  2623. });
  2624. expect(mocked.events).toEqual([
  2625. "session:create",
  2626. "channel:create",
  2627. "mcp:create",
  2628. "plugin:create",
  2629. "turn:create",
  2630. "session-applications:create",
  2631. "applications:create",
  2632. "cron:create",
  2633. ]);
  2634. expect(mocked.cronOptions).toMatchObject({
  2635. sessionPorts,
  2636. });
  2637. expect(mocked.cronOptions).not.toHaveProperty("turnDelivery");
  2638. expect(services.cronDelivery).toBe(customDelivery);
  2639. });
  2640. it("routes scheduled and generated Cron delivery through the same steer-or-activate port", async () => {
  2641. const compatibility = defaultCompatibility();
  2642. const services = await createRuntimeServices({
  2643. db: {} as AppDb,
  2644. dataDir: "/data",
  2645. scheduler: {} as SchedulerClient,
  2646. eventBus: new EventBus<GlobalEvent>(),
  2647. compatibility,
  2648. agentService: localAgentService,
  2649. });
  2650. const scheduledDelivery = (
  2651. mocked.cronOptions?.["sessionPorts"] as {
  2652. readonly delivery: {
  2653. deliver(input: CronDeliveryInput): Promise<unknown>;
  2654. };
  2655. }
  2656. ).delivery;
  2657. const request: CronDeliveryInput = {
  2658. cronId: "cron-1",
  2659. runId: "run-1",
  2660. sessionId: "session-1",
  2661. text: "inspect the build",
  2662. };
  2663. await expect(scheduledDelivery.deliver(request)).resolves.toEqual({
  2664. delivered: true,
  2665. });
  2666. await expect(services.cronDelivery?.deliver(request)).resolves.toEqual({
  2667. delivered: true,
  2668. });
  2669. expect(mocked.turnSystem.turns.steer).toHaveBeenCalledTimes(2);
  2670. expect(mocked.turnSystem.turns.steer).toHaveBeenNthCalledWith(1, {
  2671. sessionId: "session-1",
  2672. input: { text: "inspect the build" },
  2673. producerId: "cron:cron-1",
  2674. idempotencyKey: "run-1",
  2675. provenance: {
  2676. source: "cron",
  2677. routingFingerprint: "cron:cron-1:run-1",
  2678. sourceContext: { cronId: "cron-1", runId: "run-1" },
  2679. },
  2680. });
  2681. expect(mocked.turnSystem.turns.steer).toHaveBeenNthCalledWith(
  2682. 2,
  2683. expect.objectContaining({
  2684. producerId: "cron:cron-1",
  2685. idempotencyKey: "run-1",
  2686. }),
  2687. );
  2688. });
  2689. it("disables persisted Cron recovery for a quarantined runtime clone", async () => {
  2690. await createRuntimeServices({
  2691. db: {} as AppDb,
  2692. dataDir: "/data",
  2693. scheduler: {} as SchedulerClient,
  2694. eventBus: new EventBus<GlobalEvent>(),
  2695. compatibility: defaultCompatibility(),
  2696. agentService: localAgentService,
  2697. recoverPersistedState: false,
  2698. });
  2699. expect(mocked.cronOptions).toMatchObject({ recoverPendingRuns: false });
  2700. });
  2701. });
  2702. describe("runtime Root lifecycle diagnostics", () => {
  2703. it("routes v2 Root participant failures through the production reporter", async () => {
  2704. const compatibility = defaultCompatibility();
  2705. await createRuntimeServices({
  2706. db: {} as AppDb,
  2707. dataDir: "/data",
  2708. scheduler: {} as SchedulerClient,
  2709. eventBus: new EventBus<GlobalEvent>(),
  2710. compatibility,
  2711. agentService: localAgentService,
  2712. });
  2713. const rootDiagnostics = mocked.applicationOptions as {
  2714. readonly onRootBestEffortFailure: (input: {
  2715. readonly stage: "turn-abort";
  2716. readonly sessionId: string;
  2717. readonly error: unknown;
  2718. }) => void;
  2719. };
  2720. rootDiagnostics.onRootBestEffortFailure({
  2721. stage: "turn-abort",
  2722. sessionId: "root-1",
  2723. error: new Error("abort failed"),
  2724. });
  2725. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  2726. "root-1",
  2727. "root_replacement_abort_failed:abort failed",
  2728. );
  2729. });
  2730. });
  2731. describe("runtime Session Application composition", () => {
  2732. it.each([false, true])(
  2733. "cleans both MCP scopes when disposing a session (agent failure: %s)",
  2734. async (fails) => {
  2735. const services = await createRuntimeServices({
  2736. db: {} as AppDb,
  2737. dataDir: "/data",
  2738. scheduler: {} as SchedulerClient,
  2739. eventBus: new EventBus<GlobalEvent>(),
  2740. compatibility: defaultCompatibility(),
  2741. agentService: localAgentService,
  2742. });
  2743. const dispose = mocked.turnOptions?.disposeRuntimeSession;
  2744. if (!dispose)
  2745. throw new Error("Runtime session disposal was not composed");
  2746. if (fails)
  2747. mocked.agentRuntimeLifecycle.disposeSession.mockRejectedValueOnce(
  2748. new Error("agent disposal failed"),
  2749. );
  2750. const disposing = dispose("session-mcp");
  2751. if (fails)
  2752. await expect(disposing).rejects.toThrow("agent disposal failed");
  2753. else await disposing;
  2754. expect(mocked.agentRuntimeLifecycle.disposeSession).toHaveBeenCalledWith(
  2755. "session-mcp",
  2756. );
  2757. expect(mocked.mcp.disposeSession).toHaveBeenCalledWith("session-mcp");
  2758. await services.close();
  2759. },
  2760. );
  2761. it("resumes Session deletion through the bound Application lifecycle", async () => {
  2762. const services = await createRuntimeServices({
  2763. db: {} as AppDb,
  2764. dataDir: "/data",
  2765. scheduler: {} as SchedulerClient,
  2766. eventBus: new EventBus<GlobalEvent>(),
  2767. compatibility: defaultCompatibility(),
  2768. agentService: localAgentService,
  2769. });
  2770. const resumeSessionDeletion = mocked.turnOptions?.resumeSessionDeletion;
  2771. if (!resumeSessionDeletion)
  2772. throw new Error("Session deletion recovery was not composed");
  2773. await resumeSessionDeletion("session-deleting");
  2774. expect(
  2775. mocked.runtimeApplications.session.lifecycle.deleteSessionById,
  2776. ).toHaveBeenCalledWith("session-deleting");
  2777. await services.close();
  2778. });
  2779. it("always composes Applications over the main SessionSystem owner graph", async () => {
  2780. const db = {} as AppDb;
  2781. const compatibility = defaultCompatibility();
  2782. const services = await createRuntimeServices({
  2783. db,
  2784. dataDir: "/data",
  2785. scheduler: {} as SchedulerClient,
  2786. eventBus: new EventBus<GlobalEvent>(),
  2787. compatibility,
  2788. agentService: localAgentService,
  2789. });
  2790. expect(mocked.sessionApplicationOptions).toMatchObject({
  2791. owner: mocked.sessionSystem,
  2792. canvas: services.canvas,
  2793. compatibility: compatibility.sessionV2,
  2794. maintenance: mocked.turnSystem.maintenance,
  2795. facts: mocked.applicationFactPorts,
  2796. });
  2797. expect(mocked.applicationFactOptions).toEqual({
  2798. publish: expect.any(Function),
  2799. });
  2800. expect(mocked.applicationOptions).toMatchObject({
  2801. sessionSystem: mocked.initializedSessionApplicationSystem,
  2802. compatibility: compatibility.sessionV2,
  2803. turn: mocked.turnSystem.turns,
  2804. });
  2805. expect(services.applications).toBe(mocked.runtimeApplications);
  2806. mocked.events.length = 0;
  2807. await services.ready();
  2808. expect(mocked.events).toEqual([
  2809. "session:ready",
  2810. "plan-documents:reconcile",
  2811. "mcp:ready",
  2812. "plugin:ready",
  2813. "turn:ready",
  2814. "conversation:bind",
  2815. "questionnaire:recover",
  2816. "questionnaire:plan-reconcile:true",
  2817. "cron:ready",
  2818. ]);
  2819. await expect(services.builtinAgentDefinitionsReady).resolves.toBe(true);
  2820. expect(mocked.events.at(-1)).toBe("agent:ensure");
  2821. expect(mocked.agentService.ensureBuiltinRows).toHaveBeenCalledOnce();
  2822. expect(
  2823. mocked.agentService.bindBuiltinModelGroupResolver,
  2824. ).toHaveBeenCalledWith(expect.any(Function));
  2825. expect(
  2826. mocked.agentService.bindConfigPreviewDiagnostics,
  2827. ).toHaveBeenCalledWith(expect.any(Function));
  2828. expect(
  2829. mocked.agentService.bindEffectiveConfigResolver,
  2830. ).toHaveBeenCalledWith(expect.any(Function));
  2831. expect(
  2832. mocked.agentService.bindCandidateModelValidator,
  2833. ).toHaveBeenCalledWith(expect.any(Function));
  2834. mocked.events.length = 0;
  2835. await services.close();
  2836. expect(mocked.events).toEqual([
  2837. "cron:close",
  2838. "turn:close",
  2839. "plugin:close",
  2840. "mcp:close",
  2841. "session:close",
  2842. ]);
  2843. });
  2844. });
  2845. describe("runtime persisted-state recovery policy", () => {
  2846. it("skips persisted Questionnaire and Plan recovery for a quarantined runtime clone", async () => {
  2847. const services = await createRuntimeServices({
  2848. db: {} as AppDb,
  2849. dataDir: "/data",
  2850. scheduler: {} as SchedulerClient,
  2851. eventBus: new EventBus<GlobalEvent>(),
  2852. compatibility: defaultCompatibility(),
  2853. recoverPersistedState: false,
  2854. agentService: localAgentService,
  2855. });
  2856. mocked.events.length = 0;
  2857. await services.ready();
  2858. expect(mocked.events).toEqual([
  2859. "session:ready",
  2860. "mcp:ready",
  2861. "plugin:ready",
  2862. "turn:ready",
  2863. "conversation:bind",
  2864. "cron:ready",
  2865. ]);
  2866. await expect(services.builtinAgentDefinitionsReady).resolves.toBe(true);
  2867. expect(mocked.events.at(-1)).toBe("agent:ensure");
  2868. });
  2869. });
  2870. describe("Goal verifier service binding", () => {
  2871. it("binds both backends, immutable transcript capture, and the readonly child extension", async () => {
  2872. const bindVerifier =
  2873. vi.fn<
  2874. NonNullable<
  2875. V1ServiceCompatibility["sessionV2"]["goals"]["bindVerifier"]
  2876. >
  2877. >();
  2878. const compatibility = defaultCompatibility();
  2879. Object.assign(compatibility.sessionV2.goals, { bindVerifier });
  2880. const canonicalMessage = { role: "user", content: "fixed evidence" };
  2881. mocked.sessionSystem.canonicalHistory.inspectActive.mockResolvedValue({
  2882. revision: "sha256:goal-evaluator",
  2883. messages: [canonicalMessage],
  2884. });
  2885. const services = await createRuntimeServices({
  2886. db: {} as AppDb,
  2887. dataDir: "/data",
  2888. scheduler: {} as SchedulerClient,
  2889. eventBus: new EventBus<GlobalEvent>(),
  2890. compatibility,
  2891. agentService: localAgentService,
  2892. });
  2893. expect(bindVerifier).toHaveBeenCalledOnce();
  2894. const [verifier, reader] = bindVerifier.mock.calls[0] ?? [];
  2895. expect(verifier?.dispatch).toEqual(expect.any(Function));
  2896. expect(mocked.agentHostOptions?.["normalExtensions"]).toEqual(
  2897. expect.arrayContaining([
  2898. expect.objectContaining({ id: "local-goal-verifier-readonly" }),
  2899. expect.objectContaining({ id: "local-goal-budget-summary" }),
  2900. ]),
  2901. );
  2902. // Without this the child's per-request cap would never reach the Turn, and
  2903. // only the coordinator's cumulative check would remain.
  2904. const outputTokenCap = mocked.agentHostOptions?.["outputTokenCap"] as
  2905. | { resolveOutputTokenCap: (input: unknown) => number | undefined }
  2906. | undefined;
  2907. expect(outputTokenCap?.resolveOutputTokenCap).toEqual(expect.any(Function));
  2908. expect(outputTokenCap?.resolveOutputTokenCap({})).toBeUndefined();
  2909. const captured = await reader?.capture("session-goal");
  2910. canonicalMessage.content = "concurrent mutation";
  2911. expect(captured).toEqual({
  2912. messages: [{ role: "user", content: "fixed evidence" }],
  2913. truncated: false,
  2914. });
  2915. expect(
  2916. mocked.sessionSystem.canonicalHistory.inspectActive,
  2917. ).toHaveBeenCalledWith("session-goal");
  2918. await services.close();
  2919. });
  2920. it("captures only the newest bounded Goal verifier transcript and reports truncation", async () => {
  2921. const bindVerifier =
  2922. vi.fn<
  2923. NonNullable<
  2924. V1ServiceCompatibility["sessionV2"]["goals"]["bindVerifier"]
  2925. >
  2926. >();
  2927. const compatibility = defaultCompatibility();
  2928. Object.assign(compatibility.sessionV2.goals, { bindVerifier });
  2929. const canonicalMessages = Array.from({ length: 201 }, (_, index) => ({
  2930. role: "user",
  2931. content: `evidence-${index}`,
  2932. }));
  2933. mocked.sessionSystem.canonicalHistory.inspectActive.mockResolvedValue({
  2934. revision: "sha256:goal-evaluator-bounded",
  2935. messages: canonicalMessages,
  2936. });
  2937. const services = await createRuntimeServices({
  2938. db: {} as AppDb,
  2939. dataDir: "/data",
  2940. scheduler: {} as SchedulerClient,
  2941. eventBus: new EventBus<GlobalEvent>(),
  2942. compatibility,
  2943. agentService: localAgentService,
  2944. });
  2945. const [, reader] = bindVerifier.mock.calls[0] ?? [];
  2946. const captured = await reader?.capture("session-goal-bounded");
  2947. const newestCanonicalMessage = canonicalMessages.at(-1);
  2948. if (!newestCanonicalMessage)
  2949. throw new Error("expected bounded canonical transcript");
  2950. newestCanonicalMessage.content = "concurrent mutation";
  2951. expect(captured).toMatchObject({
  2952. truncated: true,
  2953. truncationNote: expect.stringContaining("newest 200 messages"),
  2954. });
  2955. expect(captured?.messages).toHaveLength(200);
  2956. expect(captured?.messages[0]).toEqual({
  2957. role: "user",
  2958. content: "evidence-1",
  2959. });
  2960. expect(captured?.messages[199]).toEqual({
  2961. role: "user",
  2962. content: "evidence-200",
  2963. });
  2964. await services.close();
  2965. });
  2966. });
  2967. describe("runtime Browser services lifecycle", () => {
  2968. it("treats an unspecified runtime owner as Desktop Plugin-managed Browser activation", async () => {
  2969. const compatibility = defaultCompatibility();
  2970. Object.assign(compatibility.agentHost.preparation.configBuilder, {
  2971. config: () => ({
  2972. provider: {},
  2973. dataDir: "/data",
  2974. custom_provider: { "openai-work": {} },
  2975. beta: { filePanelBrowser: true, browserUseTooling: true },
  2976. }),
  2977. });
  2978. const services = await createRuntimeServices({
  2979. db: {} as AppDb,
  2980. dataDir: "/data",
  2981. scheduler: {} as SchedulerClient,
  2982. eventBus: new EventBus<GlobalEvent>(),
  2983. compatibility,
  2984. browserUse: { adapter: { execute: vi.fn() } },
  2985. agentService: localAgentService,
  2986. });
  2987. expect(services.browserUse.builtinSkillDescriptor()).toBeUndefined();
  2988. expect(
  2989. services.browserUse.admitQuestionnaireRequest({
  2990. request: {
  2991. mode: "feature-enable",
  2992. modePayload: { featureKey: "browser-use" },
  2993. },
  2994. }),
  2995. ).toMatchObject({ status: 403, code: "BROWSER_PLUGIN_MANAGED" });
  2996. await services.close();
  2997. });
  2998. it("clears V2 Browser receipts only for committed context-reset rewinds", async () => {
  2999. const compatibility = defaultCompatibility();
  3000. Object.assign(compatibility.agentHost.preparation.configBuilder, {
  3001. config: () => ({
  3002. provider: {},
  3003. dataDir: "/data",
  3004. custom_provider: { "openai-work": {} },
  3005. beta: { filePanelBrowser: true, browserUseTooling: true },
  3006. }),
  3007. });
  3008. const services = await createRuntimeServices({
  3009. db: {} as AppDb,
  3010. dataDir: "/data",
  3011. scheduler: {} as SchedulerClient,
  3012. eventBus: new EventBus<GlobalEvent>(),
  3013. compatibility,
  3014. browserUse: { adapter: { execute: vi.fn() } },
  3015. agentService: localAgentService,
  3016. runtimeOwnerKind: "cli",
  3017. });
  3018. const publish = mocked.applicationFactOptions?.["publish"] as (
  3019. event: GlobalEventInput,
  3020. ) => void;
  3021. const baseSkill = {
  3022. def: LocalSkillToolDef,
  3023. impl: { execute: vi.fn(async () => ({ content: [] })) },
  3024. } as unknown as RuntimeTool;
  3025. const browserCapability = services.browserUse.resolveTurnCapability({
  3026. sessionId: "assembly-session",
  3027. turnId: "assembly-turn",
  3028. surface: "interactive",
  3029. workspaceRoot: "/data",
  3030. baseTools: [baseSkill],
  3031. });
  3032. const skill = browserCapability.tools.find(
  3033. (candidate) => candidate.def.name === "skill",
  3034. );
  3035. const browser = browserCapability.tools.find(
  3036. (candidate) => candidate.def.name === "browser",
  3037. );
  3038. if (!skill || !browser) throw new Error("expected Browser tools");
  3039. for (const sessionId of [
  3040. "session-reset",
  3041. "session-ui-only",
  3042. "session-deleted",
  3043. ]) {
  3044. await skill.impl.execute(
  3045. { sessionId, turnId: "turn-a" },
  3046. {
  3047. name: "control-in-app-browser",
  3048. },
  3049. );
  3050. }
  3051. services.browserUse.turnContext.record({
  3052. sessionId: "session-reset",
  3053. turnId: "turn-reset",
  3054. inAppBrowser: { visible: true, selectedTab: true },
  3055. });
  3056. services.browserUse.turnContext.record({
  3057. sessionId: "session-deleted",
  3058. turnId: "turn-deleted",
  3059. inAppBrowser: { visible: true, selectedTab: false },
  3060. });
  3061. publish({
  3062. type: "message.rewind",
  3063. payload: { sessionId: "session-reset", contextReset: true },
  3064. });
  3065. publish({
  3066. type: "message.rewind",
  3067. payload: { sessionId: "session-ui-only", contextReset: false },
  3068. });
  3069. publish({
  3070. type: "content.retry.exceeded",
  3071. payload: { sessionId: "session-retry", variant: "content" },
  3072. });
  3073. publish({
  3074. type: "session.deleted",
  3075. payload: { sessionId: "session-deleted" },
  3076. });
  3077. await expect(
  3078. browser.impl.execute(
  3079. { sessionId: "session-reset", turnId: "turn-a" },
  3080. {
  3081. action: "inspect",
  3082. input: {},
  3083. },
  3084. ),
  3085. ).resolves.toMatchObject({
  3086. isError: true,
  3087. details: { code: "SKILL_REQUIRED" },
  3088. });
  3089. await expect(
  3090. browser.impl.execute(
  3091. { sessionId: "session-ui-only", turnId: "turn-a" },
  3092. {
  3093. action: "inspect",
  3094. input: {},
  3095. },
  3096. ),
  3097. ).resolves.toMatchObject({ details: { action: "inspect" } });
  3098. expect(
  3099. services.browserUse.turnContext.read("session-reset", "turn-reset"),
  3100. ).toEqual({
  3101. visible: true,
  3102. selectedTab: true,
  3103. });
  3104. await expect(
  3105. browser.impl.execute(
  3106. { sessionId: "session-deleted", turnId: "turn-a" },
  3107. {
  3108. action: "inspect",
  3109. input: {},
  3110. },
  3111. ),
  3112. ).resolves.toMatchObject({
  3113. isError: true,
  3114. details: { code: "SKILL_REQUIRED" },
  3115. });
  3116. expect(
  3117. services.browserUse.turnContext.read("session-deleted", "turn-deleted"),
  3118. ).toBeUndefined();
  3119. await services.close();
  3120. });
  3121. });
  3122. describe("runtime services lifecycle", () => {
  3123. it("keeps startup available when ordinary Questionnaire recovery fails", async () => {
  3124. const failure = new Error("Questionnaire query failed");
  3125. mocked.questionnaireService.recoverOnStartup.mockRejectedValueOnce(failure);
  3126. const compatibility = defaultCompatibility();
  3127. const services = await createRuntimeServices({
  3128. db: {} as AppDb,
  3129. dataDir: "/data",
  3130. scheduler: {} as SchedulerClient,
  3131. eventBus: new EventBus<GlobalEvent>(),
  3132. compatibility,
  3133. agentService: localAgentService,
  3134. });
  3135. await expect(services.ready()).resolves.toBeUndefined();
  3136. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  3137. "questionnaire-recovery",
  3138. "owner=questionnaire;stage=startup-recovery;error=Questionnaire query failed",
  3139. );
  3140. });
  3141. it("keeps startup available when Plan draft recovery reports isolated failures", async () => {
  3142. const failure = new AggregateError(
  3143. [new Error("bad manifest")],
  3144. "draft recovery failed",
  3145. );
  3146. mocked.sessionSystem.planDocuments.reconcilePreparedDrafts.mockRejectedValueOnce(
  3147. failure,
  3148. );
  3149. const compatibility = defaultCompatibility();
  3150. const services = await createRuntimeServices({
  3151. db: {} as AppDb,
  3152. dataDir: "/data",
  3153. scheduler: {} as SchedulerClient,
  3154. eventBus: new EventBus<GlobalEvent>(),
  3155. compatibility,
  3156. agentService: localAgentService,
  3157. });
  3158. await expect(services.ready()).resolves.toBeUndefined();
  3159. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  3160. "plan-document-recovery",
  3161. "owner=session-system;component=plan-document;stage=startup-reconcile;error=draft recovery failed",
  3162. );
  3163. });
  3164. it("accepts v1 events through the injected write port once and detaches on close", async () => {
  3165. let publish:
  3166. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3167. | undefined;
  3168. const unbind = vi.fn();
  3169. const bindPublisher = vi.fn<
  3170. V1ServiceCompatibility["events"]["bindPublisher"]
  3171. >((publisher) => {
  3172. publish = publisher;
  3173. return unbind;
  3174. });
  3175. const eventBus = new EventBus<GlobalEvent>();
  3176. const compatibility = defaultCompatibility({ bindPublisher });
  3177. const services = await createRuntimeServices({
  3178. db: {} as AppDb,
  3179. dataDir: "/data",
  3180. scheduler: {} as SchedulerClient,
  3181. eventBus,
  3182. compatibility,
  3183. agentService: localAgentService,
  3184. nowMs: () => 1_700_000_000_000,
  3185. });
  3186. const received: GlobalEvent[] = [];
  3187. services.globalEvents.subscribe({ next: (event) => received.push(event) });
  3188. expect(publish).toBeUndefined();
  3189. await services.ready();
  3190. publish?.({ type: "agent.created", payload: { agentName: "mavis" } });
  3191. expect(received).toEqual([
  3192. {
  3193. type: "agent.created",
  3194. timestamp: 1_700_000_000_000,
  3195. source: "local-runtime",
  3196. payload: { agentName: "mavis" },
  3197. },
  3198. ]);
  3199. publish?.({
  3200. type: "session.finish",
  3201. payload: {
  3202. sessionId: "session-1",
  3203. agentName: "mavis",
  3204. turnId: "turn-greeting",
  3205. status: "finished",
  3206. },
  3207. });
  3208. expect(received[1]).toMatchObject({
  3209. type: "session.finish",
  3210. payload: { turnId: "turn-greeting" },
  3211. });
  3212. publish?.({
  3213. type: "session.error",
  3214. payload: {
  3215. sessionId: "session-1",
  3216. agentName: "mavis",
  3217. turnId: "turn-failed-greeting",
  3218. status: "error",
  3219. },
  3220. });
  3221. publish?.({
  3222. type: "session.abort",
  3223. payload: {
  3224. sessionId: "session-1",
  3225. agentName: "mavis",
  3226. turnId: "turn-cancelled-greeting",
  3227. status: "aborted",
  3228. },
  3229. });
  3230. await services.close();
  3231. expect(bindPublisher).toHaveBeenCalledOnce();
  3232. expect(unbind).toHaveBeenCalledOnce();
  3233. expect(mocked.conversationShutdowns).toHaveLength(1);
  3234. publish?.({ type: "agent.created", payload: { agentName: "late-event" } });
  3235. expect(received).toHaveLength(4);
  3236. });
  3237. });
  3238. describe("runtime services readiness and shutdown", () => {
  3239. it("swallows greeting terminal persistence failures without leaking a rejection", async () => {
  3240. let publish:
  3241. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3242. | undefined;
  3243. const bindPublisher = vi.fn<
  3244. V1ServiceCompatibility["events"]["bindPublisher"]
  3245. >((publisher) => {
  3246. publish = publisher;
  3247. return () => undefined;
  3248. });
  3249. const compatibility = defaultCompatibility({ bindPublisher });
  3250. const services = await createRuntimeServices({
  3251. db: {} as AppDb,
  3252. dataDir: "/data",
  3253. scheduler: {} as SchedulerClient,
  3254. eventBus: new EventBus<GlobalEvent>(),
  3255. compatibility,
  3256. agentService: localAgentService,
  3257. greetingEnabled: true,
  3258. });
  3259. await services.ready();
  3260. const notification = vi.mocked(services.agent.notifyGreetingTurnTerminal);
  3261. notification.mockRejectedValueOnce(
  3262. new Error("greeting state write failed"),
  3263. );
  3264. publish?.({
  3265. type: "session.finish",
  3266. payload: {
  3267. sessionId: "session-1",
  3268. agentName: "mavis",
  3269. turnId: "turn-greeting-persistence-failure",
  3270. status: "finished",
  3271. },
  3272. });
  3273. await Promise.resolve();
  3274. expect(notification).toHaveBeenCalledOnce();
  3275. await services.close();
  3276. });
  3277. });
  3278. describe("runtime services ready and close", () => {
  3279. it("runs post-infra service readiness once and preserves its failure", async () => {
  3280. const failure = new Error("Cron recovery failed");
  3281. mocked.readyError = failure;
  3282. const services = await createRuntimeServices({
  3283. db: {} as AppDb,
  3284. dataDir: "/data",
  3285. logger: noopLogger,
  3286. scheduler: {} as SchedulerClient,
  3287. eventBus: new EventBus<GlobalEvent>(),
  3288. compatibility: defaultCompatibility(),
  3289. agentService: localAgentService,
  3290. });
  3291. const first = services.ready();
  3292. const second = services.ready();
  3293. expect(second).toBe(first);
  3294. await expect(first).rejects.toBe(failure);
  3295. expect(mocked.conversationBindings).toEqual([mocked.conversationService]);
  3296. expect(mocked.events).toEqual([
  3297. "session:create",
  3298. "channel:create",
  3299. "mcp:create",
  3300. "plugin:create",
  3301. "turn:create",
  3302. "session-applications:create",
  3303. "applications:create",
  3304. "cron:create",
  3305. "session:ready",
  3306. "plan-documents:reconcile",
  3307. "mcp:ready",
  3308. "plugin:ready",
  3309. "turn:ready",
  3310. "conversation:bind",
  3311. "questionnaire:recover",
  3312. "questionnaire:plan-reconcile:true",
  3313. "cron:ready",
  3314. ]);
  3315. });
  3316. it("keeps runtime startup available while a failed Plan recovery retries after Queue readiness", async () => {
  3317. const failure = new Error("Plan recovery temporarily unavailable");
  3318. mocked.questionnaireService.reconcileOwnedActions.mockRejectedValueOnce(
  3319. failure,
  3320. );
  3321. const compatibility = defaultCompatibility();
  3322. const services = await createRuntimeServices({
  3323. db: {} as AppDb,
  3324. dataDir: "/data",
  3325. scheduler: {} as SchedulerClient,
  3326. eventBus: new EventBus<GlobalEvent>(),
  3327. compatibility,
  3328. agentService: localAgentService,
  3329. });
  3330. await expect(services.ready()).resolves.toBeUndefined();
  3331. await vi.waitFor(() => {
  3332. expect(mocked.events).toContain("questionnaire:plan-reconcile:true");
  3333. });
  3334. await expect(services.builtinAgentDefinitionsReady).resolves.toBe(true);
  3335. expect(mocked.events.filter((event) => event !== "agent:ensure")).toEqual([
  3336. "session:create",
  3337. "channel:create",
  3338. "mcp:create",
  3339. "plugin:create",
  3340. "turn:create",
  3341. "session-applications:create",
  3342. "applications:create",
  3343. "cron:create",
  3344. "session:ready",
  3345. "plan-documents:reconcile",
  3346. "mcp:ready",
  3347. "plugin:ready",
  3348. "turn:ready",
  3349. "conversation:bind",
  3350. "questionnaire:recover",
  3351. "cron:ready",
  3352. "questionnaire:plan-reconcile:true",
  3353. ]);
  3354. expect(
  3355. mocked.events.filter((event) => event === "agent:ensure"),
  3356. ).toHaveLength(1);
  3357. expect(compatibility.agentHost.executor.reportFailure).toHaveBeenCalledWith(
  3358. "plan-lifecycle",
  3359. "owner=plan;stage=lifecycle-reconcile;error=Plan recovery temporarily unavailable",
  3360. );
  3361. await services.close();
  3362. });
  3363. it("shares close, closes Cron once, and cannot become ready afterwards", async () => {
  3364. const bindPublisher = vi.fn(() => () => undefined);
  3365. const services = await createRuntimeServices({
  3366. db: {} as AppDb,
  3367. dataDir: "/data",
  3368. logger: noopLogger,
  3369. scheduler: {} as SchedulerClient,
  3370. eventBus: new EventBus<GlobalEvent>(),
  3371. compatibility: defaultCompatibility({ bindPublisher }),
  3372. agentService: localAgentService,
  3373. });
  3374. mocked.events.length = 0;
  3375. const closePreview = vi.spyOn(services.workspace.htmlPreview, "close");
  3376. const first = services.close();
  3377. const second = services.close();
  3378. expect(second).toBe(first);
  3379. await first;
  3380. expect(closePreview).toHaveBeenCalledTimes(1);
  3381. await services.ready();
  3382. expect(mocked.events).toEqual([
  3383. "cron:close",
  3384. "turn:close",
  3385. "plugin:close",
  3386. "mcp:close",
  3387. "session:close",
  3388. ]);
  3389. expect(bindPublisher).not.toHaveBeenCalled();
  3390. expect(mocked.conversationShutdowns).toHaveLength(1);
  3391. });
  3392. it("closes Cron when publisher cleanup fails and preserves the first failure", async () => {
  3393. const failure = new Error("global events close failed");
  3394. const compatibility = defaultCompatibility({
  3395. bindPublisher: () => () => {
  3396. throw failure;
  3397. },
  3398. });
  3399. const services = await createRuntimeServices({
  3400. db: {} as AppDb,
  3401. dataDir: "/data",
  3402. scheduler: {} as SchedulerClient,
  3403. eventBus: new EventBus<GlobalEvent>(),
  3404. compatibility,
  3405. agentService: localAgentService,
  3406. });
  3407. await services.ready();
  3408. mocked.events.length = 0;
  3409. const closePreview = vi.spyOn(services.workspace.htmlPreview, "close");
  3410. await expect(services.close()).rejects.toBe(failure);
  3411. expect(closePreview).toHaveBeenCalledTimes(1);
  3412. expect(mocked.events).toEqual([
  3413. "cron:close",
  3414. "turn:close",
  3415. "plugin:close",
  3416. "mcp:close",
  3417. "session:close",
  3418. ]);
  3419. });
  3420. });
  3421. describe("runtime services greeting terminal timing", () => {
  3422. it("invokes greeting terminal observation before publishing the terminal event", async () => {
  3423. let publish:
  3424. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3425. | undefined;
  3426. const bindPublisher = vi.fn<
  3427. V1ServiceCompatibility["events"]["bindPublisher"]
  3428. >((publisher) => {
  3429. publish = publisher;
  3430. return () => undefined;
  3431. });
  3432. const eventBus = new EventBus<GlobalEvent>();
  3433. const order: string[] = [];
  3434. eventBus.subscribe({ next: () => order.push("event") });
  3435. const services = await createRuntimeServices({
  3436. db: {} as AppDb,
  3437. dataDir: "/data",
  3438. scheduler: {} as SchedulerClient,
  3439. eventBus,
  3440. compatibility: defaultCompatibility({ bindPublisher }),
  3441. agentService: localAgentService,
  3442. greetingEnabled: true,
  3443. });
  3444. await services.ready();
  3445. const notification = vi.mocked(services.agent.notifyGreetingTurnTerminal);
  3446. notification.mockImplementationOnce(() => {
  3447. order.push("notify");
  3448. return Promise.resolve();
  3449. });
  3450. publish?.({
  3451. type: "session.finish",
  3452. payload: {
  3453. sessionId: "session-1",
  3454. agentName: "mavis",
  3455. turnId: "turn-greeting-order",
  3456. status: "finished",
  3457. },
  3458. });
  3459. expect(order).toEqual(["notify", "event"]);
  3460. await services.close();
  3461. });
  3462. it("swallows synchronous greeting terminal observer failures", async () => {
  3463. let publish:
  3464. | Parameters<V1ServiceCompatibility["events"]["bindPublisher"]>[0]
  3465. | undefined;
  3466. const bindPublisher = vi.fn<
  3467. V1ServiceCompatibility["events"]["bindPublisher"]
  3468. >((publisher) => {
  3469. publish = publisher;
  3470. return () => undefined;
  3471. });
  3472. const services = await createRuntimeServices({
  3473. db: {} as AppDb,
  3474. dataDir: "/data",
  3475. scheduler: {} as SchedulerClient,
  3476. eventBus: new EventBus<GlobalEvent>(),
  3477. compatibility: defaultCompatibility({ bindPublisher }),
  3478. agentService: localAgentService,
  3479. greetingEnabled: true,
  3480. });
  3481. await services.ready();
  3482. const notification = vi.mocked(services.agent.notifyGreetingTurnTerminal);
  3483. notification.mockImplementationOnce(() => {
  3484. throw new Error("synchronous greeting observer failure");
  3485. });
  3486. publish?.({
  3487. type: "session.finish",
  3488. payload: {
  3489. sessionId: "session-1",
  3490. agentName: "mavis",
  3491. turnId: "turn-greeting-sync-failure",
  3492. status: "finished",
  3493. },
  3494. });
  3495. expect(notification).toHaveBeenCalledOnce();
  3496. await services.close();
  3497. });
  3498. });
  3499. describe("runtime Plan lifecycle recovery", () => {
  3500. it("releases recovered Plan review Queue work only after TurnSystem is ready", async () => {
  3501. mocked.questionnaireService.reconcileOwnedActions.mockImplementationOnce(
  3502. async (dispatch: boolean) => {
  3503. mocked.events.push(`questionnaire:plan-reconcile:${String(dispatch)}`);
  3504. const binding = mocked.questionnaireActionBindings[0] as {
  3505. readonly handler: QuestionnaireOwnedActionHandler;
  3506. };
  3507. await binding.handler.afterConsumed?.({
  3508. record: {
  3509. requestId: "plan-review-request",
  3510. sessionId: "session-plan-review",
  3511. request: {
  3512. mode: "plan",
  3513. modePayload: {
  3514. planReview: {
  3515. markdown: "# Frozen plan",
  3516. path: "/history/session-1/artifacts/plan.md",
  3517. },
  3518. },
  3519. },
  3520. } as never,
  3521. action: {
  3522. kind: "reply",
  3523. reply: {
  3524. schemaVersion: 2,
  3525. requestId: "plan-review-request",
  3526. answers: [
  3527. {
  3528. stepId: "plan-review-decision",
  3529. selectedOptionIds: ["approve"],
  3530. selectedOther: false,
  3531. },
  3532. ],
  3533. submittedAt: 1_700_000_000_000,
  3534. },
  3535. },
  3536. dispatch,
  3537. });
  3538. return 1;
  3539. },
  3540. );
  3541. mocked.turnSystem.turns.dispatchQueue.mockImplementationOnce(
  3542. async (sessionId: string) => {
  3543. mocked.events.push(`queue:dispatch:${sessionId}`);
  3544. },
  3545. );
  3546. const services = await createRuntimeServices({
  3547. db: {} as AppDb,
  3548. dataDir: "/data",
  3549. scheduler: {} as SchedulerClient,
  3550. eventBus: new EventBus<GlobalEvent>(),
  3551. compatibility: defaultCompatibility(),
  3552. agentService: localAgentService,
  3553. });
  3554. await services.ready();
  3555. await vi.waitFor(() => {
  3556. expect(mocked.events).toContain("queue:dispatch:session-plan-review");
  3557. });
  3558. expect(
  3559. mocked.events.indexOf("queue:dispatch:session-plan-review"),
  3560. ).toBeGreaterThan(mocked.events.indexOf("turn:ready"));
  3561. await services.close();
  3562. });
  3563. });
  3564. async function assertWorkspaceBashFileSourceResolution(): Promise<void> {
  3565. // The rollout kill switch keeps the extension out of every composed runtime,
  3566. // so exercise the retained implementation directly for future re-enable.
  3567. const compatibility = defaultCompatibility();
  3568. const extension = createRuntimeSourceReferenceExtension(
  3569. compatibility.attachmentRegistration,
  3570. );
  3571. const runtime = await createAgentRuntime({ base: [extension] });
  3572. const turn = baseCtx({
  3573. sessionId: "session-workspace-source",
  3574. turnId: "turn-workspace-source",
  3575. workspaceDir: "/workspace/project",
  3576. });
  3577. const assembly = await runtime.assembleTurn(turn);
  3578. const afterToolCall = assembly.hooks.afterToolCallHook?.[0];
  3579. if (!afterToolCall)
  3580. throw new Error("source-reference tool hook was not registered");
  3581. const insidePatch = await afterToolCall({
  3582. assistantMessage: {} as never,
  3583. toolCall: { id: "bash-inside", name: "bash" } as never,
  3584. args: {
  3585. command: "unzip -q /workspace/project/demo.docx -d /tmp/docx_extract",
  3586. },
  3587. result: { content: [{ type: "text", text: "document body" }], details: {} },
  3588. isError: false,
  3589. context: {} as never,
  3590. });
  3591. const outsidePatch = await afterToolCall({
  3592. assistantMessage: {} as never,
  3593. toolCall: { id: "bash-outside", name: "bash" } as never,
  3594. args: { command: "unzip -q /outside/private.docx -d /tmp/docx_extract" },
  3595. result: { content: [{ type: "text", text: "private body" }], details: {} },
  3596. isError: false,
  3597. context: {} as never,
  3598. });
  3599. expect(insidePatch?.content?.at(-1)).toEqual({
  3600. type: "text",
  3601. text: expect.stringContaining(
  3602. "Citation candidate: [demo.docx](#mavis-source=file:L3dvcmtzcGFjZS9wcm9qZWN0L2RlbW8uZG9jeA)",
  3603. ),
  3604. });
  3605. expect(insidePatch?.details).toMatchObject({
  3606. source_references: [
  3607. expect.objectContaining({
  3608. type: "file",
  3609. path: "/workspace/project/demo.docx",
  3610. name: "demo.docx",
  3611. }),
  3612. ],
  3613. });
  3614. expect(outsidePatch).toBeUndefined();
  3615. expect(
  3616. compatibility.attachmentRegistration.resolveSource,
  3617. ).toHaveBeenCalledTimes(2);
  3618. }
  3619. function defaultCompatibility(
  3620. events: V1ServiceCompatibility["events"] = {
  3621. bindPublisher: () => () => undefined,
  3622. },
  3623. generatedAssets: Partial<V1ServiceCompatibility["generatedAssets"]> = {},
  3624. ): V1ServiceCompatibility {
  3625. return {
  3626. sandbox: { writeConfig: vi.fn(async () => undefined) },
  3627. modelProvider: { refreshOfficialModels: vi.fn(async () => undefined) },
  3628. peripherals: {} as never,
  3629. skills: {
  3630. listSkills: vi.fn(async () => ({ skills: [], hasMore: false })),
  3631. } as never,
  3632. managedWorktrees: {
  3633. list: vi.fn(async () => ({ success: true, worktrees: [] })),
  3634. remove: vi.fn(async () => ({ status: 200, body: { success: true } })),
  3635. removeBatch: vi.fn(async () => ({
  3636. success: true,
  3637. removedPaths: [],
  3638. failedItems: [],
  3639. })),
  3640. },
  3641. agentReferences: {
  3642. resolveDelegatable: vi.fn(
  3643. async (): Promise<"authorized"> => "authorized",
  3644. ),
  3645. },
  3646. cron: {
  3647. bindAgentCleanup: (service) => mocked.cleanupServices.push(service),
  3648. deleteAgentTasks: vi.fn(async () => undefined),
  3649. },
  3650. agentHost: {
  3651. preparation: {
  3652. configBuilder: {
  3653. config: () => ({
  3654. provider: {},
  3655. dataDir: "/data",
  3656. custom_provider: { "openai-work": {} },
  3657. }),
  3658. skills: {
  3659. listRuntimeSkills: vi.fn(async () => ({
  3660. skills: [],
  3661. refreshedAt: 0,
  3662. })),
  3663. renderCatalog: vi.fn(async () => ""),
  3664. },
  3665. },
  3666. },
  3667. toolSources: {
  3668. resolve: vi.fn(async () => ({
  3669. nativeTools: [],
  3670. mcpEntries: [],
  3671. threadGoalTools: [],
  3672. cuRuntimeAvailable: false,
  3673. })),
  3674. },
  3675. inputPreparation: {
  3676. reminders: {
  3677. buildSystem: vi.fn(async () => ({ content: "" })),
  3678. },
  3679. },
  3680. runner: {},
  3681. executor: { reportFailure: vi.fn() },
  3682. } as never,
  3683. generatedAssets: {
  3684. compressModelImage: vi.fn(() => undefined),
  3685. registerGeneratedAsset: vi.fn(),
  3686. ...generatedAssets,
  3687. },
  3688. promptConfig: { autoUpdate: true },
  3689. promptSnapshots: {
  3690. bind: vi.fn(),
  3691. },
  3692. internalTurnPromptReads: {
  3693. bind: vi.fn(),
  3694. },
  3695. attachmentRegistration: {
  3696. register: vi.fn(async ({ attachments }) => attachments),
  3697. discard: vi.fn(async () => undefined),
  3698. resolveSource: vi.fn(() => undefined),
  3699. },
  3700. channel: {
  3701. finalReplies: { deliver: vi.fn() },
  3702. typing: { start: vi.fn(), end: vi.fn() },
  3703. },
  3704. backgroundTasks: {
  3705. bindRuntimeOwner: vi.fn(),
  3706. recover: vi.fn(async () => undefined),
  3707. pollRecovery: vi.fn(async () => false),
  3708. },
  3709. conversation: {
  3710. bind: async (service) => {
  3711. mocked.conversationBindings.push(service);
  3712. mocked.events.push("conversation:bind");
  3713. },
  3714. fail: vi.fn(),
  3715. shutdown: (error) => mocked.conversationShutdowns.push(error),
  3716. },
  3717. events,
  3718. safety: {
  3719. review: vi.fn(async () => ({ pass: true })),
  3720. },
  3721. greeting: {
  3722. canSend: vi.fn(() => false),
  3723. sendSystemReminder: vi.fn(),
  3724. },
  3725. questionnaires: {
  3726. resolveLocale: vi.fn(() => "en-US"),
  3727. createService: () => mocked.questionnaireService as never,
  3728. bindOwnedAction: (handler, onFailure) => {
  3729. mocked.questionnaireActionBindings.push({ handler, onFailure });
  3730. },
  3731. bindRequestAdmission: vi.fn(),
  3732. },
  3733. sessionV2: {
  3734. bindSessionPinReader: vi.fn(),
  3735. legacyMigration: {
  3736. primaryAgentName: "mavis",
  3737. assets: {
  3738. register: vi.fn(),
  3739. },
  3740. },
  3741. canvasAssets: {
  3742. importDeliverable: vi.fn(async () => undefined),
  3743. importExternal: vi.fn(async () => undefined),
  3744. resolve: vi.fn(async () => undefined),
  3745. },
  3746. diff: {
  3747. capability: {} as never,
  3748. rewind: {} as never,
  3749. inputNavigation: {
  3750. listSessionDiffs: vi.fn(async () => []),
  3751. },
  3752. pruneExpired: vi.fn(async () => undefined),
  3753. deleteSession: vi.fn(async () => undefined),
  3754. },
  3755. communication: {
  3756. deleteSession: vi.fn(async () => undefined),
  3757. },
  3758. channelBindings: {
  3759. listSessionIds: vi.fn(async () => []),
  3760. deleteSession: vi.fn(async () => undefined),
  3761. },
  3762. questionnaires: {
  3763. copyPendingForFork: vi.fn(async () => undefined),
  3764. deleteSession: vi.fn(async () => undefined),
  3765. },
  3766. permissions: {
  3767. copyForFork: vi.fn(async () => undefined),
  3768. deleteSession: vi.fn(async () => undefined),
  3769. },
  3770. goals: {
  3771. deleteSession: vi.fn(async () => undefined),
  3772. getBySession: vi.fn(async () => undefined),
  3773. classifyQueuedItem: vi.fn(async () => "ready" as const),
  3774. pauseActiveForAbort: vi.fn(async () => undefined),
  3775. },
  3776. workspace: {
  3777. defaultDirectory: () => "/workspace",
  3778. },
  3779. },
  3780. mcp: {
  3781. enableLiveMcp: false,
  3782. builtinMatrix: false,
  3783. matrixWebSearchOnly: false,
  3784. },
  3785. plugin: {
  3786. dataDir: "/tmp/plugin",
  3787. authContextGetter: () => undefined,
  3788. fetchImpl: globalThis.fetch,
  3789. metrics: {} as never,
  3790. skill: {} as never,
  3791. standaloneSkillIdentities: async () => ({
  3792. names: new Set(),
  3793. sourceUrls: new Set(),
  3794. }),
  3795. },
  3796. };
  3797. }
  3798. interface CronDeliveryInput {
  3799. readonly cronId: string;
  3800. readonly runId: string;
  3801. readonly sessionId: string;
  3802. readonly text: string;
  3803. }
  3804. describe("runtime services Agent reference projection", () => {
  3805. type AgentReferenceResolver = (requestRef: string) => Promise<unknown>;
  3806. const resetAgentGet = () => {
  3807. mocked.agentService.get.mockReset();
  3808. mocked.agentService.get.mockResolvedValue(undefined as never);
  3809. };
  3810. beforeEach(resetAgentGet);
  3811. afterEach(resetAgentGet);
  3812. async function composeAgentReferenceResolver(
  3813. compatibility: V1ServiceCompatibility,
  3814. ): Promise<{
  3815. readonly services: RuntimeServices;
  3816. readonly resolve: AgentReferenceResolver;
  3817. }> {
  3818. const services = await createRuntimeServices({
  3819. db: {} as AppDb,
  3820. dataDir: "/data",
  3821. scheduler: {} as SchedulerClient,
  3822. eventBus: new EventBus<GlobalEvent>(),
  3823. compatibility,
  3824. agentService: localAgentService,
  3825. });
  3826. const product = mocked.agentHostOptions?.["product"] as
  3827. | {
  3828. readonly inputPreparation: {
  3829. readonly agentReferenceProjection: {
  3830. readonly resolveAgentReference: AgentReferenceResolver;
  3831. };
  3832. };
  3833. }
  3834. | undefined;
  3835. if (!product) {
  3836. await services.close();
  3837. throw new Error("Agent reference projection was not composed.");
  3838. }
  3839. return {
  3840. services,
  3841. resolve:
  3842. product.inputPreparation.agentReferenceProjection.resolveAgentReference,
  3843. };
  3844. }
  3845. it("reads a trusted display name only after authorization", async () => {
  3846. const compatibility = defaultCompatibility();
  3847. const resolveDelegatable = vi.mocked(
  3848. compatibility.agentReferences.resolveDelegatable,
  3849. );
  3850. const order: string[] = [];
  3851. resolveDelegatable.mockImplementation(async (requestRef) => {
  3852. order.push(`authorize:${requestRef}`);
  3853. return "authorized";
  3854. });
  3855. mocked.agentService.get.mockImplementation(async () => {
  3856. order.push("read");
  3857. return { displayName: "马来 / 两个圈" } as never;
  3858. });
  3859. const { services, resolve } =
  3860. await composeAgentReferenceResolver(compatibility);
  3861. try {
  3862. await expect(resolve("agent:9007199254740993123")).resolves.toEqual({
  3863. status: "authorized",
  3864. trustedDisplayName: "马来 / 两个圈",
  3865. });
  3866. expect(order).toEqual(["authorize:agent:9007199254740993123", "read"]);
  3867. expect(mocked.agentService.get).toHaveBeenCalledWith(
  3868. "agent:9007199254740993123",
  3869. );
  3870. } finally {
  3871. await services.close();
  3872. }
  3873. });
  3874. it("does not read an Agent when delegation is denied", async () => {
  3875. const compatibility = defaultCompatibility();
  3876. vi.mocked(
  3877. compatibility.agentReferences.resolveDelegatable,
  3878. ).mockResolvedValue("unauthorized");
  3879. const { services, resolve } =
  3880. await composeAgentReferenceResolver(compatibility);
  3881. try {
  3882. await expect(resolve("agent:9007199254740993123")).resolves.toBe(
  3883. "unauthorized",
  3884. );
  3885. expect(mocked.agentService.get).not.toHaveBeenCalled();
  3886. } finally {
  3887. await services.close();
  3888. }
  3889. });
  3890. it("keeps authorization when the trusted Agent read fails", async () => {
  3891. const compatibility = defaultCompatibility();
  3892. mocked.agentService.get.mockRejectedValue(new Error("Agent read failed"));
  3893. const { services, resolve } =
  3894. await composeAgentReferenceResolver(compatibility);
  3895. try {
  3896. await expect(resolve("agent:9007199254740993123")).resolves.toEqual({
  3897. status: "authorized",
  3898. });
  3899. } finally {
  3900. await services.close();
  3901. }
  3902. });
  3903. it("keeps authorization when the trusted display name is blank", async () => {
  3904. const compatibility = defaultCompatibility();
  3905. mocked.agentService.get.mockResolvedValue({ displayName: " " } as never);
  3906. const { services, resolve } =
  3907. await composeAgentReferenceResolver(compatibility);
  3908. try {
  3909. await expect(resolve("agent:9007199254740993123")).resolves.toEqual({
  3910. status: "authorized",
  3911. });
  3912. } finally {
  3913. await services.close();
  3914. }
  3915. });
  3916. });
  3917. describe("runtime services primary family execution identity", () => {
  3918. interface ComposedAgentSources {
  3919. readonly agents: {
  3920. getExecutionSnapshot(
  3921. agentName: string,
  3922. context?: { sessionId: string; sessionKind?: "task" },
  3923. ): Promise<
  3924. | {
  3925. readonly agentName: string;
  3926. readonly executionOwnerName?: string;
  3927. readonly resourceAgentName?: string;
  3928. readonly displayName?: string;
  3929. readonly agentRole?: string;
  3930. readonly metadata?: Record<string, unknown>;
  3931. }
  3932. | undefined
  3933. >;
  3934. };
  3935. readonly preparation: {
  3936. readonly configBuilder: {
  3937. readonly profile: {
  3938. render(input: {
  3939. readonly session: unknown;
  3940. readonly agent: unknown;
  3941. readonly isSessionFirstTurn: boolean;
  3942. }): Promise<unknown>;
  3943. };
  3944. };
  3945. };
  3946. }
  3947. function view(
  3948. name: string,
  3949. displayName: string,
  3950. canonicalViewName = "mavis",
  3951. ) {
  3952. return {
  3953. exactOwnerName: name,
  3954. requestRef: canonicalViewName,
  3955. canonicalViewName,
  3956. resolvedAgentName: canonicalViewName,
  3957. agentRole: "orchestrator",
  3958. creationSource: "builtin" as const,
  3959. displayName,
  3960. };
  3961. }
  3962. async function composeAgentSources(
  3963. logger = noopLogger,
  3964. ): Promise<ComposedAgentSources> {
  3965. await createRuntimeServices({
  3966. db: {} as AppDb,
  3967. dataDir: "/data",
  3968. logger,
  3969. scheduler: {} as SchedulerClient,
  3970. eventBus: new EventBus<GlobalEvent>(),
  3971. compatibility: defaultCompatibility(),
  3972. agentService: localAgentService,
  3973. });
  3974. return mocked.agentHostOptions?.[
  3975. "product"
  3976. ] as unknown as ComposedAgentSources;
  3977. }
  3978. function primaryFamilyViews(canonicalDisplayName: string): void {
  3979. mocked.agentService.getPersistedOwnerForFrozenTask.mockImplementation(
  3980. async (name) =>
  3981. name === "mavis"
  3982. ? view("mavis", canonicalDisplayName)
  3983. : name === "main"
  3984. ? view("main", "Legacy Main")
  3985. : undefined,
  3986. );
  3987. mocked.agentService.resolvePrimaryExecutionIdentity.mockImplementation(
  3988. async (name) => ({
  3989. storageOwnerName: name,
  3990. executionOwnerName: "mavis",
  3991. outcome: "canonical" as const,
  3992. }),
  3993. );
  3994. }
  3995. it("binds Task Session definition reads into the production execution source", async () => {
  3996. mocked.sessionSystem.sessions.records.ensureSessionAgentDefinition.mockResolvedValueOnce(
  3997. {
  3998. sessionId: "saved-session",
  3999. definition: {
  4000. definitionVersion: 2,
  4001. exactOwnerName: "deleted-agent",
  4002. ownerInstanceId: "old-instance",
  4003. systemPrompt: "saved prompt",
  4004. capabilities: {
  4005. tools: [],
  4006. mcpServers: [],
  4007. skills: [],
  4008. extensionSkills: [],
  4009. },
  4010. model: { providerId: "minimax", modelId: "MiniMax-M3" },
  4011. project: { workspaceDir: "/workspace", isDefaultWorkspace: false },
  4012. },
  4013. },
  4014. );
  4015. const sources = await composeAgentSources();
  4016. await expect(
  4017. sources.agents.getExecutionSnapshot("deleted-agent", {
  4018. sessionId: "saved-session",
  4019. sessionKind: "task",
  4020. }),
  4021. ).resolves.toMatchObject({
  4022. agentName: "deleted-agent",
  4023. systemPrompt: "saved prompt",
  4024. });
  4025. expect(
  4026. mocked.sessionSystem.sessions.records.ensureSessionAgentDefinition,
  4027. ).toHaveBeenCalledWith("saved-session");
  4028. expect(
  4029. mocked.agentService.getPersistedOwnerForFrozenTask,
  4030. ).not.toHaveBeenCalled();
  4031. });
  4032. it("keeps the main storage owner while sourcing identity from canonical mavis", async () => {
  4033. primaryFamilyViews("Mavis Canonical");
  4034. const info = vi.fn();
  4035. const sources = await composeAgentSources({ ...noopLogger, info });
  4036. await expect(
  4037. sources.agents.getExecutionSnapshot("main"),
  4038. ).resolves.toMatchObject({
  4039. agentName: "main",
  4040. executionOwnerName: "mavis",
  4041. resourceAgentName: "mavis",
  4042. displayName: "Mavis Canonical",
  4043. metadata: { requestRef: "mavis", canonicalViewName: "mavis" },
  4044. });
  4045. await expect(
  4046. sources.agents.getExecutionSnapshot("mavis"),
  4047. ).resolves.toMatchObject({
  4048. agentName: "mavis",
  4049. executionOwnerName: "mavis",
  4050. resourceAgentName: "mavis",
  4051. displayName: "Mavis Canonical",
  4052. });
  4053. expect(info).toHaveBeenCalledWith(
  4054. { storage_owner: "main", execution_owner: "mavis", outcome: "canonical" },
  4055. "primary_agent_execution_identity",
  4056. );
  4057. });
  4058. it("renders the Turn profile from the resolved execution owner, not the storage owner", async () => {
  4059. primaryFamilyViews("Mavis Canonical");
  4060. mocked.agentService.renderProfile.mockResolvedValue({
  4061. requestRef: "mavis",
  4062. resourceReadRef: "mavis",
  4063. exactOwnerName: "mavis",
  4064. canonicalViewName: "mavis",
  4065. resolvedAgentName: "mavis",
  4066. agentRole: "orchestrator",
  4067. creationSource: "builtin",
  4068. surface: "interactive",
  4069. memoryReadAgentNames: ["mavis", "main"],
  4070. corePrompt: "core",
  4071. surfacePrompt: "surface",
  4072. capabilityCeiling: {
  4073. personaEnabled: true,
  4074. features: { mavis: true, delegation: true, webSearch: true },
  4075. },
  4076. provenance: {
  4077. source: "builtin",
  4078. assetAgentName: "mavis",
  4079. locale: "en-US",
  4080. },
  4081. } as never);
  4082. const sources = await composeAgentSources();
  4083. const snapshot = await sources.agents.getExecutionSnapshot("main");
  4084. await expect(
  4085. sources.preparation.configBuilder.profile.render({
  4086. session: {
  4087. sessionId: "session-1",
  4088. sessionType: "root",
  4089. sessionKind: "conversation",
  4090. },
  4091. agent: snapshot,
  4092. isSessionFirstTurn: true,
  4093. }),
  4094. // Memory keeps reading the whole trusted family; behaviour does not.
  4095. ).resolves.toMatchObject({ memoryReadAgentNames: ["mavis", "main"] });
  4096. expect(mocked.agentService.renderProfile).toHaveBeenCalledWith(
  4097. expect.objectContaining({
  4098. exactOwnerName: "mavis",
  4099. requestRef: "mavis",
  4100. capabilities: undefined,
  4101. }),
  4102. );
  4103. });
  4104. it("leaves every non-primary Agent executing as its own persisted row", async () => {
  4105. mocked.agentService.getPersistedOwnerForFrozenTask.mockImplementation(
  4106. async (name) =>
  4107. name === "explore" ? view("explore", "Explore", "explore") : undefined,
  4108. );
  4109. const info = vi.fn();
  4110. const sources = await composeAgentSources({ ...noopLogger, info });
  4111. await expect(
  4112. sources.agents.getExecutionSnapshot("explore"),
  4113. ).resolves.toMatchObject({
  4114. agentName: "explore",
  4115. executionOwnerName: "explore",
  4116. });
  4117. expect(info).not.toHaveBeenCalled();
  4118. });
  4119. });