From 0be122443f5c588739d93fcc131b37ccf71b592c Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 07:44:17 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20Inbox:=20transcribe=20first,=20?= =?UTF-8?q?then=20share=20audio-only=20items?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- .../added-inbox-transcribe-then-share.md | 1 + dashboard/test/inbox-item.test.js | 18 +- src/docs/inbox-transcription.md | 4 + src/docs/inbox-voice-sources.md | 29 ++- src/pkg/dashboard/api_inbox.go | 76 +++++- .../dashboard/api_inbox_share_role_test.go | 57 +++++ src/pkg/dashboard/inbox_share_menu_test.go | 51 +++- src/pkg/dashboard/static-src/js/inbox.js | 62 +++-- src/pkg/dashboard/static/index.html | 62 +++-- src/pkg/inbox/inbox.go | 3 + src/pkg/inbox/service.go | 9 +- src/pkg/inbox/shareintent.go | 231 ++++++++++++++++++ src/pkg/inbox/shareintent_test.go | 208 ++++++++++++++++ src/pkg/inbox/store.go | 74 ++++++ src/pkg/inbox/transcription.go | 1 + src/pkg/inbox/transcription_progress.go | 6 + 16 files changed, 832 insertions(+), 60 deletions(-) create mode 100644 changelog.d/added-inbox-transcribe-then-share.md create mode 100644 src/pkg/dashboard/api_inbox_share_role_test.go create mode 100644 src/pkg/inbox/shareintent.go create mode 100644 src/pkg/inbox/shareintent_test.go diff --git a/changelog.d/added-inbox-transcribe-then-share.md b/changelog.d/added-inbox-transcribe-then-share.md new file mode 100644 index 0000000000..704be80fff --- /dev/null +++ b/changelog.d/added-inbox-transcribe-then-share.md @@ -0,0 +1 @@ +- Sharing from the Inbox 🔗 Share → Hive menu is open to read-write users as well as owners (read users still only get Link), and RFC… / Knowledge on an audio-only item now transcribe it first and share when the transcript completes, with a "Transcribing, then → RFC" progress label; DIBS still sends straight away. diff --git a/dashboard/test/inbox-item.test.js b/dashboard/test/inbox-item.test.js index 857d0b5feb..8e35308826 100644 --- a/dashboard/test/inbox-item.test.js +++ b/dashboard/test/inbox-item.test.js @@ -30,6 +30,7 @@ function makeContext(role) { window: { _hiveRole: role }, INBOX_SOURCE_ICONS: { plaud: '🎙️' }, INBOX_DEST_LABELS: { spek_rfc: 'RFC', dibs: 'dibs' }, + INBOX_INTENT_LABELS: { spek_rfc: 'RFC', dismiss: 'Knowledge', spek: 'spek' }, INBOX_SUMMARY_COLLAPSE_CHARS: 280, _inboxSelected: new Set(), _inboxExpanded: new Set(), @@ -48,7 +49,7 @@ function makeContext(role) { Array, }; vm.createContext(ctx); - for (const fn of ['inboxSourceIcon', 'inboxItemKey', 'inboxViewerCanPlay', 'inboxApiPath', 'inboxFmtDuration', 'inboxStatePill', 'inboxSummaryHtml', 'inboxTranscriptHtml', 'inboxTxUnavailableText', 'inboxTxEtaText', 'inboxTxElapsedText', 'inboxTxProgressHtml', 'inboxTranscriptionHtml', 'inboxItemHtml']) { + for (const fn of ['inboxCanShare', 'inboxIntentLabel', 'inboxIntentThen', 'inboxSourceIcon', 'inboxItemKey', 'inboxViewerCanPlay', 'inboxApiPath', 'inboxFmtDuration', 'inboxStatePill', 'inboxSummaryHtml', 'inboxTranscriptHtml', 'inboxTxUnavailableText', 'inboxTxEtaText', 'inboxTxElapsedText', 'inboxTxProgressHtml', 'inboxTranscriptionHtml', 'inboxItemHtml']) { vm.runInContext(extractFunction(fn), ctx); } return ctx; @@ -140,3 +141,18 @@ test('File RFC route state: a failed hand-off shows its error inline, delegated assert.match(html, /muted-xs">handed to agent builder to draft with spek and publish to o\/r { + const ctx = makeContext('read-write'); + const running = Object.assign({}, pendingItem, { + transcription: { status: 'running', phase: 'transcribing', progress: 0.4, started_at: '2026-11-16T10:00:00Z', eta_seconds: 240 }, + share_intents: { spek_rfc: { status: 'waiting', actor: 'rw@example.com' } }, + }); + let html = vm.runInContext('inboxItemHtml(' + JSON.stringify(running) + ')', ctx); + assert.match(html, /Transcribing, then → RFC · 40%/); + const failed = Object.assign({}, pendingItem, { share_intents: { dismiss: { status: 'failed', error: 'transcription failed: provider down' } } }); + html = vm.runInContext('inboxItemHtml(' + JSON.stringify(failed) + ')', ctx); + assert.match(html, /data-status="error"[^>]*>→ Knowledge failedtranscription failed: provider down#section-inbox-section?item=%2F`); **Share…** opens the browser's share sheet and appears only where the browser has one. - The selection bar has the same kind of **Hive ▾** menu for bulk Knowledge. + The selection bar has a **Hive ▾** menu for bulk Knowledge, which waits for + transcripts the same way. Sharing never shares the media URL: the recipient signs in to this hive and needs owner or read-write access to play. Opening the link opens the Inbox, shows diff --git a/src/pkg/dashboard/api_inbox.go b/src/pkg/dashboard/api_inbox.go index 0c8c0a8b69..76fa85ecea 100644 --- a/src/pkg/dashboard/api_inbox.go +++ b/src/pkg/dashboard/api_inbox.go @@ -99,6 +99,9 @@ func (s *Server) handleInboxContent(w http.ResponseWriter, r *http.Request) { // requireInboxPlaybackRole admits owners (verified) and read-write sessions: // playing a recording is a read of private audio, not an operator mutation. +// +// Sharing an item (route, Knowledge-only) takes the same owner or read-write +// admission (requireInboxShareRole); settings stay owner-only. func requireInboxPlaybackRole(w http.ResponseWriter, r *http.Request) bool { role := r.Header.Get("X-Hive-Role") if isOwnerRole(role) && r.Header.Get(ownerRoleVerifiedHeader) != "true" { @@ -404,6 +407,14 @@ type inboxRouteRequest struct { ItemID string `json:"item_id"` Destination string `json:"destination"` Repo string `json:"repo,omitempty"` + // Params are short dialog choices kept with a transcribe-first share. + Params map[string]string `json:"params,omitempty"` +} + +// requireInboxShareRole admits owners (verified) and read-write sessions to +// share an inbox item; read is denied. Every share is audited with the user. +func requireInboxShareRole(w http.ResponseWriter, r *http.Request) bool { + return requireInboxPlaybackRole(w, r) } // InboxRouteResponse is POST /api/inbox/route. @@ -412,12 +423,15 @@ type InboxRouteResponse struct { ItemID string `json:"item_id"` Destination string `json:"destination"` State inbox.RouteState `json:"state"` + // WaitingTranscript is true when the item has audio but no text: the hive + // transcribes it first and shares when the transcript completes. + WaitingTranscript bool `json:"waiting_transcript,omitempty"` } -// handleInboxRoute (owner) queues one item for one destination; progress is +// handleInboxRoute (owner or read-write) queues one item for one destination; progress is // read back from GET /api/inbox. func (s *Server) handleInboxRoute(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { + if !requireInboxShareRole(w, r) { return } svc, ok := s.inboxService(w) @@ -449,7 +463,17 @@ func (s *Server) handleInboxRoute(w http.ResponseWriter, r *http.Request) { jsonError(w, msg, http.StatusNotFound) return } - st, err := svc.Route(ctx, it, inbox.Request{Destination: req.Destination, Repo: req.Repo}) + actor := requestUser(r) + var st inbox.RouteState + waiting := false + if req.Destination == inbox.DestDibs { + // DIBS sends straight away, audio-only items included. + st, err = svc.Route(ctx, it, inbox.Request{Destination: req.Destination, Repo: req.Repo}) + } else { + var out inbox.ShareOutcome + out, err = svc.ShareWhenReady(ctx, it, inbox.ShareIntent{Destination: req.Destination, Actor: actor, Repo: req.Repo, Params: req.Params}, s.inboxTranscribeOptions(actor)) + st, waiting = out.State, out.Waiting + } switch { case errors.Is(err, inbox.ErrRouteBusy): jsonError(w, "that route is already queued or running", http.StatusConflict) @@ -457,12 +481,25 @@ func (s *Server) handleInboxRoute(w http.ResponseWriter, r *http.Request) { case errors.Is(err, inbox.ErrUnknownDestination): jsonError(w, err.Error(), http.StatusBadRequest) return + case errors.Is(err, inbox.ErrTranscribeUnavailable): + jsonError(w, "this item has audio but no text yet, and "+err.Error(), http.StatusPreconditionFailed) + return case err != nil: jsonError(w, "route failed: "+err.Error(), http.StatusInternalServerError) return } - s.auditFromRequest(r, "inbox_route", auditDetail("source", req.Source, "item", req.ItemID, "destination", req.Destination, "repo", req.Repo), "") - jsonStatusResponse(w, http.StatusAccepted, InboxRouteResponse{Source: req.Source, ItemID: req.ItemID, Destination: req.Destination, State: st}) + s.auditFromRequest(r, "inbox_route", auditDetail("source", req.Source, "item", req.ItemID, "destination", req.Destination, "repo", req.Repo, "actor", actor, "transcribe_first", strconv.FormatBool(waiting)), "") + jsonStatusResponse(w, http.StatusAccepted, InboxRouteResponse{Source: req.Source, ItemID: req.ItemID, Destination: req.Destination, State: st, WaitingTranscript: waiting}) +} + +// inboxTranscribeOptions builds the audited options for a transcription the +// request caused. +func (s *Server) inboxTranscribeOptions(actor string) inbox.TranscribeOptions { + return inbox.TranscribeOptions{Actor: actor, Audit: func(a inbox.TranscribeAudit) { + if s.audit != nil { + s.audit.Log(a.Actor, "inbox_transcribe", auditDetail(a.Fields()...), "") + } + }} } func inboxRepoOK(repo string) bool { @@ -481,11 +518,15 @@ type inboxDismissRequest struct { // InboxDismissResponse is POST /api/inbox/dismiss. type InboxDismissResponse struct { Dismissed int `json:"dismissed"` + // WaitingTranscript counts items that will be kept once transcribed. + WaitingTranscript int `json:"waiting_transcript,omitempty"` } -// handleInboxDismiss (owner) marks items "knowledge only" (bulk). +// handleInboxDismiss (owner or read-write) marks items "knowledge only" +// (bulk). Audio-only items are transcribed first when transcription is +// available (the dismissal runs when the transcript completes). func (s *Server) handleInboxDismiss(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { + if !requireInboxShareRole(w, r) { return } svc, ok := s.inboxService(w) @@ -497,19 +538,34 @@ func (s *Server) handleInboxDismiss(w http.ResponseWriter, r *http.Request) { jsonError(w, "items[] is required", http.StatusBadRequest) return } - n := 0 + n, waiting := 0, 0 + actor := requestUser(r) for _, it := range req.Items { if it.Source == "" || it.ItemID == "" { continue } + if !req.Undo { + if item, found, _ := svc.Find(r.Context(), it.Source, it.ItemID); found { + if out, err := svc.ShareWhenReady(r.Context(), item, inbox.ShareIntent{Destination: inbox.DestDismiss, Actor: actor}, s.inboxTranscribeOptions(actor)); err == nil { + if out.Waiting { + waiting++ + } + n++ + continue + } else if !errors.Is(err, inbox.ErrTranscribeUnavailable) { + jsonError(w, "dismiss failed: "+err.Error(), http.StatusInternalServerError) + return + } + } + } if err := svc.Dismiss(it.Source, it.ItemID, !req.Undo); err != nil { jsonError(w, "dismiss failed: "+err.Error(), http.StatusInternalServerError) return } n++ } - s.auditFromRequest(r, "inbox_dismiss", auditDetail("count", strconv.Itoa(n)), "") - jsonResponse(w, InboxDismissResponse{Dismissed: n}) + s.auditFromRequest(r, "inbox_dismiss", auditDetail("count", strconv.Itoa(n), "actor", actor, "waiting_transcript", strconv.Itoa(waiting)), "") + jsonResponse(w, InboxDismissResponse{Dismissed: n, WaitingTranscript: waiting}) } func (s *Server) handleInboxSettingsGet(w http.ResponseWriter, r *http.Request) { diff --git a/src/pkg/dashboard/api_inbox_share_role_test.go b/src/pkg/dashboard/api_inbox_share_role_test.go new file mode 100644 index 0000000000..9dec22584f --- /dev/null +++ b/src/pkg/dashboard/api_inbox_share_role_test.go @@ -0,0 +1,57 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +func doPostRole(s *Server, path, role string, body any) *httptest.ResponseRecorder { + var b bytes.Buffer + _ = json.NewEncoder(&b).Encode(body) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, path, &b) + req.Header.Set("Content-Type", "application/json") + if role != "" { + req.Header.Set("X-Hive-Role", role) + } + if role == "owner" { + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + s.mux.ServeHTTP(rec, req) + return rec +} + +// Sharing an item (route, Knowledge-only) is open to owner and read-write; +// read and anonymous callers get 403. Settings stay owner-only. +func TestInboxShareRoleMatrix(t *testing.T) { + s, deps := apiServer(t) + spek := &inboxTestDest{name: "spek_rfc"} + deps.Config.Inbox = config.InboxConfig{Spek: config.InboxSpek{Repo: "myorg/rfcs"}} + deps.Inbox = newInboxTestService(t, deps.Config.Inbox, spek) + route := map[string]string{"source": "plaud", "item_id": "rec-1", "destination": "spek_rfc"} + for _, role := range []string{"", "read-only", "read"} { + if rec := doPostRole(s, "/api/inbox/route", role, route); rec.Code != http.StatusForbidden { + t.Fatalf("role %q route = %d, want 403", role, rec.Code) + } + if rec := doPostRole(s, "/api/inbox/dismiss", role, map[string]any{"items": []map[string]string{{"source": "plaud", "item_id": "rec-1"}}}); rec.Code != http.StatusForbidden { + t.Fatalf("role %q dismiss = %d, want 403", role, rec.Code) + } + } + if rec := doPostRole(s, "/api/inbox/route", "read-write", route); rec.Code != http.StatusAccepted { + t.Fatalf("read-write route = %d: %s", rec.Code, rec.Body.String()) + } + if rec := doPostRole(s, "/api/inbox/dismiss", "read-write", map[string]any{"items": []map[string]string{{"source": "plaud", "item_id": "rec-1"}}}); rec.Code != http.StatusOK { + t.Fatalf("read-write dismiss = %d: %s", rec.Code, rec.Body.String()) + } + if rec := doPostRole(s, "/api/inbox/route", "owner", route); rec.Code != http.StatusAccepted { + t.Fatalf("owner route = %d: %s", rec.Code, rec.Body.String()) + } + if rec := doPostRole(s, "/api/inbox/settings", "read-write", map[string]any{"spek_repo": "o/r"}); rec.Code != http.StatusForbidden { + t.Fatalf("read-write settings = %d, want 403 (settings stay owner-only)", rec.Code) + } +} diff --git a/src/pkg/dashboard/inbox_share_menu_test.go b/src/pkg/dashboard/inbox_share_menu_test.go index 80db65a460..01dc803a92 100644 --- a/src/pkg/dashboard/inbox_share_menu_test.go +++ b/src/pkg/dashboard/inbox_share_menu_test.go @@ -36,10 +36,20 @@ func TestInboxShareMenuBehaviour(t *testing.T) { "function inboxShareCopy(s, i) { calls.push(['copy', s, i]); } async function inboxShareNative(s, i) { calls.push(['native', s, i]); }", "function inboxDismissSelected() { calls.push(['bulk-dismiss']); } const _inboxSelected = new Set(['plaud/r1']);", "function inboxFind(s, i) { return ((_inboxCache || {}).items || []).find(it => it.source === s && it.id === i); }", - jsConstLine(t, html, "INBOX_NO_TEXT_REASON"), + jsConstLine(t, html, "INBOX_INTENT_LABELS"), + "function inboxOpenSettings() { calls.push(['settings']); }", jsConstBlock(t, html, "inboxShareHiveActions"), jsConstBlock(t, html, "inboxShareLinkActions"), jsFunc(t, html, "inboxDibsReady"), + jsFunc(t, html, "inboxCanShare"), + jsFunc(t, html, "inboxTxBlocked"), + jsFunc(t, html, "inboxTxUnavailableText"), + jsFunc(t, html, "inboxShareGate"), + jsFunc(t, html, "inboxIntentLabel"), + jsFunc(t, html, "inboxIntentThen"), + jsFunc(t, html, "inboxTxEtaText"), + jsFunc(t, html, "inboxTxElapsedText"), + jsFunc(t, html, "inboxTxProgressHtml"), jsFunc(t, html, "inboxShareMenuGroups"), jsFunc(t, html, "inboxShareMenuHtml"), jsFunc(t, html, "inboxShareMenuRun"), @@ -60,14 +70,45 @@ const ids = (gs) => gs.map(g => g.id + ':' + g.items.map(i => i.id).join(',')); assert.strictEqual((markup.match(/role="menuitem"/g) || []).length, 5); navigator = {}; assert.deepStrictEqual(ids(inboxShareMenuGroups(item())), ['hive:rfc,knowledge,dibs', 'link:copy']); - // Role gating: read and read-write only get the Link group. - for (const role of ['read', 'read-write']) { window._hiveRole = role; assert.deepStrictEqual(ids(inboxShareMenuGroups(item())), ['link:copy']); } + // Role gating: read gets only the Link group; read-write and owner get Hive too. + window._hiveRole = 'read'; assert.deepStrictEqual(ids(inboxShareMenuGroups(item())), ['link:copy']); assert.deepStrictEqual(inboxBulkMenuGroups(), []); + window._hiveRole = 'read-write'; + assert.deepStrictEqual(ids(inboxShareMenuGroups(item())), ['hive:rfc,knowledge,dibs', 'link:copy']); + assert.deepStrictEqual(ids(inboxBulkMenuGroups()), ['hive:knowledge']); window._hiveRole = 'owner'; // Disabled reasons. _inboxCache = { items: [], repos: [], settings: {} }; - let hive = inboxShareMenuGroups(item({ pending: true }))[0].items; - assert(hive.find(i => i.id === 'rfc').disabled && hive.find(i => i.id === 'rfc').hint.includes('Transcribe')); + // Audio-only item with transcription unavailable: RFC and Knowledge are + // disabled with the reason and a link to the Transcription settings; DIBS is not. + _inboxCache = { items: [], repos: ['o/r'], settings: { dibs_url: 'u', dibs_token_set: true } }; + let hive = inboxShareMenuGroups(item({ pending: true, transcribe_unavailable: 'disabled' }))[0].items; + for (const id of ['rfc', 'knowledge']) { const e = hive.find(i => i.id === id); assert(e.disabled && e.hint.includes('Transcription is off'), id); } + assert(!hive.find(i => i.id === 'dibs').disabled, 'DIBS always sends straight away'); + assert(hive.some(i => i.id === 'tx-settings')); + window._hiveRole = 'read-write'; + assert(!inboxShareMenuGroups(item({ pending: true, transcribe_unavailable: 'budget' }))[0].items.some(i => i.id === 'tx-settings'), 'settings link is owner-only'); + window._hiveRole = 'owner'; + _inboxCache.items = [item()]; + await inboxShareMenuRun('hive', 'tx-settings', 'plaud', 'r1'); + assert.deepStrictEqual(calls.splice(0), [['settings']]); + // Audio-only item that can be transcribed: enabled (transcribe first, then share). + hive = inboxShareMenuGroups(item({ pending: true, transcribable: true }))[0].items; + assert(!hive.find(i => i.id === 'rfc').disabled && !hive.find(i => i.id === 'knowledge').disabled); + assert(!hive.some(i => i.id === 'tx-settings')); + // A waiting intent shows as disabled: Transcribing, then → RFC. + hive = inboxShareMenuGroups(item({ pending: true, share_intents: { spek_rfc: { status: 'waiting' } } }))[0].items; + assert.strictEqual(hive.find(i => i.id === 'rfc').hint, 'Transcribing, then → RFC'); + // A failed intent offers Retry. + hive = inboxShareMenuGroups(item({ share_intents: { dismiss: { status: 'failed', error: 'x' } } }))[0].items; + assert.strictEqual(hive.find(i => i.id === 'knowledge').label, 'Retry Knowledge'); + // Progress label. + assert.strictEqual(inboxIntentThen(item({ share_intents: { spek_rfc: { status: 'waiting' } } })), 'RFC'); + const bar = inboxTxProgressHtml({ status: 'running', started_at: '2026-11-16T10:00:00Z', phase: 'transcribing', progress: 0.4, eta_seconds: 240 }, Date.parse('2026-11-16T10:01:00Z'), 'RFC'); + assert(bar.includes('Transcribing, then → RFC · 40%'), bar); + assert(!inboxTxProgressHtml({ status: 'running', started_at: '2026-11-16T10:00:00Z', phase: 'transcribing', progress: 0.4 }, 0).includes('then')); + assert(inboxTxProgressHtml({ status: 'queued' }, 0, 'Knowledge').includes('Transcribing, then → Knowledge')); + _inboxCache = { items: [], repos: [], settings: {} }; hive = inboxShareMenuGroups(item())[0].items; assert(hive.find(i => i.id === 'rfc').hint.includes('RFC repository')); const dibs = hive.find(i => i.id === 'dibs'); diff --git a/src/pkg/dashboard/static-src/js/inbox.js b/src/pkg/dashboard/static-src/js/inbox.js index 2540e5d750..ac362cdad9 100644 --- a/src/pkg/dashboard/static-src/js/inbox.js +++ b/src/pkg/dashboard/static-src/js/inbox.js @@ -160,12 +160,13 @@ // Progress bar for a queued or running transcription, in the connector // sync progress styling (kc-progress). Queued shows its place in line; // running shows phase, percent, time left (aria-live) and elapsed time. - function inboxTxProgressHtml(st, nowMs) { + function inboxTxProgressHtml(st, nowMs, then) { if (!st || (st.status !== 'queued' && st.status !== 'running')) return ''; const phases = { downloading: 'Downloading audio', decoding: 'Preparing audio', transcribing: 'Transcribing', finalizing: 'Finishing' }; if (st.status === 'queued' || !st.started_at) { const ahead = Number(st.queue_position) || 0; - const wait = ahead > 0 ? 'Waiting: ' + ahead + (ahead === 1 ? ' transcription' : ' transcriptions') + ' ahead (one runs at a time)' : 'Starting…'; + const thenText = then ? ', then → ' + then : ''; + const wait = (then ? 'Transcribing' + thenText + ': ' : '') + (ahead > 0 ? 'Waiting: ' + ahead + (ahead === 1 ? ' transcription' : ' transcriptions') + ' ahead (one runs at a time)' : 'Starting…'); return '
' + '' + '
' + escapeHtml(wait) + '
'; @@ -174,7 +175,7 @@ const phase = phases[st.phase] || 'Transcribing'; const eta = st.phase === 'finalizing' ? 'almost done' : (inboxTxEtaText(st.eta_seconds) || (pct > 0 ? 'finishing up' : 'estimating time left')); const elapsed = inboxTxElapsedText(st.started_at, nowMs); - const label = phase + ' · ' + pct + '%'; + const label = phase + (then ? ', then → ' + then : '') + ' · ' + pct + '%'; return '
' + '' + '
' + escapeHtml(label) + ' · ' + escapeHtml(eta) + '' + @@ -207,7 +208,7 @@ html += '' + (busy ? ' ' : '') + escapeHtml(label) + ''; if (st.reason && (st.status === 'failed' || st.status === 'skipped')) html += ' ' + escapeHtml(st.reason) + ''; - if (busy) html += inboxTxProgressHtml(st); + if (busy) html += inboxTxProgressHtml(st, undefined, inboxIntentThen(it)); } const why = inboxTxUnavailableText(it.transcribe_unavailable); if (why) { @@ -306,6 +307,10 @@ let pills = ''; for (const d of Object.keys(routes)) pills += inboxStatePill(d, routes[d]) + ' '; if (it.dismissed) pills += 'knowledge only'; + for (const d of Object.keys(it.share_intents || {})) { + const si = it.share_intents[d]; + if (si && si.status === 'failed') pills += '→ ' + escapeHtml(inboxIntentLabel(d)) + ' failed ' + escapeHtml(si.error || '') + ' '; + } const owner = viewerIsOwner(); const src = escapeHtml(it.source), id = escapeHtml(it.id); let actions = ''; @@ -313,7 +318,7 @@ actions += ''; actions += ''; return '
' + - (owner ? '' : '') + + (inboxCanShare(window._hiveRole) ? '' : '') + '
' + inboxSourceIcon(it.source) + '
' + '
' + escapeHtml(it.title || it.id) + '
' + '
' + meta + '
' + @@ -422,7 +427,7 @@ catch (e) { if (!e || e.name !== 'AbortError') await inboxShareCopy(src, id); } } // The Share menu has two groups. Hive actions file or keep the item and - // are owner-only (the route and dismiss APIs are); Link actions only share + // need owner or read-write (as do the route and dismiss APIs); Link actions only share // a link. Each entry is {id, label, enabled(item, role), run(item)} where // label is a string or fn(item), and enabled returns true, false (hide) or // a string (show disabled, the string is the reason). Other features add @@ -430,15 +435,37 @@ // session action, instead of a new row button. An entry may also carry // bulk(items) to appear in the multi-select Hive menu. const inboxShareHiveActions = [ - { id: 'rfc', dest: 'spek_rfc', label: 'RFC…', enabled: (it, role) => role !== 'owner' ? false : it.pending ? INBOX_NO_TEXT_REASON : !(((_inboxCache || {}).repos || []).length) ? 'No RFC repository configured: set one in Settings → Inbox' : true, run: it => inboxOpenRoute(it.source, it.id, 'spek_rfc') }, - { id: 'knowledge', label: it => it.dismissed ? 'Back to inbox' : 'Knowledge', enabled: (it, role) => role === 'owner', run: it => it.dismissed ? inboxUndismiss(it.source, it.id) : inboxDismiss(it.source, it.id), bulkLabel: 'Knowledge', bulk: () => inboxDismissSelected() }, - { id: 'dibs', dest: 'dibs', label: 'DIBS', enabled: (it, role) => role !== 'owner' ? false : inboxDibsReady() ? true : 'Not configured: set the dibs URL in Settings → Inbox → dibs URL', run: it => inboxOpenRoute(it.source, it.id, 'dibs') }, + { id: 'rfc', dest: 'spek_rfc', label: 'RFC…', enabled: (it, role) => !inboxCanShare(role) ? false : inboxShareGate(it, 'spek_rfc') || (!(((_inboxCache || {}).repos || []).length) ? 'No RFC repository configured: set one in Settings → Inbox' : true), run: it => inboxOpenRoute(it.source, it.id, 'spek_rfc') }, + { id: 'knowledge', dest: 'dismiss', label: it => it.dismissed ? 'Back to inbox' : 'Knowledge', enabled: (it, role) => !inboxCanShare(role) ? false : (it.dismissed ? true : inboxShareGate(it, 'dismiss') || true), run: it => it.dismissed ? inboxUndismiss(it.source, it.id) : inboxDismiss(it.source, it.id), bulkLabel: 'Knowledge', bulk: () => inboxDismissSelected() }, + { id: 'dibs', dest: 'dibs', label: 'DIBS', enabled: (it, role) => !inboxCanShare(role) ? false : inboxDibsReady() ? true : 'Not configured: set the dibs URL in Settings → Inbox → dibs URL', run: it => inboxOpenRoute(it.source, it.id, 'dibs') }, + { id: 'tx-settings', label: '⚙ Transcription settings…', enabled: (it, role) => role === 'owner' && inboxTxBlocked(it) ? true : false, run: () => inboxOpenSettings() }, ]; const inboxShareLinkActions = [ { id: 'copy', label: 'Copy link', enabled: () => true, run: it => inboxShareCopy(it.source, it.id) }, { id: 'native', label: 'Share…', enabled: () => typeof navigator !== 'undefined' && !!navigator.share, run: it => inboxShareNative(it.source, it.id) }, ]; - const INBOX_NO_TEXT_REASON = 'No transcript yet: use 🎧 Transcribe first'; + // Owners and read-write viewers may share (route, Knowledge); read may not. + function inboxCanShare(role) { return role === 'owner' || role === 'read-write'; } + // An audio-only item (pending, audio, transcription cannot run) cannot be + // shared to RFC, spek or Knowledge: they need a transcript first. + function inboxTxBlocked(it) { return !!(it && it.pending && it.transcribe_unavailable); } + // inboxShareGate returns the disabled reason for a Hive destination that + // needs a transcript, or '' when it may proceed (audio-only items are + // transcribed first, then shared). + function inboxShareGate(it, dest) { + const intent = (it.share_intents || {})[dest]; + if (intent && intent.status === 'waiting') return 'Transcribing, then → ' + inboxIntentLabel(dest); + if (inboxTxBlocked(it)) return inboxTxUnavailableText(it.transcribe_unavailable) + ' (a transcript is needed first)'; + return ''; + } + const INBOX_INTENT_LABELS = { spek_rfc: 'RFC', dismiss: 'Knowledge', spek: 'spek' }; + function inboxIntentLabel(dest) { return INBOX_INTENT_LABELS[dest] || dest; } + // The first waiting share intent of an item, for the progress label. + function inboxIntentThen(it) { + const m = (it && it.share_intents) || {}; + const d = Object.keys(m).find(k => m[k] && m[k].status === 'waiting'); + return d ? inboxIntentLabel(d) : ''; + } function inboxDibsReady() { const st = (_inboxCache || {}).settings || {}; return !!st.dibs_url && !!st.dibs_token_set; } // inboxShareMenuGroups resolves the registries for one item and the // viewer's role into labelled groups; empty groups are dropped. @@ -449,7 +476,8 @@ const en = a.enabled(it, role); if (en === false) return null; let label = typeof a.label === 'function' ? a.label(it) : a.label; - if (a.dest && routes[a.dest] && routes[a.dest].status === 'failed') label = 'Retry ' + label; + const intents = (it && it.share_intents) || {}; + if (a.dest && ((routes[a.dest] && routes[a.dest].status === 'failed') || (intents[a.dest] && intents[a.dest].status === 'failed'))) label = 'Retry ' + label; return { id: a.id, label, disabled: typeof en === 'string', hint: typeof en === 'string' ? en : '' }; }).filter(Boolean); return [{ id: 'hive', label: 'Hive', items: resolve(inboxShareHiveActions) }, { id: 'link', label: 'Link', items: resolve(inboxShareLinkActions) }].filter(g => g.items.length); @@ -467,9 +495,9 @@ const entry = (group === 'hive' ? inboxShareHiveActions : inboxShareLinkActions).find(a => a.id === act); if (it && entry) await entry.run(it); } - // Bulk Hive menu: entries with bulk(), owner only. + // Bulk Hive menu: entries with bulk(), owner or read-write. function inboxBulkMenuGroups() { - if (window._hiveRole !== 'owner') return []; + if (!inboxCanShare(window._hiveRole)) return []; const items = inboxShareHiveActions.filter(a => typeof a.bulk === 'function').map(a => ({ id: a.id, label: a.bulkLabel || (typeof a.label === 'function' ? a.id : a.label), disabled: false, hint: '' })); return items.length ? [{ id: 'hive', label: 'Hive', items }] : []; } @@ -599,7 +627,7 @@ if (!settings.spek_ready && owner) html += '

RFC filing needs at least one enabled, unpaused agent to draft the spec with spektacular (inbox.spek.agent overrides the default; inbox.spek.binary names the CLI the agent runs).

'; if (_inboxFocusKey && items.some(it => it.processed && inboxItemKey(it) === _inboxFocusKey)) _inboxShowProcessed = true; const shown = items.filter(it => _inboxShowProcessed || !it.processed); - if (owner && shown.length) { + if (inboxCanShare(window._hiveRole) && shown.length) { const sel = _inboxSelected.size; html += '
' + (sel ? '' : '') + '
'; @@ -635,7 +663,7 @@ return data; } async function inboxDismiss(src, id) { - try { await inboxPostDismiss([{ source: src, item_id: id }], false); showToast('Kept as a Knowledge fact only', 'success'); await fetchInbox(); } + try { const d = await inboxPostDismiss([{ source: src, item_id: id }], false); showToast(d && d.waiting_transcript ? 'Transcribing, then → Knowledge' : 'Kept as a Knowledge fact only', 'success'); await fetchInbox(); } catch (e) { showToast('Dismiss failed: ' + e.message, 'error'); } } async function inboxUndismiss(src, id) { @@ -646,7 +674,7 @@ const items = Array.from(_inboxSelected).map(k => { const i = k.indexOf('/'); return { source: k.slice(0, i), item_id: k.slice(i + 1) }; }); if (!items.length) return; if (!(await hiveConfirm('Mark ' + items.length + ' item' + (items.length === 1 ? '' : 's') + ' as Knowledge only? They stay searchable as facts; no RFC or dibs idea is created.', 'Knowledge only'))) return; - try { await inboxPostDismiss(items, false); _inboxSelected.clear(); await fetchInbox(); } + try { const d = await inboxPostDismiss(items, false); _inboxSelected.clear(); if (d && d.waiting_transcript) showToast(d.waiting_transcript + ' item' + (d.waiting_transcript === 1 ? '' : 's') + ' will be kept once transcribed', 'success'); await fetchInbox(); } catch (e) { showToast('Dismiss failed: ' + e.message, 'error'); } } @@ -680,7 +708,7 @@ const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); kbCloseModal(); - showToast((INBOX_DEST_LABELS[dest] || dest) + ' queued — the pill updates when it finishes.', 'success'); + showToast(data.waiting_transcript ? 'Transcribing, then → ' + (INBOX_DEST_LABELS[dest] || dest) + '. It is sent when the transcript is ready.' : (INBOX_DEST_LABELS[dest] || dest) + ' queued — the pill updates when it finishes.', 'success'); await fetchInbox(); } catch (e) { if (errEl) errEl.textContent = e.message; else showToast('Route failed: ' + e.message, 'error'); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index b4d389a0cf..425dbaeb9e 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -47499,12 +47499,13 @@ // Progress bar for a queued or running transcription, in the connector // sync progress styling (kc-progress). Queued shows its place in line; // running shows phase, percent, time left (aria-live) and elapsed time. - function inboxTxProgressHtml(st, nowMs) { + function inboxTxProgressHtml(st, nowMs, then) { if (!st || (st.status !== 'queued' && st.status !== 'running')) return ''; const phases = { downloading: 'Downloading audio', decoding: 'Preparing audio', transcribing: 'Transcribing', finalizing: 'Finishing' }; if (st.status === 'queued' || !st.started_at) { const ahead = Number(st.queue_position) || 0; - const wait = ahead > 0 ? 'Waiting: ' + ahead + (ahead === 1 ? ' transcription' : ' transcriptions') + ' ahead (one runs at a time)' : 'Starting…'; + const thenText = then ? ', then → ' + then : ''; + const wait = (then ? 'Transcribing' + thenText + ': ' : '') + (ahead > 0 ? 'Waiting: ' + ahead + (ahead === 1 ? ' transcription' : ' transcriptions') + ' ahead (one runs at a time)' : 'Starting…'); return '
' + '' + '
' + escapeHtml(wait) + '
'; @@ -47513,7 +47514,7 @@ const phase = phases[st.phase] || 'Transcribing'; const eta = st.phase === 'finalizing' ? 'almost done' : (inboxTxEtaText(st.eta_seconds) || (pct > 0 ? 'finishing up' : 'estimating time left')); const elapsed = inboxTxElapsedText(st.started_at, nowMs); - const label = phase + ' · ' + pct + '%'; + const label = phase + (then ? ', then → ' + then : '') + ' · ' + pct + '%'; return '
' + '' + '
' + escapeHtml(label) + ' · ' + escapeHtml(eta) + '' + @@ -47546,7 +47547,7 @@ html += '' + (busy ? ' ' : '') + escapeHtml(label) + ''; if (st.reason && (st.status === 'failed' || st.status === 'skipped')) html += ' ' + escapeHtml(st.reason) + ''; - if (busy) html += inboxTxProgressHtml(st); + if (busy) html += inboxTxProgressHtml(st, undefined, inboxIntentThen(it)); } const why = inboxTxUnavailableText(it.transcribe_unavailable); if (why) { @@ -47645,6 +47646,10 @@ let pills = ''; for (const d of Object.keys(routes)) pills += inboxStatePill(d, routes[d]) + ' '; if (it.dismissed) pills += 'knowledge only'; + for (const d of Object.keys(it.share_intents || {})) { + const si = it.share_intents[d]; + if (si && si.status === 'failed') pills += '→ ' + escapeHtml(inboxIntentLabel(d)) + ' failed ' + escapeHtml(si.error || '') + ' '; + } const owner = viewerIsOwner(); const src = escapeHtml(it.source), id = escapeHtml(it.id); let actions = ''; @@ -47652,7 +47657,7 @@ actions += ''; actions += ''; return '
' + - (owner ? '' : '') + + (inboxCanShare(window._hiveRole) ? '' : '') + '
' + inboxSourceIcon(it.source) + '
' + '
' + escapeHtml(it.title || it.id) + '
' + '
' + meta + '
' + @@ -47761,7 +47766,7 @@ catch (e) { if (!e || e.name !== 'AbortError') await inboxShareCopy(src, id); } } // The Share menu has two groups. Hive actions file or keep the item and - // are owner-only (the route and dismiss APIs are); Link actions only share + // need owner or read-write (as do the route and dismiss APIs); Link actions only share // a link. Each entry is {id, label, enabled(item, role), run(item)} where // label is a string or fn(item), and enabled returns true, false (hide) or // a string (show disabled, the string is the reason). Other features add @@ -47769,15 +47774,37 @@ // session action, instead of a new row button. An entry may also carry // bulk(items) to appear in the multi-select Hive menu. const inboxShareHiveActions = [ - { id: 'rfc', dest: 'spek_rfc', label: 'RFC…', enabled: (it, role) => role !== 'owner' ? false : it.pending ? INBOX_NO_TEXT_REASON : !(((_inboxCache || {}).repos || []).length) ? 'No RFC repository configured: set one in Settings → Inbox' : true, run: it => inboxOpenRoute(it.source, it.id, 'spek_rfc') }, - { id: 'knowledge', label: it => it.dismissed ? 'Back to inbox' : 'Knowledge', enabled: (it, role) => role === 'owner', run: it => it.dismissed ? inboxUndismiss(it.source, it.id) : inboxDismiss(it.source, it.id), bulkLabel: 'Knowledge', bulk: () => inboxDismissSelected() }, - { id: 'dibs', dest: 'dibs', label: 'DIBS', enabled: (it, role) => role !== 'owner' ? false : inboxDibsReady() ? true : 'Not configured: set the dibs URL in Settings → Inbox → dibs URL', run: it => inboxOpenRoute(it.source, it.id, 'dibs') }, + { id: 'rfc', dest: 'spek_rfc', label: 'RFC…', enabled: (it, role) => !inboxCanShare(role) ? false : inboxShareGate(it, 'spek_rfc') || (!(((_inboxCache || {}).repos || []).length) ? 'No RFC repository configured: set one in Settings → Inbox' : true), run: it => inboxOpenRoute(it.source, it.id, 'spek_rfc') }, + { id: 'knowledge', dest: 'dismiss', label: it => it.dismissed ? 'Back to inbox' : 'Knowledge', enabled: (it, role) => !inboxCanShare(role) ? false : (it.dismissed ? true : inboxShareGate(it, 'dismiss') || true), run: it => it.dismissed ? inboxUndismiss(it.source, it.id) : inboxDismiss(it.source, it.id), bulkLabel: 'Knowledge', bulk: () => inboxDismissSelected() }, + { id: 'dibs', dest: 'dibs', label: 'DIBS', enabled: (it, role) => !inboxCanShare(role) ? false : inboxDibsReady() ? true : 'Not configured: set the dibs URL in Settings → Inbox → dibs URL', run: it => inboxOpenRoute(it.source, it.id, 'dibs') }, + { id: 'tx-settings', label: '⚙ Transcription settings…', enabled: (it, role) => role === 'owner' && inboxTxBlocked(it) ? true : false, run: () => inboxOpenSettings() }, ]; const inboxShareLinkActions = [ { id: 'copy', label: 'Copy link', enabled: () => true, run: it => inboxShareCopy(it.source, it.id) }, { id: 'native', label: 'Share…', enabled: () => typeof navigator !== 'undefined' && !!navigator.share, run: it => inboxShareNative(it.source, it.id) }, ]; - const INBOX_NO_TEXT_REASON = 'No transcript yet: use 🎧 Transcribe first'; + // Owners and read-write viewers may share (route, Knowledge); read may not. + function inboxCanShare(role) { return role === 'owner' || role === 'read-write'; } + // An audio-only item (pending, audio, transcription cannot run) cannot be + // shared to RFC, spek or Knowledge: they need a transcript first. + function inboxTxBlocked(it) { return !!(it && it.pending && it.transcribe_unavailable); } + // inboxShareGate returns the disabled reason for a Hive destination that + // needs a transcript, or '' when it may proceed (audio-only items are + // transcribed first, then shared). + function inboxShareGate(it, dest) { + const intent = (it.share_intents || {})[dest]; + if (intent && intent.status === 'waiting') return 'Transcribing, then → ' + inboxIntentLabel(dest); + if (inboxTxBlocked(it)) return inboxTxUnavailableText(it.transcribe_unavailable) + ' (a transcript is needed first)'; + return ''; + } + const INBOX_INTENT_LABELS = { spek_rfc: 'RFC', dismiss: 'Knowledge', spek: 'spek' }; + function inboxIntentLabel(dest) { return INBOX_INTENT_LABELS[dest] || dest; } + // The first waiting share intent of an item, for the progress label. + function inboxIntentThen(it) { + const m = (it && it.share_intents) || {}; + const d = Object.keys(m).find(k => m[k] && m[k].status === 'waiting'); + return d ? inboxIntentLabel(d) : ''; + } function inboxDibsReady() { const st = (_inboxCache || {}).settings || {}; return !!st.dibs_url && !!st.dibs_token_set; } // inboxShareMenuGroups resolves the registries for one item and the // viewer's role into labelled groups; empty groups are dropped. @@ -47788,7 +47815,8 @@ const en = a.enabled(it, role); if (en === false) return null; let label = typeof a.label === 'function' ? a.label(it) : a.label; - if (a.dest && routes[a.dest] && routes[a.dest].status === 'failed') label = 'Retry ' + label; + const intents = (it && it.share_intents) || {}; + if (a.dest && ((routes[a.dest] && routes[a.dest].status === 'failed') || (intents[a.dest] && intents[a.dest].status === 'failed'))) label = 'Retry ' + label; return { id: a.id, label, disabled: typeof en === 'string', hint: typeof en === 'string' ? en : '' }; }).filter(Boolean); return [{ id: 'hive', label: 'Hive', items: resolve(inboxShareHiveActions) }, { id: 'link', label: 'Link', items: resolve(inboxShareLinkActions) }].filter(g => g.items.length); @@ -47806,9 +47834,9 @@ const entry = (group === 'hive' ? inboxShareHiveActions : inboxShareLinkActions).find(a => a.id === act); if (it && entry) await entry.run(it); } - // Bulk Hive menu: entries with bulk(), owner only. + // Bulk Hive menu: entries with bulk(), owner or read-write. function inboxBulkMenuGroups() { - if (window._hiveRole !== 'owner') return []; + if (!inboxCanShare(window._hiveRole)) return []; const items = inboxShareHiveActions.filter(a => typeof a.bulk === 'function').map(a => ({ id: a.id, label: a.bulkLabel || (typeof a.label === 'function' ? a.id : a.label), disabled: false, hint: '' })); return items.length ? [{ id: 'hive', label: 'Hive', items }] : []; } @@ -47938,7 +47966,7 @@ if (!settings.spek_ready && owner) html += '

