From 3484cd139fdd6de94957037973f13e8d284489fd Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 08:32:03 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20meetings:=20Settings=20tab=20"M?= =?UTF-8?q?eeting=20attendee"=20with=20Kokoro=20persona=20presets=20(Betty?= =?UTF-8?q?=20E)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new Settings tab manages the meeting attendee persona. - config: eleven presets built only from voices Kokoro-FastAPI v0.10.0 ships (Betty Bee default; American and British English, Spanish, French, Italian, Brazilian Portuguese, Hindi, Japanese, Mandarin) with intros and sample lines in their language; the Kokoro voice catalog, voice types (bot-style listed as coming later), preset order, override sources and the persona sample line. - dashboard: GET/PUT /api/meetings/persona (owner or read-write; effective persona, presets, overrides, voices, restart_required, attendee email section) and POST /api/meetings/persona/sample (Kokoro speech through a TTS resolver; 503 TTS not configured until it is wired). Email-in data arrives through SetMeetingsAttendeeEmail. - UI: Persona (preset cards, editable fields, voice list by language, live intro preview, Play sample), Behaviour (unprompted caps, voice on address) and Email (address, access list, approvals, switches disabled until email-in). - openapi.json, API reference, meetings.md, settings.md. Part of #18391. Fixes #18396. Signed-off-by: Andy Anderson --- .../added-18396-meeting-attendee-settings.md | 1 + dashboard/openapi.json | 762 ++++++++++++++++++ src/docs/api-reference/auth.md | 14 +- src/docs/api-reference/configuration.md | 4 +- src/docs/api-reference/dashboard-misc.md | 2 +- .../api-reference/health-status-events.md | 22 +- src/docs/api-reference/knowledge.md | 3 + src/docs/api-reference/packs-and-acmm.md | 2 +- src/docs/api-reference/snapshots-and-style.md | 2 +- src/docs/dashboard-sections.md | 2 +- src/docs/meetings.md | 28 + src/docs/settings.md | 4 + src/pkg/config/meetings_persona.go | 181 ++++- src/pkg/config/meetings_persona_catalog.go | 224 +++++ .../config/meetings_persona_catalog_test.go | 164 ++++ src/pkg/dashboard/api.go | 1 + src/pkg/dashboard/api_meetings_persona.go | 632 +++++++++++++++ .../dashboard/api_meetings_persona_test.go | 361 +++++++++ src/pkg/dashboard/meeting_attendee_ui_test.go | 154 ++++ .../dashboard/openapi_schema_parity_test.go | 5 + src/pkg/dashboard/server.go | 3 + .../static-src/css/meeting-attendee.css | 20 + .../dashboard/static-src/js/config-state.js | 3 +- .../dashboard/static-src/js/config-tabs.js | 2 + .../static-src/js/meeting-attendee.js | 301 +++++++ src/pkg/dashboard/static-src/manifest.txt | 2 + src/pkg/dashboard/static/index.html | 326 +++++++- src/pkg/meetings/betty/presets.go | 14 +- 28 files changed, 3200 insertions(+), 39 deletions(-) create mode 100644 changelog.d/added-18396-meeting-attendee-settings.md create mode 100644 src/pkg/config/meetings_persona_catalog.go create mode 100644 src/pkg/config/meetings_persona_catalog_test.go create mode 100644 src/pkg/dashboard/api_meetings_persona.go create mode 100644 src/pkg/dashboard/api_meetings_persona_test.go create mode 100644 src/pkg/dashboard/meeting_attendee_ui_test.go create mode 100644 src/pkg/dashboard/static-src/css/meeting-attendee.css create mode 100644 src/pkg/dashboard/static-src/js/meeting-attendee.js diff --git a/changelog.d/added-18396-meeting-attendee-settings.md b/changelog.d/added-18396-meeting-attendee-settings.md new file mode 100644 index 0000000000..ed680ce294 --- /dev/null +++ b/changelog.d/added-18396-meeting-attendee-settings.md @@ -0,0 +1 @@ +- **Settings, Meeting attendee.** A new Settings tab manages the hive's meeting persona: pick one of eleven presets built only from voices the self-hosted Kokoro TTS ships (Betty Bee by default, plus American and British English, Spanish, French, Italian, Brazilian Portuguese, Hindi, Japanese and Mandarin personas with intros in their own language) or edit the name, aliases, pronouns, voice type, language, accent, voice, humor and intro with a live preview and a Play sample button, set the unprompted-answer caps and voice-on-address, and see the attendee address `hive@` with the people who may invite her. Owner or read-write, through `GET`/`PUT /api/meetings/persona` and `POST /api/meetings/persona/sample`; the email controls are shown disabled until email-in lands ([#18396](https://github.com/hivecommons/hive/issues/18396)). diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 1d21434f40..4f21d45363 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -978,6 +978,768 @@ } } }, + "/api/meetings/persona": { + "get": { + "tags": [ + "Meetings" + ], + "summary": "Get the meeting attendee persona", + "description": "Settings, Meeting attendee: the effective persona, the presets, which fields are overridden (config or env), the Kokoro voices, whether a restart is required, and the attendee email section. Owner or read-write.", + "responses": { + "200": { + "description": "Meeting attendee settings", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "effective": { + "type": "object", + "description": "The resolved persona. Fields resolve as if the persona were on; enabled says whether it is.", + "properties": { + "enabled": { + "type": "boolean" + }, + "preset": { + "type": "string" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "pronouns": { + "type": "string" + }, + "language": { + "type": "string" + }, + "voice": { + "type": "string" + }, + "voice_type": { + "type": "string" + }, + "accent": { + "type": "string" + }, + "intro_template": { + "type": "string" + }, + "leave_phrases": { + "type": "array", + "items": { + "type": "string" + } + }, + "humor": { + "type": "string" + }, + "intro": { + "type": "string", + "description": "The rendered intro" + }, + "unprompted": { + "type": "object", + "properties": { + "per_10m": { + "type": "integer" + }, + "min_gap_s": { + "type": "integer" + }, + "per_meeting": { + "type": "integer" + }, + "answer_wait_s": { + "type": "integer" + }, + "min_confidence": { + "type": "number" + }, + "queue_depth": { + "type": "integer" + }, + "stale_s": { + "type": "integer" + } + } + }, + "voice_on_address": { + "type": "boolean" + } + } + }, + "presets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "pronouns": { + "type": "string" + }, + "language": { + "type": "string" + }, + "voice": { + "type": "string" + }, + "voice_type": { + "type": "string" + }, + "accent": { + "type": "string" + }, + "humor": { + "type": "string" + }, + "intro_template": { + "type": "string" + }, + "plain_intro_template": { + "type": "string" + }, + "leave_phrases": { + "type": "array", + "items": { + "type": "string" + } + }, + "sample_line": { + "type": "string" + } + } + } + }, + "overridden": { + "type": "object", + "description": "meetings.persona keys not taken from the preset or defaults, mapped to config or env", + "additionalProperties": { + "type": "string" + } + }, + "voices": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "language": { + "type": "string" + }, + "accent": { + "type": "string" + }, + "voice_type": { + "type": "string" + } + } + } + }, + "voice_types": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "available": { + "type": "boolean" + }, + "note": { + "type": "string" + } + } + } + }, + "restart_required": { + "type": "boolean" + }, + "running": { + "type": "boolean" + }, + "tts_configured": { + "type": "boolean" + }, + "email": { + "type": "object", + "description": "The Email section; available is false until email-in is enabled", + "properties": { + "available": { + "type": "boolean" + }, + "address": { + "type": "string", + "description": "hive@" + }, + "inviters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "login": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "role": { + "type": "string" + }, + "emails": { + "type": "array", + "items": { + "type": "object", + "properties": { + "address": { + "type": "string" + }, + "proof": { + "type": "string", + "description": "verified or pending" + }, + "verified_at": { + "type": "string" + } + } + } + } + } + } + }, + "approvals": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "from": { + "type": "string" + }, + "subject": { + "type": "string" + }, + "received_at": { + "type": "string" + } + } + } + }, + "calendar_invites": { + "type": "boolean" + }, + "mail_in_files": { + "type": "boolean" + }, + "error": { + "type": "string" + } + } + } + } + } + } + } + }, + "403": { + "description": "Owner or read-write access required" + }, + "503": { + "description": "Config is not available" + } + } + }, + "put": { + "tags": [ + "Meetings" + ], + "summary": "Save the meeting attendee persona", + "description": "Saves meetings.persona (and meetings.voice_on_address) to hive.yaml. An absent field is unchanged, an empty one (or 0 for a cap) clears the override, and a value equal to the preset's is stored as no override. Validated as if the persona were on. Owner or read-write. Audited as meetings_persona.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "preset": { + "type": "string" + }, + "clear_overrides": { + "type": "boolean", + "description": "Drop every field override first" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "pronouns": { + "type": "string" + }, + "language": { + "type": "string" + }, + "voice": { + "type": "string" + }, + "voice_type": { + "type": "string" + }, + "accent": { + "type": "string" + }, + "intro_template": { + "type": "string" + }, + "leave_phrases": { + "type": "array", + "items": { + "type": "string" + } + }, + "humor": { + "type": "string" + }, + "unprompted": { + "type": "object", + "properties": { + "per_10m": { + "type": "integer" + }, + "min_gap_s": { + "type": "integer" + }, + "per_meeting": { + "type": "integer" + }, + "answer_wait_s": { + "type": "integer" + }, + "min_confidence": { + "type": "number" + }, + "queue_depth": { + "type": "integer" + }, + "stale_s": { + "type": "integer" + } + } + }, + "voice_on_address": { + "type": "boolean" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Meeting attendee settings", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "effective": { + "type": "object", + "description": "The resolved persona. Fields resolve as if the persona were on; enabled says whether it is.", + "properties": { + "enabled": { + "type": "boolean" + }, + "preset": { + "type": "string" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "pronouns": { + "type": "string" + }, + "language": { + "type": "string" + }, + "voice": { + "type": "string" + }, + "voice_type": { + "type": "string" + }, + "accent": { + "type": "string" + }, + "intro_template": { + "type": "string" + }, + "leave_phrases": { + "type": "array", + "items": { + "type": "string" + } + }, + "humor": { + "type": "string" + }, + "intro": { + "type": "string", + "description": "The rendered intro" + }, + "unprompted": { + "type": "object", + "properties": { + "per_10m": { + "type": "integer" + }, + "min_gap_s": { + "type": "integer" + }, + "per_meeting": { + "type": "integer" + }, + "answer_wait_s": { + "type": "integer" + }, + "min_confidence": { + "type": "number" + }, + "queue_depth": { + "type": "integer" + }, + "stale_s": { + "type": "integer" + } + } + }, + "voice_on_address": { + "type": "boolean" + } + } + }, + "presets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "pronouns": { + "type": "string" + }, + "language": { + "type": "string" + }, + "voice": { + "type": "string" + }, + "voice_type": { + "type": "string" + }, + "accent": { + "type": "string" + }, + "humor": { + "type": "string" + }, + "intro_template": { + "type": "string" + }, + "plain_intro_template": { + "type": "string" + }, + "leave_phrases": { + "type": "array", + "items": { + "type": "string" + } + }, + "sample_line": { + "type": "string" + } + } + } + }, + "overridden": { + "type": "object", + "description": "meetings.persona keys not taken from the preset or defaults, mapped to config or env", + "additionalProperties": { + "type": "string" + } + }, + "voices": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "language": { + "type": "string" + }, + "accent": { + "type": "string" + }, + "voice_type": { + "type": "string" + } + } + } + }, + "voice_types": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "available": { + "type": "boolean" + }, + "note": { + "type": "string" + } + } + } + }, + "restart_required": { + "type": "boolean" + }, + "running": { + "type": "boolean" + }, + "tts_configured": { + "type": "boolean" + }, + "email": { + "type": "object", + "description": "The Email section; available is false until email-in is enabled", + "properties": { + "available": { + "type": "boolean" + }, + "address": { + "type": "string", + "description": "hive@" + }, + "inviters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "login": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "role": { + "type": "string" + }, + "emails": { + "type": "array", + "items": { + "type": "object", + "properties": { + "address": { + "type": "string" + }, + "proof": { + "type": "string", + "description": "verified or pending" + }, + "verified_at": { + "type": "string" + } + } + } + } + } + } + }, + "approvals": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "from": { + "type": "string" + }, + "subject": { + "type": "string" + }, + "received_at": { + "type": "string" + } + } + } + }, + "calendar_invites": { + "type": "boolean" + }, + "mail_in_files": { + "type": "boolean" + }, + "error": { + "type": "string" + } + } + } + } + } + } + } + }, + "400": { + "description": "Invalid persona" + }, + "403": { + "description": "Owner or read-write access required" + }, + "500": { + "description": "Saving the config failed" + }, + "503": { + "description": "Config is not available" + } + } + } + }, + "/api/meetings/persona/sample": { + "post": { + "tags": [ + "Meetings" + ], + "summary": "Play a persona sample", + "description": "Speaks a short line through the meetings TTS service (Kokoro /v1/audio/speech) and returns the audio, at most 2 MiB. Optional unsaved voice, language and display name; text at most 200 characters, default the persona's sample line. Owner or read-write.", + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "voice": { + "type": "string" + }, + "language": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "text": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The audio", + "content": { + "audio/mpeg": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "Invalid request or text too long" + }, + "403": { + "description": "Owner or read-write access required" + }, + "502": { + "description": "The TTS service failed" + }, + "503": { + "description": "TTS not configured, or config is not available" + } + } + } + }, "/api/integration-orchestration": { "get": { "tags": ["System"], diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index edbfa874be..c479b952ed 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,10 +24,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1776` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1777` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1778` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:551` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:552` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:553` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:554` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1779` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1780` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1781` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:552` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:553` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:554` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:555` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 2f1fb3ebd4..2d79a5ecca 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -101,8 +101,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:215` | | `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:522` | | `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:523` | -| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:547` | -| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:548` | +| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:548` | +| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:549` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:218` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:221` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:227` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 6847ccf131..357daa6a14 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -84,7 +84,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:377` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:378` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:379` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1783` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1786` | ### Activity observation provenance The CI snapshot retains real check/node IDs, head, App ID and transition times. diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 573bcd31b8..73194e7845 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:45` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:70` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1756` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1757` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1758` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1764` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1769` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1770` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1771` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1772` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1773` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1774` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1775` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1759` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1760` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1761` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1767` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1772` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1773` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1774` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1775` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1776` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1777` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1778` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index 21a2399480..edd2a1aed3 100644 --- a/src/docs/api-reference/knowledge.md +++ b/src/docs/api-reference/knowledge.md @@ -100,3 +100,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/meetings/schedule/{eid}/decline` | Owner only | Decline an event awaiting approval; later updates of the same invite stay declined. Audited as `meeting_schedule_decline` | `pkg/dashboard/api_meetings_schedule.go:86` | | `POST` | `/api/meetings/schedule/{eid}/cancel` | Owner only | Stop hive joining the event (every occurrence of a series); a meeting already live is not left. Audited as `meeting_schedule_cancel` | `pkg/dashboard/api_meetings_schedule.go:87` | | `POST` | `/api/meetings/schedule/{eid}/skip` | Owner only | Skip the next occurrence hive has not joined: a single meeting becomes `skipped`, a series moves on. Audited as `meeting_schedule_skip` | `pkg/dashboard/api_meetings_schedule.go:88` | +| `GET` | `/api/meetings/persona` | Owner or read-write | Settings, Meeting attendee: `{effective, presets, overridden, voices, voice_types, restart_required, running, tts_configured, email}`. `effective` is the resolved persona (fields resolved as if on, `enabled` separately) with the rendered `intro` and `voice_on_address`; `presets` lists the built-in personas, the default first; `overridden` maps each `meetings.persona` key not taken from the preset or defaults to `config` or `env`; `voices` are the Kokoro voices with language, accent and voice type; `restart_required` is true when the saved persona differs from the one the hive booted with; `email` is the attendee address (`hive@`), the access list with registered calendar emails and proof status, the approval queue and the email-in switches (`available: false` until email-in is enabled). See [Meeting attendee settings](../meetings.md#meeting-attendee-settings) | `pkg/dashboard/api_meetings_persona.go:163` | +| `PUT` | `/api/meetings/persona` | Owner or read-write | Save `meetings.persona` to `hive.yaml`: `{enabled?, preset?, clear_overrides?, name?, display_name?, aliases?, pronouns?, language?, voice?, voice_type?, accent?, intro_template?, leave_phrases?, humor?, unprompted?: {per_10m?, min_gap_s?, per_meeting?, answer_wait_s?, min_confidence?, queue_depth?, stale_s?}, voice_on_address?}`. An absent field is unchanged, an empty one (or 0 for a cap) clears the override, a value equal to the preset's is stored as no override, and `clear_overrides` drops every field override first. Validated as if the persona were on; returns the GET body. 400 invalid. Audited as `meetings_persona` | `pkg/dashboard/api_meetings_persona.go:164` | +| `POST` | `/api/meetings/persona/sample` | Owner or read-write | Speak a short line through the meetings TTS service (Kokoro `POST /v1/audio/speech`) and return the audio (`audio/mpeg`, at most 2 MiB, `Cache-Control: no-store`). Optional `{voice?, language?, display_name?, text?}` (unsaved form values; `text` at most 200 characters, default the persona's sample line in its language). 503 "TTS not configured" until `meetings.tts_url` is set, 400 invalid, 502 the TTS service failed | `pkg/dashboard/api_meetings_persona.go:165` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index eb040a8909..71379fe6e6 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -25,7 +25,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:341`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:342` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:343` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:545`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:546`, `pkg/dashboard/api_repo_item_accept_triage.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | | `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:345`, `pkg/dashboard/api_acmm_eval.go` | | `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:346` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index e95c663f3e..4970d3ccca 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1846` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1849` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:83` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:84` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:85` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 4576270635..4d9087a863 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -202,7 +202,7 @@ Right after Inbox in the left menu. Each row shows the title, organizer, start a Meetings hive joins to take notes: send it to one, follow the live transcript, notes and research, or make it leave. -Owner only. Approve research past the per-meeting cap and answer Discord join requests here; settings are under Settings, Meetings. Full entry: [Meetings](meetings.md). +Owner only. Approve research past the per-meeting cap and answer Discord join requests here; settings are under Settings, Meetings, and the persona under Settings, Meeting attendee. Full entry: [Meetings](meetings.md). ## Contributors diff --git a/src/docs/meetings.md b/src/docs/meetings.md index 1aa5873064..0ec073ed7b 100644 --- a/src/docs/meetings.md +++ b/src/docs/meetings.md @@ -57,6 +57,34 @@ With `meetings.persona.searxng_url` set (`HIVE_MEETINGS_PERSONA_SEARXNG_URL`), w On hive-oke, SearXNG runs in the `meetings` namespace as a ClusterIP Service: set `searxng_url` to `http://searxng.meetings.svc.cluster.local:8080`. Its manifests (JSON output on, a small engine set, the limiter off for internal use, the secret key in a Secret) live in hivecommons/quorum `deploy/hive-oke/`. Any SearXNG with `json` in `search.formats` works. +### Meeting attendee settings + +Settings, **Meeting attendee** edits all of this from the dashboard ([#18396](https://github.com/hivecommons/hive/issues/18396)). The owner and read-write users can open it; it saves `meetings.persona` (and `meetings.voice_on_address`) to `hive.yaml`. The persona is read when hive starts, so a saved change shows "restart the hive to apply" until the next restart. A field set by an `HIVE_MEETINGS_PERSONA_*` variable is marked **env**, and edits to it have no effect while the variable is set; a field that differs from the preset is marked **custom**. + +- **Persona.** Preset cards show each persona's flag, language, accent, voice type and voice id. Picking one fills the form; Save stores it. A value equal to the preset's is stored as no override, so the persona keeps following the preset. The voice list shows the Kokoro voices for the chosen language, and changing the language picks a voice of the same type. The intro has a live preview. **Play sample** speaks a short line in the persona's language through the meetings TTS service; until that service is configured (`meetings.tts_url` and its token, phase B) the button is disabled and the API answers "TTS not configured". +- **Behaviour.** The unprompted caps above (`per_10m`, `min_gap_s`, `per_meeting`, `answer_wait_s`, `min_confidence`, `queue_depth`, `stale_s`; 0 restores a default) and whether hive may speak aloud when addressed (`meetings.voice_on_address`). +- **Email.** The attendee address, `hive@`, with a copy button, the people with access to this hive (owner, read-write and read) with their registered calendar emails and proof status, the invites and files waiting for approval, and switches for calendar invites and mailed-in files. Until email-in is enabled ([#18395](https://github.com/hivecommons/hive/issues/18395)) the section is shown with its controls disabled. + +The presets use only voices the self-hosted Kokoro TTS ([Kokoro-FastAPI](https://github.com/remsky/Kokoro-FastAPI) v0.10.0) ships. Leave phrases stay in Latin script because the leave matcher uses ASCII word boundaries, and every preset keeps "hive" as an alias and "hive leave" as a leave phrase. + +| Preset | Language | Accent | Voice | Voice type | +|---|---|---|---|---| +| `betty`: Betty Bee from the hive (default) | `en-US` | American | `af_heart` | female | +| `barnaby`: Barnaby Bee from the hive | `en-US` | American | `am_michael` | male | +| `beatrice`: Beatrice Bee from the hive | `en-GB` | British | `bf_emma` | female | +| `bertie`: Bertie Bee from the hive | `en-GB` | British | `bm_george` | male | +| `melisa`: Melisa, la abeja de la colmena | `es-ES` | Spanish (Spain) | `ef_dora` | female | +| `melie`: Mélie, l'abeille de la ruche | `fr-FR` | French | `ff_siwis` | female | +| `melina`: Melina, l'ape dell'alveare | `it-IT` | Italian | `if_sara` | female | +| `bia`: Bia, a abelha da colmeia | `pt-BR` | Brazilian | `pf_dora` | female | +| `madhu`: मधु, छत्ते की मधुमक्खी | `hi-IN` | Indian | `hf_alpha` | female | +| `mitsu`: ミツバチのミツ | `ja-JP` | Standard Japanese | `jf_alpha` | female | +| `mimi`: 蜂巢的小蜜蜂蜜蜜 | `zh-CN` | Standard Mandarin | `zf_xiaobei` | female | + +A bot-style voice is listed as coming later: Kokoro has no bot-style voice, and one would need a new service. + +The API is `/api/meetings/persona` ([API reference](api-reference/knowledge.md)). + ## The model Spek reasons with Hive owns the model credential and the budget; Spektacular never receives an OpenAI-compatible key. diff --git a/src/docs/settings.md b/src/docs/settings.md index b2ce9a4c23..d0a2bab236 100644 --- a/src/docs/settings.md +++ b/src/docs/settings.md @@ -89,6 +89,10 @@ The other features on this tab (OpenTelemetry export, external execution, auto-p Whether the public read-only knowledge MCP endpoint is on, the knowledge pipeline, and the external knowledge connectors. The **Knowledge pipeline** block sets the bead synthesizer (schedule, target layer, minimum confidence, per-cycle fact and GitHub API caps, bead retention), scheduled curator promotion (schedule, threshold, source and target layers), repository code maps (schedule, layer, size cap) and the kick primer's fact and byte caps. Turning the bead synthesizer on or off applies at once; the other pipeline settings apply after a restart, and 0 or empty restores the default. The engine, the vault paths and the primer merge strategy are shown read-only because they are set in `hive.yaml`. The repositories to map and the primer priority list stay yaml-only. See [Knowledge curator](knowledge-curator.md) and [Knowledge connectors](knowledge-connectors.md). +## Meeting attendee + +The persona hive attends meetings as (Betty by default): pick a preset or edit its name, display name, aliases, pronouns, voice type, language, accent, Kokoro voice, humor and intro (with a live preview and a **Play sample** button), set how often she answers room questions unprompted, and see the address people invite her with. Owner or read-write. Changes apply after a restart. See [Meeting attendee settings](meetings.md#meeting-attendee-settings). + ## Advisory How many advisory findings are shown, how often they refresh, and when a finding counts as stale. See [Advisory](advisory.md) and [Advisory staleness](advisory-staleness.md). diff --git a/src/pkg/config/meetings_persona.go b/src/pkg/config/meetings_persona.go index 137b76df9a..4d72da7e39 100644 --- a/src/pkg/config/meetings_persona.go +++ b/src/pkg/config/meetings_persona.go @@ -88,9 +88,16 @@ type MeetingsPersonaPreset struct { IntroTemplate string `json:"intro_template"` PlainIntroTemplate string `json:"plain_intro_template"` LeavePhrases []string `json:"leave_phrases"` + // SampleLine is the short line the settings tab's Play sample button + // speaks, in the preset's language. Same placeholders as the intro. + SampleLine string `json:"sample_line"` } -// MeetingsPersonaPresets are the built-in personas, keyed by ID. +// MeetingsPersonaPresets are the built-in personas, keyed by ID. Every +// voice is one the self-hosted Kokoro TTS ships (KokoroVoices); the order +// the settings tab lists them in is MeetingsPersonaPresetOrder. Leave +// phrases stay in Latin script: the leave matcher uses ASCII word +// boundaries. var MeetingsPersonaPresets = map[string]MeetingsPersonaPreset{ "betty": { ID: "betty", @@ -103,12 +110,180 @@ var MeetingsPersonaPresets = map[string]MeetingsPersonaPreset{ VoiceType: MeetingsPersonaVoiceFemale, Accent: "American", Humor: MeetingsPersonaHumorLight, - IntroTemplate: "Hi, I'm {display_name} ({pronouns}). I take notes, keep this meeting's transcript, and answer questions from what the hive knows: its knowledge base and work items. Say my name to ask me something. Say \"{leave}\" and I'll buzz off.", - PlainIntroTemplate: "Hi, I'm {display_name} ({pronouns}). I take notes, keep this meeting's transcript, and answer questions from the hive's knowledge base and work items. Say my name to ask me something, or say \"{leave}\" to remove me.", + IntroTemplate: meetingsIntroEnglish, + PlainIntroTemplate: meetingsPlainIntroEnglish, LeavePhrases: []string{"betty leave", "hive leave"}, + SampleLine: meetingsSampleEnglish, + }, + "barnaby": { + ID: "barnaby", + Name: "Barnaby", + DisplayName: "Barnaby Bee from the hive", + Aliases: []string{"barnaby", "barnaby bee", "hive"}, + Pronouns: "he/him", + Language: "en-US", + Voice: "am_michael", + VoiceType: MeetingsPersonaVoiceMale, + Accent: "American", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: meetingsIntroEnglish, + PlainIntroTemplate: meetingsPlainIntroEnglish, + LeavePhrases: []string{"barnaby leave", "hive leave"}, + SampleLine: meetingsSampleEnglish, + }, + "beatrice": { + ID: "beatrice", + Name: "Beatrice", + DisplayName: "Beatrice Bee from the hive", + Aliases: []string{"beatrice", "beatrice bee", "hive"}, + Pronouns: "she/her", + Language: "en-GB", + Voice: "bf_emma", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "British", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: meetingsIntroEnglish, + PlainIntroTemplate: meetingsPlainIntroEnglish, + LeavePhrases: []string{"beatrice leave", "hive leave"}, + SampleLine: meetingsSampleEnglish, + }, + "bertie": { + ID: "bertie", + Name: "Bertie", + DisplayName: "Bertie Bee from the hive", + Aliases: []string{"bertie", "bertie bee", "hive"}, + Pronouns: "he/him", + Language: "en-GB", + Voice: "bm_george", + VoiceType: MeetingsPersonaVoiceMale, + Accent: "British", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: meetingsIntroEnglish, + PlainIntroTemplate: meetingsPlainIntroEnglish, + LeavePhrases: []string{"bertie leave", "hive leave"}, + SampleLine: meetingsSampleEnglish, + }, + "melisa": { + ID: "melisa", + Name: "Melisa", + DisplayName: "Melisa, la abeja de la colmena", + Aliases: []string{"melisa", "abeja", "hive"}, + Pronouns: "ella", + Language: "es-ES", + Voice: "ef_dora", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "Spanish (Spain)", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: "Hola, soy {display_name} ({pronouns}). Tomo notas, guardo la transcripción de esta reunión y respondo preguntas con lo que sabe la colmena: su base de conocimiento y sus tareas. Di mi nombre para preguntarme algo. Di \"{leave}\" y saldré volando.", + PlainIntroTemplate: "Hola, soy {display_name} ({pronouns}). Tomo notas, guardo la transcripción de esta reunión y respondo preguntas con la base de conocimiento y las tareas de la colmena. Di mi nombre para preguntarme algo, o di \"{leave}\" para que me vaya.", + LeavePhrases: []string{"melisa vete", "hive leave"}, + SampleLine: "Hola, soy {display_name}. Pregúntame lo que quieras sobre el trabajo de la colmena.", + }, + "melie": { + ID: "melie", + Name: "Mélie", + DisplayName: "Mélie, l'abeille de la ruche", + Aliases: []string{"mélie", "melie", "abeille", "hive"}, + Pronouns: "elle", + Language: "fr-FR", + Voice: "ff_siwis", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "French", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: "Bonjour, je suis {display_name} ({pronouns}). Je prends des notes, je garde la transcription de cette réunion et je réponds aux questions avec ce que sait la ruche : sa base de connaissances et ses tâches. Dites mon nom pour me poser une question. Dites « {leave} » et je m'envole.", + PlainIntroTemplate: "Bonjour, je suis {display_name} ({pronouns}). Je prends des notes, je garde la transcription de cette réunion et je réponds aux questions à partir de la base de connaissances et des tâches de la ruche. Dites mon nom pour me poser une question, ou dites « {leave} » pour me retirer.", + LeavePhrases: []string{"melie pars", "hive leave"}, + SampleLine: "Bonjour, je suis {display_name}. Posez-moi vos questions sur le travail de la ruche.", + }, + "melina": { + ID: "melina", + Name: "Melina", + DisplayName: "Melina, l'ape dell'alveare", + Aliases: []string{"melina", "ape", "hive"}, + Pronouns: "lei", + Language: "it-IT", + Voice: "if_sara", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "Italian", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: "Ciao, sono {display_name} ({pronouns}). Prendo appunti, conservo la trascrizione di questa riunione e rispondo alle domande con ciò che sa l'alveare: la sua base di conoscenza e le sue attività. Di' il mio nome per farmi una domanda. Di' \"{leave}\" e volo via.", + PlainIntroTemplate: "Ciao, sono {display_name} ({pronouns}). Prendo appunti, conservo la trascrizione di questa riunione e rispondo alle domande con la base di conoscenza e le attività dell'alveare. Di' il mio nome per farmi una domanda, oppure di' \"{leave}\" per farmi uscire.", + LeavePhrases: []string{"melina esci", "hive leave"}, + SampleLine: "Ciao, sono {display_name}. Chiedimi pure qualcosa sul lavoro dell'alveare.", + }, + "bia": { + ID: "bia", + Name: "Bia", + DisplayName: "Bia, a abelha da colmeia", + Aliases: []string{"bia", "abelha", "hive"}, + Pronouns: "ela", + Language: "pt-BR", + Voice: "pf_dora", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "Brazilian", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: "Oi, eu sou a {display_name} ({pronouns}). Faço anotações, guardo a transcrição desta reunião e respondo perguntas com o que a colmeia sabe: a base de conhecimento e as tarefas dela. Diga meu nome para me perguntar algo. Diga \"{leave}\" e eu saio voando.", + PlainIntroTemplate: "Oi, eu sou a {display_name} ({pronouns}). Faço anotações, guardo a transcrição desta reunião e respondo perguntas com a base de conhecimento e as tarefas da colmeia. Diga meu nome para me perguntar algo, ou diga \"{leave}\" para me remover.", + LeavePhrases: []string{"bia sai", "hive leave"}, + SampleLine: "Oi, eu sou a {display_name}. Pode me perguntar qualquer coisa sobre o trabalho da colmeia.", + }, + "madhu": { + ID: "madhu", + Name: "मधु", + DisplayName: "मधु, छत्ते की मधुमक्खी", + Aliases: []string{"मधु", "madhu", "hive"}, + Pronouns: "वह", + Language: "hi-IN", + Voice: "hf_alpha", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "Indian", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: "नमस्ते, मैं {display_name} हूँ ({pronouns})। मैं नोट्स लेती हूँ, इस मीटिंग का ट्रांसक्रिप्ट रखती हूँ, और छत्ते की जानकारी, यानी उसके नॉलेज बेस और काम की चीज़ों से सवालों के जवाब देती हूँ। कुछ पूछना हो तो मेरा नाम लीजिए। \"{leave}\" कहिए और मैं उड़ जाऊँगी।", + PlainIntroTemplate: "नमस्ते, मैं {display_name} हूँ ({pronouns})। मैं नोट्स लेती हूँ, इस मीटिंग का ट्रांसक्रिप्ट रखती हूँ, और छत्ते के नॉलेज बेस और काम की चीज़ों से सवालों के जवाब देती हूँ। कुछ पूछना हो तो मेरा नाम लीजिए, या मुझे हटाने के लिए \"{leave}\" कहिए।", + LeavePhrases: []string{"madhu leave", "hive leave"}, + SampleLine: "नमस्ते, मैं {display_name} हूँ। छत्ते के काम के बारे में मुझसे कुछ भी पूछिए।", + }, + "mitsu": { + ID: "mitsu", + Name: "ミツ", + DisplayName: "ミツバチのミツ", + Aliases: []string{"ミツ", "ミツさん", "mitsu", "hive"}, + Pronouns: "彼女", + Language: "ja-JP", + Voice: "jf_alpha", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "Standard Japanese", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: "こんにちは、{display_name}です({pronouns})。メモを取り、この会議の文字起こしを記録し、ハイブのナレッジベースと作業項目をもとに質問にお答えします。質問があるときは私の名前を呼んでください。「{leave}」と言えば、ぶーんと飛んで帰ります。", + PlainIntroTemplate: "こんにちは、{display_name}です({pronouns})。メモを取り、この会議の文字起こしを記録し、ハイブのナレッジベースと作業項目をもとに質問にお答えします。質問があるときは私の名前を呼んでください。退出させるには「{leave}」と言ってください。", + LeavePhrases: []string{"mitsu leave", "hive leave"}, + SampleLine: "こんにちは、{display_name}です。ハイブの作業について何でも聞いてください。", + }, + "mimi": { + ID: "mimi", + Name: "蜜蜜", + DisplayName: "蜂巢的小蜜蜂蜜蜜", + Aliases: []string{"蜜蜜", "mimi", "hive"}, + Pronouns: "她", + Language: "zh-CN", + Voice: "zf_xiaobei", + VoiceType: MeetingsPersonaVoiceFemale, + Accent: "Standard Mandarin", + Humor: MeetingsPersonaHumorLight, + IntroTemplate: "大家好,我是{display_name}({pronouns})。我负责记笔记、保存这次会议的文字记录,并根据蜂巢的知识库和工作项回答问题。想问我问题,就叫我的名字。说“{leave}”,我就嗡嗡飞走啦。", + PlainIntroTemplate: "大家好,我是{display_name}({pronouns})。我负责记笔记、保存这次会议的文字记录,并根据蜂巢的知识库和工作项回答问题。想问我问题,就叫我的名字;要让我离开,请说“{leave}”。", + LeavePhrases: []string{"mimi leave", "hive leave"}, + SampleLine: "大家好,我是{display_name}。关于蜂巢的工作,尽管问我。", }, } +// The English presets share their intro and sample templates. +const ( + meetingsIntroEnglish = "Hi, I'm {display_name} ({pronouns}). I take notes, keep this meeting's transcript, and answer questions from what the hive knows: its knowledge base and work items. Say my name to ask me something. Say \"{leave}\" and I'll buzz off." + meetingsPlainIntroEnglish = "Hi, I'm {display_name} ({pronouns}). I take notes, keep this meeting's transcript, and answer questions from the hive's knowledge base and work items. Say my name to ask me something, or say \"{leave}\" to remove me." + meetingsSampleEnglish = "Hi, I'm {display_name}. Ask me anything about the hive's work and I'll keep it short and sweet." +) + // Persona env overrides. List values are comma separated. const ( MeetingsPersonaEnabledEnv = "HIVE_MEETINGS_PERSONA_ENABLED" diff --git a/src/pkg/config/meetings_persona_catalog.go b/src/pkg/config/meetings_persona_catalog.go new file mode 100644 index 0000000000..01e155f98b --- /dev/null +++ b/src/pkg/config/meetings_persona_catalog.go @@ -0,0 +1,224 @@ +package config + +import ( + "os" + "sort" + "strings" +) + +// Meeting attendee catalog (hivecommons/hive#18396): the order the settings +// tab lists the persona presets in, the TTS voices the self-hosted Kokoro +// provides, the voice types, and which persona fields an operator has +// overridden. + +// MeetingsPersonaPresetOrder is the order the settings tab lists the +// presets in: the default first, then English, then the other languages. +var MeetingsPersonaPresetOrder = []string{ + "betty", "barnaby", "beatrice", "bertie", + "melisa", "melie", "melina", "bia", "madhu", "mitsu", "mimi", +} + +// OrderedMeetingsPersonaPresets returns the presets in +// MeetingsPersonaPresetOrder, then any preset the order does not name (by +// ID), so a new preset is never hidden. +func OrderedMeetingsPersonaPresets() []MeetingsPersonaPreset { + out := make([]MeetingsPersonaPreset, 0, len(MeetingsPersonaPresets)) + seen := make(map[string]bool, len(MeetingsPersonaPresets)) + for _, id := range MeetingsPersonaPresetOrder { + if p, ok := MeetingsPersonaPresets[id]; ok && !seen[id] { + out = append(out, p) + seen[id] = true + } + } + var rest []string + for id := range MeetingsPersonaPresets { + if !seen[id] { + rest = append(rest, id) + } + } + sort.Strings(rest) + for _, id := range rest { + out = append(out, MeetingsPersonaPresets[id]) + } + return out +} + +// MeetingsTTSVoice is one voice the meetings TTS service offers. +type MeetingsTTSVoice struct { + ID string `json:"id"` + // Language is the BCP-47 tag the voice speaks. + Language string `json:"language"` + Accent string `json:"accent"` + VoiceType string `json:"voice_type"` +} + +// kokoroLanguages maps a Kokoro voice id's first letter to the language it +// speaks and the accent shown for it. Kokoro ids are _: +// a American English, b British English, e Spanish, f French, h Hindi, +// i Italian, j Japanese, p Brazilian Portuguese, z Mandarin. +var kokoroLanguages = map[byte][2]string{ + 'a': {"en-US", "American"}, + 'b': {"en-GB", "British"}, + 'e': {"es-ES", "Spanish (Spain)"}, + 'f': {"fr-FR", "French"}, + 'h': {"hi-IN", "Indian"}, + 'i': {"it-IT", "Italian"}, + 'j': {"ja-JP", "Standard Japanese"}, + 'p': {"pt-BR", "Brazilian"}, + 'z': {"zh-CN", "Standard Mandarin"}, +} + +// kokoroVoiceIDs are the Kokoro-82M v1.0 voices Kokoro-FastAPI v0.10.0 +// ships (api/src/voices/v1_0 at that tag, which GET /v1/audio/voices +// lists): the standard voices, without the legacy v0 voices and the +// FastAPI-only blends. +var kokoroVoiceIDs = []string{ + "af_alloy", "af_aoede", "af_bella", "af_heart", "af_jessica", "af_kore", "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky", + "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam", "am_michael", "am_onyx", "am_puck", "am_santa", + "bf_alice", "bf_emma", "bf_isabella", "bf_lily", + "bm_daniel", "bm_fable", "bm_george", "bm_lewis", + "ef_dora", "em_alex", "em_santa", + "ff_siwis", + "hf_alpha", "hf_beta", "hm_omega", "hm_psi", + "if_sara", "im_nicola", + "jf_alpha", "jf_gongitsune", "jf_nezumi", "jf_tebukuro", "jm_kumo", + "pf_dora", "pm_alex", "pm_santa", + "zf_xiaobei", "zf_xiaoni", "zf_xiaoxiao", "zf_xiaoyi", "zm_yunjian", "zm_yunxi", "zm_yunxia", "zm_yunyang", +} + +// KokoroVoice describes a Kokoro voice id; ok is false when the id does +// not follow Kokoro's _ shape. +func KokoroVoice(id string) (MeetingsTTSVoice, bool) { + if len(id) < len("af_x") || id[2] != '_' { + return MeetingsTTSVoice{}, false + } + lang, ok := kokoroLanguages[id[0]] + if !ok { + return MeetingsTTSVoice{}, false + } + var vt string + switch id[1] { + case 'f': + vt = MeetingsPersonaVoiceFemale + case 'm': + vt = MeetingsPersonaVoiceMale + default: + return MeetingsTTSVoice{}, false + } + return MeetingsTTSVoice{ID: id, Language: lang[0], Accent: lang[1], VoiceType: vt}, true +} + +// KokoroVoices returns the Kokoro voices in catalog order. +func KokoroVoices() []MeetingsTTSVoice { + out := make([]MeetingsTTSVoice, 0, len(kokoroVoiceIDs)) + for _, id := range kokoroVoiceIDs { + if v, ok := KokoroVoice(id); ok { + out = append(out, v) + } + } + return out +} + +// MeetingsVoiceTypeOption is one voice type the settings tab offers. +type MeetingsVoiceTypeOption struct { + ID string `json:"id"` + Label string `json:"label"` + // Available is false for a type no shipped voice provides yet. + Available bool `json:"available"` + Note string `json:"note,omitempty"` +} + +// MeetingsVoiceTypeOptions are the voice types. Kokoro has no robotic +// voice and a bot-style voice would need a new service, so bot-style is +// listed as coming later. +func MeetingsVoiceTypeOptions() []MeetingsVoiceTypeOption { + return []MeetingsVoiceTypeOption{ + {ID: MeetingsPersonaVoiceFemale, Label: "Female", Available: true}, + {ID: MeetingsPersonaVoiceMale, Label: "Male", Available: true}, + {ID: MeetingsPersonaVoiceBot, Label: "Bot-style", Note: "coming later: the self-hosted Kokoro TTS has no bot-style voice"}, + } +} + +// Persona override sources. +const ( + MeetingsPersonaSourceEnv = "env" + MeetingsPersonaSourceConfig = "config" +) + +// Overrides reports which persona fields do not come from the preset (or, +// for the unprompted caps, the defaults), keyed by the meetings.persona key +// ("name", "unprompted.per_10m") with the source: "env" when an +// HIVE_MEETINGS_PERSONA_* variable sets it, else "config" when hive.yaml +// does. The preset itself is reported the same way. +func (p MeetingsPersonaConfig) Overrides() map[string]string { + out := map[string]string{} + set := func(key, env string, inConfig bool) { + switch { + case strings.TrimSpace(os.Getenv(env)) != "": + out[key] = MeetingsPersonaSourceEnv + case inConfig: + out[key] = MeetingsPersonaSourceConfig + } + } + set("enabled", MeetingsPersonaEnabledEnv, p.Enabled != nil) + set("preset", MeetingsPersonaPresetEnv, strings.TrimSpace(p.Preset) != "") + for _, f := range []struct { + key, env, v string + }{ + {"name", MeetingsPersonaNameEnv, p.Name}, + {"display_name", MeetingsPersonaDisplayNameEnv, p.DisplayName}, + {"pronouns", MeetingsPersonaPronounsEnv, p.Pronouns}, + {"language", MeetingsPersonaLanguageEnv, p.Language}, + {"voice", MeetingsPersonaVoiceEnv, p.Voice}, + {"voice_type", MeetingsPersonaVoiceTypeEnv, p.VoiceType}, + {"accent", MeetingsPersonaAccentEnv, p.Accent}, + {"intro_template", MeetingsPersonaIntroTemplateEnv, p.IntroTemplate}, + {"humor", MeetingsPersonaHumorEnv, p.Humor}, + {"searxng_url", MeetingsPersonaSearxngURLEnv, p.SearxngURL}, + } { + set(f.key, f.env, strings.TrimSpace(f.v) != "") + } + set("aliases", MeetingsPersonaAliasesEnv, len(p.Aliases) > 0) + set("leave_phrases", MeetingsPersonaLeavePhrasesEnv, len(p.LeavePhrases) > 0) + u := p.Unprompted + for _, f := range []struct { + key, env string + set bool + }{ + {"unprompted.per_10m", MeetingsPersonaPer10mEnv, u.Per10m > 0}, + {"unprompted.min_gap_s", MeetingsPersonaMinGapEnv, u.MinGapS > 0}, + {"unprompted.per_meeting", MeetingsPersonaPerMeetingEnv, u.PerMeeting > 0}, + {"unprompted.answer_wait_s", MeetingsPersonaAnswerWaitEnv, u.AnswerWaitS > 0}, + {"unprompted.min_confidence", MeetingsPersonaMinConfEnv, u.MinConfidence > 0}, + {"unprompted.queue_depth", MeetingsPersonaQueueDepthEnv, u.QueueDepth > 0}, + {"unprompted.stale_s", MeetingsPersonaStaleEnv, u.StaleS > 0}, + } { + set(f.key, f.env, f.set) + } + return out +} + +// SampleLine renders the effective persona's sample line: the preset's +// line for the persona's language (the persona's own preset when it +// speaks that language, else the first preset that does, else the default +// preset's line), with the intro placeholders filled in. +func (r ResolvedMeetingsPersona) SampleLine() string { + line := "" + if pre, ok := MeetingsPersonaPresets[r.Preset]; ok && strings.EqualFold(pre.Language, r.Language) { + line = pre.SampleLine + } + if line == "" { + for _, pre := range OrderedMeetingsPersonaPresets() { + if strings.EqualFold(pre.Language, r.Language) { + line = pre.SampleLine + break + } + } + } + if line == "" { + line = MeetingsPersonaPresets[DefaultMeetingsPersonaPreset].SampleLine + } + t := r + t.IntroTemplate = line + return t.Intro() +} diff --git a/src/pkg/config/meetings_persona_catalog_test.go b/src/pkg/config/meetings_persona_catalog_test.go new file mode 100644 index 0000000000..0aefb2a3b0 --- /dev/null +++ b/src/pkg/config/meetings_persona_catalog_test.go @@ -0,0 +1,164 @@ +package config + +import ( + "strings" + "testing" + "unicode" +) + +// Every preset must be a persona Validate accepts, speak with a voice the +// self-hosted Kokoro ships in the preset's own language and voice type, and +// carry an intro, a plain intro and a sample line in that language. +func TestMeetingsPersonaPresetsAreKokoroBacked(t *testing.T) { + voices := map[string]MeetingsTTSVoice{} + for _, v := range KokoroVoices() { + voices[v.ID] = v + } + if len(voices) != len(kokoroVoiceIDs) { + t.Fatalf("catalog has %d valid voices of %d ids", len(voices), len(kokoroVoiceIDs)) + } + languages := map[string]bool{} + for id, p := range MeetingsPersonaPresets { + if p.ID != id { + t.Errorf("preset key %q has ID %q", id, p.ID) + } + v, ok := voices[p.Voice] + if !ok { + t.Errorf("%s: voice %q is not a Kokoro voice", id, p.Voice) + continue + } + if v.Language != p.Language || v.VoiceType != p.VoiceType { + t.Errorf("%s: voice %s speaks %s %s, preset says %s %s", id, p.Voice, v.Language, v.VoiceType, p.Language, p.VoiceType) + } + languages[p.Language] = true + if err := (MeetingsPersonaConfig{Preset: id}).Validate(); err != nil { + t.Errorf("%s: %v", id, err) + } + for name, tmpl := range map[string]string{"intro": p.IntroTemplate, "plain intro": p.PlainIntroTemplate} { + if !strings.Contains(tmpl, "{display_name}") || !strings.Contains(tmpl, "{leave}") { + t.Errorf("%s: %s %q must name the persona and the leave phrase", id, name, tmpl) + } + if n := len([]rune(tmpl)); n > meetingsMaxIntroChars { + t.Errorf("%s: %s is %d characters", id, name, n) + } + } + if !strings.Contains(p.SampleLine, "{display_name}") { + t.Errorf("%s: sample line %q", id, p.SampleLine) + } + for _, l := range p.LeavePhrases { + for _, r := range l { + if r > unicode.MaxASCII { + t.Errorf("%s: leave phrase %q must be ASCII (the leave matcher uses ASCII word boundaries)", id, l) + break + } + } + } + if p.LeavePhrases[len(p.LeavePhrases)-1] != "hive leave" || p.Aliases[len(p.Aliases)-1] != "hive" { + t.Errorf("%s: every preset keeps hive as an alias and hive leave as a leave phrase", id) + } + r := MeetingsPersonaConfig{Preset: id, Humor: MeetingsPersonaHumorOff}.Resolve() + if r.IntroTemplate != p.PlainIntroTemplate { + t.Errorf("%s: humor off must use the plain intro", id) + } + } + for _, lang := range []string{"en-US", "en-GB", "es-ES", "fr-FR", "it-IT", "pt-BR", "hi-IN", "ja-JP", "zh-CN"} { + if !languages[lang] { + t.Errorf("no preset speaks %s", lang) + } + } +} + +func TestMeetingsPersonaPresetOrder(t *testing.T) { + ps := OrderedMeetingsPersonaPresets() + if len(ps) != len(MeetingsPersonaPresets) || ps[0].ID != DefaultMeetingsPersonaPreset { + t.Fatalf("ordered %d presets, first %q", len(ps), ps[0].ID) + } + seen := map[string]bool{} + for _, id := range MeetingsPersonaPresetOrder { + if seen[id] { + t.Errorf("%s listed twice", id) + } + seen[id] = true + if _, ok := MeetingsPersonaPresets[id]; !ok { + t.Errorf("order names unknown preset %q", id) + } + } + // A preset the order does not name is listed after the ordered ones. + MeetingsPersonaPresets["zz-extra"] = MeetingsPersonaPreset{ID: "zz-extra"} + MeetingsPersonaPresets["aa-extra"] = MeetingsPersonaPreset{ID: "aa-extra"} + t.Cleanup(func() { + delete(MeetingsPersonaPresets, "zz-extra") + delete(MeetingsPersonaPresets, "aa-extra") + }) + ps = OrderedMeetingsPersonaPresets() + if n := len(ps); ps[n-2].ID != "aa-extra" || ps[n-1].ID != "zz-extra" { + t.Fatalf("unordered presets not appended by ID: %q %q", ps[n-2].ID, ps[n-1].ID) + } +} + +func TestKokoroVoice(t *testing.T) { + if v, ok := KokoroVoice("bm_george"); !ok || v.Language != "en-GB" || v.Accent != "British" || v.VoiceType != MeetingsPersonaVoiceMale { + t.Fatalf("bm_george = %+v %v", v, ok) + } + for _, bad := range []string{"", "af", "af_", "afx_y", "qf_x", "ax_y"} { + if _, ok := KokoroVoice(bad); ok { + t.Errorf("%q accepted", bad) + } + } +} + +func TestMeetingsVoiceTypeOptions(t *testing.T) { + opts := MeetingsVoiceTypeOptions() + got := map[string]bool{} + for _, o := range opts { + got[o.ID] = o.Available + } + if len(opts) != 3 || !got[MeetingsPersonaVoiceFemale] || !got[MeetingsPersonaVoiceMale] || got[MeetingsPersonaVoiceBot] { + t.Fatalf("voice types %+v", opts) + } +} + +func TestMeetingsPersonaOverrides(t *testing.T) { + if o := (MeetingsPersonaConfig{}).Overrides(); len(o) != 0 { + t.Fatalf("zero config overrides %v", o) + } + on := true + p := MeetingsPersonaConfig{ + Enabled: &on, Preset: "bertie", Name: "B", DisplayName: "D", Pronouns: "p", Language: "en-GB", Voice: "bm_lewis", + VoiceType: "male", Accent: "a", IntroTemplate: "i {leave}", Humor: "off", SearxngURL: "http://s", + Aliases: []string{"b"}, LeavePhrases: []string{"b leave"}, + Unprompted: MeetingsPersonaUnprompted{Per10m: 1, MinGapS: 1, PerMeeting: 1, AnswerWaitS: 1, MinConfidence: 0.5, QueueDepth: 1, StaleS: 1}, + } + o := p.Overrides() + for _, k := range []string{"enabled", "preset", "name", "display_name", "pronouns", "language", "voice", "voice_type", "accent", + "intro_template", "humor", "searxng_url", "aliases", "leave_phrases", "unprompted.per_10m", "unprompted.min_gap_s", + "unprompted.per_meeting", "unprompted.answer_wait_s", "unprompted.min_confidence", "unprompted.queue_depth", "unprompted.stale_s"} { + if o[k] != MeetingsPersonaSourceConfig { + t.Errorf("%s = %q, want config", k, o[k]) + } + } + t.Setenv(MeetingsPersonaNameEnv, "Envy") + t.Setenv(MeetingsPersonaPer10mEnv, "4") + o = (MeetingsPersonaConfig{}).Overrides() + if o["name"] != MeetingsPersonaSourceEnv || o["unprompted.per_10m"] != MeetingsPersonaSourceEnv || len(o) != 2 { + t.Fatalf("env overrides %v", o) + } +} + +func TestMeetingsPersonaSampleLine(t *testing.T) { + if got := (MeetingsPersonaConfig{}).Resolve().SampleLine(); got != "Hi, I'm Betty Bee from the hive. Ask me anything about the hive's work and I'll keep it short and sweet." { + t.Fatalf("default sample %q", got) + } + // The persona's own preset speaks the language. + if got := (MeetingsPersonaConfig{Preset: "melie"}).Resolve().SampleLine(); !strings.HasPrefix(got, "Bonjour, je suis Mélie") { + t.Fatalf("melie sample %q", got) + } + // Betty switched to Italian takes the Italian preset's line with her name. + if got := (MeetingsPersonaConfig{Language: "it-IT"}).Resolve().SampleLine(); got != "Ciao, sono Betty Bee from the hive. Chiedimi pure qualcosa sul lavoro dell'alveare." { + t.Fatalf("italian betty sample %q", got) + } + // A language no preset speaks falls back to the default preset's line. + if got := (MeetingsPersonaConfig{Language: "de-DE", DisplayName: "Biene"}).Resolve().SampleLine(); !strings.HasPrefix(got, "Hi, I'm Biene.") { + t.Fatalf("fallback sample %q", got) + } +} diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 5f8ea791aa..8cd84f91ee 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -538,6 +538,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.registerInboxRecordingRoutes() s.registerMeetingsRoutes() s.registerMeetingsScheduleRoutes() + s.registerMeetingsPersonaRoutes() s.mux.HandleFunc("POST /api/system-alerts/dismiss", s.handleSystemAlertDismiss) // Per-agent Variables tab (#11458, api_variables.go). s.registerAgentVariableRoutes() diff --git a/src/pkg/dashboard/api_meetings_persona.go b/src/pkg/dashboard/api_meetings_persona.go new file mode 100644 index 0000000000..d7571dabc8 --- /dev/null +++ b/src/pkg/dashboard/api_meetings_persona.go @@ -0,0 +1,632 @@ +package dashboard + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "reflect" + "sort" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// Meeting attendee settings (hivecommons/hive#18396): Settings, Meeting +// attendee reads and saves meetings.persona (the preset and any field +// overrides), plays a sample line through the meetings TTS service, and +// shows the attendee's email address and inviters. Owner or read-write, +// like the Calendar. The meetings feature resolves the persona at boot, so +// a saved change reports restart_required until the hive restarts. +// +// The TTS service (meetings.tts_url and its token) and the email-in data +// (registered calendar emails, proof status, the approval queue) arrive +// through SetMeetingsTTSResolver and SetMeetingsAttendeeEmail, which +// cmd/hive wires once those features exist; until then the sample says TTS +// is not configured and the email section reports available: false. + +const ( + // meetingsSampleMaxBytes caps the audio a sample returns. + meetingsSampleMaxBytes = 2 << 20 + // meetingsSampleMaxChars caps a caller-supplied sample line. + meetingsSampleMaxChars = 200 + // meetingsSampleTimeout bounds one TTS call. + meetingsSampleTimeout = 20 * time.Second + // meetingsTTSSpeechPath is the OpenAI-compatible speech route Kokoro + // serves. + meetingsTTSSpeechPath = "/v1/audio/speech" + // meetingsTTSModel is the model name Kokoro-FastAPI accepts. + meetingsTTSModel = "kokoro" + // meetingsTTSFormat is the audio format asked for; every browser plays it. + meetingsTTSFormat = "mp3" + // meetingsTTSDefaultContentType is used when the TTS service sends no + // audio content type. + meetingsTTSDefaultContentType = "audio/mpeg" + // meetingsTTSErrorBodyMax bounds the TTS error text echoed back. + meetingsTTSErrorBodyMax = 300 + // meetingsAttendeeMailbox is the local part of the attendee address. + meetingsAttendeeMailbox = "hive" +) + +// ErrMeetingsTTSNotConfigured is returned by a MeetingsTTSResolver when +// no TTS service is set. +var ErrMeetingsTTSNotConfigured = errors.New("TTS not configured: set meetings.tts_url (and its token) to play samples") + +// MeetingsTTSConfig is the TTS service a sample is spoken through. +type MeetingsTTSConfig struct { + URL string + Token string +} + +// MeetingsTTSResolver returns the TTS service, or an error wrapping +// ErrMeetingsTTSNotConfigured when none is set. +type MeetingsTTSResolver func(ctx context.Context) (MeetingsTTSConfig, error) + +// MeetingsCalendarEmail is one calendar address a user registered for +// invites, with its proof status ("verified" or "pending"). +type MeetingsCalendarEmail struct { + Address string `json:"address"` + Proof string `json:"proof"` + VerifiedAt string `json:"verified_at,omitempty"` +} + +// MeetingsEmailApproval is one mail waiting for the owner: an invite or +// mail-in file from someone not on the allowlist. +type MeetingsEmailApproval struct { + ID string `json:"id"` + Kind string `json:"kind"` + From string `json:"from"` + Subject string `json:"subject,omitempty"` + ReceivedAt string `json:"received_at,omitempty"` +} + +// MeetingsAttendeeEmailSnapshot is the email-in state. +type MeetingsAttendeeEmailSnapshot struct { + // Emails are the registered calendar emails by login. + Emails map[string][]MeetingsCalendarEmail + Approvals []MeetingsEmailApproval + CalendarInvites bool + MailInFiles bool +} + +// MeetingsAttendeeEmail is the email-in feature as the settings tab sees it. +type MeetingsAttendeeEmail interface { + Snapshot(ctx context.Context) (MeetingsAttendeeEmailSnapshot, error) +} + +// meetingsAttendeeState is the Server's attendee settings state. +type meetingsAttendeeState struct { + mu sync.Mutex + bootOnce sync.Once + // boot is what the running hive resolved at start. + boot meetingsAttendeeBoot + tts MeetingsTTSResolver + email MeetingsAttendeeEmail + // client calls the TTS service; nil uses a client with + // meetingsSampleTimeout. + client *http.Client +} + +// meetingsAttendeeBoot is the attendee configuration a hive resolves at +// start; a saved change to it needs a restart. +type meetingsAttendeeBoot struct { + Persona config.ResolvedMeetingsPersona + VoiceOnAddress bool +} + +func meetingsAttendeeBootOf(m config.MeetingsConfig) meetingsAttendeeBoot { + return meetingsAttendeeBoot{Persona: m.Persona.Resolve(), VoiceOnAddress: m.VoiceOnAddressEnabled()} +} + +// SetMeetingsTTSResolver installs the TTS service lookup (nil removes it). +func (s *Server) SetMeetingsTTSResolver(fn MeetingsTTSResolver) { + s.meetingsAttendee.mu.Lock() + defer s.meetingsAttendee.mu.Unlock() + s.meetingsAttendee.tts = fn +} + +// SetMeetingsAttendeeEmail installs the email-in data (nil removes it). +func (s *Server) SetMeetingsAttendeeEmail(e MeetingsAttendeeEmail) { + s.meetingsAttendee.mu.Lock() + defer s.meetingsAttendee.mu.Unlock() + s.meetingsAttendee.email = e +} + +func (s *Server) meetingsAttendeeDeps() (MeetingsTTSResolver, MeetingsAttendeeEmail, *http.Client) { + s.meetingsAttendee.mu.Lock() + defer s.meetingsAttendee.mu.Unlock() + c := s.meetingsAttendee.client + if c == nil { + c = &http.Client{Timeout: meetingsSampleTimeout} + } + return s.meetingsAttendee.tts, s.meetingsAttendee.email, c +} + +// captureMeetingsPersonaBoot records the persona the hive booted with. It +// runs when the routes register, before any save. +func (s *Server) captureMeetingsPersonaBoot() { + s.meetingsAttendee.bootOnce.Do(func() { + if s.deps != nil && s.deps.Config != nil { + s.meetingsAttendee.boot = meetingsAttendeeBootOf(s.deps.Config.Meetings) + } + }) +} + +func (s *Server) registerMeetingsPersonaRoutes() { + s.captureMeetingsPersonaBoot() + s.mux.HandleFunc("GET /api/meetings/persona", s.handleMeetingsPersonaGet) + s.mux.HandleFunc("PUT /api/meetings/persona", s.handleMeetingsPersonaPut) + s.mux.HandleFunc("POST /api/meetings/persona/sample", s.handleMeetingsPersonaSample) +} + +// MeetingsPersonaUnpromptedView is the effective unprompted caps. +type MeetingsPersonaUnpromptedView struct { + Per10m int `json:"per_10m"` + MinGapS int `json:"min_gap_s"` + PerMeeting int `json:"per_meeting"` + AnswerWaitS int `json:"answer_wait_s"` + MinConfidence float64 `json:"min_confidence"` + QueueDepth int `json:"queue_depth"` + StaleS int `json:"stale_s"` +} + +// MeetingsPersonaView is the effective persona. +type MeetingsPersonaView struct { + Enabled bool `json:"enabled"` + Preset string `json:"preset"` + Name string `json:"name"` + DisplayName string `json:"display_name"` + Aliases []string `json:"aliases"` + Pronouns string `json:"pronouns"` + Language string `json:"language"` + Voice string `json:"voice"` + VoiceType string `json:"voice_type"` + Accent string `json:"accent"` + IntroTemplate string `json:"intro_template"` + Intro string `json:"intro"` + LeavePhrases []string `json:"leave_phrases"` + Humor string `json:"humor"` + Unprompted MeetingsPersonaUnpromptedView `json:"unprompted"` + // VoiceOnAddress is meetings.voice_on_address: hive may speak when + // addressed (otherwise replies go to chat). + VoiceOnAddress bool `json:"voice_on_address"` +} + +// MeetingsAttendeeInviter is one person on the live access list. +type MeetingsAttendeeInviter struct { + Login string `json:"login"` + DisplayName string `json:"display_name,omitempty"` + Role string `json:"role"` + Emails []MeetingsCalendarEmail `json:"emails"` +} + +// MeetingsAttendeeEmailView is the Email section. +type MeetingsAttendeeEmailView struct { + // Available is false until email-in is enabled (hivecommons/hive#18395); + // the tab then shows the section with its controls disabled. + Available bool `json:"available"` + Address string `json:"address"` + Inviters []MeetingsAttendeeInviter `json:"inviters"` + Approvals []MeetingsEmailApproval `json:"approvals"` + CalendarInvites bool `json:"calendar_invites"` + MailInFiles bool `json:"mail_in_files"` + Error string `json:"error,omitempty"` +} + +// MeetingsPersonaSettings is GET and PUT /api/meetings/persona. +type MeetingsPersonaSettings struct { + Effective MeetingsPersonaView `json:"effective"` + Presets []config.MeetingsPersonaPreset `json:"presets"` + // Overridden maps each meetings.persona key not taken from the preset + // (or the defaults) to its source, "config" or "env". + Overridden map[string]string `json:"overridden"` + Voices []config.MeetingsTTSVoice `json:"voices"` + VoiceTypes []config.MeetingsVoiceTypeOption `json:"voice_types"` + // RestartRequired is true when the saved persona differs from the one + // the running hive booted with. + RestartRequired bool `json:"restart_required"` + Running bool `json:"running"` + TTSConfigured bool `json:"tts_configured"` + Email MeetingsAttendeeEmailView `json:"email"` +} + +// resolvePersonaFields resolves the persona's fields as if it were on: a +// disabled persona resolves its name to "hive", but the tab edits (and +// samples) the persona that turning it back on would bring. +func resolvePersonaFields(p config.MeetingsPersonaConfig) config.ResolvedMeetingsPersona { + on := true + p.Enabled = &on + return p.Resolve() +} + +func meetingsPersonaView(m config.MeetingsConfig) MeetingsPersonaView { + r := resolvePersonaFields(m.Persona) + u := r.Unprompted + return MeetingsPersonaView{ + Enabled: m.Persona.IsEnabled(), Preset: r.Preset, Name: r.Name, DisplayName: r.DisplayName, + Aliases: nonNilStrings(r.Aliases), Pronouns: r.Pronouns, Language: r.Language, Voice: r.Voice, + VoiceType: r.VoiceType, Accent: r.Accent, IntroTemplate: r.IntroTemplate, Intro: r.Intro(), + LeavePhrases: nonNilStrings(r.LeavePhrases), Humor: r.Humor, + Unprompted: MeetingsPersonaUnpromptedView{ + Per10m: u.Per10m, MinGapS: u.MinGapS, PerMeeting: u.PerMeeting, AnswerWaitS: u.AnswerWaitS, + MinConfidence: u.MinConfidence, QueueDepth: u.QueueDepth, StaleS: u.StaleS, + }, + VoiceOnAddress: m.VoiceOnAddressEnabled(), + } +} + +func nonNilStrings(in []string) []string { + if in == nil { + return []string{} + } + return in +} + +// meetingsAttendeeHost is the dashboard host the attendee address uses: +// the forwarded host behind a proxy, else the request host, without a port. +func meetingsAttendeeHost(r *http.Request) string { + host := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Host"), ",")[0]) + if host == "" { + host = r.Host + } + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + return strings.ToLower(strings.Trim(host, "[]")) +} + +func (s *Server) meetingsAttendeeEmail(r *http.Request, email MeetingsAttendeeEmail) MeetingsAttendeeEmailView { + out := MeetingsAttendeeEmailView{Inviters: []MeetingsAttendeeInviter{}, Approvals: []MeetingsEmailApproval{}} + if host := meetingsAttendeeHost(r); host != "" { + out.Address = meetingsAttendeeMailbox + "@" + host + } + var snap MeetingsAttendeeEmailSnapshot + if email != nil { + var err error + if snap, err = email.Snapshot(r.Context()); err != nil { + out.Error = err.Error() + } else { + out.Available = true + out.CalendarInvites, out.MailInFiles = snap.CalendarInvites, snap.MailInFiles + if snap.Approvals != nil { + out.Approvals = snap.Approvals + } + } + } + d := s.deps.Config.Dashboard + for i, entry := range d.AuthorizedUsers { + login, role := dashboardAuthorizedUserEntry(entry) + if login == "" { + continue + } + if role == "" { + role = config.RoleRead + if i == 0 { + role = config.RoleOwner + } + } + // Everyone with access (read and up) may invite the attendee. + if !config.RoleAtLeast(role, config.RoleRead) { + continue + } + emails := snap.Emails[login] + if emails == nil { + emails = []MeetingsCalendarEmail{} + } + out.Inviters = append(out.Inviters, MeetingsAttendeeInviter{ + Login: login, DisplayName: strings.TrimSpace(d.AuthorizedUserNames[login]), Role: role, Emails: emails, + }) + } + sort.Slice(out.Inviters, func(i, j int) bool { return out.Inviters[i].Login < out.Inviters[j].Login }) + return out +} + +func (s *Server) meetingsPersonaSettings(r *http.Request) MeetingsPersonaSettings { + tts, email, _ := s.meetingsAttendeeDeps() + m := s.deps.Config.Meetings + h := (&s.meetings).Load() + ttsOK := false + if tts != nil { + cfg, err := tts(r.Context()) + ttsOK = err == nil && cfg.URL != "" + } + return MeetingsPersonaSettings{ + Effective: meetingsPersonaView(m), + Presets: config.OrderedMeetingsPersonaPresets(), + Overridden: m.Persona.Overrides(), + Voices: config.KokoroVoices(), + VoiceTypes: config.MeetingsVoiceTypeOptions(), + RestartRequired: !reflect.DeepEqual(meetingsAttendeeBootOf(m), s.meetingsAttendee.boot), + Running: h != nil && h.svc != nil, + TTSConfigured: ttsOK, + Email: s.meetingsAttendeeEmail(r, email), + } +} + +func (s *Server) meetingsPersonaConfigReady(w http.ResponseWriter, r *http.Request) bool { + if _, ok := requireMeetingsScheduleRole(w, r); !ok { + return false + } + if s.deps == nil || s.deps.Config == nil { + jsonError(w, "config is not available", http.StatusServiceUnavailable) + return false + } + return true +} + +func (s *Server) handleMeetingsPersonaGet(w http.ResponseWriter, r *http.Request) { + if !s.meetingsPersonaConfigReady(w, r) { + return + } + jsonResponse(w, s.meetingsPersonaSettings(r)) +} + +// meetingsPersonaUnpromptedRequest sets the unprompted caps; 0 restores a +// default. +type meetingsPersonaUnpromptedRequest struct { + Per10m *int `json:"per_10m,omitempty"` + MinGapS *int `json:"min_gap_s,omitempty"` + PerMeeting *int `json:"per_meeting,omitempty"` + AnswerWaitS *int `json:"answer_wait_s,omitempty"` + MinConfidence *float64 `json:"min_confidence,omitempty"` + QueueDepth *int `json:"queue_depth,omitempty"` + StaleS *int `json:"stale_s,omitempty"` +} + +// meetingsPersonaRequest is PUT /api/meetings/persona. An absent field is +// unchanged; an empty string or list clears the override, so the field +// follows the preset again. A value equal to the preset's is stored as no +// override. clear_overrides drops every field override first (picking a +// preset card). +type meetingsPersonaRequest struct { + Enabled *bool `json:"enabled,omitempty"` + Preset *string `json:"preset,omitempty"` + ClearOverrides bool `json:"clear_overrides,omitempty"` + Name *string `json:"name,omitempty"` + DisplayName *string `json:"display_name,omitempty"` + Aliases *[]string `json:"aliases,omitempty"` + Pronouns *string `json:"pronouns,omitempty"` + Language *string `json:"language,omitempty"` + Voice *string `json:"voice,omitempty"` + VoiceType *string `json:"voice_type,omitempty"` + Accent *string `json:"accent,omitempty"` + IntroTemplate *string `json:"intro_template,omitempty"` + LeavePhrases *[]string `json:"leave_phrases,omitempty"` + Humor *string `json:"humor,omitempty"` + Unprompted *meetingsPersonaUnpromptedRequest `json:"unprompted,omitempty"` + // VoiceOnAddress sets meetings.voice_on_address. + VoiceOnAddress *bool `json:"voice_on_address,omitempty"` +} + +// applyMeetingsPersonaRequest returns p with req applied. +func applyMeetingsPersonaRequest(p config.MeetingsPersonaConfig, req meetingsPersonaRequest) config.MeetingsPersonaConfig { + if req.Enabled != nil { + v := *req.Enabled + p.Enabled = &v + } + if req.Preset != nil { + p.Preset = strings.ToLower(strings.TrimSpace(*req.Preset)) + } + if req.ClearOverrides { + p = config.MeetingsPersonaConfig{Enabled: p.Enabled, Preset: p.Preset, Unprompted: p.Unprompted, SearxngURL: p.SearxngURL} + } + pre, ok := config.MeetingsPersonaPresets[p.Preset] + if !ok { + pre = config.MeetingsPersonaPresets[config.DefaultMeetingsPersonaPreset] + } + str := func(dst *string, v *string, preset string) { + if v == nil { + return + } + x := strings.TrimSpace(*v) + if x == preset { + x = "" + } + *dst = x + } + str(&p.Name, req.Name, pre.Name) + str(&p.DisplayName, req.DisplayName, pre.DisplayName) + str(&p.Pronouns, req.Pronouns, pre.Pronouns) + str(&p.Language, req.Language, pre.Language) + str(&p.Voice, req.Voice, pre.Voice) + str(&p.VoiceType, req.VoiceType, pre.VoiceType) + str(&p.Accent, req.Accent, pre.Accent) + str(&p.Humor, req.Humor, pre.Humor) + if req.IntroTemplate != nil { + // The preset intro depends on humor, so compare with both. + x := strings.TrimSpace(*req.IntroTemplate) + if x == pre.IntroTemplate || x == pre.PlainIntroTemplate { + x = "" + } + p.IntroTemplate = x + } + list := func(dst *[]string, v *[]string, preset []string) { + if v == nil { + return + } + var out []string + for _, s := range *v { + if s = strings.TrimSpace(s); s != "" { + out = append(out, s) + } + } + if strings.EqualFold(strings.Join(out, "\x00"), strings.Join(preset, "\x00")) { + out = nil + } + *dst = out + } + list(&p.Aliases, req.Aliases, pre.Aliases) + list(&p.LeavePhrases, req.LeavePhrases, pre.LeavePhrases) + if u := req.Unprompted; u != nil { + setInt := func(dst *int, v *int) { + if v != nil { + *dst = *v + } + } + setInt(&p.Unprompted.Per10m, u.Per10m) + setInt(&p.Unprompted.MinGapS, u.MinGapS) + setInt(&p.Unprompted.PerMeeting, u.PerMeeting) + setInt(&p.Unprompted.AnswerWaitS, u.AnswerWaitS) + setInt(&p.Unprompted.QueueDepth, u.QueueDepth) + setInt(&p.Unprompted.StaleS, u.StaleS) + if u.MinConfidence != nil { + p.Unprompted.MinConfidence = *u.MinConfidence + } + } + return p +} + +// handleMeetingsPersonaPut saves meetings.persona to hive.yaml. The +// persona is validated as if enabled, so a disabled persona is still a +// valid one to turn back on. +func (s *Server) handleMeetingsPersonaPut(w http.ResponseWriter, r *http.Request) { + if !s.meetingsPersonaConfigReady(w, r) { + return + } + var req meetingsPersonaRequest + if err := decodeBody(r, &req); err != nil { + jsonError(w, "invalid request body", http.StatusBadRequest) + return + } + next := applyMeetingsPersonaRequest(s.deps.Config.Meetings.Persona, req) + check := next + on := true + check.Enabled = &on + if err := check.Validate(); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + s.deps.Config.Meetings.Persona = next + if req.VoiceOnAddress != nil { + v := *req.VoiceOnAddress + s.deps.Config.Meetings.VoiceOnAddress = &v + } + if err := s.saveConfig(); err != nil { + jsonError(w, "saving config: "+err.Error(), http.StatusInternalServerError) + return + } + res := next.Resolve() + s.auditFromRequest(r, "meetings_persona", auditDetail("preset", res.Preset, "enabled", boolString(res.Enabled), + "voice", res.Voice, "language", res.Language), "") + jsonResponse(w, s.meetingsPersonaSettings(r)) +} + +// meetingsPersonaSampleRequest is POST /api/meetings/persona/sample: an +// optional voice (default the persona's), language (picks the sample +// line's language) and text (default the persona's sample line). +type meetingsPersonaSampleRequest struct { + Voice string `json:"voice,omitempty"` + Language string `json:"language,omitempty"` + DisplayName string `json:"display_name,omitempty"` + Text string `json:"text,omitempty"` +} + +// meetingsTTSSpeechRequest is Kokoro's OpenAI-compatible speech body. +type meetingsTTSSpeechRequest struct { + Model string `json:"model"` + Input string `json:"input"` + Voice string `json:"voice"` + ResponseFormat string `json:"response_format"` + Stream bool `json:"stream"` +} + +// handleMeetingsPersonaSample speaks a short line through the TTS service +// and returns the audio for the browser to play. +func (s *Server) handleMeetingsPersonaSample(w http.ResponseWriter, r *http.Request) { + if !s.meetingsPersonaConfigReady(w, r) { + return + } + var req meetingsPersonaSampleRequest + if r.ContentLength != 0 { + if err := decodeBody(r, &req); err != nil { + jsonError(w, "invalid request body", http.StatusBadRequest) + return + } + } + tts, _, client := s.meetingsAttendeeDeps() + if tts == nil { + jsonError(w, ErrMeetingsTTSNotConfigured.Error(), http.StatusServiceUnavailable) + return + } + cfg, err := tts(r.Context()) + if err == nil && strings.TrimSpace(cfg.URL) == "" { + err = ErrMeetingsTTSNotConfigured + } + if err != nil { + jsonError(w, err.Error(), http.StatusServiceUnavailable) + return + } + persona := resolvePersonaFields(s.deps.Config.Meetings.Persona) + if v := strings.TrimSpace(req.Voice); v != "" { + persona.Voice = v + } + if l := strings.TrimSpace(req.Language); l != "" { + persona.Language = l + } + if d := strings.TrimSpace(req.DisplayName); d != "" { + persona.DisplayName = d + } + text := strings.Join(strings.Fields(req.Text), " ") + if text == "" { + text = persona.SampleLine() + } + if n := len([]rune(text)); n > meetingsSampleMaxChars { + jsonError(w, fmt.Sprintf("sample text is %d characters, at most %d", n, meetingsSampleMaxChars), http.StatusBadRequest) + return + } + audio, ctype, status, err := meetingsSpeak(r.Context(), client, cfg, persona.Voice, text) + if err != nil { + jsonError(w, err.Error(), status) + return + } + w.Header().Set("Content-Type", ctype) + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + _, _ = w.Write(audio) +} + +// meetingsSpeak calls the TTS service. On failure it returns the HTTP +// status to answer with. +func meetingsSpeak(ctx context.Context, client *http.Client, cfg MeetingsTTSConfig, voice, text string) ([]byte, string, int, error) { + body, _ := json.Marshal(meetingsTTSSpeechRequest{Model: meetingsTTSModel, Input: text, Voice: voice, ResponseFormat: meetingsTTSFormat}) + ctx, cancel := context.WithTimeout(ctx, meetingsSampleTimeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(cfg.URL, "/")+meetingsTTSSpeechPath, bytes.NewReader(body)) + if err != nil { + return nil, "", http.StatusServiceUnavailable, fmt.Errorf("TTS URL: %w", err) + } + req.Header.Set("Content-Type", "application/json") + if cfg.Token != "" { + req.Header.Set("Authorization", "Bearer "+cfg.Token) + } + resp, err := client.Do(req) + if err != nil { + return nil, "", http.StatusBadGateway, fmt.Errorf("TTS service: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + msg, _ := io.ReadAll(io.LimitReader(resp.Body, meetingsTTSErrorBodyMax)) + return nil, "", http.StatusBadGateway, fmt.Errorf("TTS service returned %d: %s", resp.StatusCode, strings.TrimSpace(string(msg))) + } + audio, err := io.ReadAll(io.LimitReader(resp.Body, meetingsSampleMaxBytes+1)) + if err != nil { + return nil, "", http.StatusBadGateway, fmt.Errorf("reading TTS audio: %w", err) + } + if len(audio) > meetingsSampleMaxBytes { + return nil, "", http.StatusBadGateway, fmt.Errorf("TTS audio is over %d bytes", meetingsSampleMaxBytes) + } + if len(audio) == 0 { + return nil, "", http.StatusBadGateway, errors.New("TTS service returned no audio") + } + ctype := strings.TrimSpace(resp.Header.Get("Content-Type")) + if !strings.HasPrefix(strings.ToLower(ctype), "audio/") { + ctype = meetingsTTSDefaultContentType + } + return audio, ctype, http.StatusOK, nil +} diff --git a/src/pkg/dashboard/api_meetings_persona_test.go b/src/pkg/dashboard/api_meetings_persona_test.go new file mode 100644 index 0000000000..b02822cf0c --- /dev/null +++ b/src/pkg/dashboard/api_meetings_persona_test.go @@ -0,0 +1,361 @@ +package dashboard + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +func personaReq(s *Server, method, path, body, role string, verified bool, hdr ...string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + var rd io.Reader + if body != "" { + rd = strings.NewReader(body) + } + req := httptest.NewRequest(method, path, rd) + req.Host = "hive.example.org:8443" + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Hive-User", "octo") + if role != "" { + req.Header.Set("X-Hive-Role", role) + } + if verified { + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + for i := 0; i+1 < len(hdr); i += 2 { + req.Header.Set(hdr[i], hdr[i+1]) + } + s.mux.ServeHTTP(rec, req) + return rec +} + +func personaGet(t *testing.T, s *Server) MeetingsPersonaSettings { + t.Helper() + rec := personaReq(s, http.MethodGet, "/api/meetings/persona", "", "owner", true) + if rec.Code != http.StatusOK { + t.Fatalf("get = %d %s", rec.Code, rec.Body.String()) + } + var got MeetingsPersonaSettings + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + return got +} + +func personaPut(t *testing.T, s *Server, body string, want int) MeetingsPersonaSettings { + t.Helper() + rec := personaReq(s, http.MethodPut, "/api/meetings/persona", body, "read-write", false) + if rec.Code != want { + t.Fatalf("put %s = %d %s", body, rec.Code, rec.Body.String()) + } + var got MeetingsPersonaSettings + if want == http.StatusOK { + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + } + return got +} + +func TestMeetingsPersonaAuth(t *testing.T) { + s, deps := apiServer(t) + cases := []struct{ method, path string }{ + {http.MethodGet, "/api/meetings/persona"}, + {http.MethodPut, "/api/meetings/persona"}, + {http.MethodPost, "/api/meetings/persona/sample"}, + } + for _, c := range cases { + if rec := personaReq(s, c.method, c.path, "{}", "read", false); rec.Code != http.StatusForbidden { + t.Errorf("%s %s as read = %d", c.method, c.path, rec.Code) + } + if rec := personaReq(s, c.method, c.path, "{}", "owner", false); rec.Code != http.StatusForbidden { + t.Errorf("%s %s as unverified owner = %d", c.method, c.path, rec.Code) + } + } + if rec := personaReq(s, http.MethodGet, "/api/meetings/persona", "", "read-write", false); rec.Code != http.StatusOK { + t.Fatalf("read-write get = %d", rec.Code) + } + deps.Config = nil + for _, c := range cases { + if rec := personaReq(s, c.method, c.path, "{}", "owner", true); rec.Code != http.StatusServiceUnavailable { + t.Errorf("%s %s without config = %d", c.method, c.path, rec.Code) + } + } +} + +func TestMeetingsPersonaGetDefaults(t *testing.T) { + s, deps := apiServer(t) + deps.Config.Dashboard.AuthorizedUsers = []string{"alice", "bob:read-write", "carol:read", "dave:merger", ""} + deps.Config.Dashboard.AuthorizedUserNames = map[string]string{"bob": " Bob B "} + got := personaGet(t, s) + e := got.Effective + if !e.Enabled || e.Preset != "betty" || e.Name != "Betty" || e.Voice != "af_heart" || e.Language != "en-US" || + !strings.Contains(e.Intro, "Betty Bee from the hive") || e.Unprompted.AnswerWaitS != config.DefaultMeetingsPersonaAnswerWaitS { + t.Fatalf("effective %+v", e) + } + if len(got.Presets) != len(config.MeetingsPersonaPresets) || got.Presets[0].ID != "betty" { + t.Fatalf("presets %d, first %q", len(got.Presets), got.Presets[0].ID) + } + if len(got.Overridden) != 0 || got.RestartRequired || got.Running || got.TTSConfigured { + t.Fatalf("flags %+v", got) + } + if len(got.Voices) == 0 || len(got.VoiceTypes) != 3 { + t.Fatalf("voices %d, types %d", len(got.Voices), len(got.VoiceTypes)) + } + em := got.Email + if em.Available || em.Address != "hive@hive.example.org" || len(em.Approvals) != 0 { + t.Fatalf("email %+v", em) + } + roles := map[string]string{} + for _, in := range em.Inviters { + roles[in.Login] = in.Role + if in.Emails == nil { + t.Fatalf("%s emails must be [] not null", in.Login) + } + } + if len(roles) != 4 || roles["alice"] != "owner" || roles["bob"] != "read-write" || roles["carol"] != "read" || roles["dave"] != "merger" { + t.Fatalf("inviters %+v", em.Inviters) + } + if em.Inviters[1].DisplayName != "Bob B" { + t.Fatalf("display name %+v", em.Inviters[1]) + } + // Behind a proxy the forwarded host names the address. + rec := personaReq(s, http.MethodGet, "/api/meetings/persona", "", "owner", true, "X-Forwarded-Host", "Spoke.Hivecommons.dev, inner") + var fwd MeetingsPersonaSettings + _ = json.Unmarshal(rec.Body.Bytes(), &fwd) + if fwd.Email.Address != "hive@spoke.hivecommons.dev" { + t.Fatalf("forwarded address %q", fwd.Email.Address) + } +} + +type fakeAttendeeEmail struct { + snap MeetingsAttendeeEmailSnapshot + err error +} + +func (f fakeAttendeeEmail) Snapshot(context.Context) (MeetingsAttendeeEmailSnapshot, error) { + return f.snap, f.err +} + +func TestMeetingsPersonaEmailProvider(t *testing.T) { + s, deps := apiServer(t) + deps.Config.Dashboard.AuthorizedUsers = []string{"alice", "bob:read-write"} + s.SetMeetingsAttendeeEmail(fakeAttendeeEmail{snap: MeetingsAttendeeEmailSnapshot{ + Emails: map[string][]MeetingsCalendarEmail{"bob": {{Address: "bob@example.com", Proof: "verified"}}}, + Approvals: []MeetingsEmailApproval{{ID: "a1", Kind: "invite", From: "x@example.net"}}, + CalendarInvites: true, MailInFiles: true, + }}) + em := personaGet(t, s).Email + if !em.Available || !em.CalendarInvites || !em.MailInFiles || len(em.Approvals) != 1 || em.Error != "" { + t.Fatalf("email %+v", em) + } + if em.Inviters[1].Login != "bob" || len(em.Inviters[1].Emails) != 1 || em.Inviters[1].Emails[0].Proof != "verified" || len(em.Inviters[0].Emails) != 0 { + t.Fatalf("inviters %+v", em.Inviters) + } + s.SetMeetingsAttendeeEmail(fakeAttendeeEmail{err: errors.New("mail store down")}) + em = personaGet(t, s).Email + if em.Available || em.Error != "mail store down" || len(em.Inviters) != 2 { + t.Fatalf("email error %+v", em) + } + s.SetMeetingsAttendeeEmail(nil) + if personaGet(t, s).Email.Available { + t.Fatal("removed email provider still available") + } +} + +func TestMeetingsPersonaPut(t *testing.T) { + s, deps := apiServer(t) + // Picking a preset card drops field overrides and needs a restart. + deps.Config.Meetings.Persona.Name = "Old" + got := personaPut(t, s, `{"preset":" Melie ","clear_overrides":true}`, http.StatusOK) + if got.Effective.Name != "Mélie" || got.Effective.Language != "fr-FR" || got.Effective.Voice != "ff_siwis" || !got.RestartRequired { + t.Fatalf("melie %+v", got.Effective) + } + if len(got.Overridden) != 1 || got.Overridden["preset"] != "config" { + t.Fatalf("overridden %v", got.Overridden) + } + // A value equal to the preset's is not an override. + got = personaPut(t, s, `{"name":"Mélie","aliases":["Mélie","melie","abeille","hive"],"intro_template":`+jsonString(config.MeetingsPersonaPresets["melie"].PlainIntroTemplate)+`}`, http.StatusOK) + if len(got.Overridden) != 1 { + t.Fatalf("preset-equal values stored as overrides: %v", got.Overridden) + } + got = personaPut(t, s, `{"enabled":false,"name":" Zed ","display_name":"Zed Bee","pronouns":"they/them","language":"fr-CA","voice":"ff_siwis", + "voice_type":"male","accent":"Québécois","humor":"off","intro_template":"Salut, {name}. {leave}", + "aliases":["zed"," ",""],"leave_phrases":["zed leave"], + "unprompted":{"per_10m":4,"min_gap_s":30,"per_meeting":5,"answer_wait_s":3,"min_confidence":0.9,"queue_depth":2,"stale_s":20}, + "voice_on_address":false}`, http.StatusOK) + e := got.Effective + if e.VoiceOnAddress || deps.Config.Meetings.VoiceOnAddress == nil || *deps.Config.Meetings.VoiceOnAddress { + t.Fatalf("voice_on_address %+v", e) + } + if e.Enabled || e.Name != "Zed" || e.DisplayName != "Zed Bee" || e.VoiceType != "male" || e.Humor != "off" || + strings.Join(e.Aliases, ",") != "zed" || strings.Join(e.LeavePhrases, ",") != "zed leave" || + e.Unprompted.Per10m != 4 || e.Unprompted.MinConfidence != 0.9 || e.Unprompted.StaleS != 20 { + t.Fatalf("overrides %+v", e) + } + for _, k := range []string{"enabled", "name", "display_name", "pronouns", "language", "voice_type", "accent", "humor", + "intro_template", "aliases", "leave_phrases", "unprompted.per_10m", "unprompted.min_confidence"} { + if got.Overridden[k] != "config" { + t.Errorf("%s not reported overridden: %v", k, got.Overridden) + } + } + if _, ok := got.Overridden["voice"]; ok { + t.Error("voice equal to the preset reported as overridden") + } + p := deps.Config.Meetings.Persona + if p.Preset != "melie" || p.Name != "Zed" || p.Voice != "" || p.Enabled == nil || *p.Enabled { + t.Fatalf("stored %+v", p) + } + // Empty values clear the overrides; clear_overrides keeps the caps. + got = personaPut(t, s, `{"name":"","aliases":[],"enabled":true}`, http.StatusOK) + if got.Effective.Name != "Mélie" || strings.Join(got.Effective.Aliases, ",") != "mélie,melie,abeille,hive" { + t.Fatalf("cleared %+v", got.Effective) + } + got = personaPut(t, s, `{"preset":"bertie","clear_overrides":true}`, http.StatusOK) + if got.Effective.Name != "Bertie" || got.Effective.Humor != "light" || got.Effective.Unprompted.Per10m != 4 { + t.Fatalf("bertie %+v", got.Effective) + } + for _, bad := range []string{`{"preset":"nobody"}`, `{"humor":"loud"}`, `{"voice_type":"robot"}`, `{"language":"not a tag"}`, + `{"unprompted":{"min_confidence":2}}`, `{"unprompted":{"per_10m":-1}}`, `{`} { + personaPut(t, s, bad, http.StatusBadRequest) + } + if deps.Config.Meetings.Persona.Preset != "bertie" { + t.Fatal("a rejected save must not change the config") + } +} + +func jsonString(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + +func samplePost(s *Server, body string) *httptest.ResponseRecorder { + return personaReq(s, http.MethodPost, "/api/meetings/persona/sample", body, "owner", true) +} + +func TestMeetingsPersonaSampleNotConfigured(t *testing.T) { + s, _ := apiServer(t) + rec := samplePost(s, "") + if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "TTS not configured") { + t.Fatalf("no resolver = %d %s", rec.Code, rec.Body.String()) + } + s.SetMeetingsTTSResolver(func(context.Context) (MeetingsTTSConfig, error) { return MeetingsTTSConfig{}, nil }) + if rec := samplePost(s, `{}`); rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "TTS not configured") { + t.Fatalf("empty url = %d %s", rec.Code, rec.Body.String()) + } + if personaGet(t, s).TTSConfigured { + t.Fatal("an empty TTS URL is not configured") + } + s.SetMeetingsTTSResolver(func(context.Context) (MeetingsTTSConfig, error) { + return MeetingsTTSConfig{}, errors.New("tts token unreadable") + }) + if rec := samplePost(s, `{}`); rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "unreadable") { + t.Fatalf("resolver error = %d %s", rec.Code, rec.Body.String()) + } + s.SetMeetingsTTSResolver(func(context.Context) (MeetingsTTSConfig, error) { return MeetingsTTSConfig{URL: "http://[::1"}, nil }) + if rec := samplePost(s, `{}`); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("bad url = %d %s", rec.Code, rec.Body.String()) + } + if rec := samplePost(s, `{`); rec.Code != http.StatusBadRequest { + t.Fatalf("bad body = %d", rec.Code) + } +} + +func TestMeetingsPersonaSample(t *testing.T) { + s, _ := apiServer(t) + var ( + mu sync.Mutex + seen meetingsTTSSpeechRequest + token string + ) + reply := func(w http.ResponseWriter) { + w.Header().Set("Content-Type", "audio/mpeg") + _, _ = w.Write([]byte("ID3audio")) + } + setReply := func(fn func(http.ResponseWriter)) { + mu.Lock() + defer mu.Unlock() + reply = fn + } + lastReq := func() (meetingsTTSSpeechRequest, string) { + mu.Lock() + defer mu.Unlock() + return seen, token + } + tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != meetingsTTSSpeechPath || r.Method != http.MethodPost { + http.NotFound(w, r) + return + } + var body meetingsTTSSpeechRequest + _ = json.NewDecoder(r.Body).Decode(&body) + mu.Lock() + seen, token = body, r.Header.Get("Authorization") + fn := reply + mu.Unlock() + fn(w) + })) + t.Cleanup(tts.Close) + s.SetMeetingsTTSResolver(func(context.Context) (MeetingsTTSConfig, error) { + return MeetingsTTSConfig{URL: tts.URL + "/", Token: "tts-secret"}, nil + }) + if !personaGet(t, s).TTSConfigured { + t.Fatal("tts_configured") + } + rec := samplePost(s, "") + if rec.Code != http.StatusOK || rec.Body.String() != "ID3audio" || rec.Header().Get("Content-Type") != "audio/mpeg" || rec.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("sample = %d %q %v", rec.Code, rec.Body.String(), rec.Header()) + } + last, auth := lastReq() + if auth != "Bearer tts-secret" || last.Model != meetingsTTSModel || last.Voice != "af_heart" || last.ResponseFormat != "mp3" || + !strings.HasPrefix(last.Input, "Hi, I'm Betty Bee from the hive.") { + t.Fatalf("tts request %+v auth %q", last, auth) + } + // The form's unsaved voice, language and name are sampled. + rec = samplePost(s, `{"voice":"jf_alpha","language":"ja-JP","display_name":"ミツ"}`) + last, _ = lastReq() + if rec.Code != http.StatusOK || last.Voice != "jf_alpha" || !strings.Contains(last.Input, "ミツです") { + t.Fatalf("japanese sample %d %+v", rec.Code, last) + } + rec = samplePost(s, `{"text":" hello there "}`) + last, _ = lastReq() + if rec.Code != http.StatusOK || last.Input != "hello there" { + t.Fatalf("custom text %d %+v", rec.Code, last) + } + if rec := samplePost(s, `{"text":"`+strings.Repeat("a", meetingsSampleMaxChars+1)+`"}`); rec.Code != http.StatusBadRequest { + t.Fatalf("long text = %d", rec.Code) + } + failures := map[string]func(http.ResponseWriter){ + "upstream error": func(w http.ResponseWriter) { http.Error(w, "voice not found", http.StatusBadRequest) }, + "empty audio": func(w http.ResponseWriter) {}, + "oversized audio": func(w http.ResponseWriter) { + _, _ = w.Write(make([]byte, meetingsSampleMaxBytes+1)) + }, + } + for name, fn := range failures { + setReply(fn) + if rec := samplePost(s, `{}`); rec.Code != http.StatusBadGateway { + t.Errorf("%s = %d %s", name, rec.Code, rec.Body.String()) + } + } + // A non-audio content type is served as mp3. + setReply(func(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/octet-stream") + _, _ = w.Write([]byte("raw")) + }) + if rec := samplePost(s, `{}`); rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != meetingsTTSDefaultContentType { + t.Fatalf("octet stream = %d %v", rec.Code, rec.Header()) + } + tts.Close() + if rec := samplePost(s, `{}`); rec.Code != http.StatusBadGateway { + t.Fatalf("unreachable = %d", rec.Code) + } +} diff --git a/src/pkg/dashboard/meeting_attendee_ui_test.go b/src/pkg/dashboard/meeting_attendee_ui_test.go new file mode 100644 index 0000000000..bce85d5ba4 --- /dev/null +++ b/src/pkg/dashboard/meeting_attendee_ui_test.go @@ -0,0 +1,154 @@ +package dashboard + +import ( + "encoding/json" + "os/exec" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// TestSettingsMeetingAttendeeTabWiring pins Settings, Meeting attendee +// (hivecommons/hive#18396): the tab right after Meetings, its render and +// lazy load, the search entry, the persona API calls and the three sections. +func TestSettingsMeetingAttendeeTabWiring(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + "'Project Observability', 'Meetings', 'Meeting attendee', 'Advisory'", + "case 'Meeting attendee': return renderGovMeetingAttendee();", + "if (tabId === 'Meeting attendee') loadMeetingAttendeeInline();", + "{ tab: 'Meeting attendee', section: 'Meeting attendee', label: 'Meeting attendee persona', key: 'meetings.persona.preset', lazy: true", + "yamlHint('meetings.persona')", + `id="meeting-attendee-inline"`, + "fetch('/api/meetings/persona')", + "fetch('/api/meetings/persona', { method: 'PUT'", + "fetch('/api/meetings/persona/sample', { method: 'POST'", + `data-action="maPickPreset"`, + `data-action="maPlaySample"`, + `data-action="maCopyAddress"`, + `data-action="maSave"`, + `data-change-action="maLanguageChanged"`, + `aria-labelledby="ma-persona-h"`, + `aria-labelledby="ma-behaviour-h"`, + `aria-labelledby="ma-email-h"`, + "Available once email-in is enabled.", + ".ma-presets {", + } { + if !strings.Contains(html, want) { + t.Errorf("Meeting attendee wiring missing %q", want) + } + } +} + +// jsConstBlock returns a const declaration whose value may span lines (an +// object or array literal), through its closing bracket and semicolon. +func jsConstBlock(t *testing.T, html, name string) string { + t.Helper() + start := strings.Index(html, "const "+name+" = ") + if start < 0 { + t.Fatalf("index.html does not declare const %s", name) + } + body := start + len("const "+name+" = ") + if c := html[body]; c != '{' && c != '[' { + end := strings.Index(html[body:], ";") + return html[start : body+end+1] + } + depth := 0 + for i := body; i < len(html); i++ { + switch html[i] { + case '{', '[': + depth++ + case '}', ']': + depth-- + if depth == 0 { + return html[start:i+1] + ";" + } + } + } + t.Fatalf("const %s never closes", name) + return "" +} + +// TestMeetingAttendeeTabBehaviour executes the tab's rules against the real +// preset and voice catalog: flags, the intro preview, the voice list +// filtered by language, picking a preset, a language change keeping a voice +// of the same type, bot-style shown as coming later, and the Email section +// disabled until email-in is available. +func TestMeetingAttendeeTabBehaviour(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not on PATH — the Meeting attendee rules were NOT executed by this run") + } + s, _ := apiServer(t) + data, err := json.Marshal(personaGet(t, s)) + if err != nil { + t.Fatal(err) + } + html := indexHTML(t) + parts := []string{ + "const assert = require('assert');", + "const escapeHtml = s => String(s).replace(/&/g, '&').replace(//g, '>').replace(/\"/g, '"');", + "const yamlHint = p => '' + p + '';", + "const document = { getElementById: () => null, querySelector: () => null };", + "let _maState = null;", + } + for _, c := range []string{"MA_LANGUAGE_LABELS", "MA_FLAG_BASE", "MA_PERSONA_FIELDS", "MA_LIST_FIELDS", "MA_CAP_FIELDS"} { + parts = append(parts, jsConstBlock(t, html, c)) + } + for _, f := range []string{"maLanguageLabel", "maFlag", "maRenderIntro", "renderGovMeetingAttendee", "maSetData", "maPreset", + "maOverrideNote", "maPresetCardHtml", "maField", "maTextInput", "maVoiceOptions", "maLanguageOptions", "maVoiceTypeOptions", + "maPersonaHtml", "maBehaviourHtml", "maEmailHtml", "maRender", "maRefreshPreview", "maInput", "maCapInput", + "maLanguageChanged", "maPickPreset", "maRequestBody"} { + parts = append(parts, jsFunc(t, html, f)) + } + parts = append(parts, + "const data = "+string(data)+";", + `assert.strictEqual(maFlag('en-GB'), '🇬🇧'); assert.strictEqual(maFlag('pt-BR'), '🇧🇷'); assert.strictEqual(maFlag('es'), '');`, + `assert.ok(renderGovMeetingAttendee().includes('meeting-attendee-inline'));`, + `assert.strictEqual(maRenderIntro({intro_template: 'I am {display_name} ({pronouns}); say "{leave}". {nope}', display_name: 'Betty Bee', pronouns: 'she/her', leave_phrases: ['betty leave']}), 'I am Betty Bee (she/her); say "betty leave". {nope}');`, + `maSetData(data);`, + `let f = _maState.form;`, + `assert.strictEqual(f.preset, 'betty'); assert.strictEqual(f.voice, 'af_heart');`, + `let html = maPersonaHtml(f);`, + `assert.ok(html.includes('data-arg0="betty" aria-pressed="true"'), 'betty card selected');`, + `assert.ok(html.includes('value="af_heart" selected'), 'current voice selected');`, + `assert.ok(!html.includes('value="bf_emma"'), 'voices filtered to the language');`, + `assert.ok(/value="bot" disabled>Bot-style \(coming later\)/.test(html), 'bot-style listed as coming later');`, + `assert.ok(html.includes('disabled title="Set meetings.tts_url'), 'sample disabled without TTS');`, + `maPickPreset('melie'); f = _maState.form;`, + `assert.strictEqual(f.language, 'fr-FR'); assert.strictEqual(f.voice, 'ff_siwis'); assert.ok(f.intro_template.startsWith('Bonjour'));`, + `assert.strictEqual(f.aliases.join(','), 'mélie,melie,abeille,hive');`, + `maPickPreset('nobody'); assert.strictEqual(_maState.form.preset, 'melie');`, + `maLanguageChanged('ja-JP'); f = _maState.form;`, + `assert.strictEqual(f.voice, 'jf_alpha'); assert.strictEqual(f.accent, 'Standard Japanese');`, + `f.voice_type = 'male'; maLanguageChanged('en-GB');`, + `assert.strictEqual(_maState.form.voice.slice(0, 2), 'bm', 'a language change keeps the voice type');`, + `maInput('aliases', ' a, b ,, '); assert.deepStrictEqual(_maState.form.aliases, ['a', 'b']);`, + `maInput('enabled', false); assert.strictEqual(_maState.form.enabled, false);`, + `maInput('name', 'Zed'); maCapInput('per_10m', '5'); maCapInput('stale_s', '');`, + `const body = maRequestBody();`, + `assert.strictEqual(body.name, 'Zed'); assert.strictEqual(body.unprompted.per_10m, 5); assert.strictEqual(body.unprompted.stale_s, 0);`, + `assert.strictEqual(body.preset, 'melie'); assert.strictEqual(body.enabled, false); assert.ok('voice_on_address' in body);`, + `let email = maEmailHtml();`, + `assert.ok(email.includes('Available once email-in is enabled'), 'pending note');`, + `assert.ok(email.includes('data-ma-email="calendar_invites" disabled>'), 'toggles disabled until email-in');`, + `_maState.data.email = { available: true, address: 'hive@h.example', calendar_invites: true, inviters: [{login: 'bob', role: 'read-write', display_name: 'Bob', emails: [{address: 'bob@example.com', proof: 'verified'}]}], approvals: [{kind: 'invite', from: 'x@y', subject: 'Sync'}] };`, + `email = maEmailHtml();`, + `assert.ok(!email.includes('Available once email-in'), 'no pending note once available');`, + `assert.ok(email.includes('data-ma-email="calendar_invites" checked>'), 'toggle enabled');`, + `assert.ok(email.includes('bob@example.com') && email.includes('ma-verified') && email.includes('invite from x@y'), email);`, + `_maState.data.overridden = { name: 'env', pronouns: 'config' };`, + `assert.ok(maOverrideNote('name').includes('env') && maOverrideNote('pronouns').includes('custom') && maOverrideNote('voice') === '');`, + `assert.ok(maBehaviourHtml(_maState.form).includes('data-ma-cap="answer_wait_s"'));`, + `maRender(); maRefreshPreview();`, + `console.log('ok');`, + ) + out, err := runNodeStdin(node, strings.Join(parts, "\n")) + if err != nil || !strings.Contains(string(out), "ok") { + t.Fatalf("Meeting attendee rules failed: %v\n%s", err, out) + } + if len(config.KokoroVoices()) == 0 { + t.Fatal("no voices") + } +} diff --git a/src/pkg/dashboard/openapi_schema_parity_test.go b/src/pkg/dashboard/openapi_schema_parity_test.go index 1f2a0e0164..3fd468a386 100644 --- a/src/pkg/dashboard/openapi_schema_parity_test.go +++ b/src/pkg/dashboard/openapi_schema_parity_test.go @@ -96,6 +96,11 @@ func TestOpenAPISchemaFieldsExistOnGoTypes(t *testing.T) { path: "/api/watchdog/activity", goType: reflect.TypeOf(WatchdogActivity{}), }, + { + name: "GET /api/meetings/persona", + path: "/api/meetings/persona", + goType: reflect.TypeOf(MeetingsPersonaSettings{}), + }, } raw, err := os.ReadFile(openAPISpecPath) diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index dfe2ec537d..fdae5c9630 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -477,6 +477,9 @@ type Server struct { // meetingsSchedule is the meeting scheduler behind the Calendar // section (hivecommons/hive#18394); nil while meetings are off. meetingsSchedule atomic.Pointer[meetingsScheduleHolder] + // meetingsAttendee is Settings, Meeting attendee: the boot persona, + // the TTS service and the email-in data (hivecommons/hive#18396). + meetingsAttendee meetingsAttendeeState audit *AuditLog diff --git a/src/pkg/dashboard/static-src/css/meeting-attendee.css b/src/pkg/dashboard/static-src/css/meeting-attendee.css new file mode 100644 index 0000000000..1fb1ae8b80 --- /dev/null +++ b/src/pkg/dashboard/static-src/css/meeting-attendee.css @@ -0,0 +1,20 @@ + /* Settings, Meeting attendee: persona presets, behaviour, email (#18396) */ + .ma-section { display: flex; flex-direction: column; gap: var(--sp-3); margin-top: var(--sp-5); } + .ma-section h4 { margin: var(--sp-0); } + .ma-section.is-pending { opacity: 0.75; } + .ma-presets { display: grid; grid-template-columns: repeat(auto-fill, minmax(12em, 1fr)); gap: var(--sp-2); } + .ma-preset { display: flex; flex-direction: column; align-items: flex-start; gap: var(--sp-1); padding: var(--sp-3); border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); color: var(--text); text-align: left; cursor: pointer; } + .ma-preset:hover, .ma-preset:focus-visible { border-color: var(--accent); } + .ma-preset.is-selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); } + .ma-preset-flag { font-size: var(--fs-base); } + .ma-preset-name { font-weight: 600; } + .ma-intro { width: 100%; resize: vertical; font-family: inherit; } + .ma-preview { padding: var(--sp-3); border: 1px dashed var(--border); border-radius: var(--r); } + .ma-preview-text { margin: var(--sp-1) var(--sp-0) var(--sp-0); white-space: pre-wrap; } + .ma-sample, .ma-address { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } + .ma-audio { max-width: 100%; } + .ma-inviters td { vertical-align: top; } + .ma-email { display: inline-flex; align-items: center; gap: var(--sp-1); margin-right: var(--sp-2); } + .ma-verified { border-color: var(--green); } + .ma-env { border-color: var(--accent); } + .ma-approvals { margin: var(--sp-0); } diff --git a/src/pkg/dashboard/static-src/js/config-state.js b/src/pkg/dashboard/static-src/js/config-state.js index fdb3bcd78d..72e2f42f92 100644 --- a/src/pkg/dashboard/static-src/js/config-state.js +++ b/src/pkg/dashboard/static-src/js/config-state.js @@ -23,7 +23,7 @@ // which is read-only hub-synced user/role data. It sits next to Model // Gateways because both are backend configuration. const GOVERNOR_BOB_TAB = 'Bob'; - const GOVERNOR_CONFIG_TABS = ['General', 'Appearance', 'Dashboard', 'Agents', 'Thresholds', 'Labels', 'Repos', 'Workflows', 'Budget', 'Notifications', 'Health', 'Sensing', 'Logging', 'Features', 'Knowledge', 'Inbox', 'Project Observability', 'Meetings', 'Advisory', 'Work Source', 'Hub', 'Forge App', 'Model Gateways', GOVERNOR_BOB_TAB, 'Variables', 'Security', 'Compliance']; + const GOVERNOR_CONFIG_TABS = ['General', 'Appearance', 'Dashboard', 'Agents', 'Thresholds', 'Labels', 'Repos', 'Workflows', 'Budget', 'Notifications', 'Health', 'Sensing', 'Logging', 'Features', 'Knowledge', 'Inbox', 'Project Observability', 'Meetings', 'Meeting attendee', 'Advisory', 'Work Source', 'Hub', 'Forge App', 'Model Gateways', GOVERNOR_BOB_TAB, 'Variables', 'Security', 'Compliance']; const PIPELINE_STAGES = ['resolve-beads', 'track-prs', 'stale-check', 'repo-scan', 'coverage-gate', 'prompt-compose', 'budget-check', 'api-collect', 'final-compose']; const PIPELINE_STAGE_TIPS = { 'resolve-beads': 'Fetch and inject knowledge beads (facts, patterns, gotchas) relevant to the agent\'s current task context.', @@ -83,6 +83,7 @@ { tab: 'Labels', section: 'Labels', label: 'Contributor nudge', key: 'governor.labels.stage.contributor_nudge.enabled', text: 'contributor nudge returned-to-contributor red ci fix-pr relay interrupt renudge presence window governor.labels.stage.contributor_nudge.enabled governor.labels.stage.contributor_nudge.renudge_interval auto_merge.nudge_repeat_after governor.labels.stage.contributor_nudge.ci_failure_cooldown governor.labels.stage.presence_window' }, { tab: 'Labels', section: 'Labels', label: 'Adopt red contributor PRs', key: 'governor.labels.stage.adoption.enabled', text: 'adoption adopted-by-hive stage 074 red contributor pr grace online offline supersede takeover in place after offline unregistered heartbeat governor.labels.stage.adoption.enabled governor.labels.stage.contributor_grace_online governor.labels.stage.contributor_grace_offline governor.labels.stage.adoption.after_offline governor.labels.stage.adoption.after_unregistered governor.labels.stage.adoption.in_place governor.labels.stage.adoption.strict_attribution strict attribution governor.labels.stage.adoption.auto_merge auto merge adopted head hive authority governor.labels.stage.adoption.supersede.close_first close first superseded reopen copy failed governor.labels.stage.adoption.close_superseded close superseded on adopt on merge clanker authored opt-in label governor.labels.stage.adoption.offline_grace offline grace rebase failed twice fixer resolving conflicts governor.labels.stage.adoption.rebase_attempt_timeout rebase attempt timeout' }, { tab: 'Inbox', section: 'Inbox', label: 'Inbox routing', key: 'inbox.spek.repo', lazy: true, text: 'inbox voice recordings plaud wispr default rfc repository spek dibs url auto-routing rules inbox.spek.repo inbox.dibs.url inbox.rules transcription transcribe whisper gemini deepgram auto provider progress speech to text diarize consent budget minutes inbox.transcription.enabled inbox.transcription.mode inbox.transcription.provider inbox.transcription.model inbox.transcription.api_key_env inbox.transcription.sources[] inbox.transcription.diarize inbox.transcription.language inbox.transcription.max_duration_minutes inbox.transcription.max_bytes inbox.transcription.monthly_budget_minutes inbox.transcription.daily_max_items inbox.transcription.whisper_model inbox.transcription.whisper_threads inbox.transcription.gemini_model whisper.cpp model threads cpu inbox.transcription.consent_acknowledged' }, + { tab: 'Meeting attendee', section: 'Meeting attendee', label: 'Meeting attendee persona', key: 'meetings.persona.preset', lazy: true, text: 'meeting attendee persona betty bee preset name display name aliases pronouns voice type language accent kokoro tts voice id humor intro sample unprompted answers caps answer wait confidence voice when addressed email invite calendar address allowlist approval mail-in files meetings.persona meetings.persona.preset meetings.persona.voice meetings.persona.language meetings.persona.unprompted meetings.voice_on_address' }, { tab: 'Meetings', section: 'Meetings', label: 'Meetings (Quorum)', key: 'meetings.enabled', lazy: true, text: 'meetings quorum vexa discord live meeting notes research google meet teams zoom tenant key bot token meetings.enabled meetings.vexa.url meetings.vexa.api_key_file meetings.discord.token_file' }, { tab: 'Hub', section: 'Contributor Relay', label: 'Fix budget', key: 'contribute.max_parallel_fixes', text: 'fix budget parallel fixes focus window red pr fix-pr preempt spawn contribute.max_parallel_fixes contribute.min_focus_window' }, { tab: 'Logging', section: 'Logging', label: 'Governor logging', key: 'governor.logging.max_size_mb', text: 'governor logging directory level compression max size age backups governor.logging.compress governor.logging.dir governor.logging.level governor.logging.max_age_days governor.logging.max_backups governor.logging.max_size_mb' }, diff --git a/src/pkg/dashboard/static-src/js/config-tabs.js b/src/pkg/dashboard/static-src/js/config-tabs.js index ab519fc45c..1e6cde39d6 100644 --- a/src/pkg/dashboard/static-src/js/config-tabs.js +++ b/src/pkg/dashboard/static-src/js/config-tabs.js @@ -55,6 +55,7 @@ if (tabId === 'Features') loadLinearAgentStatus(); if (tabId === 'Inbox') loadInboxSettingsInline(); if (tabId === 'Meetings') loadMeetingsSettingsInline(); + if (tabId === 'Meeting attendee') loadMeetingAttendeeInline(); // The same tab carries the upstream-watch editor and divergence view // (#9969, #11211); it loads from its own endpoint. if (tabId === 'Features') loadUpstreamWatch(); @@ -269,6 +270,7 @@ case 'Knowledge': return renderGovKnowledgeSharing(); case 'Inbox': return renderGovInbox(); case 'Meetings': return renderGovMeetings(); + case 'Meeting attendee': return renderGovMeetingAttendee(); case 'Project Observability': return renderGovProjectObservability(d.project_observability || {}); case 'Advisory': return renderGovAdvisory(d.advisory || {}); case 'Work Source': return renderGovWorkSource(d.work_source || {}); diff --git a/src/pkg/dashboard/static-src/js/meeting-attendee.js b/src/pkg/dashboard/static-src/js/meeting-attendee.js new file mode 100644 index 0000000000..ac26e88ef8 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/meeting-attendee.js @@ -0,0 +1,301 @@ + // ── Settings → Meeting attendee (#18396) ── + // The persona hive attends meetings as (Betty by default): a preset or a + // customized persona, its behaviour caps, and the attendee's email + // address and inviters. GET/PUT /api/meetings/persona, owner or + // read-write; POST /api/meetings/persona/sample plays a line through the + // meetings TTS service. The Email section stays disabled (layout only) + // until the server reports email.available (email-in, #18395). + let _maState = null; // { data, form } + let _maSampleURL = ''; + // Language tags the presets and Kokoro voices speak, for labels. + const MA_LANGUAGE_LABELS = { + 'en-US': 'English (US)', 'en-GB': 'English (UK)', 'es-ES': 'Spanish', 'fr-FR': 'French', 'it-IT': 'Italian', + 'pt-BR': 'Portuguese (Brazil)', 'hi-IN': 'Hindi', 'ja-JP': 'Japanese', 'zh-CN': 'Mandarin Chinese', + }; + // Regional indicator symbols start here; 'A' maps to U+1F1E6. + const MA_FLAG_BASE = 0x1F1E6; + const MA_PERSONA_FIELDS = ['name', 'display_name', 'pronouns', 'language', 'voice', 'voice_type', 'accent', 'humor', 'intro_template']; + const MA_LIST_FIELDS = ['aliases', 'leave_phrases']; + const MA_CAP_FIELDS = [ + ['per_10m', 'Unprompted answers per 10 minutes', '1'], + ['min_gap_s', 'Seconds between unprompted answers', '1'], + ['per_meeting', 'Unprompted answers per meeting', '1'], + ['answer_wait_s', 'Answer wait (seconds a person has to answer first)', '1'], + ['min_confidence', 'Confidence needed to answer unprompted (0 to 1)', '0.05'], + ['queue_depth', 'Room questions waiting at once', '1'], + ['stale_s', 'Drop a question after (seconds)', '1'], + ]; + + function maLanguageLabel(tag) { return MA_LANGUAGE_LABELS[tag] || tag || ''; } + + function maFlag(tag) { + const region = String(tag || '').split('-')[1] || ''; + if (!/^[A-Za-z]{2}$/.test(region)) return ''; + const up = region.toUpperCase(); + return String.fromCodePoint(MA_FLAG_BASE + up.charCodeAt(0) - 65, MA_FLAG_BASE + up.charCodeAt(1) - 65); + } + + // maRenderIntro fills the intro placeholders the way the server does + // (ResolvedMeetingsPersona.Intro). + function maRenderIntro(f) { + const leave = (f.leave_phrases || [])[0] || ''; + const subs = { '{name}': f.name, '{display_name}': f.display_name, '{pronouns}': f.pronouns, '{leave}': leave, + '{accent}': f.accent, '{voice_type}': f.voice_type, '{language}': f.language }; + return String(f.intro_template || '').replace(/\{(name|display_name|pronouns|leave|accent|voice_type|language)\}/g, m => subs[m] || ''); + } + + function renderGovMeetingAttendee() { + return '

