Show each bot's Bot Chat in Canopy and harden the session tree (0.2.0)
- Bot Chat as the first row under each bot, read from the roster projection (profiles.list include_sessions) and opened in the bots workspace like the built-in Bots pane; never created by Canopy - Sort conversations by last activity, cap the stored-cursor scan at 100 pages, typed CanopyError for user-facing messages - jsxs for static children (no React key warnings), useRef for the lock - package.json with npm test, .gitignore, tests and browser fixture Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a8b2459dbc
commit
e0a147e2e8
6 files changed
+225
-66
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
__pycache__/
|
||||||
|
node_modules/
|
||||||
|
*.zip
|
||||||
|
.DS_Store
|
||||||
@@ -1,8 +1,14 @@
|
|||||||
# Hermes Canopy
|
# Hermes Canopy
|
||||||
|
|
||||||
Geplante Hermes-Erweiterung: **Sessions | Bots | Übersicht**, mit einem aufklappbaren Baum **Bot → 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 keine Chatdaten ändern.
|
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.1.2 – Testversion.** Der Bot-Knoten klappt auf und zu; ein Klick auf eine Unterhaltung ruft die offizielle Session-Navigation auf. Der kanonische „Bot Chat“ bleibt im Reiter „Bots“: Canopy fragt seine Identität nicht ab. Der Avatar-Fix aus 0.1.1 (React #137) bleibt enthalten.
|
**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.
|
||||||
|
|
||||||
|
**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“.
|
||||||
|
|
||||||
|
Bekannte Grenzen: (1) Die Roster-Projektion kann einen *versehentlich* archivierten Bot Chat (wiederherstellbarer End-Grund, #92687) beim Lesen wieder entarchivieren – genau wie der Bots-Reiter es ohnehin tut. (2) Sie meldet Lesefehler als „kein Bot Chat“; Canopy zeigt dann nur den Hinweis und erzeugt nichts. (3) Der Öffnen-Aufruf bildet interne Logik des Bots-Plugins nach (Stand `apps/desktop/src/plugins/hermes-bots/canonical-chat.ts`, Hermes-Checkout `caafe5389a`) und muss nach Hermes-Updates geprüft werden.
|
||||||
|
|
||||||
|
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. Bei einem erkennbar älteren Abfragevertrag verwendet 0.1.2 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. Bei einem erkennbar älteren Abfragevertrag verwendet 0.1.2 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.
|
||||||
|
|
||||||
@@ -47,8 +53,8 @@ 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 `node --test` (Node 26). Abdeckung: Docking-Beitrag, Routing, Stored-Cursor-Scan und Abbruch, Deduplizierung, Metadatenfilter, Live-Limit, 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, 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, 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, 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
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"name": "hermes-canopy",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"description": "Ein Baum für Bots, ihren Bot Chat und ihre bestehenden Unterhaltungen auf einem Gateway.",
|
||||||
|
"engines": {"node": ">=22.15"},
|
||||||
|
"scripts": {
|
||||||
|
"check": "node --check plugin.js",
|
||||||
|
"test": "node --check plugin.js && node --test"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,18 @@
|
|||||||
import {host, useQuery, useQueryClient, useValue} from '@hermes/plugin-sdk'
|
import {host, useQuery, useQueryClient, useValue} from '@hermes/plugin-sdk'
|
||||||
import {useEffect, useId, useState} from 'react'
|
import {useEffect, useId, useRef, useState} from 'react'
|
||||||
import {jsx as h} from 'react/jsx-runtime'
|
import {jsx as h, jsxs} from 'react/jsx-runtime'
|
||||||
|
|
||||||
const ID = 'hermes-canopy'
|
const ID = 'hermes-canopy'
|
||||||
const PAGE_SIZE = 200
|
const PAGE_SIZE = 200
|
||||||
const PERSISTED_LIMIT = 500
|
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)}
|
||||||
const HIDDEN_SOURCES = new Set(['bot_room', 'kanban', 'tool', 'oneshot'])
|
const HIDDEN_SOURCES = new Set(['bot_room', 'kanban', 'tool', 'oneshot'])
|
||||||
const idText = v => typeof v === 'string' && v.trim() === v && v ? v : null
|
const idText = v => typeof v === 'string' && v.trim() === v && v ? v : null
|
||||||
const text = v => typeof v === 'string' ? v.trim() : ''
|
const text = v => typeof v === 'string' ? v.trim() : ''
|
||||||
@@ -14,26 +22,26 @@ 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'})
|
const timeFormat = new Intl.DateTimeFormat('de', {day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})
|
||||||
|
|
||||||
export async function routesFor(api, connection) {
|
export async function routesFor(api, connection) {
|
||||||
if (!idText(connection)) throw Error('Keine eindeutige Gateway-Verbindung.')
|
if (!idText(connection)) fail('Keine eindeutige Gateway-Verbindung.')
|
||||||
const routes = await api.profileRoutes()
|
const routes = await api.profileRoutes()
|
||||||
if (!Array.isArray(routes)) throw Error('Profilverzeichnis nicht verfügbar.')
|
if (!Array.isArray(routes)) fail('Profilverzeichnis nicht verfügbar.')
|
||||||
const byProfile = new Map()
|
const byProfile = new Map()
|
||||||
for (const r of routes) {
|
for (const r of routes) {
|
||||||
if (r?.connectionId !== connection) continue
|
if (r?.connectionId !== connection) continue
|
||||||
if (!idText(r.profile) || !idText(r.targetProfile) || !['local','remote'].includes(r.mode)) {
|
if (!idText(r.profile) || !idText(r.targetProfile) || !['local','remote'].includes(r.mode)) {
|
||||||
throw Error('Ungültige Profilroute.')
|
fail('Ungültige Profilroute.')
|
||||||
}
|
}
|
||||||
if (byProfile.has(r.profile) && identity(byProfile.get(r.profile)) !== identity(r)) throw Error('Mehrdeutige Profilroute.')
|
if (byProfile.has(r.profile) && identity(byProfile.get(r.profile)) !== identity(r)) fail('Mehrdeutige Profilroute.')
|
||||||
byProfile.set(r.profile,r)
|
byProfile.set(r.profile,r)
|
||||||
}
|
}
|
||||||
if (!byProfile.size) throw Error('Keine erreichbaren Profile auf diesem Gateway.')
|
if (!byProfile.size) fail('Keine erreichbaren Profile auf diesem Gateway.')
|
||||||
return [...byProfile.values()].sort((a,b)=>collator.compare(a.profile,b.profile))
|
return [...byProfile.values()].sort((a,b)=>collator.compare(a.profile,b.profile))
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseList(res, scope) {
|
function parseList(res, scope) {
|
||||||
if (res?.scope !== scope || !Array.isArray(res.sessions) || res.sessions.length > PAGE_SIZE ||
|
if (res?.scope !== scope || !Array.isArray(res.sessions) || res.sessions.length > PAGE_SIZE ||
|
||||||
(scope === 'stored' && res.next_cursor !== null && !idText(res.next_cursor))) {
|
(scope === 'stored' && res.next_cursor !== null && !idText(res.next_cursor))) {
|
||||||
throw Error('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
|
fail('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
|
||||||
}
|
}
|
||||||
return res.sessions
|
return res.sessions
|
||||||
}
|
}
|
||||||
@@ -41,7 +49,7 @@ function parseList(res, scope) {
|
|||||||
function normalized(r) {
|
function normalized(r) {
|
||||||
if (r?.hidden || r?.archived || r?.auto_archived || r?.is_internal_child || HIDDEN_SOURCES.has(r?.source)) return null
|
if (r?.hidden || r?.archived || r?.auto_archived || r?.is_internal_child || HIDDEN_SOURCES.has(r?.source)) return null
|
||||||
if (!idText(r?.id) || !idText(r?.session_id)) {
|
if (!idText(r?.id) || !idText(r?.session_id)) {
|
||||||
throw Error('Unvollständige Session-Metadaten.')
|
fail('Unvollständige Session-Metadaten.')
|
||||||
}
|
}
|
||||||
const aliases = [...new Set([r.id,r.session_id,r.resolved_id,r._lineage_root_id,
|
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))]
|
...(Array.isArray(r._lineage_ids) ? r._lineage_ids : [])].filter(idText))]
|
||||||
@@ -57,20 +65,20 @@ function unsupportedList(error) {
|
|||||||
async function loadPersisted(api, route, signal) {
|
async function loadPersisted(api, route, signal) {
|
||||||
signal?.throwIfAborted()
|
signal?.throwIfAborted()
|
||||||
if (typeof api.listPersistedSessions !== 'function') {
|
if (typeof api.listPersistedSessions !== 'function') {
|
||||||
throw Error('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
|
fail('Dieses Gateway meldet keinen unterstützten Session-/Paginationsvertrag.')
|
||||||
}
|
}
|
||||||
const result = await api.listPersistedSessions(route,{profile:route.targetProfile,limit:PERSISTED_LIMIT})
|
const result = await api.listPersistedSessions(route,{profile:route.targetProfile,limit:PERSISTED_LIMIT})
|
||||||
signal?.throwIfAborted()
|
signal?.throwIfAborted()
|
||||||
if (!Array.isArray(result?.sessions) || !Number.isSafeInteger(result.total) || result.total < 0 ||
|
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.offset !== 0 || !Number.isSafeInteger(result.limit) || result.limit < 1 || result.limit > PERSISTED_LIMIT ||
|
||||||
(result.errors !== undefined && !Array.isArray(result.errors))) {
|
(result.errors !== undefined && !Array.isArray(result.errors))) {
|
||||||
throw Error('Die gespeicherte Sessionliste hat ein unbekanntes Format.')
|
fail('Die gespeicherte Sessionliste hat ein unbekanntes Format.')
|
||||||
}
|
}
|
||||||
if (result.errors?.length || result.storage?.[route.targetProfile] === 'corrupt') {
|
if (result.errors?.length || result.storage?.[route.targetProfile] === 'corrupt') {
|
||||||
throw Error('Der Profilspeicher konnte nicht vollständig gelesen werden.')
|
fail('Der Profilspeicher konnte nicht vollständig gelesen werden.')
|
||||||
}
|
}
|
||||||
if (result.sessions.some(row=>row?.profile !== route.targetProfile)) {
|
if (result.sessions.some(row=>row?.profile !== route.targetProfile)) {
|
||||||
throw Error('Die gespeicherte Sessionliste enthält eine fremde Profilzuordnung.')
|
fail('Die gespeicherte Sessionliste enthält eine fremde Profilzuordnung.')
|
||||||
}
|
}
|
||||||
return {sessions:mergeRows(result.sessions.map(row=>({...row,session_id:row.id}))),liveAtLimit:false,
|
return {sessions:mergeRows(result.sessions.map(row=>({...row,session_id:row.id}))),liveAtLimit:false,
|
||||||
storedAtLimit:result.total > result.limit || result.sessions.length >= result.limit}
|
storedAtLimit:result.total > result.limit || result.sessions.length >= result.limit}
|
||||||
@@ -92,7 +100,8 @@ export async function loadBot(api, route, signal) {
|
|||||||
const rows = [...parseList(first,'stored')]
|
const rows = [...parseList(first,'stored')]
|
||||||
const seen = new Set()
|
const seen = new Set()
|
||||||
for (let cursor = first.next_cursor; cursor !== null;) {
|
for (let cursor = first.next_cursor; cursor !== null;) {
|
||||||
if (seen.has(cursor)) throw Error('Wiederholter Cursor: Abruf wurde abgebrochen.')
|
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)
|
seen.add(cursor)
|
||||||
const page = await request('stored',cursor)
|
const page = await request('stored',cursor)
|
||||||
rows.push(...parseList(page,'stored'))
|
rows.push(...parseList(page,'stored'))
|
||||||
@@ -115,27 +124,34 @@ function mergeRows(rows) {
|
|||||||
merged.lastActive = Math.max(merged.lastActive,r.lastActive,...matches.map(m=>m.lastActive))
|
merged.lastActive = Math.max(merged.lastActive,r.lastActive,...matches.map(m=>m.lastActive))
|
||||||
for (const alias of merged.aliases) identities.set(alias,merged)
|
for (const alias of merged.aliases) identities.set(alias,merged)
|
||||||
}
|
}
|
||||||
return [...new Set(identities.values())].sort((a,b)=>collator.compare(a.title,b.title) || collator.compare(a.id,b.id))
|
// 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) {
|
export async function openExisting(api, connection, route, session, inventory) {
|
||||||
const stillConnected = () => api.state.connectionId.get() === connection && api.state.gateway.get() === 'open'
|
await assertRoute(api,connection,route)
|
||||||
if (!stillConnected()) throw Error('Gateway ist nicht verbunden.')
|
|
||||||
const current = await routesFor(api,connection)
|
|
||||||
if (!stillConnected() || !current.some(r=>identity(r) === identity(route))) throw Error('Profilroute nicht mehr verfügbar.')
|
|
||||||
const has = entry => entry.sessions?.some(s=>s.id === session.id)
|
const has = entry => entry.sessions?.some(s=>s.id === session.id)
|
||||||
if (!inventory.some(entry=>identity(entry.route) === identity(route) && has(entry))) {
|
if (!inventory.some(entry=>identity(entry.route) === identity(route) && has(entry))) {
|
||||||
throw Error('Die Unterhaltung ist nicht mehr verfügbar.')
|
fail('Die Unterhaltung ist nicht mehr verfügbar.')
|
||||||
}
|
}
|
||||||
const aliases = new Set(session.aliases)
|
const aliases = new Set(session.aliases)
|
||||||
if (inventory.some(entry=>entry.route.connectionId === connection && identity(entry.route) !== identity(route) &&
|
if (inventory.some(entry=>entry.route.connectionId === connection && identity(entry.route) !== identity(route) &&
|
||||||
entry.sessions?.some(other=>other.aliases.some(a=>aliases.has(a))))) {
|
entry.sessions?.some(other=>other.aliases.some(a=>aliases.has(a))))) {
|
||||||
throw Error('Die Session-ID ist nicht eindeutig. Bitte über „Sessions“ öffnen.')
|
fail('Die Session-ID ist nicht eindeutig. Bitte über „Sessions“ öffnen.')
|
||||||
}
|
}
|
||||||
const owner = api.state.focusedSessionOwner?.get()
|
const owner = api.state.focusedSessionOwner?.get()
|
||||||
const currentId = api.state.focusedStoredSessionId?.get()
|
const currentId = api.state.focusedStoredSessionId?.get()
|
||||||
if (aliases.has(currentId) && (!owner || owner.connectionId !== connection || owner.profile !== route.profile)) {
|
if (aliases.has(currentId) && (!owner || owner.connectionId !== connection || owner.profile !== route.profile)) {
|
||||||
throw Error('Die aktive Session-ID ist nicht eindeutig.')
|
fail('Die aktive Session-ID ist nicht eindeutig.')
|
||||||
}
|
}
|
||||||
await api.openSession(session.id,{route,intent:'in-place',awaitHydration:true,keepAllProfilesScope:true})
|
await api.openSession(session.id,{route,intent:'in-place',awaitHydration:true,keepAllProfilesScope:true})
|
||||||
}
|
}
|
||||||
@@ -145,17 +161,54 @@ export function avatarSource(value) {
|
|||||||
/^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/]+=*$/i.test(value.data) ? value.data : null
|
/^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) {
|
async function loadMetadata(api, route) {
|
||||||
const res = await api.requestProfile(route,'profiles.list',{profile:route.targetProfile,include_sessions:false},15000)
|
const res = await api.requestProfile(route,'profiles.list',{profile:route.targetProfile,include_sessions:true},15000)
|
||||||
if (!Array.isArray(res?.profiles)) throw Error('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=>[p.name,{
|
||||||
name:text(p.ui_meta?.['hermes-bots']?.title) || text(p.display_name) || p.name, hasAvatar:p.has_avatar === true,
|
name:text(p.ui_meta?.['hermes-bots']?.title) || text(p.display_name) || p.name, hasAvatar:p.has_avatar === true,
|
||||||
|
botChat:botChatOf(p.canonical_session),
|
||||||
}]))
|
}]))
|
||||||
}
|
}
|
||||||
|
|
||||||
const el = (type, props, ...children) => h(type,children.length ? {
|
/**
|
||||||
...props,children:children.length === 1 ? children[0] : children,
|
* Opens a bot's existing Bot Chat the way the built-in Bots pane does (bots workspace, owner-scoped tab,
|
||||||
} : props)
|
* 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 sr = {color:'var(--ui-text-secondary)',fontSize:'0.85em',margin:'6px 0'}
|
||||||
const clip = {minWidth:0,overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis'}
|
const clip = {minWidth:0,overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis'}
|
||||||
const line = {display:'flex',gap:6,alignItems:'center',textAlign:'start',width:'100%'}
|
const line = {display:'flex',gap:6,alignItems:'center',textAlign:'start',width:'100%'}
|
||||||
@@ -176,7 +229,15 @@ function Avatar({route, name, enabled}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const botKey = r => [ID,'bot',r.connectionId,identity(r)]
|
const botKey = r => [ID,'bot',r.connectionId,identity(r)]
|
||||||
function Bot({route, connection, meta, online, expanded, toggle, routes, setNotice, busy, setBusy, openLock}) {
|
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)))
|
||||||
|
}
|
||||||
|
|
||||||
|
function Bot({route, connection, meta, metaRoute, metaReady, 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)
|
||||||
@@ -186,45 +247,46 @@ function Bot({route, connection, meta, online, expanded, toggle, routes, setNoti
|
|||||||
queryFn:({signal})=>loadBot(host,route,signal),staleTime:20000,
|
queryFn:({signal})=>loadBot(host,route,signal),staleTime:20000,
|
||||||
refetchInterval:expanded && online ? 90000 : false,retry:false})
|
refetchInterval:expanded && online ? 90000 : false,retry:false})
|
||||||
const botName = meta?.name || route.profile
|
const botName = meta?.name || route.profile
|
||||||
const select = async (s) => {
|
const botChat = meta?.botChat ?? null
|
||||||
|
const mine = owner?.connectionId === connection && owner.profile === route.profile
|
||||||
|
const guarded = (action, fallback) => async () => {
|
||||||
if (openLock.current) return
|
if (openLock.current) return
|
||||||
openLock.current = true
|
openLock.current = true
|
||||||
setNotice('')
|
setNotice('')
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
try {
|
try {await action()} catch (error) {
|
||||||
const entries = routes.map(r=>({route:r,sessions: client.getQueryData(botKey(r))?.sessions}))
|
setNotice(error instanceof CanopyError ? error.message : fallback)
|
||||||
await openExisting(host,connection,route,s,entries)
|
|
||||||
} catch (error) {
|
|
||||||
setNotice(error.message?.startsWith('Die ') || error.message?.startsWith('Profilroute') || error.message?.startsWith('Gateway ist')
|
|
||||||
? error.message : 'Unterhaltung konnte nicht geöffnet werden.')
|
|
||||||
} finally {openLock.current = false; setBusy(false)}
|
} 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)))
|
||||||
return el('li',null,
|
return el('li',null,
|
||||||
el('button',{type:'button','aria-expanded':expanded,'aria-controls':listId,onClick:toggle,
|
el('button',{type:'button','aria-expanded':expanded,'aria-controls':listId,onClick:toggle,
|
||||||
title:botName,style:{...line,...control}},
|
title:botName,style:{...line,...control}},
|
||||||
el('span',{'aria-hidden':true},expanded?'▾':'▸'),h(Avatar,{route,name:botName,enabled:online && !!meta?.hasAvatar}),
|
el('span',{'aria-hidden':true},expanded?'▾':'▸'),h(Avatar,{route,name:botName,enabled:online && !!meta?.hasAvatar}),
|
||||||
el('strong',{style:clip},botName)),
|
el('strong',{style:clip},botName)),
|
||||||
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 ? null : [
|
...(!expanded ? [] : [
|
||||||
q.isPending && online && message('Unterhaltungen werden geladen …'),
|
|
||||||
!online && message('Gateway nicht verbunden.'),
|
!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,
|
q.isError && el('div',null,
|
||||||
message('Unterhaltungen konnten für dieses Profil nicht geladen werden.',true),
|
message('Unterhaltungen konnten für dieses Profil nicht geladen werden.',true),
|
||||||
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 && q.data.sessions.length === 0 && message('Keine sichtbaren Unterhaltungen.'),
|
q.isSuccess && 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},...(q.data?.sessions ?? []).slice(0,shown).map(s=>{
|
el('ul',{style:list},...sessions.slice(0,shown).map(s=>h('li',{children:h(Row,{title:s.title,
|
||||||
const active = owner?.connectionId === connection && owner.profile === route.profile && s.aliases.includes(focused)
|
stamp:stampOf(s.lastActive),disabled:!online || busy || q.isError,
|
||||||
const stamp = s.lastActive ? new Date(s.lastActive*1000) : null
|
active:mine && s.aliases.includes(focused),onClick:()=>select(s)})},s.id))),
|
||||||
return h('li',{children:el('button',{type:'button',title:s.title,disabled:!online || busy || q.isError,
|
sessions.length>shown && el('button',{type:'button',style:control,onClick:()=>setShown(n=>n+25)},'Weitere Sessions anzeigen'),
|
||||||
'aria-current':active?'true':undefined,onClick:()=>select(s),style:{...line,...control,
|
])))
|
||||||
...(active?{fontWeight:650,background:'var(--ui-stroke-secondary)'}:{})}},
|
|
||||||
el('span',{style:{...clip,flex:'1 1 auto'}},s.title),
|
|
||||||
stamp && el('time',{dateTime:stamp.toISOString(),style:{...sr,whiteSpace:'nowrap',margin:0}},timeFormat.format(stamp)))},s.id)
|
|
||||||
})),
|
|
||||||
(q.data?.sessions.length ?? 0)>shown && el('button',{type:'button',style:control,onClick:()=>setShown(n=>n+25)},'Weitere Sessions anzeigen'),
|
|
||||||
]))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function Overview({ctx}) {
|
function Overview({ctx}) {
|
||||||
@@ -232,7 +294,7 @@ function Overview({ctx}) {
|
|||||||
const activeProfile = useValue(host.state.profile)
|
const activeProfile = useValue(host.state.profile)
|
||||||
const online = useValue(host.state.gateway) === 'open'
|
const online = useValue(host.state.gateway) === 'open'
|
||||||
const client = useQueryClient()
|
const client = useQueryClient()
|
||||||
const [openLock] = useState(()=>({current:false}))
|
const openLock = useRef(false)
|
||||||
const [busy,setBusy] = useState(false)
|
const [busy,setBusy] = useState(false)
|
||||||
const [notice,setNotice] = useState('')
|
const [notice,setNotice] = useState('')
|
||||||
const [open,setOpen] = useState(()=>{
|
const [open,setOpen] = useState(()=>{
|
||||||
@@ -262,20 +324,20 @@ function Overview({ctx}) {
|
|||||||
return next
|
return next
|
||||||
})
|
})
|
||||||
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'}},
|
||||||
message('Bot Chat bleibt im Reiter „Bots“.'),
|
|
||||||
!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 und Avatare 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],online:online && !directory.isError,
|
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,
|
||||||
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.1.2',defaultEnabled:false,
|
id:ID,name:'Hermes Canopy',version:'0.2.0',defaultEnabled:false,
|
||||||
description:'Ein Baum für Bots 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,
|
||||||
data:{placement:'left',collapsible:true,hideOnly:true,dock:{pane:'sessions',pos:'center'}},
|
data:{placement:'left',collapsible:true,hideOnly:true,dock:{pane:'sessions',pos:'center'}},
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ if (!deps || !out) throw Error('Usage: node scripts/browser-fixture.mjs DEPENDEN
|
|||||||
const react = await readFile(join(deps,'react/umd/react.production.min.js'),'utf8')
|
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 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'))
|
const src = (await readFile(new URL('../plugin.js',import.meta.url),'utf8'))
|
||||||
.replace(/^import .+\n/gm,'').replace(/^export (?=(?:async )?function)/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,useState}=React;
|
const {useEffect,useId,useRef,useState}=React;
|
||||||
const h=(type,props,key)=>React.createElement(type,{...props,key});
|
const h=(type,props,key)=>React.createElement(type,{...props,key});
|
||||||
|
const jsxs=h;
|
||||||
const owner={connectionId:'fixture',profile:'ops',targetProfile:'ops',mode:'remote'};
|
const owner={connectionId:'fixture',profile:'ops',targetProfile:'ops',mode:'remote'};
|
||||||
const atom=v=>({get:()=>v});
|
const atom=v=>({get:()=>v});
|
||||||
const actions=[], storage=new Map();
|
const actions=[], storage=new Map();
|
||||||
@@ -18,13 +19,15 @@ 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]),
|
profileRoutes:async()=>[owner],openSession:async(id,o)=>actions.push([id,o.route,o.workspaceMode]),
|
||||||
|
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');
|
||||||
return {sessions:fixtureSessions,total:600,limit:500,offset:0};
|
return {sessions:fixtureSessions,total:600,limit:500,offset:0};
|
||||||
},
|
},
|
||||||
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}}]};
|
||||||
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:[]};
|
||||||
@@ -69,6 +72,12 @@ 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);
|
||||||
|
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');
|
||||||
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;});
|
||||||
|
|||||||
+69
-3
@@ -3,11 +3,11 @@ import assert from 'node:assert/strict'
|
|||||||
import {registerHooks} from 'node:module'
|
import {registerHooks} from 'node:module'
|
||||||
const hooks = registerHooks({resolve(specifier, context, next) {
|
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 === '@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=()=>{}', 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})', 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, avatarSource} = await import('../plugin.js')
|
const {default: plugin, routesFor, loadBot, openExisting, openBotChat, botChatOf, avatarSource, CanopyError} = 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})
|
||||||
@@ -104,3 +104,69 @@ test('avatar only accepts raster data or falls back to initials', ()=>{
|
|||||||
assert.equal(avatarSource({found:true,data:'data:image/svg+xml;base64,aGk='}),null)
|
assert.equal(avatarSource({found:true,data:'data:image/svg+xml;base64,aGk='}),null)
|
||||||
assert.equal(avatarSource({found:false}),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)
|
||||||
|
})
|
||||||
Reference in new issue
Block a user