RFC filing needs at least one enabled, unpaused agent to draft the spec with spektacular (inbox.spek.agent overrides the default; inbox.spek.binary names the CLI the agent runs).

'; if (_inboxFocusKey && items.some(it => it.processed && inboxItemKey(it) === _inboxFocusKey)) _inboxShowProcessed = true; const shown = items.filter(it => _inboxShowProcessed || !it.processed); - if (owner && shown.length) { + if (inboxCanShare(window._hiveRole) && shown.length) { const sel = _inboxSelected.size; html += '
' + (sel ? '' : '') + '
'; @@ -47974,7 +48002,7 @@ return data; } async function inboxDismiss(src, id) { - try { await inboxPostDismiss([{ source: src, item_id: id }], false); showToast('Kept as a Knowledge fact only', 'success'); await fetchInbox(); } + try { const d = await inboxPostDismiss([{ source: src, item_id: id }], false); showToast(d && d.waiting_transcript ? 'Transcribing, then → Knowledge' : 'Kept as a Knowledge fact only', 'success'); await fetchInbox(); } catch (e) { showToast('Dismiss failed: ' + e.message, 'error'); } } async function inboxUndismiss(src, id) { @@ -47985,7 +48013,7 @@ const items = Array.from(_inboxSelected).map(k => { const i = k.indexOf('/'); return { source: k.slice(0, i), item_id: k.slice(i + 1) }; }); if (!items.length) return; if (!(await hiveConfirm('Mark ' + items.length + ' item' + (items.length === 1 ? '' : 's') + ' as Knowledge only? They stay searchable as facts; no RFC or dibs idea is created.', 'Knowledge only'))) return; - try { await inboxPostDismiss(items, false); _inboxSelected.clear(); await fetchInbox(); } + try { const d = await inboxPostDismiss(items, false); _inboxSelected.clear(); if (d && d.waiting_transcript) showToast(d.waiting_transcript + ' item' + (d.waiting_transcript === 1 ? '' : 's') + ' will be kept once transcribed', 'success'); await fetchInbox(); } catch (e) { showToast('Dismiss failed: ' + e.message, 'error'); } } @@ -48019,7 +48047,7 @@ const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); kbCloseModal(); - showToast((INBOX_DEST_LABELS[dest] || dest) + ' queued — the pill updates when it finishes.', 'success'); + showToast(data.waiting_transcript ? 'Transcribing, then → ' + (INBOX_DEST_LABELS[dest] || dest) + '. It is sent when the transcript is ready.' : (INBOX_DEST_LABELS[dest] || dest) + ' queued — the pill updates when it finishes.', 'success'); await fetchInbox(); } catch (e) { if (errEl) errEl.textContent = e.message; else showToast('Route failed: ' + e.message, 'error'); diff --git a/src/pkg/inbox/inbox.go b/src/pkg/inbox/inbox.go index cf55790f23..34f92c3cb7 100644 --- a/src/pkg/inbox/inbox.go +++ b/src/pkg/inbox/inbox.go @@ -55,6 +55,9 @@ type Item struct { FactState string `json:"fact_state,omitempty"` // Routes holds per-destination state; absent means never routed. Routes map[string]*RouteState `json:"routes,omitempty"` + // ShareIntents are shares waiting for a machine transcript (or failed + // because it did not finish), keyed by destination. See ShareIntent. + ShareIntents map[string]*ShareIntent `json:"share_intents,omitempty"` // Dismissed marks "knowledge only": the item stays a fact, no further route. Dismissed bool `json:"dismissed,omitempty"` // Processed is true once any route filed or the item was dismissed. diff --git a/src/pkg/inbox/service.go b/src/pkg/inbox/service.go index 07979530e0..3d24fbcba5 100644 --- a/src/pkg/inbox/service.go +++ b/src/pkg/inbox/service.go @@ -59,9 +59,11 @@ type Service struct { // holds queued and running jobs in order (the head runs, one at a time) // with their live progress, guarded by txQMu. transcripts *TranscriptStore - txMu sync.Mutex - txQMu sync.Mutex - txQueue []*txJob + // intentRunners are the registered transcribe-then-share handlers. + intentRunners map[string]IntentRunner + txMu sync.Mutex + txQMu sync.Mutex + txQueue []*txJob // NewTranscriber builds the provider for a run; nil uses // DefaultTranscriber with the key from Getenv. Tests inject a fake. NewTranscriber func(config.InboxTranscription) (transcribe.Transcriber, error) @@ -355,6 +357,7 @@ func (s *Service) fail(key, dest string, err error) { // marks every listed item seen, so a rule added later never back-fires on // old recordings. It is called after each connector sync. func (s *Service) Sweep(ctx context.Context) (routed int, err error) { + s.ResumeIntents(ctx) items, lerr := s.Items(ctx) rules := s.Config().Rules for _, it := range items { diff --git a/src/pkg/inbox/shareintent.go b/src/pkg/inbox/shareintent.go new file mode 100644 index 0000000000..cad95cc7b1 --- /dev/null +++ b/src/pkg/inbox/shareintent.go @@ -0,0 +1,231 @@ +package inbox + +import ( + "context" + "errors" + "fmt" + "strings" + "time" +) + +// Share intent statuses. +const ( + // IntentWaiting: the share runs when the machine transcript completes. + IntentWaiting = "waiting" + // IntentFailed: the transcript did not complete (or the share could not + // start); nothing was sent. The Share menu offers a retry. + IntentFailed = "failed" +) + +// ShareIntent is a share chosen for an audio-only item before it has any +// text. The hive transcribes first and runs the share when the transcript +// completes. It holds only the choices made in the dialog, never item text +// or secrets, and is persisted with the item state so a restart resumes it. +type ShareIntent struct { + // Destination is spek_rfc, dismiss (Knowledge) or a destination with a + // registered IntentRunner (e.g. the spek session). + Destination string `json:"destination"` + // Actor is the dashboard user who chose the share. + Actor string `json:"actor"` + // Repo is the RFC repository picked in the dialog. + Repo string `json:"repo,omitempty"` + // Params carries other short dialog choices (e.g. a spek session name or + // "new session" flag). Values are choices, not item content. + Params map[string]string `json:"params,omitempty"` + Status string `json:"status"` + Error string `json:"error,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// IntentRunner performs a share for an item that now has text. Built in for +// spek_rfc and dismiss; other destinations register one with +// RegisterIntentRunner. +type IntentRunner func(ctx context.Context, it Item, in ShareIntent) error + +// ErrTranscribeUnavailable wraps the reason transcription cannot run now +// (a TranscribeBlocked* code); shares that need a transcript are refused. +var ErrTranscribeUnavailable = errors.New("transcription is not available") + +// ShareOutcome says what ShareWhenReady did. +type ShareOutcome struct { + // Waiting is true when the share is queued behind a transcription. + Waiting bool + // State is the route state when the share started immediately. + State RouteState +} + +// RegisterIntentRunner is the hook other destinations use to take part in +// transcribe-then-share. The spek session action registers "spek" here, with +// a runner that seeds the session from ShareIntent.Params. +func (s *Service) RegisterIntentRunner(dest string, run IntentRunner) { + s.mu.Lock() + defer s.mu.Unlock() + if s.intentRunners == nil { + s.intentRunners = map[string]IntentRunner{} + } + s.intentRunners[dest] = run +} + +func (s *Service) intentRunner(dest string) (IntentRunner, bool) { + s.mu.RLock() + run, ok := s.intentRunners[dest] + s.mu.RUnlock() + if ok { + return run, true + } + switch dest { + case DestSpekRFC, DestDismiss: + return func(ctx context.Context, it Item, in ShareIntent) error { + _, err := s.Route(ctx, it, Request{Destination: in.Destination, Repo: in.Repo}) + return err + }, true + } + return nil, false +} + +// needsTranscript reports whether an item has audio but no text yet. +func (s *Service) needsTranscript(it Item) bool { + return it.Pending && s.hasAudio(it) +} + +// ShareWhenReady shares an item to a Hive destination. An item with text is +// shared now; an audio-only item is transcribed first (the manual path, with +// its consent, budget and cap checks) and shared when the transcript +// completes. When transcription cannot run, ErrTranscribeUnavailable (with +// the reason code) is returned and nothing is stored or sent. +func (s *Service) ShareWhenReady(ctx context.Context, it Item, in ShareIntent, opts TranscribeOptions) (ShareOutcome, error) { + run, ok := s.intentRunner(in.Destination) + if !ok { + return ShareOutcome{}, fmt.Errorf("%w: %q", ErrUnknownDestination, in.Destination) + } + if !s.needsTranscript(it) { + st := RouteState{Status: StatusQueued, UpdatedAt: s.now()} + if err := run(ctx, it, in); err != nil { + return ShareOutcome{}, err + } + return ShareOutcome{State: st}, nil + } + store := s.transcriptStore() + cfg := s.Config().Transcription + if reason := s.transcribeBlockedReason(cfg, store); reason != "" { + return ShareOutcome{}, fmt.Errorf("%w: %s", ErrTranscribeUnavailable, reason) + } + in.Status, in.Error, in.CreatedAt, in.UpdatedAt = IntentWaiting, "", s.now(), s.now() + if err := s.Store.SetIntent(it.Key(), in); err != nil { + return ShareOutcome{}, err + } + st, err := s.Transcribe(ctx, it, opts) + switch { + case errors.Is(err, ErrTranscriptionBusy): + // A run is already in flight; the intent rides on it. + case errors.Is(err, ErrAlreadyTranscribed): + s.Store.ClearIntent(it.Key(), in.Destination) + return s.ShareWhenReady(ctx, withText(it), in, opts) + case err != nil: + s.Store.ClearIntent(it.Key(), in.Destination) + return ShareOutcome{}, err + case st.Status == TranscriptionSkipped: + s.Store.ClearIntent(it.Key(), in.Destination) + return ShareOutcome{}, fmt.Errorf("%w: %s", ErrTranscribeUnavailable, st.Reason) + } + return ShareOutcome{Waiting: true}, nil +} + +func withText(it Item) Item { it.Pending, it.HasTranscript = false, true; return it } + +// finishIntents runs (or fails) the intents waiting on a finished +// transcription. It is called after the transcript record is stored. +func (s *Service) finishIntents(it Item, rec TranscriptRecord) { + key := it.Key() + intents := s.Store.Intents(key) + if len(intents) == 0 { + return + } + ctx, cancel := context.WithTimeout(context.Background(), routeTimeout) + defer cancel() + for dest, in := range intents { + if in.Status != IntentWaiting { + continue + } + if rec.Status != TranscriptionDone { + s.failIntent(key, dest, "transcription "+rec.Status+": "+rec.Reason) + continue + } + run, ok := s.intentRunner(dest) + if !ok { + s.failIntent(key, dest, "no handler for destination "+dest) + continue + } + done := withText(it) + if err := run(ctx, done, *in); err != nil { + s.failIntent(key, dest, err.Error()) + continue + } + s.Store.ClearIntent(key, dest) + s.Logger.Info("inbox: shared after transcription", "item", key, "destination", dest, "actor", in.Actor) + } +} + +func (s *Service) failIntent(key, dest, reason string) { + s.Logger.Warn("inbox: share after transcription failed", "item", key, "destination", dest, "reason", reason) + if err := s.Store.FailIntent(key, dest, strings.TrimSpace(reason)); err != nil { + s.Logger.Warn("inbox: persist failed share intent", "item", key, "error", err) + } +} + +// ResumeIntents re-attaches shares that were waiting on a transcript when +// the hive stopped: a finished transcript runs them, an interrupted one is +// transcribed again. Sweep calls it after every sync. +func (s *Service) ResumeIntents(ctx context.Context) { + for _, key := range s.Store.IntentKeys() { + source, id, _ := strings.Cut(key, "/") + it, found, _ := s.Find(ctx, source, id) + if !found { + continue + } + store := s.transcriptStore() + if store == nil { + continue + } + rec, ok := store.Get(it.Source, it.ID) + switch { + case ok && rec.Status == TranscriptionDone: + s.finishIntents(it, rec) + case ok && (rec.Status == TranscriptionFailed || rec.Status == TranscriptionSkipped): + s.finishIntents(it, rec) + case ok && (rec.Status == TranscriptionQueued || rec.Status == TranscriptionRunning) && s.txIsLive(it.Source, it.ID): + // A live job will finish the intents itself. + default: + opts := TranscribeOptions{Actor: AutoTranscribeActor} + if rec.Status == TranscriptionQueued || rec.Status == TranscriptionRunning { + // Persisted as running but no job exists: the hive restarted. + rec.Status = TranscriptionFailed + _ = store.Put(rec) + } + if _, err := s.Transcribe(ctx, it, opts); err != nil && !errors.Is(err, ErrTranscriptionBusy) { + for dest := range s.Store.Intents(key) { + s.failIntent(key, dest, err.Error()) + } + } + } + } +} + +func cloneIntents(in map[string]*ShareIntent) map[string]*ShareIntent { + if len(in) == 0 { + return nil + } + out := make(map[string]*ShareIntent, len(in)) + for k, v := range in { + c := *v + if v.Params != nil { + c.Params = make(map[string]string, len(v.Params)) + for pk, pv := range v.Params { + c.Params[pk] = pv + } + } + out[k] = &c + } + return out +} diff --git a/src/pkg/inbox/shareintent_test.go b/src/pkg/inbox/shareintent_test.go new file mode 100644 index 0000000000..115642ee4e --- /dev/null +++ b/src/pkg/inbox/shareintent_test.go @@ -0,0 +1,208 @@ +package inbox + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/transcribe" +) + +// rfcDest records the content an RFC route delivered. +type rfcDest struct { + mu sync.Mutex + got []Content + req []Request +} + +func (d *rfcDest) Name() string { return DestSpekRFC } +func (d *rfcDest) Deliver(_ context.Context, _ Item, c Content, r Request) (Result, error) { + d.mu.Lock() + defer d.mu.Unlock() + d.got, d.req = append(d.got, c), append(d.req, r) + return Result{URL: "https://github.com/o/r/issues/9"}, nil +} + +func (d *rfcDest) count() int { d.mu.Lock(); defer d.mu.Unlock(); return len(d.got) } + +func intentFor(dest string) ShareIntent { + return ShareIntent{Destination: dest, Actor: "rw@example.com", Repo: "o/r"} +} + +// An audio-only item is transcribed first, then the RFC runs with the +// transcript; the intent is gone afterwards. +func TestShareWhenReadyTranscribesThenRoutes(t *testing.T) { + srv := audioServer(t, http.StatusOK, txAudio) + dest := &rfcDest{} + e := newTxEnv(t, activeTx(), srv.URL, dest) + out, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestSpekRFC), e.opts()) + if err != nil || !out.Waiting { + t.Fatalf("ShareWhenReady = %+v, %v", out, err) + } + e.svc.Wait() + if dest.count() != 1 || !strings.Contains(dest.got[0].Text(), "hello hive") || dest.req[0].Repo != "o/r" { + t.Fatalf("RFC delivered = %+v %+v", dest.got, dest.req) + } + if got := e.svc.Store.Intents("plaud/rec-1"); len(got) != 0 { + t.Fatalf("intent left behind: %+v", got) + } +} + +// Knowledge-only waits for the transcript the same way. +func TestShareWhenReadyKnowledgeAfterTranscript(t *testing.T) { + srv := audioServer(t, http.StatusOK, txAudio) + e := newTxEnv(t, activeTx(), srv.URL) + if _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestDismiss), e.opts()); err != nil { + t.Fatal(err) + } + e.svc.Wait() + if it := e.item(t); !it.Dismissed { + t.Fatalf("item not kept as knowledge after transcription: %+v", it) + } +} + +// Transcription failure fails the intent with the reason; nothing is sent. +func TestShareIntentFailsWithReasonAndSendsNothing(t *testing.T) { + srv := audioServer(t, http.StatusOK, txAudio) + dest := &rfcDest{} + e := newTxEnv(t, activeTx(), srv.URL, dest) + boom := errors.New("provider exploded") + e.fake.Errs = []error{boom, boom, boom, boom, boom, boom} + if _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestSpekRFC), e.opts()); err != nil { + t.Fatal(err) + } + e.svc.Wait() + in := e.svc.Store.Intents("plaud/rec-1")[DestSpekRFC] + if in == nil || in.Status != IntentFailed || !strings.Contains(in.Error, "provider exploded") { + t.Fatalf("intent = %+v", in) + } + if dest.count() != 0 { + t.Fatal("a failed transcription must not send the share") + } + if it := e.item(t); it.ShareIntents[DestSpekRFC] == nil || it.Dismissed { + t.Fatalf("item = %+v", it) + } +} + +// Unavailable transcription refuses audio-only shares; DIBS and items with +// text are unaffected. +func TestShareWhenReadyUnavailableAndTextItems(t *testing.T) { + srv := audioServer(t, http.StatusOK, txAudio) + dest := &rfcDest{} + e := newTxEnv(t, config.InboxTranscription{}, srv.URL, dest) + _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestSpekRFC), e.opts()) + if !errors.Is(err, ErrTranscribeUnavailable) || !strings.Contains(err.Error(), TranscribeBlockedDisabled) { + t.Fatalf("err = %v", err) + } + if len(e.svc.Store.Intents("plaud/rec-1")) != 0 || dest.count() != 0 { + t.Fatal("nothing may be stored or sent when transcription is unavailable") + } + withText := e.item(t) + withText.Pending = false + out, err := e.svc.ShareWhenReady(context.Background(), withText, intentFor(DestSpekRFC), e.opts()) + e.svc.Wait() + if err != nil || out.Waiting || dest.count() != 1 { + t.Fatalf("item with text: %+v %v delivered=%d", out, err, dest.count()) + } +} + +// DIBS is not a transcribe-first destination: it routes directly. +func TestRouteDibsIsUnaffectedByTranscription(t *testing.T) { + srv := audioServer(t, http.StatusOK, txAudio) + dibs := &contentDest{} + e := newTxEnv(t, config.InboxTranscription{}, srv.URL, dibs) + if _, err := e.svc.Route(context.Background(), e.item(t), Request{Destination: DestDibs}); err != nil { + t.Fatal(err) + } + e.svc.Wait() + if len(e.svc.Store.Intents("plaud/rec-1")) != 0 { + t.Fatal("DIBS must not create a share intent") + } +} + +// A restart with a persisted intent resumes: the transcript is made again +// and the share runs. The intent file holds no item text. +func TestShareIntentSurvivesRestart(t *testing.T) { + srv := audioServer(t, http.StatusOK, txAudio) + dest := &rfcDest{} + e := newTxEnv(t, activeTx(), srv.URL, dest) + var deferred []func() + e.svc.Run = func(fn func()) { deferred = append(deferred, fn) } + if _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestSpekRFC), e.opts()); err != nil { + t.Fatal(err) + } + if dest.count() != 0 { + t.Fatal("share must wait for the transcript") + } + raw, err := os.ReadFile(e.svc.Store.Path) + if err != nil { + t.Fatal(err) + } + for _, text := range []string{"Standup", "not transcribed", "hello hive", "secret-signature"} { + if strings.Contains(string(raw), text) { + t.Fatalf("intent state stores item text or a secret (%q): %s", text, raw) + } + } + if info, _ := os.Stat(e.svc.Store.Path); info.Mode().Perm() != 0o600 { + t.Fatalf("state mode = %v", info.Mode().Perm()) + } + // "Restart": a fresh service over the same files; the queued job is gone. + svc2 := NewService(config.InboxConfig{Transcription: activeTx()}, NewStore(e.svc.Store.Path), []Source{e.src}, []Destination{dest}, nil) + svc2.Run = func(fn func()) { fn() } + svc2.Now = func() time.Time { return e.now } + svc2.EnableTranscription(NewTranscriptStore(e.dir)) + svc2.NewTranscriber = func(config.InboxTranscription) (transcribe.Transcriber, error) { return e.fake, nil } + svc2.TranscribeBackoff = func(int) time.Duration { return 0 } + svc2.ResumeIntents(context.Background()) + svc2.Wait() + if dest.count() != 1 || !strings.Contains(dest.got[0].Text(), "hello hive") { + t.Fatalf("restart did not resume the share: %+v", dest.got) + } + if len(svc2.Store.Intents("plaud/rec-1")) != 0 { + t.Fatal("intent should be cleared after the resumed share") + } +} + +// Other destinations (the spek session) register through the hook. +func TestRegisterIntentRunnerHook(t *testing.T) { + srv := audioServer(t, http.StatusOK, txAudio) + e := newTxEnv(t, activeTx(), srv.URL) + var got ShareIntent + e.svc.RegisterIntentRunner("spek", func(_ context.Context, it Item, in ShareIntent) error { + got = in + if it.Pending { + t.Error("runner must see the item as having text") + } + return nil + }) + in := ShareIntent{Destination: "spek", Actor: "rw", Params: map[string]string{"session": "new"}} + if _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), in, e.opts()); err != nil { + t.Fatal(err) + } + e.svc.Wait() + if got.Destination != "spek" || got.Params["session"] != "new" || got.Actor != "rw" { + t.Fatalf("runner got %+v", got) + } +} + +// An old state file (no intents) still loads. +func TestStoreLoadsOldStateWithoutIntents(t *testing.T) { + path := filepath.Join(t.TempDir(), "inbox.json") + old, _ := json.Marshal(map[string]any{"plaud/a": map[string]any{"dismissed": true}}) + if err := os.WriteFile(path, old, 0o600); err != nil { + t.Fatal(err) + } + items := []Item{{Source: "plaud", ID: "a"}} + NewStore(path).Apply(items) + if !items[0].Dismissed || items[0].ShareIntents != nil { + t.Fatalf("items = %+v", items) + } +} diff --git a/src/pkg/inbox/store.go b/src/pkg/inbox/store.go index 2fbb028e27..bf11f2a7ad 100644 --- a/src/pkg/inbox/store.go +++ b/src/pkg/inbox/store.go @@ -14,6 +14,9 @@ import ( type entryState struct { Routes map[string]*RouteState `json:"routes,omitempty"` Dismissed bool `json:"dismissed,omitempty"` + // Intents are shares waiting for a transcript; persisted so a restart + // resumes them. + Intents map[string]*ShareIntent `json:"intents,omitempty"` } // Store persists route states as one JSON file next to connector state. @@ -100,6 +103,7 @@ func (s *Store) Apply(items []Item) { } items[i].Dismissed = e.Dismissed items[i].Routes = cloneRoutes(e.Routes) + items[i].ShareIntents = cloneIntents(e.Intents) items[i].Processed = e.Dismissed for _, r := range e.Routes { if r.Status == StatusFiled { @@ -217,3 +221,73 @@ func (s *Store) MarkSeen(key string) error { s.entry(key) return s.save() } + +// SetIntent records (or replaces) a share waiting on a transcript. +func (s *Store) SetIntent(key string, in ShareIntent) error { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + e := s.entry(key) + if e.Intents == nil { + e.Intents = map[string]*ShareIntent{} + } + c := in + e.Intents[in.Destination] = &c + return s.save() +} + +// ClearIntent removes the intent for key/dest. +func (s *Store) ClearIntent(key, dest string) { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + if e := s.entries[key]; e != nil && e.Intents[dest] != nil { + delete(e.Intents, dest) + if len(e.Intents) == 0 { + e.Intents = nil + } + _ = s.save() + } +} + +// FailIntent marks the intent failed with a reason; nothing was sent. +func (s *Store) FailIntent(key, dest, reason string) error { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + e := s.entries[key] + if e == nil || e.Intents[dest] == nil { + return nil + } + e.Intents[dest].Status, e.Intents[dest].Error, e.Intents[dest].UpdatedAt = IntentFailed, reason, s.now() + return s.save() +} + +// Intents returns a copy of key's share intents. +func (s *Store) Intents(key string) map[string]*ShareIntent { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + if e := s.entries[key]; e != nil { + return cloneIntents(e.Intents) + } + return nil +} + +// IntentKeys lists the items with a waiting share intent, sorted. +func (s *Store) IntentKeys() []string { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + var out []string + for k, e := range s.entries { + for _, in := range e.Intents { + if in.Status == IntentWaiting { + out = append(out, k) + break + } + } + } + sort.Strings(out) + return out +} diff --git a/src/pkg/inbox/transcription.go b/src/pkg/inbox/transcription.go index ca90ce88ab..175301e0ac 100644 --- a/src/pkg/inbox/transcription.go +++ b/src/pkg/inbox/transcription.go @@ -432,6 +432,7 @@ func (s *Service) runTranscription(it Item, cfg config.InboxTranscription, rec T s.Logger.Warn("inbox: write machine transcript to fact", "item", key, "error", ferr) } } + s.finishIntents(it, rec) s.auditTranscription(opts, rec, billed) s.Logger.Info("inbox: transcription finished", "item", key, "status", rec.Status, "provider", rec.Provider, "model", rec.Model, "audio_seconds", int(billed)) } diff --git a/src/pkg/inbox/transcription_progress.go b/src/pkg/inbox/transcription_progress.go index b575e37320..3a1ed1b7af 100644 --- a/src/pkg/inbox/transcription_progress.go +++ b/src/pkg/inbox/transcription_progress.go @@ -244,3 +244,9 @@ func expectedSpeed(store *TranscriptStore, provider, model string) transcribe.Sp } return transcribe.TypicalSpeed(provider) } + +// txIsLive reports whether a transcription job for the item is in the queue. +func (s *Service) txIsLive(source, id string) bool { + var st TranscriptionState + return s.txLive(source, id, &st) +} From a7a23e785480efed60c42338e93d9fa6e7935012 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 07:55:20 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=E2=9C=A8=20Inbox:=20avoid=20test=20helper?= =?UTF-8?q?=20name=20clash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/api_inbox_share_role_test.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/pkg/dashboard/api_inbox_share_role_test.go b/src/pkg/dashboard/api_inbox_share_role_test.go index 9dec22584f..df33f20435 100644 --- a/src/pkg/dashboard/api_inbox_share_role_test.go +++ b/src/pkg/dashboard/api_inbox_share_role_test.go @@ -10,7 +10,7 @@ import ( "github.com/hivecommons/hive/pkg/config" ) -func doPostRole(s *Server, path, role string, body any) *httptest.ResponseRecorder { +func doShareRolePost(s *Server, path, role string, body any) *httptest.ResponseRecorder { var b bytes.Buffer _ = json.NewEncoder(&b).Encode(body) rec := httptest.NewRecorder() @@ -35,23 +35,23 @@ func TestInboxShareRoleMatrix(t *testing.T) { deps.Inbox = newInboxTestService(t, deps.Config.Inbox, spek) route := map[string]string{"source": "plaud", "item_id": "rec-1", "destination": "spek_rfc"} for _, role := range []string{"", "read-only", "read"} { - if rec := doPostRole(s, "/api/inbox/route", role, route); rec.Code != http.StatusForbidden { + if rec := doShareRolePost(s, "/api/inbox/route", role, route); rec.Code != http.StatusForbidden { t.Fatalf("role %q route = %d, want 403", role, rec.Code) } - if rec := doPostRole(s, "/api/inbox/dismiss", role, map[string]any{"items": []map[string]string{{"source": "plaud", "item_id": "rec-1"}}}); rec.Code != http.StatusForbidden { + if rec := doShareRolePost(s, "/api/inbox/dismiss", role, map[string]any{"items": []map[string]string{{"source": "plaud", "item_id": "rec-1"}}}); rec.Code != http.StatusForbidden { t.Fatalf("role %q dismiss = %d, want 403", role, rec.Code) } } - if rec := doPostRole(s, "/api/inbox/route", "read-write", route); rec.Code != http.StatusAccepted { + if rec := doShareRolePost(s, "/api/inbox/route", "read-write", route); rec.Code != http.StatusAccepted { t.Fatalf("read-write route = %d: %s", rec.Code, rec.Body.String()) } - if rec := doPostRole(s, "/api/inbox/dismiss", "read-write", map[string]any{"items": []map[string]string{{"source": "plaud", "item_id": "rec-1"}}}); rec.Code != http.StatusOK { + if rec := doShareRolePost(s, "/api/inbox/dismiss", "read-write", map[string]any{"items": []map[string]string{{"source": "plaud", "item_id": "rec-1"}}}); rec.Code != http.StatusOK { t.Fatalf("read-write dismiss = %d: %s", rec.Code, rec.Body.String()) } - if rec := doPostRole(s, "/api/inbox/route", "owner", route); rec.Code != http.StatusAccepted { + if rec := doShareRolePost(s, "/api/inbox/route", "owner", route); rec.Code != http.StatusAccepted { t.Fatalf("owner route = %d: %s", rec.Code, rec.Body.String()) } - if rec := doPostRole(s, "/api/inbox/settings", "read-write", map[string]any{"spek_repo": "o/r"}); rec.Code != http.StatusForbidden { + if rec := doShareRolePost(s, "/api/inbox/settings", "read-write", map[string]any{"spek_repo": "o/r"}); rec.Code != http.StatusForbidden { t.Fatalf("read-write settings = %d, want 403 (settings stay owner-only)", rec.Code) } } From 1fefa648d842fd6fb8b8191dfa168c3b2a3462af Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 08:08:37 -0500 Subject: [PATCH 3/3] =?UTF-8?q?=E2=9C=A8=20Inbox:=20fix=20transcribe-then-?= =?UTF-8?q?share=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/inbox_share_menu_test.go | 1 - src/pkg/dashboard/inbox_transcribe.test.js | 4 ++-- src/pkg/dashboard/static-src/js/inbox.js | 3 +-- src/pkg/dashboard/static/index.html | 3 +-- src/pkg/inbox/shareintent_test.go | 9 +++++++++ 5 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/pkg/dashboard/inbox_share_menu_test.go b/src/pkg/dashboard/inbox_share_menu_test.go index 01dc803a92..eda891e723 100644 --- a/src/pkg/dashboard/inbox_share_menu_test.go +++ b/src/pkg/dashboard/inbox_share_menu_test.go @@ -36,7 +36,6 @@ func TestInboxShareMenuBehaviour(t *testing.T) { "function inboxShareCopy(s, i) { calls.push(['copy', s, i]); } async function inboxShareNative(s, i) { calls.push(['native', s, i]); }", "function inboxDismissSelected() { calls.push(['bulk-dismiss']); } const _inboxSelected = new Set(['plaud/r1']);", "function inboxFind(s, i) { return ((_inboxCache || {}).items || []).find(it => it.source === s && it.id === i); }", - jsConstLine(t, html, "INBOX_INTENT_LABELS"), "function inboxOpenSettings() { calls.push(['settings']); }", jsConstBlock(t, html, "inboxShareHiveActions"), jsConstBlock(t, html, "inboxShareLinkActions"), diff --git a/src/pkg/dashboard/inbox_transcribe.test.js b/src/pkg/dashboard/inbox_transcribe.test.js index db9807bd3b..d6c5826057 100644 --- a/src/pkg/dashboard/inbox_transcribe.test.js +++ b/src/pkg/dashboard/inbox_transcribe.test.js @@ -40,7 +40,7 @@ const itemHarness = ({ role = 'owner', status = 202, body = { state: { status: ' }; const h = new Function('ctx', 'fetch', 'escapeHtml', 'formatDashboardDateTime', 'showToast', 'renderInbox', 'fetchInbox', 'INBOX_TX_STATUS_LABELS', 'const window = ctx.window; const _inboxTranscribing = ctx._inboxTranscribing; const _inboxContent = ctx._inboxContent;\n' + - fnSrc('inboxViewerCanPlay') + '\n' + fnSrc('inboxApiPath') + '\n' + fnSrc('inboxTxUnavailableText') + '\n' + fnSrc('inboxTxEtaText') + '\n' + fnSrc('inboxTxElapsedText') + '\n' + fnSrc('inboxTxProgressHtml') + '\n' + fnSrc('inboxTranscriptionHtml') + '\n' + fnSrc('inboxTranscribe') + '\n' + + fnSrc('inboxViewerCanPlay') + '\n' + fnSrc('inboxApiPath') + '\n' + fnSrc('inboxTxUnavailableText') + '\n' + fnSrc('inboxTxEtaText') + '\n' + fnSrc('inboxTxElapsedText') + '\n' + fnSrc('inboxTxProgressHtml') + '\n' + fnSrc('inboxIntentThen') + '\n' + fnSrc('inboxIntentLabel') + '\n' + fnSrc('inboxTranscriptionHtml') + '\n' + fnSrc('inboxTranscribe') + '\n' + 'return { inboxTranscriptionHtml, inboxTranscribe };'); const api = h(ctx, fetch, escapeHtml, s => 'at ' + s, (msg, kind) => calls.toasts.push([msg, kind]), () => { calls.renders++; }, async () => { calls.refreshes++; }, LABELS); @@ -238,7 +238,7 @@ test('pending text is provider-neutral for every source and keeps the upstream h // progressHarness extracts the progress helpers and the live poll merge. const progressHarness = () => new Function('escapeHtml', 'function inboxTxBusy(st) { return !!st && (st.status === "queued" || st.status === "running"); }\n' + - fnSrc('inboxTxEtaText') + '\n' + fnSrc('inboxTxElapsedText') + '\n' + fnSrc('inboxTxProgressHtml') + '\n' + fnSrc('inboxTxApplyActive') + '\n' + + fnSrc('inboxTxEtaText') + '\n' + fnSrc('inboxTxElapsedText') + '\n' + fnSrc('inboxTxProgressHtml') + '\n' + fnSrc('inboxIntentThen') + '\n' + fnSrc('inboxIntentLabel') + '\n' + fnSrc('inboxTxApplyActive') + '\n' + 'return { inboxTxEtaText, inboxTxElapsedText, inboxTxProgressHtml, inboxTxApplyActive };')(escapeHtml); test('ETA text rounds the way people say it', () => { diff --git a/src/pkg/dashboard/static-src/js/inbox.js b/src/pkg/dashboard/static-src/js/inbox.js index ac362cdad9..736503d16b 100644 --- a/src/pkg/dashboard/static-src/js/inbox.js +++ b/src/pkg/dashboard/static-src/js/inbox.js @@ -458,8 +458,7 @@ if (inboxTxBlocked(it)) return inboxTxUnavailableText(it.transcribe_unavailable) + ' (a transcript is needed first)'; return ''; } - const INBOX_INTENT_LABELS = { spek_rfc: 'RFC', dismiss: 'Knowledge', spek: 'spek' }; - function inboxIntentLabel(dest) { return INBOX_INTENT_LABELS[dest] || dest; } + function inboxIntentLabel(dest) { return ({ spek_rfc: 'RFC', dismiss: 'Knowledge', spek: 'spek' })[dest] || dest; } // The first waiting share intent of an item, for the progress label. function inboxIntentThen(it) { const m = (it && it.share_intents) || {}; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 425dbaeb9e..9cd769f2b8 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -47797,8 +47797,7 @@ if (inboxTxBlocked(it)) return inboxTxUnavailableText(it.transcribe_unavailable) + ' (a transcript is needed first)'; return ''; } - const INBOX_INTENT_LABELS = { spek_rfc: 'RFC', dismiss: 'Knowledge', spek: 'spek' }; - function inboxIntentLabel(dest) { return INBOX_INTENT_LABELS[dest] || dest; } + function inboxIntentLabel(dest) { return ({ spek_rfc: 'RFC', dismiss: 'Knowledge', spek: 'spek' })[dest] || dest; } // The first waiting share intent of an item, for the progress label. function inboxIntentThen(it) { const m = (it && it.share_intents) || {}; diff --git a/src/pkg/inbox/shareintent_test.go b/src/pkg/inbox/shareintent_test.go index 115642ee4e..80a9b0def5 100644 --- a/src/pkg/inbox/shareintent_test.go +++ b/src/pkg/inbox/shareintent_test.go @@ -33,6 +33,9 @@ func (d *rfcDest) Deliver(_ context.Context, _ Item, c Content, r Request) (Resu func (d *rfcDest) count() int { d.mu.Lock(); defer d.mu.Unlock(); return len(d.got) } +// withKeyEnv makes the default provider's API key present. +func withKeyEnv(string) string { return "test-key" } + func intentFor(dest string) ShareIntent { return ShareIntent{Destination: dest, Actor: "rw@example.com", Repo: "o/r"} } @@ -43,6 +46,7 @@ func TestShareWhenReadyTranscribesThenRoutes(t *testing.T) { srv := audioServer(t, http.StatusOK, txAudio) dest := &rfcDest{} e := newTxEnv(t, activeTx(), srv.URL, dest) + e.svc.Getenv = withKeyEnv out, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestSpekRFC), e.opts()) if err != nil || !out.Waiting { t.Fatalf("ShareWhenReady = %+v, %v", out, err) @@ -60,6 +64,7 @@ func TestShareWhenReadyTranscribesThenRoutes(t *testing.T) { func TestShareWhenReadyKnowledgeAfterTranscript(t *testing.T) { srv := audioServer(t, http.StatusOK, txAudio) e := newTxEnv(t, activeTx(), srv.URL) + e.svc.Getenv = withKeyEnv if _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestDismiss), e.opts()); err != nil { t.Fatal(err) } @@ -74,6 +79,7 @@ func TestShareIntentFailsWithReasonAndSendsNothing(t *testing.T) { srv := audioServer(t, http.StatusOK, txAudio) dest := &rfcDest{} e := newTxEnv(t, activeTx(), srv.URL, dest) + e.svc.Getenv = withKeyEnv boom := errors.New("provider exploded") e.fake.Errs = []error{boom, boom, boom, boom, boom, boom} if _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestSpekRFC), e.opts()); err != nil { @@ -134,6 +140,7 @@ func TestShareIntentSurvivesRestart(t *testing.T) { srv := audioServer(t, http.StatusOK, txAudio) dest := &rfcDest{} e := newTxEnv(t, activeTx(), srv.URL, dest) + e.svc.Getenv = withKeyEnv var deferred []func() e.svc.Run = func(fn func()) { deferred = append(deferred, fn) } if _, err := e.svc.ShareWhenReady(context.Background(), e.item(t), intentFor(DestSpekRFC), e.opts()); err != nil { @@ -157,6 +164,7 @@ func TestShareIntentSurvivesRestart(t *testing.T) { // "Restart": a fresh service over the same files; the queued job is gone. svc2 := NewService(config.InboxConfig{Transcription: activeTx()}, NewStore(e.svc.Store.Path), []Source{e.src}, []Destination{dest}, nil) svc2.Run = func(fn func()) { fn() } + svc2.Getenv = withKeyEnv svc2.Now = func() time.Time { return e.now } svc2.EnableTranscription(NewTranscriptStore(e.dir)) svc2.NewTranscriber = func(config.InboxTranscription) (transcribe.Transcriber, error) { return e.fake, nil } @@ -175,6 +183,7 @@ func TestShareIntentSurvivesRestart(t *testing.T) { func TestRegisterIntentRunnerHook(t *testing.T) { srv := audioServer(t, http.StatusOK, txAudio) e := newTxEnv(t, activeTx(), srv.URL) + e.svc.Getenv = withKeyEnv var got ShareIntent e.svc.RegisterIntentRunner("spek", func(_ context.Context, it Item, in ShareIntent) error { got = in