Meeting attendee

' + + '

Who hive is in meetings: the persona\'s name, voice, language and manners, how often she speaks up unprompted, and how people invite her. ' + + yamlHint('meetings.persona') + ' Changes apply after a restart.

' + + '

Loading…

'; + } + + async function loadMeetingAttendeeInline() { + const host = document.getElementById('meeting-attendee-inline'); + if (!host) return; + try { + const r = await fetch('/api/meetings/persona'); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + maSetData(data); + maRender(); + } catch (e) { + host.innerHTML = '

Meeting attendee settings unavailable: ' + escapeHtml(e.message) + '

'; + } + } + + function maSetData(data) { + const e = data.effective || {}; + const form = { enabled: !!e.enabled, preset: e.preset || '', voice_on_address: !!e.voice_on_address, unprompted: Object.assign({}, e.unprompted || {}) }; + MA_PERSONA_FIELDS.forEach(k => { form[k] = e[k] || ''; }); + MA_LIST_FIELDS.forEach(k => { form[k] = (e[k] || []).slice(); }); + _maState = { data: data, form: form, dirty: false }; + } + + function maPreset(id) { return ((_maState && _maState.data.presets) || []).find(p => p.id === id) || null; } + + function maOverrideNote(key) { + const src = ((_maState && _maState.data.overridden) || {})[key]; + if (src === 'env') return ' env'; + if (src === 'config') return ' custom'; + return ''; + } + + function maPresetCardHtml(p, selected) { + const vt = (p.voice_type || '').replace(/^./, c => c.toUpperCase()); + return ''; + } + + function maField(label, key, inner) { + return ''; + } + + function maTextInput(key, value, placeholder) { + return ''; + } + + function maVoiceOptions(f) { + const voices = ((_maState.data.voices) || []).filter(v => v.language === f.language); + let opts = voices.map(v => '').join(''); + if (f.voice && !voices.some(v => v.id === f.voice)) opts = '' + opts; + return opts; + } + + function maLanguageOptions(f) { + const langs = []; + ((_maState.data.voices) || []).forEach(v => { if (langs.indexOf(v.language) < 0) langs.push(v.language); }); + if (f.language && langs.indexOf(f.language) < 0) langs.unshift(f.language); + return langs.map(l => '').join(''); + } + + function maVoiceTypeOptions(f) { + return ((_maState.data.voice_types) || []).map(t => { + const sel = t.id === f.voice_type; + // A type no shipped voice provides is listed but not selectable + // (bot-style: coming later), unless the config already uses it. + const disabled = !t.available && !sel; + return ''; + }).join(''); + } + + function maPersonaHtml(f) { + const presets = (_maState.data.presets || []).map(p => maPresetCardHtml(p, p.id === f.preset)).join(''); + return '

