managedBrowserCardSmoke.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // @vitest-environment node
  2. import { expect, it } from 'vitest'
  3. import { chromium, expect as browserExpect } from '@playwright/test'
  4. import { mkdtemp, mkdir, rm } from 'node:fs/promises'
  5. import { spawn } from 'node:child_process'
  6. import { createServer } from 'node:net'
  7. import { tmpdir } from 'node:os'
  8. import { join, resolve } from 'node:path'
  9. async function freePort(){const server=createServer();await new Promise<void>(done=>server.listen(0,'127.0.0.1',done));const port=(server.address() as {port:number}).port;await new Promise<void>(done=>server.close(()=>done()));return port}
  10. // Uses a built client and isolated authentication fixture; no model, VM or
  11. // installation is started. Run after `vite build` with YAOYAO_BROWSER_UI_SMOKE=1.
  12. it.runIf(process.env.YAOYAO_BROWSER_UI_SMOKE==='1')('opens the structured chat card in the existing native/Web viewer and fits small screens',async()=>{
  13. const root=resolve(import.meta.dirname,'../..'),home=await mkdtemp(join(tmpdir(),'yaoyao-browser-ui-'))
  14. const port=await freePort(),upstream=await freePort(),origin=`http://127.0.0.1:${port}`
  15. const server=spawn(process.execPath,['--import','tsx','tests/fixtures/workspace-server.ts'],{cwd:root,env:{...process.env,WORKSPACE_FIXTURE_HOME:home,WORKSPACE_FIXTURE_TEAM_TOOLS:'1',WORKSPACE_FIXTURE_PORT:String(port),WORKSPACE_FIXTURE_UPSTREAM_PORT:String(upstream)},stdio:'ignore'})
  16. let browser:Awaited<ReturnType<typeof chromium.launch>>|undefined
  17. try{
  18. await browserExpect.poll(async()=>{try{return(await fetch(origin+'/healthz')).status}catch{return 0}},{timeout:30000}).toBe(200)
  19. browser=await chromium.launch();const page=await browser.newPage({viewport:{width:1100,height:850}})
  20. await page.goto(origin+'/conversations')
  21. await page.getByRole('textbox',{name:'账号',exact:true}).fill('fixture')
  22. await page.getByRole('textbox',{name:'密码',exact:true}).fill('fixture-pass')
  23. await page.getByRole('button',{name:'登录',exact:true}).click()
  24. await browserExpect(page.locator('.desktop-sidebar .sidebar-create-trigger')).toBeVisible()
  25. const seed=await(await page.request.post(origin+'/__test/computer',{data:{}})).json()
  26. const calls:{op:string;body?:any}[]=[]
  27. let available=false,installing=false,human=false,online=true,browserReads=0
  28. const installation=()=>({status:available?'ready':installing?'installing':'missing',message:available?'浏览器已准备':installing?'正在下载 Chromium · 45%':'首次使用将自动准备 Chromium',...(installing&&!available?{progress:45}:{}),updatedAt:Date.now()})
  29. const card=()=>({id:'real-server-card',agentId:seed.agentId,agentName:'电脑面板验收 1',status:available?'active':'preparing',title:'产品文档 · 浏览器接管验证',url:'https://example.com/docs/browser/session-with-long-title-and-path',installation:installation(),updatedAt:Date.now()})
  30. const inject=(data:any)=>{if(data.conversation?.id===seed.conversationId)data.messages=[{id:'browser-message',conversationId:seed.conversationId,agentId:seed.agentId,agentName:'电脑面板验收 1',seq:1,role:'assistant',content:'',reasoning:'',status:'complete',attachments:[],tools:[],browserCard:card(),createdAt:Date.now()},{id:'service-warning',conversationId:seed.conversationId,agentId:seed.agentId,agentName:'电脑面板验收 1',seq:2,role:'assistant',content:'',reasoning:'',status:'complete',attachments:[],tools:[],serviceWarnings:[{code:'plugin_unavailable',service:'天气插件',message:'MCP 服务暂不可用,本次任务继续使用其余能力。'}],createdAt:Date.now()}];return data}
  31. await page.route('**/api/app/conversations/'+seed.conversationId+'?*',async route=>{const response=await route.fetch();await route.fulfill({response,json:inject(await response.json())})})
  32. await page.route('**/api/app/workspace/snapshot*',async route=>{const response=await route.fetch(),data=await response.json();data.details=data.details.map(inject);await route.fulfill({response,json:data})})
  33. await page.route('**/api/app/settings/host-tools',route=>route.fulfill({json:{scriptMachine:false,serverComputer:false,vm:false,cloud:false,managedBrowser:true}}))
  34. const image=await page.evaluate(()=>{const canvas=document.createElement('canvas');canvas.width=1000;canvas.height=650;const ctx=canvas.getContext('2d')!;ctx.fillStyle='#f4f6f8';ctx.fillRect(0,0,1000,650);ctx.fillStyle='#27313f';ctx.font='32px sans-serif';ctx.fillText('Browser control preview',50,95);ctx.font='20px sans-serif';ctx.fillText('The same page continues after handoff.',50,145);return canvas.toDataURL('image/png').split(',')[1]})
  35. await page.route('**/api/app/agents/'+seed.agentId+'/**',async route=>{
  36. const url=new URL(route.request().url()),path=url.pathname
  37. if(path.endsWith('/managed-browser/prepare')){calls.push({op:'prepare',body:route.request().postDataJSON()});installing=true}
  38. if(path.endsWith('/managed-browser')||path.endsWith('/managed-browser/prepare')){browserReads++;return route.fulfill({json:{enabled:true,available:online&&available,...(online?{installation:installation()}:{reason:'执行节点离线,请恢复节点连接'}),open:human,generation:4,profile:'persistent',tabs:human?[{id:'tab',title:'产品文档',url:'https://example.com/docs',active:true}]:[],downloads:[]}})}
  39. if(!path.includes('/computer'))return route.continue()
  40. expect(url.searchParams.get('backend')).toBe('managed-browser')
  41. if(path.endsWith('/frame'))return route.fulfill({json:{id:'frame',generation:4,width:1000,height:650,data:image}})
  42. if(route.request().method()==='POST'){
  43. const op=path.split('/').at(-1)!;calls.push({op,body:route.request().postDataJSON()})
  44. if(op==='take'){expect(available).toBe(true);human=true}
  45. if(op==='giveback')human=false
  46. }
  47. return route.fulfill({json:{mode:human?'human':'off',backend:'managed-browser',hostName:'托管浏览器',generation:4,canResume:true,...(human?{controlId:'control',token:'fixture-token'}:{})}})
  48. })
  49. await page.goto(origin+'/conversations/'+seed.conversationId)
  50. const element=page.getByRole('region',{name:'托管浏览器会话'})
  51. await browserExpect(element).toContainText('产品文档 · 浏览器接管验证')
  52. const warnings=page.getByLabel('服务状态提示')
  53. await browserExpect(warnings.getByRole('status')).toHaveText('天气插件:MCP 服务暂不可用,本次任务继续使用其余能力。')
  54. await browserExpect(warnings.getByRole('alert')).toHaveCount(0)
  55. const output=join(root,'test-results/managed-browser-cards');await mkdir(output,{recursive:true})
  56. await page.setViewportSize({width:375,height:812})
  57. await browserExpect(element.getByRole('button',{name:'接管浏览器',exact:true})).toBeVisible()
  58. expect(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth)).toBe(false)
  59. await page.screenshot({path:join(output,'chat-375.png')})
  60. // The native bridge receives exactly the trusted card's Bot and backend.
  61. await page.evaluate(()=>{(window as any).__native=[];(window as any).yaoyaoDesktop={openComputer:async(...args:unknown[])=>{(window as any).__native.push(args);return true}}})
  62. await element.getByRole('button',{name:'接管浏览器',exact:true}).click()
  63. await browserExpect.poll(()=>page.evaluate(()=>(window as any).__native)).toEqual([[seed.agentId,{backend:'managed-browser'}]])
  64. await page.evaluate(()=>delete (window as any).yaoyaoDesktop)
  65. await element.getByRole('button',{name:'接管浏览器',exact:true}).click()
  66. const panel=page.locator('dialog.computer-panel')
  67. await browserExpect(panel.getByRole('status')).toContainText('正在下载 Chromium')
  68. expect(calls.filter(call=>call.op==='prepare')).toHaveLength(1)
  69. expect(calls.some(call=>call.op==='take')).toBe(false)
  70. await page.screenshot({path:join(output,'preparing-375.png')})
  71. available=true
  72. await browserExpect(panel).toContainText('人工控制中')
  73. await browserExpect(panel.locator('.computer-screen img')).toBeVisible()
  74. expect(calls.filter(call=>call.op==='take')).toHaveLength(1)
  75. expect(await panel.evaluate(el=>el.scrollWidth>el.clientWidth)).toBe(false)
  76. await page.screenshot({path:join(output,'control-375.png')})
  77. await panel.getByRole('button',{name:'交还并关闭',exact:true}).click()
  78. await browserExpect(panel).toHaveCount(0)
  79. expect(calls.filter(call=>call.op==='giveback')).toHaveLength(1)
  80. expect(page.url()).toContain('/conversations/'+seed.conversationId)
  81. // Offline is a connection state, never a synthetic installation. Rechecking
  82. // must recover the same browser with read-only requests before another take.
  83. online=false
  84. const writesBeforeRecheck=calls.length
  85. await element.getByRole('button',{name:'接管浏览器',exact:true}).click()
  86. await browserExpect(panel).toContainText('执行节点离线,请恢复节点连接')
  87. await browserExpect(panel.getByRole('button',{name:'打开并控制',exact:true})).toBeDisabled()
  88. await browserExpect(panel.locator('progress')).toHaveCount(0)
  89. await page.screenshot({path:join(output,'offline-recheck-375.png')})
  90. online=true
  91. const readsBeforeRecheck=browserReads
  92. await panel.getByRole('button',{name:'重新检测',exact:true}).click()
  93. await browserExpect(panel.getByRole('button',{name:'打开并控制',exact:true})).toBeEnabled()
  94. expect(browserReads).toBeGreaterThan(readsBeforeRecheck)
  95. expect(calls).toHaveLength(writesBeforeRecheck)
  96. await panel.getByRole('button',{name:'关闭',exact:true}).click()
  97. await browserExpect(panel).toHaveCount(0)
  98. await page.reload();await browserExpect(element).toContainText('产品文档 · 浏览器接管验证')
  99. await browserExpect(warnings).toContainText('MCP 服务暂不可用,本次任务继续使用其余能力。')
  100. await page.emulateMedia({reducedMotion:'reduce',colorScheme:'dark'})
  101. await browserExpect(page.locator('html')).toHaveClass(/dark/)
  102. await page.screenshot({path:join(output,'chat-dark-375.png')})
  103. await page.setViewportSize({width:812,height:375})
  104. await element.getByRole('button',{name:'接管浏览器',exact:true}).scrollIntoViewIfNeeded()
  105. expect(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth)).toBe(false)
  106. await page.screenshot({path:join(output,'chat-landscape-dark.png')})
  107. }finally{
  108. await browser?.close();server.kill('SIGTERM')
  109. await new Promise<void>(done=>{if(server.exitCode!==null)return done();const timer=setTimeout(()=>{server.kill('SIGKILL');done()},3000);server.once('exit',()=>{clearTimeout(timer);done()})})
  110. await rm(home,{recursive:true,force:true})
  111. }
  112. },60000)