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
@@ -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