Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(teamhub): save voice provider keys in the product and resolve voice at use time

shoudi zheng85af769791e8
diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.md
index a567873a..39457ce6 100644
--- a/apps/teamhub/AGENTS.md
+++ b/apps/teamhub/AGENTS.md
@@ -147,5 +147,13 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.
`notify_river_queue` so the job does not wait for the queue's poll. Such a
loop is woken on commit and sleeps until its next due time, with a fallback
of at least one minute; it never polls on a short fixed interval.
+- Voice: `TEAMHUB_VOICE_MEDIA` (`on` by default) builds the voice media plane
+ over LiveKit; `off`, a missing `LINGER_SECRET_SEED`, or missing ffmpeg keep
+ voice off (the last two log `voice.media_unavailable`) without stopping
+ TeamHub.
+ `internal/voicekey` resolves the Soniox and xAI keys at each use, the
+ environment key over one saved in the product (`voice_provider_keys`, sealed
+ with `TEAMHUB_SECRET_ENCRYPTION_KEY`), so a save applies without a restart
+ on every replica. A save wakes the Node Services voice workers best effort.
- Do not add write-only audit, event, or provenance tables. A new audit table
needs a named product or compliance reader in the same pull request.
diff --git a/apps/teamhub/internal/app/app.go b/apps/teamhub/internal/app/app.go
index 64b05b89..fcea681f 100644
--- a/apps/teamhub/internal/app/app.go
+++ b/apps/teamhub/internal/app/app.go
@@ -65,6 +65,7 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/taskexecution"
"github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicecaptureqa"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicemedia"
"github.com/simplexai-labs/linger/apps/teamhub/internal/workitem"
httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
@@ -114,8 +115,11 @@ type App struct {
agentManagement roomagent.AgentManagement
localComputers roomagent.LocalComputerManagement
voiceMedia voicemedia.Plane
- // voiceTranscription is Soniox ASR: Recording, dictation and Pocket Notes.
- voiceTranscription bool
+ // voiceKeys resolves the Soniox and xAI keys at each use.
+ voiceKeys *voicekey.Service
+ // reconcileVoiceWorkers wakes the Node Services voice workers after a key
+ // is saved; nil without a Node Services link.
+ reconcileVoiceWorkers func(context.Context) error
voiceRecordings *voicemedia.LocalStagingStore
accounts *account.Lifecycle
passwordHashes *account.HashLimiter
@@ -205,10 +209,13 @@ type Deps struct {
WikiCandidates document.WikiCandidateGenerator
DocumentTextNormalizer documenttext.Normalizer
VoiceMedia voicemedia.Plane
- PersonalProfile personalprofile.Generator
- PersonalInsight personalinsight.Generator
- ProactiveEventJudge proactive.EventJudge
- PermissionJudge permissionreview.Judge
+ // VoiceKeyChecker checks a voice provider key before it is saved; nil
+ // asks the provider's API.
+ VoiceKeyChecker voicekey.Checker
+ PersonalProfile personalprofile.Generator
+ PersonalInsight personalinsight.Generator
+ ProactiveEventJudge proactive.EventJudge
+ PermissionJudge permissionreview.Judge
// RealtimeBroker lets a test watch committed-event wakes.
RealtimeBroker *realtime.Broker
// QueryTracer observes TeamHub database queries.
@@ -508,7 +515,7 @@ func newApp(cfg config.Config, deps Deps, pool *pgxpool.Pool, signingKey []byte,
// registerFeatures builds every domain feature in dependency order; a
// feature reads only the ones registered before it.
func (a *App) registerFeatures(ctx context.Context, cfg config.Config, deps Deps, core coreServices) error {
- if err := a.registerVoice(cfg.Voice, deps.VoiceMedia, core.artifacts, cfg.ArtifactStorageRoot); err != nil {
+ if err := a.registerVoice(cfg, deps, core.artifacts); err != nil {
return err
}
a.reminders = reminder.New(a.pool)
diff --git a/apps/teamhub/internal/app/contract_server_voice_runtime.go b/apps/teamhub/internal/app/contract_server_voice_runtime.go
index 7718c72f..a871cef4 100644
--- a/apps/teamhub/internal/app/contract_server_voice_runtime.go
+++ b/apps/teamhub/internal/app/contract_server_voice_runtime.go
@@ -20,23 +20,30 @@ func (a *App) requireVoiceRuntime() gin.HandlerFunc {
c.Abort()
return
}
- if a.cfg.Voice.RuntimeToken == "" {
- c.JSON(http.StatusServiceUnavailable, teamhubinternal.VoiceError{
- Code: "DEPENDENCY_UNAVAILABLE", Message: "Voice Runtime callback is not configured",
- })
- c.Abort()
- return
- }
- token, ok := strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
- if !ok || token == "" || subtle.ConstantTimeCompare([]byte(token), []byte(a.cfg.Voice.RuntimeToken)) != 1 {
- c.JSON(http.StatusUnauthorized, teamhubinternal.VoiceError{
- Code: "UNAUTHENTICATED", Message: "Voice Runtime authentication is invalid",
- })
- c.Abort()
- return
- }
- c.Next()
+ a.authenticateVoiceRuntime(c)
+ }
+}
+
+// authenticateVoiceRuntime checks the Voice Runtime credential. The provider
+// key read uses it alone: Node Services asks whether to run voice workers
+// whether or not voice media is on, and gets no key while it is off.
+func (a *App) authenticateVoiceRuntime(c *gin.Context) {
+ if a.cfg.Voice.RuntimeToken == "" {
+ c.JSON(http.StatusServiceUnavailable, teamhubinternal.VoiceError{
+ Code: "DEPENDENCY_UNAVAILABLE", Message: "Voice Runtime callback is not configured",
+ })
+ c.Abort()
+ return
+ }
+ token, ok := strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
+ if !ok || token == "" || subtle.ConstantTimeCompare([]byte(token), []byte(a.cfg.Voice.RuntimeToken)) != 1 {
+ c.JSON(http.StatusUnauthorized, teamhubinternal.VoiceError{
+ Code: "UNAUTHENTICATED", Message: "Voice Runtime authentication is invalid",
+ })
+ c.Abort()
+ return
}
+ c.Next()
}
func (a *App) reportVoiceObservationRoute(c *gin.Context) {
diff --git a/apps/teamhub/internal/app/feature_external_apps.go b/apps/teamhub/internal/app/feature_external_apps.go
index ce9e6a0c..88474813 100644
--- a/apps/teamhub/internal/app/feature_external_apps.go
+++ b/apps/teamhub/internal/app/feature_external_apps.go
@@ -47,11 +47,9 @@ func (a *App) registerExternalApps(ctx context.Context, cfg config.ExternalAppsC
sources.SetAppImportLimits(composio.AppImportLimits{
MaxFieldBytes: config.AppImportMaxFieldBytes, MaxDocumentBytes: config.AppImportMaxDocumentBytes, MaxBatchBytes: config.AppImportMaxBatchBytes,
})
- var keyBox *secretbox.Box
- if cfg.SecretEncryptionKey != "" {
- if keyBox, err = secretbox.New(cfg.SecretEncryptionKey); err != nil {
- return err
- }
+ keyBox, err := secretBox(cfg.SecretEncryptionKey)
+ if err != nil {
+ return err
}
if err = sources.ConfigureManagedApps(ctx, client, keyBox); err != nil {
return fmt.Errorf("configure managed connected apps: %w", err)
@@ -108,3 +106,12 @@ func (a *App) onboardingConnections(ctx context.Context, tx pgx.Tx, agentActorID
}
return connections, nil
}
+
+// secretBox opens the box that seals provider keys saved in the product; nil
+// when the deployment sets no TEAMHUB_SECRET_ENCRYPTION_KEY.
+func secretBox(encodedKey string) (*secretbox.Box, error) {
+ if encodedKey == "" {
+ return nil, nil
+ }
+ return secretbox.New(encodedKey)
+}
diff --git a/apps/teamhub/internal/app/feature_voice.go b/apps/teamhub/internal/app/feature_voice.go
index b576a938..bb36c7e8 100644
--- a/apps/teamhub/internal/app/feature_voice.go
+++ b/apps/teamhub/internal/app/feature_voice.go
@@ -2,41 +2,119 @@ package app
import (
"context"
+ "errors"
"fmt"
+ "net/http"
"time"
"github.com/jackc/pgx/v5/pgxpool"
artifactstore "github.com/simplexai-labs/linger/apps/teamhub/internal/artifact"
"github.com/simplexai-labs/linger/apps/teamhub/internal/config"
"github.com/simplexai-labs/linger/apps/teamhub/internal/document"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voice"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicemedia"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicetranscription"
)
-// registerVoice builds voice media when SONIOX_API_KEY or XAI_API_KEY is set,
-// or takes the plane a test injects. Soniox turns on transcription
-// (Recording, dictation and Pocket Notes) with archive recovery; xAI turns on
-// Live alone. Without either voice stays off: the Voice Runtime callbacks
-// answer not found, the Voice media policy reports nothing supported, and no
-// voice retention rule or job exists.
-func (a *App) registerVoice(cfg config.VoiceConfig, injected voicemedia.Plane, objects artifactstore.ObjectStore, stagingRoot string) error {
- media := injected
- a.voiceTranscription = injected != nil || cfg.SonioxAPIKey != ""
- if media == nil && (cfg.SonioxAPIKey != "" || cfg.XaiAPIKey != "") {
- service, recordings, err := newVoiceMedia(a.pool, objects, stagingRoot, a.documents, cfg)
- if err != nil {
+// voiceReconcileTimeout bounds the best-effort wake of the Node Services voice
+// workers after a key is saved; their own periodic reconcile covers a miss.
+const voiceReconcileTimeout = 5 * time.Second
+
+// registerVoice builds voice media while TEAMHUB_VOICE_MEDIA is on, or takes
+// the plane a test injects; without LINGER_SECRET_SEED or ffmpeg it runs
+// with voice off. Whether a provider can be used is decided at each
+// use from the key in effect then: the environment key, else the one saved in
+// the product. Soniox enables transcription (Recording, dictation and Pocket
+// Notes) with archive recovery; xAI enables Live alone. With voice media off
+// voice stays off: the Voice Runtime callbacks answer not found, the Voice
+// media policy reports nothing available, and no voice retention rule or job
+// exists. With voice on and no key the voice jobs and rules are registered
+// but find no work, because no voice session can start without a key.
+func (a *App) registerVoice(cfg config.Config, deps Deps, objects artifactstore.ObjectStore) error {
+ box, err := secretBox(cfg.ExternalApps.SecretEncryptionKey)
+ if err != nil {
+ return err
+ }
+ checker := deps.VoiceKeyChecker
+ if checker == nil {
+ checker = voicekey.NewHTTPChecker()
+ }
+ if cfg.NodeServicesURL != "" && cfg.NodeServicesInternalToken != "" {
+ if a.reconcileVoiceWorkers, err = newVoiceWorkerReconciler(cfg.NodeServicesURL, cfg.NodeServicesInternalToken); err != nil {
return err
}
- media, a.voiceRecordings = service, recordings
}
- if media == nil {
- return nil
+ media, err := a.buildVoiceMedia(cfg, deps.VoiceMedia, objects)
+ if err != nil {
+ return err
}
+ // This is the one place voice is decided on or off for the process: the
+ // key service's Enabled drives the policy, saves and the key read.
a.voiceMedia = media
+ a.voiceKeys = voicekey.New(a.queries, checker, voicekey.Config{
+ Enabled: media != nil,
+ Environment: map[voicekey.Provider]string{
+ voicekey.Soniox: cfg.Voice.SonioxAPIKey, voicekey.XAI: cfg.Voice.XaiAPIKey,
+ },
+ Box: box,
+ }, a.logger)
return nil
}
+// newVoiceMediaPlane builds the production plane; a test replaces it to
+// inject a build failure.
+var newVoiceMediaPlane = newVoiceMedia
+
+// buildVoiceMedia returns the plane voice runs on, or nil with voice off.
+// Like every other service link, voice stays off without LINGER_SECRET_SEED,
+// and a computer without ffmpeg runs without voice rather than not at all;
+// any other build error still stops startup.
+func (a *App) buildVoiceMedia(cfg config.Config, injected voicemedia.Plane, objects artifactstore.ObjectStore) (voicemedia.Plane, error) {
+ if injected != nil {
+ return injected, nil
+ }
+ if !cfg.Voice.MediaEnabled {
+ return nil, nil
+ }
+ if cfg.Voice.RuntimeToken == "" {
+ a.logger.Warn("voice.media_unavailable", "reason", "secret_seed_missing")
+ return nil, nil
+ }
+ service, recordings, err := newVoiceMediaPlane(a.pool, objects, cfg.ArtifactStorageRoot, a.documents, cfg.Voice, func(ctx context.Context) (string, error) {
+ return a.voiceKeys.Effective(ctx, voicekey.Soniox)
+ })
+ if errors.Is(err, voicemedia.ErrMediaToolsMissing) {
+ a.logger.Warn("voice.media_unavailable", "reason", "ffmpeg_missing")
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ a.voiceRecordings = recordings
+ return service, nil
+}
+
+// newVoiceWorkerReconciler asks Node Services to start or stop its voice
+// workers for the keys now in effect. The request carries no key.
+func newVoiceWorkerReconciler(baseURL, token string) (func(context.Context) error, error) {
+ client, err := roomagent.NewAgentManagementClient(baseURL, token, &http.Client{Timeout: voiceReconcileTimeout})
+ if err != nil {
+ return nil, fmt.Errorf("configure Node Services voice reconcile: %w", err)
+ }
+ return func(ctx context.Context) error {
+ response, err := client.ReconcileVoiceWorkersWithResponse(ctx)
+ if err != nil {
+ return err
+ }
+ if response.StatusCode() != http.StatusAccepted {
+ return fmt.Errorf("Node Services voice reconcile returned HTTP %d", response.StatusCode())
+ }
+ return nil
+ }, nil
+}
+
// addVoiceJobs registers the voice River jobs when the voice media plane has
// them.
func (a *App) addVoiceJobs(features *featureSet) {
@@ -52,10 +130,10 @@ func (a *App) addVoiceJobs(features *featureSet) {
})
}
-// newVoiceMedia builds voice media over LiveKit, with Soniox archive recovery
-// when Soniox is configured. The recorder's HLS staging files live under
-// stagingRoot.
-func newVoiceMedia(pool *pgxpool.Pool, objects artifactstore.ObjectStore, stagingRoot string, documents *document.Service, cfg config.VoiceConfig) (*voicemedia.Service, *voicemedia.LocalStagingStore, error) {
+// newVoiceMedia builds voice media over LiveKit. Archive recovery reads the
+// Soniox key at each use, so it starts working as soon as a key is saved. The
+// recorder's HLS staging files live under stagingRoot.
+func newVoiceMedia(pool *pgxpool.Pool, objects artifactstore.ObjectStore, stagingRoot string, documents *document.Service, cfg config.VoiceConfig, sonioxKey func(context.Context) (string, error)) (*voicemedia.Service, *voicemedia.LocalStagingStore, error) {
liveKitProvider, err := voicemedia.NewLiveKitProvider(voicemedia.LiveKitConfig{
APIURL: cfg.LiveKitAPIURL, PublicURL: cfg.LiveKitURL,
APIKey: cfg.LiveKitAPIKey, APISecret: cfg.LiveKitAPISecret,
@@ -72,15 +150,8 @@ func newVoiceMedia(pool *pgxpool.Pool, objects artifactstore.ObjectStore, stagin
return nil, nil, fmt.Errorf("configure voice media materializer: %w", err)
}
service := voicemedia.NewWithDocuments(pool, liveKitProvider, materializer, documents)
- if cfg.SonioxAPIKey != "" {
- archiveTranscriber, err := voicetranscription.NewSonioxTranscriber(voicetranscription.SonioxConfig{
- APIKey: cfg.SonioxAPIKey, LanguageHints: voicetranscription.SonioxLanguageHints,
- })
- if err != nil {
- return nil, nil, fmt.Errorf("configure voice transcription: %w", err)
- }
- service.SetArchiveTranscriber(archiveTranscriber, voice.NormalizeCaptureTranscript)
- service.SetArchiveRecoveryConcurrency(config.VoiceArchiveRecoveryConcurrency)
- }
+ archiveTranscriber := voicetranscription.NewKeyedSonioxTranscriber(sonioxKey, voicetranscription.SonioxConfig{LanguageHints: voicetranscription.SonioxLanguageHints})
+ service.SetArchiveTranscriber(archiveTranscriber, voice.NormalizeCaptureTranscript)
+ service.SetArchiveRecoveryConcurrency(config.VoiceArchiveRecoveryConcurrency)
return service, recordings, nil
}
diff --git a/apps/teamhub/internal/app/features_test.go b/apps/teamhub/internal/app/features_test.go
index 4b173d0b..8561f74b 100644
--- a/apps/teamhub/internal/app/features_test.go
+++ b/apps/teamhub/internal/app/features_test.go
@@ -1,18 +1,28 @@
package app
import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
"net/http"
"net/http/httptest"
+ "os/exec"
"reflect"
"slices"
"strings"
"testing"
"github.com/gin-gonic/gin"
+ "github.com/jackc/pgx/v5/pgxpool"
"github.com/riverqueue/river"
+ artifactstore "github.com/simplexai-labs/linger/apps/teamhub/internal/artifact"
"github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/document"
"github.com/simplexai-labs/linger/apps/teamhub/internal/permissionreview"
"github.com/simplexai-labs/linger/apps/teamhub/internal/retention"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicemedia"
)
@@ -85,7 +95,7 @@ func TestOptionalFeaturesRegisterFromConfiguration(t *testing.T) {
if tc.voice {
plane = voicemedia.New(nil, nil, nil)
}
- if err := a.registerVoice(config.VoiceConfig{}, plane, nil, ""); err != nil {
+ if err := a.registerVoice(config.ForTest(), Deps{VoiceMedia: plane}, nil); err != nil {
t.Fatal(err)
}
a.addVoiceJobs(features)
@@ -147,7 +157,7 @@ func TestVoiceRuntimeCallbacksNeedVoiceMedia(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
a := &App{}
a.cfg.Voice.RuntimeToken = "voice-token"
- if err := a.registerVoice(config.VoiceConfig{}, tc.media, nil, ""); err != nil {
+ if err := a.registerVoice(config.ForTest(), Deps{VoiceMedia: tc.media}, nil); err != nil {
t.Fatal(err)
}
engine := gin.New()
@@ -175,8 +185,11 @@ func TestVoiceSessionPurposeNeedsItsProvider(t *testing.T) {
{"live without xAI", "chat_live", "", true},
} {
t.Run(tc.name, func(t *testing.T) {
- a := &App{voiceMedia: voicemedia.New(nil, nil, nil), voiceTranscription: tc.transcription}
- a.cfg.Voice.XaiAPIKey = tc.xai
+ environment := map[voicekey.Provider]string{voicekey.XAI: tc.xai}
+ if tc.transcription {
+ environment[voicekey.Soniox] = "soniox-key"
+ }
+ a := &App{voiceMedia: voicemedia.New(nil, nil, nil), voiceKeys: voicekey.New(nil, nil, voicekey.Config{Enabled: true, Environment: environment}, nil)}
engine := gin.New()
engine.POST("/v0/rooms/:roomId/voice-sessions", func(c *gin.Context) {
c.Set("request_id", "request")
@@ -191,3 +204,101 @@ func TestVoiceSessionPurposeNeedsItsProvider(t *testing.T) {
})
}
}
+
+// With TEAMHUB_VOICE_MEDIA on and no key anywhere the full voice plane is
+// built and its jobs and retention rules registered; they only find work once
+// a voice session exists, and none can start without a key.
+func TestVoiceMediaOnWithoutKeysRegistersTheVoicePlane(t *testing.T) {
+ if _, err := exec.LookPath("ffmpeg"); err != nil {
+ t.Skip("ffmpeg required to build the voice media materializer")
+ }
+ if _, err := exec.LookPath("ffprobe"); err != nil {
+ t.Skip("ffprobe required to build the voice media materializer")
+ }
+ cfg := voiceOnConfig()
+ a := &App{cfg: cfg, logger: slog.Default()}
+ if err := a.registerVoice(cfg, Deps{}, nil); err != nil {
+ t.Fatal(err)
+ }
+ if a.voiceMedia == nil || a.voiceRecordings == nil || !a.voiceKeys.Enabled() {
+ t.Fatal("voice media on did not build the voice plane")
+ }
+ features := newFeatureSet()
+ a.addVoiceJobs(features)
+ // The bare App has no Document service, so materialization stays out.
+ want := []string{
+ "voice_capture_completion", "voice_capture_reconcile", "voice_capture_stop",
+ "voice_session_reconcile", "voice_staging_cleanup", "voice_transcript_recovery",
+ }
+ if got := registeredKinds(features.workers); !slices.Equal(got, want) {
+ t.Fatalf("River kinds:\n got %v\nwant %v", got, want)
+ }
+ if len(features.periodic) != 0 || len(features.resume) != 1 {
+ t.Fatalf("periodic=%d resume=%d, want no periodic voice job and one resume", len(features.periodic), len(features.resume))
+ }
+ if got := retentionTables(a.retentionRules()); !slices.Equal(got, slices.Concat(retentionTables(retention.Core), voiceRetentionTables)) {
+ t.Fatalf("retention rules = %v", got)
+ }
+}
+
+func voiceOnConfig() config.Config {
+ return config.ForTest(func(cfg *config.Config) {
+ cfg.Voice.MediaEnabled = true
+ cfg.Voice.RuntimeToken = "voice-token"
+ cfg.Voice.LiveKitAPIURL = "http://127.0.0.1:17880"
+ })
+}
+
+// Voice that cannot run here leaves TeamHub up with voice off and one
+// warning: without LINGER_SECRET_SEED, or without ffmpeg. Any other build
+// failure still stops startup.
+func TestVoiceMediaThatCannotRunTurnsVoiceOff(t *testing.T) {
+ for _, tc := range []struct {
+ name, reason string
+ seed bool
+ build error
+ fails bool
+ }{
+ {name: "no secret seed", reason: "secret_seed_missing"},
+ {name: "no ffmpeg", reason: "ffmpeg_missing", seed: true, build: fmt.Errorf("ffprobe: %w", voicemedia.ErrMediaToolsMissing)},
+ {name: "bad LiveKit configuration", seed: true, build: errors.New("configure LiveKit voice media provider"), fails: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ built := false
+ original := newVoiceMediaPlane
+ t.Cleanup(func() { newVoiceMediaPlane = original })
+ newVoiceMediaPlane = func(*pgxpool.Pool, artifactstore.ObjectStore, string, *document.Service, config.VoiceConfig, func(context.Context) (string, error)) (*voicemedia.Service, *voicemedia.LocalStagingStore, error) {
+ built = true
+ return nil, nil, tc.build
+ }
+ cfg := voiceOnConfig()
+ if !tc.seed {
+ cfg.Voice.RuntimeToken = ""
+ }
+ var logs bytes.Buffer
+ a := &App{cfg: cfg, logger: slog.New(slog.NewJSONHandler(&logs, nil))}
+ err := a.registerVoice(cfg, Deps{}, nil)
+ if tc.fails {
+ if err == nil {
+ t.Fatal("a broken voice configuration started")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if built != tc.seed || a.voiceMedia != nil || a.voiceKeys.Enabled() {
+ t.Fatalf("built=%v media=%v enabled=%v", built, a.voiceMedia != nil, a.voiceKeys.Enabled())
+ }
+ if !strings.Contains(logs.String(), `"msg":"voice.media_unavailable"`) || !strings.Contains(logs.String(), `"reason":"`+tc.reason+`"`) {
+ t.Fatalf("logs = %s", logs.String())
+ }
+ if status, _ := a.voiceKeys.Status(t.Context(), voicekey.Soniox); status.CanSave {
+ t.Fatal("a key can be saved with voice off")
+ }
+ if err := a.voiceKeys.Save(t.Context(), voicekey.Soniox, "key"); !errors.Is(err, voicekey.ErrVoiceOff) {
+ t.Fatalf("Save = %v", err)
+ }
+ })
+ }
+}
diff --git a/apps/teamhub/internal/app/handlers_voice_media.go b/apps/teamhub/internal/app/handlers_voice_media.go
index 7c31aff2..c3d8b9da 100644
--- a/apps/teamhub/internal/app/handlers_voice_media.go
+++ b/apps/teamhub/internal/app/handlers_voice_media.go
@@ -11,6 +11,7 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/collaboration"
"github.com/simplexai-labs/linger/apps/teamhub/internal/idempotency"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voice"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicemedia"
httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
)
@@ -49,12 +50,16 @@ func (a *App) createVoiceSession(c *gin.Context) {
return
}
// Live runs on xAI alone; every other purpose transcribes with Soniox.
- if purpose == voicemedia.PurposeChatLive && a.cfg.Voice.XaiAPIKey == "" {
- a.writeVoiceMediaError(c, "start Live", voicemedia.ErrProviderUnavailable)
- return
+ // The key is read now, so one saved a moment ago already counts.
+ provider := voicekey.Soniox
+ if purpose == voicemedia.PurposeChatLive {
+ provider = voicekey.XAI
+ }
+ key, err := a.voiceKeys.Effective(c.Request.Context(), provider)
+ if err == nil && key == "" {
+ err = voicemedia.ErrProviderUnavailable
}
- if purpose != voicemedia.PurposeChatLive && !a.voiceTranscription {
- a.writeVoiceMediaError(c, "start voice transcription", voicemedia.ErrProviderUnavailable)
+ if a.writeVoiceMediaError(c, "resolve voice provider key", err) {
return
}
session, err := a.voiceMedia.CreateVoiceSession(c.Request.Context(), voicemedia.CreateVoiceSessionRequest{
diff --git a/apps/teamhub/internal/app/routes.go b/apps/teamhub/internal/app/routes.go
index 0d58d65f..6211e023 100644
--- a/apps/teamhub/internal/app/routes.go
+++ b/apps/teamhub/internal/app/routes.go
@@ -56,6 +56,13 @@ func (a *App) routeGroups() []routeGroup {
},
middleware: []gin.HandlerFunc{a.requireVoiceRuntime()}, routes: a.voiceRuntimeRoutes(),
},
+ {
+ contract: "teamhub-internal",
+ paramError: func(c *gin.Context, _ reflect.Type, _ error) {
+ c.JSON(http.StatusBadRequest, teamhubinternal.VoiceError{Code: "INVALID_REQUEST", Message: "Voice Runtime request is invalid"})
+ },
+ middleware: []gin.HandlerFunc{a.authenticateVoiceRuntime}, routes: a.voiceKeyRoutes(),
+ },
{
contract: "teamhub-agent-api",
paramError: func(c *gin.Context, _ reflect.Type, _ error) {
diff --git a/apps/teamhub/internal/app/routes_internal.go b/apps/teamhub/internal/app/routes_internal.go
index 44f82800..086b505e 100644
--- a/apps/teamhub/internal/app/routes_internal.go
+++ b/apps/teamhub/internal/app/routes_internal.go
@@ -86,6 +86,14 @@ func (a *App) mcpContextRoutes() []contractRoute {
}
}
+// voiceKeyRoutes mounts the Voice Runtime operations that answer with voice
+// media off too.
+func (a *App) voiceKeyRoutes() []contractRoute {
+ return []contractRoute{
+ route(http.MethodGet, "/internal/v1/voice/provider-keys", nil, a.getVoiceProviderKeys),
+ }
+}
+
// voiceRuntimeRoutes mounts the teamhub-internal operations Voice Runtime calls.
func (a *App) voiceRuntimeRoutes() []contractRoute {
return []contractRoute{
@@ -93,7 +101,6 @@ func (a *App) voiceRuntimeRoutes() []contractRoute {
route(http.MethodPost, "/internal/v1/voice/live-tool-calls", nil, a.executeVoiceLiveToolCall),
route(http.MethodPut, "/internal/v1/voice/media-objects", teamhubinternal.PutVoiceMediaObjectParams{}, a.putVoiceMediaObject),
route(http.MethodPost, "/internal/v1/voice/observations", nil, a.reportVoiceObservationRoute),
- route(http.MethodGet, "/internal/v1/voice/provider-keys", nil, a.getVoiceProviderKeys),
route(http.MethodPost, "/internal/v1/voice/recordings", nil, a.reportVoiceRecording),
route(http.MethodGet, "/internal/v1/voice/sessions/:voiceSessionId/live-context", nil, a.getVoiceLiveContext),
route(http.MethodGet, "/internal/v1/voice/sessions/:voiceSessionId/live-task-events", nil, a.streamVoiceLiveTaskEvents),
diff --git a/apps/teamhub/internal/app/voice_media_policy.go b/apps/teamhub/internal/app/voice_media_policy.go
index 4036837a..efc4be6b 100644
--- a/apps/teamhub/internal/app/voice_media_policy.go
+++ b/apps/teamhub/internal/app/voice_media_policy.go
@@ -5,9 +5,12 @@ import (
"github.com/gin-gonic/gin"
"github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
)
+// getVoiceMediaPolicy reports what voice can do now: each provider's key is
+// read at request time, so a key saved a moment ago already counts.
func (a *App) getVoiceMediaPolicy(c *gin.Context) {
policy, err := a.voice.MediaPolicy(c.Request.Context(), store.GetVoiceMediaPolicyForAccountParams{
AccountID: currentPrincipal(c).Session.AccountID, TenantID: c.Param("tenantId"),
@@ -16,10 +19,23 @@ func (a *App) getVoiceMediaPolicy(c *gin.Context) {
if a.writeVoiceMediaError(c, "resolve Voice media policy", err) {
return
}
- live := a.voiceMedia != nil && a.cfg.Voice.XaiAPIKey != ""
+ soniox, err := a.voiceKeys.Status(c.Request.Context(), voicekey.Soniox)
+ if a.writeVoiceMediaError(c, "resolve Soniox key status", err) {
+ return
+ }
+ xai, err := a.voiceKeys.Status(c.Request.Context(), voicekey.XAI)
+ if a.writeVoiceMediaError(c, "resolve xAI key status", err) {
+ return
+ }
+ available := a.voiceMedia != nil && a.voiceKeys.Enabled()
+ transcription := available && soniox.Source != voicekey.SourceNone
+ live := available && xai.Source != voicekey.SourceNone
+ sonioxStatus, xaiStatus := voiceProviderKeyModel(soniox), voiceProviderKeyModel(xai)
response := httpapi.VoiceMediaPolicy{
LiveSupported: &live, LiveEnabled: &live,
- VoiceMediaSupported: a.voiceTranscription,
+ VoiceMediaSupported: transcription,
+ VoiceAvailable: &available,
+ SonioxKey: &sonioxStatus, XaiKey: &xaiStatus,
}
if policy.LivekitRoomID != "" {
response.ActiveRoomId = &policy.LivekitRoomID
diff --git a/apps/teamhub/internal/app/voice_provider_keys.go b/apps/teamhub/internal/app/voice_provider_keys.go
index f7a259b6..2e71ab34 100644
--- a/apps/teamhub/internal/app/voice_provider_keys.go
+++ b/apps/teamhub/internal/app/voice_provider_keys.go
@@ -1,19 +1,89 @@
package app
import (
+ "context"
+ "errors"
"net/http"
"github.com/gin-gonic/gin"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
+ "github.com/simplexai-labs/linger/contracts-go/teamhubinternal"
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
)
-// saveVoiceProviderKey stores the deployment's API key for one voice provider.
+// saveVoiceProviderKey stores the deployment's API key for one voice provider
+// after the provider accepts it. Any signed-in Human may save, as for
+// Composio. The key is never returned, logged or echoed in an error.
func (a *App) saveVoiceProviderKey(c *gin.Context) {
- // Replaced by the voice provider key store.
- a.writeError(c, http.StatusNotImplemented, "NOT_IMPLEMENTED", "Saving voice provider keys is not implemented")
+ provider := voicekey.Provider(c.Param("provider"))
+ var request httpapi.SaveVoiceProviderKeyRequest
+ if !provider.Valid() || decodeJSON(c, &request) != nil {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Voice provider key request is invalid")
+ return
+ }
+ err := a.voiceKeys.Save(c.Request.Context(), provider, request.ApiKey)
+ switch {
+ case errors.Is(err, voicekey.ErrInvalid):
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Voice provider API key is invalid")
+ case errors.Is(err, voicekey.ErrRejected):
+ a.writeError(c, http.StatusBadRequest, "VOICE_KEY_REJECTED", "The voice provider rejected this API key")
+ case errors.Is(err, voicekey.ErrFromEnvironment):
+ a.writeError(c, http.StatusConflict, "VOICE_KEY_FROM_ENVIRONMENT", "This deployment sets this voice provider's API key")
+ case errors.Is(err, voicekey.ErrVoiceOff):
+ a.writeError(c, http.StatusServiceUnavailable, "VOICE_MEDIA_OFF", "Voice is off in this deployment")
+ case errors.Is(err, voicekey.ErrStorageMissing):
+ a.writeError(c, http.StatusServiceUnavailable, "VOICE_KEY_STORAGE_UNAVAILABLE", "This deployment cannot store a voice provider API key")
+ case errors.Is(err, voicekey.ErrProviderUnavailable):
+ a.writeError(c, http.StatusServiceUnavailable, "VOICE_PROVIDER_UNAVAILABLE", "The voice provider could not be reached; try again")
+ case err != nil:
+ a.internalError(c, "save voice provider key", err)
+ default:
+ status, err := a.voiceKeys.Status(c.Request.Context(), provider)
+ if err != nil {
+ a.internalError(c, "resolve voice provider key status", err)
+ return
+ }
+ a.notifyVoiceWorkers(c.Request.Context())
+ c.JSON(http.StatusOK, voiceProviderKeyModel(status))
+ }
}
-// getVoiceProviderKeys returns the effective voice provider keys to the Voice Runtime.
+// notifyVoiceWorkers asks Node Services, in the background, to start the
+// voice workers the saved key enables. A failure only logs: the save stands
+// and Node Services' periodic reconcile picks the key up.
+func (a *App) notifyVoiceWorkers(requestContext context.Context) {
+ if a.reconcileVoiceWorkers == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(requestContext), voiceReconcileTimeout)
+ go func() {
+ defer cancel()
+ if err := a.reconcileVoiceWorkers(ctx); err != nil {
+ a.logger.Warn("voice.reconcile_notify_failed", "error", err)
+ }
+ }()
+}
+
+func voiceProviderKeyModel(status voicekey.Status) httpapi.VoiceProviderKeyStatus {
+ return httpapi.VoiceProviderKeyStatus{Source: httpapi.VoiceProviderKeyStatusSource(status.Source), CanSave: status.CanSave}
+}
+
+// getVoiceProviderKeys returns the effective voice provider keys to the Voice
+// Runtime; a provider without a key is absent, and both are while voice media
+// is off.
func (a *App) getVoiceProviderKeys(c *gin.Context) {
- // Replaced by the voice provider key store.
- a.writeError(c, http.StatusNotImplemented, "NOT_IMPLEMENTED", "Reading voice provider keys is not implemented")
+ c.Header("Cache-Control", "no-store")
+ var keys teamhubinternal.VoiceRuntimeProviderKeys
+ for provider, target := range map[voicekey.Provider]**string{voicekey.Soniox: &keys.SonioxApiKey, voicekey.XAI: &keys.XaiApiKey} {
+ key, err := a.voiceKeys.Effective(c.Request.Context(), provider)
+ if err != nil {
+ a.logger.Error("voice.provider_keys_read_failed", "provider", string(provider), "error", err)
+ c.JSON(http.StatusInternalServerError, teamhubinternal.VoiceError{Code: "INTERNAL_ERROR", Message: "Voice provider keys could not be read"})
+ return
+ }
+ if key != "" {
+ *target = &key
+ }
+ }
+ c.JSON(http.StatusOK, keys)
}
diff --git a/apps/teamhub/internal/app/voice_provider_keys_test.go b/apps/teamhub/internal/app/voice_provider_keys_test.go
new file mode 100644
index 00000000..3ca1e16e
--- /dev/null
+++ b/apps/teamhub/internal/app/voice_provider_keys_test.go
@@ -0,0 +1,230 @@
+package app
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/jackc/pgx/v5"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/secretbox"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicemedia"
+)
+
+const testVoiceKey = "sk-voice-provider-secret-1234"
+
+type memoryVoiceKeys struct {
+ mu sync.Mutex
+ rows map[string][]byte
+}
+
+func (m *memoryVoiceKeys) GetVoiceProviderKey(_ context.Context, provider string) ([]byte, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if sealed, ok := m.rows[provider]; ok {
+ return sealed, nil
+ }
+ return nil, pgx.ErrNoRows
+}
+
+func (m *memoryVoiceKeys) UpsertVoiceProviderKey(_ context.Context, arg store.UpsertVoiceProviderKeyParams) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.rows == nil {
+ m.rows = map[string][]byte{}
+ }
+ m.rows[arg.Provider] = arg.ApiKeyCiphertext
+ return nil
+}
+
+type voiceKeyCheck func(context.Context, voicekey.Provider, string) error
+
+func (f voiceKeyCheck) Check(ctx context.Context, provider voicekey.Provider, key string) error {
+ return f(ctx, provider, key)
+}
+
+// syncBuffer collects log lines written from the background notify.
+type syncBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (b *syncBuffer) Write(p []byte) (int, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.Write(p)
+}
+
+func (b *syncBuffer) String() string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.String()
+}
+
+func newVoiceKeyTestApp(t *testing.T, cfg voicekey.Config, check voiceKeyCheck) (*App, *syncBuffer) {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ logs := &syncBuffer{}
+ logger := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ if check == nil {
+ check = func(context.Context, voicekey.Provider, string) error { return nil }
+ }
+ a := &App{
+ cfg: config.ForTest(func(c *config.Config) { c.Voice.RuntimeToken = "voice-token" }),
+ logger: logger, voiceMedia: voicemedia.New(nil, nil, nil),
+ voiceKeys: voicekey.New(&memoryVoiceKeys{}, check, cfg, logger),
+ }
+ return a, logs
+}
+
+func testSecretBox(t *testing.T) *secretbox.Box {
+ t.Helper()
+ box, err := secretbox.New(base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return box
+}
+
+func putVoiceKey(a *App, provider, body string) *httptest.ResponseRecorder {
+ engine := gin.New()
+ engine.PUT("/v0/voice-provider-keys/:provider", func(c *gin.Context) {
+ c.Set("request_id", "request-voice-key")
+ a.saveVoiceProviderKey(c)
+ })
+ response := httptest.NewRecorder()
+ engine.ServeHTTP(response, httptest.NewRequest(http.MethodPut, "/v0/voice-provider-keys/"+provider, strings.NewReader(body)))
+ return response
+}
+
+// A save answers with the new status, wakes Node Services once in the
+// background, and a failed wake only logs; the key appears in neither the
+// response nor the logs.
+func TestSaveVoiceProviderKeyNotifiesNodeServicesBestEffort(t *testing.T) {
+ a, logs := newVoiceKeyTestApp(t, voicekey.Config{Enabled: true, Box: testSecretBox(t)}, nil)
+ notified := make(chan struct{}, 1)
+ a.reconcileVoiceWorkers = func(ctx context.Context) error {
+ if _, ok := ctx.Deadline(); !ok {
+ t.Error("the reconcile notify has no deadline")
+ }
+ notified <- struct{}{}
+ return errors.New("connection refused")
+ }
+ response := putVoiceKey(a, "soniox", `{"api_key":" `+testVoiceKey+` "}`)
+ if response.Code != http.StatusOK || response.Body.String() != `{"can_save":true,"source":"stored"}` {
+ t.Fatalf("save = %d %s", response.Code, response.Body)
+ }
+ select {
+ case <-notified:
+ case <-time.After(30 * time.Second):
+ t.Fatal("Node Services was not notified")
+ }
+ deadline := time.Now().Add(30 * time.Second)
+ for !strings.Contains(logs.String(), "voice.reconcile_notify_failed") {
+ if time.Now().After(deadline) {
+ t.Fatalf("no notify failure log: %s", logs.String())
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if key, _ := a.voiceKeys.Effective(t.Context(), voicekey.Soniox); key != testVoiceKey {
+ t.Fatalf("effective key = %q", key)
+ }
+ if strings.Contains(response.Body.String(), testVoiceKey) || strings.Contains(logs.String(), testVoiceKey) {
+ t.Fatal("the key leaked into the response or the logs")
+ }
+}
+
+func TestSaveVoiceProviderKeyErrors(t *testing.T) {
+ rejected := func(context.Context, voicekey.Provider, string) error { return voicekey.ErrRejected }
+ unreachable := func(context.Context, voicekey.Provider, string) error { return voicekey.ErrProviderUnavailable }
+ box := testSecretBox(t)
+ for _, tc := range []struct {
+ name, provider, body string
+ cfg voicekey.Config
+ check voiceKeyCheck
+ status int
+ code string
+ }{
+ {"unknown provider", "openai", `{"api_key":"` + testVoiceKey + `"}`, voicekey.Config{Enabled: true, Box: box}, nil, http.StatusBadRequest, "INVALID_REQUEST"},
+ {"malformed body", "soniox", `{"key":"` + testVoiceKey + `"}`, voicekey.Config{Enabled: true, Box: box}, nil, http.StatusBadRequest, "INVALID_REQUEST"},
+ {"blank key", "soniox", `{"api_key":" "}`, voicekey.Config{Enabled: true, Box: box}, nil, http.StatusBadRequest, "INVALID_REQUEST"},
+ {"rejected", "soniox", `{"api_key":"` + testVoiceKey + `"}`, voicekey.Config{Enabled: true, Box: box}, rejected, http.StatusBadRequest, "VOICE_KEY_REJECTED"},
+ {"unreachable", "xai", `{"api_key":"` + testVoiceKey + `"}`, voicekey.Config{Enabled: true, Box: box}, unreachable, http.StatusServiceUnavailable, "VOICE_PROVIDER_UNAVAILABLE"},
+ {"environment", "xai", `{"api_key":"` + testVoiceKey + `"}`, voicekey.Config{Enabled: true, Box: box, Environment: map[voicekey.Provider]string{voicekey.XAI: "env-key"}}, nil, http.StatusConflict, "VOICE_KEY_FROM_ENVIRONMENT"},
+ {"no encryption key", "soniox", `{"api_key":"` + testVoiceKey + `"}`, voicekey.Config{Enabled: true}, nil, http.StatusServiceUnavailable, "VOICE_KEY_STORAGE_UNAVAILABLE"},
+ {"voice off", "soniox", `{"api_key":"` + testVoiceKey + `"}`, voicekey.Config{Box: box}, nil, http.StatusServiceUnavailable, "VOICE_MEDIA_OFF"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ a, logs := newVoiceKeyTestApp(t, tc.cfg, tc.check)
+ a.reconcileVoiceWorkers = func(context.Context) error {
+ t.Error("a refused save notified Node Services")
+ return nil
+ }
+ response := putVoiceKey(a, tc.provider, tc.body)
+ if response.Code != tc.status || !strings.Contains(response.Body.String(), `"code":"`+tc.code+`"`) {
+ t.Fatalf("save = %d %s", response.Code, response.Body)
+ }
+ if strings.Contains(response.Body.String(), testVoiceKey) || strings.Contains(logs.String(), testVoiceKey) {
+ t.Fatal("the key leaked into the response or the logs")
+ }
+ })
+ }
+}
+
+func getRuntimeVoiceKeys(a *App, authorization string) *httptest.ResponseRecorder {
+ engine := gin.New()
+ a.registerContractRoutes(engine)
+ request := httptest.NewRequest(http.MethodGet, "/internal/v1/voice/provider-keys", nil)
+ if authorization != "" {
+ request.Header.Set("Authorization", authorization)
+ }
+ response := httptest.NewRecorder()
+ engine.ServeHTTP(response, request)
+ return response
+}
+
+func TestGetVoiceProviderKeysReturnsEffectiveKeysToTheVoiceRuntime(t *testing.T) {
+ a, _ := newVoiceKeyTestApp(t, voicekey.Config{
+ Enabled: true, Box: testSecretBox(t), Environment: map[voicekey.Provider]string{voicekey.XAI: "xai-env-key"},
+ }, nil)
+ for _, authorization := range []string{"", "Bearer wrong-token"} {
+ if response := getRuntimeVoiceKeys(a, authorization); response.Code != http.StatusUnauthorized || strings.Contains(response.Body.String(), "xai-env-key") {
+ t.Fatalf("auth %q = %d %s", authorization, response.Code, response.Body)
+ }
+ }
+ response := getRuntimeVoiceKeys(a, "Bearer voice-token")
+ if response.Code != http.StatusOK || response.Body.String() != `{"xai_api_key":"xai-env-key"}` || response.Header().Get("Cache-Control") != "no-store" {
+ t.Fatalf("keys = %d %s cache=%q", response.Code, response.Body, response.Header().Get("Cache-Control"))
+ }
+ if err := a.voiceKeys.Save(t.Context(), voicekey.Soniox, testVoiceKey); err != nil {
+ t.Fatal(err)
+ }
+ response = getRuntimeVoiceKeys(a, "Bearer voice-token")
+ if response.Code != http.StatusOK || response.Body.String() != `{"soniox_api_key":"`+testVoiceKey+`","xai_api_key":"xai-env-key"}` {
+ t.Fatalf("keys after save = %d %s", response.Code, response.Body)
+ }
+}
+
+// With voice media off the read still answers, without any key, so Node
+// Services stops its voice workers instead of retrying a missing route.
+func TestGetVoiceProviderKeysWithVoiceOff(t *testing.T) {
+ a, _ := newVoiceKeyTestApp(t, voicekey.Config{
+ Box: testSecretBox(t), Environment: map[voicekey.Provider]string{voicekey.Soniox: "soniox-env-key", voicekey.XAI: "xai-env-key"},
+ }, nil)
+ a.voiceMedia = nil
+ response := getRuntimeVoiceKeys(a, "Bearer voice-token")
+ if response.Code != http.StatusOK || response.Body.String() != `{}` || response.Header().Get("Cache-Control") != "no-store" {
+ t.Fatalf("keys = %d %s", response.Code, response.Body)
+ }
+}
diff --git a/apps/teamhub/internal/config/config.go b/apps/teamhub/internal/config/config.go
index 8636889a..0b13f060 100644
--- a/apps/teamhub/internal/config/config.go
+++ b/apps/teamhub/internal/config/config.go
@@ -121,11 +121,17 @@ type PermissionReviewConfig struct {
// VoiceConfig configures voice media.
type VoiceConfig struct {
- // XaiAPIKey turns Live Voice Mode on over LiveKit, independently of Soniox.
+ // MediaEnabled is TEAMHUB_VOICE_MEDIA: whether this deployment can run
+ // voice at all (LiveKit and the voice tools). Off keeps voice entirely
+ // off whatever keys exist; without LINGER_SECRET_SEED or ffmpeg the App
+ // runs with voice off too.
+ MediaEnabled bool
+ // XaiAPIKey is the deployment's xAI key for Live. It wins over a key saved
+ // in the product, which then cannot be saved.
XaiAPIKey string
- // SonioxAPIKey turns transcription on: Recording, Voice Mode dictation and
- // Pocket Notes dictation over LiveKit, with Soniox archive recovery for
- // recordings.
+ // SonioxAPIKey is the deployment's Soniox key for transcription:
+ // Recording, Voice Mode dictation and Pocket Notes dictation, with archive
+ // recovery for recordings. It wins over a key saved in the product.
SonioxAPIKey string
// LiveKitURL is the ws(s) origin browsers dial. LiveKitAPIURL is where
// TeamHub calls the LiveKit API: LIVEKIT_API_URL when TeamHub reaches
@@ -151,6 +157,9 @@ func Load() (Config, error) {
if err := applyPermissionReview(&cfg); err != nil {
return Config{}, err
}
+ if err := applyVoiceMedia(&cfg); err != nil {
+ return Config{}, err
+ }
if err := applyDerivedCredentials(&cfg); err != nil {
return Config{}, err
}
@@ -241,6 +250,8 @@ func ForTest(edits ...func(*Config)) Config {
cfg.ArtifactStorageRoot = filepath.Join(os.TempDir(), "teamhub-artifacts")
cfg.DocumentPreviewPublicOrigin = LocalPreviewOrigin(cfg.HTTPAddress)
cfg.Jobs.PollInterval = 25 * time.Millisecond
+ // Building voice media needs LiveKit and ffmpeg; a voice test turns it on.
+ cfg.Voice.MediaEnabled = false
for _, edit := range edits {
edit(&cfg)
}
@@ -271,6 +282,7 @@ func Default() Config {
AppImportProviderCallBudget: 100,
},
Voice: VoiceConfig{
+ MediaEnabled: true,
LiveKitURL: "ws://127.0.0.1:17880",
LiveKitAPIKey: "devkey",
LiveKitAPISecret: "devsecret-livekit-voice-local-only-32-bytes",
@@ -326,9 +338,6 @@ func validate(cfg *Config) error {
}
}
- if (strings.TrimSpace(cfg.Voice.SonioxAPIKey) != "" || strings.TrimSpace(cfg.Voice.XaiAPIKey) != "") && strings.TrimSpace(cfg.Voice.RuntimeToken) == "" {
- return errors.New("LINGER_SECRET_SEED is required when SONIOX_API_KEY or XAI_API_KEY turns voice media on")
- }
liveKitURL, err := url.Parse(cfg.Voice.LiveKitURL)
if err != nil || liveKitURL.Host == "" || liveKitURL.User != nil || (liveKitURL.Path != "" && liveKitURL.Path != "/") || liveKitURL.RawQuery != "" || liveKitURL.Fragment != "" || (liveKitURL.Scheme != "ws" && liveKitURL.Scheme != "wss") {
return errors.New("LIVEKIT_URL must be an absolute ws or wss origin without credentials, path, query, or fragment")
@@ -461,6 +470,20 @@ func applyPermissionReview(cfg *Config) error {
return nil
}
+// applyVoiceMedia reads TEAMHUB_VOICE_MEDIA; unset keeps the default, on.
+func applyVoiceMedia(cfg *Config) error {
+ switch strings.TrimSpace(os.Getenv("TEAMHUB_VOICE_MEDIA")) {
+ case "":
+ case "on":
+ cfg.Voice.MediaEnabled = true
+ case "off":
+ cfg.Voice.MediaEnabled = false
+ default:
+ return errors.New("TEAMHUB_VOICE_MEDIA must be on or off")
+ }
+ return nil
+}
+
func setNonemptyEnvironment(target *string, name string) {
if value := os.Getenv(name); value != "" {
*target = value
diff --git a/apps/teamhub/internal/config/config_test.go b/apps/teamhub/internal/config/config_test.go
index b44b2c48..24f3f9fb 100644
--- a/apps/teamhub/internal/config/config_test.go
+++ b/apps/teamhub/internal/config/config_test.go
@@ -24,6 +24,8 @@ var teamhubEnvironment = []string{
"TEAMHUB_COMPOSIO_ENVIRONMENT_KEY",
"WEB_PUBLIC_ORIGIN",
"SONIOX_API_KEY",
+ "XAI_API_KEY",
+ "TEAMHUB_VOICE_MEDIA",
"LIVEKIT_URL",
"LIVEKIT_API_URL",
"LIVEKIT_API_KEY",
@@ -149,26 +151,53 @@ func TestLoadRejectsInvalidPublicURL(t *testing.T) {
}
}
-func TestLoadSonioxKeyTurnsVoiceMediaOnWithSecretSeed(t *testing.T) {
+// Voice media is on by default. Without a seed Load still succeeds, like
+// every other link; the App then runs with voice off.
+func TestLoadVoiceMediaIsOnByDefault(t *testing.T) {
clearTeamHubEnvironment(t)
t.Setenv("TEAMHUB_DATABASE_URL", "postgres://environment.example/teamhub")
- t.Setenv("SONIOX_API_KEY", "soniox-secret")
- if _, err := Load(); err == nil || !strings.Contains(err.Error(), "LINGER_SECRET_SEED") {
- t.Fatalf("Soniox without a seed error = %v", err)
+ if cfg, err := Load(); err != nil || !cfg.Voice.MediaEnabled || cfg.Voice.RuntimeToken != "" {
+ t.Fatalf("voice media without a seed: enabled=%v err=%v", cfg.Voice.MediaEnabled, err)
}
t.Setenv("LINGER_SECRET_SEED", testSecretSeed)
+ t.Setenv("SONIOX_API_KEY", "soniox-secret")
+ t.Setenv("XAI_API_KEY", "xai-secret")
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
- if cfg.Voice.SonioxAPIKey != "soniox-secret" || cfg.Voice.RuntimeToken != ServiceCredential(testSecretSeed, "voice-runtime") {
- t.Fatalf("unexpected voice config: %+v", cfg)
+ if !cfg.Voice.MediaEnabled || cfg.Voice.SonioxAPIKey != "soniox-secret" || cfg.Voice.XaiAPIKey != "xai-secret" || cfg.Voice.RuntimeToken != ServiceCredential(testSecretSeed, "voice-runtime") {
+ t.Fatalf("unexpected voice config: %+v", cfg.Voice)
}
if cfg.Voice.LiveKitURL != "ws://127.0.0.1:17880" || cfg.Voice.LiveKitAPIURL != "http://127.0.0.1:17880" || cfg.Voice.LiveKitAPIKey != "devkey" || cfg.Voice.LiveKitAPISecret != "devsecret-livekit-voice-local-only-32-bytes" {
t.Fatalf("unexpected LiveKit defaults: %+v", cfg)
}
}
+func TestLoadVoiceMediaSetting(t *testing.T) {
+ for _, tc := range []struct {
+ value string
+ want bool
+ }{{"on", true}, {"off", false}, {" off ", false}} {
+ clearTeamHubEnvironment(t)
+ t.Setenv("TEAMHUB_DATABASE_URL", "postgres://environment.example/teamhub")
+ t.Setenv("LINGER_SECRET_SEED", testSecretSeed)
+ t.Setenv("TEAMHUB_VOICE_MEDIA", tc.value)
+ cfg, err := Load()
+ if err != nil || cfg.Voice.MediaEnabled != tc.want {
+ t.Fatalf("TEAMHUB_VOICE_MEDIA=%q: enabled=%v err=%v", tc.value, cfg.Voice.MediaEnabled, err)
+ }
+ }
+ clearTeamHubEnvironment(t)
+ t.Setenv("TEAMHUB_DATABASE_URL", "postgres://environment.example/teamhub")
+ for _, value := range []string{"true", "ON", "1", "yes"} {
+ t.Setenv("TEAMHUB_VOICE_MEDIA", value)
+ if _, err := Load(); err == nil || !strings.Contains(err.Error(), "TEAMHUB_VOICE_MEDIA") {
+ t.Fatalf("TEAMHUB_VOICE_MEDIA=%q error = %v", value, err)
+ }
+ }
+}
+
func TestLoadLiveKitEnvironment(t *testing.T) {
clearTeamHubEnvironment(t)
t.Setenv("TEAMHUB_DATABASE_URL", "postgres://environment.example/teamhub")
diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.go
index f1a58956..7db981d2 100644
--- a/apps/teamhub/internal/store/models.go
+++ b/apps/teamhub/internal/store/models.go
@@ -1850,6 +1850,12 @@ type VoiceMediaEpoch struct {
RestartRetryAt pgtype.Timestamptz `json:"restart_retry_at"`
}
+type VoiceProviderKey struct {
+ Provider string `json:"provider"`
+ ApiKeyCiphertext []byte `json:"api_key_ciphertext"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type VoiceSession struct {
ID string `json:"id"`
TenantID string `json:"tenant_id"`
diff --git a/apps/teamhub/internal/store/queries/voice_provider_keys.sql b/apps/teamhub/internal/store/queries/voice_provider_keys.sql
new file mode 100644
index 00000000..7dc73942
--- /dev/null
+++ b/apps/teamhub/internal/store/queries/voice_provider_keys.sql
@@ -0,0 +1,6 @@
+-- name: GetVoiceProviderKey :one
+SELECT api_key_ciphertext FROM voice_provider_keys WHERE provider = $1;
+
+-- name: UpsertVoiceProviderKey :exec
+INSERT INTO voice_provider_keys (provider, api_key_ciphertext) VALUES ($1, $2)
+ON CONFLICT (provider) DO UPDATE SET api_key_ciphertext = excluded.api_key_ciphertext, updated_at = now();
diff --git a/apps/teamhub/internal/store/voice_provider_keys.sql.go b/apps/teamhub/internal/store/voice_provider_keys.sql.go
new file mode 100644
index 00000000..bd76cf4d
--- /dev/null
+++ b/apps/teamhub/internal/store/voice_provider_keys.sql.go
@@ -0,0 +1,36 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.29.0
+// source: voice_provider_keys.sql
+
+package store
+
+import (
+ "context"
+)
+
+const getVoiceProviderKey = `-- name: GetVoiceProviderKey :one
+SELECT api_key_ciphertext FROM voice_provider_keys WHERE provider = $1
+`
+
+func (q *Queries) GetVoiceProviderKey(ctx context.Context, provider string) ([]byte, error) {
+ row := q.db.QueryRow(ctx, getVoiceProviderKey, provider)
+ var api_key_ciphertext []byte
+ err := row.Scan(&api_key_ciphertext)
+ return api_key_ciphertext, err
+}
+
+const upsertVoiceProviderKey = `-- name: UpsertVoiceProviderKey :exec
+INSERT INTO voice_provider_keys (provider, api_key_ciphertext) VALUES ($1, $2)
+ON CONFLICT (provider) DO UPDATE SET api_key_ciphertext = excluded.api_key_ciphertext, updated_at = now()
+`
+
+type UpsertVoiceProviderKeyParams struct {
+ Provider string `json:"provider"`
+ ApiKeyCiphertext []byte `json:"api_key_ciphertext"`
+}
+
+func (q *Queries) UpsertVoiceProviderKey(ctx context.Context, arg UpsertVoiceProviderKeyParams) error {
+ _, err := q.db.Exec(ctx, upsertVoiceProviderKey, arg.Provider, arg.ApiKeyCiphertext)
+ return err
+}
diff --git a/apps/teamhub/internal/voicekey/checker.go b/apps/teamhub/internal/voicekey/checker.go
new file mode 100644
index 00000000..fe532c9f
--- /dev/null
+++ b/apps/teamhub/internal/voicekey/checker.go
@@ -0,0 +1,94 @@
+package voicekey
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+)
+
+// The provider APIs a saved key is checked against. Tests point an
+// HTTPChecker at fakes instead.
+const (
+ DefaultSonioxBaseURL = "https://api.soniox.com"
+ DefaultXAIBaseURL = "https://api.x.ai"
+ checkTimeout = 10 * time.Second
+)
+
+// HTTPChecker checks a key with one authenticated read: Soniox lists one
+// uploaded file, xAI describes the key itself. Neither costs usage.
+type HTTPChecker struct {
+ SonioxBaseURL string
+ XAIBaseURL string
+ Client *http.Client
+}
+
+// NewHTTPChecker checks keys against the real provider APIs.
+func NewHTTPChecker() *HTTPChecker {
+ return &HTTPChecker{
+ SonioxBaseURL: DefaultSonioxBaseURL, XAIBaseURL: DefaultXAIBaseURL,
+ // A key never follows a redirect to another host.
+ Client: &http.Client{Timeout: checkTimeout, CheckRedirect: func(*http.Request, []*http.Request) error {
+ return http.ErrUseLastResponse
+ }},
+ }
+}
+
+// Check returns nil when provider accepts key, ErrRejected when it refuses it
+// and ErrProviderUnavailable otherwise. Errors never carry the key or the
+// provider's response.
+func (c *HTTPChecker) Check(ctx context.Context, provider Provider, key string) error {
+ var endpoint string
+ switch provider {
+ case Soniox:
+ endpoint = strings.TrimRight(c.SonioxBaseURL, "/") + "/v1/files?limit=1"
+ case XAI:
+ endpoint = strings.TrimRight(c.XAIBaseURL, "/") + "/v1/api-key"
+ default:
+ return ErrInvalid
+ }
+ ctx, cancel := context.WithTimeout(ctx, checkTimeout)
+ defer cancel()
+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return ErrProviderUnavailable
+ }
+ request.Header.Set("Authorization", "Bearer "+key)
+ request.Header.Set("Accept", "application/json")
+ response, err := c.Client.Do(request)
+ if err != nil {
+ return ErrProviderUnavailable
+ }
+ defer response.Body.Close()
+ body, _ := io.ReadAll(io.LimitReader(response.Body, 64<<10))
+ switch {
+ case response.StatusCode >= 200 && response.StatusCode < 300:
+ if provider == XAI && xaiKeyBlocked(body) {
+ return ErrRejected
+ }
+ return nil
+ // The request carries nothing but the key, so xAI's 400 for a malformed
+ // key is a refusal like 401 and 403.
+ case response.StatusCode == http.StatusBadRequest || response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden:
+ return ErrRejected
+ default:
+ return ErrProviderUnavailable
+ }
+}
+
+// xaiKeyBlocked reads only the flags xAI sets on a key it would refuse: a key
+// can be described with 200 and still be blocked or disabled. An unreadable
+// body or absent flags accept the key; the body is never logged or returned.
+func xaiKeyBlocked(body []byte) bool {
+ var flags struct {
+ APIKeyBlocked bool `json:"api_key_blocked"`
+ APIKeyDisabled bool `json:"api_key_disabled"`
+ TeamBlocked bool `json:"team_blocked"`
+ }
+ if json.Unmarshal(body, &flags) != nil {
+ return false
+ }
+ return flags.APIKeyBlocked || flags.APIKeyDisabled || flags.TeamBlocked
+}
diff --git a/apps/teamhub/internal/voicekey/checker_test.go b/apps/teamhub/internal/voicekey/checker_test.go
new file mode 100644
index 00000000..4427e436
--- /dev/null
+++ b/apps/teamhub/internal/voicekey/checker_test.go
@@ -0,0 +1,84 @@
+package voicekey
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestHTTPCheckerAsksEachProviderWithTheKey(t *testing.T) {
+ for _, tc := range []struct {
+ provider Provider
+ path string
+ }{{Soniox, "/v1/files"}, {XAI, "/v1/api-key"}} {
+ t.Run(string(tc.provider), func(t *testing.T) {
+ for _, status := range []struct {
+ code int
+ want error
+ }{
+ {http.StatusOK, nil},
+ {http.StatusBadRequest, ErrRejected},
+ {http.StatusUnauthorized, ErrRejected},
+ {http.StatusForbidden, ErrRejected},
+ {http.StatusTooManyRequests, ErrProviderUnavailable},
+ {http.StatusInternalServerError, ErrProviderUnavailable},
+ {http.StatusBadGateway, ErrProviderUnavailable},
+ } {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != tc.path || r.Header.Get("Authorization") != "Bearer provider-secret" {
+ t.Errorf("request %s %s auth=%q", r.Method, r.URL.Path, r.Header.Get("Authorization"))
+ }
+ w.WriteHeader(status.code)
+ }))
+ checker := &HTTPChecker{SonioxBaseURL: server.URL, XAIBaseURL: server.URL, Client: server.Client()}
+ if err := checker.Check(t.Context(), tc.provider, "provider-secret"); !errors.Is(err, status.want) || (status.want == nil && err != nil) {
+ t.Fatalf("HTTP %d: Check = %v, want %v", status.code, err, status.want)
+ }
+ server.Close()
+ }
+ })
+ }
+}
+
+func TestHTTPCheckerUnreachableProvider(t *testing.T) {
+ server := httptest.NewServer(http.NotFoundHandler())
+ server.Close()
+ checker := &HTTPChecker{SonioxBaseURL: server.URL, XAIBaseURL: server.URL, Client: http.DefaultClient}
+ err := checker.Check(t.Context(), Soniox, "provider-secret")
+ if !errors.Is(err, ErrProviderUnavailable) || err.Error() != ErrProviderUnavailable.Error() {
+ t.Fatalf("Check = %v, want only ErrProviderUnavailable", err)
+ }
+}
+
+func TestNewHTTPCheckerUsesTheProviderAPIs(t *testing.T) {
+ checker := NewHTTPChecker()
+ if checker.SonioxBaseURL != "https://api.soniox.com" || checker.XAIBaseURL != "https://api.x.ai" || checker.Client.Timeout == 0 {
+ t.Fatalf("checker = %+v", checker)
+ }
+}
+
+// xAI describes a blocked or disabled key with 200; only its flags are read.
+func TestHTTPCheckerRejectsBlockedXAIKeys(t *testing.T) {
+ for _, tc := range []struct {
+ body string
+ want error
+ }{
+ {`{"api_key_blocked":true,"name":"k"}`, ErrRejected},
+ {`{"api_key_disabled":true}`, ErrRejected},
+ {`{"team_blocked":true}`, ErrRejected},
+ {`{"api_key_blocked":false,"api_key_disabled":false,"team_blocked":false}`, nil},
+ {`{"name":"k"}`, nil},
+ {`not json`, nil},
+ } {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(tc.body))
+ }))
+ checker := &HTTPChecker{XAIBaseURL: server.URL, Client: server.Client()}
+ err := checker.Check(t.Context(), XAI, "provider-secret")
+ server.Close()
+ if !errors.Is(err, tc.want) || (tc.want == nil && err != nil) {
+ t.Fatalf("%s: Check = %v, want %v", tc.body, err, tc.want)
+ }
+ }
+}
diff --git a/apps/teamhub/internal/voicekey/voicekey.go b/apps/teamhub/internal/voicekey/voicekey.go
new file mode 100644
index 00000000..fe99a153
--- /dev/null
+++ b/apps/teamhub/internal/voicekey/voicekey.go
@@ -0,0 +1,177 @@
+// Package voicekey resolves the Soniox and xAI keys voice runs on: a
+// deployment's environment key, else one saved in the product, sealed with the
+// secret box. Keys are read from the database at each use, so a save takes
+// effect at once on every TeamHub replica without a restart.
+package voicekey
+
+import (
+ "context"
+ "crypto/sha256"
+ "errors"
+ "log/slog"
+ "strings"
+ "sync"
+ "unicode"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/secretbox"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// Provider names one voice provider; the values are the contract's.
+type Provider string
+
+// The providers: Soniox transcribes, xAI runs Live.
+const (
+ Soniox Provider = "soniox"
+ XAI Provider = "xai"
+)
+
+// Valid reports whether p is a known provider.
+func (p Provider) Valid() bool { return p == Soniox || p == XAI }
+
+// Where a provider's effective key comes from.
+const (
+ SourceNone = "none"
+ SourceEnvironment = "environment"
+ SourceStored = "stored"
+)
+
+// MaxKeyBytes bounds a saved key.
+const MaxKeyBytes = 512
+
+// Save's refusals; the handler maps each to its error code.
+var (
+ ErrInvalid = errors.New("the voice provider API key is invalid")
+ ErrFromEnvironment = errors.New("the voice provider API key is set by the deployment")
+ ErrStorageMissing = errors.New("the deployment has no secret encryption key")
+ ErrVoiceOff = errors.New("voice media is off in this deployment")
+ ErrRejected = errors.New("the voice provider rejected the API key")
+ ErrProviderUnavailable = errors.New("the voice provider could not be reached")
+)
+
+// Status reports where a provider's key comes from and whether a user may save
+// one. The key itself is never part of it.
+type Status struct {
+ Source string
+ CanSave bool
+}
+
+// Checker asks a provider whether it accepts key, with one cheap
+// authenticated request. It returns ErrRejected or ErrProviderUnavailable.
+type Checker interface {
+ Check(ctx context.Context, provider Provider, key string) error
+}
+
+// Store is the key table; *store.Queries implements it.
+type Store interface {
+ GetVoiceProviderKey(ctx context.Context, provider string) ([]byte, error)
+ UpsertVoiceProviderKey(ctx context.Context, arg store.UpsertVoiceProviderKeyParams) error
+}
+
+// Config is what the deployment decides about voice keys.
+type Config struct {
+ // Enabled is TEAMHUB_VOICE_MEDIA; off resolves no key at all.
+ Enabled bool
+ // Environment holds each provider's environment key; empty is unset.
+ Environment map[Provider]string
+ // Box seals saved keys; nil means keys cannot be saved or read.
+ Box *secretbox.Box
+}
+
+// Service resolves and saves voice provider keys.
+type Service struct {
+ store Store
+ checker Checker
+ cfg Config
+ logger *slog.Logger
+
+ mu sync.Mutex
+ // unreadable is the digest of the last row per provider that would not
+ // open, so its warning is logged once.
+ unreadable map[Provider][sha256.Size]byte
+}
+
+// New returns a Service over keys. A nil logger logs to slog.Default.
+func New(keys Store, checker Checker, cfg Config, logger *slog.Logger) *Service {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &Service{store: keys, checker: checker, cfg: cfg, logger: logger, unreadable: map[Provider][sha256.Size]byte{}}
+}
+
+// Enabled reports whether this deployment can run voice.
+func (s *Service) Enabled() bool { return s.cfg.Enabled }
+
+// Effective returns the key provider runs on now, or "" when it has none.
+func (s *Service) Effective(ctx context.Context, provider Provider) (string, error) {
+ key, _, err := s.resolve(ctx, provider)
+ return key, err
+}
+
+// Status reports where provider's key comes from and whether one can be saved.
+func (s *Service) Status(ctx context.Context, provider Provider) (Status, error) {
+ _, source, err := s.resolve(ctx, provider)
+ if err != nil {
+ return Status{}, err
+ }
+ return Status{Source: source, CanSave: s.cfg.Enabled && s.cfg.Box != nil && source != SourceEnvironment}, nil
+}
+
+func (s *Service) resolve(ctx context.Context, provider Provider) (string, string, error) {
+ if !s.cfg.Enabled || !provider.Valid() {
+ return "", SourceNone, nil
+ }
+ if key := strings.TrimSpace(s.cfg.Environment[provider]); key != "" {
+ return key, SourceEnvironment, nil
+ }
+ if s.cfg.Box == nil {
+ return "", SourceNone, nil
+ }
+ sealed, err := s.store.GetVoiceProviderKey(ctx, string(provider))
+ if errors.Is(err, pgx.ErrNoRows) {
+ return "", SourceNone, nil
+ }
+ if err != nil {
+ return "", "", err
+ }
+ if key, openErr := s.cfg.Box.Open(sealed); openErr == nil {
+ return string(key), SourceStored, nil
+ }
+ // A key sealed under another encryption key is unusable; voice treats the
+ // provider as unconfigured so a new save replaces it. Keys are read on
+ // every use, so each unreadable row is logged once, not on every read.
+ digest := sha256.Sum256(sealed)
+ s.mu.Lock()
+ logged := s.unreadable[provider] == digest
+ s.unreadable[provider] = digest
+ s.mu.Unlock()
+ if !logged {
+ s.logger.Warn("voice.provider_key_unreadable", "provider", string(provider))
+ }
+ return "", SourceNone, nil
+}
+
+// Save checks key with the provider, then seals and stores it. Saving the same
+// key again rewrites the one row; of concurrent saves the last one wins.
+func (s *Service) Save(ctx context.Context, provider Provider, key string) error {
+ key = strings.TrimSpace(key)
+ switch {
+ case !provider.Valid() || key == "" || len(key) > MaxKeyBytes || strings.IndexFunc(key, unicode.IsSpace) >= 0 || strings.IndexFunc(key, unicode.IsControl) >= 0:
+ return ErrInvalid
+ case !s.cfg.Enabled:
+ return ErrVoiceOff
+ case strings.TrimSpace(s.cfg.Environment[provider]) != "":
+ return ErrFromEnvironment
+ case s.cfg.Box == nil:
+ return ErrStorageMissing
+ }
+ if err := s.checker.Check(ctx, provider, key); err != nil {
+ return err
+ }
+ sealed, err := s.cfg.Box.Seal([]byte(key))
+ if err != nil {
+ return err
+ }
+ return s.store.UpsertVoiceProviderKey(ctx, store.UpsertVoiceProviderKeyParams{Provider: string(provider), ApiKeyCiphertext: sealed})
+}
diff --git a/apps/teamhub/internal/voicekey/voicekey_test.go b/apps/teamhub/internal/voicekey/voicekey_test.go
new file mode 100644
index 00000000..bd2a701f
--- /dev/null
+++ b/apps/teamhub/internal/voicekey/voicekey_test.go
@@ -0,0 +1,206 @@
+package voicekey
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "errors"
+ "log/slog"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/secretbox"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+type memoryStore struct {
+ mu sync.Mutex
+ rows map[string][]byte
+}
+
+func (m *memoryStore) GetVoiceProviderKey(_ context.Context, provider string) ([]byte, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ sealed, ok := m.rows[provider]
+ if !ok {
+ return nil, pgx.ErrNoRows
+ }
+ return sealed, nil
+}
+
+func (m *memoryStore) UpsertVoiceProviderKey(_ context.Context, arg store.UpsertVoiceProviderKeyParams) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.rows == nil {
+ m.rows = map[string][]byte{}
+ }
+ m.rows[arg.Provider] = arg.ApiKeyCiphertext
+ return nil
+}
+
+type checkerFunc func(context.Context, Provider, string) error
+
+func (f checkerFunc) Check(ctx context.Context, provider Provider, key string) error {
+ return f(ctx, provider, key)
+}
+
+var accept = checkerFunc(func(context.Context, Provider, string) error { return nil })
+
+func testBox(t *testing.T, fill byte) *secretbox.Box {
+ t.Helper()
+ box, err := secretbox.New(base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{fill}, 32)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return box
+}
+
+func TestSaveSealsAndResolvesTheStoredKey(t *testing.T) {
+ keys := &memoryStore{}
+ service := New(keys, accept, Config{Enabled: true, Box: testBox(t, 1)}, nil)
+ if status, err := service.Status(t.Context(), Soniox); err != nil || status != (Status{Source: SourceNone, CanSave: true}) {
+ t.Fatalf("status before save = %+v, %v", status, err)
+ }
+ for range 2 {
+ if err := service.Save(t.Context(), Soniox, " soniox-secret "); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if len(keys.rows) != 1 || bytes.Contains(keys.rows["soniox"], []byte("soniox-secret")) {
+ t.Fatalf("rows = %d, sealed row holds the plaintext or is missing", len(keys.rows))
+ }
+ if key, err := service.Effective(t.Context(), Soniox); err != nil || key != "soniox-secret" {
+ t.Fatalf("Effective = %q, %v", key, err)
+ }
+ if status, err := service.Status(t.Context(), Soniox); err != nil || status != (Status{Source: SourceStored, CanSave: true}) {
+ t.Fatalf("status after save = %+v, %v", status, err)
+ }
+ if key, _ := service.Effective(t.Context(), XAI); key != "" {
+ t.Fatal("saving Soniox resolved an xAI key")
+ }
+}
+
+func TestEnvironmentKeyWinsOverAStoredKey(t *testing.T) {
+ keys := &memoryStore{}
+ box := testBox(t, 1)
+ if err := New(keys, accept, Config{Enabled: true, Box: box}, nil).Save(t.Context(), XAI, "stored-key"); err != nil {
+ t.Fatal(err)
+ }
+ service := New(keys, accept, Config{Enabled: true, Box: box, Environment: map[Provider]string{XAI: "environment-key"}}, nil)
+ if key, _ := service.Effective(t.Context(), XAI); key != "environment-key" {
+ t.Fatalf("Effective = %q, want the environment key", key)
+ }
+ if status, _ := service.Status(t.Context(), XAI); status != (Status{Source: SourceEnvironment}) {
+ t.Fatalf("status = %+v", status)
+ }
+ if err := service.Save(t.Context(), XAI, "another-key"); !errors.Is(err, ErrFromEnvironment) {
+ t.Fatalf("Save = %v, want ErrFromEnvironment", err)
+ }
+}
+
+func TestSaveRefusals(t *testing.T) {
+ rejecting := checkerFunc(func(context.Context, Provider, string) error { return ErrRejected })
+ unreachable := checkerFunc(func(context.Context, Provider, string) error { return ErrProviderUnavailable })
+ for _, tc := range []struct {
+ name string
+ cfg Config
+ checker Checker
+ provider Provider
+ key string
+ want error
+ canSave bool
+ }{
+ {"empty key", Config{Enabled: true, Box: testBox(t, 1)}, accept, Soniox, " ", ErrInvalid, true},
+ {"long key", Config{Enabled: true, Box: testBox(t, 1)}, accept, Soniox, strings.Repeat("k", MaxKeyBytes+1), ErrInvalid, true},
+ {"newline inside", Config{Enabled: true, Box: testBox(t, 1)}, accept, Soniox, "abc\ndef", ErrInvalid, true},
+ {"space inside", Config{Enabled: true, Box: testBox(t, 1)}, accept, Soniox, "abc def", ErrInvalid, true},
+ {"control character inside", Config{Enabled: true, Box: testBox(t, 1)}, accept, XAI, "abc\x00def", ErrInvalid, true},
+ {"unknown provider", Config{Enabled: true, Box: testBox(t, 1)}, accept, "openai", "key", ErrInvalid, true},
+ {"no encryption key", Config{Enabled: true}, accept, Soniox, "key", ErrStorageMissing, false},
+ {"voice off", Config{Box: testBox(t, 1)}, accept, Soniox, "key", ErrVoiceOff, false},
+ {"rejected", Config{Enabled: true, Box: testBox(t, 1)}, rejecting, Soniox, "key", ErrRejected, true},
+ {"unreachable", Config{Enabled: true, Box: testBox(t, 1)}, unreachable, XAI, "key", ErrProviderUnavailable, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ keys := &memoryStore{}
+ service := New(keys, tc.checker, tc.cfg, nil)
+ if err := service.Save(t.Context(), tc.provider, tc.key); !errors.Is(err, tc.want) {
+ t.Fatalf("Save = %v, want %v", err, tc.want)
+ }
+ if len(keys.rows) != 0 {
+ t.Fatal("a refused save stored a row")
+ }
+ if status, _ := service.Status(t.Context(), Soniox); status.CanSave != tc.canSave {
+ t.Fatalf("CanSave = %v, want %v", status.CanSave, tc.canSave)
+ }
+ })
+ }
+}
+
+func TestVoiceOffResolvesNoKey(t *testing.T) {
+ keys := &memoryStore{}
+ box := testBox(t, 1)
+ if err := New(keys, accept, Config{Enabled: true, Box: box}, nil).Save(t.Context(), Soniox, "stored-key"); err != nil {
+ t.Fatal(err)
+ }
+ service := New(keys, accept, Config{Box: box, Environment: map[Provider]string{XAI: "environment-key"}}, nil)
+ for _, provider := range []Provider{Soniox, XAI} {
+ if key, _ := service.Effective(t.Context(), provider); key != "" {
+ t.Fatalf("%s resolved a key with voice off", provider)
+ }
+ if status, _ := service.Status(t.Context(), provider); status != (Status{Source: SourceNone}) {
+ t.Fatalf("%s status = %+v", provider, status)
+ }
+ }
+}
+
+// A key sealed under another encryption key reads as absent, so saving a new
+// one repairs the deployment; the log names the provider and never the key.
+func TestUnreadableStoredKeyIsAbsent(t *testing.T) {
+ keys := &memoryStore{}
+ if err := New(keys, accept, Config{Enabled: true, Box: testBox(t, 1)}, nil).Save(t.Context(), Soniox, "old-secret"); err != nil {
+ t.Fatal(err)
+ }
+ var logs bytes.Buffer
+ service := New(keys, accept, Config{Enabled: true, Box: testBox(t, 2)}, slog.New(slog.NewJSONHandler(&logs, nil)))
+ for range 3 {
+ if key, err := service.Effective(t.Context(), Soniox); err != nil || key != "" {
+ t.Fatalf("Effective = %q, %v", key, err)
+ }
+ }
+ if status, _ := service.Status(t.Context(), Soniox); status != (Status{Source: SourceNone, CanSave: true}) {
+ t.Fatalf("status = %+v", status)
+ }
+ if strings.Count(logs.String(), "voice.provider_key_unreadable") != 1 || strings.Contains(logs.String(), "old-secret") {
+ t.Fatalf("repeated reads must log once: %s", logs.String())
+ }
+ // Another unreadable row is a new fact and is logged again.
+ if err := New(keys, accept, Config{Enabled: true, Box: testBox(t, 1)}, nil).Save(t.Context(), Soniox, "newer-secret"); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = service.Effective(t.Context(), Soniox)
+ if strings.Count(logs.String(), "voice.provider_key_unreadable") != 2 {
+ t.Fatalf("a new unreadable row was not logged: %s", logs.String())
+ }
+}
+
+// Concurrent saves keep one row per provider; the last write wins.
+func TestConcurrentSavesKeepOneRow(t *testing.T) {
+ keys := &memoryStore{}
+ service := New(keys, accept, Config{Enabled: true, Box: testBox(t, 1)}, nil)
+ var wg sync.WaitGroup
+ for _, key := range []string{"first-key", "second-key", "third-key"} {
+ wg.Go(func() {
+ if err := service.Save(context.Background(), Soniox, key); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+ wg.Wait()
+ key, _ := service.Effective(t.Context(), Soniox)
+ if len(keys.rows) != 1 || (key != "first-key" && key != "second-key" && key != "third-key") {
+ t.Fatalf("rows=%d key=%q", len(keys.rows), key)
+ }
+}
diff --git a/apps/teamhub/internal/voicemedia/archive_ready_test.go b/apps/teamhub/internal/voicemedia/archive_ready_test.go
new file mode 100644
index 00000000..a942d31d
--- /dev/null
+++ b/apps/teamhub/internal/voicemedia/archive_ready_test.go
@@ -0,0 +1,38 @@
+package voicemedia
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicetranscription"
+)
+
+// A transient key-read failure must fail the materialize step so River
+// retries it; reading it as "no key" would skip saving the source audio and
+// lose archive recovery for good.
+func TestArchiveTranscriberReadinessReturnsKeyReadFailures(t *testing.T) {
+ readFailure := errors.New("database unavailable")
+ for _, tc := range []struct {
+ name string
+ key func(context.Context) (string, error)
+ ready bool
+ err error
+ }{
+ {"saved key", func(context.Context) (string, error) { return "key", nil }, true, nil},
+ {"no key", func(context.Context) (string, error) { return "", nil }, false, nil},
+ {"key read failed", func(context.Context) (string, error) { return "", readFailure }, false, readFailure},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ service := New(nil, nil, nil)
+ service.SetArchiveTranscriber(voicetranscription.NewKeyedSonioxTranscriber(tc.key, voicetranscription.SonioxConfig{}), func(text string) string { return text })
+ ready, err := service.archiveTranscriberReady(t.Context())
+ if ready != tc.ready || !errors.Is(err, tc.err) {
+ t.Fatalf("ready=%v err=%v", ready, err)
+ }
+ })
+ }
+ if ready, err := New(nil, nil, nil).archiveTranscriberReady(t.Context()); ready || err != nil {
+ t.Fatalf("without a transcriber: ready=%v err=%v", ready, err)
+ }
+}
diff --git a/apps/teamhub/internal/voicemedia/hls_materializer.go b/apps/teamhub/internal/voicemedia/hls_materializer.go
index e4117120..1c109021 100644
--- a/apps/teamhub/internal/voicemedia/hls_materializer.go
+++ b/apps/teamhub/internal/voicemedia/hls_materializer.go
@@ -52,6 +52,10 @@ type HLSMaterializer struct {
ffprobe string
}
+// ErrMediaToolsMissing means ffmpeg or ffprobe is not on PATH, so this
+// computer cannot materialize recordings.
+var ErrMediaToolsMissing = errors.New("voice media tools are missing")
+
func NewHLSMaterializer(
pool *pgxpool.Pool,
objects artifactstore.ObjectStore,
@@ -59,11 +63,11 @@ func NewHLSMaterializer(
) (*HLSMaterializer, error) {
ffmpeg, err := exec.LookPath("ffmpeg")
if err != nil {
- return nil, errors.New("ffmpeg is required for voice media materialization")
+ return nil, fmt.Errorf("ffmpeg is required for voice media materialization: %w", ErrMediaToolsMissing)
}
ffprobe, err := exec.LookPath("ffprobe")
if err != nil {
- return nil, errors.New("ffprobe is required for voice media validation")
+ return nil, fmt.Errorf("ffprobe is required for voice media validation: %w", ErrMediaToolsMissing)
}
return &HLSMaterializer{
queries: store.New(pool), staging: staging, objects: objects,
diff --git a/apps/teamhub/internal/voicemedia/materialize_worker.go b/apps/teamhub/internal/voicemedia/materialize_worker.go
index 8d70dcc7..62b1193d 100644
--- a/apps/teamhub/internal/voicemedia/materialize_worker.go
+++ b/apps/teamhub/internal/voicemedia/materialize_worker.go
@@ -176,7 +176,11 @@ func (s *Service) processMaterialization(ctx context.Context, captureID string)
return ErrCaptureConflict
}
var source store.CaptureMediaOutput
- if s.archiveASR != nil {
+ ready, err := s.archiveTranscriberReady(ctx)
+ if err != nil {
+ return err
+ }
+ if ready {
source, err = s.saveSourceAudio(ctx, job)
if err != nil {
return err
diff --git a/apps/teamhub/internal/voicemedia/service.go b/apps/teamhub/internal/voicemedia/service.go
index 7b8c9429..5fd16883 100644
--- a/apps/teamhub/internal/voicemedia/service.go
+++ b/apps/teamhub/internal/voicemedia/service.go
@@ -39,6 +39,22 @@ func (s *Service) SetArchiveTranscriber(asr voicetranscription.ArchiveTranscribe
s.archiveASR, s.normalizeTranscript = asr, normalize
}
+// archiveTranscriberReady reports whether archive recovery can transcribe
+// now. A transcriber whose provider key is saved while TeamHub runs answers
+// per call; without a key no source audio is kept and no recovery is queued.
+// A failed key read is returned so the job retries.
+func (s *Service) archiveTranscriberReady(ctx context.Context) (bool, error) {
+ if s.archiveASR == nil {
+ return false, nil
+ }
+ if keyed, ok := s.archiveASR.(interface {
+ Ready(context.Context) (bool, error)
+ }); ok {
+ return keyed.Ready(ctx)
+ }
+ return true, nil
+}
+
func (s *Service) SetArchiveRecoveryConcurrency(limit int) {
s.archiveRecoveryConcurrency = limit
}
diff --git a/apps/teamhub/internal/voicetranscription/soniox_keyed.go b/apps/teamhub/internal/voicetranscription/soniox_keyed.go
new file mode 100644
index 00000000..8ef7d7cc
--- /dev/null
+++ b/apps/teamhub/internal/voicetranscription/soniox_keyed.go
@@ -0,0 +1,51 @@
+package voicetranscription
+
+import (
+ "context"
+ "errors"
+)
+
+// ErrProviderNotConfigured is returned while no Soniox key is in effect.
+var ErrProviderNotConfigured = errors.New("voice transcription provider has no API key")
+
+// KeyedSonioxTranscriber reads the Soniox key at each call, so a key saved
+// while TeamHub runs applies to the next block and every replica agrees.
+type KeyedSonioxTranscriber struct {
+ key func(context.Context) (string, error)
+ cfg SonioxConfig
+}
+
+// NewKeyedSonioxTranscriber transcribes with cfg and the key key returns; an
+// empty key means Soniox is not configured. cfg.APIKey is ignored.
+func NewKeyedSonioxTranscriber(key func(context.Context) (string, error), cfg SonioxConfig) *KeyedSonioxTranscriber {
+ return &KeyedSonioxTranscriber{key: key, cfg: cfg}
+}
+
+// Ready reports whether a Soniox key is in effect now. A failed key read is
+// an error, not "no key", so the caller retries instead of giving up on
+// archive recovery.
+func (t *KeyedSonioxTranscriber) Ready(ctx context.Context) (bool, error) {
+ key, err := t.key(ctx)
+ if err != nil {
+ return false, err
+ }
+ return key != "", nil
+}
+
+// TranscribeArchivePCM transcribes one block with the key in effect now.
+func (t *KeyedSonioxTranscriber) TranscribeArchivePCM(ctx context.Context, pcm []byte) ([]StreamingResult, error) {
+ key, err := t.key(ctx)
+ if err != nil {
+ return nil, errors.Join(ErrProviderFailure, err)
+ }
+ if key == "" {
+ return nil, ErrProviderNotConfigured
+ }
+ cfg := t.cfg
+ cfg.APIKey = key
+ transcriber, err := NewSonioxTranscriber(cfg)
+ if err != nil {
+ return nil, err
+ }
+ return transcriber.TranscribeArchivePCM(ctx, pcm)
+}
diff --git a/apps/teamhub/internal/voicetranscription/soniox_keyed_test.go b/apps/teamhub/internal/voicetranscription/soniox_keyed_test.go
new file mode 100644
index 00000000..f43bc3f3
--- /dev/null
+++ b/apps/teamhub/internal/voicetranscription/soniox_keyed_test.go
@@ -0,0 +1,70 @@
+package voicetranscription
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+)
+
+// The keyed transcriber reads the key at each call: no key means no provider
+// request at all, and a key saved later is used by the next block.
+func TestKeyedSonioxTranscriberReadsTheKeyAtEachCall(t *testing.T) {
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ if r.Header.Get("Authorization") != "Bearer saved-later" {
+ t.Errorf("Authorization = %q", r.Header.Get("Authorization"))
+ }
+ switch r.URL.Path {
+ case "/v1/files":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "file-1"})
+ case "/v1/transcriptions/tx-1/transcript":
+ _ = json.NewEncoder(w).Encode(map[string]any{"text": "", "tokens": []any{}})
+ default:
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "tx-1", "status": "completed"})
+ }
+ }))
+ defer server.Close()
+ var key atomic.Value
+ key.Store("")
+ transcriber := NewKeyedSonioxTranscriber(func(context.Context) (string, error) {
+ return key.Load().(string), nil
+ }, SonioxConfig{BaseURL: server.URL, HTTPClient: server.Client()})
+
+ if ready, err := transcriber.Ready(t.Context()); ready || err != nil {
+ t.Fatalf("Ready without a key = %v, %v", ready, err)
+ }
+ if _, err := transcriber.TranscribeArchivePCM(t.Context(), make([]byte, 3200)); !errors.Is(err, ErrProviderNotConfigured) {
+ t.Fatalf("TranscribeArchivePCM without a key = %v", err)
+ }
+ if requests.Load() != 0 {
+ t.Fatalf("%d Soniox requests without a key", requests.Load())
+ }
+ key.Store("saved-later")
+ if ready, err := transcriber.Ready(t.Context()); !ready || err != nil {
+ t.Fatalf("Ready after a key was saved = %v, %v", ready, err)
+ }
+ if _, err := transcriber.TranscribeArchivePCM(t.Context(), make([]byte, 3200)); err != nil {
+ t.Fatal(err)
+ }
+ if requests.Load() == 0 {
+ t.Fatal("no Soniox request with a key")
+ }
+}
+
+func TestKeyedSonioxTranscriberKeyReadFailure(t *testing.T) {
+ transcriber := NewKeyedSonioxTranscriber(func(context.Context) (string, error) {
+ return "", errors.New("database unavailable")
+ }, SonioxConfig{})
+ // A failed read is an error, not "no key", so materialization retries.
+ if ready, err := transcriber.Ready(t.Context()); ready || err == nil {
+ t.Fatalf("Ready while the key cannot be read = %v, %v", ready, err)
+ }
+ if _, err := transcriber.TranscribeArchivePCM(t.Context(), make([]byte, 3200)); !errors.Is(err, ErrProviderFailure) {
+ t.Fatalf("TranscribeArchivePCM = %v, want a retryable provider failure", err)
+ }
+}
diff --git a/apps/teamhub/migrations/00863_voice_provider_keys.sql b/apps/teamhub/migrations/00863_voice_provider_keys.sql
new file mode 100644
index 00000000..8b257808
--- /dev/null
+++ b/apps/teamhub/migrations/00863_voice_provider_keys.sql
@@ -0,0 +1,13 @@
+-- +goose Up
+-- Voice provider API keys saved in the product, one row per provider, sealed
+-- with TEAMHUB_SECRET_ENCRYPTION_KEY like composio_settings. TeamHub reads a
+-- row each time voice needs the key, so every replica sees a save at once; a
+-- provider's environment variable wins over its row.
+CREATE TABLE voice_provider_keys (
+ provider text PRIMARY KEY CHECK (provider IN ('soniox', 'xai')),
+ api_key_ciphertext bytea NOT NULL,
+ updated_at timestamp with time zone DEFAULT now() NOT NULL
+);
+
+-- +goose Down
+DROP TABLE voice_provider_keys;
diff --git a/apps/teamhub/tests/integration/livekit_voice_recovery_test.go b/apps/teamhub/tests/integration/livekit_voice_recovery_test.go
index 83ffff32..e0003087 100644
--- a/apps/teamhub/tests/integration/livekit_voice_recovery_test.go
+++ b/apps/teamhub/tests/integration/livekit_voice_recovery_test.go
@@ -28,7 +28,9 @@ func TestLiveKitStartEventProjectsCaptureIdentity(t *testing.T) {
t.Skip("ffmpeg required")
}
env, alice, _ := newHardwareVoiceCaptureEnvWithStorageAndLimitsAndConfig(t, 1<<20, 1<<30, func(cfg *config.Config) {
- cfg.Voice.SonioxAPIKey = "test-soniox-key"
+ cfg.Voice.MediaEnabled = true
+ cfg.Voice.RuntimeToken = "voice-test-service-token"
+ cfg.Voice.LiveKitAPIURL = "http://127.0.0.1:17880"
})
q := store.New(env.pool)
roomID := env.createRoom(alice, acmeTenant, "Voice transcript identity", "voice-transcript-identity")
diff --git a/apps/teamhub/tests/integration/voice_provider_keys_test.go b/apps/teamhub/tests/integration/voice_provider_keys_test.go
new file mode 100644
index 00000000..45d11510
--- /dev/null
+++ b/apps/teamhub/tests/integration/voice_provider_keys_test.go
@@ -0,0 +1,226 @@
+package integration_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/app"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicemedia"
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
+)
+
+const voiceKeyRuntimeToken = "voice-key-runtime-token"
+
+type voiceKeyChecker struct {
+ mu sync.Mutex
+ seen []string
+}
+
+func (c *voiceKeyChecker) Check(_ context.Context, provider voicekey.Provider, key string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.seen = append(c.seen, string(provider))
+ if strings.HasPrefix(key, "rejected") {
+ return voicekey.ErrRejected
+ }
+ return nil
+}
+
+func withVoiceKeyChecker(checker voicekey.Checker) appOption {
+ return withDeps(func(deps *app.Deps) { deps.VoiceKeyChecker = checker })
+}
+
+// newVoiceKeyEnv runs voice over a fake LiveKit API with no environment key
+// and a secret encryption key, so provider keys are saved in the product.
+func newVoiceKeyEnv(t *testing.T, checker voicekey.Checker) (*testEnv, *http.Client) {
+ t.Helper()
+ providerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/protobuf")
+ w.WriteHeader(http.StatusOK)
+ }))
+ registerIntegrationServerCleanup(t, providerAPI)
+ media := &dictationTestMedia{}
+ env, alice, _ := newHardwareVoiceCaptureEnvWithStorageAndLimitsAndConfig(t, 1<<20, 1<<30, func(cfg *config.Config) {
+ cfg.Voice.SonioxAPIKey, cfg.Voice.XaiAPIKey = "", ""
+ cfg.Voice.RuntimeToken = voiceKeyRuntimeToken
+ cfg.ExternalApps.SecretEncryptionKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{9}, 32))
+ }, withVoiceMedia(media), withVoiceKeyChecker(checker))
+ provider, err := voicemedia.NewLiveKitProvider(voicemedia.LiveKitConfig{APIURL: providerAPI.URL, PublicURL: providerAPI.URL, APIKey: "test", APISecret: "test"}, env.pool)
+ if err != nil {
+ t.Fatal(err)
+ }
+ media.Plane = voicemedia.New(env.pool, provider, nil)
+ return env, alice
+}
+
+func voiceMediaPolicy(t *testing.T, env *testEnv, client *http.Client) httpapi.VoiceMediaPolicy {
+ t.Helper()
+ status, _, body := env.request(client, http.MethodGet, "/v0/tenants/"+acmeTenant+"/voice-media-policy", nil, "")
+ if status != http.StatusOK {
+ t.Fatalf("voice media policy=%d %s", status, body)
+ }
+ var policy httpapi.VoiceMediaPolicy
+ decode(t, body, &policy)
+ return policy
+}
+
+func runtimeVoiceKeys(t *testing.T, env *testEnv) string {
+ t.Helper()
+ request, err := http.NewRequestWithContext(t.Context(), http.MethodGet, env.server.URL+"/internal/v1/voice/provider-keys", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Authorization", "Bearer "+voiceKeyRuntimeToken)
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ var body bytes.Buffer
+ if _, err := body.ReadFrom(response.Body); err != nil {
+ t.Fatal(err)
+ }
+ if response.StatusCode != http.StatusOK || response.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("runtime keys=%d cache=%q %s", response.StatusCode, response.Header.Get("Cache-Control"), body.String())
+ }
+ return strings.TrimSpace(body.String())
+}
+
+// Saving a key turns its voice feature on at once, without a restart: the
+// policy, session creation and the Voice Runtime key read all follow the
+// row. The row is sealed, a repeated save keeps one row, and the key is never
+// echoed to the browser.
+func TestVoiceProviderKeySaveTurnsVoiceOnWithoutRestart(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ checker := &voiceKeyChecker{}
+ env, alice := newVoiceKeyEnv(t, checker)
+ roomID := env.createRoom(alice, acmeTenant, "Voice keys", "voice-keys-room")
+
+ policy := voiceMediaPolicy(t, env, alice)
+ if policy.VoiceAvailable == nil || !*policy.VoiceAvailable || policy.VoiceMediaSupported || *policy.LiveSupported ||
+ policy.SonioxKey == nil || *policy.SonioxKey != (httpapi.VoiceProviderKeyStatus{Source: httpapi.None, CanSave: true}) {
+ t.Fatalf("policy before save=%+v", policy)
+ }
+ if status, _, body := env.request(alice, http.MethodPost, "/v0/rooms/"+roomID+"/voice-sessions", map[string]any{"purpose": "hardware_control"}, "recording-before-key"); status != http.StatusServiceUnavailable {
+ t.Fatalf("recording without a key=%d %s", status, body)
+ }
+ if keys := runtimeVoiceKeys(t, env); keys != `{}` {
+ t.Fatalf("runtime keys before save=%s", keys)
+ }
+
+ if status, _, body := env.request(alice, http.MethodPut, "/v0/voice-provider-keys/soniox", map[string]any{"api_key": "rejected-soniox-key"}, ""); status != http.StatusBadRequest || !strings.Contains(string(body), "VOICE_KEY_REJECTED") {
+ t.Fatalf("rejected save=%d %s", status, body)
+ }
+ for range 2 {
+ status, _, body := env.request(alice, http.MethodPut, "/v0/voice-provider-keys/soniox", map[string]any{"api_key": " soniox-product-key "}, "")
+ if status != http.StatusOK || strings.Contains(string(body), "soniox-product-key") || strings.TrimSpace(string(body)) != `{"can_save":true,"source":"stored"}` {
+ t.Fatalf("save=%d %s", status, body)
+ }
+ }
+ var rows int
+ var sealed []byte
+ if err := env.pool.QueryRow(t.Context(), `SELECT count(*) OVER (), api_key_ciphertext FROM voice_provider_keys`).Scan(&rows, &sealed); err != nil {
+ t.Fatal(err)
+ }
+ if rows != 1 || bytes.Contains(sealed, []byte("soniox-product-key")) {
+ t.Fatalf("rows=%d, sealed row holds the plaintext", rows)
+ }
+
+ policy = voiceMediaPolicy(t, env, alice)
+ if !policy.VoiceMediaSupported || *policy.LiveSupported || *policy.SonioxKey != (httpapi.VoiceProviderKeyStatus{Source: httpapi.Stored, CanSave: true}) {
+ t.Fatalf("policy after Soniox save=%+v", policy)
+ }
+ if status, _, body := env.request(alice, http.MethodPost, "/v0/rooms/"+roomID+"/voice-sessions", map[string]any{"purpose": "hardware_control"}, "recording-after-key"); status != http.StatusCreated {
+ t.Fatalf("recording after save=%d %s", status, body)
+ }
+ if keys := runtimeVoiceKeys(t, env); keys != `{"soniox_api_key":"soniox-product-key"}` {
+ t.Fatalf("runtime keys after save=%s", keys)
+ }
+
+ if status, _, body := env.request(alice, http.MethodPut, "/v0/voice-provider-keys/xai", map[string]any{"api_key": "xai-product-key"}, ""); status != http.StatusOK {
+ t.Fatalf("xAI save=%d %s", status, body)
+ }
+ if policy = voiceMediaPolicy(t, env, alice); !*policy.LiveSupported || !*policy.LiveEnabled {
+ t.Fatalf("policy after xAI save=%+v", policy)
+ }
+}
+
+// Concurrent saves of one provider keep one row and the last write wins.
+func TestVoiceProviderKeyConcurrentSavesKeepOneRow(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ env, alice := newVoiceKeyEnv(t, &voiceKeyChecker{})
+ keys := []string{"xai-key-one", "xai-key-two", "xai-key-three", "xai-key-four"}
+ var wg sync.WaitGroup
+ for _, key := range keys {
+ wg.Go(func() {
+ if status, _, body := env.request(alice, http.MethodPut, "/v0/voice-provider-keys/xai", map[string]any{"api_key": key}, ""); status != http.StatusOK {
+ t.Errorf("save %s=%d %s", key, status, body)
+ }
+ })
+ }
+ wg.Wait()
+ if rows := countRows(t, env, `SELECT count(*) FROM voice_provider_keys WHERE provider='xai'`); rows != 1 {
+ t.Fatalf("rows=%d", rows)
+ }
+ got := runtimeVoiceKeys(t, env)
+ found := false
+ for _, key := range keys {
+ found = found || got == `{"xai_api_key":"`+key+`"}`
+ }
+ if !found {
+ t.Fatalf("runtime keys=%s", got)
+ }
+}
+
+// The table accepts only the two providers.
+func TestVoiceProviderKeyTableRejectsUnknownProviders(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ env, _ := newVoiceKeyEnv(t, &voiceKeyChecker{})
+ if _, err := env.pool.Exec(t.Context(), `INSERT INTO voice_provider_keys(provider,api_key_ciphertext) VALUES('openai','\x00')`); err == nil {
+ t.Fatal("an unknown provider was stored")
+ }
+}
+
+// With voice media off voice stays off whatever keys exist: the policy
+// reports nothing, saving answers VOICE_MEDIA_OFF and the Voice Runtime reads
+// no key.
+func TestVoiceProviderKeysWithVoiceMediaOff(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ env, alice, _ := newHardwareVoiceCaptureEnvWithStorageAndLimitsAndConfig(t, 1<<20, 1<<30, func(cfg *config.Config) {
+ cfg.Voice.RuntimeToken = voiceKeyRuntimeToken
+ cfg.Voice.XaiAPIKey = "xai-environment-key"
+ cfg.ExternalApps.SecretEncryptionKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{9}, 32))
+ }, withVoiceKeyChecker(&voiceKeyChecker{}))
+ policy := voiceMediaPolicy(t, env, alice)
+ if policy.VoiceAvailable == nil || *policy.VoiceAvailable || policy.VoiceMediaSupported || *policy.LiveSupported ||
+ *policy.SonioxKey != (httpapi.VoiceProviderKeyStatus{Source: httpapi.None}) || *policy.XaiKey != (httpapi.VoiceProviderKeyStatus{Source: httpapi.None}) {
+ t.Fatalf("policy with voice off=%+v", policy)
+ }
+ if status, _, body := env.request(alice, http.MethodPut, "/v0/voice-provider-keys/soniox", map[string]any{"api_key": "soniox-key"}, ""); status != http.StatusServiceUnavailable || !strings.Contains(string(body), "VOICE_MEDIA_OFF") {
+ t.Fatalf("save with voice off=%d %s", status, body)
+ }
+ if keys := runtimeVoiceKeys(t, env); keys != `{}` {
+ t.Fatalf("runtime keys with voice off=%s", keys)
+ }
+ request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, env.server.URL+"/internal/v1/voice/observations", strings.NewReader(`{}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Authorization", "Bearer "+voiceKeyRuntimeToken)
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = response.Body.Close()
+ if response.StatusCode != http.StatusNotFound {
+ t.Fatalf("voice callback with voice off=%d", response.StatusCode)
+ }
+}
diff --git a/apps/teamhub/tests/integration/voice_test_env_test.go b/apps/teamhub/tests/integration/voice_test_env_test.go
index 2d4f6948..6f07a029 100644
--- a/apps/teamhub/tests/integration/voice_test_env_test.go
+++ b/apps/teamhub/tests/integration/voice_test_env_test.go
@@ -57,6 +57,8 @@ func newHardwareVoiceEnv(
c.ArtifactStorageRoot = storageRoot
c.ArtifactMaxBytes = artifactMaxBytes
c.CaptureMaxBytes = captureMaxBytes
+ // Voice sessions other than Live start only with a Soniox key.
+ c.Voice.SonioxAPIKey = "test-soniox-key"
})
if configure != nil {
configure(&appConfig)
diff --git a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts
index afbb9448..580aaebc 100644
--- a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts
@@ -5185,6 +5185,24 @@ export interface operations {
};
};
401: components["responses"]["VoiceUnauthenticated"];
+ /** @description The keys could not be read (INTERNAL_ERROR). */
+ 500: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["VoiceError"];
+ };
+ };
+ /** @description TeamHub has no voice runtime credential (DEPENDENCY_UNAVAILABLE). */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["VoiceError"];
+ };
+ };
};
};
putVoiceMediaObject: {
diff --git a/contracts/openapi/teamhub-internal/openapi.yaml b/contracts/openapi/teamhub-internal/openapi.yaml
index 77323190..d9eecf56 100644
--- a/contracts/openapi/teamhub-internal/openapi.yaml
+++ b/contracts/openapi/teamhub-internal/openapi.yaml
@@ -803,6 +803,18 @@ paths:
$ref: "#/components/schemas/VoiceRuntimeProviderKeys"
"401":
$ref: "#/components/responses/VoiceUnauthenticated"
+ "500":
+ description: The keys could not be read (INTERNAL_ERROR).
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/VoiceError"
+ "503":
+ description: TeamHub has no voice runtime credential (DEPENDENCY_UNAVAILABLE).
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/VoiceError"
security:
- voiceRuntimeBearer: []
/internal/v1/voice/media-objects:
diff --git a/docs/voice.md b/docs/voice.md
index f301ad3b..d6213d38 100644
--- a/docs/voice.md
+++ b/docs/voice.md
@@ -7,9 +7,18 @@ keep talking to an agent hands-free.**
## Turning voice on
-Voice needs a [Soniox](https://soniox.com) key in `SONIOX_API_KEY` for
-recording and dictation, or an [xAI](https://x.ai) key in `XAI_API_KEY` for
-Grok Live voice mode; either works without the other.
+Voice runs wherever the deployment can run it: TeamHub's
+`TEAMHUB_VOICE_MEDIA` is `on` (the default), `LINGER_SECRET_SEED` is set, and
+`ffmpeg` and `ffprobe` are on `PATH`. `TEAMHUB_VOICE_MEDIA=off`, a missing seed,
+or missing ffmpeg keep voice off; TeamHub still starts and logs
+`voice.media_unavailable` for the last two.
+
+Each feature then needs its provider key: [Soniox](https://soniox.com) for
+recording and dictation, [xAI](https://x.ai) for Grok Live voice mode; either
+works without the other. Set a key in `SONIOX_API_KEY` or `XAI_API_KEY`, or
+save it in the app when voice asks for it. A saved key applies at once,
+without a restart; an environment key wins over a saved one and cannot be
+replaced from the app.
- The Linger app: put the keys in `user.env` in its instance folder
(`~/.simplexai/instances/desktop/`), or type them under Customize → API