Persona

' + + '' + + '

Presets use voices the self-hosted Kokoro TTS provides. Pick one, then adjust any field.' + maOverrideNote('preset') + '

' + + '
' + presets + '
' + + '
' + + maField('Name', 'name', maTextInput('name', f.name, 'Betty')) + + maField('Display name', 'display_name', maTextInput('display_name', f.display_name, 'Betty Bee from the hive')) + + maField('Aliases (comma separated)', 'aliases', maTextInput('aliases', f.aliases.join(', '), 'betty, betty bee, hive')) + + maField('Pronouns', 'pronouns', maTextInput('pronouns', f.pronouns, 'she/her')) + + maField('Voice type', 'voice_type', '') + + maField('Language', 'language', '') + + maField('Accent', 'accent', maTextInput('accent', f.accent, 'American')) + + maField('Voice', 'voice', '') + + maField('Humor', 'humor', '') + + maField('Leave phrases (comma separated)', 'leave_phrases', maTextInput('leave_phrases', f.leave_phrases.join(', '), 'betty leave, hive leave')) + + '
' + + maField('Intro (placeholders: {name}, {display_name}, {pronouns}, {leave}, {accent}, {voice_type}, {language})', 'intro_template', + '') + + '

' + escapeHtml(maRenderIntro(f)) + '

