runner.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // @vitest-environment node
  2. import { afterEach, beforeEach, expect, it, vi } from 'vitest'
  3. import Koa from 'koa'
  4. import { createServer, type Server } from 'node:http'
  5. import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  6. import { spawn } from 'node:child_process'
  7. import { once } from 'node:events'
  8. import { tmpdir } from 'node:os'
  9. import { join } from 'node:path'
  10. import { randomUUID } from 'node:crypto'
  11. import { WebSocketServer, type WebSocket } from 'ws'
  12. import { WorkspaceStore } from '../../src/server/workspaceStore'
  13. import { LocalAuthStore } from '../../src/server/localAuth'
  14. import { RunnerHub } from '../../src/server/runnerHub'
  15. import { RunnerAgent } from '../../src/runner/agent'
  16. import { ComputerGateway } from '../../src/runner/worker/gateway'
  17. import { WorkspaceGateway, type GatewayTarget, type GatewayFrame } from '../../src/server/workspaceGateway'
  18. import { createWorkspaceToolLease } from '../../src/server/workspaceToolLease'
  19. import { HttpError } from '../../src/server/errors'
  20. import type { RunnerCommand, RunnerConfiguration } from '../../src/shared/runner'
  21. class Auth extends LocalAuthStore {
  22. version=1
  23. allowed=true
  24. override isUserActive(){return true}
  25. override pushAuthorizationVersion(){return this.version}
  26. override canUseSource(){return this.allowed}
  27. }
  28. let home:string,store:WorkspaceStore,auth:Auth,hub:RunnerHub,runner:RunnerAgent,config:RunnerConfiguration
  29. let web:Server,hermes:Server,ws:WebSocketServer,controller:AbortController,running:Promise<void>
  30. let target:GatewayTarget,bindings:any[],rpc:Array<{method:string;params:any}>,frames:GatewayFrame[],sockets:WebSocket[]
  31. const gateways:WorkspaceGateway[]=[]
  32. const listen=(server:Server)=>new Promise<string>(resolve=>server.listen(0,'127.0.0.1',()=>resolve(`http://127.0.0.1:${(server.address() as {port:number}).port}`)))
  33. const close=(server:Server)=>new Promise<void>(resolve=>{server.close(()=>resolve());server.closeAllConnections()})
  34. beforeEach(async()=>{
  35. home=mkdtempSync(join(tmpdir(),'yaoyao-runner-'));store=new WorkspaceStore(home);auth=new Auth(home)
  36. bindings=[];rpc=[];frames=[];sockets=[]
  37. hermes=createServer(async(req,res)=>{
  38. let body='';for await(const part of req)body+=part
  39. if(req.url?.endsWith('/bind'))bindings.push(JSON.parse(body))
  40. res.setHeader('Content-Type','application/json')
  41. res.end(JSON.stringify(req.url==='/api/auth/ws-ticket'?{ticket:'fixture'}:req.url==='/api/profiles'?{profiles:['default',{name:'writer'},{name:'secret'}]}:req.url?.endsWith('/capabilities')?{version:1,ready:true,in_process:true,native_tools:true}:{ok:true,native_tools:true,workspace_memory:body?JSON.parse(body).workspace_memory===true:false,terminal:{cwd:'/fixture/workspace'}}))
  42. })
  43. const hermesURL=await listen(hermes)
  44. ws=new WebSocketServer({server:hermes})
  45. ws.on('connection',socket=>{
  46. sockets.push(socket);socket.send(JSON.stringify({method:'event',params:{type:'gateway.ready'}}))
  47. socket.on('message',raw=>{
  48. const value=JSON.parse(String(raw));rpc.push(value)
  49. const result=['session.create','session.resume'].includes(value.method)?{session_id:randomUUID(),stored_session_id:randomUUID(),info:{profile_name:value.params.profile}}:{ok:true}
  50. socket.send(JSON.stringify({id:value.id,result}))
  51. })
  52. })
  53. hub=new RunnerHub(store,auth,{url:new URL(hermesURL)} as GatewayTarget)
  54. const registered=hub.enroll('owner',{name:'测试电脑',allowedProfiles:['default','writer']})
  55. const app=new Koa();app.use(async(ctx,next)=>{try{await next()}catch(error){ctx.status=error instanceof HttpError?error.status:500;ctx.body={code:error instanceof HttpError?error.code:'error'}}});app.use(hub.middleware())
  56. web=createServer(app.callback());const serverURL=await listen(web)
  57. config={protocol:1,serverURL,runnerId:registered.runner.id,token:registered.token,hermesURL,allowedProfiles:['default','writer'],artifactRoots:[]}
  58. runner=new RunnerAgent(config,home);controller=new AbortController();running=runner.run(controller.signal);void running.catch(()=>{})
  59. await vi.waitFor(()=>expect(hub.summary(hub.records()[0]!).online).toBe(true))
  60. await vi.waitFor(()=>expect((runner as any).serverEpoch).toBeTruthy())
  61. target=hub.target('owner','local')!
  62. })
  63. afterEach(async()=>{
  64. for(const gateway of gateways.splice(0))gateway.close()
  65. controller.abort();await running.catch(()=>{});hub.close()
  66. for(const socket of ws.clients)socket.terminate()
  67. await new Promise<void>(resolve=>ws.close(()=>resolve()));await close(hermes);await close(web)
  68. store.close();rmSync(home,{recursive:true,force:true})
  69. })
  70. async function channel(){
  71. const gateway=new WorkspaceGateway(target);gateways.push(gateway);gateway.onEvent=frame=>frames.push(frame)
  72. await gateway.connect();const session=await gateway.rpc('session.create',{profile:'default'})
  73. return {gateway,session}
  74. }
  75. it('blocks old Runner control paths when the global VM proxy is enabled',async()=>{
  76. hub.executionSettings={proxy:()=>({enabled:true,revision:1})} as any
  77. hub.controlAllowed=()=>true
  78. for(const payload of [{op:'take'},{op:'input'},{op:'lifecycle',action:'start'}])await expect((hub as any).request(config.runnerId,'computer.control',payload)).rejects.toMatchObject({code:'proxy_runner_required'})
  79. expect(await (runner as any).api('control-check',{controlId:randomUUID()})).toEqual({allowed:false})
  80. expect((hub as any).networkCommandAllowed(config.runnerId,'computer.control',{op:'lifecycle',action:'stop'})).toBe(true)
  81. })
  82. it('reports missing network prerequisites for saved proxy settings and clears the error after applying them',async()=>{
  83. hub.executionSettings={proxy:()=>({enabled:true,revision:4})} as any
  84. ;(hub as any).online.get(config.runnerId).features.push('vm-egress-v1')
  85. const request=vi.spyOn(hub as any,'request').mockRejectedValue(new HttpError(502,'private transport details','computer_network_upgrade_required'))
  86. try{
  87. await hub.configureNetworks()
  88. expect(hub.networkStatus()[0]?.status).toContain('缺少虚拟机网络网关')
  89. const result=await hub.testNetworks()
  90. expect(result.nodes[0]).toMatchObject({ok:false,error:expect.stringContaining('重新准备网络镜像')})
  91. expect(JSON.stringify(result)).not.toContain('private transport details')
  92. request.mockRejectedValue(new Error('http://user:secret@proxy.invalid'))
  93. expect(JSON.stringify(await hub.testNetworks())).not.toContain('secret')
  94. request.mockResolvedValue({revision:4})
  95. await hub.configureNetworks()
  96. expect(hub.networkStatus()[0]?.status).toBe('已同步,启动时校验出口')
  97. }finally{request.mockRestore()}
  98. })
  99. it('does not report a successful VM proxy test when the network gateway is missing',async()=>{
  100. hub.executionSettings={proxy:()=>({enabled:true,revision:4})} as any
  101. const verifyNetwork=vi.fn().mockRejectedValue(new HttpError(409,'缺少网络网关','computer_network_upgrade_required'))
  102. const original=(runner as any).computers
  103. ;(runner as any).computers={provider:{verifyNetwork},config:{imageId:'sha256:'+'a'.repeat(64)}}
  104. try{
  105. await expect((runner as any).execute({kind:'network.test',payload:{}})).rejects.toMatchObject({code:'computer_network_upgrade_required'})
  106. expect(verifyNetwork).toHaveBeenCalledOnce()
  107. }finally{(runner as any).computers=original}
  108. })
  109. it('admits virtual computer calls only on a computer gateway with an owned session',async()=>{
  110. const connectionId=randomUUID(),sessionId=randomUUID(),rpc=vi.fn(async()=>({ok:true}))
  111. const computer=Object.assign(Object.create(ComputerGateway.prototype),{rpc,close:()=>{}}) as ComputerGateway
  112. const connection={gateway:computer,sessions:new Map([[sessionId,'default']]),running:new Set(),events:Promise.resolve()}
  113. ;(runner as any).connections.set(connectionId,connection)
  114. const command=(method:string,id=sessionId)=>({kind:'gateway.rpc',payload:{connectionId,method,params:{session_id:id,name:'computer_desktop_state',arguments:{}}}})
  115. expect(await (runner as any).execute(command('computer.invoke'))).toEqual({ok:true})
  116. expect(await (runner as any).execute(command('computer.transfer'))).toEqual({ok:true})
  117. await expect((runner as any).execute(command('computer.invoke',randomUUID()))).rejects.toMatchObject({code:'runner_session_forbidden'})
  118. connection.gateway=Object.assign(Object.create(WorkspaceGateway.prototype),{rpc,close:()=>{}}) as ComputerGateway
  119. await expect((runner as any).execute(command('computer.invoke'))).rejects.toMatchObject({code:'runner_command_forbidden'})
  120. expect(rpc).toHaveBeenCalledTimes(2)
  121. })
  122. it('requires an upgraded Runner before granting mixed host and VM tools',()=>{
  123. const id=randomUUID()
  124. expect(()=>hub.target('owner','local',{environmentId:id,agentId:id,ownerKey:'owner',hostAccess:true})).toThrow('不支持同时使用本机和虚拟机')
  125. })
  126. it('distinguishes a missing or disabled VM runner, an offline runner and incompatible features',async()=>{
  127. const agent=store.createAgent('owner',{name:'虚拟机状态',profile:'default'})
  128. expect(()=>hub.computerRunner('owner',agent)).toThrow('请启用隔离电脑 Worker 或更新 Runner')
  129. controller.abort();await running
  130. const record=hub.records()[0]!
  131. hub.remove(record.id)
  132. expect(()=>hub.computerRunner('owner',agent)).toThrow('本地虚拟机执行节点尚未启用')
  133. store.put('_system','runner',record.id,{...record,enabled:true})
  134. expect(()=>hub.computerRunner('owner',agent)).toThrow('本地虚拟机执行节点未连接')
  135. store.remove('_system','runner',record.id)
  136. expect(()=>hub.computerRunner('owner',agent)).toThrow('本地虚拟机执行节点尚未启用')
  137. })
  138. it('rejects Profile collaboration on a Runner that does not advertise the execution backend',()=>{
  139. const id=randomUUID()
  140. expect(()=>hub.target('owner','local',{environmentId:id,agentId:id,ownerKey:'owner',hostAccess:true,profileSession:true})).toThrow('不支持本机协作模式')
  141. })
  142. it.each([false,true])('admits Profile collaboration after an actual computer Runner handshake (Compose: %s)',async compose=>{
  143. controller.abort();await running
  144. config.computers={runtime:'docker',imageId:'sha256:'+'0'.repeat(64),python:'/fixture/python',hermesSource:home,hermesHome:home,...(compose?{managedBy:'compose' as const}:{})}
  145. runner=new RunnerAgent(config,home);controller=new AbortController();running=runner.run(controller.signal);void running.catch(()=>{})
  146. await vi.waitFor(()=>expect((runner as any).serverEpoch).toBeTruthy())
  147. const features=hub.summary(hub.records()[0]!).features
  148. expect(features).toContain('profile-computer-v1')
  149. expect(features).toEqual(expect.arrayContaining(['host-computer-tools-v1','computer-worker-v1','computer-control-v1']))
  150. if(compose)expect(features).toContain('compose-desktops-v1')
  151. const agent=store.createAgent('owner',{name:'协作握手',profile:'default',computer:'vm',execution:'computer',vmExecution:'profile'})
  152. expect(()=>hub.target('owner','local',{agentId:agent.id,environmentId:agent.id,ownerKey:'owner',hostAccess:true,profileSession:true})).not.toThrow()
  153. })
  154. async function machine(path:string,body?:unknown,overrides:Record<string,string>={}){
  155. return fetch(`${config.serverURL}/api/runner/v1/${config.runnerId}/${path}`,{
  156. method:body===undefined?'GET':'POST',headers:{Authorization:`Bearer ${config.token}`,'x-runner-instance':runner.instance,'x-runner-protocol':'1','x-runner-epoch':(runner as any).serverEpoch,'Content-Type':'application/json',...overrides},...(body===undefined?{}:{body:JSON.stringify(body)})
  157. })
  158. }
  159. it('connects through outbound transport, filters profiles and forwards only owned session events',async()=>{
  160. const profiles=await target.session.request('/api/profiles')
  161. expect(JSON.parse(profiles.body.toString()).profiles).toEqual(['default',{name:'writer'}])
  162. const {gateway,session}=await channel()
  163. await expect(gateway.rpc('session.create',{profile:'secret'})).rejects.toMatchObject({code:'runner_profile_forbidden'})
  164. await expect(gateway.rpc('prompt.submit',{session_id:'someone-else',text:'no'})).rejects.toMatchObject({code:'runner_session_forbidden'})
  165. await gateway.rpc('prompt.submit',{session_id:session.session_id,text:'hello'})
  166. sockets[0]!.send(JSON.stringify({method:'event',params:{type:'message.delta',session_id:'someone-else',payload:{text:'private'}}}))
  167. sockets[0]!.send(JSON.stringify({method:'event',params:{type:'message.delta',session_id:session.session_id,payload:{text:'hello'}}}))
  168. await vi.waitFor(()=>expect(frames.some(f=>f.payload?.text==='hello')).toBe(true))
  169. expect(frames.some(f=>f.payload?.text==='private')).toBe(false)
  170. })
  171. it('mounts loopback-only tools with stable call ids and revokes an active grant',async()=>{
  172. const {session}=await channel(),abort=new AbortController(),call=vi.fn(async()=>({agent:{id:'created'}}))
  173. let active=true
  174. const lease=await createWorkspaceToolLease({target,profile:'default',workId:'work',session:()=>({runtimeId:session.session_id,storedId:session.stored_session_id}),signal:abort.signal,
  175. assertActive:()=>{if(!active)throw new HttpError(403,'撤权','revoked')},catalog:()=>[{id:'workspace_create_agent',name:'workspace_create_agent',description:'create',inputSchema:{type:'object'}}],call,onFailure:()=>{}})
  176. await lease.bind();const binding=bindings[0]
  177. const toolHTTP=(path:string,body:unknown)=>fetch(binding.bridge_url+path,{method:'POST',headers:{Authorization:`Bearer ${binding.token}`,'Content-Type':'application/json'},body:JSON.stringify(body)})
  178. const catalog=await (await toolHTTP('/tools/list',{})).json() as any
  179. const body={callId:'same-call',toolId:catalog.tools[0].id,arguments:{name:'worker'}}
  180. const first=await (await toolHTTP('/tools/call',body)).json()
  181. expect(await (await toolHTTP('/tools/call',body)).json()).toEqual(first)
  182. expect(call).toHaveBeenCalledExactlyOnceWith('workspace_create_agent',{name:'worker'},'same-call')
  183. active=false
  184. expect(await (await toolHTTP('/tools/call',{...body,callId:'late-call'})).json()).toMatchObject({isError:true})
  185. expect(call).toHaveBeenCalledTimes(1)
  186. await lease.dispose()
  187. })
  188. it('denies browser credentials, stale epochs, foreign lease ids and unauthorized HTTP operations',async()=>{
  189. expect((await machine('admit',{id:randomUUID()},{Origin:config.serverURL})).status).toBe(403)
  190. expect((await machine('admit',{id:randomUUID()},{Authorization:'Bearer wrong'})).status).toBe(403)
  191. expect((await machine('admit',{id:randomUUID()},{'x-runner-epoch':'old'})).status).toBe(409)
  192. expect((await machine('tool',{leaseId:randomUUID(),callId:'test',toolId:'workspace_create_agent',arguments:{}})).status).toBe(410)
  193. await expect(target.session.request('/api/config',{method:'POST',body:{}})).rejects.toMatchObject({code:'runner_http_forbidden'})
  194. await expect(target.session.request('/api/files/download',{search:new URLSearchParams({profile:'default',path:'/etc/hosts'})})).rejects.toMatchObject({code:'runner_artifact_forbidden'})
  195. })
  196. it('does not execute a queued command after account authorization changes',async()=>{
  197. const {gateway,session}=await channel()
  198. auth.version++
  199. await expect(gateway.rpc('prompt.submit',{session_id:session.session_id,text:'late'})).rejects.toMatchObject({code:'runner_command_not_admitted'})
  200. expect(rpc.filter(r=>r.method==='prompt.submit')).toHaveLength(0)
  201. })
  202. it('keeps one result for a command and refuses conflicting or unfinished replay after restart',async()=>{
  203. const seen:RunnerCommand[]=[];const execute=(runner as any).execute.bind(runner)
  204. vi.spyOn(runner as any,'execute').mockImplementation(async(command:any)=>{seen.push(command);return execute(command)})
  205. await channel()
  206. const command=seen.find(c=>c.kind==='gateway.rpc')!
  207. const before=rpc.length
  208. expect(await runner.handle(command)).toHaveProperty('result.session_id')
  209. expect(rpc).toHaveLength(before)
  210. await expect(runner.handle({...command,payload:{changed:true}})).rejects.toMatchObject({code:'idempotency_conflict'})
  211. const incomplete={...command,id:randomUUID()}
  212. const {createHash}=await import('node:crypto')
  213. ;(runner as any).db.prepare("INSERT INTO commands VALUES(?,?,'started',NULL,?)").run(incomplete.id,createHash('sha256').update(JSON.stringify(incomplete)).digest('hex'),Date.now())
  214. controller.abort();await running
  215. runner=new RunnerAgent(config,home);controller=new AbortController();running=runner.run(controller.signal);void running.catch(()=>{})
  216. await expect(runner.handle(incomplete)).rejects.toMatchObject({code:'runner_command_uncertain'})
  217. expect(await runner.handle(command)).toHaveProperty('result.session_id')
  218. expect(rpc).toHaveLength(before)
  219. })
  220. it('closes a pending gateway before a delayed handshake can revive it',async()=>{
  221. const connect=WorkspaceGateway.prototype.connect
  222. let release!:()=>void
  223. const gate=new Promise<void>(resolve=>{release=resolve})
  224. vi.spyOn(WorkspaceGateway.prototype,'connect').mockImplementationOnce(async function(this:WorkspaceGateway){await gate;return connect.call(this)})
  225. const connectionId=randomUUID(),request=(hub as any).request.bind(hub)
  226. // The control plane normally installs this owner record before opening.
  227. ;(hub as any).connections.set(connectionId,{runnerId:config.runnerId,valid:()=>true,onEvent:()=>{},onDisconnect:()=>{}})
  228. const opening=request(config.runnerId,'gateway.open',{connectionId}).catch((error:unknown)=>error)
  229. await vi.waitFor(()=>expect((runner as any).connections.has(connectionId)).toBe(true))
  230. await request(config.runnerId,'gateway.close',{connectionId})
  231. release()
  232. expect(await opening).toBeInstanceOf(Error)
  233. expect((runner as any).connections.has(connectionId)).toBe(false)
  234. })
  235. it('fences a replaced process and does not route to the host when its runner goes offline',async()=>{
  236. const {gateway}=await channel();const disconnected=vi.fn();gateway.onDisconnect=disconnected
  237. const oldInstance=runner.instance
  238. controller.abort();await running
  239. runner=new RunnerAgent(config,home);controller=new AbortController();running=runner.run(controller.signal);void running.catch(()=>{})
  240. await vi.waitFor(()=>expect(disconnected).toHaveBeenCalled())
  241. expect((await machine('poll',undefined,{'x-runner-instance':oldInstance})).status).toBe(409)
  242. hub.remove(config.runnerId)
  243. await expect(target.session.request('/api/status')).rejects.toMatchObject({code:'runner_offline'})
  244. })
  245. it('resets the hub epoch after a transport failure and closes the obsolete gateways',async()=>{
  246. const {gateway}=await channel(),disconnected=vi.fn();gateway.onDisconnect=disconnected
  247. const epoch=(runner as any).serverEpoch
  248. await (runner as any).disconnect()
  249. // Wake the outstanding poll. Its response must be ignored after disconnect.
  250. ;(hub as any).online.get(config.runnerId).wake?.()
  251. await vi.waitFor(()=>expect((runner as any).serverEpoch).not.toBe(epoch))
  252. expect(disconnected).toHaveBeenCalledTimes(1)
  253. const next=await channel()
  254. expect(await next.gateway.rpc('session.usage',{session_id:next.session.session_id})).toEqual({ok:true})
  255. })
  256. it('a closed account channel cannot interrupt an unrelated connection',async()=>{
  257. const first=await channel(),second=await channel()
  258. const entries=[...(hub as any).connections.entries()] as Array<[string,any]>
  259. entries[0]![1].valid=()=>false
  260. sockets[0]!.send(JSON.stringify({method:'event',params:{type:'message.delta',session_id:first.session.session_id,payload:{text:'revoked'}}}))
  261. await vi.waitFor(()=>expect((runner as any).connections.size).toBe(1))
  262. expect((runner as any).connected).toBe(true)
  263. expect(await second.gateway.rpc('prompt.submit',{session_id:second.session.session_id,text:'continue'})).toEqual({ok:true})
  264. expect(rpc.filter(r=>r.method==='session.interrupt'&&r.params.session_id===second.session.session_id)).toHaveLength(0)
  265. })
  266. it('rechecks admission after a queued prompt loses its account permission',async()=>{
  267. const {gateway,session}=await channel()
  268. const api=(runner as any).api.bind(runner)
  269. let release!:()=>void,waiting=false
  270. const gate=new Promise<void>(resolve=>{release=resolve})
  271. vi.spyOn(runner as any,'api').mockImplementation(async(path:any,body:any)=>{if(path==='admit'){waiting=true;await gate}return api(path,body)})
  272. const result=gateway.rpc('prompt.submit',{session_id:session.session_id,text:'must not run'}).catch(error=>error)
  273. await vi.waitFor(()=>expect(waiting).toBe(true));auth.version++;release()
  274. expect(await result).toMatchObject({code:'runner_command_not_admitted'})
  275. expect(rpc.filter(r=>r.method==='prompt.submit')).toHaveLength(0)
  276. })
  277. it('does not recreate a lease when cancellation overtakes its admitted creation',async()=>{
  278. const {session}=await channel(),abort=new AbortController()
  279. const execute=(runner as any).execute.bind(runner)
  280. let release!:()=>void,waiting=false
  281. const gate=new Promise<void>(resolve=>{release=resolve})
  282. vi.spyOn(runner as any,'execute').mockImplementation(async(command:any)=>{if(command.kind==='lease.create'){waiting=true;await gate}return execute(command)})
  283. const result=createWorkspaceToolLease({target,profile:'default',workId:'cancel-race',session:()=>({runtimeId:session.session_id,storedId:session.stored_session_id}),signal:abort.signal,
  284. assertActive:()=>{if(abort.signal.aborted)throw new Error('stopped')},catalog:()=>[],call:async()=>({}),onFailure:()=>{}}).catch(error=>error)
  285. await vi.waitFor(()=>expect(waiting).toBe(true));abort.abort()
  286. await vi.waitFor(()=>expect((runner as any).closedLeases.size).toBe(1));release()
  287. expect(await result).toBeInstanceOf(Error)
  288. expect((runner as any).leases.size).toBe(0)
  289. expect(bindings).toHaveLength(0)
  290. })
  291. it.each([0o600,0o644])('runs the CLI with private configuration and rejects broad permissions (%s)',async(mode)=>{
  292. controller.abort();await running
  293. const file=join(home,'runner.json');writeFileSync(file,JSON.stringify(config),{mode})
  294. const bundle=process.env.RUNNER_BUNDLE_PATH
  295. const args=bundle?[bundle,'--config',file]:['--import','tsx','src/runner/index.ts','--config',file]
  296. const child=spawn(process.execPath,args,{stdio:['ignore','ignore','pipe']})
  297. let output='';child.stderr?.on('data',data=>{output+=String(data)})
  298. const exited=once(child,'exit')
  299. try {
  300. if(mode===0o644){expect((await exited)[0]).not.toBe(0);expect(output).toContain('chmod 600');return}
  301. await vi.waitFor(()=>{if(child.exitCode!==null)throw new Error(`Runner 提前退出 ${child.exitCode}: ${output}`);expect(output).toContain('执行节点已连接')},{timeout:7000})
  302. expect((await target.session.request('/api/profiles')).status).toBe(200)
  303. child.kill('SIGTERM')
  304. expect((await exited)[0]).toBe(0)
  305. expect(output).toContain('执行节点已停止')
  306. expect(output).not.toContain(config.token)
  307. }finally{if(child.exitCode===null&&child.signalCode===null){child.kill('SIGTERM');await exited}}
  308. },15000)
  309. it('refuses a computer gateway on a legacy Runner before any native session is opened',async()=>{
  310. const target=hub.target('owner','local',{environmentId:randomUUID(),agentId:randomUUID(),ownerKey:'a'.repeat(64)})!
  311. const gateway=new WorkspaceGateway(target,{workId:randomUUID(),authorize:()=>{}});gateways.push(gateway)
  312. await expect(gateway.connect()).rejects.toMatchObject({code:'computer_unavailable'})
  313. expect(rpc.some(call=>call.method==='session.create')).toBe(false)
  314. })
  315. it('binds chunked artifacts to one live connection, validates bytes and publishes exactly once',async()=>{
  316. const {createHash}=await import('node:crypto'),bytes=Buffer.from('artifact payload'),id=randomUUID()
  317. const publish=vi.fn(async(name:string,data:Buffer)=>({id:randomUUID(),name,size:data.length}))
  318. const gateway=new WorkspaceGateway(target,{workId:randomUUID(),authorize:()=>{},publishArtifact:publish});gateways.push(gateway)
  319. await gateway.connect()
  320. const connectionId=[...(hub as any).connections.keys()][0]
  321. const send=(body:object)=>machine('artifact',{connectionId,id,...body})
  322. const metadata={phase:'begin',name:'report.txt',size:bytes.length,digest:createHash('sha256').update(bytes).digest('hex')}
  323. expect((await send(metadata)).status).toBe(200)
  324. expect((await send({phase:'finish'})).status).toBe(409)
  325. expect((await send({phase:'append',index:0,data:bytes.toString('base64')})).status).toBe(200)
  326. expect((await send({phase:'append',index:0,data:bytes.toString('base64')})).status).toBe(200)
  327. expect((await send({phase:'append',index:0,data:Buffer.from('wrong').toString('base64')})).status).toBe(409)
  328. const first=await (await send({phase:'finish'})).json()
  329. expect(await (await send({phase:'finish'})).json()).toEqual(first)
  330. expect(publish).toHaveBeenCalledExactlyOnceWith('report.txt',bytes)
  331. expect((await machine('artifact',{...metadata,connectionId:randomUUID(),id:randomUUID()})).status).toBe(403)
  332. auth.version++
  333. expect((await send({phase:'finish'})).status).toBe(403)
  334. })
  335. it('keeps only stop operations available on an existing channel after task permission is revoked',async()=>{
  336. let allowed=true
  337. const gateway=new WorkspaceGateway(target,{workId:randomUUID(),authorize:()=>{if(!allowed)throw new Error('revoked')}});gateways.push(gateway)
  338. await gateway.connect();const session=await gateway.rpc('session.create',{profile:'default'})
  339. allowed=false
  340. await expect(gateway.rpc('prompt.submit',{session_id:session.session_id,text:'forbidden'})).rejects.toMatchObject({code:'runner_command_not_admitted'})
  341. expect(await gateway.rpc('session.interrupt',{session_id:session.session_id})).toEqual({ok:true})
  342. expect(rpc.filter(call=>call.method==='prompt.submit')).toHaveLength(0)
  343. })
  344. it('carries workspace memory policy through the Runner to the authenticated Hermes binding',async()=>{
  345. const {session}=await channel(),abort=new AbortController()
  346. const lease=await createWorkspaceToolLease({target,profile:'default',workId:'memory-work',workspaceMemory:true,
  347. session:()=>({runtimeId:session.session_id,storedId:session.stored_session_id}),signal:abort.signal,
  348. assertActive:()=>{},catalog:()=>[],call:async()=>({}),onFailure:()=>{}})
  349. try{await lease.bind();expect(bindings.at(-1)).toMatchObject({workspace_memory:true})}finally{await lease.dispose()}
  350. })
  351. it('distinguishes automatically supported browsers from explicit node opt-out, old runners and offline nodes',()=>{
  352. const agent=store.createAgent('owner',{name:'浏览器节点状态',profile:'default'}),record=hub.records()[0]!
  353. const states=(hub as any).online as Map<string,{features:string[]}>,state=states.get(record.id)!,features=state.features
  354. try{
  355. expect(state.features).toContain('managed-browser-setup-v1')
  356. expect(hub.browserRunner('owner',agent).id).toBe(record.id)
  357. auth.allowed=false
  358. expect(()=>hub.browserRunner('owner',agent)).toThrow('浏览器 Profile 未授权')
  359. auth.allowed=true
  360. state.features=['managed-browser-disabled-v1']
  361. expect(()=>hub.browserRunner('owner',agent)).toThrow('节点管理员已关闭托管浏览器')
  362. state.features=[]
  363. expect(()=>hub.browserRunner('owner',agent)).toThrow('执行节点版本尚不支持自动准备浏览器')
  364. states.delete(record.id)
  365. expect(()=>hub.browserRunner('owner',agent)).toThrow('执行节点暂未连接')
  366. store.put('_system','runner',record.id,{...record,enabled:false})
  367. expect(()=>hub.browserRunner('owner',agent)).toThrow('尚未找到此 Bot 的执行节点')
  368. }finally{auth.allowed=true;state.features=features;states.set(record.id,state);store.put('_system','runner',record.id,record)}
  369. })