Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions server/live_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,19 @@ func (s *Server) handleLiveSession(w http.ResponseWriter, r *http.Request, conve
conversation.Model = &profile.Model
}
}
session := map[string]any{
"model": "gpt-live-1",
"instructions": liveInstructions(profile.VoicePrompt, s.liveSituation(conversation)),
"input": append(history, liveHistoryItem{Type: "message", Role: "developer", Content: []liveHistoryText{{Type: "input_text", Text: liveGreeting}}}),
"delegation": map[string]string{"type": "client"},
}
if profile.Voice != "" {
session["audio"] = map[string]any{
"output": map[string]string{"voice": profile.Voice},
}
}
payload, err := json.Marshal(map[string]any{
"session": map[string]any{
"model": "gpt-live-1",
"instructions": liveInstructions(profile.VoicePrompt, s.liveSituation(conversation)),
"input": append(history, liveHistoryItem{Type: "message", Role: "developer", Content: []liveHistoryText{{Type: "input_text", Text: liveGreeting}}}),
"delegation": map[string]string{"type": "client"},
},
"session": session,
"transport": map[string]string{"type": "webrtc", "sdp": offer.SDP},
})
if err != nil {
Expand Down
28 changes: 18 additions & 10 deletions server/live_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ type liveSessionRequest struct {
Model string `json:"model"`
Instructions string `json:"instructions"`
Input []liveHistoryItem `json:"input"`
Audio *struct {
Output *struct {
Voice string `json:"voice"`
} `json:"output"`
} `json:"audio"`
} `json:"session"`
Transport struct {
SDP string `json:"sdp"`
Expand Down Expand Up @@ -61,7 +66,7 @@ func TestLiveSession(t *testing.T) {
}

const juniper = "You are Juniper. Speak warmly and briefly."
e.want(201, "POST", "/api/profiles", `{"name":"Personal","model":"model-b","voice_prompt":"`+juniper+`"}`)
e.want(201, "POST", "/api/profiles", `{"name":"Personal","model":"model-b","voice":"cedar","voice_prompt":"`+juniper+`"}`)
cwd, model := t.TempDir(), "model-b"
conv, err := e.database.CreateConversation(t.Context(), nil, true, &cwd, &model, db.ConversationOptions{Profile: "Personal"})
if err != nil {
Expand Down Expand Up @@ -95,6 +100,9 @@ func TestLiveSession(t *testing.T) {
if req.Session.Model != "gpt-live-1" || req.Transport.SDP != "v=0\r\nm=audio test" || voicePrompt(req) != juniper {
t.Fatalf("session = %+v", req)
}
if req.Session.Audio == nil || req.Session.Audio.Output == nil || req.Session.Audio.Output.Voice != "cedar" {
t.Fatalf("session audio = %+v, want voice cedar", req.Session.Audio)
}
for _, want := range []string{"Delegation policy:", "Answer yourself first.", "are status questions, not small talk", "Interruption policy:", "Backend state: idle.", "Working directory: " + cwd + ".", "Backend model: model-b."} {
if !strings.Contains(req.Session.Instructions, want) {
t.Errorf("instructions lack %q:\n%s", want, req.Session.Instructions)
Expand All @@ -112,12 +120,12 @@ func TestLiveSession(t *testing.T) {
t.Fatalf("a call asked a model %d times or wrote messages", n)
}

// An edit applies to the next call; "" means no persona.
e.want(200, "PUT", "/api/profiles/Personal", `{"model":"model-b","voice_prompt":""}`)
if req := call(id, ""); strings.Contains(req.Session.Instructions, "voice_guidance") {
t.Errorf("instructions have voice guidance without a voice prompt:\n%s", req.Session.Instructions)
// An edit applies to the next call; "" means no persona or default voice.
e.want(200, "PUT", "/api/profiles/Personal", `{"model":"model-b","voice":"","voice_prompt":""}`)
if req := call(id, ""); strings.Contains(req.Session.Instructions, "voice_guidance") || req.Session.Audio != nil {
t.Errorf("instructions/audio set when cleared:\naudio=%+v\n%s", req.Session.Audio, req.Session.Instructions)
}
e.want(200, "PUT", "/api/profiles/Personal", `{"model":"model-b","voice_prompt":"`+juniper+`"}`)
e.want(200, "PUT", "/api/profiles/Personal", `{"model":"model-b","voice":"cedar","voice_prompt":"`+juniper+`"}`)

// A draft speaks as the profile its first send would start from.
var draft struct {
Expand All @@ -127,15 +135,15 @@ func TestLiveSession(t *testing.T) {
t.Fatal(err)
}
req = call(draft.ConversationID, "")
if voicePrompt(req) != "" {
t.Errorf("the default profile has no voice prompt: %s", req.Session.Instructions)
if voicePrompt(req) != "" || req.Session.Audio != nil {
t.Errorf("the default profile has no voice prompt or custom voice: audio=%+v %s", req.Session.Audio, req.Session.Instructions)
}
if len(req.Session.Input) != 1 || req.Session.Input[0].Role != "developer" {
t.Errorf("empty draft history = %+v", req.Session.Input)
}
req = call(draft.ConversationID, `,"cwd":"`+cwd+`","conversation_options":{"profile":"Personal","thinking_level":"high"}`)
if voicePrompt(req) != juniper || !strings.Contains(req.Session.Instructions, "Backend model: model-b.") || !strings.Contains(req.Session.Instructions, "Working directory: "+cwd+".") {
t.Errorf("draft selection: %s", req.Session.Instructions)
if voicePrompt(req) != juniper || req.Session.Audio == nil || req.Session.Audio.Output == nil || req.Session.Audio.Output.Voice != "cedar" || !strings.Contains(req.Session.Instructions, "Backend model: model-b.") || !strings.Contains(req.Session.Instructions, "Working directory: "+cwd+".") {
t.Errorf("draft selection: audio=%+v %s", req.Session.Audio, req.Session.Instructions)
}
if row, err := e.database.GetConversationByID(t.Context(), draft.ConversationID); err != nil || !row.IsDraft || row.Model != nil {
t.Fatalf("calling changed the draft: %+v", row)
Expand Down
53 changes: 42 additions & 11 deletions server/profiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,42 @@ type Profile struct {
// it are in the project; they don't switch profiles, but move.
Project bool `json:"project"`
Settings
// Voice is the output voice for the profile's live calls; "" uses the
// provider's default (marin). Like VoicePrompt, it belongs to the
// profile, not its Settings.
Voice string `json:"voice"`
// VoicePrompt is how the profile's voice calls speak; "" means no
// persona. It belongs to the profile, not its Settings: conversations
// don't copy it, and a call reads the current one.
VoicePrompt string `json:"voice_prompt"`
}

// storedProfile is a profile's settings column: its Settings and voice prompt.
// storedProfile is a profile's settings column: its Settings, voice, and voice prompt.
type storedProfile struct {
Settings
Voice string `json:"voice,omitempty"`
VoicePrompt string `json:"voice_prompt,omitempty"`
}

const maxVoicePromptRunes = 4000

var liveVoices = []string{
"alloy", "ash", "ballad", "beacon", "bossa", "brise",
"calandria", "cedar", "cinder", "compas", "coral", "delta",
"destello", "echo", "flitz", "gleam", "halo", "harema",
"hornero", "juni", "luciernaga", "marin", "meridian", "nira",
"noeul", "nuri", "pearl", "quartz", "ripple", "sage",
"shida", "shimmer", "sillage", "stone", "tempo", "verse",
"vesper", "willow",
}

func voiceProblem(voice string) string {
if voice != "" && !slices.Contains(liveVoices, voice) {
return fmt.Sprintf("unknown voice %q", voice)
}
return ""
}

// voicePromptProblem says what's wrong with a trimmed voice prompt, or "".
func voicePromptProblem(prompt string) string {
if utf8.RuneCountInString(prompt) > maxVoicePromptRunes {
Expand Down Expand Up @@ -72,6 +94,7 @@ func profileFromRow(row generated.Profile) (Profile, error) {
}
stored.ToolOverrides = orEmpty(stored.ToolOverrides)
p.Settings = stored.Settings
p.Voice = stored.Voice
p.VoicePrompt = stored.VoicePrompt
return p, nil
}
Expand Down Expand Up @@ -169,21 +192,22 @@ func (e profileEcho) problem(p Profile) string {
)
}

func encodeProfile(st Settings, voicePrompt string) string {
b, err := json.Marshal(storedProfile{Settings: st, VoicePrompt: voicePrompt})
func encodeProfile(st Settings, voice, voicePrompt string) string {
b, err := json.Marshal(storedProfile{Settings: st, Voice: voice, VoicePrompt: voicePrompt})
if err != nil {
panic(err) // Settings always marshals.
}
return string(b)
}

// handleCreateProfile handles POST /api/profiles: {name, ...settings,
// voice_prompt}.
// voice, voice_prompt}.
func (s *Server) handleCreateProfile(w http.ResponseWriter, r *http.Request) {
var body struct {
Name string `json:"name"`
profileEcho
Settings
Voice string `json:"voice"`
VoicePrompt string `json:"voice_prompt"`
}
if !decodeStrict(w, r, &body) {
Expand All @@ -194,8 +218,9 @@ func (s *Server) handleCreateProfile(w http.ResponseWriter, r *http.Request) {
http.Error(w, msg, http.StatusBadRequest)
return
}
body.Voice = strings.TrimSpace(body.Voice)
body.VoicePrompt = strings.TrimSpace(body.VoicePrompt)
if msg := voicePromptProblem(body.VoicePrompt); msg != "" {
if msg := cmp.Or(voiceProblem(body.Voice), voicePromptProblem(body.VoicePrompt)); msg != "" {
http.Error(w, msg, http.StatusBadRequest)
return
}
Expand All @@ -205,7 +230,7 @@ func (s *Server) handleCreateProfile(w http.ResponseWriter, r *http.Request) {
}
var row generated.Profile
err := s.db.QueriesTx(r.Context(), func(q *generated.Queries) (err error) {
row, err = q.CreateProfile(r.Context(), generated.CreateProfileParams{Name: body.Name, Settings: encodeProfile(body.Settings, body.VoicePrompt)})
row, err = q.CreateProfile(r.Context(), generated.CreateProfileParams{Name: body.Name, Settings: encodeProfile(body.Settings, body.Voice, body.VoicePrompt)})
return err
})
if errors.Is(err, sql.ErrNoRows) {
Expand All @@ -225,12 +250,14 @@ func (s *Server) handleCreateProfile(w http.ResponseWriter, r *http.Request) {
}

// handleUpdateProfile handles PUT /api/profiles/{name}: the body is the
// profile's new settings, and optionally its voice prompt, which an absent
// voice_prompt keeps. Its model needn't be available if it is unchanged.
// profile's new settings, and optionally its voice and voice prompt, which
// when absent keep their values. Its model needn't be available if it is
// unchanged.
func (s *Server) handleUpdateProfile(w http.ResponseWriter, r *http.Request) {
var body struct {
profileEcho
Settings
Voice *string `json:"voice"`
VoicePrompt *string `json:"voice_prompt"`
}
if !decodeStrict(w, r, &body) {
Expand Down Expand Up @@ -259,21 +286,25 @@ func (s *Server) handleUpdateProfile(w http.ResponseWriter, r *http.Request) {
http.Error(w, msg, http.StatusBadRequest)
return
}
voice := existing.Voice
if body.Voice != nil {
voice = strings.TrimSpace(*body.Voice)
}
voicePrompt := existing.VoicePrompt
if body.VoicePrompt != nil {
voicePrompt = strings.TrimSpace(*body.VoicePrompt)
}
if msg := cmp.Or(voicePromptProblem(voicePrompt), st.validate(s.getModelList(), st.Model != existing.Model)); msg != "" {
if msg := cmp.Or(voiceProblem(voice), voicePromptProblem(voicePrompt), st.validate(s.getModelList(), st.Model != existing.Model)); msg != "" {
http.Error(w, msg, http.StatusBadRequest)
return
}
if existing.Settings.equal(st) && existing.VoicePrompt == voicePrompt {
if existing.Settings.equal(st) && existing.Voice == voice && existing.VoicePrompt == voicePrompt {
writeJSON(w, http.StatusOK, existing)
return
}
var row generated.Profile
err = s.db.QueriesTx(r.Context(), func(q *generated.Queries) (err error) {
row, err = q.UpdateProfile(r.Context(), generated.UpdateProfileParams{Name: name, Settings: encodeProfile(st, voicePrompt)})
row, err = q.UpdateProfile(r.Context(), generated.UpdateProfileParams{Name: name, Settings: encodeProfile(st, voice, voicePrompt)})
return err
})
if errors.Is(err, sql.ErrNoRows) {
Expand Down
45 changes: 36 additions & 9 deletions server/profiles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,17 +233,17 @@ func TestPreinstalledAssistant(t *testing.T) {
// rejected edits must not do so either. Each editable field does opt out.
func TestBuiltinProfileEdits(t *testing.T) {
t.Parallel()
for _, field := range []string{"model", "tools", "prompt", "voice", "reasoning", "compact"} {
for _, field := range []string{"model", "tools", "prompt", "voice", "speaker", "reasoning", "compact"} {
t.Run(field, func(t *testing.T) {
t.Parallel()
e := newProfileEnv(t)
initial := e.profiles()["Default"]
if !initial.Builtin || initial.UserEdited {
t.Fatalf("initial Default: %+v", initial)
}
save := func(st Settings, voice string) Profile {
save := func(st Settings, speaker, voice string) Profile {
t.Helper()
body, err := json.Marshal(storedProfile{Settings: st, VoicePrompt: voice})
body, err := json.Marshal(storedProfile{Settings: st, Voice: speaker, VoicePrompt: voice})
if err != nil {
t.Fatal(err)
}
Expand All @@ -253,21 +253,23 @@ func TestBuiltinProfileEdits(t *testing.T) {
}
return p
}
if p := save(initial.Settings, initial.VoicePrompt); p.UserEdited || !p.Builtin {
if p := save(initial.Settings, initial.Voice, initial.VoicePrompt); p.UserEdited || !p.Builtin {
t.Fatalf("no-op save opted out: %+v", p)
}
for _, body := range []string{
`{"model":"missing-model"}`,
`{"tool_overrides":{"bash":"maybe"}}`,
`{"system_prompt":"{{.Nope}}"}`,
`{"voice":"not-a-voice"}`,
`{"voice_prompt":"` + strings.Repeat("x", 4001) + `"}`,
} {
e.want(400, "PUT", "/api/profiles/Default", body)
}
if p := e.profiles()["Default"]; p.UserEdited || !p.Settings.equal(initial.Settings) || p.VoicePrompt != initial.VoicePrompt {
if p := e.profiles()["Default"]; p.UserEdited || !p.Settings.equal(initial.Settings) || p.Voice != initial.Voice || p.VoicePrompt != initial.VoicePrompt {
t.Fatalf("failed validation changed profile: %+v", p)
}
edited := initial.Settings
speaker := initial.Voice
voice := initial.VoicePrompt
switch field {
case "model":
Expand All @@ -278,12 +280,14 @@ func TestBuiltinProfileEdits(t *testing.T) {
edited.SystemPrompt = "A custom prompt."
case "voice":
voice = "A custom voice."
case "speaker":
speaker = "cedar"
case "reasoning":
edited.ThinkingLevel = "low"
case "compact":
edited.CompactNudgeTokens = 12000
}
if p := save(edited, voice); !p.Builtin || !p.UserEdited || !p.Settings.equal(edited) || p.VoicePrompt != voice {
if p := save(edited, speaker, voice); !p.Builtin || !p.UserEdited || !p.Settings.equal(edited) || p.Voice != speaker || p.VoicePrompt != voice {
t.Fatalf("edit not persisted: %+v", p)
}
if p := e.profiles()["Default"]; !p.UserEdited {
Expand All @@ -299,7 +303,7 @@ func TestRestoreBuiltinProfile(t *testing.T) {
t.Parallel()
e := newProfileEnv(t)
initial := e.profiles()["Default"]
e.want(200, "PUT", "/api/profiles/Default", `{"model":"model-b","thinking_level":"low","compact_nudge_tokens":12000,"tool_overrides":{"bash":"off"},"system_prompt":"Custom chat prompt.","voice_prompt":"Custom voice prompt."}`)
e.want(200, "PUT", "/api/profiles/Default", `{"model":"model-b","thinking_level":"low","compact_nudge_tokens":12000,"tool_overrides":{"bash":"off"},"system_prompt":"Custom chat prompt.","voice":"cedar","voice_prompt":"Custom voice prompt."}`)
var created struct {
ConversationID string `json:"conversation_id"`
}
Expand All @@ -318,10 +322,10 @@ func TestRestoreBuiltinProfile(t *testing.T) {
if err := json.Unmarshal([]byte(e.want(200, "POST", "/api/profiles/Default/restore", "")), &restored); err != nil {
t.Fatal(err)
}
if !restored.Builtin || restored.UserEdited || !restored.Default || !restored.Settings.equal(initial.Settings) || restored.VoicePrompt != initial.VoicePrompt {
if !restored.Builtin || restored.UserEdited || !restored.Default || !restored.Settings.equal(initial.Settings) || restored.Voice != initial.Voice || restored.VoicePrompt != initial.VoicePrompt {
t.Fatalf("restore didn't recover shipped defaults: %+v", restored)
}
if p := e.profiles()["Default"]; !p.Builtin || p.UserEdited || !p.Default || !p.Settings.equal(initial.Settings) || p.VoicePrompt != initial.VoicePrompt {
if p := e.profiles()["Default"]; !p.Builtin || p.UserEdited || !p.Default || !p.Settings.equal(initial.Settings) || p.Voice != initial.Voice || p.VoicePrompt != initial.VoicePrompt {
t.Fatalf("restored profile wasn't persisted: %+v", p)
}
after, err := e.database.GetConversationByID(t.Context(), created.ConversationID)
Expand Down Expand Up @@ -688,6 +692,29 @@ func TestProfileVoicePrompt(t *testing.T) {
}
}

func TestProfileVoice(t *testing.T) {
t.Parallel()
e := newProfileEnv(t)
e.want(400, "POST", "/api/profiles", `{"name":"BadVoice","model":"model-b","voice":"nope"}`)
created := e.want(201, "POST", "/api/profiles", `{"name":"Speaker","model":"model-b","voice":" cedar "}`)
if !strings.Contains(created, `"voice":"cedar"`) {
t.Fatalf("created: %s", created)
}
e.want(200, "PUT", "/api/profiles/Speaker", `{"model":"model-a","thinking_level":"low"}`)
if got := e.profiles()["Speaker"]; got.Voice != "cedar" || got.Model != "model-a" {
t.Fatalf("a settings-only PUT changed the voice: %+v", got)
}
e.want(200, "PUT", "/api/profiles/Speaker", `{"model":"model-a","voice":"alloy"}`)
e.want(400, "PUT", "/api/profiles/Speaker", `{"model":"model-a","voice":"nope"}`)
if got := e.profiles()["Speaker"]; got.Voice != "alloy" {
t.Fatalf("replaced: %+v", got)
}
e.want(200, "PUT", "/api/profiles/Speaker", `{"model":"model-a","voice":""}`)
if got := e.profiles()["Speaker"]; got.Voice != "" {
t.Fatalf("cleared: %+v", got)
}
}

func TestProfileIdlePolicyIsCopiedAndCanBeDisabled(t *testing.T) {
e := newProfileEnv(t)
for _, invalid := range []string{
Expand Down
22 changes: 16 additions & 6 deletions ui/src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1526,21 +1526,31 @@ export const profilesApi = {
async list(): Promise<Profile[]> {
return apiJSON("/api/profiles", "Failed to load profiles");
},
/** voicePrompt, if given, is saved too; else a new profile has none and
* an updated one keeps its own. */
async create(name: string, settings: Settings, voicePrompt?: string): Promise<Profile> {
/** voice and voicePrompt, if given, are saved too; else a new profile has
* none and an updated one keeps its own. */
async create(
name: string,
settings: Settings,
voicePrompt?: string,
voice?: string,
): Promise<Profile> {
const response = await apiFetch(
"/api/profiles",
"Failed to save profile",
sendJSON("POST", { name, ...settings, voice_prompt: voicePrompt }),
sendJSON("POST", { name, ...settings, voice, voice_prompt: voicePrompt }),
);
return response.json();
},
async update(name: string, settings: Settings, voicePrompt?: string): Promise<Profile> {
async update(
name: string,
settings: Settings,
voicePrompt?: string,
voice?: string,
): Promise<Profile> {
const response = await apiFetch(
`/api/profiles/${encodeURIComponent(name)}`,
"Failed to save profile",
sendJSON("PUT", { ...settings, voice_prompt: voicePrompt }),
sendJSON("PUT", { ...settings, voice, voice_prompt: voicePrompt }),
);
return response.json();
},
Expand Down
Loading