index.ts 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588
  1. import { resolvePreinstalledToolsRelease } from "@zcode/shared/preinstalled-tools";
  2. import { resolvePreinstalledToolsBinDir } from "@zcode/shared/preinstalled-tools/node";
  3. import { ZCODE_PRODUCT_FLAVOR, resolveZCodeRuntimeEnv } from "@zcode/shared";
  4. import { normalizeRemoteConnectionError, sanitizeRemoteConnectionLog } from "@zcode/shared";
  5. import { createCredentialCipherBridge } from "@zcode/shared/credential-security";
  6. import { join } from "node:path";
  7. /* eslint-disable max-lines -- Host 入口集中编排 local/remote service wiring,本次退出保护需要在同一处桥接 host 上报。 */
  8. /* eslint-disable max-lines -- host process 入口集中维护 local/remote 初始化和资源回收,realtime bridge 接入后先保持同文件收口。 */
  9. /**
  10. * Host Process 入口 —— 每个窗口对应一个独立的 host process
  11. *
  12. * 同一窗口的 Renderer 和手机 都 attachment 到这个 Host:
  13. * Renderer / Mobile ←MessagePort→ Window Host
  14. * ├─ local services
  15. * └─ remote connection registry
  16. *
  17. * 启动流程:
  18. * 1. main 进程通过 Electron `utilityProcess.fork()` 创建本进程
  19. * 2. main 进程只发送一次 init-local 初始化窗口 Host
  20. * 3. 后续远端 connect / scoped attachment 都由同一 Host 处理
  21. */
  22. import { createHostDatabaseStartup } from "./database-startup/hostDatabaseStartup.js";
  23. import { isOffPeakTerminalStatus } from "@zcode/shared";
  24. import { createHostNetworkCapture } from "./hostNetworkCapture.js";
  25. import { randomUUID } from "node:crypto";
  26. import { createPluginSandboxRegistrationBridge } from "./pluginSandbox/index.js";
  27. import { createWindowTopicResourceRelay } from "./windowTopicResourceRelay.js";
  28. import {
  29. MessagePortProtocol,
  30. ChannelServer,
  31. type IDisposable,
  32. type IChannelServer,
  33. LoggingChannelServer,
  34. NetworkTelemetryChannelServer,
  35. } from "@zcode/rpc";
  36. import { registerHostNetworkTelemetry, stopHostNetworkTelemetry } from "./hostNetworkTelemetry.js";
  37. import { registerHostServiceResourceTelemetry } from "./hostServiceResourceTelemetry.js";
  38. import { resolveResourceTelemetryEnvironmentKey } from "./hostResourceTelemetryEnvironment.js";
  39. import { reportHostSessionCreate } from "./hostSessionCreateTelemetry.js";
  40. import { createBrowserControlMainBridge } from "./browserControlMainBridge.js";
  41. import {
  42. createAppControlNavigationBridge,
  43. createAppControlDiscoverySourceResolver,
  44. appNavigationResultMessageSchema,
  45. } from "#src/app-control-navigation/host.js";
  46. import { materializeBrowserRecordingArtifact } from "./browserRecordingArtifactMaterializer.js";
  47. import { mainToExtensionWindowMessageSchema } from "@zcode/shared/extension-host";
  48. import {
  49. ServiceCollection,
  50. IBotsService,
  51. ICredentialService,
  52. IFileService,
  53. IClientConfigService,
  54. IMediaPreviewService,
  55. IOffPeakTaskService,
  56. IRemoteProjectService,
  57. type RemoteProjectHost,
  58. IProjectService,
  59. ITaskGroupService,
  60. IBroadcastService,
  61. IModelSelectionService,
  62. ISettingService,
  63. ISourceServerManagementService,
  64. ITerminalService,
  65. IDeviceSyncStateService,
  66. IProviderProvisioningStatusService,
  67. IExtensionsService,
  68. IExtensionViewsService,
  69. IExtensionGrantsService,
  70. IPluginManagementService,
  71. IWindowControllerService,
  72. IConversationShareService,
  73. IPromptAttachmentTransferService,
  74. IZCodeAgentService,
  75. IZCodeTaskService,
  76. IZCodeSessionService,
  77. ICuaPipSessionService,
  78. createZCodeAgentConnectionScope,
  79. type ZCodeAgentV4ClientMode,
  80. collectServiceMemoryDiagnostics,
  81. createWebRemoteProjectTreeActivityBridge,
  82. } from "@zcode/services";
  83. import {
  84. createLocalServices,
  85. createProjectWorkspaceNavigation,
  86. createRemoteProjectConnectionAdmission,
  87. releaseRemoteProjectProfileHost,
  88. findRemoteProjectHostIdForProfile,
  89. remoteProjectHostIdForProfile,
  90. remoteProjectHostIdForTarget,
  91. prepareRemoteServerConnection,
  92. bindRemoteProjectIdentities,
  93. createRemoteIdentityRegistrationCache,
  94. getOffPeakRequestAuthBuilder,
  95. disposeServiceResources,
  96. disposeServiceResourcesAndWait,
  97. AutomationRepo,
  98. OffPeakTaskRepo,
  99. OffPeakTaskService,
  100. createServiceLogger,
  101. buildTaskChangeSummary,
  102. createHostApiNetworkTransport,
  103. createSettingServiceWithMigrations,
  104. createDeviceSyncStateService,
  105. createHostProviderProvisioningStatus,
  106. createWindowHostExtensions,
  107. getPluginUserOptionsReader,
  108. type AppControlServiceHandle,
  109. type WindowHostExtensions,
  110. getAppConfigDir,
  111. getZCodeDataRootDir,
  112. OffPeakModelUnavailableError,
  113. OffPeakPermanentDispatchError,
  114. type BotProjectConnection,
  115. type HostApiNetworkTransport,
  116. type OffPeakRequestAuthBuilder,
  117. } from "@zcode/services/node";
  118. import { createHostResourceUsageResponder } from "./hostResourceUsage.js";
  119. import {
  120. assertBoundSessionDispatchable,
  121. resolveOffPeakDispatchKind,
  122. } from "./offPeakDispatchPlan.js";
  123. import {
  124. CREDENTIAL_KEY_SHARE_UNAVAILABLE_ERROR_CODE,
  125. HostMessageTypes,
  126. HostResponseTypes,
  127. formatLogPrefix,
  128. formatZCodeHostProcessName,
  129. formatZodError,
  130. buildRemoteWorkspaceIdentity,
  131. buildServerRemoteWorkspaceIdentity,
  132. remoteHostIdFromWorkspaceIdentity,
  133. buildRemoteEnvironmentKey,
  134. isRemoteWorkspaceIdentity,
  135. parseRemoteWorkspaceIdentity,
  136. buildRemoteHostWorkspaceIdentity,
  137. resolveWorkspaceKey,
  138. REMOTE_BIND_CANCELED_ERROR_CODE,
  139. REMOTE_WORKSPACE_BIND_SESSION_MISSING_ERROR_CODE,
  140. formatModelPickerValue,
  141. type ZCodePromptAttachment,
  142. type ZCodeStreamEvent,
  143. type ZCodeTaskMeta,
  144. type TaskStreamMirrorableEvent,
  145. type TraceId,
  146. type ZCodeTaskMode,
  147. type WindowHostAttachmentScope,
  148. type SourceServerArtifactPolicy,
  149. type ZCodeAutomation,
  150. type ZCodeAutomationRun,
  151. type ZCodeAutomationRunOutcome,
  152. type ModelSelection,
  153. } from "@zcode/shared";
  154. import {
  155. parseHostIncomingMessageEvent,
  156. rejectUnavailableAttachedServicePort,
  157. } from "./hostMessagePortGuard.js";
  158. // remote backend 相关模块延迟加载:ssh2 的 CJS 依赖链(asn1 等)在 asar 打包后路径断裂,
  159. // 静态 import 会导致 local 模式的 host process 也崩溃。
  160. // 改为动态 import,仅 remote 模式时才加载。
  161. import type { IRemoteBackend } from "@zcode/server/remote";
  162. import type { Locale, RemoteTarget } from "@zcode/shared";
  163. import { wrapElectronPort } from "./electronPort.js";
  164. import { createTaskRealtimeBridgeForHostInit } from "./taskRealtimeBridge.js";
  165. import { resolveRpcLogLevel } from "./rpcLogLevel.js";
  166. import { createHostWorkspaceTaskTracker } from "./hostWorkspaceTaskTracker.js";
  167. import {
  168. createRemoteMediaPreviewProxy,
  169. type RemoteMediaPreviewProxy,
  170. } from "./remoteMediaPreviewProxy.js";
  171. import { watchCronRunBotDelivery } from "./cronBotDelivery.js";
  172. import { createHostRemoteWorkspaceProxyState } from "./hostRemoteWorkspaceProxyState.js";
  173. import {
  174. createServerRemoteWorkspaceServiceCollection,
  175. resolveServerProjectService,
  176. } from "./remoteWorkspaceServiceCollection.js";
  177. import { getRemoteProviderProvisioningExecutor } from "./remoteProviderProvisioningService.js";
  178. import {
  179. createSourceSettingsServiceCollection,
  180. shouldDetachSourceSettingsAttachment,
  181. } from "./sourceSettingsServiceCollection.js";
  182. import { shouldReportHostConsoleError, stringifyHostLogArg } from "./hostLog.js";
  183. import { flushHostE2ECoverage } from "./e2eCoverage.js";
  184. import { runHostShutdownPhases, type HostShutdownResult } from "./hostShutdownPhases.js";
  185. import { initializeHostApiNetworkTransportOwner } from "./hostInitialization.js";
  186. import { createHostUncaughtExceptionHandler } from "./hostUncaughtExceptionGuard.js";
  187. import {
  188. recordCronRunOutcomeBestEffort,
  189. startManualClaimHeartbeat,
  190. settleCronRunTerminalOutcome,
  191. settleManualDispatchFailureBestEffort,
  192. } from "./cronRunLifecycle.js";
  193. import { connectServerRemote, type ServerRemoteConnection } from "./serverRemoteConnection.js";
  194. import { bindBotGroupTaskScope } from "./botGroupTaskScope.js";
  195. import { createWindowHostAttachmentRegistry } from "./windowHostAttachmentRegistry.js";
  196. import {
  197. exposeWindowHostAttachmentServices,
  198. createWindowHostTerminalOwners,
  199. createTerminalScope,
  200. } from "./windowHostAttachmentRpcPolicy.js";
  201. import { scopeConversationShareServiceForAttachment } from "./conversationShareAttachmentService.js";
  202. import {
  203. createWindowRemoteConnectionRegistry,
  204. type WindowRemoteConnectionCloseEvent,
  205. type WindowRemoteConnectionHandle,
  206. } from "./windowRemoteConnectionRegistry.js";
  207. import { pushDynamicWorkflowUserModeToRemoteHosts } from "./remoteDynamicWorkflowUserMode.js";
  208. import { connectDesktopSourceServer } from "./connectDesktopSourceServer.js";
  209. import { prepareRemoteWorkspaceIdentity } from "./remoteWorkspacePreparation.js";
  210. import { createWindowHostControllerRuntime } from "./windowHostControllerService.js";
  211. import { resolveBotRemoteWorkspace } from "./botRemoteWorkspaceResolver.js";
  212. import { SourceServerDirectory } from "./sourceServerDirectory.js";
  213. import { connectSourceServerTarget } from "./connectSourceServerTarget.js";
  214. import {
  215. SourceServerConnectionManager,
  216. SourceServerInstallRequiredError,
  217. SourceServerUpgradeRequiredError,
  218. } from "./sourceServerConnectionManager.js";
  219. import { createSourceServerRecoveryCloseEvent } from "./sourceServerRecoveryPolicy.js";
  220. import { runStartupReconnectBatch } from "./sourceServerStartupReconnect.js";
  221. import {
  222. createSourceServerManagementService,
  223. type SourceServerManagementService,
  224. } from "./sourceServerManagementService.js";
  225. import { resolveSourceServerReleaseAsset } from "./sourceServerReleaseResolver.js";
  226. import { resolveAutomationSubmissionModelSelection } from "./automationModelSelection.js";
  227. import { createRemoteConnectionProgressContext } from "@zcode/server/remote/remoteConnectionProgressContext.js";
  228. import {
  229. createRemotePromptAttachmentTransferService,
  230. type RemotePromptAttachmentTransferService,
  231. } from "./promptAttachmentTransferService.js";
  232. import { startHostSelfResourceTelemetry } from "./hostSelfResourceTelemetry.js";
  233. type HostRemoteConnection = ServerRemoteConnection;
  234. interface HostRemoteConnectionCapabilities {
  235. promptAttachmentTransferFactory?: (
  236. scope: Extract<WindowHostAttachmentScope, { kind: "remote" }>,
  237. ) => RemotePromptAttachmentTransferService;
  238. browserRecordingUploader?: Pick<IRemoteBackend, "upload">;
  239. remoteMediaPreviewFactory?: (
  240. scope: Extract<WindowHostAttachmentScope, { kind: "remote" }>,
  241. ) => RemoteMediaPreviewProxy;
  242. sourceServerId?: string;
  243. persistentSourceConnection?: boolean;
  244. /** underlying 服务实例标识,创建 logical wrapper 不代表物理连接换代。 */
  245. physicalOwner?: () => object;
  246. /** 当前物理连接的项目能力;只读发现不接受旧 Server 的兼容项目代理。 */
  247. readonly virtualProjects?: boolean;
  248. profileId?: string;
  249. recordWorkspaceOpen?: (input: {
  250. workspacePath: string;
  251. workspaceIdentity: string;
  252. workspacePurpose?: import("@zcode/shared").WorkspacePurpose;
  253. legacyWorkspaceIdentity?: string;
  254. signal?: AbortSignal;
  255. }) => Promise<void>;
  256. bindWorkspaceIdentity?: (input: {
  257. workspacePath: string;
  258. stableWorkspaceIdentity: string;
  259. legacyRouteHint?: string;
  260. signal?: AbortSignal;
  261. }) => Promise<void>;
  262. }
  263. let activeRemoteMediaRequests = 0;
  264. const hostRemoteMediaRequestLimiter = {
  265. tryAcquire: () => {
  266. if (activeRemoteMediaRequests >= 4) return false;
  267. activeRemoteMediaRequests += 1;
  268. return true;
  269. },
  270. release: () => {
  271. activeRemoteMediaRequests = Math.max(0, activeRemoteMediaRequests - 1);
  272. },
  273. getState: () => ({ active: activeRemoteMediaRequests, limit: 4 }),
  274. };
  275. const remoteMediaRangePreviewEnabled =
  276. process.env["ZCODE_REMOTE_MEDIA_RANGE_PREVIEW_ENABLED"] !== "0";
  277. type RemoteAssetDirs = import("./windowRemoteConnectionRegistry.js").WindowRemoteAssetDirs;
  278. const { parentPort } = process;
  279. const credentialCipherBridge = createCredentialCipherBridge((request) => {
  280. if (!parentPort) throw new Error("parentPort unavailable");
  281. parentPort.postMessage({ type: HostResponseTypes.CredentialCipherRequest, ...request });
  282. });
  283. const hostNetworkCapture = createHostNetworkCapture(parentPort);
  284. // 进程检索体验优化:host 由 utilityProcess 拉起时外壳仍是 Electron Helper,
  285. // 这里根据 main 传入的窗口 label 补一层稳定的 zcode-* title,方便系统进程列表过滤。
  286. process.title = formatZCodeHostProcessName(process.env["ZCODE_PROCESS_LABEL"]);
  287. type HostLogLevel = "info" | "warn" | "error";
  288. interface PendingFeedbackLogArchiveRequest {
  289. resolve: (archive: { path: string; size: number }) => void;
  290. reject: (error: Error) => void;
  291. onProgress?: (event: { processedBytes: number; totalBytes: number }) => void;
  292. }
  293. interface PendingLocalMediaPreviewPathAuthorization {
  294. resolve: (path: string) => void;
  295. reject: (error: Error) => void;
  296. }
  297. const pendingFeedbackLogArchiveRequests = new Map<string, PendingFeedbackLogArchiveRequest>();
  298. let nextFeedbackLogArchiveRequestSeq = 0;
  299. const pendingLocalMediaPreviewPathAuthorizations = new Map<
  300. string,
  301. PendingLocalMediaPreviewPathAuthorization
  302. >();
  303. function authorizeLocalMediaPreviewPath(path: string): Promise<string> {
  304. if (!parentPort) {
  305. return Promise.reject(new Error("parentPort unavailable"));
  306. }
  307. const requestId = randomUUID();
  308. return new Promise<string>((resolve, reject) => {
  309. pendingLocalMediaPreviewPathAuthorizations.set(requestId, { resolve, reject });
  310. try {
  311. parentPort.postMessage({
  312. type: HostResponseTypes.LocalMediaPreviewPathAuthorizeRequest,
  313. requestId,
  314. path,
  315. });
  316. } catch (error) {
  317. pendingLocalMediaPreviewPathAuthorizations.delete(requestId);
  318. reject(error instanceof Error ? error : new Error(String(error)));
  319. }
  320. });
  321. }
  322. interface PendingCredentialKeyShare {
  323. resolve: () => void;
  324. reject: (error: Error) => void;
  325. }
  326. const pendingCredentialKeyShares = new Map<string, PendingCredentialKeyShare>();
  327. /**
  328. * 数据存储路径切换复制完成后,请求 Main 把当前系统密钥登记到目标数据根。
  329. * 只有 Main 访问系统库;失败时 reject,由设置服务中止切换(见系统安全存储规格)。
  330. */
  331. function shareCredentialKeyWithDataRoot(targetBaseDir: string): Promise<void> {
  332. if (!parentPort) {
  333. return Promise.reject(new Error("parentPort unavailable"));
  334. }
  335. const requestId = randomUUID();
  336. return new Promise<void>((resolve, reject) => {
  337. pendingCredentialKeyShares.set(requestId, { resolve, reject });
  338. try {
  339. parentPort.postMessage({
  340. type: HostResponseTypes.CredentialKeyShareRequest,
  341. requestId,
  342. targetBaseDir,
  343. });
  344. } catch (error) {
  345. pendingCredentialKeyShares.delete(requestId);
  346. reject(error instanceof Error ? error : new Error(String(error)));
  347. }
  348. });
  349. }
  350. // 数据同步页「模型提供商」分类读取 / 重试 Main 协调器的 Provisioning lane(只在本机 Host)。
  351. const hostProviderProvisioningStatus = createHostProviderProvisioningStatus((message) => {
  352. if (!parentPort) throw new Error("parentPort unavailable");
  353. parentPort.postMessage(message);
  354. });
  355. const pluginSandboxRegistrationBridge = createPluginSandboxRegistrationBridge({
  356. send: (message) => {
  357. if (!parentPort) throw new Error("parentPort unavailable");
  358. parentPort.postMessage(message);
  359. },
  360. });
  361. // browser-use host↔main 桥:把 agent 的 browser 命令经 parentPort 转给 main(WebContentsView+CDP)。
  362. // parentPort 为空(不应发生于 host 进程)时 postToMain 抛错,bridge 自身返回 backend_unavailable。
  363. const appControlNavigation = createAppControlNavigationBridge({
  364. post: (message) => {
  365. if (!parentPort) throw new Error("parentPort unavailable");
  366. parentPort.postMessage(message);
  367. },
  368. });
  369. let browserBackendIdentity: { id: string; generation: number } | undefined;
  370. const browserControlMainBridge = createBrowserControlMainBridge({
  371. getBackendIdentity: () => browserBackendIdentity,
  372. postToMain: (message) => {
  373. if (!parentPort) {
  374. throw new Error("parentPort unavailable");
  375. }
  376. parentPort.postMessage(message);
  377. },
  378. materializeRecording: (input) => {
  379. let remoteBackend: Pick<IRemoteBackend, "upload"> | undefined;
  380. if (input.remoteSessionId) {
  381. const workspaceIdentity = input.workspaceIdentity;
  382. if (!workspaceIdentity?.trim()) {
  383. throw new Error("remote Browser recording materialization requires workspaceIdentity");
  384. }
  385. // Window Host 重构后同一进程可同时持有多个远端连接,旧的进程级
  386. // remoteConnection 会串 session。必须用完整 scope 从 registry 的权威 entry 取 uploader。
  387. remoteBackend = windowRemoteConnectionRegistry.resolveScopedCapabilities({
  388. kind: "remote",
  389. remoteSessionId: input.remoteSessionId,
  390. workspacePath: input.workspacePath,
  391. workspaceIdentity,
  392. })?.browserRecordingUploader;
  393. if (!remoteBackend) {
  394. throw new Error(
  395. "Source Server browser recording transfer requires the remote resource transaction path",
  396. );
  397. }
  398. }
  399. return materializeBrowserRecordingArtifact({
  400. ...input,
  401. ...(remoteBackend ? { remoteBackend } : {}),
  402. });
  403. },
  404. });
  405. function reportHostLog(level: HostLogLevel, args: unknown[]): void {
  406. if (!parentPort) {
  407. return;
  408. }
  409. try {
  410. parentPort.postMessage({
  411. type: HostResponseTypes.Log,
  412. level,
  413. source: "host",
  414. message: args.map((arg) => stringifyHostLogArg(arg)).join(" "),
  415. });
  416. } catch {
  417. // 日志上报失败不应影响 host 主流程。
  418. }
  419. }
  420. const rawConsole = {
  421. log: console.log.bind(console),
  422. warn: console.warn.bind(console),
  423. error: console.error.bind(console),
  424. };
  425. const remoteConnectionProgressContext = createRemoteConnectionProgressContext({
  426. emit: ({ requestId, level, args }) => {
  427. if (!parentPort) {
  428. return;
  429. }
  430. try {
  431. parentPort.postMessage({
  432. type: HostResponseTypes.RemoteWorkspaceConnectionLog,
  433. requestId,
  434. level,
  435. message: args.map((arg) => stringifyHostLogArg(arg)).join(" "),
  436. });
  437. } catch {
  438. // 连接进度上报失败不应中断 SSH/WSL/Docker 的真实连接流程。
  439. }
  440. },
  441. });
  442. function writeHostLog(level: HostLogLevel, ...args: unknown[]): void {
  443. const prefix = formatLogPrefix("zcode-host", process.pid);
  444. const consoleFn =
  445. level === "error" ? rawConsole.error : level === "warn" ? rawConsole.warn : rawConsole.log;
  446. consoleFn(prefix, ...args);
  447. reportHostLog(level, [prefix, ...args]);
  448. }
  449. function createFullFeedbackLogArchiveViaMain(
  450. sourceDir: string,
  451. options?: {
  452. onProgress?: (event: { processedBytes: number; totalBytes: number }) => void;
  453. },
  454. ): Promise<{ path: string; size: number }> {
  455. const requestId = `feedback-log-archive-${Date.now()}-${nextFeedbackLogArchiveRequestSeq++}`;
  456. options?.onProgress?.({ processedBytes: 0, totalBytes: 0 });
  457. return new Promise((resolve, reject) => {
  458. pendingFeedbackLogArchiveRequests.set(requestId, {
  459. resolve,
  460. reject,
  461. onProgress: options?.onProgress,
  462. });
  463. // 问题反馈以前在 host service 内走 compactLogArchive 的 full fallback,
  464. // 收集范围和“导出日志”不一致,缺少 zcode-cli 日志、rollout/debug 以及导出链路脱敏。
  465. // 这里把完整日志打包委托给 main process 的导出日志同源逻辑,host 只拿 zip 路径继续上传。
  466. try {
  467. parentPort.postMessage({
  468. type: HostResponseTypes.FeedbackLogArchiveRequest,
  469. requestId,
  470. sourceDir,
  471. });
  472. } catch (error) {
  473. pendingFeedbackLogArchiveRequests.delete(requestId);
  474. reject(error instanceof Error ? error : new Error(String(error)));
  475. }
  476. });
  477. }
  478. const logger = {
  479. info: (...args: unknown[]) => writeHostLog("info", ...args),
  480. warn: (...args: unknown[]) => writeHostLog("warn", ...args),
  481. error: (...args: unknown[]) => writeHostLog("error", ...args),
  482. };
  483. const cronAutomationRepo = new AutomationRepo();
  484. const cronRunSubscriptions = new Map<string, { dispose(): void }>();
  485. // ---- 闲时任务(off-peak)派发:与 cron 并行的独立链路(表/消息/常量互不复用)----
  486. const offPeakTaskRepo = new OffPeakTaskRepo();
  487. const offPeakRunSubscriptions = new Map<string, { dispose(): void }>();
  488. /**
  489. * 续跑提示词("实现时定"的落地):3h 时间盒到期 / app 重启恢复后 resume 同一
  490. * session 续发。不重发原始 prompt(会让模型从头再做一遍),而是指示接续未完成的工作。
  491. */
  492. const OFF_PEAK_RESUME_PROMPT =
  493. "Continue the previous task from where it left off. The run was interrupted " +
  494. "(app restart or execution window expired). Do not start over; review what has " +
  495. "already been done and complete the remaining work.";
  496. // ---- off-peak 运行时装配(server client + 进程内 mock 网关 + 编排服务,host 域属主)----
  497. // ⚠ 多窗口=多 host 会各自跑一份 sync 轮询(批量接口幂等、写入同库同数据,重复仅多耗请求);
  498. // mock 网关用固定端口单实例共享票据状态。若多窗口轮询放大成本,再加跨 host 选主。
  499. interface OffPeakRuntime {
  500. service: OffPeakTaskService;
  501. /** 派发时按本段票据构造逐请求鉴权;静态模型事实由 CLI Built-in Config 提供。 */
  502. buildRequestAuth: OffPeakRequestAuthBuilder;
  503. validateSelection: (selection: {
  504. providerId: string;
  505. modelId: string;
  506. options?: { reasoningLevel?: string };
  507. }) => Promise<boolean>;
  508. }
  509. let offPeakRuntime: OffPeakRuntime | null = null;
  510. async function ensureOffPeakRuntime(): Promise<OffPeakRuntime | null> {
  511. if (offPeakRuntime) return offPeakRuntime;
  512. const services = activeServices;
  513. if (!services) return null;
  514. const service = services.getOptional(IOffPeakTaskService);
  515. const buildRequestAuth = getOffPeakRequestAuthBuilder(services);
  516. if (!service || !buildRequestAuth) {
  517. logger.warn("off-peak runtime unavailable: missing host services");
  518. return null;
  519. }
  520. offPeakRuntime = {
  521. service: service as OffPeakTaskService,
  522. buildRequestAuth,
  523. validateSelection: (selection) =>
  524. (service as OffPeakTaskService).validateDispatchModelSelection(selection),
  525. };
  526. logger.info("off-peak runtime ready (service from local collection)");
  527. return offPeakRuntime;
  528. }
  529. function disposeOffPeakRuntime(): void {
  530. if (!offPeakRuntime) return;
  531. offPeakRuntime = null;
  532. }
  533. interface OffPeakRunDispatchRequest {
  534. offPeakTaskId: string;
  535. prompt: string;
  536. permissionMode: string;
  537. modelSelection: ModelSelection;
  538. conversationId?: string;
  539. sessionId?: string;
  540. serverTicketId?: string;
  541. workspacePath: string;
  542. workspaceIdentity?: string;
  543. projectId?: string | null;
  544. hostId?: string;
  545. additionalDirectories?: string[];
  546. }
  547. function offPeakRunSubscriptionKey(taskId: string, traceId: TraceId): string {
  548. return `${taskId}\u0000${traceId}`;
  549. }
  550. function disposeOffPeakRunSubscription(key: string): void {
  551. const disposable = offPeakRunSubscriptions.get(key);
  552. if (!disposable) return;
  553. offPeakRunSubscriptions.delete(key);
  554. disposable.dispose();
  555. }
  556. /** 终态回填 files_changed:复用现有 task diff 汇总(工具写盘型统计,Bash 改动不计入,接受)。 */
  557. async function resolveOffPeakFilesChanged(params: {
  558. zcodeTaskService: IZCodeTaskService;
  559. taskId: string;
  560. workspacePath: string;
  561. workspaceIdentity?: string;
  562. }): Promise<number | undefined> {
  563. try {
  564. const snapshot = await params.zcodeTaskService.getTaskSnapshot({
  565. taskId: params.taskId,
  566. workspacePath: params.workspacePath,
  567. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  568. });
  569. const fileChanges = snapshot?.fileChanges;
  570. if (!fileChanges) return undefined;
  571. // 汇总为空(无文件改动)按 0 计——"改了 0 个文件"对完成通知是真实信息。
  572. return buildTaskChangeSummary(fileChanges)?.fileCount ?? 0;
  573. } catch (error) {
  574. logger.warn("off-peak files_changed 汇总失败(不阻塞终态落库):", error);
  575. return undefined;
  576. }
  577. }
  578. /** loop 终态 → off_peak_tasks 终态:succeeded→completed、stopped→cancelled(用户手动停止)、其余→failed。 */
  579. async function finalizeOffPeakRun(params: {
  580. zcodeTaskService: IZCodeTaskService;
  581. offPeakTaskId: string;
  582. taskId: string;
  583. workspacePath: string;
  584. workspaceIdentity?: string;
  585. outcome: ZCodeAutomationRunOutcome;
  586. error?: string;
  587. }): Promise<void> {
  588. const status =
  589. params.outcome === "succeeded"
  590. ? ("completed" as const)
  591. : params.outcome === "stopped"
  592. ? ("cancelled" as const)
  593. : ("failed" as const);
  594. const filesChanged = await resolveOffPeakFilesChanged(params);
  595. const updated = await offPeakTaskRepo.markTerminal(params.offPeakTaskId, {
  596. status,
  597. endedAt: Date.now(),
  598. ...(params.error ? { failureReason: params.error } : {}),
  599. ...(filesChanged !== undefined ? { filesChanged } : {}),
  600. });
  601. if (!updated) {
  602. // 终态不可逆出:任务已被用户先一步取消/删除等,丢弃迟到回写(幂等兜底)。
  603. logger.info(
  604. `off-peak terminal writeback dropped (already terminal) task=${params.offPeakTaskId}`,
  605. );
  606. return;
  607. }
  608. logger.info(
  609. `off-peak run finished task=${params.offPeakTaskId} status=${status} filesChanged=${filesChanged ?? "n/a"}`,
  610. );
  611. // 后台完成统一置未读,打开 task 时由导航链路清除(与 cron 同款)。
  612. void params.zcodeTaskService.setTaskUnread({
  613. taskId: params.taskId,
  614. workspacePath: params.workspacePath,
  615. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  616. unread: true,
  617. });
  618. }
  619. function trackOffPeakRunOutcome(params: {
  620. zcodeTaskService: IZCodeTaskService;
  621. zcodeAgentService: IZCodeAgentService;
  622. service: OffPeakTaskService;
  623. ticketId: string;
  624. offPeakTaskId: string;
  625. taskId: string;
  626. traceId: TraceId;
  627. workspacePath: string;
  628. workspaceIdentity?: string;
  629. }): { admitted(): void } {
  630. const key = offPeakRunSubscriptionKey(params.taskId, params.traceId);
  631. disposeOffPeakRunSubscription(key);
  632. const target = {
  633. workspacePath: params.workspacePath,
  634. workspaceIdentity: params.workspaceIdentity,
  635. };
  636. const registration = params.service.residentExecutions.register({
  637. offPeakTaskId: params.offPeakTaskId,
  638. executionId: params.traceId,
  639. sessionId: params.taskId,
  640. ticketId: params.ticketId,
  641. control: (control) =>
  642. params.zcodeAgentService.controlOffPeakExecutionV4({ ...target, control }),
  643. complete: (outcome) => finalizeOffPeakRun({ ...params, outcome }),
  644. disposed: () => disposeOffPeakRunSubscription(key),
  645. });
  646. const disposable = params.zcodeAgentService.onDynamicOffPeakLifecycle(target)((event) => {
  647. if (event.executionId !== params.traceId || event.sessionId !== params.taskId) return;
  648. void params.service.residentExecutions
  649. .handle(event)
  650. .catch((error) => logger.warn("off-peak 生命周期处理失败:", error));
  651. });
  652. offPeakRunSubscriptions.set(key, {
  653. dispose() {
  654. disposable.dispose();
  655. registration.dispose();
  656. },
  657. });
  658. return registration;
  659. }
  660. /**
  661. * 把一次闲时任务派发提交给当前 host 的 V4 task service。
  662. * 首跑 createTask;进程内换票只交付现存执行,绝不重发初始 prompt。
  663. * 已有任务行的中断恢复仍复用会话;它不恢复旧进程的后台工作或通知。
  664. */
  665. async function dispatchOffPeakRun(request: OffPeakRunDispatchRequest): Promise<{
  666. conversationId?: string;
  667. sessionId?: string;
  668. lifecycleManaged: true;
  669. }> {
  670. const zcodeTaskService = activeServices?.getOptional(IZCodeTaskService);
  671. const zcodeAgentService = activeServices?.getOptional(IZCodeAgentService);
  672. if (!zcodeTaskService || !zcodeAgentService) {
  673. throw new Error("ZCode task service is not initialized.");
  674. }
  675. const runtime = await ensureOffPeakRuntime();
  676. if (!runtime) {
  677. throw new Error("off-peak runtime is not available");
  678. }
  679. if (!request.serverTicketId) {
  680. // schedulable 必然已取号;无票派发说明快照失序,按 transient 回执等下轮(轮询会补票)。
  681. throw new Error("off-peak dispatch without server ticket");
  682. }
  683. const currentTask = await offPeakTaskRepo.get(request.offPeakTaskId);
  684. if (!currentTask || isOffPeakTerminalStatus(currentTask.status)) {
  685. // 调度认领与 CLI 收口可以交错;迟到的派发不能重放已经完成的任务。
  686. await runtime.service.residentExecutions.discardTicket(request.serverTicketId);
  687. const sessionId = currentTask?.conversationId ?? request.conversationId ?? request.sessionId;
  688. return { conversationId: sessionId, sessionId, lifecycleManaged: true };
  689. }
  690. if (runtime.service.residentExecutions.has(request.offPeakTaskId)) {
  691. const stillNeedsTicket = runtime.service.residentExecutions.retakeGuard(request.offPeakTaskId);
  692. const auth = runtime.service.residentExecutions.isUserOwned(request.offPeakTaskId)
  693. ? {}
  694. : await runtime.buildRequestAuth(request.serverTicketId);
  695. // 先写 running 再唤醒 CLI;否则新请求立即过期产生的 requeue 会被迟到确认覆盖。
  696. await offPeakTaskRepo.markRunning(request.offPeakTaskId, { startedAt: Date.now() });
  697. try {
  698. const resident = await runtime.service.residentExecutions.deliverTicket(
  699. request.offPeakTaskId,
  700. request.serverTicketId,
  701. auth,
  702. );
  703. if (resident)
  704. return {
  705. conversationId: resident.sessionId,
  706. sessionId: resident.sessionId,
  707. lifecycleManaged: true,
  708. };
  709. // 等凭据期间驻留执行可能完成并注销;此派发已属于续票,禁止降级成初始 prompt。
  710. await runtime.service.residentExecutions.discardTicket(request.serverTicketId);
  711. const sessionId = currentTask.conversationId ?? request.conversationId ?? request.sessionId;
  712. return { conversationId: sessionId, sessionId, lifecycleManaged: true };
  713. } catch (error) {
  714. // RPC 在途可能发生用户接管或整项完成,失败回执不能重新夺回调度归属。
  715. if (stillNeedsTicket()) await offPeakTaskRepo.requeueForContinuation(request.offPeakTaskId);
  716. throw error;
  717. }
  718. }
  719. // 闲时 Selection 只承载驻内存续跑;普通 Session entry 与 CLI 默认不持久化它。
  720. const idleSelection = request.modelSelection;
  721. if (!(await runtime.validateSelection(idleSelection))) {
  722. throw new OffPeakModelUnavailableError("idlePlan");
  723. }
  724. const requestAuth = await runtime.buildRequestAuth(request.serverTicketId);
  725. // 首次派发与复用会话的恢复派发需要在轮次事实中可区分;该字段只描述
  726. // 当前自动 turn 的调度阶段,不改变稳定 task ID、独立 message ID 或手动消息语义。
  727. const dispatchKind = resolveOffPeakDispatchKind(request);
  728. const offPeakRunType = dispatchKind === "resume" ? "resume" : "init";
  729. let trackedKey: string | null = null;
  730. try {
  731. let taskId: string;
  732. let traceId: TraceId;
  733. let promptContent = request.prompt;
  734. if (dispatchKind === "bound-first-run") {
  735. // 绑定首跑:会话内创建的任务在创建它的会话里执行(对齐 dispatchCronRun 的 targetTaskId 路径)。
  736. // 先探测再写配置:绑定的是用户的工作会话,忙碌时直接 transient 交给调度器退避,
  737. // 不能先 setMode 再被 session/send 以 -32010 拒绝(那会悄悄改掉用户会话的权限模式)。
  738. taskId = request.sessionId!;
  739. traceId = `${request.offPeakTaskId}:bound:${randomUUID()}` as TraceId;
  740. const workspaceScope = {
  741. workspacePath: request.workspacePath,
  742. workspaceIdentity: request.workspaceIdentity,
  743. additionalDirectories: request.additionalDirectories,
  744. };
  745. // Bug 原因:归属收口后 tasks-index 行的 status 只镜像 CLI 的 last_outcome,
  746. // 永远不会是 running,原来按 listTasks(...).status === "running" 的忙碌判断已失效,
  747. // 闲时任务会被派发到仍在运行的绑定会话上。运行中事实只能取 syncer 的活动集合。
  748. const [deletedIds, activeIds] = await Promise.all([
  749. zcodeTaskService.listDeletedTaskIds(workspaceScope),
  750. zcodeTaskService.listActiveTaskIds(workspaceScope),
  751. ]);
  752. assertBoundSessionDispatchable({
  753. sessionId: taskId,
  754. deleted: deletedIds.includes(taskId),
  755. running: activeIds.includes(taskId),
  756. });
  757. await zcodeTaskService.resumeTask({
  758. ...workspaceScope,
  759. taskId,
  760. // 绑定会话首次盖章归属标记,侧栏归入闲时分组(机制同 cron targetTaskId)。
  761. offPeakTaskId: request.offPeakTaskId,
  762. });
  763. await zcodeTaskService.setConfigOption({
  764. taskId,
  765. traceId,
  766. configId: "mode",
  767. value: request.permissionMode,
  768. });
  769. } else if (dispatchKind === "resume") {
  770. // 续跑段:resume 同一 session(冷恢复水合历史;send 前必须先 resume)。
  771. taskId = request.conversationId!;
  772. // 原因:offPeakTaskId 只用于跨 talk 关联;每次自动轮必须生成独立消息身份,
  773. // 不能复用 task ID,也不能依赖同毫秒时间戳避免碰撞。
  774. traceId = `${request.offPeakTaskId}:resume:${randomUUID()}` as TraceId;
  775. promptContent = OFF_PEAK_RESUME_PROMPT;
  776. await zcodeTaskService.resumeTask({
  777. taskId,
  778. workspacePath: request.workspacePath,
  779. workspaceIdentity: request.workspaceIdentity,
  780. additionalDirectories: request.additionalDirectories,
  781. // D48:pre-打点会话续跑时补写归属标记(bootstrap 回填之外的双保险)。
  782. offPeakTaskId: request.offPeakTaskId,
  783. });
  784. // 权限模式随派发下发(resume 后显式设置,幂等)。
  785. await zcodeTaskService.setConfigOption({
  786. taskId,
  787. traceId,
  788. configId: "mode",
  789. value: request.permissionMode,
  790. });
  791. // 档位是 idle Selection 的一部分,只在 sendPrompt 注入;单独写档位会污染用户会话。
  792. } else {
  793. const task = await zcodeTaskService.createTask({
  794. projectId: request.projectId,
  795. workspacePath: request.workspacePath,
  796. workspaceIdentity: request.workspaceIdentity,
  797. additionalDirectories: request.additionalDirectories,
  798. // 空 Session 沿用普通初始化;idle Selection 只在下方执行中注入。
  799. // 在此写入会让闲时轮结束后的普通消息继续使用无票的隐藏 Provider。
  800. mode: request.permissionMode as ZCodeTaskMode,
  801. // 闲时任务是无界面的 createTask + sendPrompt 连续派发;空 session 必须在首条
  802. // V4 admission 内先持久化,否则 session_input 外键会先于 session 主记录写入。
  803. deferPersistenceUntilFirstPrompt: true,
  804. // 创建时即盖章持久归属标记(月亮图标/后续系统分组只看该标记,不再反查 store)。
  805. offPeakTaskId: request.offPeakTaskId,
  806. });
  807. taskId = task.taskId;
  808. traceId = task.traceId;
  809. }
  810. // 准备会话含异步 I/O;任务可能在此期间取消,首条 prompt 接纳前必须重新核对。
  811. const beforeAdmission = await offPeakTaskRepo.get(request.offPeakTaskId);
  812. if (!beforeAdmission || isOffPeakTerminalStatus(beforeAdmission.status)) {
  813. await runtime.service.residentExecutions.discardTicket(request.serverTicketId);
  814. return { conversationId: taskId, sessionId: taskId, lifecycleManaged: true };
  815. }
  816. trackedKey = offPeakRunSubscriptionKey(taskId, traceId);
  817. const lifecycle = trackOffPeakRunOutcome({
  818. zcodeTaskService,
  819. zcodeAgentService,
  820. service: runtime.service,
  821. ticketId: request.serverTicketId,
  822. offPeakTaskId: request.offPeakTaskId,
  823. taskId,
  824. traceId,
  825. workspacePath: request.workspacePath,
  826. ...(request.workspaceIdentity ? { workspaceIdentity: request.workspaceIdentity } : {}),
  827. });
  828. await zcodeTaskService.sendPrompt({
  829. taskId,
  830. traceId,
  831. content: promptContent,
  832. clientMode: "desktop-continuous",
  833. // Bug 原因:闲时自动 turn 以前只注入 idle plan,没有限制工具面,模型可在后台创建
  834. // 持久化定时任务。首跑与续跑在此收敛,显式隐藏 CronCreate 且不伪造 cron automation 归属。
  835. // 闲时轮同时隐藏 OffPeakCreate,OffPeakList 只读保留。
  836. toolDenylist: ["CronCreate", "OffPeakCreate"],
  837. modelSelection: idleSelection,
  838. modelExecution: {
  839. // 闲时执行凭据只服务主 Turn;完成后不再派生自动 Memory 请求。
  840. memoryExtraction: "skip",
  841. selectionScope: "execution",
  842. offPeak: {
  843. executionId: traceId,
  844. ticketId: request.serverTicketId,
  845. providerErrorCode: "3102",
  846. },
  847. requestAuth,
  848. subagents: {
  849. foregroundModel: "submission",
  850. background: "allow",
  851. },
  852. },
  853. offPeakTaskId: request.offPeakTaskId,
  854. offPeakRunType,
  855. });
  856. await offPeakTaskRepo.markRunning(request.offPeakTaskId, {
  857. startedAt: Date.now(),
  858. conversationId: taskId,
  859. sessionId: taskId,
  860. });
  861. lifecycle.admitted();
  862. // 只有 init 实际新建;绑定首跑和跨票续跑只是原 Session 的后续输入。
  863. if (dispatchKind === "init") {
  864. reportHostSessionCreate(parentPort, {
  865. clientLanguage: resolveHostClientLanguage(),
  866. sessionId: taskId,
  867. messageId: traceId,
  868. source: "automation_idle",
  869. workspaceIdentity: request.workspaceIdentity,
  870. });
  871. }
  872. return { conversationId: taskId, sessionId: taskId, lifecycleManaged: true };
  873. } catch (error) {
  874. if (trackedKey) disposeOffPeakRunSubscription(trackedKey);
  875. throw error;
  876. }
  877. }
  878. interface CronRunDispatchRequest {
  879. automationId: string;
  880. runId: string;
  881. prompt: string;
  882. targetTaskId?: string;
  883. modelSelection?: ModelSelection;
  884. mode?: ZCodeTaskMode;
  885. workspacePath: string;
  886. workspaceIdentity?: string;
  887. projectId?: string | null;
  888. hostId?: string;
  889. additionalDirectories?: string[];
  890. }
  891. function resolveAutomationTargetServices(request: {
  892. workspacePath: string;
  893. workspaceIdentity?: string;
  894. }): ServiceCollection {
  895. const remoteSession = windowRemoteConnectionRegistry.findSessionForWorkspace(request);
  896. if (remoteSession) {
  897. if (!remoteSession.workspaceIdentity) {
  898. throw new Error("Automation 目标 Remote Host 缺少 workspaceIdentity");
  899. }
  900. return windowRemoteConnectionRegistry.resolveScopedServices({
  901. kind: "remote",
  902. remoteSessionId: remoteSession.remoteSessionId,
  903. workspacePath: request.workspacePath,
  904. workspaceIdentity: remoteSession.workspaceIdentity,
  905. });
  906. }
  907. // 远程 Automation 找不到目标 logical session 时,旧派发会静默落到 Local Host,
  908. // 从而使用本地模型首选与 Registry。远程身份只能失败,不能跨 Environment fallback。
  909. if (request.workspaceIdentity && isRemoteWorkspaceIdentity(request.workspaceIdentity)) {
  910. throw new Error("Automation 目标 Remote Host 当前不可用");
  911. }
  912. if (!activeServices) {
  913. throw new Error("Local Host services are not initialized.");
  914. }
  915. return activeServices;
  916. }
  917. function cronRunSubscriptionKey(taskId: string, traceId: TraceId): string {
  918. return `${taskId}\u0000${traceId}`;
  919. }
  920. function parseCronRunScheduledAt(runId: string, automationId: string): number | null {
  921. const prefix = `${automationId}:`;
  922. if (!runId.startsWith(prefix)) return null;
  923. const value = Number(runId.slice(prefix.length).split(":")[0]);
  924. return Number.isSafeInteger(value) && value > 0 ? value : null;
  925. }
  926. function markCronRunOutcome(params: {
  927. runId: string;
  928. automationId: string;
  929. workspaceKey: string;
  930. scheduledAt: number | null;
  931. trigger: "schedule" | "manual";
  932. outcome: ZCodeAutomationRunOutcome;
  933. error?: string;
  934. }): void {
  935. void recordCronRunOutcomeBestEffort({
  936. ...params,
  937. repo: cronAutomationRepo,
  938. logWarn: (message, error) => logger.warn(message, error),
  939. });
  940. }
  941. function disposeCronRunSubscription(key: string): void {
  942. const disposable = cronRunSubscriptions.get(key);
  943. if (!disposable) return;
  944. cronRunSubscriptions.delete(key);
  945. disposable.dispose();
  946. }
  947. async function applyCronRunConfigToExistingTask(params: {
  948. zcodeTaskService: IZCodeTaskService;
  949. taskId: string;
  950. traceId: TraceId;
  951. modelSelection?: ModelSelection;
  952. mode?: string;
  953. }): Promise<void> {
  954. let thoughtAppliedWithModel = false;
  955. let modeAppliedWithModel = false;
  956. if (params.modelSelection) {
  957. await params.zcodeTaskService.setAutomationSessionConfig({
  958. taskId: params.taskId,
  959. traceId: params.traceId,
  960. modelSelection: params.modelSelection,
  961. thoughtLevel: params.modelSelection.options?.reasoningLevel,
  962. mode: params.mode?.trim() as ZCodeTaskMode | undefined,
  963. });
  964. thoughtAppliedWithModel = true;
  965. modeAppliedWithModel = true;
  966. }
  967. if (!modeAppliedWithModel && params.mode?.trim()) {
  968. await params.zcodeTaskService.setConfigOption({
  969. taskId: params.taskId,
  970. traceId: params.traceId,
  971. configId: "mode",
  972. value: params.mode.trim(),
  973. });
  974. }
  975. if (!thoughtAppliedWithModel && params.modelSelection?.options?.reasoningLevel) {
  976. await params.zcodeTaskService.setConfigOption({
  977. taskId: params.taskId,
  978. traceId: params.traceId,
  979. configId: "thought_level",
  980. value: params.modelSelection.options.reasoningLevel,
  981. });
  982. }
  983. }
  984. function trackCronRunOutcome(params: {
  985. zcodeTaskService: IZCodeTaskService;
  986. taskId: string;
  987. traceId: TraceId;
  988. workspacePath: string;
  989. workspaceIdentity?: string;
  990. runId: string;
  991. automationId: string;
  992. workspaceKey: string;
  993. scheduledAt: number | null;
  994. trigger: "schedule" | "manual";
  995. }): void {
  996. const key = cronRunSubscriptionKey(params.taskId, params.traceId);
  997. disposeCronRunSubscription(key);
  998. markCronRunOutcome({ ...params, outcome: "running" });
  999. const disposable = params.zcodeTaskService.onDynamicTaskTerminalOutcome(params.taskId)(
  1000. (result) => {
  1001. if (result.inputId !== params.traceId) return;
  1002. void settleCronRunTerminalOutcome({
  1003. ...params,
  1004. outcome: result.outcome,
  1005. error: result.error,
  1006. repo: cronAutomationRepo,
  1007. logWarn: (message, error) => logger.warn(message, error),
  1008. });
  1009. // 定时任务在后台完成后统一置为未读,真正打开 task 时再由导航链路清除。
  1010. void params.zcodeTaskService.setTaskUnread({
  1011. taskId: params.taskId,
  1012. workspacePath: params.workspacePath,
  1013. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  1014. unread: true,
  1015. });
  1016. disposeCronRunSubscription(key);
  1017. },
  1018. );
  1019. const claimHeartbeat =
  1020. params.trigger === "manual"
  1021. ? startManualClaimHeartbeat({
  1022. ...params,
  1023. repo: cronAutomationRepo,
  1024. logWarn: (message, error) => logger.warn(message, error),
  1025. })
  1026. : null;
  1027. cronRunSubscriptions.set(key, {
  1028. dispose() {
  1029. claimHeartbeat?.dispose();
  1030. disposable.dispose();
  1031. },
  1032. });
  1033. }
  1034. /**
  1035. * 把一次 cron/manual run 直接提交给当前 host 的 V4 task service。
  1036. * 会话内 automation 可能绑定到未激活 session,必须先恢复再应用保存的运行参数。
  1037. */
  1038. async function dispatchCronRun(request: CronRunDispatchRequest): Promise<{
  1039. taskId: string;
  1040. sessionId: string;
  1041. }> {
  1042. const targetServices = resolveAutomationTargetServices(request);
  1043. const zcodeTaskService = targetServices.getOptional(IZCodeTaskService);
  1044. if (!zcodeTaskService) {
  1045. throw new Error("ZCode task service is not initialized.");
  1046. }
  1047. const modelSelectionService = targetServices.getOptional(IModelSelectionService);
  1048. if (!modelSelectionService) {
  1049. throw new Error("目标 Host Model Selection service is not initialized.");
  1050. }
  1051. // 长期配置是原意图;首次派发在目标 Host 解析后固定。已有 run 必须直接复用,
  1052. // 不能因账号变化或本次 Registry 读取失败重新解释历史执行选择。
  1053. const existingRun = await cronAutomationRepo.getRun(request.runId);
  1054. const resolvedSubmissionModelSelection = await resolveAutomationSubmissionModelSelection({
  1055. selection: request.modelSelection,
  1056. fixedSelection: existingRun?.modelSelection,
  1057. modelSelectionService,
  1058. // Repo 已在读取前完成离线导入;不再为迁移绕行 Agent/账号服务。
  1059. // 未迁入或损坏的新值仍由此入口明确拒绝,不能当成跟随 Workspace。
  1060. readSelection: () =>
  1061. cronAutomationRepo.getModelSelectionForDispatch(
  1062. request.automationId,
  1063. resolveWorkspaceKey(request),
  1064. ),
  1065. });
  1066. const submissionModelSelection = await cronAutomationRepo.fixRunModelSelection(
  1067. request.runId,
  1068. resolvedSubmissionModelSelection,
  1069. );
  1070. let trackedKey: string | null = null;
  1071. const workspaceKey = resolveWorkspaceKey(request);
  1072. const trigger = request.runId.includes(":manual:") ? "manual" : "schedule";
  1073. const scheduledAt = parseCronRunScheduledAt(request.runId, request.automationId);
  1074. try {
  1075. const task = request.targetTaskId
  1076. ? { taskId: request.targetTaskId }
  1077. : await zcodeTaskService.createTask({
  1078. projectId: request.projectId,
  1079. workspacePath: request.workspacePath,
  1080. workspaceIdentity: request.workspaceIdentity,
  1081. additionalDirectories: request.additionalDirectories,
  1082. model: formatModelPickerValue(submissionModelSelection),
  1083. mode: request.mode,
  1084. thoughtLevel: submissionModelSelection.options?.reasoningLevel,
  1085. automationId: request.automationId,
  1086. });
  1087. // 未绑定会话时不能沿用 createTask 的 session trace 作为首条 prompt trace:
  1088. // CLI 无法从 inputId 还原 manual/schedule admission。
  1089. // 建会话 trace 与执行 runId 是两种身份;两条派发路径的 prompt 都必须统一使用 runId。
  1090. const promptTraceId = request.runId as TraceId;
  1091. if (request.targetTaskId) {
  1092. // 绑定会话在 app 重启或切换 workspace 后通常不处于 active;旧实现直接
  1093. // setConfig/sendPrompt 会立即报 Session is not active,看起来像「立即运行」没有触发。
  1094. await zcodeTaskService.resumeTask({
  1095. taskId: task.taskId,
  1096. workspacePath: request.workspacePath,
  1097. workspaceIdentity: request.workspaceIdentity,
  1098. additionalDirectories: request.additionalDirectories,
  1099. model: formatModelPickerValue(submissionModelSelection),
  1100. thoughtLevel: submissionModelSelection.options?.reasoningLevel,
  1101. automationId: request.automationId,
  1102. });
  1103. await applyCronRunConfigToExistingTask({
  1104. zcodeTaskService,
  1105. taskId: task.taskId,
  1106. traceId: promptTraceId,
  1107. modelSelection: submissionModelSelection,
  1108. mode: request.mode,
  1109. });
  1110. }
  1111. const botsService = targetServices.getOptional(IBotsService);
  1112. if (botsService) {
  1113. try {
  1114. await watchCronRunBotDelivery({
  1115. automationId: request.automationId,
  1116. runId: promptTraceId,
  1117. workspaceKey,
  1118. workspacePath: request.workspacePath,
  1119. ...(request.workspaceIdentity ? { workspaceIdentity: request.workspaceIdentity } : {}),
  1120. taskId: task.taskId,
  1121. repo: cronAutomationRepo,
  1122. botsService,
  1123. });
  1124. } catch (error) {
  1125. // Bot 回推是 best-effort 辅助通道;配置/凭据/订阅失败不能阻断 automation 派发与结算。
  1126. logger.warn(
  1127. `automation Bot delivery subscription failed automation=${request.automationId} provider=unknown`,
  1128. error,
  1129. );
  1130. }
  1131. }
  1132. trackedKey = cronRunSubscriptionKey(task.taskId, promptTraceId);
  1133. trackCronRunOutcome({
  1134. zcodeTaskService,
  1135. taskId: task.taskId,
  1136. traceId: promptTraceId,
  1137. workspacePath: request.workspacePath,
  1138. workspaceIdentity: request.workspaceIdentity,
  1139. runId: request.runId,
  1140. automationId: request.automationId,
  1141. workspaceKey,
  1142. scheduledAt,
  1143. trigger,
  1144. });
  1145. await zcodeTaskService.sendPrompt({
  1146. taskId: task.taskId,
  1147. traceId: promptTraceId,
  1148. content: request.prompt,
  1149. clientMode: "desktop-continuous",
  1150. automationId: request.automationId,
  1151. });
  1152. // prompt 创建的定时任务带 targetTaskId,追加原会话不能计成 session_create。
  1153. if (!request.targetTaskId) {
  1154. reportHostSessionCreate(parentPort, {
  1155. clientLanguage: resolveHostClientLanguage(),
  1156. sessionId: task.taskId,
  1157. messageId: promptTraceId,
  1158. source: "automation_scheduled",
  1159. workspaceIdentity: request.workspaceIdentity,
  1160. });
  1161. }
  1162. return { taskId: task.taskId, sessionId: task.taskId };
  1163. } catch (error) {
  1164. if (trackedKey) disposeCronRunSubscription(trackedKey);
  1165. markCronRunOutcome({
  1166. runId: request.runId,
  1167. automationId: request.automationId,
  1168. workspaceKey,
  1169. scheduledAt,
  1170. trigger,
  1171. outcome: "failed",
  1172. error: error instanceof Error ? error.message : String(error),
  1173. });
  1174. throw error;
  1175. }
  1176. }
  1177. async function dispatchManualAutomationRun(params: {
  1178. automation: ZCodeAutomation;
  1179. run: ZCodeAutomationRun;
  1180. }): Promise<void> {
  1181. logger.info(
  1182. `direct manual automation dispatch started automation=${params.automation.automationId} runId=${params.run.runId}`,
  1183. );
  1184. let result: Awaited<ReturnType<typeof dispatchCronRun>>;
  1185. try {
  1186. result = await dispatchCronRun({
  1187. automationId: params.automation.automationId,
  1188. runId: params.run.runId,
  1189. prompt: params.automation.prompt,
  1190. targetTaskId: params.automation.targetTaskId,
  1191. modelSelection: params.run.modelSelection ?? params.automation.modelSelection,
  1192. mode: params.automation.mode,
  1193. workspacePath: params.automation.workspacePath,
  1194. workspaceIdentity: params.automation.workspaceIdentity,
  1195. projectId: params.automation.projectId,
  1196. hostId: params.automation.hostId,
  1197. additionalDirectories: params.automation.additionalDirectories,
  1198. });
  1199. } catch (error) {
  1200. logger.warn(
  1201. `direct manual automation dispatch failed automation=${params.automation.automationId} runId=${params.run.runId}:`,
  1202. error,
  1203. );
  1204. await settleManualDispatchFailureBestEffort({
  1205. repo: cronAutomationRepo,
  1206. automationId: params.automation.automationId,
  1207. runId: params.run.runId,
  1208. workspaceKey: params.automation.workspaceKey,
  1209. scheduledAt: params.run.scheduledAt ?? null,
  1210. trigger: "manual",
  1211. dispatchError: error,
  1212. logWarn: (message, releaseError) => logger.warn(message, releaseError),
  1213. });
  1214. throw error;
  1215. }
  1216. try {
  1217. await cronAutomationRepo.markManualRunDispatched({
  1218. runId: params.run.runId,
  1219. sessionId: result.sessionId,
  1220. dispatchedAt: Date.now(),
  1221. });
  1222. } catch (error) {
  1223. // prompt 已经 accepted/queued,台账和累计次数回写失败不能伪装成派发失败并提前释放锁;
  1224. // 真实终态仍由 trackCronRunOutcome 收口,避免同一 automation 重复排队。
  1225. logger.warn(
  1226. `回写 manual automation dispatched 状态与运行次数失败 automation=${params.automation.automationId} runId=${params.run.runId}`,
  1227. error,
  1228. );
  1229. }
  1230. // sendPrompt ACK 可能只表示进入 busy queue;manual claim 必须保留到对应 turn 终态。
  1231. logger.info(
  1232. `direct manual automation dispatch accepted automation=${params.automation.automationId} runId=${params.run.runId} taskId=${result.taskId}`,
  1233. );
  1234. }
  1235. // Node warning 不是远端连接失败,改成结构化 warn,避免默认 stderr 被误染成 error。
  1236. process.on("warning", (warning) => logger.warn(`${warning.name}: ${warning.message}`));
  1237. registerHostNetworkTelemetry(parentPort);
  1238. // Host 进程自身的 60 秒采样:一次读数两个出口——门控后写本地
  1239. // `[memory]` 行,同一次读数换算成 HostResourceSample 经 parentPort 送 main 作 heap 来源。
  1240. // services 计数器由各 service 工厂自注册。
  1241. const hostSelfResourceTelemetry = startHostSelfResourceTelemetry({
  1242. logger,
  1243. collectCounters: collectServiceMemoryDiagnostics,
  1244. postMessage: parentPort ? (message) => parentPort.postMessage(message) : undefined,
  1245. });
  1246. const runtimeProcessLifecycleReporter = {
  1247. onSpawn(event) {
  1248. if (!parentPort) {
  1249. return;
  1250. }
  1251. parentPort.postMessage({
  1252. type: HostResponseTypes.AgentProcessSpawned,
  1253. ...event,
  1254. });
  1255. },
  1256. onReady(event) {
  1257. if (!parentPort) {
  1258. return;
  1259. }
  1260. parentPort.postMessage({
  1261. type: HostResponseTypes.AgentProcessReady,
  1262. ...event,
  1263. });
  1264. },
  1265. onExit(event) {
  1266. if (!parentPort) {
  1267. return;
  1268. }
  1269. parentPort.postMessage({
  1270. type: HostResponseTypes.AgentProcessExited,
  1271. ...event,
  1272. signal: event.signal ?? null,
  1273. });
  1274. },
  1275. onError(event) {
  1276. if (!parentPort) {
  1277. return;
  1278. }
  1279. parentPort.postMessage({
  1280. type: HostResponseTypes.AgentProcessError,
  1281. ...event,
  1282. });
  1283. },
  1284. onException(event) {
  1285. parentPort?.postMessage({ type: HostResponseTypes.AgentProcessException, ...event });
  1286. },
  1287. } satisfies NonNullable<Parameters<typeof createLocalServices>[0]>["processLifecycleReporter"];
  1288. let activeV4SessionCount = 0;
  1289. let legacyRuntimeTaskCount = 0;
  1290. const runtimeTaskReporter = {
  1291. onActiveSessionCountChanged(event: { runningTaskCount: number }) {
  1292. activeV4SessionCount = event.runningTaskCount;
  1293. reportHostRunningTaskCount();
  1294. },
  1295. onRunningTaskCountChanged(event) {
  1296. legacyRuntimeTaskCount = event.runningTaskCount;
  1297. reportHostRunningTaskCount();
  1298. },
  1299. } satisfies NonNullable<Parameters<typeof createLocalServices>[0]>["taskRuntimeReporter"];
  1300. const quitBlockerReporter = {
  1301. onQuitBlockersChanged(blockers) {
  1302. parentPort?.postMessage({ type: HostResponseTypes.QuitBlockersChanged, blockers });
  1303. },
  1304. } satisfies NonNullable<Parameters<typeof createLocalServices>[0]>["quitBlockerReporter"];
  1305. const cuaOperationStateReporter = {
  1306. onStateChanged(event) {
  1307. if (!parentPort) {
  1308. return;
  1309. }
  1310. parentPort.postMessage({
  1311. type: HostResponseTypes.CuaOperationState,
  1312. ...event,
  1313. });
  1314. },
  1315. } satisfies NonNullable<Parameters<typeof createLocalServices>[0]>["cuaOperationStateReporter"];
  1316. let untrackedPromptRpcCount = 0;
  1317. function reportHostRunningTaskCount(): void {
  1318. // v4 会话与旧代理分别报告,统一出口避免旧 ready 归零覆盖仍在执行的后台工作。
  1319. parentPort?.postMessage({
  1320. type: HostResponseTypes.AgentRunningTaskCountChanged,
  1321. runningTaskCount:
  1322. activeV4SessionCount +
  1323. legacyRuntimeTaskCount +
  1324. workspaceTaskTracker.getTotalRunningTaskCount() +
  1325. untrackedPromptRpcCount,
  1326. });
  1327. }
  1328. const workspaceTaskTracker = createHostWorkspaceTaskTracker((event) => {
  1329. parentPort?.postMessage({
  1330. type: HostResponseTypes.WorkspaceRunningTaskCountChanged,
  1331. ...event,
  1332. });
  1333. windowRemoteConnectionRegistry.setWorkspaceRunningTaskCount(event);
  1334. reportHostRunningTaskCount();
  1335. });
  1336. function isZCodeTaskMeta(value: unknown): value is ZCodeTaskMeta {
  1337. return (
  1338. typeof value === "object" &&
  1339. value !== null &&
  1340. "taskId" in value &&
  1341. "workspacePath" in value &&
  1342. "traceId" in value &&
  1343. typeof (value as { taskId?: unknown }).taskId === "string" &&
  1344. typeof (value as { workspacePath?: unknown }).workspacePath === "string" &&
  1345. typeof (value as { traceId?: unknown }).traceId === "string"
  1346. );
  1347. }
  1348. function isRemoteMirrorableStreamEvent(
  1349. event: ZCodeStreamEvent,
  1350. ): event is TaskStreamMirrorableEvent {
  1351. return event.type !== "task_stream_mirror_batch" && event.type !== "task_snapshot_updated";
  1352. }
  1353. function createReportingRemoteZCodeTaskService<T extends object>(
  1354. service: T,
  1355. options?: {
  1356. reportRunningPromptCount?: boolean;
  1357. taskRealtimePort?: ReturnType<typeof createTaskRealtimeBridgeForHostInit>;
  1358. materializePromptAttachments?: (params: {
  1359. taskId: string;
  1360. traceId: TraceId;
  1361. content: string;
  1362. attachments?: ZCodePromptAttachment[];
  1363. }) => Promise<{ content: string; attachments?: ZCodePromptAttachment[] }>;
  1364. },
  1365. ): T {
  1366. const workspaceProxyState = createHostRemoteWorkspaceProxyState();
  1367. function forwardSessionMessageRequest(request: unknown): void {
  1368. parentPort?.postMessage({
  1369. type: HostResponseTypes.SessionMessageSendRequested,
  1370. request,
  1371. });
  1372. }
  1373. function subscribeSessionMessageRequests(target: T, meta: ZCodeTaskMeta): void {
  1374. const onDynamicWorkspaceEvent = Reflect.get(target, "onDynamicWorkspaceEvent");
  1375. if (typeof onDynamicWorkspaceEvent !== "function") {
  1376. return;
  1377. }
  1378. const subscribe = onDynamicWorkspaceEvent.call(target, {
  1379. workspacePath: meta.workspacePath,
  1380. ...(meta.workspaceIdentity ? { workspaceIdentity: meta.workspaceIdentity } : {}),
  1381. });
  1382. if (typeof subscribe !== "function") {
  1383. return;
  1384. }
  1385. workspaceProxyState.ensureWorkspaceSubscription(meta, () =>
  1386. subscribe((event: unknown) => {
  1387. if (
  1388. typeof event === "object" &&
  1389. event !== null &&
  1390. (event as { type?: unknown }).type === "workspace_session_message_send_requested"
  1391. ) {
  1392. forwardSessionMessageRequest((event as { request?: unknown }).request);
  1393. }
  1394. }),
  1395. );
  1396. }
  1397. function rememberTaskMeta(result: unknown): void {
  1398. if (isZCodeTaskMeta(result)) {
  1399. workspaceProxyState.rememberTaskMeta(result);
  1400. subscribeSessionMessageRequests(service, result);
  1401. parentPort?.postMessage({
  1402. type: HostResponseTypes.SessionRouteAnnounce,
  1403. route: {
  1404. sessionId: result.taskId,
  1405. },
  1406. });
  1407. }
  1408. }
  1409. function rememberTaskMetasFromResult(result: unknown): void {
  1410. if (Array.isArray(result)) {
  1411. for (const item of result) {
  1412. rememberTaskMetasFromResult(item);
  1413. }
  1414. return;
  1415. }
  1416. rememberTaskMeta(result);
  1417. if (typeof result !== "object" || result === null) {
  1418. return;
  1419. }
  1420. const items = (result as { items?: unknown }).items;
  1421. if (Array.isArray(items)) {
  1422. for (const item of items) {
  1423. rememberTaskMeta(item);
  1424. }
  1425. }
  1426. const snapshot = (result as { snapshot?: unknown }).snapshot;
  1427. if (typeof snapshot === "object" && snapshot !== null) {
  1428. rememberTaskMeta((snapshot as { meta?: unknown }).meta);
  1429. }
  1430. rememberTaskMeta((result as { meta?: unknown }).meta);
  1431. }
  1432. async function prepareRemotePromptParams(params: {
  1433. taskId: string;
  1434. traceId: TraceId;
  1435. content: string;
  1436. attachments?: ZCodePromptAttachment[];
  1437. }): Promise<{
  1438. taskId: string;
  1439. traceId: TraceId;
  1440. content: string;
  1441. attachments?: ZCodePromptAttachment[];
  1442. }> {
  1443. if (!options?.materializePromptAttachments) {
  1444. return params;
  1445. }
  1446. return {
  1447. ...params,
  1448. ...(await options.materializePromptAttachments(params)),
  1449. };
  1450. }
  1451. async function mirrorRemotePrompt(
  1452. target: T,
  1453. sendPrompt: (...args: unknown[]) => Promise<unknown>,
  1454. params: {
  1455. taskId: string;
  1456. traceId: TraceId;
  1457. content: string;
  1458. attachments?: ZCodePromptAttachment[];
  1459. },
  1460. ): Promise<unknown> {
  1461. const taskRealtimePort = options?.taskRealtimePort;
  1462. const meta = workspaceProxyState.getTaskMeta(params.taskId);
  1463. if (!taskRealtimePort || !meta) {
  1464. return sendPrompt.call(target, params);
  1465. }
  1466. const mirrorTarget = {
  1467. workspacePath: meta.workspacePath,
  1468. workspaceIdentity: meta.workspaceIdentity,
  1469. workspaceKey: resolveWorkspaceKey(meta),
  1470. taskId: params.taskId,
  1471. runId: params.traceId,
  1472. traceId: params.traceId,
  1473. };
  1474. const leaseResult = await taskRealtimePort
  1475. .acquireTaskRunLease(mirrorTarget)
  1476. .catch((error: unknown) => {
  1477. logger.warn("Bot remote runtime realtime lease failed:", error);
  1478. return null;
  1479. });
  1480. if (!leaseResult?.acquired) {
  1481. return sendPrompt.call(target, params);
  1482. }
  1483. taskRealtimePort.publishStreamOp(mirrorTarget, {
  1484. kind: "user_message",
  1485. messageId: `user-${params.traceId}`,
  1486. content: params.content,
  1487. attachments: params.attachments,
  1488. timestamp: Date.now(),
  1489. });
  1490. // 写路径(send/stop/交互回执)已收敛 v4 命令面;本镜像属**读路径**——
  1491. // taskRealtimePort → 手机 relay → 手机端
  1492. // zcodeSessionStore 的整条消费链词表都是 ZCodeStreamEvent。两个方案的评估结论:
  1493. // a) relay 直接转发 v4 帧、手机端消费 v4 store(正解):需要重做 relay stream-op
  1494. // 协议 + 手机端 store;
  1495. // b) 帧→ZCodeStreamEvent 薄映射:等价复刻 adapter mapSessionEvent,
  1496. // 否决。
  1497. // 结论:本镜像保持 legacy 源不动。
  1498. const dynamicStreamEvent = Reflect.get(target, "onDynamicStreamEvent");
  1499. const streamDisposable =
  1500. typeof dynamicStreamEvent === "function"
  1501. ? dynamicStreamEvent.call(
  1502. target,
  1503. params.taskId,
  1504. )((event: ZCodeStreamEvent) => {
  1505. if (isRemoteMirrorableStreamEvent(event)) {
  1506. taskRealtimePort.publishStreamOp(mirrorTarget, {
  1507. kind: "stream_event",
  1508. event,
  1509. });
  1510. }
  1511. })
  1512. : null;
  1513. try {
  1514. return await sendPrompt.call(target, params);
  1515. } finally {
  1516. // 远端 zcode-server 没有 desktop realtime port;由窗口 Host 内的
  1517. // remote facade 接管 lease 和 stream mirror,确保 UI 能持续收到远端会话流。
  1518. streamDisposable?.dispose();
  1519. taskRealtimePort.releaseTaskRunLease(mirrorTarget);
  1520. }
  1521. }
  1522. function finishWorkspaceTask(taskId: string, meta: ZCodeTaskMeta): void {
  1523. workspaceProxyState.disposeTaskReadySubscription(taskId);
  1524. workspaceTaskTracker.finish(taskId, meta);
  1525. }
  1526. function beginWorkspaceTask(target: T, taskId: string, meta: ZCodeTaskMeta): boolean {
  1527. const started = workspaceTaskTracker.begin(taskId, meta);
  1528. if (!started) {
  1529. return false;
  1530. }
  1531. const onDynamicTaskReady = Reflect.get(target, "onDynamicTaskReady");
  1532. if (typeof onDynamicTaskReady !== "function") {
  1533. workspaceTaskTracker.finish(taskId, meta);
  1534. throw new Error("remote ZCode task service does not expose onDynamicTaskReady");
  1535. }
  1536. const subscribe = onDynamicTaskReady.call(target, taskId);
  1537. if (typeof subscribe !== "function") {
  1538. workspaceTaskTracker.finish(taskId, meta);
  1539. throw new Error("remote ZCode task ready event is not subscribable");
  1540. }
  1541. workspaceProxyState.trackTaskReady(
  1542. taskId,
  1543. meta,
  1544. (listener) => subscribe(listener),
  1545. () => finishWorkspaceTask(taskId, meta),
  1546. );
  1547. return true;
  1548. }
  1549. // remote workspace 的 ZCode Agent manager 跑在远端 server,desktop main 不能直接看到
  1550. // `handles` 状态。sendPrompt Promise 只是远端 ACK,必须等待 task ready 才能允许回收 workspace。
  1551. return new Proxy(service, {
  1552. get(target, property, receiver) {
  1553. const value = Reflect.get(target, property, receiver);
  1554. if ((property === "createTask" || property === "resumeTask") && typeof value === "function") {
  1555. return async (...args: unknown[]) => {
  1556. const result = await value.apply(target, args);
  1557. rememberTaskMeta(result);
  1558. return result;
  1559. };
  1560. }
  1561. if (
  1562. (property === "listTasks" ||
  1563. property === "listPinnedTasks" ||
  1564. property === "listTaskList" ||
  1565. property === "listArchivedTasks" ||
  1566. property === "getTaskMeta" ||
  1567. property === "getTaskSnapshot" ||
  1568. property === "getTaskSnapshotWithEtag") &&
  1569. typeof value === "function"
  1570. ) {
  1571. return async (...args: unknown[]) => {
  1572. const result = await value.apply(target, args);
  1573. rememberTaskMetasFromResult(result);
  1574. return result;
  1575. };
  1576. }
  1577. if (property === "releaseWorkspacePreparation" && typeof value === "function") {
  1578. return async (...args: unknown[]) => {
  1579. const result = await value.apply(target, args);
  1580. const context = args[0];
  1581. if (
  1582. typeof context === "object" &&
  1583. context !== null &&
  1584. typeof (context as { workspacePath?: unknown }).workspacePath === "string"
  1585. ) {
  1586. const workspaceContext = context as {
  1587. workspacePath: string;
  1588. workspaceIdentity?: string;
  1589. };
  1590. // pooled Host 不随 tab 退出;runtime 成功释放后必须同步解除 Host 代理层引用,
  1591. // 否则 task meta 和动态事件 listener 会在整个应用生命周期内单调增长。
  1592. workspaceProxyState.clearWorkspace(workspaceContext);
  1593. workspaceTaskTracker.clearWorkspace(workspaceContext);
  1594. }
  1595. return result;
  1596. };
  1597. }
  1598. const shouldWrapSendPrompt =
  1599. options?.reportRunningPromptCount !== false ||
  1600. Boolean(options?.taskRealtimePort) ||
  1601. Boolean(options?.materializePromptAttachments);
  1602. if (property !== "sendPrompt" || typeof value !== "function" || !shouldWrapSendPrompt) {
  1603. return value;
  1604. }
  1605. return async (...args: unknown[]) => {
  1606. let trackedTask: { taskId: string; meta: ZCodeTaskMeta; started: boolean } | undefined;
  1607. let tracksOnlyRpcLifetime = false;
  1608. try {
  1609. const params = args[0];
  1610. if (
  1611. typeof params === "object" &&
  1612. params !== null &&
  1613. typeof (params as { taskId?: unknown }).taskId === "string" &&
  1614. typeof (params as { traceId?: unknown }).traceId === "string" &&
  1615. typeof (params as { content?: unknown }).content === "string"
  1616. ) {
  1617. const promptParams = params as {
  1618. taskId: string;
  1619. traceId: TraceId;
  1620. content: string;
  1621. attachments?: ZCodePromptAttachment[];
  1622. };
  1623. const taskMeta = workspaceProxyState.getTaskMeta(promptParams.taskId) as
  1624. | ZCodeTaskMeta
  1625. | undefined;
  1626. if (taskMeta) {
  1627. trackedTask = {
  1628. taskId: promptParams.taskId,
  1629. meta: taskMeta,
  1630. started: beginWorkspaceTask(target, promptParams.taskId, taskMeta),
  1631. };
  1632. } else if (options?.reportRunningPromptCount !== false) {
  1633. // task meta 缺失时无法安全伪造 workspace identity;仅保留 ACK 期间的 Host 退出诊断,
  1634. // 不让该 fallback 参与 workspace runtime 的释放裁决。
  1635. tracksOnlyRpcLifetime = true;
  1636. untrackedPromptRpcCount += 1;
  1637. reportHostRunningTaskCount();
  1638. }
  1639. const preparedParams = await prepareRemotePromptParams(promptParams);
  1640. return await mirrorRemotePrompt(
  1641. target,
  1642. value.bind(target) as (...promptArgs: unknown[]) => Promise<unknown>,
  1643. preparedParams,
  1644. );
  1645. }
  1646. if (options?.reportRunningPromptCount !== false) {
  1647. tracksOnlyRpcLifetime = true;
  1648. untrackedPromptRpcCount += 1;
  1649. reportHostRunningTaskCount();
  1650. }
  1651. return await value.apply(target, args);
  1652. } catch (error) {
  1653. if (trackedTask?.started) {
  1654. finishWorkspaceTask(trackedTask.taskId, trackedTask.meta);
  1655. }
  1656. throw error;
  1657. } finally {
  1658. if (tracksOnlyRpcLifetime) {
  1659. untrackedPromptRpcCount = Math.max(0, untrackedPromptRpcCount - 1);
  1660. reportHostRunningTaskCount();
  1661. }
  1662. }
  1663. };
  1664. },
  1665. });
  1666. }
  1667. function warmUpZCodeAgent(
  1668. services: ServiceCollection,
  1669. context: { workspacePath?: string; workspaceIdentity?: string },
  1670. reason: string,
  1671. ): void {
  1672. if (!context.workspacePath) {
  1673. return;
  1674. }
  1675. const workspacePath = context.workspacePath;
  1676. const workspaceIdentity = context.workspaceIdentity;
  1677. const zcodeSessionService = services.getOptional(IZCodeSessionService);
  1678. if (!zcodeSessionService) {
  1679. return;
  1680. }
  1681. void zcodeSessionService
  1682. .initializeWorkspace({
  1683. workspacePath,
  1684. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  1685. })
  1686. .then((result) => {
  1687. if (!result.available) {
  1688. if (result.reasonCode === "provider_not_ready") {
  1689. logger.info(
  1690. `ZCode agent warmup waiting for provider/model (${reason}) workspace=${workspacePath}`,
  1691. );
  1692. return;
  1693. }
  1694. logger.warn(
  1695. `ZCode agent warmup unavailable (${reason}) workspace=${workspacePath} reason=${result.reason ?? "unknown"}`,
  1696. );
  1697. return;
  1698. }
  1699. // 模型候选和首选项已经由目标 Host ModelSelectionView 提供;workspace
  1700. // presentation 只剩 mode 与 slash commands。预热不能为读取 presentation 额外创建
  1701. // Agent App,否则其 MCP close 会占住协议通道并阻塞真正的 Session 初始化。
  1702. logger.info(
  1703. `ZCode agent warmup ready (${reason}) workspace=${workspacePath} transport=${result.transportKind ?? "unknown"}`,
  1704. );
  1705. })
  1706. .catch((error) => {
  1707. logger.warn(`ZCode agent warmup failed (${reason}) workspace=${workspacePath}:`, error);
  1708. });
  1709. }
  1710. // 后台输出轮询仍需独立的 debug logger,不能随其他日志调用方移除而丢失工厂导入。
  1711. const rpcDebugLogger = createServiceLogger("rpc");
  1712. function logRpc(message: string, ...args: unknown[]): void {
  1713. const level = resolveRpcLogLevel(message, ...args);
  1714. if (level === "debug") {
  1715. rpcDebugLogger.debug(undefined, message, ...args);
  1716. return;
  1717. }
  1718. logger[level](message, ...args);
  1719. }
  1720. function formatRemoteTargetForLog(target: RemoteTarget): string {
  1721. switch (target.kind) {
  1722. case "ssh":
  1723. return `ssh:${target.username}@${target.host}:${target.port ?? 22}`;
  1724. case "wsl": {
  1725. const user = target.user?.trim();
  1726. const distro = target.distro ?? "default";
  1727. return user ? `wsl:${distro}:${user}` : `wsl:${distro}`;
  1728. }
  1729. case "docker":
  1730. return `docker:${target.container}`;
  1731. case "server":
  1732. return `server:${target.name?.trim() || target.url}`;
  1733. }
  1734. }
  1735. console.log = (...args: unknown[]) => {
  1736. rawConsole.log(...args);
  1737. reportHostLog("info", args);
  1738. };
  1739. console.warn = (...args: unknown[]) => {
  1740. rawConsole.warn(...args);
  1741. reportHostLog("warn", args);
  1742. };
  1743. console.error = (...args: unknown[]) => {
  1744. rawConsole.error(...args);
  1745. // Electron 会把 Node warning 先走 console.error,而 process warning listener 随后还会
  1746. // 结构化记录 warn;若这里继续上报,就会为同一个 warning 留下一条 error 和一条 warn。
  1747. if (!shouldReportHostConsoleError(args)) {
  1748. return;
  1749. }
  1750. reportHostLog("error", args);
  1751. };
  1752. /** 当前 host 已注册的服务集合,进程退出时用于统一回收本地资源 */
  1753. let databaseStartup: ReturnType<typeof createHostDatabaseStartup> | undefined;
  1754. const pendingStartupAttachments = new Map<string, () => void>();
  1755. let activeServices: ServiceCollection | null = null;
  1756. // 扩展门面(docs/plugins/extension-host.md):InitLocal 建立服务后创建,Host 退出时断开扩展进程端口。
  1757. let windowHostExtensions: WindowHostExtensions | null = null;
  1758. /**
  1759. * Main 推送的实时界面语言,供 ZCode endpoint 请求的 X-Client-Language。
  1760. * 过去 Host 用进程 Intl locale(Dock 启动无 LANG 会回退 en-US);setting.json 写入可能滞后或失败,
  1761. * 也不能代表当前界面,所以只认 Main 的 InitLocal 初值与 application-locale-changed 变更。
  1762. */
  1763. let applicationLocale: Locale | undefined;
  1764. /**
  1765. * InitLocal 没带 locale(或尚未到达)时的兜底:setting.json 里持久化的界面语言。
  1766. * 以前这种情况下 NodeApiClient 回落到进程 Intl 系统语言,会和 UI 选的语言不一致。
  1767. * 只作兜底,Main 推送的 applicationLocale 永远优先。
  1768. */
  1769. let persistedApplicationLocale: Locale | undefined;
  1770. function resolveHostClientLanguage(): Locale | undefined {
  1771. return applicationLocale ?? persistedApplicationLocale;
  1772. }
  1773. /**
  1774. * Agent 回复语言(null 为未设置),应答 CLI 的 session/readReplyLanguage。
  1775. * 值由 Main 持有;这里只认 InitLocal 初值与 reply-language-changed,不读 setting.json。
  1776. */
  1777. let replyLanguage: string | null = null;
  1778. let activeHostApiNetworkTransport: HostApiNetworkTransport | null = null;
  1779. let sourceServerDirectory: SourceServerDirectory | null = null;
  1780. let sourceServerConnectionManager: SourceServerConnectionManager | null = null;
  1781. let sourceServerManagementService: SourceServerManagementService | null = null;
  1782. let sourceServerArtifactPolicy: SourceServerArtifactPolicy = "release-versioned";
  1783. const sourceServerDisplayNameById = new Map<string, string>();
  1784. let sourceSettingsStateSubscription: IDisposable | null = null;
  1785. const activeWorkspaceBindRequestIds = new Set<string>();
  1786. const cancelledWorkspaceBindRequestIds = new Set<string>();
  1787. const workspaceBindAbortControllers = new Map<string, AbortController>();
  1788. const projectNavigationAbortControllers = new Map<string, AbortController>();
  1789. let sourceServerRuntimeInitializeFlight: Promise<SourceServerConnectionManager> | null = null;
  1790. function notifyProjectChange(): void {
  1791. void activeServices
  1792. ?.get(IBroadcastService)
  1793. .send({ channel: "state:projects", payload: {} })
  1794. .catch((error) => logger.warn("failed to notify project change", error));
  1795. }
  1796. /** Bot 只取得当前 Source 代际,不拥有连接,也不创建 logical tab。 */
  1797. function resolveBotProjectConnection(hostId: string): BotProjectConnection | undefined {
  1798. const serverId = parseRemoteWorkspaceIdentity(
  1799. buildRemoteHostWorkspaceIdentity(hostId, "/"),
  1800. )?.sourceServerId;
  1801. if (!serverId) return undefined;
  1802. const registered = windowRemoteConnectionRegistry.getOnlineSource(serverId);
  1803. if (registered) {
  1804. const services = registered.services;
  1805. return {
  1806. owner: registered.capabilities?.physicalOwner?.() ?? services,
  1807. taskService: createControllerRoutedTaskService(services.get(IZCodeTaskService), {
  1808. kind: "local",
  1809. }),
  1810. modelSelectionService: services.get(IModelSelectionService),
  1811. agentService: services.get(IZCodeAgentService),
  1812. bindWorkspace: async (target) => {
  1813. await registered.capabilities?.bindWorkspaceIdentity?.({
  1814. workspacePath: target.workspacePath,
  1815. stableWorkspaceIdentity: target.workspaceIdentity,
  1816. legacyRouteHint: target.workspaceIdentity,
  1817. });
  1818. },
  1819. };
  1820. }
  1821. const connection = sourceServerConnectionManager?.getOnlineConnection(serverId);
  1822. if (!connection) return undefined;
  1823. return {
  1824. owner: connection.services,
  1825. taskService: createControllerRoutedTaskService(connection.services.zcodeTaskService, {
  1826. kind: "local",
  1827. }),
  1828. modelSelectionService: connection.services.modelSelectionService,
  1829. agentService: connection.services.zcodeAgentService,
  1830. bindWorkspace: async (target) => {
  1831. await connection.services.sourceServerWorkspaceService.resolveWorkspace({
  1832. workspacePath: target.workspacePath,
  1833. legacyRouteHint: target.workspaceIdentity,
  1834. });
  1835. },
  1836. };
  1837. }
  1838. function requireActiveHostApiNetworkTransport(): HostApiNetworkTransport {
  1839. if (!activeHostApiNetworkTransport) {
  1840. // Bug 原因:Source Server release 下载若在 Host 网络策略之外回退 global fetch,会绕过设置页代理。
  1841. throw new Error("Window Host network transport is not initialized");
  1842. }
  1843. return activeHostApiNetworkTransport;
  1844. }
  1845. async function ensureSourceServerConnectionManager(): Promise<SourceServerConnectionManager> {
  1846. if (sourceServerConnectionManager) return sourceServerConnectionManager;
  1847. if (!sourceServerDirectory) throw new Error("Source Server directory 尚未初始化");
  1848. if (!activeServices) throw new Error("Host services 尚未初始化");
  1849. const directory = sourceServerDirectory;
  1850. const remoteProjects = activeServices.get(IRemoteProjectService);
  1851. sourceServerRuntimeInitializeFlight ??= (async () => {
  1852. await directory.initialize();
  1853. if (hasDisposedHostResources || sourceServerDirectory !== directory) {
  1854. throw new Error("Source Server directory 初始化期间 Host 已释放");
  1855. }
  1856. const manager = new SourceServerConnectionManager({
  1857. directory,
  1858. admitConnection: createRemoteProjectConnectionAdmission(remoteProjects),
  1859. onProjectChange: notifyProjectChange,
  1860. logWarn: (message, error) => logger.warn(message, error),
  1861. sourceServerArtifactPolicy,
  1862. connectServer: (options) =>
  1863. connectDesktopSourceServer(options, {
  1864. resolveServices: (scope) => windowRemoteConnectionRegistry.resolveScopedServices(scope),
  1865. getBots: () => activeServices?.getOptional(IBotsService),
  1866. readDynamicWorkflowMode: async () =>
  1867. (await activeServices?.get(ISettingService).get())?.dynamicWorkflowMode,
  1868. onModeSyncError: (error) =>
  1869. logger.warn("remote dynamic workflow user mode push failed", error),
  1870. }),
  1871. });
  1872. sourceServerConnectionManager = manager;
  1873. return manager;
  1874. })().finally(() => {
  1875. sourceServerRuntimeInitializeFlight = null;
  1876. });
  1877. return await sourceServerRuntimeInitializeFlight;
  1878. }
  1879. /** 本地 host services 的资源遥测订阅;远端连接的订阅由各自的 connection handle 持有。 */
  1880. let activeLocalResourceTelemetry: IDisposable | null = null;
  1881. // 资源管理器采样只在 main 请求时执行一次,Host 不维护任何周期定时器。
  1882. const hostResourceUsageResponder = createHostResourceUsageResponder({
  1883. getAgentService: () => activeServices?.getOptional(IZCodeAgentService),
  1884. postMessage: (message) => parentPort?.postMessage(message),
  1885. });
  1886. let activeSessionRealtimePort: ReturnType<typeof createTaskRealtimeBridgeForHostInit> = null;
  1887. let hasDisposedHostResources = false;
  1888. let disposeHostResourcesInFlight: Promise<HostShutdownResult> | null = null;
  1889. async function disposeHostRemoteConnection(connection: HostRemoteConnection): Promise<void> {
  1890. connection.dispose();
  1891. }
  1892. async function createWindowRemoteConnectionHandle(params: {
  1893. target: RemoteTarget;
  1894. membershipIntent?: "add" | "retain";
  1895. existingSourceServerId?: string;
  1896. remoteAssets: RemoteAssetDirs;
  1897. signal: AbortSignal;
  1898. confirmSourceServerInstall?: boolean;
  1899. }): Promise<WindowRemoteConnectionHandle<ServiceCollection, HostRemoteConnectionCapabilities>> {
  1900. if (!activeServices) throw new Error("Local Host services are not initialized.");
  1901. const clientConfigService = activeServices.get(IClientConfigService);
  1902. if (params.signal.aborted) {
  1903. throw new Error("远程连接已取消");
  1904. }
  1905. const closeListeners = new Set<(event: WindowRemoteConnectionCloseEvent) => void>();
  1906. const reconnectListeners = new Set<() => void>();
  1907. let topicResourceRelay: ReturnType<typeof createWindowTopicResourceRelay> | undefined;
  1908. const notifyClose = (event: WindowRemoteConnectionCloseEvent) => {
  1909. topicResourceRelay?.dispose();
  1910. for (const listener of closeListeners) {
  1911. listener(event);
  1912. }
  1913. };
  1914. let connection: HostRemoteConnection;
  1915. let managedProfile: import("@zcode/shared").ConnectionProfile | undefined;
  1916. let reusedConnectionTarget: RemoteTarget | undefined;
  1917. let managerStateSubscription: { dispose(): void } | undefined;
  1918. let managerConnectionInvalidatedSubscription: { dispose(): void } | undefined;
  1919. let managerReconnectSubscription: { dispose(): void } | undefined;
  1920. let services: ServiceCollection;
  1921. let resourceTelemetry: IDisposable | undefined;
  1922. const refreshResourceTelemetry = () => {
  1923. resourceTelemetry?.dispose();
  1924. // Source 重连会替换 services;遥测也必须释放旧订阅并挂到新一代代理,避免重连后静默丢样本。
  1925. resourceTelemetry = registerHostServiceResourceTelemetry({
  1926. services,
  1927. postMessage: (message) => parentPort?.postMessage(message),
  1928. runtimeSurface: "remote",
  1929. // SSH/WSL/Docker 也会复用兼容的旧 Source;所有 Server 都须声明能力才订阅新增事件。
  1930. telemetrySupported: connection.serverInfo.capabilities.processResourceTelemetry === true,
  1931. remoteConversationTelemetrySupported:
  1932. connection.serverInfo.capabilities.remoteConversationTelemetry === true,
  1933. environmentKey: resolveResourceTelemetryEnvironmentKey(
  1934. params.target,
  1935. connection.serverInfo.serverId,
  1936. ),
  1937. onError: (error) => logger.warn("remote resource telemetry subscription failed", error),
  1938. });
  1939. };
  1940. let lastNotifiedRecoveryAttempt = 0;
  1941. let disposed = false;
  1942. let sourceClosed = false;
  1943. let projectSubscription: { dispose(): void } | undefined;
  1944. const detachOwnSourceSettings = () => {
  1945. const sourceId = connection?.serverInfo.serverId;
  1946. if (!sourceId || params.target.kind !== "server") return;
  1947. const current = windowRemoteConnectionRegistry.getOnlineSource(sourceId);
  1948. if (!current || current.services === services)
  1949. windowHostAttachmentRegistry.detachSourceSettingsAttachments(sourceId);
  1950. };
  1951. if (params.target.kind === "server") {
  1952. if (params.existingSourceServerId) throw new Error("project.host-offline");
  1953. if (!activeServices) throw new Error("Host services 尚未初始化");
  1954. const admission = await prepareRemoteServerConnection({
  1955. service: activeServices.get(IRemoteProjectService),
  1956. credentials: activeServices.get(ICredentialService),
  1957. target: params.target,
  1958. intent: params.membershipIntent ?? "add",
  1959. });
  1960. params.signal.throwIfAborted();
  1961. topicResourceRelay = createWindowTopicResourceRelay({
  1962. getPeerAgentService: () => connection?.services.zcodeAgentService,
  1963. resolveServices: (scope) => windowRemoteConnectionRegistry.resolveScopedServices(scope),
  1964. getBots: () => activeServices?.getOptional(IBotsService),
  1965. });
  1966. try {
  1967. connection = await connectServerRemote(admission.target, {
  1968. signal: params.signal,
  1969. fetchImpl: requireActiveHostApiNetworkTransport().fetch,
  1970. commitMembership: admission.commit,
  1971. topicResourceChannel: topicResourceRelay.channel,
  1972. onClose: ({ code, reason }) => {
  1973. sourceClosed = true;
  1974. detachOwnSourceSettings();
  1975. notifyClose({ exitCode: code, signal: null, ...(reason ? { error: reason } : {}) });
  1976. },
  1977. });
  1978. } catch (error) {
  1979. topicResourceRelay.dispose();
  1980. throw error;
  1981. }
  1982. } else {
  1983. if (!sourceServerDirectory) {
  1984. throw new Error("Source Server manager 尚未初始化");
  1985. }
  1986. const manager = await ensureSourceServerConnectionManager();
  1987. const existingProfile = params.existingSourceServerId
  1988. ? (await sourceServerDirectory.snapshot()).profiles.find(
  1989. (item) => item.sourceServerId === params.existingSourceServerId,
  1990. )
  1991. : undefined;
  1992. const existingConnection = params.existingSourceServerId
  1993. ? manager.getOnlineConnection(params.existingSourceServerId)
  1994. : undefined;
  1995. if (params.existingSourceServerId && (!existingProfile || !existingConnection))
  1996. throw new Error("project.host-offline");
  1997. const { profile, connection: managed } =
  1998. existingProfile && existingConnection
  1999. ? { profile: existingProfile, connection: existingConnection }
  2000. : await connectSourceServerTarget(sourceServerDirectory, manager, {
  2001. membershipIntent: params.membershipIntent,
  2002. target: params.target,
  2003. allowInstall: params.confirmSourceServerInstall === true,
  2004. resolveRelease: async (probe, target, options) =>
  2005. await resolveSourceServerReleaseAsset(
  2006. probe,
  2007. params.remoteAssets,
  2008. target,
  2009. {
  2010. fetch: requireActiveHostApiNetworkTransport().fetch,
  2011. },
  2012. options,
  2013. ),
  2014. context: {
  2015. signal: params.signal,
  2016. onLog: (event) => {
  2017. const progress =
  2018. event.progress == null
  2019. ? ""
  2020. : ` ${(Math.max(0, Math.min(1, event.progress)) * 100).toFixed(1)}%`;
  2021. // 上传与本机下载的进度消息自带百分比和速度,原样输出。
  2022. const message =
  2023. event.progress == null || /^(?:upload|download) progress:/u.test(event.message)
  2024. ? `[source-server:${event.phase}] ${event.message}`
  2025. : `[source-server:${event.phase}] upload progress (${event.message}):${progress}`;
  2026. remoteConnectionProgressContext.report(event.level ?? "info", [message]);
  2027. },
  2028. },
  2029. });
  2030. managedProfile = profile;
  2031. reusedConnectionTarget = managed.reusedConnectionTarget;
  2032. const sourceDirectorySnapshot = await sourceServerDirectory.snapshot();
  2033. for (const server of sourceDirectorySnapshot.servers) {
  2034. sourceServerDisplayNameById.set(server.sourceServerId, server.displayName);
  2035. }
  2036. managerStateSubscription = manager.onDidChangeState((state) => {
  2037. if (state.profileId !== profile.profileId) return;
  2038. if (state.state === "online") {
  2039. lastNotifiedRecoveryAttempt = 0;
  2040. return;
  2041. }
  2042. const closeEvent = createSourceServerRecoveryCloseEvent(state);
  2043. if (!closeEvent) return;
  2044. if (state.state === "retrying" && state.recoveryAttempt === lastNotifiedRecoveryAttempt) {
  2045. return;
  2046. }
  2047. if (state.state === "retrying") {
  2048. lastNotifiedRecoveryAttempt = state.recoveryAttempt ?? lastNotifiedRecoveryAttempt;
  2049. }
  2050. notifyClose(closeEvent);
  2051. });
  2052. connection = {
  2053. serverInfo: managed.serverInfo,
  2054. services: managed.services,
  2055. dispose() {
  2056. // Bug 原因:Window registry handle 是 logical/attachment lease,不是 Source connection owner。
  2057. // 旧 entry 取消或迟到恢复时若调用 manager.disconnect,会拆掉新 entry 正在共享的
  2058. // Source。真实物理连接由 SourceServerConnectionManager 在显式断开或 Host shutdown 回收。
  2059. },
  2060. };
  2061. managerConnectionInvalidatedSubscription = manager.onDidInvalidateConnection((event) => {
  2062. if (event.sourceServerId !== managed.sourceServerId || disposed) return;
  2063. // Bug 原因:物理 Source connection 被更新或其当前 Profile 被删除时,若不先按
  2064. // Source 通知 Registry,已有 logical workspace 会继续以 online 状态持有失效 services。
  2065. // 只有显式列出的原因可恢复:更新与重启远端服务完成后由 reconnect 换代。删除当前 Profile
  2066. // 属于用户显式断开,必须发布 terminal close;未来新增的原因默认不可恢复,需在此显式声明。
  2067. notifyClose({
  2068. exitCode: null,
  2069. signal: null,
  2070. recoverable: event.reason === "update" || event.reason === "restart",
  2071. });
  2072. });
  2073. managerReconnectSubscription = manager.onDidReconnect((reconnected) => {
  2074. if (reconnected.sourceServerId !== managed.sourceServerId || disposed) return;
  2075. connection = {
  2076. serverInfo: reconnected.serverInfo,
  2077. services: reconnected.services,
  2078. dispose() {
  2079. // 同上:只释放当前 wrapper 的订阅,不跨 lease 关闭共享 Source。
  2080. },
  2081. };
  2082. services = createServerRemoteWorkspaceServiceCollection({
  2083. clientConfigService,
  2084. connectionServices: reconnected.services,
  2085. virtualProjects: reconnected.serverInfo.capabilities.virtualProjects,
  2086. serverId: reconnected.serverInfo.serverId,
  2087. sourceServices: activeServices ?? undefined,
  2088. targetKind: params.target.kind,
  2089. });
  2090. refreshResourceTelemetry();
  2091. lastNotifiedRecoveryAttempt = 0;
  2092. for (const listener of reconnectListeners) listener();
  2093. });
  2094. }
  2095. if (params.signal.aborted) {
  2096. topicResourceRelay?.dispose();
  2097. await disposeHostRemoteConnection(connection);
  2098. throw new Error("远程连接已取消");
  2099. }
  2100. services = createServerRemoteWorkspaceServiceCollection({
  2101. clientConfigService,
  2102. connectionServices: connection.services,
  2103. virtualProjects: connection.serverInfo.capabilities.virtualProjects,
  2104. serverId: connection.serverInfo.serverId,
  2105. targetKind: params.target.kind,
  2106. sourceServices: activeServices ?? undefined,
  2107. });
  2108. if (params.target.kind === "server") {
  2109. projectSubscription = connection.services.broadcastService.onMessage((event) => {
  2110. if (!disposed && !sourceClosed && event.channel === "state:projects") notifyProjectChange();
  2111. });
  2112. }
  2113. refreshResourceTelemetry();
  2114. // 桌面 attachment 对远端媒体走 Host loopback Range 数据面;services 会随 Source 重连换代,
  2115. // 工厂在调用时再取当前 file service。server 直连保持 renderer inline 读取。
  2116. const remoteMediaPreviewFactory =
  2117. params.target.kind === "server" || !remoteMediaRangePreviewEnabled
  2118. ? undefined
  2119. : (scope: Extract<WindowHostAttachmentScope, { kind: "remote" }>) =>
  2120. createRemoteMediaPreviewProxy({
  2121. fileService: services.get(IFileService),
  2122. logger: {
  2123. debug: (message, metadata) => {
  2124. if (process.env.NODE_ENV !== "production") logger.info(message, metadata);
  2125. },
  2126. warn: (message, metadata) => logger.warn(message, metadata),
  2127. },
  2128. scope,
  2129. requestLimiter: hostRemoteMediaRequestLimiter,
  2130. });
  2131. return {
  2132. ...(reusedConnectionTarget ? { reusedConnectionTarget } : {}),
  2133. get services() {
  2134. return services;
  2135. },
  2136. capabilities: {
  2137. sourceServerId: connection.serverInfo.serverId,
  2138. physicalOwner: () => connection.services,
  2139. get virtualProjects() {
  2140. return connection.serverInfo.capabilities.virtualProjects;
  2141. },
  2142. ...(remoteMediaPreviewFactory ? { remoteMediaPreviewFactory } : {}),
  2143. persistentSourceConnection: true,
  2144. ...(managedProfile ? { profileId: managedProfile.profileId } : {}),
  2145. ...(managedProfile
  2146. ? {
  2147. promptAttachmentTransferFactory: (
  2148. scope: Extract<WindowHostAttachmentScope, { kind: "remote" }>,
  2149. ) => {
  2150. if (!sourceServerConnectionManager) throw new Error("Source Server is unavailable");
  2151. return createRemotePromptAttachmentTransferService(
  2152. sourceServerConnectionManager.getFileTransfer(connection.serverInfo.serverId),
  2153. {
  2154. scope,
  2155. onJanitorError: (error) => logger.warn("remote attachment janitor failed", error),
  2156. },
  2157. );
  2158. },
  2159. }
  2160. : {}),
  2161. ...(managedProfile && sourceServerDirectory
  2162. ? {
  2163. bindWorkspaceIdentity: async (input) => {
  2164. input.signal?.throwIfAborted();
  2165. const currentRouteHint = buildRemoteWorkspaceIdentity(
  2166. input.workspacePath,
  2167. params.target,
  2168. );
  2169. const legacyRouteHint = await sourceServerDirectory!.resolveLegacyWorkspaceIdentity({
  2170. profileId: managedProfile!.profileId,
  2171. workspacePath: input.workspacePath,
  2172. fallback: input.legacyRouteHint ?? currentRouteHint,
  2173. });
  2174. input.signal?.throwIfAborted();
  2175. await connection.services.sourceServerWorkspaceService.resolveWorkspace({
  2176. workspacePath: input.workspacePath,
  2177. legacyRouteHint,
  2178. });
  2179. },
  2180. }
  2181. : {
  2182. bindWorkspaceIdentity: async (input) => {
  2183. await connection.services.sourceServerWorkspaceService.resolveWorkspace({
  2184. workspacePath: input.workspacePath,
  2185. });
  2186. },
  2187. }),
  2188. ...(managedProfile && sourceServerDirectory
  2189. ? {
  2190. recordWorkspaceOpen: async (input) => {
  2191. await sourceServerDirectory?.recordWorkspaceOpen({
  2192. profileId: managedProfile!.profileId,
  2193. sourceServerId: connection.serverInfo.serverId,
  2194. ...input,
  2195. });
  2196. },
  2197. }
  2198. : {}),
  2199. },
  2200. onDidClose(listener) {
  2201. closeListeners.add(listener);
  2202. return { dispose: () => closeListeners.delete(listener) };
  2203. },
  2204. onDidReconnect(listener) {
  2205. reconnectListeners.add(listener);
  2206. return { dispose: () => reconnectListeners.delete(listener) };
  2207. },
  2208. async dispose() {
  2209. if (disposed) {
  2210. return;
  2211. }
  2212. disposed = true;
  2213. detachOwnSourceSettings();
  2214. topicResourceRelay?.dispose();
  2215. closeListeners.clear();
  2216. reconnectListeners.clear();
  2217. managerStateSubscription?.dispose();
  2218. managerConnectionInvalidatedSubscription?.dispose();
  2219. managerReconnectSubscription?.dispose();
  2220. projectSubscription?.dispose();
  2221. resourceTelemetry?.dispose();
  2222. await disposeHostRemoteConnection(connection);
  2223. },
  2224. };
  2225. }
  2226. // 项目树/发送前目录解析的远端身份登记,按物理连接去重(见 createRemoteIdentityRegistrationCache)。
  2227. // Registry 路径带 Host 目录的 legacy hint,Manager 路径不带;两者分开缓存,各自的首次登记请求保持不变。
  2228. // 工作区打开(prepareWorkspaceIdentity)不走这里,打开时仍按 R3 §9.2 惰性合并旧变体。
  2229. const registryProjectIdentityRegistrations = createRemoteIdentityRegistrationCache();
  2230. const managerProjectIdentityRegistrations = createRemoteIdentityRegistrationCache();
  2231. const windowRemoteConnectionRegistry = createWindowRemoteConnectionRegistry<
  2232. ServiceCollection,
  2233. HostRemoteConnectionCapabilities
  2234. >({
  2235. connect: (request) => createWindowRemoteConnectionHandle(request),
  2236. createId: randomUUID,
  2237. onConnectionChanged: notifyProjectChange,
  2238. resolveSourceServerId: (handle) => handle.capabilities?.sourceServerId,
  2239. shouldKeepConnectionAlive: (handle) => handle.capabilities?.persistentSourceConnection === true,
  2240. prepareWorkspaceIdentity: async (handle, input) => {
  2241. // 连接向导据此显示“打开项目目录”这一步;失败(含超时)时同一步标红。只在连接请求的上下文内上报。
  2242. remoteConnectionProgressContext.report("info", [
  2243. `[source-server:workspace] Preparing ${input.workspacePath}`,
  2244. ]);
  2245. try {
  2246. await prepareRemoteWorkspaceIdentity(
  2247. handle.services.get(IFileService),
  2248. input,
  2249. handle.capabilities?.bindWorkspaceIdentity,
  2250. );
  2251. } catch (error) {
  2252. if (!input.signal?.aborted) {
  2253. remoteConnectionProgressContext.report("error", [
  2254. `[source-server:workspace] ${error instanceof Error ? error.message : String(error)}`,
  2255. ]);
  2256. }
  2257. throw error;
  2258. }
  2259. },
  2260. releaseWorkspace: async (services, context) => {
  2261. await services.get(IZCodeTaskService).releaseWorkspacePreparation({
  2262. workspacePath: context.workspacePath,
  2263. ...(context.workspaceIdentity ? { workspaceIdentity: context.workspaceIdentity } : {}),
  2264. provider: "glm",
  2265. });
  2266. logger.info(
  2267. `released WSL workspace runtime, workspaceKey=${context.workspaceIdentity?.trim() || context.workspacePath}`,
  2268. );
  2269. },
  2270. onWorkspaceReleaseError: (context, error) => {
  2271. logger.warn(
  2272. `failed to release WSL workspace runtime, workspaceKey=${context.workspaceIdentity?.trim() || context.workspacePath}`,
  2273. error,
  2274. );
  2275. },
  2276. onSessionClosed: (event) => {
  2277. // logical session 已离线时 attachment 仍持有旧 services/订阅;后续 sessionId
  2278. // 换代只释放 transport,无法按旧 ID 找回这些端口。Host 在失效源头统一关闭所有 clientMode。
  2279. windowHostAttachmentRegistry.detachRemoteSessionAttachments(event.remoteSessionId);
  2280. const session = windowRemoteConnectionRegistry.getSession(event.remoteSessionId);
  2281. if (session?.workspacePath && session.workspaceIdentity) {
  2282. windowHostControllerRuntime.disconnectSource({
  2283. kind: "remote",
  2284. ...(session.sourceServerId ? { sourceServerId: session.sourceServerId } : {}),
  2285. remoteSessionId: event.remoteSessionId,
  2286. workspacePath: session.workspacePath,
  2287. workspaceIdentity: session.workspaceIdentity,
  2288. });
  2289. }
  2290. parentPort?.postMessage({
  2291. type: HostResponseTypes.RemoteWorkspaceClosed,
  2292. remoteSessionId: event.remoteSessionId,
  2293. reason: "connection-closed",
  2294. exitCode: event.exitCode,
  2295. signal: event.signal,
  2296. ...(event.recoverable !== undefined ? { recoverable: event.recoverable } : {}),
  2297. ...(event.error ? { error: event.error } : {}),
  2298. ...(event.recoveryAttempt ? { recoveryAttempt: event.recoveryAttempt } : {}),
  2299. ...(event.recoveryLimit ? { recoveryLimit: event.recoveryLimit } : {}),
  2300. ...(event.recoveryBudgetExhausted !== undefined
  2301. ? { recoveryBudgetExhausted: event.recoveryBudgetExhausted }
  2302. : {}),
  2303. ...(event.reasonCode ? { reasonCode: event.reasonCode } : {}),
  2304. ...(event.retryable !== undefined ? { retryable: event.retryable } : {}),
  2305. });
  2306. logWindowHostTopology("remote-connection-closed");
  2307. },
  2308. onSessionReconnected: async ({
  2309. previous,
  2310. current,
  2311. services: currentServices,
  2312. isCurrent,
  2313. commit,
  2314. }) => {
  2315. if (
  2316. !previous.workspacePath ||
  2317. !previous.workspaceIdentity ||
  2318. !current.workspacePath ||
  2319. !current.workspaceIdentity
  2320. ) {
  2321. throw new Error("Source 重连换代缺少 workspace scope");
  2322. }
  2323. const previousScope = {
  2324. kind: "remote" as const,
  2325. ...(previous.sourceServerId ? { sourceServerId: previous.sourceServerId } : {}),
  2326. remoteSessionId: previous.remoteSessionId,
  2327. workspacePath: previous.workspacePath,
  2328. workspaceIdentity: previous.workspaceIdentity,
  2329. };
  2330. const currentScope = {
  2331. kind: "remote" as const,
  2332. ...(current.sourceServerId ? { sourceServerId: current.sourceServerId } : {}),
  2333. ...(current.sourceServerId && sourceServerDisplayNameById.get(current.sourceServerId)
  2334. ? {
  2335. serverDisplayName: sourceServerDisplayNameById.get(current.sourceServerId),
  2336. }
  2337. : {}),
  2338. remoteSessionId: current.remoteSessionId,
  2339. workspacePath: current.workspacePath,
  2340. workspaceIdentity: current.workspaceIdentity,
  2341. };
  2342. await windowHostControllerRuntime.replaceDisconnectedSource(
  2343. previousScope,
  2344. {
  2345. scope: currentScope,
  2346. taskService: currentServices.get(IZCodeTaskService),
  2347. agentService: currentServices.getOptional(IZCodeAgentService),
  2348. sourceAvailability: "online",
  2349. },
  2350. {
  2351. canCommit: isCurrent,
  2352. rollbackOnFailure: true,
  2353. },
  2354. );
  2355. if (!commit()) {
  2356. throw new Error("Source 重连换代在 Controller 提交后失去 Registry owner");
  2357. }
  2358. try {
  2359. parentPort?.postMessage({
  2360. type: HostResponseTypes.RemoteWorkspaceReconnected,
  2361. previousRemoteSessionId: previous.remoteSessionId,
  2362. descriptor: {
  2363. ...(current.sourceServerId ? { sourceServerId: current.sourceServerId } : {}),
  2364. remoteSessionId: current.remoteSessionId,
  2365. target: current.target,
  2366. workspacePath: current.workspacePath,
  2367. workspaceIdentity: current.workspaceIdentity,
  2368. generation: current.generation,
  2369. },
  2370. });
  2371. } catch (error) {
  2372. // Controller 已提交新 generation 后不能再让 Registry 回滚;parentPort 失效意味着
  2373. // Window Host 与 Main 的进程通道正在终止,交给既有 Host shutdown 回收全部 owner。
  2374. logger.error("failed to publish committed remote workspace replacement", error);
  2375. }
  2376. logWindowHostTopology("remote-connection-reconnected");
  2377. },
  2378. onSessionReconnectError: (error) => {
  2379. logger.warn("failed to replace Source Server logical sessions after reconnect", error);
  2380. },
  2381. });
  2382. const windowHostControllerRuntime = createWindowHostControllerRuntime({
  2383. onRunStarted: (run) =>
  2384. parentPort?.postMessage({
  2385. type: HostResponseTypes.Broadcast,
  2386. message: { channel: "mobile-push:run", payload: run },
  2387. }),
  2388. onNotification: (event) =>
  2389. parentPort?.postMessage({
  2390. type: HostResponseTypes.Broadcast,
  2391. message: { channel: "mobile-push:event", payload: event },
  2392. }),
  2393. createId: randomUUID,
  2394. readHostTaskList: (query) => {
  2395. if (!activeServices) throw new Error("Window Host services unavailable");
  2396. return activeServices.get(IZCodeTaskService).listTaskList(query);
  2397. },
  2398. onSourceError: (scope, operation, error) => {
  2399. logger.warn(
  2400. `window Controller source ${operation} failed, scope=${scope.kind}, workspaceKey=${scope.workspaceIdentity?.trim() || scope.workspacePath}`,
  2401. error,
  2402. );
  2403. },
  2404. // 归档 / 删除任务只改 task index,tab 仍挂在原任务名下:任务离开列表后没有 scope 能显示它,
  2405. // 出声的 tab 又受 residency 保护不被逐出,页面会一直在后台播放。Controller 收到任务归档/删除事实后由这里关闭属主 tab。
  2406. onTasksArchivedOrDeleted: (scope, taskIds) => {
  2407. const workspaceKey = scope.workspaceIdentity?.trim() || scope.workspacePath;
  2408. for (const taskId of taskIds) {
  2409. void browserControlMainBridge
  2410. .execute({
  2411. sessionId: taskId,
  2412. workspaceKey,
  2413. workspacePath: scope.workspacePath,
  2414. ...(scope.workspaceIdentity ? { workspaceIdentity: scope.workspaceIdentity } : {}),
  2415. ...(scope.kind === "remote" && scope.remoteSessionId
  2416. ? { remoteSessionId: scope.remoteSessionId }
  2417. : {}),
  2418. command: { method: "closeSession", closeTabs: true },
  2419. })
  2420. .then((result) => {
  2421. if (!result.ok) {
  2422. logger.warn(
  2423. `archived/deleted task browser tabs cleanup failed, taskId=${taskId}, code=${result.error?.code ?? "unknown"}`,
  2424. );
  2425. }
  2426. })
  2427. .catch((error) =>
  2428. logger.warn(`archived/deleted task browser tabs cleanup failed, taskId=${taskId}`, error),
  2429. );
  2430. }
  2431. },
  2432. resolveSource: (scope) => {
  2433. const remoteSession = windowRemoteConnectionRegistry.findSessionForWorkspace(scope);
  2434. if (remoteSession?.workspacePath && remoteSession.workspaceIdentity) {
  2435. const controllerScope = {
  2436. kind: "remote" as const,
  2437. ...(remoteSession.sourceServerId ? { sourceServerId: remoteSession.sourceServerId } : {}),
  2438. ...(remoteSession.sourceServerId &&
  2439. sourceServerDisplayNameById.get(remoteSession.sourceServerId)
  2440. ? {
  2441. serverDisplayName: sourceServerDisplayNameById.get(remoteSession.sourceServerId),
  2442. }
  2443. : {}),
  2444. remoteSessionId: remoteSession.remoteSessionId,
  2445. workspacePath: remoteSession.workspacePath,
  2446. workspaceIdentity: remoteSession.workspaceIdentity,
  2447. };
  2448. if (remoteSession.sourceAvailability !== "online") {
  2449. return {
  2450. scope: controllerScope,
  2451. sourceAvailability: "offline" as const,
  2452. };
  2453. }
  2454. const services = windowRemoteConnectionRegistry.resolveScopedServices(controllerScope);
  2455. return {
  2456. scope: controllerScope,
  2457. taskService: services.get(IZCodeTaskService),
  2458. agentService: services.getOptional(IZCodeAgentService),
  2459. sourceAvailability: "online" as const,
  2460. };
  2461. }
  2462. // 远程 history scope 未连接或已被移除时,绝不能落回本地 tasks-index。
  2463. if (scope.workspaceIdentity && isRemoteWorkspaceIdentity(scope.workspaceIdentity)) {
  2464. // 项目树不要求打开 workspace tab;列表命令可复用稳定 Source 的现有物理连接,不能伪造 logical session。
  2465. const identity = parseRemoteWorkspaceIdentity(scope.workspaceIdentity);
  2466. const connection =
  2467. identity?.kind === "server" &&
  2468. identity.sourceServerId &&
  2469. identity.workspacePath === scope.workspacePath
  2470. ? sourceServerConnectionManager?.getOnlineConnection(identity.sourceServerId)
  2471. : undefined;
  2472. const registered =
  2473. identity?.kind === "server" &&
  2474. identity.sourceServerId &&
  2475. identity.workspacePath === scope.workspacePath
  2476. ? windowRemoteConnectionRegistry.getOnlineSource(identity.sourceServerId)
  2477. : undefined;
  2478. if (identity?.kind === "server" && identity.sourceServerId && (connection || registered))
  2479. return {
  2480. scope: {
  2481. kind: "remote" as const,
  2482. sourceServerId: identity.sourceServerId,
  2483. workspacePath: scope.workspacePath,
  2484. workspaceIdentity: scope.workspaceIdentity,
  2485. },
  2486. taskService:
  2487. connection?.services.zcodeTaskService ?? registered!.services.get(IZCodeTaskService),
  2488. agentService:
  2489. connection?.services.zcodeAgentService ??
  2490. registered!.services.getOptional(IZCodeAgentService),
  2491. sourceAvailability: "online" as const,
  2492. };
  2493. return null;
  2494. }
  2495. const taskService = activeServices?.getOptional(IZCodeTaskService);
  2496. if (!taskService) {
  2497. return null;
  2498. }
  2499. return {
  2500. scope: {
  2501. kind: "local" as const,
  2502. workspacePath: scope.workspacePath,
  2503. ...(scope.workspaceIdentity ? { workspaceIdentity: scope.workspaceIdentity } : {}),
  2504. },
  2505. taskService,
  2506. agentService: activeServices?.getOptional(IZCodeAgentService),
  2507. sourceAvailability: "online" as const,
  2508. };
  2509. },
  2510. });
  2511. // 手机 project.readTree 叠加实时待处理交互;只有手机 attachment 存在时才监听投影并广播。
  2512. const webRemoteProjectTreeActivity = createWebRemoteProjectTreeActivityBridge({
  2513. readRows: () => windowHostControllerRuntime.readTaskRows(),
  2514. subscribeRows: (onChange) => windowHostControllerRuntime.subscribeTaskRows(onChange),
  2515. notifyProjectChange,
  2516. });
  2517. function wireLocalResourceTelemetry(services: ServiceCollection): void {
  2518. activeLocalResourceTelemetry?.dispose();
  2519. activeLocalResourceTelemetry = registerHostServiceResourceTelemetry({
  2520. services,
  2521. postMessage: (message) => parentPort?.postMessage(message),
  2522. runtimeSurface: "local",
  2523. onError: (error) => logger.warn("local resource telemetry subscription failed", error),
  2524. });
  2525. }
  2526. function disposeLocalResourceTelemetry(): void {
  2527. try {
  2528. activeLocalResourceTelemetry?.dispose();
  2529. } catch {
  2530. // 资源遥测释放失败不能阻塞 Host 的既有 shutdown barrier。
  2531. } finally {
  2532. activeLocalResourceTelemetry = null;
  2533. }
  2534. }
  2535. type ExposedServicePortHandle = {
  2536. server: IChannelServer & { ready(): void };
  2537. dispose(): void;
  2538. };
  2539. function createControllerRoutedTaskService(
  2540. base: IZCodeTaskService,
  2541. attachmentScope: WindowHostAttachmentScope,
  2542. ): IZCodeTaskService {
  2543. const route = async (
  2544. params: {
  2545. taskId: string;
  2546. workspacePath: string;
  2547. workspaceIdentity?: string;
  2548. },
  2549. mutation:
  2550. | { kind: "pin"; pinned: boolean }
  2551. | { kind: "archive"; archived: boolean }
  2552. | { kind: "delete" }
  2553. | { kind: "mark-read"; expectedUnreadAt?: number }
  2554. | { kind: "mark-unread" },
  2555. ) =>
  2556. windowHostControllerRuntime.service.mutateTask({
  2557. address: await windowHostControllerRuntime.resolveTaskAddress({
  2558. taskId: params.taskId,
  2559. workspacePath: params.workspacePath,
  2560. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  2561. attachmentScope,
  2562. }),
  2563. mutation,
  2564. });
  2565. return new Proxy(base, {
  2566. get(target, property, receiver) {
  2567. if (property === "setTaskPinned") {
  2568. return async (params: Parameters<IZCodeTaskService["setTaskPinned"]>[0]) => {
  2569. const meta = await route(params, {
  2570. kind: "pin",
  2571. pinned: params.pinned,
  2572. });
  2573. if (!meta) throw new Error("pin mutation 后 task 投影缺失");
  2574. return meta;
  2575. };
  2576. }
  2577. if (property === "archiveTask" || property === "unarchiveTask") {
  2578. return async (
  2579. params:
  2580. | Parameters<IZCodeTaskService["archiveTask"]>[0]
  2581. | Parameters<IZCodeTaskService["unarchiveTask"]>[0],
  2582. ) => {
  2583. const meta = await route(params, {
  2584. kind: "archive",
  2585. archived: property === "archiveTask",
  2586. });
  2587. if (!meta) throw new Error("archive mutation 后 task 投影缺失");
  2588. return meta;
  2589. };
  2590. }
  2591. if (property === "deleteTask") {
  2592. return async (params: Parameters<IZCodeTaskService["deleteTask"]>[0]) => {
  2593. await route(params, { kind: "delete" });
  2594. };
  2595. }
  2596. if (property === "deleteArchivedTasks") {
  2597. return async (params: Parameters<IZCodeTaskService["deleteArchivedTasks"]>[0]) => {
  2598. if (params.taskIds.length === 0) {
  2599. return { deletedTaskIds: [], skippedTaskIds: [], failedTaskIds: [] };
  2600. }
  2601. return windowHostControllerRuntime.service.deleteArchivedTasks({
  2602. address: await windowHostControllerRuntime.resolveTaskAddress({
  2603. workspacePath: params.workspacePath,
  2604. workspaceIdentity: params.workspaceIdentity,
  2605. taskId: params.taskIds[0]!,
  2606. attachmentScope,
  2607. allowMissingTask: true,
  2608. }),
  2609. taskIds: params.taskIds,
  2610. });
  2611. };
  2612. }
  2613. if (property === "deleteArchivedTask") {
  2614. return async (params: Parameters<IZCodeTaskService["deleteArchivedTask"]>[0]) =>
  2615. windowHostControllerRuntime.service.deleteArchivedTask({
  2616. address: await windowHostControllerRuntime.resolveTaskAddress({
  2617. ...params,
  2618. attachmentScope,
  2619. allowMissingTask: true,
  2620. }),
  2621. });
  2622. }
  2623. if (property === "setTaskUnread") {
  2624. return async (params: Parameters<IZCodeTaskService["setTaskUnread"]>[0]) => {
  2625. const meta = await route(
  2626. params,
  2627. params.unread
  2628. ? { kind: "mark-unread" }
  2629. : {
  2630. kind: "mark-read",
  2631. ...(params.expectedUnreadAt != null
  2632. ? { expectedUnreadAt: params.expectedUnreadAt }
  2633. : {}),
  2634. },
  2635. );
  2636. if (!meta) throw new Error("unread mutation 后 task 投影缺失");
  2637. return meta;
  2638. };
  2639. }
  2640. const value = Reflect.get(target, property, receiver) as unknown;
  2641. if (
  2642. typeof value === "function" &&
  2643. [
  2644. "getBotGroupTaskBlockReason",
  2645. "cancelBotGroupInput",
  2646. "submitBotGroupInput",
  2647. "readBotTopicSummaries",
  2648. ].includes(String(property))
  2649. ) {
  2650. return (params: Record<string, unknown>) =>
  2651. value.call(target, bindBotGroupTaskScope(params, attachmentScope));
  2652. }
  2653. return typeof value === "function" ? value.bind(target) : value;
  2654. },
  2655. });
  2656. }
  2657. const terminalOwners = createWindowHostTerminalOwners((error) => {
  2658. logger.warn("failed to dispose mobile terminal owner", error);
  2659. });
  2660. function exposeServicesOnMessagePort(
  2661. port: Electron.MessagePortMain,
  2662. services: ServiceCollection,
  2663. deferInit: boolean,
  2664. clientMode: ZCodeAgentV4ClientMode = "desktop-continuous",
  2665. attachmentScope: WindowHostAttachmentScope = { kind: "local" },
  2666. capabilities?: HostRemoteConnectionCapabilities,
  2667. terminalOwnerId?: string,
  2668. ): ExposedServicePortHandle {
  2669. const terminal = services.getOptional(ITerminalService);
  2670. const legacyTerminalScope =
  2671. clientMode === "web-remote-replayable" && terminal && !terminalOwnerId
  2672. ? createTerminalScope(terminal, (error) =>
  2673. logger.warn("failed to dispose mobile attachment terminal", error),
  2674. )
  2675. : undefined;
  2676. const scopedTerminal =
  2677. clientMode === "web-remote-replayable" && terminal
  2678. ? terminalOwnerId
  2679. ? terminalOwners.bind(
  2680. terminalOwnerId,
  2681. attachmentScope.kind === "remote"
  2682. ? `remote:${attachmentScope.remoteSessionId}`
  2683. : "local",
  2684. terminal,
  2685. )
  2686. : legacyTerminalScope!.service
  2687. : undefined;
  2688. const wrappedPort = wrapElectronPort(port);
  2689. const protocol = new MessagePortProtocol(wrappedPort);
  2690. // remote 模式延迟发送 Initialize:远程建连需要时间,如果构造时就发 Initialize,
  2691. // renderer 会立即发请求但 channel 还没注册,导致 "Unknown channel" 超时错误。
  2692. // attach 模式复用已就绪服务,必须立即初始化新的 RPC MessagePort。
  2693. logger.info(`creating ChannelServer (deferInit=${deferInit})`);
  2694. const rawServer = new ChannelServer(protocol, "host", 1000, deferInit);
  2695. const loggedServer = new LoggingChannelServer(rawServer, logRpc);
  2696. const server = new NetworkTelemetryChannelServer(loggedServer);
  2697. const agentService = services.getOptional(IZCodeAgentService);
  2698. const connectionContext = { connectionId: `host-rpc-${randomUUID()}`, clientMode };
  2699. const connectionScope = agentService
  2700. ? createZCodeAgentConnectionScope(agentService, connectionContext)
  2701. : undefined;
  2702. services.register(IWindowControllerService, windowHostControllerRuntime.service);
  2703. // 未读自动写入只归窗口 base renderer;手机和 remote facade 不能重复消费同一完成信号。
  2704. const controllerAttachment = windowHostControllerRuntime.createAttachmentService(
  2705. clientMode === "desktop-continuous" && attachmentScope.kind === "local",
  2706. // 侧栏手动顺序只在桌面 renderer 偏好里;桌面上报后叠加到手机 readTree,手机 attachment 不能写。
  2707. clientMode === "desktop-continuous"
  2708. ? { onProjectDisplayOrder: (order) => webRemoteProjectTreeActivity.setProjectOrder(order) }
  2709. : {},
  2710. );
  2711. const overrides = new Map<string, unknown>([
  2712. [IWindowControllerService.channelName, controllerAttachment],
  2713. ]);
  2714. // 手机可从任意远端 workspace 重建 Root;侧栏组织服务仍归控制端,不能随当前执行 attachment 换库。
  2715. if (
  2716. clientMode === "web-remote-replayable" &&
  2717. attachmentScope.kind === "remote" &&
  2718. activeServices
  2719. ) {
  2720. overrides.set(IProjectService.channelName, activeServices.get(IProjectService));
  2721. overrides.set(IRemoteProjectService.channelName, activeServices.get(IRemoteProjectService));
  2722. services.register(ITaskGroupService, activeServices.get(ITaskGroupService));
  2723. }
  2724. // 远端媒体必须按 attachment 的 clientMode 选择数据面:桌面使用 Host loopback Range,手机保持 inline。
  2725. const remoteMediaPreviewProxy =
  2726. attachmentScope.kind === "remote" && clientMode === "desktop-continuous"
  2727. ? capabilities?.remoteMediaPreviewFactory?.(attachmentScope)
  2728. : undefined;
  2729. if (remoteMediaPreviewProxy) {
  2730. overrides.set(IMediaPreviewService.channelName, remoteMediaPreviewProxy.service);
  2731. }
  2732. // R3 的 Source 本地 transfer 无法读取 Desktop localPath;跨机 staging 必须在 owning
  2733. // Window Host attachment 注入,复用当前 transport。桌面/手机不另建 runtime 或业务队列。
  2734. const remotePromptAttachmentTransfer =
  2735. attachmentScope.kind === "remote"
  2736. ? capabilities?.promptAttachmentTransferFactory?.(attachmentScope)
  2737. : undefined;
  2738. const { dispose: disposePromptAttachmentTransfer, ...promptAttachmentService } =
  2739. remotePromptAttachmentTransfer ?? {};
  2740. if (remotePromptAttachmentTransfer) {
  2741. // dispose 只属于 Host attachment 生命周期,不暴露为 Renderer RPC。
  2742. overrides.set(IPromptAttachmentTransferService.channelName, promptAttachmentService);
  2743. }
  2744. const taskService = services.getOptional(IZCodeTaskService);
  2745. if (taskService) {
  2746. overrides.set(
  2747. IZCodeTaskService.channelName,
  2748. createControllerRoutedTaskService(taskService, attachmentScope),
  2749. );
  2750. }
  2751. if (connectionScope) {
  2752. overrides.set(IZCodeAgentService.channelName, connectionScope.service);
  2753. }
  2754. const conversationShareService = services.getOptional(IConversationShareService);
  2755. if (conversationShareService) {
  2756. // Share service 若继续持有 raw Agent,会绕过当前 MessagePort 已握手的 trusted carrier,
  2757. // rowsRange 会以 connection untrusted 拒绝。必须复用同一 attachment connection scope。
  2758. overrides.set(
  2759. IConversationShareService.channelName,
  2760. scopeConversationShareServiceForAttachment(
  2761. conversationShareService,
  2762. clientMode,
  2763. connectionScope?.service,
  2764. connectionContext,
  2765. ),
  2766. );
  2767. }
  2768. if (scopedTerminal) overrides.set(ITerminalService.channelName, scopedTerminal);
  2769. const isWebRemoteAttachment = clientMode === "web-remote-replayable";
  2770. const baseProjectService = isWebRemoteAttachment
  2771. ? ((overrides.get(IProjectService.channelName) as IProjectService | undefined) ??
  2772. services.getOptional(IProjectService))
  2773. : undefined;
  2774. if (baseProjectService) {
  2775. overrides.set(
  2776. IProjectService.channelName,
  2777. webRemoteProjectTreeActivity.decorate(baseProjectService),
  2778. );
  2779. }
  2780. const webRemoteProjectTreeRetention = isWebRemoteAttachment
  2781. ? webRemoteProjectTreeActivity.retain()
  2782. : undefined;
  2783. exposeWindowHostAttachmentServices({
  2784. server,
  2785. services,
  2786. overrides,
  2787. clientMode,
  2788. attachmentScope,
  2789. windowServices: activeServices ?? undefined,
  2790. ...(isWebRemoteAttachment
  2791. ? { decorateWindowProjectService: webRemoteProjectTreeActivity.decorate }
  2792. : {}),
  2793. });
  2794. let disposed = false;
  2795. let flowUpdateChain = Promise.resolve();
  2796. const forwardFlowState = (state: "saturated" | "drained" | "closed") => {
  2797. if (!connectionScope) return Promise.resolve();
  2798. const update = flowUpdateChain.then(() => connectionScope.setTransportFlowState(state));
  2799. flowUpdateChain = update.catch((error) => {
  2800. logger.warn("failed to forward attachment connection flow state", {
  2801. state,
  2802. message: error instanceof Error ? error.message : String(error),
  2803. });
  2804. });
  2805. return update;
  2806. };
  2807. const flowStateDisposable = protocol.onFlowState((state) => {
  2808. if (disposed) return;
  2809. // MessagePort sideband 已在 protocol 层与 Uint8Array 分流;这里只把 owning scope
  2810. // 的 edge 串行送往 CLI,不能由 control object 指定 connectionId。
  2811. void forwardFlowState(state).catch(() => {});
  2812. });
  2813. const handle: ExposedServicePortHandle = {
  2814. server,
  2815. dispose() {
  2816. if (disposed) return;
  2817. disposed = true;
  2818. flowStateDisposable.dispose();
  2819. controllerAttachment.dispose();
  2820. legacyTerminalScope?.dispose();
  2821. webRemoteProjectTreeRetention?.dispose();
  2822. void disposePromptAttachmentTransfer?.().catch((error: unknown) => {
  2823. logger.warn("failed to dispose remote attachment transfer", error);
  2824. });
  2825. void remoteMediaPreviewProxy?.dispose().catch((error: unknown) => {
  2826. logger.warn("failed to dispose remote media preview proxy", error);
  2827. });
  2828. // close 排在所有已接收 SAT/DRN 之后;scope.dispose 自身会再次幂等确保 closed,
  2829. // 但绝不让迟到 saturated 在 close 后复活 CLI pause state。
  2830. void forwardFlowState("closed")
  2831. .catch(() => {})
  2832. .then(() => connectionScope?.dispose());
  2833. rawServer.dispose();
  2834. protocol.disconnect();
  2835. },
  2836. };
  2837. port.once("close", () => handle.dispose());
  2838. logger.info(`service connection ready mode=${clientMode}`);
  2839. return handle;
  2840. }
  2841. const windowHostAttachmentRegistry = createWindowHostAttachmentRegistry<
  2842. ServiceCollection,
  2843. Electron.MessagePortMain,
  2844. HostRemoteConnectionCapabilities
  2845. >({
  2846. resolveScope: (scope: WindowHostAttachmentScope) => {
  2847. if (scope.kind === "local") {
  2848. if (!activeServices) {
  2849. throw new Error("local services 尚未初始化");
  2850. }
  2851. return { services: activeServices, generation: 1 };
  2852. }
  2853. if (scope.kind === "source-settings") {
  2854. const connection = sourceServerConnectionManager?.getOnlineConnection(scope.sourceServerId);
  2855. const registered = windowRemoteConnectionRegistry.getOnlineSource(scope.sourceServerId);
  2856. const configServices = connection?.services ?? registered?.services;
  2857. if (!configServices) {
  2858. throw new Error(`Source Server is offline: ${scope.sourceServerId}`);
  2859. }
  2860. return {
  2861. services: createSourceSettingsServiceCollection(configServices),
  2862. generation:
  2863. sourceServerConnectionManager
  2864. ?.listStates()
  2865. .find((state) => state.sourceServerId === scope.sourceServerId)?.updatedAt ?? 1,
  2866. };
  2867. }
  2868. const session = windowRemoteConnectionRegistry.getSession(scope.remoteSessionId);
  2869. if (!session) {
  2870. throw new Error(`未找到远程 logical session,remoteSessionId=${scope.remoteSessionId}`);
  2871. }
  2872. return {
  2873. services: windowRemoteConnectionRegistry.resolveScopedServices(scope),
  2874. generation: session.generation,
  2875. capabilities: windowRemoteConnectionRegistry.resolveScopedCapabilities(scope),
  2876. };
  2877. },
  2878. expose: ({ port, services, clientMode, scope, capabilities, terminalOwnerId }) =>
  2879. exposeServicesOnMessagePort(
  2880. port,
  2881. services,
  2882. false,
  2883. clientMode,
  2884. scope,
  2885. capabilities,
  2886. terminalOwnerId,
  2887. ),
  2888. });
  2889. function logWindowHostTopology(reason: string): void {
  2890. const stats = windowRemoteConnectionRegistry.getStats();
  2891. logger.info(
  2892. `window Host topology, reason=${reason}, pid=${process.pid}, connections=${stats.connectionCount}, logicalSessions=${stats.logicalSessionCount}, attachments=${windowHostAttachmentRegistry.size()}`,
  2893. );
  2894. }
  2895. function disposeAttachedServicePorts(): void {
  2896. terminalOwners.setOwner(null);
  2897. windowHostAttachmentRegistry.dispose();
  2898. }
  2899. async function disposeHostResources(reason: string): Promise<HostShutdownResult> {
  2900. databaseStartup?.dispose();
  2901. pendingStartupAttachments.clear();
  2902. if (hasDisposedHostResources) {
  2903. return (
  2904. (await disposeHostResourcesInFlight) ?? {
  2905. exitCode: 0,
  2906. failedPhases: [],
  2907. timedOutPhases: [],
  2908. }
  2909. );
  2910. }
  2911. hasDisposedHostResources = true;
  2912. for (const controller of projectNavigationAbortControllers.values()) controller.abort();
  2913. projectNavigationAbortControllers.clear();
  2914. disposeHostResourcesInFlight = (async () => {
  2915. logger.info(`disposing host resources, reason=${reason}`);
  2916. appControlNavigation.dispose();
  2917. pluginSandboxRegistrationBridge.dispose();
  2918. windowHostExtensions?.dispose();
  2919. windowHostExtensions = null;
  2920. stopHostNetworkTelemetry();
  2921. hostNetworkCapture.setCaptureId(null);
  2922. hostSelfResourceTelemetry.stop();
  2923. disposeLocalResourceTelemetry();
  2924. disposeAttachedServicePorts();
  2925. windowHostControllerRuntime.dispose();
  2926. for (const key of Array.from(cronRunSubscriptions.keys())) {
  2927. disposeCronRunSubscription(key);
  2928. }
  2929. cronAutomationRepo.close();
  2930. for (const key of Array.from(offPeakRunSubscriptions.keys())) {
  2931. disposeOffPeakRunSubscription(key);
  2932. }
  2933. disposeOffPeakRuntime();
  2934. offPeakTaskRepo.close();
  2935. if (activeSessionRealtimePort) {
  2936. activeSessionRealtimePort.dispose();
  2937. activeSessionRealtimePort = null;
  2938. }
  2939. const servicesToDispose = activeServices;
  2940. activeServices = null;
  2941. // Registry 是全部远端 connection 的唯一 owner;释放失败不能阻塞本地服务继续收口。
  2942. const remoteDisposal = runHostShutdownPhases(
  2943. [
  2944. {
  2945. name: "remote-registry-dispose",
  2946. run: () => windowRemoteConnectionRegistry.dispose(),
  2947. timeoutMs: 6_000,
  2948. },
  2949. {
  2950. name: "source-server-manager-dispose",
  2951. run: async () => {
  2952. sourceServerConnectionManager?.dispose();
  2953. sourceServerManagementService?.dispose();
  2954. sourceSettingsStateSubscription?.dispose();
  2955. sourceServerConnectionManager = null;
  2956. sourceServerManagementService = null;
  2957. sourceSettingsStateSubscription = null;
  2958. sourceServerDirectory = null;
  2959. },
  2960. timeoutMs: 2_000,
  2961. },
  2962. ],
  2963. {
  2964. phaseTimeoutMs: 5_000,
  2965. log: (message, details) => logger.warn(message, details),
  2966. },
  2967. );
  2968. // 根因:先等远端连接会耗尽本地 CLI 的正常退出窗口;两个 owner 同时开始收口。
  2969. const serviceDisposal = runHostShutdownPhases(
  2970. servicesToDispose
  2971. ? [
  2972. {
  2973. name: "service-dispose",
  2974. run: () => disposeServiceResourcesAndWait(servicesToDispose),
  2975. timeoutMs: 3_500,
  2976. },
  2977. ]
  2978. : [],
  2979. { phaseTimeoutMs: 3_500, log: (message, details) => logger.warn(message, details) },
  2980. );
  2981. const results = await Promise.all([remoteDisposal, serviceDisposal]);
  2982. const shutdownResult: HostShutdownResult = {
  2983. exitCode: results.some((result) => result.exitCode !== 0) ? 1 : 0,
  2984. failedPhases: results.flatMap((result) => result.failedPhases),
  2985. timedOutPhases: results.flatMap((result) => result.timedOutPhases),
  2986. };
  2987. if (shutdownResult.exitCode !== 0) {
  2988. logger.warn("host resource cleanup completed with errors", {
  2989. failedPhases: shutdownResult.failedPhases,
  2990. reason,
  2991. timedOutPhases: shutdownResult.timedOutPhases,
  2992. });
  2993. }
  2994. activeHostApiNetworkTransport = null;
  2995. return shutdownResult;
  2996. })();
  2997. const shutdownResult = await disposeHostResourcesInFlight;
  2998. flushHostE2ECoverage((error) => {
  2999. logger.warn("[e2e-coverage] host coverage flush failed", error);
  3000. });
  3001. return shutdownResult;
  3002. }
  3003. function disposeHostResourcesBestEffort(reason: string): void {
  3004. if (hasDisposedHostResources) {
  3005. return;
  3006. }
  3007. hasDisposedHostResources = true;
  3008. logger.info(`disposing host resources, reason=${reason}`);
  3009. pluginSandboxRegistrationBridge.dispose();
  3010. windowHostExtensions?.dispose();
  3011. windowHostExtensions = null;
  3012. stopHostNetworkTelemetry();
  3013. hostNetworkCapture.setCaptureId(null);
  3014. disposeLocalResourceTelemetry();
  3015. disposeAttachedServicePorts();
  3016. windowHostControllerRuntime.dispose();
  3017. for (const key of Array.from(cronRunSubscriptions.keys())) {
  3018. disposeCronRunSubscription(key);
  3019. }
  3020. cronAutomationRepo.close();
  3021. for (const key of Array.from(offPeakRunSubscriptions.keys())) {
  3022. disposeOffPeakRunSubscription(key);
  3023. }
  3024. disposeOffPeakRuntime();
  3025. offPeakTaskRepo.close();
  3026. void windowRemoteConnectionRegistry.dispose();
  3027. if (activeServices) {
  3028. try {
  3029. disposeServiceResources(activeServices);
  3030. } catch (error) {
  3031. logger.error("failed to dispose local services:", error);
  3032. } finally {
  3033. activeServices = null;
  3034. activeHostApiNetworkTransport = null;
  3035. }
  3036. }
  3037. if (activeSessionRealtimePort) {
  3038. activeSessionRealtimePort.dispose();
  3039. activeSessionRealtimePort = null;
  3040. }
  3041. }
  3042. process.once("SIGTERM", () => {
  3043. credentialCipherBridge.dispose();
  3044. void disposeHostResources("SIGTERM").then(
  3045. (result) => process.exit(result.exitCode),
  3046. () => process.exit(1),
  3047. );
  3048. });
  3049. process.once("SIGINT", () => {
  3050. credentialCipherBridge.dispose();
  3051. void disposeHostResources("SIGINT").then(
  3052. (result) => process.exit(result.exitCode),
  3053. () => process.exit(1),
  3054. );
  3055. });
  3056. process.once("disconnect", () => {
  3057. credentialCipherBridge.dispose();
  3058. // parent IPC 消失后不会再有人发送 Dispose;有界清理结束后必须明确退出,避免 Host 常驻。
  3059. void disposeHostResources("disconnect").finally(() => process.exit(1));
  3060. });
  3061. process.once("exit", () => {
  3062. credentialCipherBridge.dispose();
  3063. disposeHostResourcesBestEffort("exit");
  3064. });
  3065. let handlingFatalUncaughtException = false;
  3066. process.on(
  3067. "uncaughtException",
  3068. createHostUncaughtExceptionHandler({
  3069. onRecovered: (error, origin) => {
  3070. const memoryUsage = process.memoryUsage();
  3071. logger.warn("contained host allocation failure from native TLS callback", {
  3072. arrayBuffers: memoryUsage.arrayBuffers,
  3073. external: memoryUsage.external,
  3074. heapUsed: memoryUsage.heapUsed,
  3075. message: error.message,
  3076. origin,
  3077. rss: memoryUsage.rss,
  3078. });
  3079. },
  3080. onFatal: (error, origin) => {
  3081. if (handlingFatalUncaughtException) {
  3082. process.exit(1);
  3083. }
  3084. handlingFatalUncaughtException = true;
  3085. logger.error(`uncaughtException origin=${origin}:`, error);
  3086. void disposeHostResources(`uncaughtException:${origin}`).finally(() => process.exit(1));
  3087. },
  3088. }),
  3089. );
  3090. parentPort.on("message", async (e: Electron.MessageEvent) => {
  3091. // 私有凭据回复先交给 bridge 校验并结束等待;通用校验丢弃非法回复会遗留文件锁。
  3092. if (e.data?.type === HostMessageTypes.CredentialCipherResult) {
  3093. const { type: _type, ...reply } = e.data;
  3094. credentialCipherBridge.receive(reply);
  3095. return;
  3096. }
  3097. const navigation = appNavigationResultMessageSchema.safeParse(e.data);
  3098. if (navigation.success) {
  3099. appControlNavigation.receive(navigation.data);
  3100. return;
  3101. }
  3102. // 扩展进程的 L0 控制消息(牵线、状态)走独立 schema,不进入 Host 消息联合类型。
  3103. const extensionControl = mainToExtensionWindowMessageSchema.safeParse(e.data);
  3104. if (extensionControl.success) {
  3105. const extensionPort = e.ports[0];
  3106. windowHostExtensions?.receiveControl(
  3107. extensionControl.data,
  3108. extensionPort
  3109. ? {
  3110. port: wrapElectronPort(extensionPort),
  3111. onClose: (listener) => extensionPort.once("close", listener),
  3112. }
  3113. : undefined,
  3114. );
  3115. return;
  3116. }
  3117. const result = parseHostIncomingMessageEvent(e);
  3118. if (!result.success) {
  3119. logger.error("invalid parentPort message:", formatZodError(result.error));
  3120. return;
  3121. }
  3122. const msg = result.data;
  3123. // 在任何 await 之前同步赋值:InitLocal 与变更消息同端口按序到达,初值不会覆盖较新的变更。
  3124. if (msg.type === HostMessageTypes.InitLocal && msg.locale) {
  3125. applicationLocale = msg.locale;
  3126. }
  3127. if (msg.type === HostMessageTypes.InitLocal) {
  3128. replyLanguage = msg.replyLanguage ?? null;
  3129. }
  3130. if (msg.type === HostMessageTypes.ReplyLanguageChanged) {
  3131. replyLanguage = msg.replyLanguage;
  3132. return;
  3133. }
  3134. if (msg.type === HostMessageTypes.ApplicationLocaleChanged) {
  3135. applicationLocale = msg.locale;
  3136. return;
  3137. }
  3138. if (msg.type === HostMessageTypes.NetworkCapture) {
  3139. hostNetworkCapture.setCaptureId(msg.control.captureId);
  3140. return;
  3141. }
  3142. const port = e.ports[0];
  3143. if (msg.type === HostMessageTypes.DatabaseStartupControl) {
  3144. if (msg.control.action === "snapshot") databaseStartup?.coordinator.publish();
  3145. else if (msg.control.action === "retry")
  3146. void databaseStartup?.coordinator.retry(msg.control.attemptId);
  3147. return;
  3148. }
  3149. if (msg.type === HostMessageTypes.PrepareProjectWorkspace) {
  3150. const controller = new AbortController();
  3151. if (projectNavigationAbortControllers.has(msg.requestId)) {
  3152. parentPort.postMessage({
  3153. type: HostResponseTypes.ProjectWorkspacePrepared,
  3154. requestId: msg.requestId,
  3155. result: { ok: false, error: "项目导航 requestId 重复" },
  3156. });
  3157. return;
  3158. }
  3159. projectNavigationAbortControllers.set(msg.requestId, controller);
  3160. try {
  3161. const services = activeServices;
  3162. if (!services || hasDisposedHostResources) throw new Error("Window Host is unavailable");
  3163. const assertHost = () => {
  3164. controller.signal.throwIfAborted();
  3165. if (activeServices !== services || hasDisposedHostResources)
  3166. throw new Error("Window Host changed during project navigation");
  3167. };
  3168. const navigation = createProjectWorkspaceNavigation({
  3169. projectService: services.get(IProjectService),
  3170. remoteProjectService: services.get(IRemoteProjectService),
  3171. readConnectionOwner: (hostId) => resolveBotProjectConnection(hostId)?.owner,
  3172. openRemoteWorkspace: async ({ host, directories, owner, assertCurrent }) => {
  3173. assertHost();
  3174. const serverId = parseRemoteWorkspaceIdentity(
  3175. buildRemoteHostWorkspaceIdentity(host.id, directories.workspacePath),
  3176. )?.sourceServerId;
  3177. if (!serverId || !host.target) throw new Error("project.host-offline");
  3178. // 对 Manager-only Source 仅登记现有连接的 wrapper;URL Source 必须已经在 Registry 在线。
  3179. const registered = await windowRemoteConnectionRegistry.connectSource({
  3180. target: host.target,
  3181. remoteAssets: {},
  3182. membershipIntent: "retain",
  3183. existingSourceServerId: serverId,
  3184. });
  3185. assertHost();
  3186. if (
  3187. (registered.handle.capabilities?.physicalOwner?.() ?? registered.handle.services) !==
  3188. owner
  3189. )
  3190. throw new Error("project.navigation-stale");
  3191. return windowRemoteConnectionRegistry.openWorkspaceOnSource({
  3192. requestId: msg.requestId,
  3193. sourceServerId: serverId,
  3194. workspacePath: directories.workspacePath,
  3195. workspaceIdentity: directories.workspaceIdentity,
  3196. workspacePurpose: directories.projectId ? "project" : "conversation",
  3197. assertCurrent: async () => {
  3198. assertHost();
  3199. await assertCurrent();
  3200. assertHost();
  3201. },
  3202. });
  3203. },
  3204. });
  3205. const value = await navigation.prepare({
  3206. projectId: msg.projectId,
  3207. hostId: msg.hostId,
  3208. draftId: msg.draftId,
  3209. reuseDraft: msg.reuseDraft,
  3210. ...(msg.task ? { task: msg.task } : {}),
  3211. });
  3212. assertHost();
  3213. parentPort.postMessage({
  3214. type: HostResponseTypes.ProjectWorkspacePrepared,
  3215. requestId: msg.requestId,
  3216. result: { ok: true, value },
  3217. });
  3218. } catch (error) {
  3219. parentPort.postMessage({
  3220. type: HostResponseTypes.ProjectWorkspacePrepared,
  3221. requestId: msg.requestId,
  3222. result: { ok: false, error: error instanceof Error ? error.message : String(error) },
  3223. });
  3224. } finally {
  3225. if (projectNavigationAbortControllers.get(msg.requestId) === controller)
  3226. projectNavigationAbortControllers.delete(msg.requestId);
  3227. }
  3228. return;
  3229. }
  3230. if (msg.type === HostMessageTypes.CuaPipFocusChanged) {
  3231. const service = activeServices?.getOptional(ICuaPipSessionService);
  3232. if (service) {
  3233. void service.publishFocus(msg.event);
  3234. } else {
  3235. // 取不到服务时过去静默丢弃,focus-changed 于是从链路上凭空消失
  3236. // (dev 实测 0 条,正式包同期 92 条)。补这条才能把「main 没发」与
  3237. // 「host 收到了但服务没注册」分开。
  3238. logger.warn("[cua-pip-session] focus event dropped: service unavailable");
  3239. }
  3240. return;
  3241. }
  3242. if (msg.type === HostMessageTypes.ResourceUsageSnapshotRequest) {
  3243. void hostResourceUsageResponder.handleRequest(msg);
  3244. return;
  3245. }
  3246. if (msg.type === HostMessageTypes.ResourceUsageSnapshotCancel) {
  3247. hostResourceUsageResponder.cancelRequest(msg.requestId);
  3248. return;
  3249. }
  3250. if (msg.type === HostMessageTypes.ProviderProvisioningLaneResult) {
  3251. hostProviderProvisioningStatus.handleResult(msg);
  3252. return;
  3253. }
  3254. if (msg.type === HostMessageTypes.FeedbackLogArchiveResult) {
  3255. const pending = pendingFeedbackLogArchiveRequests.get(msg.requestId);
  3256. if (!pending) {
  3257. return;
  3258. }
  3259. pendingFeedbackLogArchiveRequests.delete(msg.requestId);
  3260. if (msg.ok && msg.path && typeof msg.size === "number") {
  3261. pending.onProgress?.({ processedBytes: msg.size, totalBytes: msg.size });
  3262. pending.resolve({ path: msg.path, size: msg.size });
  3263. return;
  3264. }
  3265. pending.reject(new Error(msg.error ?? "反馈日志归档创建失败"));
  3266. return;
  3267. }
  3268. if (msg.type === HostMessageTypes.CredentialKeyShareResult) {
  3269. const pending = pendingCredentialKeyShares.get(msg.requestId);
  3270. if (!pending) {
  3271. return;
  3272. }
  3273. pendingCredentialKeyShares.delete(msg.requestId);
  3274. if (msg.ok) {
  3275. pending.resolve();
  3276. return;
  3277. }
  3278. pending.reject(
  3279. Object.assign(new Error("System credential storage is unavailable"), {
  3280. code: msg.errorCode ?? CREDENTIAL_KEY_SHARE_UNAVAILABLE_ERROR_CODE,
  3281. }),
  3282. );
  3283. return;
  3284. }
  3285. if (msg.type === HostMessageTypes.LocalMediaPreviewPathAuthorizeResult) {
  3286. const pending = pendingLocalMediaPreviewPathAuthorizations.get(msg.requestId);
  3287. if (!pending) return;
  3288. pendingLocalMediaPreviewPathAuthorizations.delete(msg.requestId);
  3289. if (msg.ok && msg.path) {
  3290. logger.info("local media preview path authorization OK");
  3291. pending.resolve(msg.path);
  3292. } else {
  3293. pending.reject(new Error(msg.error ?? "本地视频预览路径授权失败"));
  3294. }
  3295. return;
  3296. }
  3297. if (msg.type === HostMessageTypes.PluginSandboxRegisterResult) {
  3298. pluginSandboxRegistrationBridge.accept(msg);
  3299. return;
  3300. }
  3301. if (msg.type === HostMessageTypes.CronRun) {
  3302. if (databaseStartup?.coordinator.snapshot.phase !== "ready") {
  3303. parentPort.postMessage({
  3304. type: HostResponseTypes.CronRunResult,
  3305. runId: msg.runId,
  3306. ok: false,
  3307. error: "Local database startup is not ready",
  3308. failureKind: "transient",
  3309. });
  3310. return;
  3311. }
  3312. void (async () => {
  3313. try {
  3314. const dispatchResult = await dispatchCronRun({
  3315. ...msg,
  3316. mode: msg.mode as ZCodeTaskMode | undefined,
  3317. });
  3318. parentPort.postMessage({
  3319. type: HostResponseTypes.CronRunResult,
  3320. runId: msg.runId,
  3321. ok: true,
  3322. ...dispatchResult,
  3323. });
  3324. } catch (error) {
  3325. parentPort.postMessage({
  3326. type: HostResponseTypes.CronRunResult,
  3327. runId: msg.runId,
  3328. ok: false,
  3329. error: error instanceof Error ? error.message : String(error),
  3330. failureKind: "transient",
  3331. });
  3332. }
  3333. })();
  3334. return;
  3335. }
  3336. if (msg.type === HostMessageTypes.OffPeakRun) {
  3337. if (databaseStartup?.coordinator.snapshot.phase !== "ready") {
  3338. parentPort.postMessage({
  3339. type: HostResponseTypes.OffPeakRunResult,
  3340. offPeakTaskId: msg.offPeakTaskId,
  3341. ok: false,
  3342. error: "Local database startup is not ready",
  3343. failureKind: "transient",
  3344. });
  3345. return;
  3346. }
  3347. void (async () => {
  3348. try {
  3349. const dispatchResult = await dispatchOffPeakRun(msg);
  3350. parentPort.postMessage({
  3351. type: HostResponseTypes.OffPeakRunResult,
  3352. offPeakTaskId: msg.offPeakTaskId,
  3353. ok: true,
  3354. ...dispatchResult,
  3355. });
  3356. } catch (error) {
  3357. parentPort.postMessage({
  3358. type: HostResponseTypes.OffPeakRunResult,
  3359. offPeakTaskId: msg.offPeakTaskId,
  3360. ok: false,
  3361. error: error instanceof Error ? error.message : String(error),
  3362. // 确定性模型/凭证配置错误重试不会自愈;交给 scheduler 转 failed,
  3363. // 未知及生命周期错误仍按 transient 保持原退避语义。
  3364. failureKind: error instanceof OffPeakPermanentDispatchError ? "permanent" : "transient",
  3365. });
  3366. }
  3367. })();
  3368. return;
  3369. }
  3370. if (msg.type === HostMessageTypes.BrowserExecuteResult) {
  3371. // main 的 WebContentsView+CDP 执行完 browser 命令,按 requestId 关联回 bridge 的 pending。
  3372. void browserControlMainBridge.handleResult({
  3373. requestId: msg.requestId,
  3374. result: msg.result,
  3375. });
  3376. return;
  3377. }
  3378. if (msg.type === HostMessageTypes.Dispose) {
  3379. credentialCipherBridge.dispose();
  3380. // main 进程通知清理(窗口关闭 / app 退出时)
  3381. // 这里必须等待统一资源清理完成(含异步收尾写回),再让进程退出;main 侧仍有强杀 timer 兜底。
  3382. const result = await disposeHostResources("parent dispose");
  3383. process.exit(result.exitCode);
  3384. return;
  3385. }
  3386. if (msg.type === HostMessageTypes.Broadcast) {
  3387. return;
  3388. }
  3389. if (msg.type === HostMessageTypes.SessionMessageDeliver) {
  3390. const zcodeTaskService = activeServices?.getOptional(IZCodeTaskService);
  3391. if (!zcodeTaskService) {
  3392. parentPort.postMessage({
  3393. type: HostResponseTypes.SessionMessageDeliverResult,
  3394. result: {
  3395. error: "ZCode task service is not initialized.",
  3396. messageId: msg.request.messageId,
  3397. requestId: msg.request.requestId,
  3398. sessionId: msg.request.fromSessionId,
  3399. status: "failed",
  3400. },
  3401. });
  3402. return;
  3403. }
  3404. void zcodeTaskService
  3405. .deliverSessionMessage(msg.request)
  3406. .then((deliveryResult) => {
  3407. parentPort.postMessage({
  3408. type: HostResponseTypes.SessionMessageDeliverResult,
  3409. result: deliveryResult,
  3410. });
  3411. })
  3412. .catch((error) => {
  3413. parentPort.postMessage({
  3414. type: HostResponseTypes.SessionMessageDeliverResult,
  3415. result: {
  3416. error: error instanceof Error ? error.message : String(error),
  3417. messageId: msg.request.messageId,
  3418. requestId: msg.request.requestId,
  3419. sessionId: msg.request.fromSessionId,
  3420. status: "failed",
  3421. },
  3422. });
  3423. });
  3424. return;
  3425. }
  3426. if (msg.type === HostMessageTypes.SessionMessageDeliveryResult) {
  3427. const zcodeTaskService = activeServices?.getOptional(IZCodeTaskService);
  3428. if (!zcodeTaskService) {
  3429. logger.warn("session message delivery result received before ZCode task service initialized");
  3430. return;
  3431. }
  3432. void zcodeTaskService.sendSessionMessageDeliveryResult(msg.result).catch((error) => {
  3433. logger.warn("failed to forward session message delivery result:", error);
  3434. });
  3435. return;
  3436. }
  3437. if (msg.type === HostMessageTypes.ProviderProvisioningExecute) {
  3438. const session = windowRemoteConnectionRegistry.getSession(msg.remoteSessionId);
  3439. if (
  3440. !session ||
  3441. !session.workspaceIdentity ||
  3442. buildRemoteEnvironmentKey(session.target) !== msg.environmentKey
  3443. ) {
  3444. parentPort.postMessage({
  3445. type: HostResponseTypes.ProviderProvisioningExecutionResult,
  3446. requestId: msg.requestId,
  3447. environmentKey: msg.environmentKey,
  3448. status: "failed",
  3449. error: "Remote Environment registration 已失效",
  3450. errorCode: "session-unavailable",
  3451. });
  3452. return;
  3453. }
  3454. const scope = {
  3455. kind: "remote",
  3456. remoteSessionId: session.remoteSessionId,
  3457. workspacePath: session.workspacePath ?? "/",
  3458. workspaceIdentity: session.workspaceIdentity,
  3459. } as const;
  3460. void Promise.resolve()
  3461. .then(() =>
  3462. (() => {
  3463. const provisioningService = getRemoteProviderProvisioningExecutor(
  3464. windowRemoteConnectionRegistry.resolveScopedServices(scope),
  3465. );
  3466. if (!provisioningService) {
  3467. throw new Error("Remote Environment 不支持 Provider Provisioning");
  3468. }
  3469. return provisioningService.syncLocalToRemote();
  3470. })(),
  3471. )
  3472. .then((result) => {
  3473. parentPort.postMessage({
  3474. type: HostResponseTypes.ProviderProvisioningExecutionResult,
  3475. requestId: msg.requestId,
  3476. environmentKey: msg.environmentKey,
  3477. status: result.status,
  3478. ...(result.errorMessage ? { error: result.errorMessage } : {}),
  3479. ...(result.errorCode ? { errorCode: result.errorCode } : {}),
  3480. });
  3481. })
  3482. .catch((error: unknown) => {
  3483. parentPort.postMessage({
  3484. type: HostResponseTypes.ProviderProvisioningExecutionResult,
  3485. requestId: msg.requestId,
  3486. environmentKey: msg.environmentKey,
  3487. status: "failed",
  3488. error: error instanceof Error ? error.message : String(error),
  3489. errorCode: "host-execution-failed",
  3490. });
  3491. });
  3492. return;
  3493. }
  3494. if (msg.type === HostMessageTypes.ConnectRemoteWorkspace) {
  3495. const workspacePath =
  3496. msg.workspacePath ??
  3497. (msg.target.kind === "server" ? msg.target.workspacePath?.trim() || "/" : "/");
  3498. const workspaceIdentity =
  3499. msg.workspaceIdentity ?? buildRemoteWorkspaceIdentity(workspacePath, msg.target);
  3500. logger.info(
  3501. `connecting window-scoped remote source, requestId=${msg.requestId}, target=${formatRemoteTargetForLog(msg.target)}`,
  3502. );
  3503. void remoteConnectionProgressContext
  3504. .run(msg.requestId, () =>
  3505. windowRemoteConnectionRegistry.connect({
  3506. requestId: msg.requestId,
  3507. target: msg.target,
  3508. remoteAssets: msg.remoteAssets,
  3509. workspacePath,
  3510. workspaceIdentity,
  3511. ...(msg.confirmSourceServerInstall ? { confirmSourceServerInstall: true } : {}),
  3512. }),
  3513. )
  3514. .then(async (descriptor) => {
  3515. const replacedOfflineSessions = windowRemoteConnectionRegistry
  3516. .listSessions()
  3517. .filter(
  3518. (session) =>
  3519. session.remoteSessionId !== descriptor.remoteSessionId &&
  3520. session.state === "disconnected" &&
  3521. session.workspacePath === descriptor.workspacePath &&
  3522. session.workspaceIdentity === descriptor.workspaceIdentity,
  3523. );
  3524. for (const replaced of replacedOfflineSessions) {
  3525. if (replaced.workspacePath && replaced.workspaceIdentity) {
  3526. const previousScope = {
  3527. kind: "remote",
  3528. ...(replaced.sourceServerId ? { sourceServerId: replaced.sourceServerId } : {}),
  3529. remoteSessionId: replaced.remoteSessionId,
  3530. workspacePath: replaced.workspacePath,
  3531. workspaceIdentity: replaced.workspaceIdentity,
  3532. } as const;
  3533. const nextScope = {
  3534. kind: "remote",
  3535. ...(descriptor.sourceServerId ? { sourceServerId: descriptor.sourceServerId } : {}),
  3536. remoteSessionId: descriptor.remoteSessionId,
  3537. workspacePath: replaced.workspacePath,
  3538. workspaceIdentity: replaced.workspaceIdentity,
  3539. } as const;
  3540. try {
  3541. const services = windowRemoteConnectionRegistry.resolveScopedServices(nextScope);
  3542. await windowHostControllerRuntime.replaceDisconnectedSource(previousScope, {
  3543. scope: nextScope,
  3544. taskService: services.get(IZCodeTaskService),
  3545. sourceAvailability: "online",
  3546. });
  3547. } catch (error) {
  3548. // source 已连接但 task-index 暂时不可读时不能回滚 transport,也不能删除上一代
  3549. // 离线可信投影。Controller 会保留 pending replacement,后续 query 成功后原子替换。
  3550. logger.warn("failed to atomically replace disconnected Controller source", error);
  3551. }
  3552. }
  3553. windowHostAttachmentRegistry.detachRemoteSessionAttachments(replaced.remoteSessionId);
  3554. await windowRemoteConnectionRegistry.disposeSession(replaced.remoteSessionId);
  3555. // 重连替换后旧 remoteSessionId 已不再可 attachment;同步清理 Main 的端口请求关联,
  3556. // 但不向 Renderer 伪报一次新的 transport failure。
  3557. parentPort.postMessage({
  3558. type: HostResponseTypes.RemoteWorkspaceClosed,
  3559. remoteSessionId: replaced.remoteSessionId,
  3560. reason: "disposed",
  3561. });
  3562. }
  3563. parentPort.postMessage({
  3564. type: HostResponseTypes.RemoteWorkspaceConnected,
  3565. requestId: msg.requestId,
  3566. descriptor,
  3567. });
  3568. logWindowHostTopology("remote-connected");
  3569. })
  3570. .catch((error) => {
  3571. const failure = normalizeRemoteConnectionError(error);
  3572. parentPort.postMessage({
  3573. type: HostResponseTypes.RemoteWorkspaceConnectFailed,
  3574. requestId: msg.requestId,
  3575. error: sanitizeRemoteConnectionLog(failure.message) || "Remote connection failed",
  3576. reasonCode: failure.code,
  3577. ...(error instanceof SourceServerUpgradeRequiredError ||
  3578. error instanceof SourceServerInstallRequiredError
  3579. ? { profileId: error.profileId }
  3580. : {}),
  3581. // 安装和升级等待固定 Main 解析后的 WSL 身份,不能从可编辑 Profile 重建。
  3582. // 身份来自同一请求,独立于附加安装预览;只回传 WSL 的非敏感连接参数。
  3583. ...((error instanceof SourceServerInstallRequiredError ||
  3584. error instanceof SourceServerUpgradeRequiredError) &&
  3585. msg.target.kind === "wsl"
  3586. ? { resolvedWslTarget: msg.target }
  3587. : {}),
  3588. ...(failure.retryable === undefined ? {} : { retryable: failure.retryable }),
  3589. });
  3590. });
  3591. return;
  3592. }
  3593. if (msg.type === HostMessageTypes.CancelRemoteWorkspaceConnect) {
  3594. projectNavigationAbortControllers.get(msg.requestId)?.abort();
  3595. windowRemoteConnectionRegistry.cancelConnect(msg.requestId);
  3596. return;
  3597. }
  3598. if (msg.type === HostMessageTypes.CancelRemoteWorkspaceBind) {
  3599. cancelledWorkspaceBindRequestIds.add(msg.requestId);
  3600. workspaceBindAbortControllers.get(msg.requestId)?.abort();
  3601. // Bug 原因:bind 可能 join 到已有 Source logical session;取消一个选择目录请求不代表
  3602. // 该 session 的其他 attachment/owner 都已释放。这里只取消 request,不再连坐 dispose。
  3603. if (!activeWorkspaceBindRequestIds.has(msg.requestId)) {
  3604. parentPort.postMessage({
  3605. type: HostResponseTypes.RemoteWorkspaceContextBindFailed,
  3606. requestId: msg.requestId,
  3607. error: "Remote workspace bind was canceled",
  3608. reasonCode: REMOTE_BIND_CANCELED_ERROR_CODE,
  3609. retryable: false,
  3610. });
  3611. cancelledWorkspaceBindRequestIds.delete(msg.requestId);
  3612. workspaceBindAbortControllers.delete(msg.requestId);
  3613. }
  3614. return;
  3615. }
  3616. if (msg.type === HostMessageTypes.BindRemoteWorkspaceContext) {
  3617. activeWorkspaceBindRequestIds.add(msg.requestId);
  3618. const bindAbortController = new AbortController();
  3619. workspaceBindAbortControllers.set(msg.requestId, bindAbortController);
  3620. if (cancelledWorkspaceBindRequestIds.has(msg.requestId)) {
  3621. bindAbortController.abort();
  3622. parentPort.postMessage({
  3623. type: HostResponseTypes.RemoteWorkspaceContextBindFailed,
  3624. requestId: msg.requestId,
  3625. error: "Remote workspace bind was canceled",
  3626. reasonCode: REMOTE_BIND_CANCELED_ERROR_CODE,
  3627. retryable: false,
  3628. });
  3629. activeWorkspaceBindRequestIds.delete(msg.requestId);
  3630. cancelledWorkspaceBindRequestIds.delete(msg.requestId);
  3631. workspaceBindAbortControllers.delete(msg.requestId);
  3632. return;
  3633. }
  3634. const previous = windowRemoteConnectionRegistry.getSession(msg.remoteSessionId);
  3635. let workspaceReady: Promise<void>;
  3636. try {
  3637. workspaceReady = windowRemoteConnectionRegistry.bindWorkspaceContext({
  3638. remoteSessionId: msg.remoteSessionId,
  3639. workspacePath: msg.workspacePath,
  3640. workspaceIdentity: msg.workspaceIdentity,
  3641. ...(msg.workspacePurpose ? { workspacePurpose: msg.workspacePurpose } : {}),
  3642. ...(msg.legacyRouteHint ? { legacyWorkspaceIdentity: msg.legacyRouteHint } : {}),
  3643. signal: bindAbortController.signal,
  3644. });
  3645. } catch (error) {
  3646. logger.warn(
  3647. `failed to bind remote workspace context, remoteSessionId=${msg.remoteSessionId}`,
  3648. error,
  3649. );
  3650. parentPort.postMessage({
  3651. type: HostResponseTypes.RemoteWorkspaceContextBindFailed,
  3652. requestId: msg.requestId,
  3653. error: error instanceof Error ? error.message : String(error),
  3654. ...(error && typeof error === "object" && "code" in error && typeof error.code === "string"
  3655. ? { reasonCode: error.code }
  3656. : {}),
  3657. ...(error &&
  3658. typeof error === "object" &&
  3659. "retryable" in error &&
  3660. typeof error.retryable === "boolean"
  3661. ? { retryable: error.retryable }
  3662. : {}),
  3663. });
  3664. activeWorkspaceBindRequestIds.delete(msg.requestId);
  3665. cancelledWorkspaceBindRequestIds.delete(msg.requestId);
  3666. workspaceBindAbortControllers.delete(msg.requestId);
  3667. return;
  3668. }
  3669. const current = windowRemoteConnectionRegistry.getSession(msg.remoteSessionId);
  3670. if (current) {
  3671. // scope generation 换代后,旧 Renderer/手机 attachment 不得继续持有远端 IO facade。
  3672. windowHostAttachmentRegistry.detachStaleRemoteSessionAttachments(
  3673. msg.remoteSessionId,
  3674. current.generation,
  3675. );
  3676. }
  3677. void workspaceReady
  3678. .then(async () => {
  3679. if (cancelledWorkspaceBindRequestIds.has(msg.requestId)) {
  3680. throw Object.assign(new Error("Remote workspace bind was canceled"), {
  3681. code: REMOTE_BIND_CANCELED_ERROR_CODE,
  3682. retryable: false,
  3683. });
  3684. }
  3685. const currentSession = windowRemoteConnectionRegistry.getSession(msg.remoteSessionId);
  3686. if (!currentSession?.workspaceIdentity) {
  3687. // Bug 原因:bind 完成前 logical session 可能被并发释放;旧实现直接 return,Main
  3688. // 永远收不到 ACK。抛入统一失败链,确保每个 requestId 恰好 settle 一次。
  3689. throw Object.assign(
  3690. new Error(`远程 workspace bind 完成时 session 已失效: ${msg.remoteSessionId}`),
  3691. {
  3692. code: REMOTE_WORKSPACE_BIND_SESSION_MISSING_ERROR_CODE,
  3693. retryable: true,
  3694. },
  3695. );
  3696. }
  3697. const scope = {
  3698. kind: "remote" as const,
  3699. ...(currentSession.sourceServerId
  3700. ? { sourceServerId: currentSession.sourceServerId }
  3701. : {}),
  3702. remoteSessionId: msg.remoteSessionId,
  3703. workspacePath: msg.workspacePath,
  3704. workspaceIdentity: currentSession.workspaceIdentity,
  3705. };
  3706. await windowRemoteConnectionRegistry
  3707. .resolveScopedCapabilities(scope)
  3708. ?.recordWorkspaceOpen?.({
  3709. workspacePath: msg.workspacePath,
  3710. workspaceIdentity: currentSession.workspaceIdentity,
  3711. ...(msg.workspacePurpose ? { workspacePurpose: msg.workspacePurpose } : {}),
  3712. ...(msg.legacyRouteHint ? { legacyWorkspaceIdentity: msg.legacyRouteHint } : {}),
  3713. signal: bindAbortController.signal,
  3714. });
  3715. if (cancelledWorkspaceBindRequestIds.has(msg.requestId)) {
  3716. throw Object.assign(new Error("Remote workspace bind was canceled"), {
  3717. code: REMOTE_BIND_CANCELED_ERROR_CODE,
  3718. retryable: false,
  3719. });
  3720. }
  3721. if (previous?.workspacePath && previous.workspaceIdentity) {
  3722. windowHostControllerRuntime.removeSource({
  3723. kind: "remote",
  3724. ...(previous.sourceServerId ? { sourceServerId: previous.sourceServerId } : {}),
  3725. remoteSessionId: msg.remoteSessionId,
  3726. workspacePath: previous.workspacePath,
  3727. workspaceIdentity: previous.workspaceIdentity,
  3728. });
  3729. }
  3730. parentPort.postMessage({
  3731. type: HostResponseTypes.RemoteWorkspaceContextBound,
  3732. requestId: msg.requestId,
  3733. // Bug 原因:首次从旧 route tab 打开 Source workspace 时,Renderer 只拿到 stable
  3734. // identity 会误认为没有旧 tab,随后 addTab 产生第二个 workspace。把本次 bind
  3735. // 使用的旧 route 作为一次性 tab rekey 提示返回;它不是任务路由身份,手机端忽略。
  3736. ...(msg.legacyRouteHint && msg.legacyRouteHint !== currentSession.workspaceIdentity
  3737. ? { previousWorkspaceIdentity: msg.legacyRouteHint }
  3738. : {}),
  3739. });
  3740. logger.info(
  3741. `bound remote workspace context, remoteSessionId=${msg.remoteSessionId}, workspacePath=${msg.workspacePath}`,
  3742. );
  3743. activeWorkspaceBindRequestIds.delete(msg.requestId);
  3744. cancelledWorkspaceBindRequestIds.delete(msg.requestId);
  3745. workspaceBindAbortControllers.delete(msg.requestId);
  3746. })
  3747. .catch((error) => {
  3748. logger.warn(
  3749. `failed to prepare bound remote workspace, remoteSessionId=${msg.remoteSessionId}`,
  3750. error,
  3751. );
  3752. const normalizedError = cancelledWorkspaceBindRequestIds.has(msg.requestId)
  3753. ? Object.assign(new Error("Remote workspace bind was canceled"), {
  3754. code: REMOTE_BIND_CANCELED_ERROR_CODE,
  3755. retryable: false,
  3756. })
  3757. : error;
  3758. parentPort.postMessage({
  3759. type: HostResponseTypes.RemoteWorkspaceContextBindFailed,
  3760. requestId: msg.requestId,
  3761. error:
  3762. normalizedError instanceof Error ? normalizedError.message : String(normalizedError),
  3763. ...(normalizedError &&
  3764. typeof normalizedError === "object" &&
  3765. "code" in normalizedError &&
  3766. typeof normalizedError.code === "string"
  3767. ? { reasonCode: normalizedError.code }
  3768. : {}),
  3769. ...(normalizedError &&
  3770. typeof normalizedError === "object" &&
  3771. "retryable" in normalizedError &&
  3772. typeof normalizedError.retryable === "boolean"
  3773. ? { retryable: normalizedError.retryable }
  3774. : {}),
  3775. });
  3776. activeWorkspaceBindRequestIds.delete(msg.requestId);
  3777. cancelledWorkspaceBindRequestIds.delete(msg.requestId);
  3778. workspaceBindAbortControllers.delete(msg.requestId);
  3779. });
  3780. return;
  3781. }
  3782. if (msg.type === HostMessageTypes.DisposeRemoteWorkspaceSession) {
  3783. const disposedSession = windowRemoteConnectionRegistry.getSession(msg.remoteSessionId);
  3784. windowHostAttachmentRegistry.detachRemoteSessionAttachments(msg.remoteSessionId);
  3785. void windowRemoteConnectionRegistry
  3786. .disposeSession(msg.remoteSessionId)
  3787. .then(() => {
  3788. if (disposedSession?.workspacePath && disposedSession.workspaceIdentity) {
  3789. windowHostControllerRuntime.removeSource({
  3790. kind: "remote",
  3791. ...(disposedSession.sourceServerId
  3792. ? { sourceServerId: disposedSession.sourceServerId }
  3793. : {}),
  3794. remoteSessionId: msg.remoteSessionId,
  3795. workspacePath: disposedSession.workspacePath,
  3796. workspaceIdentity: disposedSession.workspaceIdentity,
  3797. });
  3798. }
  3799. parentPort.postMessage({
  3800. type: HostResponseTypes.RemoteWorkspaceClosed,
  3801. remoteSessionId: msg.remoteSessionId,
  3802. reason: "disposed",
  3803. });
  3804. logWindowHostTopology("remote-session-disposed");
  3805. })
  3806. .catch((error) => {
  3807. logger.warn(
  3808. `failed to dispose remote logical session, remoteSessionId=${msg.remoteSessionId}`,
  3809. error,
  3810. );
  3811. });
  3812. return;
  3813. }
  3814. if (msg.type === HostMessageTypes.SetTerminalOwner) {
  3815. terminalOwners.setOwner(msg.ownerId);
  3816. return;
  3817. }
  3818. if (msg.type === HostMessageTypes.AttachServicePort) {
  3819. if (!port) {
  3820. logger.error("attach-service-port message missing MessagePort");
  3821. return;
  3822. }
  3823. if (msg.scope.kind === "local" && databaseStartup?.coordinator.snapshot.phase !== "ready") {
  3824. // 刷新/手机 attachment 复用同一 Host,等待现有准备,不启动第二个执行者。
  3825. pendingStartupAttachments.set(msg.attachmentId, () => {
  3826. windowHostAttachmentRegistry.attach({ ...msg, port });
  3827. });
  3828. port.once("close", () => pendingStartupAttachments.delete(msg.attachmentId));
  3829. return;
  3830. }
  3831. try {
  3832. if (msg.clientMode === "web-remote-replayable" && msg.scope.kind === "source-settings") {
  3833. throw new Error("Source settings attachments are Desktop-only");
  3834. }
  3835. if (msg.scope.kind === "remote") {
  3836. // Bind 与 Attach 共用 parentPort,但 WSL 上一代 workspace release 可能仍在途。
  3837. // 持有已转移 port 等待 Host 内 generation barrier,避免新 attachment 踩过旧 runtime 清理。
  3838. await windowRemoteConnectionRegistry.waitForScopedServices(msg.scope);
  3839. }
  3840. windowHostAttachmentRegistry.attach({
  3841. requestId: msg.requestId,
  3842. attachmentId: msg.attachmentId,
  3843. clientMode: msg.clientMode,
  3844. terminalOwnerId: msg.terminalOwnerId,
  3845. scope: msg.scope,
  3846. port,
  3847. });
  3848. logger.info(
  3849. `attached scoped service port, attachmentId=${msg.attachmentId}, scope=${msg.scope.kind}, clientMode=${msg.clientMode}`,
  3850. );
  3851. logWindowHostTopology("attachment-added");
  3852. } catch (error) {
  3853. // 跨 logical session 或旧 identity 的 port 若继续暴露,会把远端请求路由到错误 source。
  3854. // scope 校验失败必须关闭已转移端口并明确记录,禁止回退 active local services。
  3855. rejectUnavailableAttachedServicePort(port, false);
  3856. logger.warn(`failed to attach scoped service port, attachmentId=${msg.attachmentId}`, error);
  3857. }
  3858. return;
  3859. }
  3860. if (msg.type === HostMessageTypes.DetachServicePort) {
  3861. pendingStartupAttachments.delete(msg.attachmentId);
  3862. windowHostAttachmentRegistry.detach(msg.attachmentId);
  3863. logger.info(`detached service port, attachmentId=${msg.attachmentId}`);
  3864. logWindowHostTopology("attachment-removed");
  3865. return;
  3866. }
  3867. if (!port) {
  3868. return;
  3869. }
  3870. if (msg.type === HostMessageTypes.InitLocal) {
  3871. browserBackendIdentity = msg.browserBackendIdentity;
  3872. if (!port) {
  3873. logger.error("init-local message missing MessagePort");
  3874. return;
  3875. }
  3876. if (databaseStartup) {
  3877. port.close();
  3878. databaseStartup.coordinator.publish();
  3879. return;
  3880. }
  3881. let basePortClosed = false;
  3882. port.once("close", () => {
  3883. basePortClosed = true;
  3884. });
  3885. databaseStartup = createHostDatabaseStartup({
  3886. startupId: msg.databaseStartupId,
  3887. cwd: msg.agentSpawnFallbackCwd ?? process.cwd(),
  3888. workingDirectories:
  3889. msg.agentWarmupTargets?.map((target) => target.workspacePath) ??
  3890. (msg.workspacePath ? [msg.workspacePath] : []),
  3891. env: msg.runtimeProcessEnvPatch,
  3892. publish: (state) => {
  3893. parentPort?.postMessage({ type: HostResponseTypes.DatabaseStartupState, state });
  3894. if (state.phase === "ready") {
  3895. for (const attach of pendingStartupAttachments.values()) {
  3896. try {
  3897. attach();
  3898. } catch (error) {
  3899. logger.warn("startup attachment failed", error);
  3900. }
  3901. }
  3902. pendingStartupAttachments.clear();
  3903. }
  3904. },
  3905. onFailure: (error) =>
  3906. logger.error(
  3907. `local database startup failed attempt=${databaseStartup?.coordinator.snapshot.attemptId}`,
  3908. error,
  3909. ),
  3910. initializeServices: async () => {
  3911. logger.info("initializing local services");
  3912. activeSessionRealtimePort = createTaskRealtimeBridgeForHostInit(msg, parentPort);
  3913. // 旧 Team 补组织必须与网络代理读取共用同一个 Setting 实例及写队列。
  3914. // 只注入 service 会跳过默认装配分支,导致缺组织的升级用户永远无法恢复连接。
  3915. const {
  3916. service: settingService,
  3917. prepareLegacyAccountConnections,
  3918. setWorkspaceProjection,
  3919. } = createSettingServiceWithMigrations({ shareCredentialKeyWithDataRoot });
  3920. // 不阻塞启动:读到持久化语言后作为 X-Client-Language 的兜底。
  3921. void settingService.get().then(
  3922. (settings) => {
  3923. persistedApplicationLocale = settings.locale;
  3924. },
  3925. () => {},
  3926. );
  3927. const hostApiNetworkTransport = createHostApiNetworkTransport(async () => {
  3928. const settings = await settingService.get();
  3929. return {
  3930. httpProxy: settings.httpProxy,
  3931. noProxy: settings.httpProxyNoProxy,
  3932. caCertPath: settings.httpProxyCaCertPath,
  3933. };
  3934. });
  3935. // createLocalServices 交出的会话控制 facade:只交给扩展网关(docs/plugins/extension-host.md §17.2),
  3936. // 不注册进 ServiceCollection,不在任何 RPC 频道上。
  3937. let appControlForExtensions: AppControlServiceHandle | undefined;
  3938. const services = await initializeHostApiNetworkTransportOwner({
  3939. transport: hostApiNetworkTransport,
  3940. log: (message, details) => logger.warn(message, details),
  3941. establishOwner: () => {
  3942. const initializedServices = createLocalServices({
  3943. // 固定目录与发布目标无关;准备完成后,既有会话下一条命令即可找到入口。
  3944. preinstalledToolsBinDir: resolvePreinstalledToolsBinDir({
  3945. dataRoot: getZCodeDataRootDir(),
  3946. release: resolvePreinstalledToolsRelease({
  3947. runtimeEnv: resolveZCodeRuntimeEnv(process.env),
  3948. productFlavor: ZCODE_PRODUCT_FLAVOR,
  3949. }),
  3950. }),
  3951. onAppControlServiceCreated: (handle) => {
  3952. appControlForExtensions = handle;
  3953. },
  3954. // 插件管理变更在 Window Host 成功返回后重推扩展进程的插件清单(§3.4),
  3955. // 配置与重置另通知该插件的扩展设置订阅者(§16.7)。
  3956. onPluginManagementMutated: (change) => windowHostExtensions?.refreshInventory(change),
  3957. reportPluginTelemetryEvent: (event) => {
  3958. parentPort?.postMessage({
  3959. type: HostResponseTypes.PluginTelemetry,
  3960. event: {
  3961. ...event,
  3962. context: {
  3963. ...event.context,
  3964. screenResolution: event.context.screenResolution || "unknown",
  3965. },
  3966. },
  3967. });
  3968. },
  3969. resolveBotProjectConnection,
  3970. resolveBotRemoteWorkspace: (workspace) =>
  3971. sourceServerDirectory
  3972. ? resolveBotRemoteWorkspace(workspace, "lookup", {
  3973. directory: sourceServerDirectory,
  3974. listSessions: () => windowRemoteConnectionRegistry.listSessions(),
  3975. })
  3976. : Promise.resolve(null),
  3977. setWorkspaceProjection,
  3978. remoteProjectConnection: {
  3979. connectHost: async (host) => {
  3980. if (host.target?.kind === "server") {
  3981. const connected = await windowRemoteConnectionRegistry.connectSource({
  3982. target: host.target,
  3983. remoteAssets: msg.remoteAssets ?? {},
  3984. membershipIntent: "retain",
  3985. });
  3986. return remoteProjectHostIdForTarget(host.target, connected.sourceServerId);
  3987. }
  3988. if (!sourceServerManagementService)
  3989. throw new Error("remote-project.connector-unavailable");
  3990. const management = sourceServerManagementService;
  3991. const snapshot = await management.getSnapshot();
  3992. // Bug 原因:IPv6 等地址不能构成成员身份,逐条计算 ID 时会抛错,任意一条这样的线路
  3993. // 都会让所有设备的侧栏重连失败。它不拥有成员行,按“不匹配”处理。
  3994. const profiles = snapshot.profiles.filter(
  3995. (profile) =>
  3996. profile.lifecycleState !== "retired" &&
  3997. findRemoteProjectHostIdForProfile(profile) === host.id,
  3998. );
  3999. const preferred = new Set(
  4000. snapshot.servers.map((server) => server.preferredProfileId),
  4001. );
  4002. const profile =
  4003. profiles.find((item) => preferred.has(item.profileId)) ?? profiles[0];
  4004. if (!profile) throw new Error("remote-project.profile-not-found");
  4005. const connected = await management.connectProfile(profile.profileId, {
  4006. retainedOnly: true,
  4007. });
  4008. const resolved = connected.profiles.find(
  4009. (item) => item.profileId === profile.profileId,
  4010. );
  4011. if (
  4012. !resolved ||
  4013. !connected.states.some(
  4014. (state) => state.profileId === resolved.profileId && state.state === "online",
  4015. )
  4016. )
  4017. throw new Error("project.host-offline");
  4018. return remoteProjectHostIdForProfile(resolved);
  4019. },
  4020. readConnectionStates: async () => {
  4021. const result = new Map<
  4022. string,
  4023. Pick<
  4024. RemoteProjectHost,
  4025. | "connectionStatus"
  4026. | "lastConnectionError"
  4027. | "lastConnectionStatus"
  4028. | "upgradeTarget"
  4029. >
  4030. >();
  4031. for (const state of windowRemoteConnectionRegistry.listConnections()) {
  4032. if (state.target.kind !== "server") continue;
  4033. result.set(remoteProjectHostIdForTarget(state.target, state.sourceServerId), {
  4034. connectionStatus:
  4035. state.state === "online"
  4036. ? "online"
  4037. : state.state === "connecting"
  4038. ? "connecting"
  4039. : "offline",
  4040. });
  4041. }
  4042. if (!sourceServerDirectory || !sourceServerConnectionManager) return result;
  4043. const snapshot = await sourceServerDirectory.snapshot();
  4044. for (const state of sourceServerConnectionManager.listStates()) {
  4045. const profile = snapshot.profiles.find(
  4046. (item) => item.profileId === state.profileId,
  4047. );
  4048. if (!profile) continue;
  4049. // Bug 原因:IPv6 等地址的失败线路会留下连接状态,这里曾计算 ID 抛错,整个
  4050. // readDirectory 随之失败。它不拥有成员行,没有可投影的目标。
  4051. const id = findRemoteProjectHostIdForProfile(profile);
  4052. if (!id) continue;
  4053. const value =
  4054. state.state === "online"
  4055. ? "online"
  4056. : ["bootstrapping", "retrying", "updating"].includes(state.state)
  4057. ? "connecting"
  4058. : "offline";
  4059. if (
  4060. result.get(id)?.connectionStatus !== "online" &&
  4061. (result.get(id)?.connectionStatus !== "connecting" || value === "online")
  4062. )
  4063. result.set(id, {
  4064. connectionStatus: value,
  4065. lastConnectionError: state.error,
  4066. lastConnectionStatus: state.state,
  4067. // 修复原因:投影曾丢掉 upgradeTarget,桌面端过旧时详情入口误显示“更新远端”。
  4068. upgradeTarget: state.upgradeTarget,
  4069. });
  4070. }
  4071. return result;
  4072. },
  4073. },
  4074. resolveAppControlDiscoverySource: createAppControlDiscoverySourceResolver({
  4075. registry: windowRemoteConnectionRegistry,
  4076. getSourceServerConnectionManager: () => sourceServerConnectionManager ?? undefined,
  4077. }),
  4078. resolveProjectHostService: async (hostId) => {
  4079. const serverId = parseRemoteWorkspaceIdentity(
  4080. buildRemoteHostWorkspaceIdentity(hostId, "/"),
  4081. )?.sourceServerId;
  4082. const registered = serverId
  4083. ? windowRemoteConnectionRegistry.getOnlineSource(serverId)
  4084. : undefined;
  4085. if (registered && serverId) {
  4086. // Registry handle 跨 Source 重连不换代;必须按物理连接去重,Core 重启后才会重新登记。
  4087. const physicalConnection =
  4088. registered.capabilities?.physicalOwner?.() ?? registered.services;
  4089. return bindRemoteProjectIdentities(
  4090. registered.services.get(IProjectService),
  4091. (workspacePath) =>
  4092. registryProjectIdentityRegistrations(
  4093. physicalConnection,
  4094. workspacePath,
  4095. async () => {
  4096. const workspaceIdentity = buildServerRemoteWorkspaceIdentity({
  4097. serverId,
  4098. workspacePath,
  4099. });
  4100. await registered.capabilities?.bindWorkspaceIdentity?.({
  4101. workspacePath,
  4102. stableWorkspaceIdentity: workspaceIdentity,
  4103. });
  4104. return workspaceIdentity;
  4105. },
  4106. ),
  4107. );
  4108. }
  4109. const source = sourceServerConnectionManager?.listStates().find(
  4110. (state) =>
  4111. state.sourceServerId &&
  4112. remoteHostIdFromWorkspaceIdentity(
  4113. buildServerRemoteWorkspaceIdentity({
  4114. serverId: state.sourceServerId,
  4115. workspacePath: "/",
  4116. }),
  4117. ) === hostId,
  4118. );
  4119. const connection = source?.sourceServerId
  4120. ? sourceServerConnectionManager?.getOnlineConnection(source.sourceServerId)
  4121. : undefined;
  4122. if (!connection || !source?.sourceServerId) throw new Error("project.host-offline");
  4123. const sourceServerId = source.sourceServerId;
  4124. return bindRemoteProjectIdentities(
  4125. resolveServerProjectService({
  4126. connectionServices: connection.services,
  4127. serverId: sourceServerId,
  4128. virtualProjects: connection.serverInfo.capabilities.virtualProjects,
  4129. sourceServices: activeServices ?? undefined,
  4130. }),
  4131. (workspacePath) =>
  4132. managerProjectIdentityRegistrations(
  4133. connection.services,
  4134. workspacePath,
  4135. async () => {
  4136. await connection.services.sourceServerWorkspaceService.resolveWorkspace({
  4137. workspacePath,
  4138. });
  4139. return buildServerRemoteWorkspaceIdentity({
  4140. serverId: sourceServerId,
  4141. workspacePath,
  4142. });
  4143. },
  4144. ),
  4145. );
  4146. },
  4147. parentPort,
  4148. credentialCipherProvider: credentialCipherBridge.cipher,
  4149. settingService,
  4150. prepareLegacyAccountConnections,
  4151. hostApiNetworkTransport,
  4152. resolveClientLanguage: resolveHostClientLanguage,
  4153. resolveReplyLanguage: () => replyLanguage,
  4154. authorizeLocalMediaPreviewPath,
  4155. // launch.md「The user's choice」:本机用户选择变化后,推给本窗口所有在线的远程 Host。
  4156. forwardDynamicWorkflowUserMode: (mode) => {
  4157. void pushDynamicWorkflowUserModeToRemoteHosts(
  4158. windowRemoteConnectionRegistry
  4159. .listReadyConnections()
  4160. .map(({ target, services: remoteServices }) => ({
  4161. target,
  4162. zcodeAgentService: remoteServices.get(IZCodeAgentService),
  4163. })),
  4164. mode,
  4165. (error) => logger.warn("remote dynamic workflow user mode forward failed", error),
  4166. );
  4167. },
  4168. registerPluginSandbox: pluginSandboxRegistrationBridge.register,
  4169. runtimeProcessEnvPatch: msg.runtimeProcessEnvPatch,
  4170. agentTelemetry: {
  4171. getDeviceMid: () => msg.deviceMid,
  4172. runtimeSurface: "desktop_local_host",
  4173. },
  4174. serviceAuthorityMode: "desktop-local",
  4175. zcodeAgentSpawnFallbackCwd: msg.agentSpawnFallbackCwd,
  4176. zcodeBuiltinProviderConfigFilePath: msg.zcodeBuiltinProviderConfigFilePath,
  4177. processLifecycleReporter: runtimeProcessLifecycleReporter,
  4178. taskRuntimeReporter: runtimeTaskReporter,
  4179. quitBlockerReporter,
  4180. feedback: {
  4181. apiBaseUrl: msg.feedbackApiBase,
  4182. createFullLogArchive: createFullFeedbackLogArchiveViaMain,
  4183. },
  4184. forwardSessionMessageSendRequested: (request) => {
  4185. parentPort?.postMessage({
  4186. type: HostResponseTypes.SessionMessageSendRequested,
  4187. request,
  4188. });
  4189. },
  4190. onAutomationManualRunRequested: dispatchManualAutomationRun,
  4191. onOffPeakSchedulerWakeRequested: () => {
  4192. parentPort?.postMessage({ type: HostResponseTypes.OffPeakSchedulerWakeRequest });
  4193. },
  4194. onProviderProvisioningSourceChanged: (trigger) => {
  4195. parentPort?.postMessage({
  4196. type: HostResponseTypes.ProviderProvisioningSourceChanged,
  4197. trigger,
  4198. });
  4199. },
  4200. // browser-use:agent 的 interaction/browserExecute 经 zcodeAgentService 转到这个 executor,
  4201. // 再经 parentPort 到 main 的 WebContentsView+CDP 执行。
  4202. browserControlExecutor: browserControlMainBridge,
  4203. appControlNavigation,
  4204. // CUA 顶部提示属于物理 Windows 桌面投影;非 Windows 和远端 authority 都不得上报。
  4205. cuaOperationStateReporter:
  4206. process.platform === "win32" ? cuaOperationStateReporter : undefined,
  4207. });
  4208. activeServices = initializedServices;
  4209. activeHostApiNetworkTransport = hostApiNetworkTransport;
  4210. return initializedServices;
  4211. },
  4212. });
  4213. const zcodeTaskService = services.getOptional(IZCodeTaskService);
  4214. if (zcodeTaskService) {
  4215. const reportingZCodeTaskService = createReportingRemoteZCodeTaskService(
  4216. zcodeTaskService,
  4217. {
  4218. reportRunningPromptCount: false,
  4219. },
  4220. );
  4221. services.register(IZCodeTaskService, reportingZCodeTaskService);
  4222. }
  4223. sourceServerDirectory = new SourceServerDirectory({
  4224. settingService: services.get(ISettingService),
  4225. credentialService: services.get(ICredentialService),
  4226. // host 域无 debug 日志通道;按 debug 语义仅在非生产输出,生产 no-op 防止刷盘。
  4227. logDebug: (message) => {
  4228. if (process.env.NODE_ENV !== "production") logger.info(message);
  4229. },
  4230. logWarn: (message) => logger.warn(message),
  4231. });
  4232. sourceServerArtifactPolicy =
  4233. msg.remoteAssets?.sourceServerArtifactPolicy ?? "release-versioned";
  4234. // Bug 原因:release resolver 过去只传给 updateSource;启动恢复和 connectProfile 直接调用
  4235. // Manager,在 development-content-addressed 同版本校验处拿不到本地 archive,必然误报 unavailable。
  4236. const resolveSourceServerRelease = async (
  4237. probe: Parameters<typeof resolveSourceServerReleaseAsset>[0],
  4238. target: Parameters<typeof resolveSourceServerReleaseAsset>[2],
  4239. options?: Parameters<typeof resolveSourceServerReleaseAsset>[4],
  4240. ) =>
  4241. await resolveSourceServerReleaseAsset(
  4242. probe,
  4243. msg.remoteAssets ?? {},
  4244. target,
  4245. {
  4246. fetch: hostApiNetworkTransport.fetch,
  4247. },
  4248. options,
  4249. );
  4250. sourceServerConnectionManager = new SourceServerConnectionManager({
  4251. directory: sourceServerDirectory,
  4252. admitConnection: createRemoteProjectConnectionAdmission(
  4253. services.get(IRemoteProjectService),
  4254. ),
  4255. onProjectChange: notifyProjectChange,
  4256. logWarn: (message, error) => logger.warn(message, error),
  4257. sourceServerArtifactPolicy,
  4258. resolveRelease: resolveSourceServerRelease,
  4259. });
  4260. sourceServerManagementService = createSourceServerManagementService({
  4261. directory: sourceServerDirectory,
  4262. manager: sourceServerConnectionManager,
  4263. resolveRelease: resolveSourceServerRelease,
  4264. onDirectorySnapshot: (snapshot) => {
  4265. sourceServerDisplayNameById.clear();
  4266. for (const server of snapshot.servers) {
  4267. sourceServerDisplayNameById.set(server.sourceServerId, server.displayName);
  4268. }
  4269. },
  4270. onBeforeSourceServerRemoved: async (sourceServerId) => {
  4271. const hostId = remoteHostIdFromWorkspaceIdentity(
  4272. buildServerRemoteWorkspaceIdentity({ serverId: sourceServerId, workspacePath: "/" }),
  4273. );
  4274. if (!hostId) throw new Error("remote-project.invalid-host-identity");
  4275. await services.get(IRemoteProjectService).removeHost(hostId);
  4276. windowHostAttachmentRegistry.detachSourceSettingsAttachments(sourceServerId);
  4277. sourceServerDisplayNameById.delete(sourceServerId);
  4278. },
  4279. releaseUnboundProfileHost: async (profile, profiles) =>
  4280. await releaseRemoteProjectProfileHost(
  4281. services.get(IRemoteProjectService),
  4282. profile,
  4283. profiles,
  4284. ),
  4285. });
  4286. sourceSettingsStateSubscription = sourceServerConnectionManager.onDidChangeState(
  4287. (state) => {
  4288. notifyProjectChange();
  4289. if (state.sourceServerId && shouldDetachSourceSettingsAttachment(state.state)) {
  4290. windowHostAttachmentRegistry.detachSourceSettingsAttachments(state.sourceServerId);
  4291. }
  4292. },
  4293. );
  4294. services.register(ISourceServerManagementService, sourceServerManagementService);
  4295. // 数据同步页的设备同步状态只属于本机 Host:不进入远程 workspace RPC 合同、
  4296. // source-settings 服务集合,也不在手机 attachment 白名单中。
  4297. services.register(
  4298. IDeviceSyncStateService,
  4299. createDeviceSyncStateService({
  4300. filePath: join(getAppConfigDir(), "data-sync-state.json"),
  4301. }),
  4302. );
  4303. services.register(
  4304. IProviderProvisioningStatusService,
  4305. hostProviderProvisioningStatus.service,
  4306. );
  4307. // 扩展门面只在桌面本机 Host 注册:不进远程 workspace 合同、source-settings 与手机白名单。
  4308. // 必须在 base attachment 之前注册,否则这条端口上看不到该频道。
  4309. windowHostExtensions?.dispose();
  4310. windowHostExtensions = createWindowHostExtensions({
  4311. pluginManagement: services.get(IPluginManagementService),
  4312. // context 组成与生成速率的数据泵(docs/plugins/extension-host.md §9、§10),也是会话读连接的底座(§17.5)。
  4313. agent: services.get(IZCodeAgentService),
  4314. // 会话列表泵(§17.5):与侧栏、手机同一份控制器投影,只在本进程内交给扩展门面。
  4315. taskRows: {
  4316. read: () => windowHostControllerRuntime.readTaskRows(),
  4317. subscribe: (onChange) => windowHostControllerRuntime.subscribeTaskRows(onChange),
  4318. },
  4319. // 扩展视图与 MCP App 共用同一条 Host → Main 沙箱登记桥(contentKind "extension")。
  4320. registerSandbox: pluginSandboxRegistrationBridge.register,
  4321. inventoryWorkspacePath: msg.agentSpawnFallbackCwd ?? process.cwd(),
  4322. // 扩展 settings 能力的读取器(含敏感值,§16.7):只在本进程内交给网关,不登记为服务。
  4323. userOptionsReader: getPluginUserOptionsReader(services),
  4324. appControl: appControlForExtensions,
  4325. // 插件项目(§17.4):本机项目服务,与侧栏「新建项目」同一条 saveProject 路径。
  4326. projects: services.get(IProjectService),
  4327. // 能力 models.list(§18.1 H9):与输入框模型选择器同一份视图。
  4328. modelSelection: services.get(IModelSelectionService),
  4329. // 授权记录与审计(§17.7、§17.8):~/.zcode/v2/extensions,只由扩展门面读写。
  4330. dataDir: join(getAppConfigDir(), "extensions"),
  4331. postToMain: (message) => parentPort.postMessage(message),
  4332. });
  4333. services.register(IExtensionsService, windowHostExtensions.service);
  4334. services.register(IExtensionViewsService, windowHostExtensions.viewsService);
  4335. services.register(IExtensionGrantsService, windowHostExtensions.grantsService);
  4336. wireLocalResourceTelemetry(services);
  4337. hasDisposedHostResources = false;
  4338. disposeHostResourcesInFlight = null;
  4339. const agentWarmupTargets =
  4340. msg.agentWarmupTargets && msg.agentWarmupTargets.length > 0
  4341. ? msg.agentWarmupTargets
  4342. : msg.workspacePath
  4343. ? [
  4344. {
  4345. workspacePath: msg.workspacePath,
  4346. ...(msg.workspaceIdentity ? { workspaceIdentity: msg.workspaceIdentity } : {}),
  4347. },
  4348. ]
  4349. : [];
  4350. // Main 已把启动预热限制为 active workspace 1 个;Host 必须显式消费这份固定名单,
  4351. // 不能让后续 task-list observer 再隐式扩大,也不能因失败扫描补位。
  4352. agentWarmupTargets.forEach((target, index) => {
  4353. warmUpZCodeAgent(
  4354. services,
  4355. target,
  4356. `local host init (${index + 1}/${agentWarmupTargets.length})`,
  4357. );
  4358. });
  4359. logger.info("exposing services on ChannelServer...");
  4360. if (!basePortClosed)
  4361. windowHostAttachmentRegistry.attach({
  4362. requestId: `init-local-${randomUUID()}`,
  4363. attachmentId: `base-${randomUUID()}`,
  4364. clientMode: "desktop-continuous",
  4365. scope: { kind: "local" },
  4366. port,
  4367. });
  4368. logWindowHostTopology("base-attachment-ready");
  4369. logger.info("local services ready, all channels registered");
  4370. // 服务就绪后请 Main 牵线扩展进程(首个就绪的 Window Host 会拉起它)。
  4371. windowHostExtensions.announceReady();
  4372. // URL Host 复用相同启动开关与 Registry;项目发现不创建 logical workspace/Agent。
  4373. void runStartupReconnectBatch({
  4374. getSettings: () => services.get(ISettingService).get(),
  4375. listCandidates: async () =>
  4376. (await services.get(IRemoteProjectService).readDirectory()).hosts.filter(
  4377. (host) => host.kind === "server",
  4378. ),
  4379. reconnect: (hosts) =>
  4380. Promise.all(
  4381. hosts.map(async (host) => {
  4382. try {
  4383. await services.get(IRemoteProjectService).connectHost(host.id);
  4384. } catch (error) {
  4385. logger.warn("URL Server startup reconnect failed", { hostId: host.id, error });
  4386. }
  4387. }),
  4388. ),
  4389. }).catch((error) => logger.warn("URL Server startup directory unavailable", error));
  4390. // Bug 原因:Directory 迁移属于远程附加能力,等待它完成会把本地 base attachment 的
  4391. // 首帧一起拖住。base ready 后再后台初始化;失败 flight 清空,用户显式连接仍可重试。
  4392. void sourceServerDirectory
  4393. .initialize()
  4394. .then(async () =>
  4395. runStartupReconnectBatch({
  4396. getSettings: () => services.get(ISettingService).get(),
  4397. listCandidates: async () => {
  4398. const retained = new Set(
  4399. (await services.get(IRemoteProjectService).readDirectory()).hosts.map(
  4400. (host) => host.id,
  4401. ),
  4402. );
  4403. return (await sourceServerDirectory!.listStartupReconnectCandidates()).filter(
  4404. (candidate) => retained.has(remoteProjectHostIdForProfile(candidate.profile)),
  4405. );
  4406. },
  4407. reconnect: (candidates) =>
  4408. sourceServerConnectionManager!.reconnectOnStartup(candidates),
  4409. }),
  4410. )
  4411. .then((results) => {
  4412. const online = results.filter((result) => result.status === "online").length;
  4413. // Bug 原因:过去只记录失败计数,真实 Profile/reason 被吞掉,导致冷启动失败只能靠
  4414. // 手动重连再次触发。启动批次最多 3 个,逐项 warn 不会形成高频日志。
  4415. for (const result of results) {
  4416. if (result.status === "failed") {
  4417. logger.warn("Source Server startup reconnect failed", {
  4418. profileId: result.profileId,
  4419. error: result.error,
  4420. });
  4421. }
  4422. }
  4423. logger.info(
  4424. `Source Server startup reconnect finished, online=${online}, failed=${results.length - online}`,
  4425. );
  4426. })
  4427. .catch((error) =>
  4428. logger.warn(
  4429. "Source Server directory initialization failed; local services remain available",
  4430. error,
  4431. ),
  4432. );
  4433. },
  4434. });
  4435. await databaseStartup.coordinator.start();
  4436. }
  4437. });