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>
This commit is contained in:
1 parent
a0f6c8bb1d
commit
352df21ff0
5 files changed
+149
-21
No files matched your search
@@ -1,4 +1,6 @@
|
||||
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'
|
||||
|
||||
@@ -206,10 +208,29 @@ export function botChatOf(c) {
|
||||
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=>[p.name,{
|
||||
name:text(p.ui_meta?.['hermes-bots']?.title) || text(p.display_name) || p.name, hasAvatar:p.has_avatar === true,
|
||||
botChat:botChatOf(p.canonical_session),
|
||||
}]))
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -263,7 +284,24 @@ function Row({title, label=title, stamp, active, disabled, onClick, accent=false
|
||||
stamp && el('time',{dateTime:stamp.toISOString(),style:{...sr,whiteSpace:'nowrap',margin:0}},timeFormat.format(stamp)))
|
||||
}
|
||||
|
||||
function Bot({route, connection, meta, metaRoute, metaReady, online, expanded, toggle, routes, setNotice, busy, setBusy, openLock}) {
|
||||
// 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)
|
||||
@@ -294,11 +332,35 @@ function Bot({route, connection, meta, metaRoute, metaReady, online, expanded, t
|
||||
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,
|
||||
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)),
|
||||
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.'),
|
||||
@@ -311,7 +373,10 @@ function Bot({route, connection, meta, metaRoute, metaReady, online, expanded, t
|
||||
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')),
|
||||
q.isSuccess && sessions.length === 0 && message('Keine weiteren Unterhaltungen.'),
|
||||
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,
|
||||
@@ -340,7 +405,10 @@ function Overview({ctx}) {
|
||||
let timer
|
||||
const off = ctx.onEvent('sessions.changed',()=>{
|
||||
if (timer !== undefined) return
|
||||
timer = setTimeout(()=>{timer=undefined; void client.invalidateQueries({queryKey:[ID,'bot',connection]})},750)
|
||||
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])
|
||||
@@ -355,20 +423,35 @@ function Overview({ctx}) {
|
||||
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},...routes.map(route=>h(Bot,{route,connection,meta:meta.data?.[route.targetProfile],
|
||||
metaRoute:home,metaReady:meta.isSuccess,online:online && !directory.isError,
|
||||
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.2.3',defaultEnabled:false,
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user