import {test} from 'node:test' import assert from 'node:assert/strict' import {registerHooks} from 'node:module' const hooks = registerHooks({resolve(specifier, context, next) { if (specifier === '@hermes/plugin-sdk') return {url: 'data:text/javascript,export const host={},useValue=()=>{},useQuery=()=>{},useQueryClient=()=>{}', shortCircuit:true} if (specifier === 'react') return {url: 'data:text/javascript,export const useEffect=()=>{},useState=()=>{},useId=()=>{},useRef=()=>{}', shortCircuit:true} if (specifier === 'react/jsx-runtime') return {url: 'data:text/javascript,export const jsx=(type,props)=>({type,props}),jsxs=(type,props)=>({type,props})', shortCircuit:true} return next(specifier, context) }}) const {default: plugin, routesFor, loadBot, openExisting, openBotChat, botChatOf, avatarSource, CanopyError, unsupportedList, errorDetail, sortBots, newConversation} = await import('../plugin.js') hooks.deregister() const route = {connectionId:'g', profile:'work',targetProfile:'work',mode:'remote'} const state = name => ({get:()=>name}) const row = (id, extra={}) => ({id,session_id:id,source:'local',title:id, ...extra}) const page = (sessions, next_cursor=null) => ({scope:'stored',sessions,next_cursor}) const live = sessions => ({scope:'live',sessions}) test('registers opt-in Overview in the Sessions group', () => { const registrations=[] plugin.register({register: v=>registrations.push(v)}) assert.equal(plugin.defaultEnabled,false) assert.equal(registrations[0].title,'Übersicht') assert.deepEqual(registrations[0].data.dock,{pane:'sessions',pos:'center'}) }) test('route inventory only includes the current gateway, no name-only routing', async () => { const host={profileRoutes: async()=>[route, {...route, connectionId:'other'},route]} assert.deepEqual(await routesFor(host,'g'),[route]) await assert.rejects(routesFor(host,'missing')) }) test('pages completely, merges live and stored aliases, filters internal and archive metadata', async () => { const calls=[] const result=await loadBot({requestProfile: async (owner,method,p)=>{ assert.equal(owner,route) assert.equal(method,'session.list') assert.equal(p.include_hidden,false) assert.ok(!('title' in p)) calls.push(p) if (p.scope==='live') return live([row('a',{last_active_at:10}),row('room',{source:'bot_room'})]) if (!p.cursor) return page([row('root',{resolved_id:'a',session_id:'a'}),row('job',{source:'kanban'}),row('old',{archived:true})],'next') return page([row('b'),row('b'),row('helper',{source:'tool'}),row('hidden',{hidden:true})]) }},route) assert.deepEqual(result.sessions.map(r=>r.id),['a','b']) assert.deepEqual(result.sessions[0].aliases,['a','root']) assert.equal(calls.filter(c=>c.cursor==='next').length,1) }) test('empty lists are supported; legacy responses and repeating cursors fail closed', async () => { assert.deepEqual(await loadBot({requestProfile:async (_,__,p)=>p.scope==='live'?live([]):page([])},route),{sessions:[],liveAtLimit:false}) await assert.rejects(loadBot({requestProfile:async()=>({sessions:[]})},route), /Pagination|Vertrag/) await assert.rejects(loadBot({requestProfile:async()=>page([], 'loop')},route),/Cursor/) }) test('request error is not an empty bot', async () => { await assert.rejects(loadBot({requestProfile: async()=>{throw Error('offline')}},route),/offline/) }) test('a legacy session.list response uses only the scoped SDK metadata fallback and flags its cap', async () => { const res=await loadBot({requestProfile:async()=>({sessions:[]}),listPersistedSessions:async(owner, options)=>{ assert.equal(owner,route) assert.deepEqual(options,{profile:'work',limit:500}) return {sessions:[{id:'kept',source:'gui',profile:'work',last_active:123}, {id:'group',source:'bot_room',profile:'work'},{id:'old',source:'gui',profile:'work',archived:true}], total:580,limit:500,offset:0,errors:[],storage:{}} }},route) assert.deepEqual(res.sessions.map(r=>[r.id,r.lastActive]),[['kept',123]]) assert.equal(res.storedAtLimit,true) }) test('unsupported query arguments can fall back but permission and storage errors may not look empty', async () => { const unsupported=async()=>{throw {code:4001,data:{reason:'invalid_params'}}} const empty=async()=>({sessions:[],total:0,limit:500,offset:0,errors:[]}) assert.equal((await loadBot({requestProfile:unsupported,listPersistedSessions:empty},route)).sessions.length,0) await assert.rejects(loadBot({requestProfile:async()=>{throw Error('permission_denied')}, listPersistedSessions:async()=>assert.fail('must not fall back')},route),/permission_denied/) await assert.rejects(loadBot({requestProfile:unsupported,listPersistedSessions:async()=>({ ...(await empty()),errors:[{profile:'work',error:'locked'}]})},route),/Profilspeicher/) await assert.rejects(loadBot({requestProfile:unsupported,listPersistedSessions:async()=>({ ...(await empty()),sessions:[{id:'wrong',profile:'other',source:'gui'}]})},route),/Profil/) }) test('a full live window is flagged, not presented as complete', async () => { const res=await loadBot({requestProfile:async (_,__,p)=>p.scope==='live' ?live(Array.from({length:200},(_,n)=>row(String(n)))):page([])},route) assert.equal(res.sessions.length,200) assert.equal(res.liveAtLimit,true) }) test('a cancelled page scan does not ask the host for more pages', async () => { const controller=new AbortController() let calls=0 await assert.rejects(loadBot({requestProfile:async()=>{ calls++ controller.abort() return page([], 'next') }},route,controller.signal),{name:'AbortError'}) assert.equal(calls,1) }) test('opens only on the scoped route, refuses missing inventory and cross-profile aliases', async () => { const calls=[] const host={state:{connectionId:state('g'),gateway:state('open')},profileRoutes:async()=>[route],openSession:async (...args)=>calls.push(args)} const session={id:'a',aliases:['a','root']} await openExisting(host,'g',route,session,[{route,sessions:[session]}]) assert.equal(calls[0][0],'a'); assert.equal(calls[0][1].route,route) await assert.rejects(openExisting(host,'g',route,session,[{route,sessions:[]}]),/verfügbar/) await assert.rejects(openExisting(host,'g',route,session,[{route,sessions:[session]},{route:{...route,profile:'b'},sessions:[{id:'root',aliases:['root']}]}]),/eindeutig/) assert.equal(calls.length,1) }) test('avatar only accepts raster data or falls back to initials', ()=>{ assert.equal(avatarSource({found:true,data:'data:image/png;base64,aGk='}),'data:image/png;base64,aGk=') assert.equal(avatarSource({found:true,data:'data:image/svg+xml;base64,aGk='}),null) assert.equal(avatarSource({found:false}),null) }) test('sorts by last activity first, then by title', async () => { const res=await loadBot({requestProfile:async (_,__,p)=>p.scope==='live'?live([]):page([ row('alt',{title:'Alpha',last_active_at:100}),row('neu',{title:'Zulu',last_active_at:200}),row('ohne',{title:'Beta'})])},route) assert.deepEqual(res.sessions.map(r=>r.id),['neu','alt','ohne']) }) test('an endless chain of fresh cursors is cut off', async () => { let n=0 await assert.rejects(loadBot({requestProfile:async (_,__,p)=>p.scope==='live'?live([]):page([], `c${++n}`)},route), err=>err instanceof CanopyError && /Zu viele Seiten/.test(err.message)) assert.equal(n,100) }) test('user-facing errors are typed, transport errors are not', async () => { await assert.rejects(routesFor({profileRoutes:async()=>[]},'g'),CanopyError) await assert.rejects(loadBot({requestProfile:async()=>{throw Error('offline')}},route), err=>!(err instanceof CanopyError)) }) test('reads the Bot Chat summary from the roster projection, preferring the compression tip', () => { assert.deepEqual(botChatOf({id:'reg',resolved_id:'tip',preview:' hi ',last_active:50,live_message_count:0}), {id:'reg',openId:'tip',aliases:['reg','tip'],preview:'hi',lastActive:50,expectHistory:false}) assert.equal(botChatOf({id:'reg'}).openId,'reg') assert.equal(botChatOf({id:'reg'}).expectHistory,true) assert.equal(botChatOf(null),null) assert.equal(botChatOf({id:''}),null) }) const botChatHost = (canonical, extra={}) => { const calls={open:[],rpc:[],focus:[]} return {calls, host:{state:{connectionId:state('g'),gateway:state('open')},profileRoutes:async()=>[route], requestProfile:async (owner,method,p)=>{ calls.rpc.push([method,p]) assert.equal(method,'profiles.list') assert.equal(p.include_sessions,true) return {profiles:[{name:'work',canonical_session:canonical}]} }, focusOpenWorkspaceSession:(...args)=>calls.focus.push(args), openSession:async (...args)=>calls.open.push(args), ...extra}} } test('opens the Bot Chat in the bots workspace like the built-in Bots pane', async () => { const {host,calls}=botChatHost({id:'reg',resolved_id:'tip',message_count:3}) await openBotChat(host,'g',route,route) const [id,o]=calls.open[0] assert.equal(id,'tip') assert.equal(o.route,route) assert.equal(o.workspaceMode,'bots') assert.equal(o.workspaceOwnerKey,'bot:g::work') assert.equal(o.tabTitle,'Bot Chat') assert.equal(o.forceResume,true) assert.equal(o.expectHistory,true) const [key,isStale,only]=calls.focus[0] assert.equal(key,'bot:g::work'); assert.deepEqual(only,[]) assert.equal(isStale({storedSessionId:'old-segment',workspaceTabTitle:'Bot Chat'}),true) assert.equal(isStale({storedSessionId:'tip',workspaceTabTitle:'Bot Chat'}),false) assert.equal(isStale({storedSessionId:'x',workspaceTabTitle:'Other'}),false) }) test('a missing Bot Chat is reported and never created', async () => { const {host,calls}=botChatHost(null) await assert.rejects(openBotChat(host,'g',route,route),err=>err instanceof CanopyError && /noch keinen Bot Chat/.test(err.message)) assert.equal(calls.open.length,0) assert.ok(calls.rpc.every(([method])=>method==='profiles.list')) }) test('Bot Chat open refuses a disconnected gateway or a vanished route', async () => { const offline=botChatHost({id:'reg'},{state:{connectionId:state('g'),gateway:state('closed')}}) await assert.rejects(openBotChat(offline.host,'g',route,route),/nicht verbunden/) const moved=botChatHost({id:'reg'},{profileRoutes:async()=>[{...route,profile:'other',targetProfile:'other'}]}) await assert.rejects(openBotChat(moved.host,'g',route,route),/Profilroute/) assert.equal(offline.calls.open.length+moved.calls.open.length,0) }) test('fallback detection survives errors that lost their JSON-RPC code across IPC', async () => { assert.equal(unsupportedList({code:-32601}),true) assert.equal(unsupportedList({code:4001,data:{reason:'invalid_params'}}),true) assert.equal(unsupportedList({code:4001,data:{reason:'permission_denied'}}),false) assert.equal(unsupportedList({code:4003,message:'invalid_params'}),false) assert.equal(unsupportedList(Error("Error invoking remote method 'hermes:gateway': Error: invalid_params")),true) assert.equal(unsupportedList(Error('Method not found: session.list')),true) assert.equal(unsupportedList(Error('permission_denied')),false) const empty=async()=>({sessions:[],total:0,limit:500,offset:0,errors:[]}) const res=await loadBot({requestProfile:async()=>{throw Error('Error: invalid_params')},listPersistedSessions:empty},route) assert.equal(res.sessions.length,0) }) test('error detail names the technical cause compactly', () => { assert.equal(errorDetail({message:' request timed out\nafter 20s ',code:4001,data:{reason:'invalid_params'}}), 'request timed out after 20s (4001) [invalid_params]') assert.equal(errorDetail({name:'AbortError',message:'x'}),'') assert.equal(errorDetail(Error('x'.repeat(300))).length,178) }) test('a profile backend without the canonical contract rejecting scope with 4000 falls back to the SDK list', async () => { const scopeRejected={code:4000,message:'invalid params for session.list: scope: Extra inputs are not permitted — the client and the Hermes backend are out of sync (different versions); run `hermes update` and restart'} assert.equal(unsupportedList(scopeRejected),true) assert.equal(unsupportedList({code:4000,message:'permission denied'}),false) assert.equal(unsupportedList({code:4000,message:'invalid params',data:{reason:'profile_mismatch'}}),false) const res=await loadBot({requestProfile:async()=>{throw scopeRejected}, listPersistedSessions:async()=>({sessions:[{id:'kept',source:'gui',profile:'work'}],total:1,limit:500,offset:0,errors:[]})},route) assert.deepEqual(res.sessions.map(s=>s.id),['kept']) }) test('empty sessions and cron runs are hidden like in the native sidebar', async () => { const res=await loadBot({requestProfile:async()=>({sessions:[]}),listPersistedSessions:async()=>({sessions:[ {id:'chat',source:'gui',profile:'work',message_count:4}, {id:'empty',source:'gui',profile:'work',message_count:0}, {id:'nightly',source:'cron',profile:'work',message_count:3}, {id:'Nightly',source:' CRON ',profile:'work',message_count:3}, {id:'live',source:'gui',profile:'work',message_count:0,live_message_count:2}, {id:'unknown',source:'gui',profile:'work'}],total:6,limit:500,offset:0,errors:[]})},route) assert.deepEqual(res.sessions.map(s=>s.id).sort(),['chat','live','unknown']) }) test('bots sort by display name or by latest activity', () => { const a={connectionId:'g',profile:'default',targetProfile:'default',mode:'remote'} const b={...a,profile:'athena-deck',targetProfile:'athena-deck'} const c={...a,profile:'zulu',targetProfile:'zulu'} const meta={default:{name:'Athena',lastActive:10},'athena-deck':{name:'Athena Deck',lastActive:30},zulu:{name:'Bravo'}} const of=r=>meta[r.targetProfile] assert.deepEqual(sortBots([c,b,a],'name',of).map(r=>r.profile),['default','athena-deck','zulu']) assert.deepEqual(sortBots([a,b,c],'recent',of).map(r=>r.profile),['athena-deck','default','zulu']) assert.deepEqual(sortBots([a,b,c],'recent',of,r=>r.profile==='zulu'?99:0).map(r=>r.profile),['zulu','athena-deck','default']) }) test('a new conversation starts on the bot route after checking it is still current', async () => { const calls=[] const host={state:{connectionId:state('g'),gateway:state('open')},profileRoutes:async()=>[route],newChat:r=>calls.push(r)} await newConversation(host,'g',route) assert.deepEqual(calls,[route]) await assert.rejects(newConversation({...host,newChat:undefined},'g',route),CanopyError) await assert.rejects(newConversation({...host,profileRoutes:async()=>[]},'g',route),/Profil/) assert.equal(calls.length,1) })