import {afterEach,beforeEach,expect,it,vi} from 'vitest' import {flushPromises,mount} from '@vue/test-utils' import ComputerPanel from '@/components/workspace/ComputerPanel.vue' import Preview from '@/components/workspace/LocalVmChatPanel.vue' import Viewer from '@/views/ComputerViewerView.vue' import BrowserToolbar from '@/components/workspace/BrowserToolbar.vue' import {apiRequest} from '@/api/client' import type {ManagedBrowserState} from '@shared/managedBrowser' vi.mock('@/api/client',()=>({apiRequest:vi.fn()})) const route={params:{agentId:'bot'},query:{} as Record} vi.mock('vue-router',()=>({useRoute:()=>route})) const request=vi.mocked(apiRequest) const agent={id:'bot',name:'竹儿',profile:'default',nodeId:'local'} as any const permission={supported:true,authorized:true,screen:true,accessibility:true,ready:true,fullAuthorized:true} const stubs={AppIcon:true,GrokAuthPanel:true} let enabled:boolean|undefined,state:ManagedBrowserState,controlled:boolean beforeEach(()=>{ vi.spyOn(document,'hidden','get').mockReturnValue(false) route.query={};enabled=true;controlled=false state={enabled:true,available:true,open:false,generation:4,profile:'temporary',tabs:[],downloads:[]} request.mockReset() request.mockImplementation(async(path,options)=>{ const url=new URL(path,'http://fixture'),backend=url.searchParams.get('backend') if(url.pathname==='/api/app/agents')return {agents:[agent]} as any if(url.pathname.endsWith('/host-tools'))return {scriptMachine:true,serverComputer:true,cloud:true,vm:true,managedBrowser:enabled} as any if(url.pathname.endsWith('/desktop-environment'))return {hosts:[{id:'local',name:'服务器',online:true,local:permission}]} as any if(url.pathname.endsWith('/cloud-computer'))return {configured:true,running:true,connected:true} as any if(url.pathname.endsWith('/local-vm'))return {enabled:true,image:true,container:'running',ready:true} as any if(url.pathname.endsWith('/managed-browser'))return structuredClone(state) as any if(url.pathname.endsWith('/managed-browser/action'))return {ok:true} as any if(url.pathname.endsWith('/frame'))return {id:'frame',data:backend,width:100,height:80,generation:4} as any if(url.pathname.includes('/computer')){ if(options?.method==='POST'&&url.pathname.endsWith('/take')){ controlled=true;state.open=true;state.tabs=[{id:'tab',title:'示例页面',url:'https://example.com',active:true}] } if(options?.method==='POST'&&url.pathname.endsWith('/giveback'))controlled=false return {mode:controlled?'human':backend==='managed-browser'&&!state.open?'off':'idle',backend:backend==='managed-browser'?'managed-browser':'local',hostName:'托管浏览器',generation:4,controlId:controlled?'control':undefined,token:'fixture-token'} as any } throw new Error(`Unexpected request ${path}`) }) }) afterEach(()=>{vi.restoreAllMocks();vi.clearAllMocks()}) it.each([false,undefined])('keeps managed browsing absent with an off or older settings response (%s)',async(value)=>{ enabled=value const wrapper=mount(ComputerPanel,{props:{agents:[agent],standalone:true},global:{stubs}}) try{ await flushPromises() expect(wrapper.find('option[value="managed-browser"]').exists()).toBe(false) expect(request.mock.calls.some(([path])=>path.includes('/managed-browser'))).toBe(false) expect(request.mock.calls.some(([,options])=>options?.method==='POST')).toBe(false) }finally{wrapper.unmount()} }) it('shows the independent browser beside existing environments without opening it during preview',async()=>{ const wrapper=mount(Preview,{props:{agents:[agent],isAdmin:true,active:true},global:{stubs}}) try{ await flushPromises() for(const key of ['desktop:local','cloud','vm','managed-browser'])expect(wrapper.find(`option[value="${key}"]`).exists()).toBe(true) await wrapper.get('[aria-label="显示的桌面"]').setValue('managed-browser');await flushPromises() expect(wrapper.get('.preview').text()).toContain('浏览器尚未打开') expect(wrapper.find('.preview img').exists()).toBe(false) expect(request.mock.calls.some(([path,options])=>path.includes('managed-browser')&&options?.method==='POST')).toBe(false) const section=wrapper.get('[aria-label="托管浏览器"]') await section.get('button').trigger('click') expect(wrapper.emitted('desktop')?.at(-1)).toEqual([agent,'managed-browser',undefined]) expect(request.mock.calls.some(([path])=>path.includes('/computer/take'))).toBe(false) }finally{wrapper.unmount()} }) it('requires takeover before navigation and routes browser actions and Linux shortcuts to the managed target',async()=>{ const wrapper=mount(ComputerPanel,{props:{agents:[agent],backend:'managed-browser',standalone:true},global:{stubs}}) try{ await flushPromises() expect(wrapper.text()).toContain('浏览器尚未打开') expect(request.mock.calls.some(([,options])=>options?.method==='POST')).toBe(false) expect(wrapper.get('[aria-label="浏览器地址"]').attributes('disabled')).toBeDefined() await wrapper.findAll('button').find(button=>button.text()==='打开并控制')!.trigger('click');await flushPromises() expect(wrapper.get('.computer-screen img').attributes('src')).toContain('base64,managed-browser') expect(request.mock.calls.find(([path])=>path.includes('/computer/take'))?.[0]).toContain('backend=managed-browser') await wrapper.get('[aria-label="浏览器地址"]').setValue('https://example.org/') await wrapper.get('.browser-toolbar form').trigger('submit');await flushPromises() expect(request).toHaveBeenCalledWith('/api/app/agents/bot/managed-browser/action',{method:'POST',body:expect.objectContaining({controlId:'control',token:'fixture-token',requestId:expect.any(String),generation:4,action:{kind:'navigate',url:'https://example.org/'}})}) expect(request.mock.calls.some(([path])=>path.includes('/computer/browser')||path.endsWith('/browser'))).toBe(false) const action=request.mock.calls.find(([path])=>path.endsWith('/managed-browser/action'))?.[1]?.body expect(action).not.toHaveProperty('frameId') await wrapper.findAll('button').find(button=>button.text()==='键盘与操作')!.trigger('click') await wrapper.findAll('button').find(button=>button.text()==='全选')!.trigger('click');await flushPromises() expect(request).toHaveBeenCalledWith('/api/app/agents/bot/computer/input?backend=managed-browser',{method:'POST',body:expect.objectContaining({generation:4,frameId:'frame',action:{kind:'key',key:'a',modifiers:['ctrl']}})}) await wrapper.get('.computer-screen img').trigger('keydown',{key:'c',metaKey:true});await flushPromises() expect(request).toHaveBeenCalledWith('/api/app/agents/bot/computer/input?backend=managed-browser',{method:'POST',body:expect.objectContaining({action:{kind:'key',key:'c',modifiers:['ctrl']}})}) await wrapper.findAll('button').find(button=>button.text()==='结束控制')!.trigger('click');await flushPromises() expect(request.mock.calls.find(([path])=>path.includes('/giveback'))?.[0]).toContain('backend=managed-browser') }finally{wrapper.unmount()} }) it('never switches an unavailable requested browser to another computer',async()=>{ state.available=false;state.reason='执行节点离线' const wrapper=mount(ComputerPanel,{props:{agents:[agent],backend:'managed-browser',standalone:true,autoTake:true},global:{stubs}}) try{ await flushPromises() expect(wrapper.get('[role="alert"]').text()).toContain('所选电脑不可用') expect(request.mock.calls.some(([path])=>path.includes('/computer/take'))).toBe(false) expect(wrapper.find('.computer-screen img').exists()).toBe(false) }finally{wrapper.unmount()} }) it('ignores browser metadata that arrives after a target switch',async()=>{ state.open=true;state.tabs=[{id:'tab',title:'原页面',url:'https://example.com',active:true}] let release!:(value:unknown)=>void,count=0 const original=request.getMockImplementation()! request.mockImplementation((path,options)=>path.endsWith('/managed-browser')&&++count===2?new Promise(resolve=>{release=resolve}):original(path,options)) const wrapper=mount(ComputerPanel,{props:{agents:[agent],backend:'managed-browser',standalone:true},global:{stubs}}) try{ await flushPromises() await wrapper.get('[aria-label="切换电脑环境"]').setValue('desktop:local');await flushPromises() release({...state,tabs:[{id:'late',title:'延迟旧页面',url:'https://old.example',active:true}]});await flushPromises() expect(wrapper.findComponent(BrowserToolbar).exists()).toBe(false) expect(wrapper.text()).not.toContain('延迟旧页面') }finally{wrapper.unmount()} }) it('accepts managed browser native viewer links but rejects a host mixed into them',async()=>{ route.query={backend:'managed-browser'} const wrapper=mount(Viewer,{global:{stubs:{ComputerPanel:true}}}) try{await flushPromises();expect(wrapper.getComponent(ComputerPanel).props()).toMatchObject({backend:'managed-browser',autoTake:true})}finally{wrapper.unmount()} route.query={backend:'managed-browser',host:'local'} const invalid=mount(Viewer,{global:{stubs:{ComputerPanel:true}}}) try{await flushPromises();expect(invalid.text()).toContain('所选电脑无效');expect(invalid.findComponent(ComputerPanel).exists()).toBe(false)}finally{invalid.unmount()} })