Files
hermes-canopy/scripts/browser-fixture.mjs
T
Mikei386andClaude Opus 5.5 352df21ff0 Bot context menu, live new conversations and bot sorting (0.3.0)
- Right-click on a bot: new conversation (host.newChat on the bot
  route), open Bot Chat, expand/collapse, refresh
- The focused conversation of a bot shows immediately as "Aktuelle
  Unterhaltung" and the list is re-read until Hermes has stored it;
  sessions.changed also refreshes Bot Chat and activity data
- Sort bots A–Z by display name or by latest activity, persisted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:02:55 +01:00

107 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Generate an offline browser fixture. Run with the directory containing the pinned React UMD files.
import {readFile,writeFile} from 'node:fs/promises'
import {join} from 'node:path'
const [deps,out,mode] = process.argv.slice(2)
if (!deps || !out) throw Error('Usage: node scripts/browser-fixture.mjs DEPENDENCY_DIR OUTPUT.html')
const react = await readFile(join(deps,'react/umd/react.production.min.js'),'utf8')
const dom = await readFile(join(deps,'react-dom/umd/react-dom.production.min.js'),'utf8')
const src = (await readFile(new URL('../plugin.js',import.meta.url),'utf8'))
.replace(/^import .+\n/gm,'').replace(/^export (?=(?:async )?function|class)/gm,'').replace(/^export default /m,'const plugin = ')
const fixture = `
const {useEffect,useId,useRef,useState}=React;
const sdk={
ContextMenu:({children})=>React.createElement(React.Fragment,null,...children),
ContextMenuTrigger:({children})=>children,
ContextMenuContent:({children})=>React.createElement('menu',{'data-menu':''},...children),
ContextMenuItem:({children,onSelect,disabled})=>React.createElement('button',{type:'button','data-menuitem':'',disabled,onClick:onSelect},children),
ContextMenuSeparator:()=>React.createElement('hr'),
};
const newChats=[];
const h=(type,props,key)=>React.createElement(type,{...props,key});
const jsxs=h;
const owner={connectionId:'fixture',profile:'ops',targetProfile:'ops',mode:'remote'};
const other={connectionId:'fixture',profile:'aaa-zeta',targetProfile:'aaa-zeta',mode:'remote'};
const atom=v=>({get:()=>v});
const actions=[], storage=new Map();
const useLegacy=${JSON.stringify(mode === 'legacy')};
const avatar='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
const fixtureSessions=Array.from({length:27},(_,i)=>({id:String(i+1),session_id:String(i+1),title:'Chat '+(i+1),source:'local',profile:'ops',started_at:1760000000}));
const host={state:{connectionId:atom('fixture'),profile:atom('ops'),gateway:atom('open'),
focusedStoredSessionId:atom('1'),focusedSessionOwner:atom(owner)},
profileRoutes:async()=>[owner,other],newChat:r=>newChats.push(r),openSession:async(id,o)=>actions.push([id,o.route,o.workspaceMode]),
focusOpenWorkspaceSession:()=>null,
listPersistedSessions:async(route,opts)=>{
if(!useLegacy||route!==owner||opts.profile!=='ops')throw Error('Unexpected fallback');
return {sessions:fixtureSessions,total:600,limit:500,offset:0};
},
requestProfile:async(_route,method,p)=>{
if(method==='profiles.list')return {profiles:[{name:'ops',display_name:'Athena',has_avatar:true,
canonical_session:{id:'bot-chat',resolved_id:'bot-chat-tip',preview:'Hallo',last_active:1760000100,message_count:2}},
{name:'aaa-zeta',display_name:'Zeta',has_avatar:false,last_session:{id:'z',last_active:1760009999}}]};
if(method==='profiles.get_asset')return {found:true,data:avatar};
if(method!=='session.list')throw Error('Unexpected RPC');
if(useLegacy)return {sessions:[]};
if(p.scope==='live')return {scope:'live',sessions:[]};
return {scope:'stored',next_cursor:null,sessions:fixtureSessions};
}};
const data=new Map();
const useQueryClient=()=>client;
const client={getQueryData:key=>data.get(JSON.stringify(key)),invalidateQueries:async()=>{}};
const useValue=a=>a.get();
function useQuery(o){
const key=JSON.stringify(o.queryKey), [s,set]=useState({});
useEffect(()=>{if(!o.enabled)return;let alive=true;const c=new AbortController();
o.queryFn({signal:c.signal}).then(v=>{if(alive){data.set(key,v);set({data:v,isSuccess:true});}},()=>{if(alive)set({isError:true});});
return ()=>{alive=false;c.abort();};
},[key,o.enabled]);
return {...s,isPending:!s.isSuccess&&!s.isError};
}
`;
const test = `
let pane;
plugin.register({register:v=>{pane=v;},storage:{get:k=>storage.get(k),set:(k,v)=>storage.set(k,v)},onEvent:()=>()=>{}});
ReactDOM.createRoot(document.getElementById('root')).render(pane.render());
const check=(v,label)=>{if(!v)throw Error(label);};
const wait=async(fn)=>{for(let n=0;n<60;n++){const v=fn();if(v)return v;await new Promise(r=>setTimeout(r,20));}throw Error('UI-Merkmal nicht gefunden');};
const button=t=>[...document.querySelectorAll('button')].find(b=>b.title===t||b.textContent===t);
window.addEventListener('error',e=>{document.body.dataset.renderError=e.message;});
(async()=>{
check(pane.data.dock.pane==='sessions'&&pane.title==='Übersicht','Dock');
const bot=await wait(()=>button('Athena'));
await wait(()=>{const img=bot.querySelector('img');return img?.getAttribute('src')===avatar&&img.complete&&img.naturalWidth>0;});
check(bot.getAttribute('aria-expanded')==='false','Initial collapsed');
bot.click();
const first=await wait(()=>button('Chat 1'));
if(useLegacy)check(document.body.textContent.includes('begrenzt die Kompatibilitätsliste'),'Missing fallback limit warning');
check(bot.getAttribute('aria-expanded')==='true'&&actions.length===0,'Toggle opened a chat');
check(first.getAttribute('aria-current')==='true','Active marker');
check(storage.get('expanded-v1')?.length===1,'Persistent expansion');
check(!button('Chat 27'),'25 rows before expansion');
button('Weitere Sessions anzeigen').click();
await wait(()=>button('Chat 27'));
first.click();
await wait(()=>actions.length);
check(actions.length===1&&actions[0][0]==='1'&&actions[0][1]===owner,'Routed existing session');
const rows=[...document.getElementById(bot.getAttribute('aria-controls')).querySelectorAll('button')].map(b=>b.textContent);
check(rows[0]?.startsWith('★ Bot Chat')&&rows.filter(t=>t.startsWith('★')).length===1,'Bot Chat is the first row');
await wait(()=>!button('Hallo').disabled);
button('Hallo').click();
await wait(()=>actions.length===2);
check(actions[1][0]==='bot-chat-tip'&&actions[1][1]===owner&&actions[1][2]==='bots','Opened Bot Chat in bots workspace');
const order=()=>[...document.querySelectorAll('button[aria-controls]')].map(b=>b.title).join(',');
check(order()==='Athena,Zeta','A-Z order by display name: '+order());
button('Zuletzt aktiv').click();
await wait(()=>order()==='Zeta,Athena');
check(storage.get('bot-order-v1')==='recent','Persisted order');
button('A–Z').click();
await wait(()=>order()==='Athena,Zeta');
const menuNew=[...document.querySelectorAll('[data-menuitem]')].find(b=>b.textContent==='Neue Unterhaltung');
menuNew.click();
await wait(()=>newChats.length===1);
check(newChats[0]===owner,'New conversation on the bot route');
check(!document.body.dataset.renderError,'Render error');
document.body.dataset.test='pass';
})().catch(e=>{document.body.dataset.test='fail';document.body.dataset.reason=e.message;});
`;
await writeFile(out,`<!doctype html><meta charset="utf-8"><title>Canopy: isolierter UI-Test</title><div id="root"></div><script>${react}</script><script>${dom}</script><script>${fixture}\n${src}\n${test}</script>`)