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:
Mikei386andClaude Opus 5.5 committed 2026-11-20 20:02:55 +01:00
1 parent a0f6c8bb1d
commit 352df21ff0
5 files changed
+149 -21

No files matched your search

+7 -2
View File
@@ -2,7 +2,7 @@
Geplante Hermes-Erweiterung: **Sessions | Bots | Übersicht**, mit einem aufklappbaren Baum **Bot → Bot Chat + Unterhaltungen**. Canopy ist für **genau ein Gateway** vorgesehen; mehrere Bots sind Profile dieses einen Gateways. Es gibt keine Gateway-Ebene im Baum und keine Unterstützung für weitere Gateways. Desktop und Webapp sind zwei getrennte Installationsziele für dasselbe Gateway. Die bestehenden Ansichten bleiben erhalten. Canopy soll nur vorhandene Unterhaltungen öffnen und selbst keine Chatdaten ändern (zur Roster-Abfrage siehe unten). Geplante Hermes-Erweiterung: **Sessions | Bots | Übersicht**, mit einem aufklappbaren Baum **Bot → Bot Chat + Unterhaltungen**. Canopy ist für **genau ein Gateway** vorgesehen; mehrere Bots sind Profile dieses einen Gateways. Es gibt keine Gateway-Ebene im Baum und keine Unterstützung für weitere Gateways. Desktop und Webapp sind zwei getrennte Installationsziele für dasselbe Gateway. Die bestehenden Ansichten bleiben erhalten. Canopy soll nur vorhandene Unterhaltungen öffnen und selbst keine Chatdaten ändern (zur Roster-Abfrage siehe unten).
**Status: 0.2.0 – Testversion.** Der Bot-Knoten klappt auf und zu. Als erste Zeile erscheint der **Bot Chat** (★) mit letzter Aktivität; ein Klick öffnet ihn im Bots-Arbeitsbereich wie im Reiter „Bots“. Darunter folgen die übrigen Unterhaltungen; ein Klick ruft die offizielle Session-Navigation auf. Der Avatar-Fix aus 0.1.1 (React #137) bleibt enthalten. **Status: 0.3.0 – Testversion.** Der Bot-Knoten klappt auf und zu. Als erste Zeile erscheint der **Bot Chat** (★) mit letzter Aktivität; ein Klick öffnet ihn im Bots-Arbeitsbereich wie im Reiter „Bots“. Darunter folgen die übrigen Unterhaltungen; ein Klick ruft die offizielle Session-Navigation auf. Der Avatar-Fix aus 0.1.1 (React #137) bleibt enthalten.
**Bot Chat (neu in 0.2.0).** Canopy liest den Bot Chat aus `canonical_session` von `profiles.list` mit `include_sessions: true`. Das ist dieselbe Roster-Abfrage, die der eingebaute Reiter „Bots“ alle 5 s stellt (serverseitig zwischengespeichert, #117257). Canopy fragt sie alle 90 s und unmittelbar vor dem Öffnen erneut ab, damit nach einer Kompression die aktuelle Lineage-Spitze geöffnet wird. Geöffnet wird mit denselben Optionen wie in `openStoredBotChat` des Bots-Plugins (`workspaceMode: 'bots'`, Owner-Schlüssel `bot:<connectionId>::<profil>`, `tabTitle: 'Bot Chat'`, `forceResume`, alte Kompressions-Tabs werden verworfen). Canopy legt **nie** einen Bot Chat an: Fehlt er, erscheint ein Hinweis auf den Reiter „Bots“. **Bot Chat (neu in 0.2.0).** Canopy liest den Bot Chat aus `canonical_session` von `profiles.list` mit `include_sessions: true`. Das ist dieselbe Roster-Abfrage, die der eingebaute Reiter „Bots“ alle 5 s stellt (serverseitig zwischengespeichert, #117257). Canopy fragt sie alle 90 s und unmittelbar vor dem Öffnen erneut ab, damit nach einer Kompression die aktuelle Lineage-Spitze geöffnet wird. Geöffnet wird mit denselben Optionen wie in `openStoredBotChat` des Bots-Plugins (`workspaceMode: 'bots'`, Owner-Schlüssel `bot:<connectionId>::<profil>`, `tabTitle: 'Bot Chat'`, `forceResume`, alte Kompressions-Tabs werden verworfen). Canopy legt **nie** einen Bot Chat an: Fehlt er, erscheint ein Hinweis auf den Reiter „Bots“.
@@ -12,6 +12,11 @@ Bekannte Grenzen: (1) Die Roster-Projektion kann einen *versehentlich* archivier
**0.2.3:** Wie die native Sessions-Seitenleiste (`min_messages=1`, Cron in eigenem Abschnitt) blendet Canopy leere Sessions (0 Nachrichten) und Cron-Läufe aus. Das betrifft vor allem die Ersatzliste, weil `host.listPersistedSessions` fest `min_messages=0` abfragt. Leere Einträge zählen dort weiter zum Limit von 500. **0.2.3:** Wie die native Sessions-Seitenleiste (`min_messages=1`, Cron in eigenem Abschnitt) blendet Canopy leere Sessions (0 Nachrichten) und Cron-Läufe aus. Das betrifft vor allem die Ersatzliste, weil `host.listPersistedSessions` fest `min_messages=0` abfragt. Leere Einträge zählen dort weiter zum Limit von 500.
**0.3.0:**
- **Rechtsklick auf einen Bot** öffnet Canopys eigenes Menü: „Neue Unterhaltung“ (über `host.newChat(route)`, dieselbe Tür wie das „+“ der Sessions-Leiste), „Bot Chat öffnen“, „Auf-/Zuklappen“ und „Liste aktualisieren“. Fehlen dem SDK die `ContextMenu`-Bausteine, bleibt das normale Menü.
- **Neue Unterhaltungen erscheinen sofort:** Gehört die gerade geöffnete Unterhaltung zu einem Bot, steht sie aber noch nicht in seiner Liste (neuer Entwurf, noch nicht gespeichert), zeigt Canopy sie als „✎ Aktuelle Unterhaltung“ und liest die Liste bis zu 2 Minuten lang alle 5 s neu, bis Hermes sie gespeichert hat. Bei `sessions.changed` werden jetzt auch Bot-Chat- und Aktivitätsdaten neu gelesen.
- **Bots sortieren:** Umschalter „A–Z“ (nach Anzeigename statt Profilkennung) und „Zuletzt aktiv“ (neueste Aktivität aus Bot Chat, letzter Session und geladener Liste). Die Wahl wird gespeichert.
Seit 0.1.3: Unterhaltungen sind nach letzter Aktivität sortiert (neueste zuerst), sodass die ersten 25 sichtbaren Zeilen die relevanten sind. Der Cursor-Scan bricht nach höchstens 100 Seiten ab, statt bei einem fehlerhaften Gateway endlos weiterzulaufen. Für Nutzer bestimmte Fehlermeldungen sind als `CanopyError` typisiert und werden vollständig angezeigt; technische Fehler erscheinen weiterhin als allgemeiner Hinweis. Mehrere Kindelemente laufen über `jsxs`, damit React im Entwicklungsmodus keine Key-Warnungen mehr meldet. Seit 0.1.3: Unterhaltungen sind nach letzter Aktivität sortiert (neueste zuerst), sodass die ersten 25 sichtbaren Zeilen die relevanten sind. Der Cursor-Scan bricht nach höchstens 100 Seiten ab, statt bei einem fehlerhaften Gateway endlos weiterzulaufen. Für Nutzer bestimmte Fehlermeldungen sind als `CanopyError` typisiert und werden vollständig angezeigt; technische Fehler erscheinen weiterhin als allgemeiner Hinweis. Mehrere Kindelemente laufen über `jsxs`, damit React im Entwicklungsmodus keine Key-Warnungen mehr meldet.
Canopy bevorzugt sämtliche gespeicherten Cursor-Seiten und ergänzt den separaten Live-Feed. Ein volles Live-Fenster (200 Zeilen, kein Cursor) wird als möglicherweise unvollständig angezeigt. Antwortet ein Profil-Backend ohne kanonischen Listenvertrag, verwendet Canopy die offizielle, profilgebundene SDK-Liste für gespeicherte Unterhaltungen. Diese Ersatzliste ist auf maximal 500 reguläre Einträge begrenzt (das SDK kann zusätzlich angeheftete Einträge liefern) und hat keinen separaten Live-Feed. Bei möglicher Abschneidung erscheint ein Hinweis. Zugriffs- und Speicherfehler werden nicht als leere Liste behandelt. Canopy bevorzugt sämtliche gespeicherten Cursor-Seiten und ergänzt den separaten Live-Feed. Ein volles Live-Fenster (200 Zeilen, kein Cursor) wird als möglicherweise unvollständig angezeigt. Antwortet ein Profil-Backend ohne kanonischen Listenvertrag, verwendet Canopy die offizielle, profilgebundene SDK-Liste für gespeicherte Unterhaltungen. Diese Ersatzliste ist auf maximal 500 reguläre Einträge begrenzt (das SDK kann zusätzlich angeheftete Einträge liefern) und hat keinen separaten Live-Feed. Bei möglicher Abschneidung erscheint ein Hinweis. Zugriffs- und Speicherfehler werden nicht als leere Liste behandelt.
@@ -58,7 +63,7 @@ Ergebnis: **3 von 3 Prüfungen erfolgreich**. Das sind Vertragsprüfungen der in
- **Praktisch geprüft:** Privates Gitea-Repo und `main` als vorgesehener Standardbranch; leeres Remote zusätzlich über SSH verifiziert; persistenter Checkout und das aktive Hermes-Projekt zeigen auf `michael/hermes-canopy`. - **Praktisch geprüft:** Privates Gitea-Repo und `main` als vorgesehener Standardbranch; leeres Remote zusätzlich über SSH verifiziert; persistenter Checkout und das aktive Hermes-Projekt zeigen auf `michael/hermes-canopy`.
- **Statisch geprüft:** Docking und Navigationspfad in den installierten Quellen; getrennte Ladewege und Browser-Routen zusätzlich im ausgelieferten Webapp-Bundle abgeglichen. - **Statisch geprüft:** Docking und Navigationspfad in den installierten Quellen; getrennte Ladewege und Browser-Routen zusätzlich im ausgelieferten Webapp-Bundle abgeglichen.
- **Automatisiert:** `node --check plugin.js` und `npm test` bzw. `node --test` (Node ≥ 22.15, geprüft mit 24 und 26). Abdeckung: Docking-Beitrag, Routing, Stored-Cursor-Scan und Abbruch, Deduplizierung, Metadatenfilter (inkl. leere Sessions und Cron), Live-Limit, Seitenlimit, Sortierung, typisierte Fehler, Bot-Chat-Erkennung und -Öffnen (Bots-Arbeitsbereich, alte Tabs, kein Anlegen), Fehler- und Leerzustände, Avatar-Fallback. - **Automatisiert:** `node --check plugin.js` und `npm test` bzw. `node --test` (Node ≥ 22.15, geprüft mit 24 und 26). Abdeckung: Docking-Beitrag, Routing, Stored-Cursor-Scan und Abbruch, Deduplizierung, Metadatenfilter (inkl. leere Sessions und Cron), Live-Limit, Seitenlimit, Sortierung, typisierte Fehler, Bot-Chat-Erkennung und -Öffnen (Bots-Arbeitsbereich, alte Tabs, kein Anlegen), Fehler- und Leerzustände, Avatar-Fallback.
- **Isolierte Browserprüfung:** Chromium mit React 18.3.1 und synthetischem SDK, einmal mit kanonischem Vertrag, einmal mit Ersatzliste und Limit-Hinweis. `scripts/browser-fixture.mjs <node_modules> <output.html> [legacy]` erzeugt den Test. Geprüft: geladenes Avatarbild, Aufklappen ohne Öffnen, Bot Chat als erste Zeile und Öffnen im Bots-Arbeitsbereich, Persistenz, aktive Markierung, zusätzliche Zeilen und Aufruf der Navigation mit dem vorgesehenen Profil. Erfolg: `data-test="pass"` im Browser-DOM. - **Isolierte Browserprüfung:** Chromium mit React 18.3.1 und synthetischem SDK, einmal mit kanonischem Vertrag, einmal mit Ersatzliste und Limit-Hinweis. `scripts/browser-fixture.mjs <node_modules> <output.html> [legacy]` erzeugt den Test. Geprüft: geladenes Avatarbild, Aufklappen ohne Öffnen, Bot Chat als erste Zeile und Öffnen im Bots-Arbeitsbereich, Bot-Sortierung samt Speicherung, „Neue Unterhaltung“ über das Kontextmenü, Persistenz, aktive Markierung, zusätzliche Zeilen und Aufruf der Navigation mit dem vorgesehenen Profil. Erfolg: `data-test="pass"` im Browser-DOM.
- **Offen:** Native Mac-App und ausgelieferte Gateway-Webapp separat mit dem echten SDK und einem Test-Gateway abnehmen. Kein produktiver Eingriff, kein Push, kein Release, kein Core-Patch. - **Offen:** Native Mac-App und ausgelieferte Gateway-Webapp separat mit dem echten SDK und einem Test-Gateway abnehmen. Kein produktiver Eingriff, kein Push, kein Release, kein Core-Patch.
## Sources ## Sources
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "hermes-canopy", "name": "hermes-canopy",
"version": "0.2.3", "version": "0.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "Ein Baum für Bots, ihren Bot Chat und ihre bestehenden Unterhaltungen auf einem Gateway.", "description": "Ein Baum für Bots, ihren Bot Chat und ihre bestehenden Unterhaltungen auf einem Gateway.",
+97 -14
View File
@@ -1,4 +1,6 @@
import {host, useQuery, useQueryClient, useValue} from '@hermes/plugin-sdk' 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 {useEffect, useId, useRef, useState} from 'react'
import {jsx as h, jsxs} from 'react/jsx-runtime' import {jsx as h, jsxs} from 'react/jsx-runtime'
@@ -206,10 +208,29 @@ export function botChatOf(c) {
async function loadMetadata(api, route) { async function loadMetadata(api, route) {
const res = await api.requestProfile(route,'profiles.list',{profile:route.targetProfile,include_sessions:true},15000) 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.') if (!Array.isArray(res?.profiles)) fail('Profilmetadaten nicht verfügbar.')
return Object.fromEntries(res.profiles.filter(p=>idText(p?.name)).map(p=>[p.name,{ return Object.fromEntries(res.profiles.filter(p=>idText(p?.name)).map(p=>{
name:text(p.ui_meta?.['hermes-bots']?.title) || text(p.display_name) || p.name, hasAvatar:p.has_avatar === true, const botChat = botChatOf(p.canonical_session)
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))) 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 listId = useId()
const client = useQueryClient() const client = useQueryClient()
const [shown,setShown] = useState(25) 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.') 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. // 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))) 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, return el('li',null,
el('button',{type:'button','aria-expanded':expanded,'aria-controls':listId,onClick:toggle, h(BotMenu,{trigger:header,items:[
title:botName,style:{...line,...control}}, {label:'Neue Unterhaltung',disabled:!online || busy,onSelect:()=>void startConversation()},
el('span',{'aria-hidden':true},expanded?'▾':'▸'),h(Avatar,{route,name:botName,enabled:online && !!meta?.hasAvatar}), {label:'Bot Chat öffnen',disabled:!online || busy || !botChat,onSelect:()=>void selectBotChat()},
el('strong',{style:clip},botName)), '-',
{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)'}}, el('div',{id:listId,hidden:!expanded,style:{marginInlineStart:12,paddingInlineStart:8,borderInlineStart:'1px solid var(--ui-stroke-secondary)'}},
...(!expanded ? [] : [ ...(!expanded ? [] : [
!online && message('Gateway nicht verbunden.'), !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), 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)}`), 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')), 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?.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), 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, 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 let timer
const off = ctx.onEvent('sessions.changed',()=>{ const off = ctx.onEvent('sessions.changed',()=>{
if (timer !== undefined) return 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)} return ()=>{off();clearTimeout(timer)}
},[ctx,client,connection,online]) },[ctx,client,connection,online])
@@ -355,20 +423,35 @@ function Overview({ctx}) {
if (next.has(key)) next.delete(key); else next.add(key) if (next.has(key)) next.delete(key); else next.add(key)
return next 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'}}, 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 && message('Gateway ist nicht verbunden.'),
online && directory.isPending && message('Profile werden geladen …'), online && directory.isPending && message('Profile werden geladen …'),
online && directory.isError && el('div',null,message('Profilverzeichnis nicht verfügbar.',true), online && directory.isError && el('div',null,message('Profilverzeichnis nicht verfügbar.',true),
el('button',{type:'button',style:control,onClick:()=>directory.refetch()},'Erneut versuchen')), 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.'), online && meta.isError && message('Anzeigenamen, Avatare und Bot Chats nicht verfügbar; Profilnamen werden verwendet.'),
notice && message(notice,true), notice && message(notice,true),
el('ul',{style:list},...routes.map(route=>h(Bot,{route,connection,meta:meta.data?.[route.targetProfile], el('ul',{style:list},...sorted.map(route=>h(Bot,{route,connection,meta:meta.data?.[route.targetProfile],
metaRoute:home,metaReady:meta.isSuccess,online:online && !directory.isError, 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))))) expanded:open.has(identity(route)),toggle:()=>toggle(route),routes,setNotice,busy,setBusy,openLock},identity(route)))))
} }
export default { 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.', description:'Ein Baum für Bots, ihren Bot Chat und ihre bestehenden Unterhaltungen auf einem Gateway.',
register(ctx) { register(ctx) {
ctx.register({id:'overview',area:'panes',title:'Übersicht',order:900, ctx.register({id:'overview',area:'panes',title:'Übersicht',order:900,
+24 -3
View File
@@ -9,9 +9,18 @@ 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 = ') .replace(/^import .+\n/gm,'').replace(/^export (?=(?:async )?function|class)/gm,'').replace(/^export default /m,'const plugin = ')
const fixture = ` const fixture = `
const {useEffect,useId,useRef,useState}=React; 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 h=(type,props,key)=>React.createElement(type,{...props,key});
const jsxs=h; const jsxs=h;
const owner={connectionId:'fixture',profile:'ops',targetProfile:'ops',mode:'remote'}; 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 atom=v=>({get:()=>v});
const actions=[], storage=new Map(); const actions=[], storage=new Map();
const useLegacy=${JSON.stringify(mode === 'legacy')}; const useLegacy=${JSON.stringify(mode === 'legacy')};
@@ -19,7 +28,7 @@ const avatar='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAAB
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 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'), const host={state:{connectionId:atom('fixture'),profile:atom('ops'),gateway:atom('open'),
focusedStoredSessionId:atom('1'),focusedSessionOwner:atom(owner)}, focusedStoredSessionId:atom('1'),focusedSessionOwner:atom(owner)},
profileRoutes:async()=>[owner],openSession:async(id,o)=>actions.push([id,o.route,o.workspaceMode]), profileRoutes:async()=>[owner,other],newChat:r=>newChats.push(r),openSession:async(id,o)=>actions.push([id,o.route,o.workspaceMode]),
focusOpenWorkspaceSession:()=>null, focusOpenWorkspaceSession:()=>null,
listPersistedSessions:async(route,opts)=>{ listPersistedSessions:async(route,opts)=>{
if(!useLegacy||route!==owner||opts.profile!=='ops')throw Error('Unexpected fallback'); if(!useLegacy||route!==owner||opts.profile!=='ops')throw Error('Unexpected fallback');
@@ -27,7 +36,8 @@ const host={state:{connectionId:atom('fixture'),profile:atom('ops'),gateway:atom
}, },
requestProfile:async(_route,method,p)=>{ requestProfile:async(_route,method,p)=>{
if(method==='profiles.list')return {profiles:[{name:'ops',display_name:'Athena',has_avatar:true, 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}}]}; 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==='profiles.get_asset')return {found:true,data:avatar};
if(method!=='session.list')throw Error('Unexpected RPC'); if(method!=='session.list')throw Error('Unexpected RPC');
if(useLegacy)return {sessions:[]}; if(useLegacy)return {sessions:[]};
@@ -72,12 +82,23 @@ window.addEventListener('error',e=>{document.body.dataset.renderError=e.message;
first.click(); first.click();
await wait(()=>actions.length); await wait(()=>actions.length);
check(actions.length===1&&actions[0][0]==='1'&&actions[0][1]===owner,'Routed existing session'); check(actions.length===1&&actions[0][0]==='1'&&actions[0][1]===owner,'Routed existing session');
const rows=[...document.querySelectorAll('[aria-controls] + div button')].map(b=>b.textContent); 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'); check(rows[0]?.startsWith('★ Bot Chat')&&rows.filter(t=>t.startsWith('★')).length===1,'Bot Chat is the first row');
await wait(()=>!button('Hallo').disabled); await wait(()=>!button('Hallo').disabled);
button('Hallo').click(); button('Hallo').click();
await wait(()=>actions.length===2); 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'); 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'); check(!document.body.dataset.renderError,'Render error');
document.body.dataset.test='pass'; document.body.dataset.test='pass';
})().catch(e=>{document.body.dataset.test='fail';document.body.dataset.reason=e.message;}); })().catch(e=>{document.body.dataset.test='fail';document.body.dataset.reason=e.message;});
+20 -1
View File
@@ -7,7 +7,7 @@ const hooks = registerHooks({resolve(specifier, context, next) {
if (specifier === 'react/jsx-runtime') return {url: 'data:text/javascript,export const jsx=(type,props)=>({type,props}),jsxs=(type,props)=>({type,props})', 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) return next(specifier, context)
}}) }})
const {default: plugin, routesFor, loadBot, openExisting, openBotChat, botChatOf, avatarSource, CanopyError, unsupportedList, errorDetail} = await import('../plugin.js') const {default: plugin, routesFor, loadBot, openExisting, openBotChat, botChatOf, avatarSource, CanopyError, unsupportedList, errorDetail, sortBots, newConversation} = await import('../plugin.js')
hooks.deregister() hooks.deregister()
const route = {connectionId:'g', profile:'work',targetProfile:'work',mode:'remote'} const route = {connectionId:'g', profile:'work',targetProfile:'work',mode:'remote'}
const state = name => ({get:()=>name}) const state = name => ({get:()=>name})
@@ -207,3 +207,22 @@ test('empty sessions and cron runs are hidden like in the native sidebar', async
{id:'unknown',source:'gui',profile:'work'}],total:6,limit:500,offset:0,errors:[]})},route) {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']) 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)
})