feat(chat): the dashboard chat records voice, downloads files a turn sends, and offers /model and /personality choices
This commit is contained in:
1 parent
201529414b
commit
8a8c8cf7e9
16 files changed
+380
-92
No files matched your search
@@ -256,5 +256,6 @@ func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskAct
|
||||
return &gateway.LocalChatAdapter{
|
||||
Router: router, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(b.log),
|
||||
Models: b.chatModels, Personas: b.personas, TaskActor: actor, Tasks: b.stateStore,
|
||||
VoiceAvailable: b.transcriber != nil,
|
||||
}, nil
|
||||
}
|
||||
@@ -730,6 +730,7 @@ type SnapshotResponse struct {
|
||||
CancellationAvailable bool `protobuf:"varint,10,opt,name=cancellation_available,json=cancellationAvailable,proto3" json:"cancellation_available,omitempty"`
|
||||
PersonasAvailable bool `protobuf:"varint,11,opt,name=personas_available,json=personasAvailable,proto3" json:"personas_available,omitempty"`
|
||||
Version string `protobuf:"bytes,12,opt,name=version,proto3" json:"version,omitempty"`
|
||||
VoiceAvailable bool `protobuf:"varint,13,opt,name=voice_available,json=voiceAvailable,proto3" json:"voice_available,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -848,6 +849,13 @@ func (x *SnapshotResponse) GetVersion() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *SnapshotResponse) GetVoiceAvailable() bool {
|
||||
if x != nil {
|
||||
return x.VoiceAvailable
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type GetSessionRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
|
||||
@@ -3811,7 +3819,7 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"StringList\x12\x16\n" +
|
||||
"\x06values\x18\x01 \x03(\tR\x06values\"\x11\n" +
|
||||
"\x0fSnapshotRequest\"\xeb\x05\n" +
|
||||
"\x0fSnapshotRequest\"\x94\x06\n" +
|
||||
"\x10SnapshotResponse\x12/\n" +
|
||||
"\bsessions\x18\x01 \x03(\v2\x13.gateway.v1.SessionR\bsessions\x12\x16\n" +
|
||||
"\x06models\x18\x02 \x03(\tR\x06models\x12`\n" +
|
||||
@@ -3825,7 +3833,8 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
|
||||
"\x16cancellation_available\x18\n" +
|
||||
" \x01(\bR\x15cancellationAvailable\x12-\n" +
|
||||
"\x12personas_available\x18\v \x01(\bR\x11personasAvailable\x12\x18\n" +
|
||||
"\aversion\x18\f \x01(\tR\aversion\x1a[\n" +
|
||||
"\aversion\x18\f \x01(\tR\aversion\x12'\n" +
|
||||
"\x0fvoice_available\x18\r \x01(\bR\x0evoiceAvailable\x1a[\n" +
|
||||
"\x15ModelsByProviderEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12,\n" +
|
||||
"\x05value\x18\x02 \x01(\v2\x16.gateway.v1.StringListR\x05value:\x028\x01\x1aA\n" +
|
||||
|
||||
@@ -17,7 +17,9 @@ type ChatSnapshot struct {
|
||||
Version string
|
||||
RestartAvailable bool
|
||||
CancellationAvailable bool
|
||||
PersonasAvailable bool
|
||||
// VoiceAvailable reports that a voice clip is transcribed into the turn.
|
||||
VoiceAvailable bool
|
||||
PersonasAvailable bool
|
||||
}
|
||||
|
||||
// ChatReply is the blocking reply from Route.
|
||||
|
||||
@@ -25,6 +25,8 @@ type LocalChatAdapter struct {
|
||||
TaskActor ChatTaskActor
|
||||
// Tasks reads the tasks /stop acts on.
|
||||
Tasks TaskReader
|
||||
// VoiceAvailable reports that voice clips are transcribed.
|
||||
VoiceAvailable bool
|
||||
}
|
||||
|
||||
// TaskReader is the task reads /stop needs.
|
||||
@@ -42,7 +44,7 @@ func (a *LocalChatAdapter) Snapshot(ctx context.Context) (ChatSnapshot, error) {
|
||||
if err != nil {
|
||||
return ChatSnapshot{}, err
|
||||
}
|
||||
s := ChatSnapshot{Sessions: sessions, Models: []string{}, Providers: []string{}, Personas: []string{}, ModelsByProvider: map[string][]string{}, ActivePersonas: map[string]string{}, RestartAvailable: a.Router.Restart != nil, CancellationAvailable: a.Turns != nil, PersonasAvailable: a.Personas != nil, Version: a.Router.Version}
|
||||
s := ChatSnapshot{Sessions: sessions, Models: []string{}, Providers: []string{}, Personas: []string{}, ModelsByProvider: map[string][]string{}, ActivePersonas: map[string]string{}, RestartAvailable: a.Router.Restart != nil, CancellationAvailable: a.Turns != nil, PersonasAvailable: a.Personas != nil, VoiceAvailable: a.VoiceAvailable, Version: a.Router.Version}
|
||||
if a.Models != nil {
|
||||
s.Models = slices.Clone(a.Models.Models())
|
||||
s.ActiveModel = a.Models.ActiveModel()
|
||||
|
||||
@@ -257,7 +257,7 @@ func snapshotProto(v messaging.ChatSnapshot) *pb.SnapshotResponse {
|
||||
for k, list := range v.ModelsByProvider {
|
||||
groups[k] = &pb.StringList{Values: list}
|
||||
}
|
||||
return &pb.SnapshotResponse{Sessions: mapValues(v.Sessions, sessionProto), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable, Version: v.Version}
|
||||
return &pb.SnapshotResponse{Sessions: mapValues(v.Sessions, sessionProto), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable, VoiceAvailable: v.VoiceAvailable, Version: v.Version}
|
||||
}
|
||||
|
||||
func snapshotValue(v *pb.SnapshotResponse) messaging.ChatSnapshot {
|
||||
@@ -265,5 +265,5 @@ func snapshotValue(v *pb.SnapshotResponse) messaging.ChatSnapshot {
|
||||
for k, list := range v.ModelsByProvider {
|
||||
groups[k] = list.GetValues()
|
||||
}
|
||||
return messaging.ChatSnapshot{Sessions: mapValues(v.Sessions, sessionValue), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable, Version: v.Version}
|
||||
return messaging.ChatSnapshot{Sessions: mapValues(v.Sessions, sessionValue), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable, VoiceAvailable: v.VoiceAvailable, Version: v.Version}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -44,8 +45,19 @@ type chatMessageRequest struct {
|
||||
// set by the web chat so the agent's system prompt can state where the
|
||||
// operator is looking and point them somewhere relevant.
|
||||
Page string `json:"page,omitempty"`
|
||||
// Voice is a recorded clip, transcribed by the Gateway like a Telegram
|
||||
// voice note. Base64 in JSON.
|
||||
Voice *chatVoice `json:"voice,omitempty"`
|
||||
}
|
||||
|
||||
type chatVoice struct {
|
||||
Data []byte `json:"data"`
|
||||
MIMEType string `json:"mime_type"`
|
||||
}
|
||||
|
||||
// maxVoiceBytes bounds a recorded clip: about ten minutes of Opus.
|
||||
const maxVoiceBytes = 10 << 20
|
||||
|
||||
// chatMessageView is one entry of a session's history as the dashboard
|
||||
// reads it. The persisted record is messaging.Message; this is the shape
|
||||
// the browser has always been served, kept here so the HTTP response owns
|
||||
@@ -175,6 +187,7 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
"active_model": snapshot.ActiveModel,
|
||||
"active_provider": snapshot.ActiveProvider,
|
||||
"personas": snapshot.Personas,
|
||||
"voice_available": snapshot.VoiceAvailable,
|
||||
"active_personas": active,
|
||||
"commands": chatCommandSpecs(chat),
|
||||
"restart_available": snapshot.RestartAvailable,
|
||||
@@ -257,11 +270,23 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) {
|
||||
var req chatMessageRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
// Base64 makes a clip a third larger than its bytes.
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxVoiceBytes*3/2)).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid chat message", http.StatusBadRequest)
|
||||
return messaging.Inbound{}, false
|
||||
}
|
||||
req.Text = strings.TrimSpace(req.Text)
|
||||
var media []messaging.MediaAttachment
|
||||
if req.Voice != nil {
|
||||
if len(req.Voice.Data) == 0 || len(req.Voice.Data) > maxVoiceBytes {
|
||||
http.Error(w, "voice clip is empty or too long", http.StatusBadRequest)
|
||||
return messaging.Inbound{}, false
|
||||
}
|
||||
media = append(media, messaging.MediaAttachment{Type: messaging.MediaTypeVoice, MIMEType: req.Voice.MIMEType, Data: req.Voice.Data})
|
||||
if req.Text == "" {
|
||||
req.Text = "[voice message]"
|
||||
}
|
||||
}
|
||||
if req.Text == "" || req.ChannelID == "" {
|
||||
http.Error(w, "text and channel_id are required", http.StatusBadRequest)
|
||||
return messaging.Inbound{}, false
|
||||
@@ -280,7 +305,8 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mess
|
||||
Role: messaging.RoleUser,
|
||||
Text: req.Text,
|
||||
},
|
||||
Page: req.Page,
|
||||
Media: media,
|
||||
Page: req.Page,
|
||||
// The dashboard names the channel it carries; see the platform field's
|
||||
// note in internal/domain/messaging/inbound.go.
|
||||
Platform: "web",
|
||||
@@ -327,6 +353,8 @@ type chatStreamEvent struct {
|
||||
type chatStreamSink struct {
|
||||
write func(chatStreamEvent)
|
||||
showToolCalls bool
|
||||
// files hands out downloads for the local files a turn sends.
|
||||
files *chatFiles
|
||||
}
|
||||
|
||||
func (s chatStreamSink) Delta(text string) {
|
||||
@@ -371,15 +399,12 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) {
|
||||
switch {
|
||||
case att.URL != "":
|
||||
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 " + att.Type + ": " + att.URL})
|
||||
case att.Path != "":
|
||||
case att.Path != "" && s.files != nil:
|
||||
name := att.FileName
|
||||
if name == "" {
|
||||
name = att.Path
|
||||
name = filepath.Base(att.Path)
|
||||
}
|
||||
s.write(chatStreamEvent{
|
||||
Type: "delta",
|
||||
Text: "\n\n📎 could not send " + name + ": this channel cannot deliver a local file. It is on the daemon host at " + att.Path + ".",
|
||||
})
|
||||
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 [" + name + "](" + chatFileURL(s.files.offer(att.Path, att.FileName)) + ")"})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -427,7 +452,7 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
|
||||
return
|
||||
}
|
||||
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context())}
|
||||
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles}
|
||||
for event := range events {
|
||||
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
|
||||
switch event.Kind {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// chatFileTTL is how long a file a turn sent stays downloadable.
|
||||
const chatFileTTL = time.Hour
|
||||
|
||||
// chatFiles serves the files a chat turn sent from the Gateway's host. Only a
|
||||
// path a turn named is reachable, through an unguessable token that expires;
|
||||
// no request can name a path of its own.
|
||||
type chatFiles struct {
|
||||
mu sync.Mutex
|
||||
files map[string]chatFile
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type chatFile struct {
|
||||
path string
|
||||
name string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
func (c *chatFiles) clock() time.Time {
|
||||
if c.now != nil {
|
||||
return c.now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// offer registers path and returns the token that downloads it.
|
||||
func (c *chatFiles) offer(path, name string) string {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
token := hex.EncodeToString(b[:])
|
||||
if name == "" {
|
||||
name = filepath.Base(path)
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.files == nil {
|
||||
c.files = make(map[string]chatFile)
|
||||
}
|
||||
now := c.clock()
|
||||
for t, f := range c.files {
|
||||
if now.After(f.expires) {
|
||||
delete(c.files, t)
|
||||
}
|
||||
}
|
||||
c.files[token] = chatFile{path: path, name: name, expires: now.Add(chatFileTTL)}
|
||||
return token
|
||||
}
|
||||
|
||||
func (c *chatFiles) lookup(token string) (chatFile, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
f, ok := c.files[token]
|
||||
if !ok || c.clock().After(f.expires) {
|
||||
return chatFile{}, false
|
||||
}
|
||||
return f, true
|
||||
}
|
||||
|
||||
func (s *Server) handleChatFile(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := s.chatFiles.lookup(r.PathValue("token"))
|
||||
if !ok {
|
||||
http.Error(w, "that file is no longer available", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": f.name}))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
http.ServeFile(w, r, f.path)
|
||||
}
|
||||
|
||||
func chatFileURL(token string) string { return fmt.Sprintf("/api/chat/file/%s", token) }
|
||||
@@ -0,0 +1,50 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestChatFileDownload: only a file a turn offered is served, and only until
|
||||
// its token expires.
|
||||
func TestChatFileDownload(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "report.txt")
|
||||
if err := os.WriteFile(path, []byte("contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
srv := &Server{}
|
||||
srv.chatFiles.now = func() time.Time { return now }
|
||||
token := srv.chatFiles.offer(path, "")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
token string
|
||||
after time.Duration
|
||||
want int
|
||||
}{
|
||||
{name: "an offered file is served", token: token, want: http.StatusOK},
|
||||
{name: "a token nobody was given is refused", token: "0123456789abcdef0123456789abcdef", want: http.StatusNotFound},
|
||||
{name: "a path is not a token", token: "..%2f..%2fetc%2fpasswd", want: http.StatusNotFound},
|
||||
{name: "an expired token is refused", token: token, after: chatFileTTL + time.Second, want: http.StatusNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv.chatFiles.now = func() time.Time { return now.Add(tt.after) }
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/chat/file/x", nil)
|
||||
req.SetPathValue("token", tt.token)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleChatFile(rec, req)
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
|
||||
}
|
||||
if tt.want == http.StatusOK && rec.Body.String() != "contents" {
|
||||
t.Fatalf("body = %q", rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,8 @@ import (
|
||||
type Server struct {
|
||||
// chatAsks holds the chat questions waiting for the operator's answer.
|
||||
chatAsks chatAsks
|
||||
// chatFiles holds the downloads for files chat turns sent.
|
||||
chatFiles chatFiles
|
||||
|
||||
Store storecontract.TaskStore
|
||||
Log *slog.Logger
|
||||
@@ -362,6 +364,7 @@ func (s *Server) registerChatRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/chat/stream", s.handleChatStream)
|
||||
mux.HandleFunc("POST /api/chat/cancel", s.handleChatCancel)
|
||||
mux.HandleFunc("POST /api/chat/answer", s.handleChatAnswer)
|
||||
mux.HandleFunc("GET /api/chat/file/{token}", s.handleChatFile)
|
||||
mux.HandleFunc("POST /api/chat/persona", s.handleChatPersona)
|
||||
mux.HandleFunc("GET /api/chat/update", s.handleChatUpdate)
|
||||
mux.HandleFunc("POST /api/chat/update/defer", s.handleChatUpdateDefer)
|
||||
|
||||
Reference in new issue
Block a user