Files
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

462 lines
26 KiB
JavaScript
Raw Permalink 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.
import {host, useQuery, useQueryClient, useValue} from '@hermes/plugin-sdk'
// Optional SDK parts (context menu components) are read off the namespace so an SDK without them still loads.
import * as sdk from '@hermes/plugin-sdk'
import {useEffect, useId, useRef, useState} from 'react'
import {jsx as h, jsxs} from 'react/jsx-runtime'
const ID = 'hermes-canopy'
const PAGE_SIZE = 200
const PERSISTED_LIMIT = 500
// Safety net against gateways that keep handing out fresh cursors (100 × 200 = 20 000 rows).
const MAX_STORED_PAGES = 100
/** An error whose message is meant for the user and may be shown verbatim. */
export class CanopyError extends Error {
name = 'CanopyError'
}
const fail = message => {throw new CanopyError(message)}
// cron runs get their own sidebar section in Hermes, they are not conversations of the bot.
const HIDDEN_SOURCES = new Set(['bot_room', 'kanban', 'tool', 'oneshot', 'cron'])
// Like the native sidebar (min_messages=1): a row that reports zero messages is an empty draft or run.
const isEmpty = r => (Number.isFinite(r?.live_message_count) ? r.live_message_count : r?.message_count) === 0
const idText = v => typeof v === 'string' && v.trim() === v && v ? v : null
const text = v => typeof v === 'string' ? v.trim() : ''
const activity = v => Number.isFinite(v) && v > 0 && v < 253402300800 ? v : 0
const identity = r => JSON.stringify([r.connectionId, r.profile, r.targetProfile, r.mode])
const collator = new Intl.Collator('de', {numeric:true})
const timeFormat = new Intl.DateTimeFormat('de', {day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})
export async function routesFor(api, connection) {
if (!idText(connection)) fail('Keine eindeutige Gateway-Verbindung.')
const routes = await api.profileRoutes()
if (!Array.isArray(routes)) fail('Profilverzeichnis nicht verfügbar.')
const byProfile = new Map()
for (const r of routes) {
if (r?.connectionId !== connection) continue
if (!idText(r.profile) || !idText(r.targetProfile) || !['local','remote'].includes(r.mode)) {
fail('Ungültige Profilroute.')
}
if (byProfile.has(r.profile) && identity(byProfile.get(r.profile)) !== identity(r)) fail('Mehrdeutige Profilroute.')
byProfile.set(r.profile,r)
}
if (!byProfile.size) fail('Keine erreichbaren Profile auf diesem Gateway.')
return [...byProfile.values()].sort((a,b)=>collator.compare(a.profile,b.profile))
}
function parseList(res, scope) {
if (res?.scope !== scope || !Array.isArray(res.sessions) || res.sessions.length > PAGE_SIZE ||
(scope === 'stored' && res.next_cursor !== null && !idText(res.next_cursor))) {
fail('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
}
return res.sessions
}
function normalized(r) {
if (r?.hidden || r?.archived || r?.auto_archived || r?.is_internal_child || isEmpty(r) ||
HIDDEN_SOURCES.has(text(r?.source).toLowerCase())) return null
if (!idText(r?.id) || !idText(r?.session_id)) {
fail('Unvollständige Session-Metadaten.')
}
const aliases = [...new Set([r.id,r.session_id,r.resolved_id,r._lineage_root_id,
...(Array.isArray(r._lineage_ids) ? r._lineage_ids : [])].filter(idText))]
return {id:r.session_id, aliases, title:text(r.title) || 'Unbenannte Unterhaltung',
lastActive:activity(r.last_active_at) || activity(r.last_active) || activity(r.started_at)}
}
// Errors that cross the desktop IPC bridge can lose their JSON-RPC frame (code/data) and keep only the
// message (see hermes-bots/rpc-errors.ts), so the message is the fallback signal when no numeric code survived.
const UNSUPPORTED_MESSAGE = /method not found|unknown method|no such method|-3260[12]\b|invalid[ _-]?params/i
// Standalone profile backends (non-canonical session.list contract) reject `scope` with 4000 and a message only, e.g.
// "invalid params for session.list: scope: Extra inputs are not permitted — … out of sync …".
const INVALID_PARAMS_CODES = new Set([4000,4001])
export function unsupportedList(error) {
const message = typeof error?.message === 'string' ? error.message : String(error ?? '')
if (typeof error?.code === 'number') {
if (error.code === -32601 || error.code === -32602) return true
if (!INVALID_PARAMS_CODES.has(error.code)) return false
const reason = error?.data?.reason
return reason === 'invalid_params' || (reason === undefined && /invalid[ _-]?params/i.test(message))
}
return UNSUPPORTED_MESSAGE.test(message)
}
/** Short technical cause for the UI, so a failure on one client can be diagnosed without devtools. */
export function errorDetail(error) {
if (error?.name === 'AbortError') return ''
const code = typeof error?.code === 'number' ? ` (${error.code})` : ''
const reason = typeof error?.data?.reason === 'string' ? ` [${error.data.reason}]` : ''
const raw = typeof error?.message === 'string' ? error.message : String(error ?? '')
const msg = raw.replace(/\s+/g,' ').trim()
return (msg.length > 180 ? `${msg.slice(0,177)}…` : msg) + code + reason
}
async function loadPersisted(api, route, signal) {
signal?.throwIfAborted()
if (typeof api.listPersistedSessions !== 'function') {
fail('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
}
const result = await api.listPersistedSessions(route,{profile:route.targetProfile,limit:PERSISTED_LIMIT})
signal?.throwIfAborted()
if (!Array.isArray(result?.sessions) || !Number.isSafeInteger(result.total) || result.total < 0 ||
result.offset !== 0 || !Number.isSafeInteger(result.limit) || result.limit < 1 || result.limit > PERSISTED_LIMIT ||
(result.errors !== undefined && !Array.isArray(result.errors))) {
fail('Die gespeicherte Sessionliste hat ein unbekanntes Format.')
}
if (result.errors?.length || result.storage?.[route.targetProfile] === 'corrupt') {
fail('Der Profilspeicher konnte nicht vollständig gelesen werden.')
}
if (result.sessions.some(row=>row?.profile !== route.targetProfile)) {
fail('Die gespeicherte Sessionliste enthält eine fremde Profilzuordnung.')
}
return {sessions:mergeRows(result.sessions.map(row=>({...row,session_id:row.id}))),liveAtLimit:false,
storedAtLimit:result.total > result.limit || result.sessions.length >= result.limit}
}
export async function loadBot(api, route, signal) {
const request = (scope, cursor) => {
signal?.throwIfAborted()
return api.requestProfile(route,'session.list',{profile:route.targetProfile,scope,
limit:PAGE_SIZE,include_hidden:false,picker:true,...(cursor ? {cursor} : {})},20000)
}
let first
try {first = await request('stored')} catch (error) {
if (!unsupportedList(error) || typeof api.listPersistedSessions !== 'function') throw error
return loadPersisted(api,route,signal)
}
if (Array.isArray(first?.sessions) && first.next_cursor === undefined &&
(first.scope === undefined || first.scope === 'stored')) return loadPersisted(api,route,signal)
const rows = [...parseList(first,'stored')]
const seen = new Set()
for (let cursor = first.next_cursor; cursor !== null;) {
if (seen.has(cursor)) fail('Wiederholter Cursor: Abruf wurde abgebrochen.')
if (seen.size + 1 >= MAX_STORED_PAGES) fail('Zu viele Seiten in der Sessionliste: Abruf wurde abgebrochen.')
seen.add(cursor)
const page = await request('stored',cursor)
rows.push(...parseList(page,'stored'))
cursor = page.next_cursor
}
const live = parseList(await request('live'),'live')
signal?.throwIfAborted()
return {sessions:mergeRows([...live,...rows]),liveAtLimit:live.length === PAGE_SIZE}
}
function mergeRows(rows) {
const identities = new Map()
// Live rows win on the navigation ID; stored rows may carry additional aliases.
for (const record of rows) {
const r = normalized(record)
if (!r) continue
const matches = [...new Set(r.aliases.map(a=>identities.get(a)).filter(Boolean))]
const merged = matches[0] ?? r
merged.aliases = [...new Set([...merged.aliases,...r.aliases,...matches.flatMap(m=>m.aliases)])]
merged.lastActive = Math.max(merged.lastActive,r.lastActive,...matches.map(m=>m.lastActive))
for (const alias of merged.aliases) identities.set(alias,merged)
}
// Most recently active first, so the initially visible rows are the relevant ones.
return [...new Set(identities.values())].sort((a,b)=>
b.lastActive - a.lastActive || collator.compare(a.title,b.title) || collator.compare(a.id,b.id))
}
const stillConnected = (api, connection) => api.state.connectionId.get() === connection && api.state.gateway.get() === 'open'
async function assertRoute(api, connection, route) {
if (!stillConnected(api,connection)) fail('Gateway ist nicht verbunden.')
const current = await routesFor(api,connection)
if (!stillConnected(api,connection) || !current.some(r=>identity(r) === identity(route))) fail('Profilroute nicht mehr verfügbar.')
}
export async function openExisting(api, connection, route, session, inventory) {
await assertRoute(api,connection,route)
const has = entry => entry.sessions?.some(s=>s.id === session.id)
if (!inventory.some(entry=>identity(entry.route) === identity(route) && has(entry))) {
fail('Die Unterhaltung ist nicht mehr verfügbar.')
}
const aliases = new Set(session.aliases)
if (inventory.some(entry=>entry.route.connectionId === connection && identity(entry.route) !== identity(route) &&
entry.sessions?.some(other=>other.aliases.some(a=>aliases.has(a))))) {
fail('Die Session-ID ist nicht eindeutig. Bitte über „Sessions“ öffnen.')
}
const owner = api.state.focusedSessionOwner?.get()
const currentId = api.state.focusedStoredSessionId?.get()
if (aliases.has(currentId) && (!owner || owner.connectionId !== connection || owner.profile !== route.profile)) {
fail('Die aktive Session-ID ist nicht eindeutig.')
}
await api.openSession(session.id,{route,intent:'in-place',awaitHydration:true,keepAllProfilesScope:true})
}
export function avatarSource(value) {
return value?.found === true && typeof value.data === 'string' && value.data.length <= 3000000 &&
/^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/]+=*$/i.test(value.data) ? value.data : null
}
// The canonical "Bot Chat" (one per bot, identified server-side by its exact title).
const BOT_CHAT_TITLE = 'Bot Chat'
// Mirrors sdk.BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS; a named import would break on older SDKs.
const BOT_CHAT_HYDRATION_MS = 60000
/** Roster summary `canonical_session` → Bot-Chat entry, or null when the gateway reports none. */
export function botChatOf(c) {
if (!idText(c?.id)) return null
const openId = idText(c.resolved_id) ?? c.id
const count = Number.isFinite(c.live_message_count) ? c.live_message_count : c.message_count
return {id:c.id, openId, aliases:[...new Set([c.id,openId])], preview:text(c.preview),
lastActive:activity(c.last_active) || activity(c.started_at),
expectHistory:Number.isFinite(count) ? count > 0 : true}
}
// include_sessions adds canonical_session: the same roster projection the built-in Bots pane polls every 5 s.
async function loadMetadata(api, route) {
const res = await api.requestProfile(route,'profiles.list',{profile:route.targetProfile,include_sessions:true},15000)
if (!Array.isArray(res?.profiles)) fail('Profilmetadaten nicht verfügbar.')
return Object.fromEntries(res.profiles.filter(p=>idText(p?.name)).map(p=>{
const botChat = botChatOf(p.canonical_session)
const last = p.last_session
return [p.name,{
name:text(p.ui_meta?.['hermes-bots']?.title) || text(p.display_name) || p.name, hasAvatar:p.has_avatar === true,
botChat, lastActive:Math.max(botChat?.lastActive ?? 0, activity(last?.last_active) || activity(last?.started_at)),
}]
}))
}
/** Bots in the chosen order: 'name' (display name A–Z) or 'recent' (latest activity first, then name). */
export function sortBots(routes, order, metaOf, activeOf = () => 0) {
const name = r => metaOf(r)?.name || r.profile
const last = r => Math.max(metaOf(r)?.lastActive ?? 0, activeOf(r) ?? 0)
return [...routes].sort((a,b)=>(order === 'recent' ? last(b) - last(a) : 0) ||
collator.compare(name(a),name(b)) || collator.compare(a.profile,b.profile))
}
/** Starts a new chat draft on the bot's own route (same door as the sidebar's per-profile "+"). */
export async function newConversation(api, connection, route) {
await assertRoute(api,connection,route)
if (typeof api.newChat !== 'function') fail('Diese Hermes-Version kann keine neue Unterhaltung für ein Plugin starten.')
api.newChat(route)
}
/**
* Opens a bot's existing Bot Chat the way the built-in Bots pane does (bots workspace, owner-scoped tab,
* stale compression tiles discarded). Never creates one: a missing Bot Chat is reported, not minted.
*/
export async function openBotChat(api, connection, route, metaRoute) {
await assertRoute(api,connection,route)
// Re-read right before opening: compression moves the lineage tip, so a polled id may be stale.
const chat = (await loadMetadata(api,metaRoute))[route.targetProfile]?.botChat
if (!chat) fail('Für diesen Bot gibt es noch keinen Bot Chat. Bitte im Reiter „Bots“ anlegen.')
if (!stillConnected(api,connection)) fail('Gateway ist nicht verbunden.')
const ownerKey = `bot:${route.connectionId}::${route.profile}`
api.focusOpenWorkspaceSession?.(ownerKey,
tile=>tile.workspaceTabTitle === BOT_CHAT_TITLE && !chat.aliases.includes(String(tile.storedSessionId)),[])
await api.openSession(chat.openId,{route,profile:route.profile,intent:'in-place',awaitHydration:true,
expectHistory:chat.expectHistory,forceResume:true,hydrationTimeoutMs:BOT_CHAT_HYDRATION_MS,keepAllProfilesScope:true,
workspaceMode:'bots',workspaceOwnerKey:ownerKey,retryHydrationTimeoutOnce:true,tabTitle:BOT_CHAT_TITLE})
return chat
}
// Positional children are static, so they go through jsxs (no key warnings); arrays of keyed items are spread in.
const el = (type, props, ...children) => children.length > 1
? jsxs(type,{...props,children})
: h(type,children.length ? {...props,children:children[0]} : props)
const sr = {color:'var(--ui-text-secondary)',fontSize:'0.85em',margin:'6px 0'}
const clip = {minWidth:0,overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis'}
const line = {display:'flex',gap:6,alignItems:'center',textAlign:'start',width:'100%'}
const control = {padding:'5px 6px',borderRadius:5,color:'inherit',cursor:'pointer'}
const list = {margin:0,padding:0,listStyle:'none'}
const message = (value, error=false) => el('p',{role:error?'alert':'status',style:sr},value)
function Avatar({route, name, enabled}) {
const image = useQuery({queryKey:[ID,'avatar',identity(route)],enabled,
queryFn:async()=>avatarSource(await host.requestProfile(route,'profiles.get_asset',{
profile:route.targetProfile,name:route.targetProfile,asset:'avatar'},12000)),staleTime:300000,retry:false})
const src = image.data
const [failed,setFailed] = useState(null)
const style = {width:23,height:23,borderRadius:'50%',flex:'0 0 auto',display:'grid',placeItems:'center',
objectFit:'cover',background:'var(--ui-stroke-secondary)',fontSize:'0.7em'}
return src && failed !== src ? el('img',{src,alt:'',style,onError:()=>setFailed(src)}) :
el('span',{'aria-hidden':true,style},(name.match(/[\p{L}\p{N}]/gu) ?? ['?']).slice(0,2).join('').toUpperCase())
}
const botKey = r => [ID,'bot',r.connectionId,identity(r)]
const stampOf = seconds => seconds ? new Date(seconds*1000) : null
function Row({title, label=title, stamp, active, disabled, onClick, accent=false}) {
return el('button',{type:'button',title,disabled,'aria-current':active?'true':undefined,onClick,style:{...line,...control,
...(accent?{fontWeight:600}:{}),...(active?{fontWeight:650,background:'var(--ui-stroke-secondary)'}:{})}},
el('span',{style:{...clip,flex:'1 1 auto'}},label),
stamp && el('time',{dateTime:stamp.toISOString(),style:{...sr,whiteSpace:'nowrap',margin:0}},timeFormat.format(stamp)))
}
// A new chat is a draft until its first message is stored, and some routes emit no sessions.changed.
// While the focused conversation of a bot is missing from its list, re-read the list for a while.
const PENDING_POLL_MS = 5000
const PENDING_POLL_MAX = 24
/** Bot header with Canopy's own right-click menu when the SDK ships the context menu components. */
function BotMenu({trigger, items}) {
const {ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator} = sdk
if (![ContextMenu,ContextMenuTrigger,ContextMenuContent,ContextMenuItem].every(Boolean)) return trigger
return h(ContextMenu,{children:[
h(ContextMenuTrigger,{asChild:true,children:trigger},'trigger'),
h(ContextMenuContent,{children:items.map((item,i)=>item === '-'
? (ContextMenuSeparator ? h(ContextMenuSeparator,{},`sep${i}`) : null)
: h(ContextMenuItem,{disabled:item.disabled,onSelect:item.onSelect,children:item.label},item.label))},'content'),
]})
}
function Bot({route, connection, meta, metaRoute, metaReady, reloadMeta, online, expanded, toggle, routes, setNotice, busy, setBusy, openLock}) {
const listId = useId()
const client = useQueryClient()
const [shown,setShown] = useState(25)
const focused = useValue(host.state.focusedStoredSessionId)
const owner = useValue(host.state.focusedSessionOwner)
const q = useQuery({queryKey:botKey(route),enabled:expanded && online,
queryFn:async ({signal})=>{
try {return await loadBot(host,route,signal)} catch (error) {
if (error?.name !== 'AbortError') console.warn(`[${ID}] session list failed for ${route.connectionId}/${route.profile}:`,errorDetail(error))
throw error
}
},staleTime:20000,
refetchInterval:expanded && online ? 90000 : false,retry:false})
const botName = meta?.name || route.profile
const botChat = meta?.botChat ?? null
const mine = owner?.connectionId === connection && owner.profile === route.profile
const guarded = (action, fallback) => async () => {
if (openLock.current) return
openLock.current = true
setNotice('')
setBusy(true)
try {await action()} catch (error) {
setNotice(error instanceof CanopyError ? error.message : fallback)
} finally {openLock.current = false; setBusy(false)}
}
const select = s => guarded(()=>openExisting(host,connection,route,s,
routes.map(r=>({route:r,sessions: client.getQueryData(botKey(r))?.sessions}))),'Unterhaltung konnte nicht geöffnet werden.')()
const selectBotChat = guarded(()=>openBotChat(host,connection,route,metaRoute),'Bot Chat konnte nicht geöffnet werden.')
// The Bot Chat has its own row; never list it twice should a gateway also return it as a regular session.
const sessions = (q.data?.sessions ?? []).filter(s=>!botChat || !s.aliases.some(a=>botChat.aliases.includes(a)))
// The conversation open right now belongs to this bot but is not listed yet (new draft, not stored yet).
const pendingId = mine && idText(focused) && q.isSuccess &&
!sessions.some(s=>s.aliases.includes(focused)) && !botChat?.aliases.includes(focused) ? focused : null
useEffect(()=>{
if (!pendingId || !expanded || !online) return
let rounds = 0
const timer = setInterval(()=>{
if (++rounds > PENDING_POLL_MAX) {clearInterval(timer); return}
void q.refetch()
},PENDING_POLL_MS)
return ()=>clearInterval(timer)
},[pendingId,expanded,online])
const refresh = () => {void q.refetch(); reloadMeta()}
const startConversation = guarded(async ()=>{
await newConversation(host,connection,route)
if (!expanded) toggle()
},'Neue Unterhaltung konnte nicht gestartet werden.')
const header = el('button',{type:'button','aria-expanded':expanded,'aria-controls':listId,onClick:toggle,
title:botName,style:{...line,...control}},
el('span',{'aria-hidden':true},expanded?'▾':'▸'),h(Avatar,{route,name:botName,enabled:online && !!meta?.hasAvatar}),
el('strong',{style:clip},botName))
return el('li',null,
h(BotMenu,{trigger:header,items:[
{label:'Neue Unterhaltung',disabled:!online || busy,onSelect:()=>void startConversation()},
{label:'Bot Chat öffnen',disabled:!online || busy || !botChat,onSelect:()=>void selectBotChat()},
'-',
{label:expanded ? 'Zuklappen' : 'Aufklappen',onSelect:toggle},
{label:'Liste aktualisieren',disabled:!online,onSelect:refresh},
]}),
el('div',{id:listId,hidden:!expanded,style:{marginInlineStart:12,paddingInlineStart:8,borderInlineStart:'1px solid var(--ui-stroke-secondary)'}},
...(!expanded ? [] : [
!online && message('Gateway nicht verbunden.'),
online && metaReady && !botChat && message('Noch kein Bot Chat – im Reiter „Bots“ anlegen.'),
botChat && el('ul',{style:list},h('li',{children:h(Row,{title:botChat.preview || BOT_CHAT_TITLE,
label:`★ ${BOT_CHAT_TITLE}`,accent:true,stamp:stampOf(botChat.lastActive),disabled:!online || busy,
active:mine && botChat.aliases.includes(focused),onClick:selectBotChat})})),
q.isPending && online && message('Unterhaltungen werden geladen …'),
q.isError && el('div',null,
message('Unterhaltungen konnten für dieses Profil nicht geladen werden.',true),
errorDetail(q.error) && el('p',{style:{...sr,fontSize:'0.78em',wordBreak:'break-word'}},`Ursache: ${errorDetail(q.error)}`),
el('button',{type:'button',style:control,disabled:!online,onClick:()=>q.refetch()},'Erneut versuchen')),
pendingId && el('ul',{style:list},h('li',{children:h(Row,{
title:'Gerade geöffnet; erscheint in der Liste, sobald Hermes sie gespeichert hat',
label:'✎ Aktuelle Unterhaltung',active:true,onClick:()=>{}})})),
q.isSuccess && !pendingId && sessions.length === 0 && message('Keine weiteren Unterhaltungen.'),
q.data?.liveAtLimit && message('Das Gateway begrenzt seine Liste laufender Sessions. Weitere aktive Unterhaltungen können fehlen.',true),
q.data?.storedAtLimit && message('Das SDK begrenzt die Kompatibilitätsliste. Weitere Unterhaltungen findest du im Reiter „Sessions“.',true),
el('ul',{style:list},...sessions.slice(0,shown).map(s=>h('li',{children:h(Row,{title:s.title,
stamp:stampOf(s.lastActive),disabled:!online || busy || q.isError,
active:mine && s.aliases.includes(focused),onClick:()=>select(s)})},s.id))),
sessions.length>shown && el('button',{type:'button',style:control,onClick:()=>setShown(n=>n+25)},'Weitere Sessions anzeigen'),
])))
}
function Overview({ctx}) {
const connection = useValue(host.state.connectionId)
const activeProfile = useValue(host.state.profile)
const online = useValue(host.state.gateway) === 'open'
const client = useQueryClient()
const openLock = useRef(false)
const [busy,setBusy] = useState(false)
const [notice,setNotice] = useState('')
const [open,setOpen] = useState(()=>{
try {const v = ctx.storage.get('expanded-v1'); return Array.isArray(v)?new Set(v.filter(idText)):new Set()} catch {return new Set()}
})
useEffect(()=>{
try {ctx.storage.set('expanded-v1',[...open])} catch {/* preferences are optional */}
},[ctx,open])
useEffect(()=>{
if (!connection || !online) return
let timer
const off = ctx.onEvent('sessions.changed',()=>{
if (timer !== undefined) return
timer = setTimeout(()=>{timer=undefined
void client.invalidateQueries({queryKey:[ID,'bot',connection]})
void client.invalidateQueries({queryKey:[ID,'profiles']})
},750)
})
return ()=>{off();clearTimeout(timer)}
},[ctx,client,connection,online])
const directory = useQuery({queryKey:[ID,'routes',connection],enabled:!!connection && online,
queryFn:()=>routesFor(host,connection),staleTime:30000,refetchInterval:online?90000:false,retry:false})
const routes = directory.data ?? []
const home = routes.find(r=>r.profile === activeProfile) ?? routes[0]
const meta = useQuery({queryKey:[ID,'profiles',home && identity(home)],enabled:!!home && online,
queryFn:()=>loadMetadata(host,home),staleTime:60000,refetchInterval:online?90000:false,retry:false})
const toggle = route => setOpen(previous=>{
const next = new Set(previous), key = identity(route)
if (next.has(key)) next.delete(key); else next.add(key)
return next
})
const [order,setOrder] = useState(()=>{
try {return ctx.storage.get('bot-order-v1') === 'recent' ? 'recent' : 'name'} catch {return 'name'}
})
useEffect(()=>{
try {ctx.storage.set('bot-order-v1',order)} catch {/* preferences are optional */}
},[ctx,order])
// Loaded conversation lists also count, so a bot moves up right after a chat even before the next roster poll.
const sorted = sortBots(routes,order,r=>meta.data?.[r.targetProfile],
r=>client.getQueryData(botKey(r))?.sessions?.[0]?.lastActive ?? 0)
const orderButton = (value, label) => el('button',{type:'button','aria-pressed':order === value,
onClick:()=>setOrder(value),style:{...control,padding:'2px 8px',fontSize:'0.85em',
...(order === value ? {background:'var(--ui-stroke-secondary)',fontWeight:600} : {})}},label)
return el('section',{'aria-label':'Bot- und Sessionübersicht',style:{height:'100%',overflow:'auto',padding:'6px 8px'}},
routes.length > 1 && el('div',{role:'group','aria-label':'Bots sortieren',
style:{display:'flex',alignItems:'center',gap:4,margin:'0 0 6px',...sr}},
el('span',null,'Sortieren:'),orderButton('name','A–Z'),orderButton('recent','Zuletzt aktiv')),
!online && message('Gateway ist nicht verbunden.'),
online && directory.isPending && message('Profile werden geladen …'),
online && directory.isError && el('div',null,message('Profilverzeichnis nicht verfügbar.',true),
el('button',{type:'button',style:control,onClick:()=>directory.refetch()},'Erneut versuchen')),
online && meta.isError && message('Anzeigenamen, Avatare und Bot Chats nicht verfügbar; Profilnamen werden verwendet.'),
notice && message(notice,true),
el('ul',{style:list},...sorted.map(route=>h(Bot,{route,connection,meta:meta.data?.[route.targetProfile],
metaRoute:home,metaReady:meta.isSuccess,reloadMeta:()=>void meta.refetch(),online:online && !directory.isError,
expanded:open.has(identity(route)),toggle:()=>toggle(route),routes,setNotice,busy,setBusy,openLock},identity(route)))))
}
export default {
id:ID,name:'Hermes Canopy',version:'0.3.0',defaultEnabled:false,
description:'Ein Baum für Bots, ihren Bot Chat und ihre bestehenden Unterhaltungen auf einem Gateway.',
register(ctx) {
ctx.register({id:'overview',area:'panes',title:'Übersicht',order:900,
data:{placement:'left',collapsible:true,hideOnly:true,dock:{pane:'sessions',pos:'center'}},
render:()=>h(Overview,{ctx})})
},
}