' + + '
' + + '' + + (_maState.data.tts_configured ? '' : 'TTS is not configured on this hive.') + + '
'; + } + + function maBehaviourHtml(f) { + const caps = MA_CAP_FIELDS.map(c => maField(c[1], 'unprompted.' + c[0], + '')).join(''); + return '

Behaviour

' + + '

Unprompted answers are chat replies to room questions nobody asked the persona directly. Addressed requests skip these caps but not the meeting\'s rate limit and budget.

' + + '
' + caps + '
' + + '
'; + } + + function maEmailHtml() { + const em = (_maState.data.email) || {}; + const on = !!em.available; + const dis = on ? '' : ' disabled'; + const people = (em.inviters || []).map(p => { + const emails = (p.emails || []).map(x => '' + escapeHtml(x.address) + ' ' + escapeHtml(x.proof || 'pending') + '').join('') || + 'no calendar email registered'; + return '' + escapeHtml(p.display_name || p.login) + (p.display_name ? ' ' + escapeHtml(p.login) + '' : '') + '' + escapeHtml(p.role) + '' + emails + ''; + }).join(''); + const approvals = (em.approvals || []).map(a => '
  • ' + escapeHtml((a.kind || '') + ' from ' + (a.from || '')) + (a.subject ? ': ' + escapeHtml(a.subject) : '') + '
  • ').join(''); + return '

    Email

    ' + + (on ? '' : '

    Available once email-in is enabled. Until then, add meetings from the Calendar.

    ') + + (em.error ? '

    ' + escapeHtml(em.error) + '

    ' : '') + + '
    Attendee address ' + escapeHtml(em.address || '') + '' + + '
    ' + + '

    Add this address to a calendar invite. Invites from people with access to this hive whose calendar email is verified are scheduled; anything else waits for the owner.

    ' + + '' + + (people || '') + '
    PersonAccessCalendar emails
    No access list on this hive.
    ' + + '' + (approvals ? '
      ' + approvals + '
    ' : '

    Nothing waiting.

    ') + + '' + + '
    '; + } + + function maRender() { + const host = document.getElementById('meeting-attendee-inline'); + if (!host || !_maState) return; + const d = _maState.data; + const f = _maState.form; + host.innerHTML = + (d.restart_required ? '

    Saved. Restart the hive to apply the new persona.

    ' : '') + + (d.running ? '' : '

    Meetings are not running on this hive; the persona applies once meetings are on (Settings, Meetings).

    ') + + maPersonaHtml(f) + maBehaviourHtml(f) + maEmailHtml() + + '' + + '
    '; + } + + function maRefreshPreview() { + const el = document.querySelector('[data-ma-preview]'); + if (el && _maState) el.textContent = maRenderIntro(_maState.form); + } + + function maInput(key, value) { + if (!_maState) return; + const f = _maState.form; + if (MA_LIST_FIELDS.indexOf(key) >= 0) f[key] = String(value || '').split(',').map(s => s.trim()).filter(Boolean); + else if (key === 'enabled' || key === 'voice_on_address') f[key] = !!value; + else f[key] = value; + _maState.dirty = true; + maRefreshPreview(); + } + + function maCapInput(key, value) { + if (!_maState) return; + const n = Number(value); + _maState.form.unprompted[key] = value === '' || !isFinite(n) ? 0 : n; + _maState.dirty = true; + } + + // maLanguageChanged keeps the voice in the new language: the current + // voice when it speaks it, else the first of the same voice type. + function maLanguageChanged(lang) { + if (!_maState) return; + const f = _maState.form; + f.language = lang; + const voices = (_maState.data.voices || []).filter(v => v.language === lang); + if (voices.length && !voices.some(v => v.id === f.voice)) { + f.voice = (voices.find(v => v.voice_type === f.voice_type) || voices[0]).id; + const known = voices.find(v => v.id === f.voice); + if (known) f.accent = known.accent; + } + _maState.dirty = true; + maRender(); + } + + // maPickPreset fills the form from a preset; Save stores it. + function maPickPreset(id) { + const p = maPreset(id); + if (!p || !_maState) return; + const f = _maState.form; + f.preset = p.id; + ['name', 'display_name', 'pronouns', 'language', 'voice', 'voice_type', 'accent', 'humor'].forEach(k => { f[k] = p[k] || ''; }); + f.intro_template = f.humor === 'off' && p.plain_intro_template ? p.plain_intro_template : p.intro_template; + f.aliases = (p.aliases || []).slice(); + f.leave_phrases = (p.leave_phrases || []).slice(); + _maState.dirty = true; + maRender(); + } + + function maRequestBody() { + const f = _maState.form; + const body = { enabled: f.enabled, preset: f.preset, voice_on_address: f.voice_on_address, unprompted: Object.assign({}, f.unprompted) }; + MA_PERSONA_FIELDS.forEach(k => { body[k] = f[k]; }); + MA_LIST_FIELDS.forEach(k => { body[k] = f[k]; }); + return body; + } + + async function maSave() { + if (!_maState) return; + const errEl = document.querySelector('[data-ma-error]'); + if (errEl) errEl.textContent = ''; + try { + const r = await fetch('/api/meetings/persona', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(maRequestBody()) }); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + maSetData(data); + maRender(); + showToast(data.restart_required ? 'Meeting attendee saved; restart the hive to apply' : 'Meeting attendee saved', 'success'); + } catch (e) { + if (errEl) errEl.textContent = e.message; else showToast('Save failed: ' + e.message, 'error'); + } + } + + async function maPlaySample() { + if (!_maState) return; + const f = _maState.form; + const status = document.querySelector('[data-ma-sample-status]'); + const audio = document.querySelector('[data-ma-audio]'); + if (status) status.textContent = 'Generating…'; + try { + const r = await fetch('/api/meetings/persona/sample', { method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ voice: f.voice, language: f.language, display_name: f.display_name }) }); + if (!r.ok) { const data = await r.json().catch(() => ({})); throw new Error(data.error || ('HTTP ' + r.status)); } + const blob = await r.blob(); + if (_maSampleURL) URL.revokeObjectURL(_maSampleURL); + _maSampleURL = URL.createObjectURL(blob); + if (status) status.textContent = ''; + if (audio) { audio.hidden = false; audio.src = _maSampleURL; audio.play().catch(() => {}); } + } catch (e) { + if (status) status.textContent = 'Sample failed: ' + e.message; + } + } + + async function maCopyAddress() { + const addr = (((_maState || {}).data || {}).email || {}).address || ''; + if (!addr) return; + try { await navigator.clipboard.writeText(addr); showToast('Copied ' + addr, 'success'); } + catch (e) { showToast('Copy failed: ' + e.message, 'error'); } + } diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 96b7878a94..85294d43d2 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -33,6 +33,7 @@ css/knowledge.css css/inbox.css css/meetings.css css/calendar.css +css/meeting-attendee.css css/sections-collapse.css css/design-system.css css/responsive.css @@ -132,6 +133,7 @@ js/knowledge.js js/inbox.js js/meetings.js js/calendar.js +js/meeting-attendee.js js/vault-audit.js js/review-queue.js js/contributors.js diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index a91b0196f4..c6fd03c080 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -6141,6 +6141,26 @@ @media (max-width: 720px) { .calendar-add-grid { grid-template-columns: 1fr; } } + /* Settings, Meeting attendee: persona presets, behaviour, email (#18396) */ + .ma-section { display: flex; flex-direction: column; gap: var(--sp-3); margin-top: var(--sp-5); } + .ma-section h4 { margin: var(--sp-0); } + .ma-section.is-pending { opacity: 0.75; } + .ma-presets { display: grid; grid-template-columns: repeat(auto-fill, minmax(12em, 1fr)); gap: var(--sp-2); } + .ma-preset { display: flex; flex-direction: column; align-items: flex-start; gap: var(--sp-1); padding: var(--sp-3); border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); color: var(--text); text-align: left; cursor: pointer; } + .ma-preset:hover, .ma-preset:focus-visible { border-color: var(--accent); } + .ma-preset.is-selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); } + .ma-preset-flag { font-size: var(--fs-base); } + .ma-preset-name { font-weight: 600; } + .ma-intro { width: 100%; resize: vertical; font-family: inherit; } + .ma-preview { padding: var(--sp-3); border: 1px dashed var(--border); border-radius: var(--r); } + .ma-preview-text { margin: var(--sp-1) var(--sp-0) var(--sp-0); white-space: pre-wrap; } + .ma-sample, .ma-address { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } + .ma-audio { max-width: 100%; } + .ma-inviters td { vertical-align: top; } + .ma-email { display: inline-flex; align-items: center; gap: var(--sp-1); margin-right: var(--sp-2); } + .ma-verified { border-color: var(--green); } + .ma-env { border-color: var(--accent); } + .ma-approvals { margin: var(--sp-0); } /* Collapsible advisory sections (#1546) */ .collapse-chevron { display: inline-block; @@ -49268,6 +49288,307 @@ catch (e) { showToast('Could not ' + action + ': ' + e.message, 'error'); } fetchCalendar(); } + // ── Settings → Meeting attendee (#18396) ── + // The persona hive attends meetings as (Betty by default): a preset or a + // customized persona, its behaviour caps, and the attendee's email + // address and inviters. GET/PUT /api/meetings/persona, owner or + // read-write; POST /api/meetings/persona/sample plays a line through the + // meetings TTS service. The Email section stays disabled (layout only) + // until the server reports email.available (email-in, #18395). + let _maState = null; // { data, form } + let _maSampleURL = ''; + // Language tags the presets and Kokoro voices speak, for labels. + const MA_LANGUAGE_LABELS = { + 'en-US': 'English (US)', 'en-GB': 'English (UK)', 'es-ES': 'Spanish', 'fr-FR': 'French', 'it-IT': 'Italian', + 'pt-BR': 'Portuguese (Brazil)', 'hi-IN': 'Hindi', 'ja-JP': 'Japanese', 'zh-CN': 'Mandarin Chinese', + }; + // Regional indicator symbols start here; 'A' maps to U+1F1E6. + const MA_FLAG_BASE = 0x1F1E6; + const MA_PERSONA_FIELDS = ['name', 'display_name', 'pronouns', 'language', 'voice', 'voice_type', 'accent', 'humor', 'intro_template']; + const MA_LIST_FIELDS = ['aliases', 'leave_phrases']; + const MA_CAP_FIELDS = [ + ['per_10m', 'Unprompted answers per 10 minutes', '1'], + ['min_gap_s', 'Seconds between unprompted answers', '1'], + ['per_meeting', 'Unprompted answers per meeting', '1'], + ['answer_wait_s', 'Answer wait (seconds a person has to answer first)', '1'], + ['min_confidence', 'Confidence needed to answer unprompted (0 to 1)', '0.05'], + ['queue_depth', 'Room questions waiting at once', '1'], + ['stale_s', 'Drop a question after (seconds)', '1'], + ]; + + function maLanguageLabel(tag) { return MA_LANGUAGE_LABELS[tag] || tag || ''; } + + function maFlag(tag) { + const region = String(tag || '').split('-')[1] || ''; + if (!/^[A-Za-z]{2}$/.test(region)) return ''; + const up = region.toUpperCase(); + return String.fromCodePoint(MA_FLAG_BASE + up.charCodeAt(0) - 65, MA_FLAG_BASE + up.charCodeAt(1) - 65); + } + + // maRenderIntro fills the intro placeholders the way the server does + // (ResolvedMeetingsPersona.Intro). + function maRenderIntro(f) { + const leave = (f.leave_phrases || [])[0] || ''; + const subs = { '{name}': f.name, '{display_name}': f.display_name, '{pronouns}': f.pronouns, '{leave}': leave, + '{accent}': f.accent, '{voice_type}': f.voice_type, '{language}': f.language }; + return String(f.intro_template || '').replace(/\{(name|display_name|pronouns|leave|accent|voice_type|language)\}/g, m => subs[m] || ''); + } + + function renderGovMeetingAttendee() { + return '

    Meeting attendee

    ' + + '

    Who hive is in meetings: the persona\'s name, voice, language and manners, how often she speaks up unprompted, and how people invite her. ' + + yamlHint('meetings.persona') + ' Changes apply after a restart.

    ' + + '

    Loading…

    '; + } + + async function loadMeetingAttendeeInline() { + const host = document.getElementById('meeting-attendee-inline'); + if (!host) return; + try { + const r = await fetch('/api/meetings/persona'); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + maSetData(data); + maRender(); + } catch (e) { + host.innerHTML = '

    Meeting attendee settings unavailable: ' + escapeHtml(e.message) + '

    '; + } + } + + function maSetData(data) { + const e = data.effective || {}; + const form = { enabled: !!e.enabled, preset: e.preset || '', voice_on_address: !!e.voice_on_address, unprompted: Object.assign({}, e.unprompted || {}) }; + MA_PERSONA_FIELDS.forEach(k => { form[k] = e[k] || ''; }); + MA_LIST_FIELDS.forEach(k => { form[k] = (e[k] || []).slice(); }); + _maState = { data: data, form: form, dirty: false }; + } + + function maPreset(id) { return ((_maState && _maState.data.presets) || []).find(p => p.id === id) || null; } + + function maOverrideNote(key) { + const src = ((_maState && _maState.data.overridden) || {})[key]; + if (src === 'env') return ' env'; + if (src === 'config') return ' custom'; + return ''; + } + + function maPresetCardHtml(p, selected) { + const vt = (p.voice_type || '').replace(/^./, c => c.toUpperCase()); + return ''; + } + + function maField(label, key, inner) { + return ''; + } + + function maTextInput(key, value, placeholder) { + return ''; + } + + function maVoiceOptions(f) { + const voices = ((_maState.data.voices) || []).filter(v => v.language === f.language); + let opts = voices.map(v => '').join(''); + if (f.voice && !voices.some(v => v.id === f.voice)) opts = '' + opts; + return opts; + } + + function maLanguageOptions(f) { + const langs = []; + ((_maState.data.voices) || []).forEach(v => { if (langs.indexOf(v.language) < 0) langs.push(v.language); }); + if (f.language && langs.indexOf(f.language) < 0) langs.unshift(f.language); + return langs.map(l => '').join(''); + } + + function maVoiceTypeOptions(f) { + return ((_maState.data.voice_types) || []).map(t => { + const sel = t.id === f.voice_type; + // A type no shipped voice provides is listed but not selectable + // (bot-style: coming later), unless the config already uses it. + const disabled = !t.available && !sel; + return ''; + }).join(''); + } + + function maPersonaHtml(f) { + const presets = (_maState.data.presets || []).map(p => maPresetCardHtml(p, p.id === f.preset)).join(''); + return '

    Persona

    ' + + '' + + '

    Presets use voices the self-hosted Kokoro TTS provides. Pick one, then adjust any field.' + maOverrideNote('preset') + '

    ' + + '
    ' + presets + '
    ' + + '
    ' + + maField('Name', 'name', maTextInput('name', f.name, 'Betty')) + + maField('Display name', 'display_name', maTextInput('display_name', f.display_name, 'Betty Bee from the hive')) + + maField('Aliases (comma separated)', 'aliases', maTextInput('aliases', f.aliases.join(', '), 'betty, betty bee, hive')) + + maField('Pronouns', 'pronouns', maTextInput('pronouns', f.pronouns, 'she/her')) + + maField('Voice type', 'voice_type', '') + + maField('Language', 'language', '') + + maField('Accent', 'accent', maTextInput('accent', f.accent, 'American')) + + maField('Voice', 'voice', '') + + maField('Humor', 'humor', '') + + maField('Leave phrases (comma separated)', 'leave_phrases', maTextInput('leave_phrases', f.leave_phrases.join(', '), 'betty leave, hive leave')) + + '
    ' + + maField('Intro (placeholders: {name}, {display_name}, {pronouns}, {leave}, {accent}, {voice_type}, {language})', 'intro_template', + '') + + '

    ' + escapeHtml(maRenderIntro(f)) + '

    ' + + '
    ' + + '' + + (_maState.data.tts_configured ? '' : 'TTS is not configured on this hive.') + + '
    '; + } + + function maBehaviourHtml(f) { + const caps = MA_CAP_FIELDS.map(c => maField(c[1], 'unprompted.' + c[0], + '')).join(''); + return '

    Behaviour

    ' + + '

    Unprompted answers are chat replies to room questions nobody asked the persona directly. Addressed requests skip these caps but not the meeting\'s rate limit and budget.

    ' + + '
    ' + caps + '
    ' + + '
    '; + } + + function maEmailHtml() { + const em = (_maState.data.email) || {}; + const on = !!em.available; + const dis = on ? '' : ' disabled'; + const people = (em.inviters || []).map(p => { + const emails = (p.emails || []).map(x => '' + escapeHtml(x.address) + ' ' + escapeHtml(x.proof || 'pending') + '').join('') || + 'no calendar email registered'; + return '' + escapeHtml(p.display_name || p.login) + (p.display_name ? ' ' + escapeHtml(p.login) + '' : '') + '' + escapeHtml(p.role) + '' + emails + ''; + }).join(''); + const approvals = (em.approvals || []).map(a => '
  • ' + escapeHtml((a.kind || '') + ' from ' + (a.from || '')) + (a.subject ? ': ' + escapeHtml(a.subject) : '') + '
  • ').join(''); + return '

    Email

    ' + + (on ? '' : '

    Available once email-in is enabled. Until then, add meetings from the Calendar.

    ') + + (em.error ? '

    ' + escapeHtml(em.error) + '

    ' : '') + + '
    Attendee address ' + escapeHtml(em.address || '') + '' + + '
    ' + + '

    Add this address to a calendar invite. Invites from people with access to this hive whose calendar email is verified are scheduled; anything else waits for the owner.

    ' + + '' + + (people || '') + '
    PersonAccessCalendar emails
    No access list on this hive.
    ' + + '' + (approvals ? '
      ' + approvals + '
    ' : '

    Nothing waiting.

    ') + + '' + + '
    '; + } + + function maRender() { + const host = document.getElementById('meeting-attendee-inline'); + if (!host || !_maState) return; + const d = _maState.data; + const f = _maState.form; + host.innerHTML = + (d.restart_required ? '

    Saved. Restart the hive to apply the new persona.

    ' : '') + + (d.running ? '' : '

    Meetings are not running on this hive; the persona applies once meetings are on (Settings, Meetings).

    ') + + maPersonaHtml(f) + maBehaviourHtml(f) + maEmailHtml() + + '' + + '
    '; + } + + function maRefreshPreview() { + const el = document.querySelector('[data-ma-preview]'); + if (el && _maState) el.textContent = maRenderIntro(_maState.form); + } + + function maInput(key, value) { + if (!_maState) return; + const f = _maState.form; + if (MA_LIST_FIELDS.indexOf(key) >= 0) f[key] = String(value || '').split(',').map(s => s.trim()).filter(Boolean); + else if (key === 'enabled' || key === 'voice_on_address') f[key] = !!value; + else f[key] = value; + _maState.dirty = true; + maRefreshPreview(); + } + + function maCapInput(key, value) { + if (!_maState) return; + const n = Number(value); + _maState.form.unprompted[key] = value === '' || !isFinite(n) ? 0 : n; + _maState.dirty = true; + } + + // maLanguageChanged keeps the voice in the new language: the current + // voice when it speaks it, else the first of the same voice type. + function maLanguageChanged(lang) { + if (!_maState) return; + const f = _maState.form; + f.language = lang; + const voices = (_maState.data.voices || []).filter(v => v.language === lang); + if (voices.length && !voices.some(v => v.id === f.voice)) { + f.voice = (voices.find(v => v.voice_type === f.voice_type) || voices[0]).id; + const known = voices.find(v => v.id === f.voice); + if (known) f.accent = known.accent; + } + _maState.dirty = true; + maRender(); + } + + // maPickPreset fills the form from a preset; Save stores it. + function maPickPreset(id) { + const p = maPreset(id); + if (!p || !_maState) return; + const f = _maState.form; + f.preset = p.id; + ['name', 'display_name', 'pronouns', 'language', 'voice', 'voice_type', 'accent', 'humor'].forEach(k => { f[k] = p[k] || ''; }); + f.intro_template = f.humor === 'off' && p.plain_intro_template ? p.plain_intro_template : p.intro_template; + f.aliases = (p.aliases || []).slice(); + f.leave_phrases = (p.leave_phrases || []).slice(); + _maState.dirty = true; + maRender(); + } + + function maRequestBody() { + const f = _maState.form; + const body = { enabled: f.enabled, preset: f.preset, voice_on_address: f.voice_on_address, unprompted: Object.assign({}, f.unprompted) }; + MA_PERSONA_FIELDS.forEach(k => { body[k] = f[k]; }); + MA_LIST_FIELDS.forEach(k => { body[k] = f[k]; }); + return body; + } + + async function maSave() { + if (!_maState) return; + const errEl = document.querySelector('[data-ma-error]'); + if (errEl) errEl.textContent = ''; + try { + const r = await fetch('/api/meetings/persona', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(maRequestBody()) }); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + maSetData(data); + maRender(); + showToast(data.restart_required ? 'Meeting attendee saved; restart the hive to apply' : 'Meeting attendee saved', 'success'); + } catch (e) { + if (errEl) errEl.textContent = e.message; else showToast('Save failed: ' + e.message, 'error'); + } + } + + async function maPlaySample() { + if (!_maState) return; + const f = _maState.form; + const status = document.querySelector('[data-ma-sample-status]'); + const audio = document.querySelector('[data-ma-audio]'); + if (status) status.textContent = 'Generating…'; + try { + const r = await fetch('/api/meetings/persona/sample', { method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ voice: f.voice, language: f.language, display_name: f.display_name }) }); + if (!r.ok) { const data = await r.json().catch(() => ({})); throw new Error(data.error || ('HTTP ' + r.status)); } + const blob = await r.blob(); + if (_maSampleURL) URL.revokeObjectURL(_maSampleURL); + _maSampleURL = URL.createObjectURL(blob); + if (status) status.textContent = ''; + if (audio) { audio.hidden = false; audio.src = _maSampleURL; audio.play().catch(() => {}); } + } catch (e) { + if (status) status.textContent = 'Sample failed: ' + e.message; + } + } + + async function maCopyAddress() { + const addr = (((_maState || {}).data || {}).email || {}).address || ''; + if (!addr) return; + try { await navigator.clipboard.writeText(addr); showToast('Copied ' + addr, 'success'); } + catch (e) { showToast('Copy failed: ' + e.message, 'error'); } + } // ── Vault Management ── function kbOpenVaults() { @@ -58346,7 +58667,7 @@

    Configure LiteLLM

    // which is read-only hub-synced user/role data. It sits next to Model // Gateways because both are backend configuration. const GOVERNOR_BOB_TAB = 'Bob'; - const GOVERNOR_CONFIG_TABS = ['General', 'Appearance', 'Dashboard', 'Agents', 'Thresholds', 'Labels', 'Repos', 'Workflows', 'Budget', 'Notifications', 'Health', 'Sensing', 'Logging', 'Features', 'Knowledge', 'Inbox', 'Project Observability', 'Meetings', 'Advisory', 'Work Source', 'Hub', 'Forge App', 'Model Gateways', GOVERNOR_BOB_TAB, 'Variables', 'Security', 'Compliance']; + const GOVERNOR_CONFIG_TABS = ['General', 'Appearance', 'Dashboard', 'Agents', 'Thresholds', 'Labels', 'Repos', 'Workflows', 'Budget', 'Notifications', 'Health', 'Sensing', 'Logging', 'Features', 'Knowledge', 'Inbox', 'Project Observability', 'Meetings', 'Meeting attendee', 'Advisory', 'Work Source', 'Hub', 'Forge App', 'Model Gateways', GOVERNOR_BOB_TAB, 'Variables', 'Security', 'Compliance']; const PIPELINE_STAGES = ['resolve-beads', 'track-prs', 'stale-check', 'repo-scan', 'coverage-gate', 'prompt-compose', 'budget-check', 'api-collect', 'final-compose']; const PIPELINE_STAGE_TIPS = { 'resolve-beads': 'Fetch and inject knowledge beads (facts, patterns, gotchas) relevant to the agent\'s current task context.', @@ -58406,6 +58727,7 @@

    Configure LiteLLM

    { tab: 'Labels', section: 'Labels', label: 'Contributor nudge', key: 'governor.labels.stage.contributor_nudge.enabled', text: 'contributor nudge returned-to-contributor red ci fix-pr relay interrupt renudge presence window governor.labels.stage.contributor_nudge.enabled governor.labels.stage.contributor_nudge.renudge_interval auto_merge.nudge_repeat_after governor.labels.stage.contributor_nudge.ci_failure_cooldown governor.labels.stage.presence_window' }, { tab: 'Labels', section: 'Labels', label: 'Adopt red contributor PRs', key: 'governor.labels.stage.adoption.enabled', text: 'adoption adopted-by-hive stage 074 red contributor pr grace online offline supersede takeover in place after offline unregistered heartbeat governor.labels.stage.adoption.enabled governor.labels.stage.contributor_grace_online governor.labels.stage.contributor_grace_offline governor.labels.stage.adoption.after_offline governor.labels.stage.adoption.after_unregistered governor.labels.stage.adoption.in_place governor.labels.stage.adoption.strict_attribution strict attribution governor.labels.stage.adoption.auto_merge auto merge adopted head hive authority governor.labels.stage.adoption.supersede.close_first close first superseded reopen copy failed governor.labels.stage.adoption.close_superseded close superseded on adopt on merge clanker authored opt-in label governor.labels.stage.adoption.offline_grace offline grace rebase failed twice fixer resolving conflicts governor.labels.stage.adoption.rebase_attempt_timeout rebase attempt timeout' }, { tab: 'Inbox', section: 'Inbox', label: 'Inbox routing', key: 'inbox.spek.repo', lazy: true, text: 'inbox voice recordings plaud wispr default rfc repository spek dibs url auto-routing rules inbox.spek.repo inbox.dibs.url inbox.rules transcription transcribe whisper gemini deepgram auto provider progress speech to text diarize consent budget minutes inbox.transcription.enabled inbox.transcription.mode inbox.transcription.provider inbox.transcription.model inbox.transcription.api_key_env inbox.transcription.sources[] inbox.transcription.diarize inbox.transcription.language inbox.transcription.max_duration_minutes inbox.transcription.max_bytes inbox.transcription.monthly_budget_minutes inbox.transcription.daily_max_items inbox.transcription.whisper_model inbox.transcription.whisper_threads inbox.transcription.gemini_model whisper.cpp model threads cpu inbox.transcription.consent_acknowledged' }, + { tab: 'Meeting attendee', section: 'Meeting attendee', label: 'Meeting attendee persona', key: 'meetings.persona.preset', lazy: true, text: 'meeting attendee persona betty bee preset name display name aliases pronouns voice type language accent kokoro tts voice id humor intro sample unprompted answers caps answer wait confidence voice when addressed email invite calendar address allowlist approval mail-in files meetings.persona meetings.persona.preset meetings.persona.voice meetings.persona.language meetings.persona.unprompted meetings.voice_on_address' }, { tab: 'Meetings', section: 'Meetings', label: 'Meetings (Quorum)', key: 'meetings.enabled', lazy: true, text: 'meetings quorum vexa discord live meeting notes research google meet teams zoom tenant key bot token meetings.enabled meetings.vexa.url meetings.vexa.api_key_file meetings.discord.token_file' }, { tab: 'Hub', section: 'Contributor Relay', label: 'Fix budget', key: 'contribute.max_parallel_fixes', text: 'fix budget parallel fixes focus window red pr fix-pr preempt spawn contribute.max_parallel_fixes contribute.min_focus_window' }, { tab: 'Logging', section: 'Logging', label: 'Governor logging', key: 'governor.logging.max_size_mb', text: 'governor logging directory level compression max size age backups governor.logging.compress governor.logging.dir governor.logging.level governor.logging.max_age_days governor.logging.max_backups governor.logging.max_size_mb' }, @@ -59504,6 +59826,7 @@

    Configure LiteLLM

    if (tabId === 'Features') loadLinearAgentStatus(); if (tabId === 'Inbox') loadInboxSettingsInline(); if (tabId === 'Meetings') loadMeetingsSettingsInline(); + if (tabId === 'Meeting attendee') loadMeetingAttendeeInline(); // The same tab carries the upstream-watch editor and divergence view // (#9969, #11211); it loads from its own endpoint. if (tabId === 'Features') loadUpstreamWatch(); @@ -59718,6 +60041,7 @@

    Configure LiteLLM

    case 'Knowledge': return renderGovKnowledgeSharing(); case 'Inbox': return renderGovInbox(); case 'Meetings': return renderGovMeetings(); + case 'Meeting attendee': return renderGovMeetingAttendee(); case 'Project Observability': return renderGovProjectObservability(d.project_observability || {}); case 'Advisory': return renderGovAdvisory(d.advisory || {}); case 'Work Source': return renderGovWorkSource(d.work_source || {}); diff --git a/src/pkg/meetings/betty/presets.go b/src/pkg/meetings/betty/presets.go index 59853b00af..1bc8aab943 100644 --- a/src/pkg/meetings/betty/presets.go +++ b/src/pkg/meetings/betty/presets.go @@ -1,24 +1,18 @@ package betty import ( - "sort" - "github.com/hivecommons/hive/pkg/config" ) // The preset table itself lives in config (config.MeetingsPersonaPresets) // because config resolves the effective persona and cannot import this // package (betty imports knowledge, which imports config). These helpers -// are the listing the settings API uses (hivecommons/hive#18396). +// re-export the listing the settings API uses (hivecommons/hive#18396). -// Presets returns the built-in personas sorted by ID. +// Presets returns the built-in personas in the settings tab's order, the +// default (Betty) first. func Presets() []config.MeetingsPersonaPreset { - out := make([]config.MeetingsPersonaPreset, 0, len(config.MeetingsPersonaPresets)) - for _, p := range config.MeetingsPersonaPresets { - out = append(out, p) - } - sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) - return out + return config.OrderedMeetingsPersonaPresets() } // Preset returns one built-in persona by ID. From 653710f320783659b0608fb0a741ba0fe524bdbd Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 08:35:53 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=8C=B1=20meetings:=20reuse=20the=20pa?= =?UTF-8?q?ckage=20nonNilStrings=20and=20jsConstBlock=20helpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/api_meetings_persona.go | 7 ----- src/pkg/dashboard/meeting_attendee_ui_test.go | 29 ------------------- 2 files changed, 36 deletions(-) diff --git a/src/pkg/dashboard/api_meetings_persona.go b/src/pkg/dashboard/api_meetings_persona.go index d7571dabc8..c44d40ae68 100644 --- a/src/pkg/dashboard/api_meetings_persona.go +++ b/src/pkg/dashboard/api_meetings_persona.go @@ -261,13 +261,6 @@ func meetingsPersonaView(m config.MeetingsConfig) MeetingsPersonaView { } } -func nonNilStrings(in []string) []string { - if in == nil { - return []string{} - } - return in -} - // meetingsAttendeeHost is the dashboard host the attendee address uses: // the forwarded host behind a proxy, else the request host, without a port. func meetingsAttendeeHost(r *http.Request) string { diff --git a/src/pkg/dashboard/meeting_attendee_ui_test.go b/src/pkg/dashboard/meeting_attendee_ui_test.go index bce85d5ba4..b4d3ce849b 100644 --- a/src/pkg/dashboard/meeting_attendee_ui_test.go +++ b/src/pkg/dashboard/meeting_attendee_ui_test.go @@ -41,35 +41,6 @@ func TestSettingsMeetingAttendeeTabWiring(t *testing.T) { } } -// jsConstBlock returns a const declaration whose value may span lines (an -// object or array literal), through its closing bracket and semicolon. -func jsConstBlock(t *testing.T, html, name string) string { - t.Helper() - start := strings.Index(html, "const "+name+" = ") - if start < 0 { - t.Fatalf("index.html does not declare const %s", name) - } - body := start + len("const "+name+" = ") - if c := html[body]; c != '{' && c != '[' { - end := strings.Index(html[body:], ";") - return html[start : body+end+1] - } - depth := 0 - for i := body; i < len(html); i++ { - switch html[i] { - case '{', '[': - depth++ - case '}', ']': - depth-- - if depth == 0 { - return html[start:i+1] + ";" - } - } - } - t.Fatalf("const %s never closes", name) - return "" -} - // TestMeetingAttendeeTabBehaviour executes the tab's rules against the real // preset and voice catalog: flags, the intro preview, the voice list // filtered by language, picking a preset, a language change keeping a voice From d31d9e1c40e24a34a5ab061db769b1480390c041 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 08:45:24 -0500 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=90=9B=20meetings:=20play=20the=20per?= =?UTF-8?q?sona=20sample=20from=20the=20dashboard=20origin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dashboard CSP has no media-src, so a blob URL cannot play and the downloads ratchet forbids createObjectURL. The