From d85692ddfdab7ae84b8afc2bee51ad6f1524ed98 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 15:56:52 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20Inbox:=20delete=20hive=20record?= =?UTF-8?q?ings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DELETE /api/inbox/hive-recording/{id} removes a finished recording's stored audio and chunks, its Knowledge fact (machine transcript), its transcript record and the Inbox item state. Owners delete any recording, read-write members only their own, read never; 409 while in progress or being transcribed. Shared copies are not touched. Audited as inbox_recording_delete. The Inbox shows 🗑 Delete with an in-page confirm. Signed-off-by: Andy Anderson --- changelog.d/added-inbox-recording-delete.md | 1 + dashboard/openapi.json | 91 +++++++++ src/docs/api-reference/knowledge.md | 1 + src/docs/inbox-recording.md | 12 ++ src/pkg/dashboard/api_inbox_recordings.go | 32 ++- .../api_inbox_recordings_delete_test.go | 182 ++++++++++++++++++ .../dashboard/inbox_recording_delete.test.js | 48 +++++ src/pkg/dashboard/static-src/js/inbox.js | 38 ++++ src/pkg/dashboard/static/index.html | 38 ++++ src/pkg/inbox/recordings.go | 34 ++++ src/pkg/inbox/recordingsource.go | 76 ++++++++ src/pkg/inbox/store.go | 16 ++ src/pkg/inbox/transcripts.go | 10 + 13 files changed, 578 insertions(+), 1 deletion(-) create mode 100644 changelog.d/added-inbox-recording-delete.md create mode 100644 src/pkg/dashboard/api_inbox_recordings_delete_test.go create mode 100644 src/pkg/dashboard/inbox_recording_delete.test.js diff --git a/changelog.d/added-inbox-recording-delete.md b/changelog.d/added-inbox-recording-delete.md new file mode 100644 index 0000000000..bc01ab9038 --- /dev/null +++ b/changelog.d/added-inbox-recording-delete.md @@ -0,0 +1 @@ +- Inbox: hive recordings get a 🗑 Delete action. It removes the audio stored on the hive, the Inbox item and the recording's Knowledge fact with its transcript, after an in-page confirm that says shared copies (RFCs, issues, DIBS ideas, spek seeds) stay. Owners can delete any recording, read-write members only their own, read members none; each delete is audited as `inbox_recording_delete` (`DELETE /api/inbox/hive-recording/{id}`). diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 9e9e2cf90c..1f11135b72 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -41363,6 +41363,97 @@ } } }, + "/api/inbox/hive-recording/{id}": { + "delete": { + "tags": [ + "Knowledge" + ], + "summary": "Delete a hive recording", + "description": "An owner, or the read-write member who recorded it. Deletes a finished recording for good: its stored audio and chunks, the Inbox item and its state, and its Knowledge fact with the machine transcript. What was already shared from it (RFC, issues, DIBS ideas, spek seeds) is not touched. Audited as `inbox_recording_delete`.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Recording id (the Inbox item id)" + } + ], + "responses": { + "200": { + "description": "Deleted", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + }, + "fact_removed": { + "type": "boolean" + }, + "shares_kept": { + "type": "integer" + } + } + } + } + } + }, + "403": { + "description": "Read role, or a read-write member deleting someone else's recording", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } + }, + "404": { + "description": "Unknown recording", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } + }, + "409": { + "description": "Still in progress, or being transcribed", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } + } + } + } + }, "/api/inbox/recordings/{id}": { "delete": { "tags": [ diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index cbaff06adc..7277bad820 100644 --- a/src/docs/api-reference/knowledge.md +++ b/src/docs/api-reference/knowledge.md @@ -87,6 +87,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/inbox/recordings/{id}/finalize` | The recorder | End a recording: `{duration_ms?}` (the recorder's count, pauses excluded). The chunks are concatenated in order into `audio.webm` or `audio.mp4`, a pending Knowledge fact (personal layer) is written and the item appears in the Inbox. 200 `{id, state, title, duration_ms, bytes, chunks, transcribes}`; audited as `inbox_recording_finalize` (400 no chunk received, 403, 404, 409 already ended) | `pkg/dashboard/api_inbox_recordings.go:22` | | `DELETE` | `/api/inbox/recordings/{id}` | The recorder, or an owner | Abort an in-progress recording and delete its chunks; audited as `inbox_recording_abort` (403, 404, 409 already ended) | `pkg/dashboard/api_inbox_recordings.go:23` | | `GET` | `/api/inbox/recordings/{id}/audio` | Owner or read-write | Play a finished recording from this hive's disk on the dashboard origin: `http.ServeContent` (Range, 206), `Content-Type` audio/webm or audio/mp4, `Cache-Control: no-store`, `Cross-Origin-Resource-Policy: same-origin`. Opening a playback is audited as `inbox_recording_audio` (seeks are not). `GET /api/inbox/hive-recording/{id}/audio/stream` serves the same file (404 unknown or not finished, 410 audio expired after `inbox.recording.retention_days`) | `pkg/dashboard/api_inbox_recordings.go:24` | +| `DELETE` | `/api/inbox/hive-recording/{id}` | An owner, or the read-write member who recorded it | Delete a finished recording for good: its stored audio and chunks, the Inbox item and its state, and its Knowledge fact with the machine transcript. What was already shared from it (RFC, issues, DIBS ideas, spek seeds) is not touched. 200 `{id, deleted, fact_removed, shares_kept}`; audited as `inbox_recording_delete` (403 read role or someone else's recording, 404 unknown, 409 still in progress or being transcribed) | `pkg/dashboard/api_inbox_recordings.go:25` | | `GET` | `/api/meetings/settings` | Owner only | Meetings settings: `enabled`, `enabled_env_override`, `running`, `vexa_url`, `vexa_key_set`, `discord_token_set`, `transcribe_token_set`, `tts_token_set` (secrets are never returned) and `effective` values of the other `meetings.*` keys ([env vars](../env-vars.md#meetings-quorum)) | `pkg/dashboard/api_meetings.go:123` | | `POST` | `/api/meetings/settings` | Owner only | Update `meetings.enabled` and `meetings.vexa.url`, and write the Vexa tenant key, Discord bot token, transcription service token and TTS service token to keystore-sealed secret files (`""` clears one): `{enabled?, vexa_url?, vexa_api_key?, discord_token?, transcribe_token?, tts_token?}`. Returns the settings with `restart_required`; 400 on an invalid value. Audited as `meetings_settings` | `pkg/dashboard/api_meetings.go:124` | | `POST` | `/api/meetings` | Owner only | Send hive to a meeting: `{url}` for Google Meet, Teams or Zoom, or `{platform: "discord", guild_id, channel_id}`, plus `title?` and `voice?`. Returns the meeting record; 400 invalid request, 502 Quorum refused, 503 meetings off. Audited as `meeting_join` | `pkg/dashboard/api_meetings.go:125` | diff --git a/src/docs/inbox-recording.md b/src/docs/inbox-recording.md index f0643cf33b..b7181e0c16 100644 --- a/src/docs/inbox-recording.md +++ b/src/docs/inbox-recording.md @@ -98,6 +98,18 @@ HTTP. The transcript is written into the recording's Knowledge fact. - Transcription limits (`max_bytes`, `max_duration_minutes`, daily and monthly budgets) apply as for every other source. +## Deleting a recording + +**🗑 Delete** on a recording's Inbox item deletes it for good: the audio +stored on this hive (and any chunk left over), the Inbox item and the +recording's Knowledge fact with its transcript. Owners can delete any +recording; read-write members only the ones they recorded; read members +cannot. The dashboard asks first, in the page; when the item was shared, the +question says that what was already shared (RFCs, issues, DIBS ideas, spek +seeds) stays where it is, because delete never touches those copies. A +recording that is being transcribed can be deleted once the transcription +finishes. Every delete is audited as `inbox_recording_delete`. + ## Retention | What | Kept | diff --git a/src/pkg/dashboard/api_inbox_recordings.go b/src/pkg/dashboard/api_inbox_recordings.go index 402acf7636..5b58cc2a8d 100644 --- a/src/pkg/dashboard/api_inbox_recordings.go +++ b/src/pkg/dashboard/api_inbox_recordings.go @@ -22,6 +22,7 @@ func (s *Server) registerInboxRecordingRoutes() { s.mux.HandleFunc("POST /api/inbox/recordings/{id}/finalize", s.handleInboxRecordingFinalize) s.mux.HandleFunc("DELETE /api/inbox/recordings/{id}", s.handleInboxRecordingAbort) s.mux.HandleFunc("GET /api/inbox/recordings/{id}/audio", s.handleInboxRecordingAudio) + s.mux.HandleFunc("DELETE /api/inbox/"+inbox.RecordingType+"/{id}", s.handleInboxRecordingDelete) } // inboxRecordingStartRequest is POST /api/inbox/recordings. @@ -100,7 +101,8 @@ func writeInboxRecordingError(w http.ResponseWriter, err error) { code = http.StatusNotFound case errors.Is(err, inbox.ErrRecordingNotYours): code = http.StatusForbidden - case errors.Is(err, inbox.ErrRecordingClosed), errors.Is(err, inbox.ErrRecordingMismatch): + case errors.Is(err, inbox.ErrRecordingClosed), errors.Is(err, inbox.ErrRecordingMismatch), + errors.Is(err, inbox.ErrRecordingNotFinished), errors.Is(err, inbox.ErrRecordingTranscribing): code = http.StatusConflict case errors.Is(err, inbox.ErrRecordingConsent), errors.Is(err, inbox.ErrRecordingBadRequest), errors.Is(err, inbox.ErrRecordingEmpty): code = http.StatusBadRequest @@ -244,6 +246,34 @@ func (s *Server) handleInboxRecordingAbort(w http.ResponseWriter, r *http.Reques jsonResponse(w, map[string]any{"id": m.ID, "aborted": true}) } +// handleInboxRecordingDelete deletes a finished hive recording: the stored +// audio and chunks, the Inbox item and its Knowledge fact (the machine +// transcript). Owners may delete any recording, read-write members only +// their own, read members none (403). What was already shared from it is +// not touched. 409 while it is in progress or being transcribed. +func (s *Server) handleInboxRecordingDelete(w http.ResponseWriter, r *http.Request) { + if !requireInboxPlaybackRole(w, r) { + return + } + svc, ok := s.inboxService(w) + if !ok { + return + } + asOwner := isOwnerRole(r.Header.Get("X-Hive-Role")) + res, err := svc.DeleteRecording(strings.TrimSpace(r.PathValue("id")), requestUser(r), asOwner, s.inboxRecordingOptions(r)) + if err != nil && res.ID == "" { + writeInboxRecordingError(w, err) + return + } + if err != nil { + // The audio and metadata are gone; a leftover (fact, transcript + // record or item state) is logged, not reported as a failure. + s.logger.Warn("inbox: recording delete left something behind", "recording", res.ID, "error", err) + } + w.Header().Set("Cache-Control", "no-store") + jsonResponse(w, map[string]any{"id": res.ID, "deleted": true, "fact_removed": res.FactRemoved, "shares_kept": res.SharesKept}) +} + // handleInboxRecordingAudio (owner or read-write) serves a finished // recording from this hive's disk, on the dashboard origin, with Range // support (http.ServeContent) and no-store. After retention the audio is diff --git a/src/pkg/dashboard/api_inbox_recordings_delete_test.go b/src/pkg/dashboard/api_inbox_recordings_delete_test.go new file mode 100644 index 0000000000..4682b832d8 --- /dev/null +++ b/src/pkg/dashboard/api_inbox_recordings_delete_test.go @@ -0,0 +1,182 @@ +package dashboard + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/inbox" + "github.com/hivecommons/hive/pkg/knowledge/connector" +) + +// recordingDeleteOtherUser is a second read-write member: not the recorder. +const recordingDeleteOtherUser = "someone-else@example.com" + +// doRecordingAs sends one request as role with an explicit user. +func doRecordingAs(s *Server, method, path, role, user string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, bytes.NewReader(nil)) + if role != "" { + req.Header.Set("X-Hive-Role", role) + req.Header.Set("X-Hive-User", user) + if role == config.RoleOwner { + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + } + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + return rec +} + +// finishTestRecording records one chunk as role and finalizes it. +func finishTestRecording(t *testing.T, s *Server, role string) string { + t.Helper() + id := startTestRecording(t, s, role) + if rec := doRecording(s, http.MethodPost, chunkPath(id, 0), role, recordingWebM, nil); rec.Code != http.StatusOK { + t.Fatalf("chunk = %d %s", rec.Code, rec.Body) + } + if rec := doRecording(s, http.MethodPost, "/api/inbox/recordings/"+id+"/finalize", role, []byte(`{"duration_ms":4000}`), nil); rec.Code != http.StatusOK { + t.Fatalf("finalize = %d %s", rec.Code, rec.Body) + } + return id +} + +func recordingDeletePath(id string) string { return "/api/inbox/" + inbox.RecordingType + "/" + id } + +func recordingFactPath(src *inbox.RecordingSource, id string) string { + return filepath.Join(src.FactDir, connector.Slug(inbox.RecordingType, inbox.RecordingConnector, id)+".md") +} + +func exists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +func TestInboxRecordingDeleteRoleMatrix(t *testing.T) { + s, svc, src := newRecordingTestServer(t, config.InboxRecording{}) + id := finishTestRecording(t, s, config.RoleReadWrite) + creator := config.RoleReadWrite + "@example.com" + dir := filepath.Join(src.Store.Dir, id) + if !exists(dir) || !exists(recordingFactPath(src, id)) { + t.Fatal("finalized recording has no audio dir or fact") + } + for _, tc := range []struct{ name, role, user string }{ + {"anonymous", "", ""}, + {"read", config.RoleRead, config.RoleRead + "@example.com"}, + {"read as the recorder", config.RoleRead, creator}, + {"read-write non-creator", config.RoleReadWrite, recordingDeleteOtherUser}, + } { + if rec := doRecordingAs(s, http.MethodDelete, recordingDeletePath(id), tc.role, tc.user); rec.Code != http.StatusForbidden { + t.Fatalf("%s delete = %d %s, want 403", tc.name, rec.Code, rec.Body) + } + } + if !exists(dir) || !exists(recordingFactPath(src, id)) { + t.Fatal("a refused delete removed something") + } + rec := doRecordingAs(s, http.MethodDelete, recordingDeletePath(id), config.RoleReadWrite, creator) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"deleted":true`) { + t.Fatalf("creator delete = %d %s", rec.Code, rec.Body) + } + if rec := doRecordingAs(s, http.MethodDelete, recordingDeletePath(id), config.RoleReadWrite, creator); rec.Code != http.StatusNotFound { + t.Fatalf("second delete = %d, want 404", rec.Code) + } + + // An owner deletes a read-write member's recording. + id2 := finishTestRecording(t, s, config.RoleReadWrite) + if rec := doRecordingAs(s, http.MethodDelete, recordingDeletePath(id2), config.RoleOwner, config.RoleOwner+"@example.com"); rec.Code != http.StatusOK { + t.Fatalf("owner delete = %d %s", rec.Code, rec.Body) + } + if e := s.audit.Recent(1); len(e) != 1 || e[0].Action != "inbox_recording_delete" || !strings.Contains(e[0].Detail, "recording="+id2) || !strings.Contains(e[0].Detail, "recorded_by="+creator) { + t.Fatalf("delete not audited: %+v", e) + } + items, err := svc.Items(context.Background()) + if err != nil { + t.Fatal(err) + } + for _, it := range items { + if it.Source == inbox.RecordingType { + t.Fatalf("deleted recording still listed: %+v", it) + } + } +} + +// Delete removes the stored audio, the Knowledge fact with its machine +// transcript, and the transcript record; the share history count is +// reported and what was shared is not touched. +func TestInboxRecordingDeleteRemovesAudioAndFact(t *testing.T) { + s, svc, src := newRecordingTestServer(t, config.InboxRecording{}) + store := inbox.NewTranscriptStore(filepath.Join(t.TempDir(), "transcripts")) + svc.EnableTranscription(store) + id := finishTestRecording(t, s, config.RoleReadWrite) + audio := filepath.Join(src.Store.Dir, id) + fact := recordingFactPath(src, id) + if err := store.Put(inbox.TranscriptRecord{Source: inbox.RecordingType, ID: id, Status: inbox.TranscriptionDone, Provider: "whisper", Model: "base.en", Text: "ship it", UpdatedAt: time.Now()}); err != nil { + t.Fatal(err) + } + if _, err := svc.Store.AppendShare(inbox.Key(inbox.RecordingType, id), inbox.ShareRecord{Destination: inbox.DestDibs, Actor: "owner@example.com", StartedAt: time.Now(), Status: inbox.StatusFiled, Ref: &inbox.ShareRef{URL: "https://dibs.example/1"}}); err != nil { + t.Fatal(err) + } + + // Refused while its transcription runs: nothing is removed. + if err := store.Put(inbox.TranscriptRecord{Source: inbox.RecordingType, ID: id, Status: inbox.TranscriptionRunning, UpdatedAt: time.Now()}); err != nil { + t.Fatal(err) + } + if rec := doRecording(s, http.MethodDelete, recordingDeletePath(id), config.RoleReadWrite, nil, nil); rec.Code != http.StatusConflict { + t.Fatalf("delete while transcribing = %d %s, want 409", rec.Code, rec.Body) + } + if !exists(audio) || !exists(fact) { + t.Fatal("a refused delete removed the audio or the fact") + } + if err := store.Put(inbox.TranscriptRecord{Source: inbox.RecordingType, ID: id, Status: inbox.TranscriptionDone, Text: "ship it", UpdatedAt: time.Now()}); err != nil { + t.Fatal(err) + } + + rec := doRecording(s, http.MethodDelete, recordingDeletePath(id), config.RoleReadWrite, nil, nil) + if rec.Code != http.StatusOK { + t.Fatalf("delete = %d %s", rec.Code, rec.Body) + } + var body struct { + Deleted bool `json:"deleted"` + FactRemoved bool `json:"fact_removed"` + SharesKept int `json:"shares_kept"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if !body.Deleted || !body.FactRemoved || body.SharesKept != 1 { + t.Fatalf("delete response = %+v", body) + } + if exists(audio) { + t.Fatal("audio directory survived the delete") + } + if exists(fact) { + t.Fatal("knowledge fact survived the delete") + } + if _, ok := store.Get(inbox.RecordingType, id); ok { + t.Fatal("transcript record survived the delete") + } + if h := svc.Store.History(inbox.Key(inbox.RecordingType, id)); len(h) != 0 { + t.Fatalf("item state survived: %+v", h) + } + if rec := doRecording(s, http.MethodGet, "/api/inbox/recordings/"+id+"/audio", config.RoleReadWrite, nil, nil); rec.Code != http.StatusNotFound { + t.Fatalf("audio after delete = %d, want 404", rec.Code) + } +} + +func TestInboxRecordingDeleteInProgressAndUnknown(t *testing.T) { + s, _, _ := newRecordingTestServer(t, config.InboxRecording{}) + if rec := doRecording(s, http.MethodDelete, recordingDeletePath("nope"), config.RoleOwner, nil, nil); rec.Code != http.StatusNotFound { + t.Fatalf("unknown = %d, want 404", rec.Code) + } + id := startTestRecording(t, s, config.RoleReadWrite) + if rec := doRecording(s, http.MethodDelete, recordingDeletePath(id), config.RoleReadWrite, nil, nil); rec.Code != http.StatusConflict { + t.Fatalf("in-progress delete = %d %s, want 409", rec.Code, rec.Body) + } +} diff --git a/src/pkg/dashboard/inbox_recording_delete.test.js b/src/pkg/dashboard/inbox_recording_delete.test.js new file mode 100644 index 0000000000..babe5bc01b --- /dev/null +++ b/src/pkg/dashboard/inbox_recording_delete.test.js @@ -0,0 +1,48 @@ +// Inbox 🗑 Delete on hive recordings: who sees it, and the in-page confirm +// text (shared copies stay). +// Run: node --test src/pkg/dashboard/*.test.js +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); +const ASYNC_PREFIX = 'async '; +const fnSrc = name => { + let start = html.indexOf('function ' + name + '('); + assert.ok(start >= 0, name + ' not found'); + if (html.slice(start - ASYNC_PREFIX.length, start) === ASYNC_PREFIX) start -= ASYNC_PREFIX.length; + let depth = 0; + for (let i = html.indexOf('{', start); i < html.length; i++) { + if (html[i] === '{') depth++; + else if (html[i] === '}' && --depth === 0) return html.slice(start, i + 1); + } + throw new Error('unbalanced ' + name); +}; +const lib = new Function(fnSrc('inboxCanDeleteRecording') + '\n' + fnSrc('inboxDeleteRecordingText') + '\nreturn { inboxCanDeleteRecording, inboxDeleteRecordingText };')(); + +test('owners delete any hive recording, read-write only their own, read never', () => { + const it = { source: 'hive-recording', id: 'r1', recorded_by: 'ana@example.com' }; + const can = lib.inboxCanDeleteRecording; + assert.strictEqual(can(it, 'owner', 'bob@example.com'), true); + assert.strictEqual(can(it, 'read-write', 'ana@example.com'), true); + assert.strictEqual(can(it, 'read-write', 'ANA@example.com'), true, 'logins compare case-insensitively'); + assert.strictEqual(can(it, 'read-write', 'bob@example.com'), false); + assert.strictEqual(can(it, 'read-write', ''), false); + assert.strictEqual(can(it, 'read', 'ana@example.com'), false); + assert.strictEqual(can(Object.assign({}, it, { source: 'plaud' }), 'owner', 'bob@example.com'), false, 'only hive recordings'); +}); + +test('the confirm says shared copies stay only when there is share history', () => { + const plain = lib.inboxDeleteRecordingText({ source: 'hive-recording' }); + assert.strictEqual(plain, 'This deletes the audio stored on this hive, this Inbox item and its transcript in Knowledge. It cannot be undone.'); + const shared = lib.inboxDeleteRecordingText({ source: 'hive-recording', share_history: [{ destination: 'dibs' }, { destination: 'spek_rfc' }] }); + assert.match(shared, /What was already shared from it \(2 shares: RFCs, issues, DIBS ideas, spek seeds\) stays where it is\.$/); +}); + +test('delete uses the in-page confirm and the DELETE endpoint', () => { + const src = fnSrc('inboxDeleteRecording'); + assert.match(src, /hiveConfirm\(/); + assert.doesNotMatch(src, /window\.confirm|\balert\(|[^.]confirm\(/); + assert.match(src, /'\/api\/inbox\/hive-recording\/' \+ encodeURIComponent\(id\), \{ method: 'DELETE' \}/); +}); diff --git a/src/pkg/dashboard/static-src/js/inbox.js b/src/pkg/dashboard/static-src/js/inbox.js index d5b9f6dbdd..ee6e319fd4 100644 --- a/src/pkg/dashboard/static-src/js/inbox.js +++ b/src/pkg/dashboard/static-src/js/inbox.js @@ -430,6 +430,11 @@ } else { actions += ''; } + if (inboxCanDeleteRecording(it, window._hiveRole, window._hiveUser)) { + const busy = it.transcription && (it.transcription.status === 'queued' || it.transcription.status === 'running'); + actions += ''; + } return '
' + (inboxCanShare(window._hiveRole) ? '' : '') + '
' + inboxSourceIcon(it.source) + '
' + @@ -783,6 +788,39 @@ if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); return data; } + // inboxCanDeleteRecording: a hive recording may be deleted by an owner, + // or by the read-write member who recorded it; read members never. + function inboxCanDeleteRecording(it, role, user) { + if (!it || it.source !== 'hive-recording') return false; + if (role === 'owner') return true; + return role === 'read-write' && !!user && !!it.recorded_by && String(it.recorded_by).toLowerCase() === String(user).toLowerCase(); + } + // inboxDeleteRecordingText is the confirm text; with share history it + // says that the shared copies stay. + function inboxDeleteRecordingText(it) { + const shared = ((it && it.share_history) || []).length; + let text = 'This deletes the audio stored on this hive, this Inbox item and its transcript in Knowledge. It cannot be undone.'; + if (shared) text += ' What was already shared from it (' + shared + ' share' + (shared === 1 ? '' : 's') + ': RFCs, issues, DIBS ideas, spek seeds) stays where it is.'; + return text; + } + async function inboxDeleteRecording(id) { + const it = inboxFind('hive-recording', id); + if (!it) return; + const ok = await hiveConfirm({ title: 'Delete this recording?', message: inboxDeleteRecordingText(it), confirmLabel: 'Delete', danger: true }); + if (!ok) return; + try { + const r = await fetch('/api/inbox/hive-recording/' + encodeURIComponent(id), { method: 'DELETE' }); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + const key = 'hive-recording/' + id; + delete _inboxContent[key]; + _inboxSelected.delete(key); + showToast('Recording deleted', 'success'); + } catch (e) { + showToast('Could not delete the recording: ' + e.message, 'error'); + } + await fetchInbox(); + } // Approval queue for mailed-in files from outside the allowlist (#18395). async function inboxEmailAct(id, action) { try { diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 33ba10bdba..846d7174bd 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -48169,6 +48169,11 @@ } else { actions += ''; } + if (inboxCanDeleteRecording(it, window._hiveRole, window._hiveUser)) { + const busy = it.transcription && (it.transcription.status === 'queued' || it.transcription.status === 'running'); + actions += ''; + } return '
' + (inboxCanShare(window._hiveRole) ? '' : '') + '
' + inboxSourceIcon(it.source) + '
' + @@ -48522,6 +48527,39 @@ if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); return data; } + // inboxCanDeleteRecording: a hive recording may be deleted by an owner, + // or by the read-write member who recorded it; read members never. + function inboxCanDeleteRecording(it, role, user) { + if (!it || it.source !== 'hive-recording') return false; + if (role === 'owner') return true; + return role === 'read-write' && !!user && !!it.recorded_by && String(it.recorded_by).toLowerCase() === String(user).toLowerCase(); + } + // inboxDeleteRecordingText is the confirm text; with share history it + // says that the shared copies stay. + function inboxDeleteRecordingText(it) { + const shared = ((it && it.share_history) || []).length; + let text = 'This deletes the audio stored on this hive, this Inbox item and its transcript in Knowledge. It cannot be undone.'; + if (shared) text += ' What was already shared from it (' + shared + ' share' + (shared === 1 ? '' : 's') + ': RFCs, issues, DIBS ideas, spek seeds) stays where it is.'; + return text; + } + async function inboxDeleteRecording(id) { + const it = inboxFind('hive-recording', id); + if (!it) return; + const ok = await hiveConfirm({ title: 'Delete this recording?', message: inboxDeleteRecordingText(it), confirmLabel: 'Delete', danger: true }); + if (!ok) return; + try { + const r = await fetch('/api/inbox/hive-recording/' + encodeURIComponent(id), { method: 'DELETE' }); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + const key = 'hive-recording/' + id; + delete _inboxContent[key]; + _inboxSelected.delete(key); + showToast('Recording deleted', 'success'); + } catch (e) { + showToast('Could not delete the recording: ' + e.message, 'error'); + } + await fetchInbox(); + } // Approval queue for mailed-in files from outside the allowlist (#18395). async function inboxEmailAct(id, action) { try { diff --git a/src/pkg/inbox/recordings.go b/src/pkg/inbox/recordings.go index 6319998d17..d50975818c 100644 --- a/src/pkg/inbox/recordings.go +++ b/src/pkg/inbox/recordings.go @@ -105,6 +105,12 @@ var ( ErrRecordingEmpty = errors.New("no audio was received for this recording") ErrRecordingExpired = errors.New("the audio of this recording has expired") ErrRecordingBadRequest = errors.New("invalid recording request") + // ErrRecordingNotFinished refuses a delete of a recording in progress + // (discard it from the recorder instead). + ErrRecordingNotFinished = errors.New("this recording is still in progress; discard it from the recorder") + // ErrRecordingTranscribing refuses a delete while the recording's + // transcription is queued or running. + ErrRecordingTranscribing = errors.New("this recording is being transcribed; delete it once the transcription finishes") ) // RecordingActiveError is returned when the user already has a recording in @@ -608,6 +614,34 @@ func (s *RecordingStore) Abort(id, user string, asOwner bool) (RecordingMeta, er return out, nil } +// Delete removes a finished recording: its directory (audio, any chunk +// left over, meta.json) and its metadata. The recorder may delete their own; +// an owner (asOwner) may delete anyone's. A recording still in progress is +// aborted, not deleted (ErrRecordingNotFinished). +func (s *RecordingStore) Delete(id, user string, asOwner bool) (RecordingMeta, error) { + s.mu.Lock() + defer s.mu.Unlock() + owner := user + if asOwner { + owner = "" + } else if user == "" { + return RecordingMeta{}, ErrRecordingNotYours + } + m, err := s.get(id, owner) + if err != nil { + return RecordingMeta{}, err + } + if m.State != RecordingFinalized { + return RecordingMeta{}, ErrRecordingNotFinished + } + out := *m + if err := os.RemoveAll(s.dir(id)); err != nil { + return RecordingMeta{}, err + } + delete(s.metas, id) + return out, nil +} + // Get returns one recording's metadata. func (s *RecordingStore) Get(id string) (RecordingMeta, bool) { s.mu.Lock() diff --git a/src/pkg/inbox/recordingsource.go b/src/pkg/inbox/recordingsource.go index 654fb1d81d..1b1d376ac5 100644 --- a/src/pkg/inbox/recordingsource.go +++ b/src/pkg/inbox/recordingsource.go @@ -363,6 +363,82 @@ func (s *Service) AbortRecording(id, user string, asOwner bool, opts RecordingOp return m, nil } +// RecordingDeleted is what DeleteRecording removed. +type RecordingDeleted struct { + ID string `json:"id"` + RecordedBy string `json:"recorded_by"` + // FactRemoved reports that the recording's Knowledge fact (with its + // machine transcript) was deleted. + FactRemoved bool `json:"fact_removed"` + // SharesKept is how many shares the item's history held; what they + // filed (RFCs, issues, DIBS ideas, spek seeds) is not touched. + SharesKept int `json:"shares_kept"` +} + +// DeleteRecording deletes a finished hive recording for good: the stored +// audio and any chunk left over, the recording's metadata, its Knowledge +// fact (the machine transcript), its transcript record and the Inbox item's +// state. The recorder may delete their own; an owner (asOwner) anyone's. +// Copies already shared from it (RFC, issues, DIBS, spek seeds) stay where +// they are. A recording whose transcription is queued or running is refused +// (ErrRecordingTranscribing). Audited as inbox_recording_delete. It works +// while recording is disabled: the recordings stay until retention. +func (s *Service) DeleteRecording(id, user string, asOwner bool, opts RecordingOptions) (RecordingDeleted, error) { + src := s.recordingSource() + if src == nil { + return RecordingDeleted{}, ErrRecordingNotFound + } + m, ok := src.Store.Get(id) + if !ok { + return RecordingDeleted{}, ErrRecordingNotFound + } + if !asOwner && (user == "" || m.RecordedBy != user) { + return RecordingDeleted{}, ErrRecordingNotYours + } + store := s.transcriptStore() + // Hold the transcription lock so no job is queued for this recording + // between the busy check and the delete. + s.txMu.Lock() + defer s.txMu.Unlock() + if store != nil { + if rec, ok := store.Get(RecordingType, id); ok && (rec.Status == TranscriptionQueued || rec.Status == TranscriptionRunning) { + return RecordingDeleted{}, ErrRecordingTranscribing + } + } + m, err := src.Store.Delete(id, user, asOwner) + if err != nil { + return RecordingDeleted{}, err + } + out := RecordingDeleted{ID: m.ID, RecordedBy: m.RecordedBy} + var errs []error + if src.FactDir != "" { + s.factMu.Lock() + err := os.Remove(src.factPath(m.ID)) + s.factMu.Unlock() + switch { + case err == nil: + out.FactRemoved = true + case !os.IsNotExist(err): + errs = append(errs, fmt.Errorf("delete recording fact: %w", err)) + } + } + if store != nil { + if err := store.Delete(RecordingType, m.ID); err != nil { + errs = append(errs, fmt.Errorf("delete recording transcript: %w", err)) + } + } + if s.Store != nil { + n, err := s.Store.Forget(Key(RecordingType, m.ID)) + out.SharesKept = n + if err != nil { + errs = append(errs, fmt.Errorf("forget recording item: %w", err)) + } + } + opts.audit("inbox_recording_delete", "recording", m.ID, "recorded_by", m.RecordedBy, "bytes", strconv.FormatInt(m.Bytes, 10), + "fact_removed", strconv.FormatBool(out.FactRemoved), "shares_kept", strconv.Itoa(out.SharesKept)) + return out, errors.Join(errs...) +} + // OpenRecordingAudio opens a finalized recording's audio (playback works // while recording is disabled: the recordings stay until retention). func (s *Service) OpenRecordingAudio(id string) (LocalAudio, error) { diff --git a/src/pkg/inbox/store.go b/src/pkg/inbox/store.go index 540f935b1d..dad5ab59ff 100644 --- a/src/pkg/inbox/store.go +++ b/src/pkg/inbox/store.go @@ -372,6 +372,22 @@ func (s *Store) History(key string) []*ShareRecord { return nil } +// Forget drops every persisted state of one item (routes, intents, share +// history). It reports how many shares the history held. The copies those +// shares made elsewhere are not touched. +func (s *Store) Forget(key string) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + e := s.entries[key] + if e == nil { + return 0, nil + } + n := len(e.History) + delete(s.entries, key) + return n, s.save() +} + // PendingRFCKeys lists the items with an RFC share still in progress. func (s *Store) PendingRFCKeys() []string { s.mu.Lock() diff --git a/src/pkg/inbox/transcripts.go b/src/pkg/inbox/transcripts.go index 7a6b32c50a..70dbbe35fb 100644 --- a/src/pkg/inbox/transcripts.go +++ b/src/pkg/inbox/transcripts.go @@ -231,6 +231,16 @@ func (s *TranscriptStore) Put(rec TranscriptRecord) error { return writeFileAtomic(s.path(rec.Source, rec.ID), data) } +// Delete removes one record; a missing record is not an error. +func (s *TranscriptStore) Delete(source, id string) error { + s.mu.Lock() + defer s.mu.Unlock() + if err := os.Remove(s.path(source, id)); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + // Usage returns what was spent this month and today (UTC). func (s *TranscriptStore) Usage(now time.Time) TranscriptUsage { s.mu.Lock() From 835e692670852e2edffb32ba481be61e913fc8b8 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 16:10:25 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=E2=9C=A8=20Inbox=20recording=20delete:=20l?= =?UTF-8?q?iteral=20route=20string=20for=20the=20citation=20guard,=20inbox?= =?UTF-8?q?-item=20test=20loads=20inboxCanDeleteRecording?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- dashboard/test/inbox-item.test.js | 2 +- src/pkg/dashboard/api_inbox_recordings.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dashboard/test/inbox-item.test.js b/dashboard/test/inbox-item.test.js index 39e0a8c860..430c51a547 100644 --- a/dashboard/test/inbox-item.test.js +++ b/dashboard/test/inbox-item.test.js @@ -51,7 +51,7 @@ function makeContext(role) { Array, }; vm.createContext(ctx); - for (const fn of ['inboxSharePillText', 'inboxShareTargetHref', 'inboxSharePillHtml', 'inboxSharePillsHtml', 'inboxCanShare', 'inboxIntentLabel', 'inboxIntentThen', 'inboxSourceIcon', 'inboxItemHasAudio', 'inboxItemKey', 'inboxViewerCanPlay', 'inboxApiPath', 'inboxFmtDuration', 'inboxStatePill', 'inboxSummaryHtml', 'inboxTranscriptHtml', 'inboxTxUnavailableText', 'inboxTxEtaText', 'inboxTxElapsedText', 'inboxTxProgressHtml', 'inboxTranscriptionHtml', 'inboxItemHtml']) { + for (const fn of ['inboxSharePillText', 'inboxShareTargetHref', 'inboxSharePillHtml', 'inboxSharePillsHtml', 'inboxCanShare', 'inboxIntentLabel', 'inboxIntentThen', 'inboxSourceIcon', 'inboxItemHasAudio', 'inboxItemKey', 'inboxViewerCanPlay', 'inboxApiPath', 'inboxFmtDuration', 'inboxStatePill', 'inboxSummaryHtml', 'inboxTranscriptHtml', 'inboxTxUnavailableText', 'inboxTxEtaText', 'inboxTxElapsedText', 'inboxTxProgressHtml', 'inboxTranscriptionHtml', 'inboxCanDeleteRecording', 'inboxItemHtml']) { vm.runInContext(extractFunction(fn), ctx); } return ctx; diff --git a/src/pkg/dashboard/api_inbox_recordings.go b/src/pkg/dashboard/api_inbox_recordings.go index 5b58cc2a8d..c661448807 100644 --- a/src/pkg/dashboard/api_inbox_recordings.go +++ b/src/pkg/dashboard/api_inbox_recordings.go @@ -22,7 +22,7 @@ func (s *Server) registerInboxRecordingRoutes() { s.mux.HandleFunc("POST /api/inbox/recordings/{id}/finalize", s.handleInboxRecordingFinalize) s.mux.HandleFunc("DELETE /api/inbox/recordings/{id}", s.handleInboxRecordingAbort) s.mux.HandleFunc("GET /api/inbox/recordings/{id}/audio", s.handleInboxRecordingAudio) - s.mux.HandleFunc("DELETE /api/inbox/"+inbox.RecordingType+"/{id}", s.handleInboxRecordingDelete) + s.mux.HandleFunc("DELETE /api/inbox/hive-recording/{id}", s.handleInboxRecordingDelete) } // inboxRecordingStartRequest is POST /api/inbox/recordings. From 0df97d4486a87c4c41c8519964aeadd0764e6a38 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 16:25:00 -0500 Subject: [PATCH 3/3] =?UTF-8?q?=E2=9C=A8=20Inbox=20recording=20delete:=20i?= =?UTF-8?q?nbox=20package=20tests=20for=20DeleteRecording,=20Store.Forget?= =?UTF-8?q?=20and=20TranscriptStore.Delete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/inbox/recordings_delete_test.go | 155 ++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 src/pkg/inbox/recordings_delete_test.go diff --git a/src/pkg/inbox/recordings_delete_test.go b/src/pkg/inbox/recordings_delete_test.go new file mode 100644 index 0000000000..11046456bf --- /dev/null +++ b/src/pkg/inbox/recordings_delete_test.go @@ -0,0 +1,155 @@ +package inbox + +import ( + "context" + "errors" + "os" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// A transcribed recording is deleted for good: audio directory, the fact +// holding the machine transcript, the transcript record and the item state. +// The share history is counted, not followed. +func TestDeleteRecordingRemovesAudioFactAndTranscript(t *testing.T) { + svc, src, _ := newRecordingService(t, enabledRecording()) + withTranscription(t, svc, config.InboxTranscription{Enabled: true, ConsentAcknowledged: true}) + m := recordAndFinalize(t, svc, "ana", RecordingOptions{}) + svc.Wait() + if _, err := svc.Items(context.Background()); err != nil { + t.Fatal(err) + } + fact := src.factPath(m.ID) + data, err := os.ReadFile(fact) + if err != nil { + t.Fatalf("no fact after finalize: %v", err) + } + if !strings.Contains(string(data), "decisions were made") { + t.Fatalf("fact has no machine transcript:\n%s", data) + } + if rec, ok := svc.transcriptStore().Get(RecordingType, m.ID); !ok || rec.Status != TranscriptionDone { + t.Fatalf("transcript record = %+v %v", rec, ok) + } + key := Key(RecordingType, m.ID) + if _, err := svc.Store.AppendShare(key, ShareRecord{Destination: DestDibs, Actor: "ana", StartedAt: time.Now(), Status: StatusFiled}); err != nil { + t.Fatal(err) + } + + var audits []RecordingAudit + opts := RecordingOptions{Actor: "ana", Audit: func(a RecordingAudit) { audits = append(audits, a) }} + if _, err := svc.DeleteRecording(m.ID, "bob", false, opts); !errors.Is(err, ErrRecordingNotYours) { + t.Fatalf("someone else's delete = %v, want ErrRecordingNotYours", err) + } + if _, err := svc.DeleteRecording(m.ID, "", false, opts); !errors.Is(err, ErrRecordingNotYours) { + t.Fatalf("anonymous delete = %v, want ErrRecordingNotYours", err) + } + res, err := svc.DeleteRecording(m.ID, "ana", false, opts) + if err != nil { + t.Fatal(err) + } + if res.ID != m.ID || res.RecordedBy != "ana" || !res.FactRemoved || res.SharesKept != 1 { + t.Fatalf("result = %+v", res) + } + if _, err := os.Stat(src.Store.dir(m.ID)); !os.IsNotExist(err) { + t.Fatalf("audio dir still there: %v", err) + } + if _, err := os.Stat(fact); !os.IsNotExist(err) { + t.Fatalf("fact still there: %v", err) + } + if _, ok := svc.transcriptStore().Get(RecordingType, m.ID); ok { + t.Fatal("transcript record survived") + } + if h := svc.Store.History(key); len(h) != 0 { + t.Fatalf("share history survived: %+v", h) + } + if _, ok := src.Store.Get(m.ID); ok { + t.Fatal("metadata survived") + } + items, err := src.List(context.Background()) + if err != nil || len(items) != 0 { + t.Fatalf("listing after delete = %+v, %v", items, err) + } + if len(audits) != 1 || audits[0].Action != "inbox_recording_delete" || !strings.Contains(audits[0].Detail(), "recording="+m.ID) || !strings.Contains(audits[0].Detail(), "shares_kept=1") { + t.Fatalf("audits = %+v", audits) + } + if _, err := svc.DeleteRecording(m.ID, "ana", false, opts); !errors.Is(err, ErrRecordingNotFound) { + t.Fatalf("second delete = %v, want ErrRecordingNotFound", err) + } +} + +func TestDeleteRecordingOwnerInProgressAndTranscribing(t *testing.T) { + svc, src, _ := newRecordingService(t, enabledRecording()) + m := recordAndFinalize(t, svc, "ana", RecordingOptions{}) + + // Refused while its transcription is queued or running; nothing removed. + for _, st := range []string{TranscriptionQueued, TranscriptionRunning} { + if err := svc.transcriptStore().Put(TranscriptRecord{Source: RecordingType, ID: m.ID, Status: st}); err != nil { + t.Fatal(err) + } + if _, err := svc.DeleteRecording(m.ID, "", true, RecordingOptions{}); !errors.Is(err, ErrRecordingTranscribing) { + t.Fatalf("%s: delete = %v, want ErrRecordingTranscribing", st, err) + } + if _, ok := src.Store.Get(m.ID); !ok { + t.Fatalf("%s: a refused delete removed the recording", st) + } + } + if err := svc.transcriptStore().Put(TranscriptRecord{Source: RecordingType, ID: m.ID, Status: TranscriptionFailed}); err != nil { + t.Fatal(err) + } + // An owner deletes anyone's recording (no user needed). + res, err := svc.DeleteRecording(m.ID, "", true, RecordingOptions{}) + if err != nil || res.ID != m.ID || !res.FactRemoved || res.SharesKept != 0 { + t.Fatalf("owner delete = %+v, %v", res, err) + } + + // A recording in progress is aborted, not deleted. + live := startRecording(t, svc, "ana", "audio/webm") + if _, err := svc.DeleteRecording(live.ID, "ana", false, RecordingOptions{}); !errors.Is(err, ErrRecordingNotFinished) { + t.Fatalf("in-progress delete = %v, want ErrRecordingNotFinished", err) + } + if _, err := svc.DeleteRecording("nope", "", true, RecordingOptions{}); !errors.Is(err, ErrRecordingNotFound) { + t.Fatalf("unknown = %v, want ErrRecordingNotFound", err) + } +} + +func TestDeleteRecordingWithoutRecordingsOrFact(t *testing.T) { + svc := NewService(config.InboxConfig{Recording: enabledRecording()}, NewStore(""), nil, nil, nil) + if _, err := svc.DeleteRecording("r", "ana", false, RecordingOptions{}); !errors.Is(err, ErrRecordingNotFound) { + t.Fatalf("no recordings wired = %v, want ErrRecordingNotFound", err) + } + + // A recording whose fact was never written still deletes. + svc2, src, _ := newRecordingService(t, enabledRecording()) + m := recordAndFinalize(t, svc2, "ana", RecordingOptions{}) + if err := os.Remove(src.factPath(m.ID)); err != nil { + t.Fatal(err) + } + res, err := svc2.DeleteRecording(m.ID, "ana", false, RecordingOptions{}) + if err != nil || res.FactRemoved { + t.Fatalf("delete without fact = %+v, %v", res, err) + } +} + +func TestRecordingStoreDeleteChecks(t *testing.T) { + _, src, _ := newRecordingService(t, enabledRecording()) + if _, err := src.Store.Delete("nope", "ana", false); !errors.Is(err, ErrRecordingNotFound) { + t.Fatalf("unknown = %v", err) + } + if _, err := src.Store.Delete("nope", "", false); !errors.Is(err, ErrRecordingNotYours) { + t.Fatalf("no user, not owner = %v", err) + } +} + +func TestStoreForgetAndTranscriptDeleteMissing(t *testing.T) { + st := NewStore("") + if n, err := st.Forget("hive-recording/none"); n != 0 || err != nil { + t.Fatalf("forget unknown = %d, %v", n, err) + } + ts := NewTranscriptStore(t.TempDir()) + if err := ts.Delete(RecordingType, "none"); err != nil { + t.Fatalf("delete missing transcript = %v", err) + } +}