refactor(webui): extract the chat module and its ask/file state (#1778)
Quality / check (push) Canceled after 1m5s
deploy / gate (push) Successful in 4m35s
deploy / archied-image (push) Successful in 2m48s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped

This commit is contained in:
sam committed 2026-11-03 08:36:09 +11:00
1 parent e8a84d3e41
commit 18e6fe6af6
6 files changed
+79 -65

No files matched your search

@@ -136,20 +136,49 @@ type chatToolView struct {
TextOffset int `json:"text_offset,omitempty"`
}
func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
if s.Chat == nil || s.Chat.Contract == nil {
// chatAPI owns the /api/chat routes and the state they share: questions
// waiting for the browser's answer and files a turn offered for download.
type chatAPI struct {
chat *ChatService
updateReportPath string
configSource func() ConfigViewSource
asks chatAsks
files chatFiles
}
func newChatAPI(s *Server) *chatAPI {
return &chatAPI{chat: s.Chat, updateReportPath: s.UpdateReportPath, configSource: s.configSource}
}
func (a *chatAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/chat/sessions", a.handleChatSessions)
mux.HandleFunc("GET /api/chat/sessions/{id}/messages", a.handleChatMessages)
mux.HandleFunc("GET /api/chat/sessions/{id}/turns", a.handleChatTurns)
mux.HandleFunc("POST /api/chat/message", a.handleChatMessage)
mux.HandleFunc("POST /api/chat/stream", a.handleChatStream)
mux.HandleFunc("POST /api/chat/cancel", a.handleChatCancel)
mux.HandleFunc("POST /api/chat/answer", a.handleChatAnswer)
mux.HandleFunc("GET /api/chat/file/{token}", a.handleChatFile)
mux.HandleFunc("GET /api/chat/update", instanceOnly(a.handleChatUpdate))
mux.HandleFunc("POST /api/chat/update/defer", instanceOnly(a.handleChatUpdateDefer))
mux.HandleFunc("POST /api/chat/update/install", instanceOnly(a.handleChatUpdateInstall))
}
func (a *chatAPI) chatReady(w http.ResponseWriter) (*ChatService, bool) {
if a.chat == nil || a.chat.Contract == nil {
http.Error(w, "chat is not configured", http.StatusNotImplemented)
return nil, false
}
return s.Chat, true
return a.chat, true
}
func chatUpdateServiceConfigured(updates ChatUpdateService) bool {
return !lifecycle.IsNil(updates)
}
func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatSessions(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -160,7 +189,7 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
}
out := make([]messaging.SessionContext, 0, len(snapshot.Sessions))
for _, session := range snapshot.Sessions {
if s.ownsChatSession(r.Context(), session) {
if a.ownsChatSession(r.Context(), session) {
out = append(out, session)
}
}
@@ -181,8 +210,8 @@ func chatCommandSpecs(chat *ChatService) []messaging.CommandSpec {
return specs
}
func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatMessages(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -192,7 +221,7 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || !s.ownsChatSession(r.Context(), session) {
if !found || !a.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -212,8 +241,8 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
writeJSON(w, views)
}
func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatTurns(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -223,7 +252,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || !s.ownsChatSession(r.Context(), session) {
if !found || !a.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -250,7 +279,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
writeJSON(w, views)
}
func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) {
func (a *chatAPI) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) {
var req chatMessageRequest
// 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 {
@@ -300,12 +329,12 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mess
}, true
}
func (s *Server) handleChatMessage(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatMessage(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
msg, ok := s.decodeChatMessage(w, r)
msg, ok := a.decodeChatMessage(w, r)
if !ok {
return
}
@@ -398,20 +427,20 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) {
// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, false when no
// config is available.
func (s *Server) chatShowToolCalls(ctx context.Context) bool {
view, found, err := s.configSource()(ctx)
func (a *chatAPI) chatShowToolCalls(ctx context.Context) bool {
view, found, err := a.configSource()(ctx)
if err != nil || !found {
return false
}
return view.Chat.ShowToolCalls
}
func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatStream(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
msg, ok := s.decodeChatMessage(w, r)
msg, ok := a.decodeChatMessage(w, r)
if !ok {
return
}
@@ -434,13 +463,13 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "data: %s\n\n", payload)
flusher.Flush()
}
asker := dashboardAsker{asks: &s.chatAsks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
asker := dashboardAsker{asks: &a.asks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
events, err := chat.Contract.Stream(withDashboardAsks(r.Context(), asker), msg)
if err != nil {
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
return
}
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles, owner: chatUser(r.Context())}
sink := chatStreamSink{showToolCalls: a.chatShowToolCalls(r.Context()), files: &a.files, owner: chatUser(r.Context())}
for event := range events {
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
switch event.Kind {
@@ -454,8 +483,8 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
}
}
func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -478,7 +507,7 @@ func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || !s.ownsChatSession(r.Context(), session) {
if !found || !a.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -500,8 +529,8 @@ func writeUpdateCheckError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadGateway)
}
func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -533,8 +562,8 @@ func updateStateDir() string {
return configuration.UpdateStateDir()
}
func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -554,8 +583,8 @@ func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]bool{"ok": true})
}
func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -592,7 +621,7 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
}()
progress := make([]string, 0, 4)
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: s.UpdateReportPath}
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: a.updateReportPath}
result, err := chat.Updates.Install(r.Context(), fresh, meta, func(message string) { progress = append(progress, message) })
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
@@ -618,6 +647,6 @@ func chatUser(ctx context.Context) string {
return ""
}
func (s *Server) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
func (a *chatAPI) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
return session.Source.Platform == "web" && session.Source.ThreadID == chatUser(ctx)
}
@@ -189,13 +189,13 @@ type chatAnswerRequest struct {
}
// handleChatAnswer delivers the operator's answer to the ask a turn waits on.
func (s *Server) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
func (a *chatAPI) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
var req chatAnswerRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ID == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if !s.chatAsks.answer(req.ID, req.Answer, chatUser(r.Context())) {
if !a.asks.answer(req.ID, req.Answer, chatUser(r.Context())) {
http.Error(w, "that question is no longer waiting", http.StatusNotFound)
return
}
@@ -72,8 +72,8 @@ func (c *chatFiles) lookup(token string) (chatFile, bool) {
return f, true
}
func (s *Server) handleChatFile(w http.ResponseWriter, r *http.Request) {
f, ok := s.chatFiles.lookup(r.PathValue("token"))
func (a *chatAPI) handleChatFile(w http.ResponseWriter, r *http.Request) {
f, ok := a.files.lookup(r.PathValue("token"))
if !ok || f.owner != chatUser(r.Context()) {
http.Error(w, "that file is no longer available", http.StatusNotFound)
return
@@ -19,10 +19,10 @@ func TestChatFileDownload(t *testing.T) {
t.Fatal(err)
}
now := time.Now()
srv := &Server{}
srv.chatFiles.now = func() time.Time { return now }
token := srv.chatFiles.offer(path, "")
private := srv.chatFiles.offerFor(path, "", "alice")
srv := newChatAPI(&Server{})
srv.files.now = func() time.Time { return now }
token := srv.files.offer(path, "")
private := srv.files.offerFor(path, "", "alice")
tests := []struct {
name string
@@ -41,7 +41,7 @@ func TestChatFileDownload(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv.chatFiles.now = func() time.Time { return now.Add(tt.after) }
srv.files.now = func() time.Time { return now.Add(tt.after) }
ctx := t.Context()
if tt.user != "" {
ctx = WithActingIdentity(ctx, identity.Identity{ID: identity.IdentityID(tt.user)})
+6 -6
View File
@@ -36,11 +36,11 @@ func (ownedChat) Cancel(context.Context, string) (messaging.ChatCancellation, er
func TestWebChatOwnership(t *testing.T) {
for _, route := range []struct {
name, body string
handler func(*Server, http.ResponseWriter, *http.Request)
handler func(*chatAPI, http.ResponseWriter, *http.Request)
}{
{"messages", "", (*Server).handleChatMessages},
{"turns", "", (*Server).handleChatTurns},
{"cancel", `{"session_id":"private"}`, (*Server).handleChatCancel},
{"messages", "", (*chatAPI).handleChatMessages},
{"turns", "", (*chatAPI).handleChatTurns},
{"cancel", `{"session_id":"private"}`, (*chatAPI).handleChatCancel},
} {
for _, user := range []string{"alice", "bob"} {
t.Run(route.name+"/"+user, func(t *testing.T) {
@@ -49,7 +49,7 @@ func TestWebChatOwnership(t *testing.T) {
req.SetPathValue("id", "private")
rec := httptest.NewRecorder()
srv := &Server{Chat: &ChatService{Contract: ownedChat{}}}
route.handler(srv, rec, req)
route.handler(newChatAPI(srv), rec, req)
want := 200
if user != "alice" {
want = 404
@@ -65,7 +65,7 @@ func TestWebChatOwnership(t *testing.T) {
func TestWebChatSenderCannotBeSuppliedByBrowser(t *testing.T) {
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: "alice"})
req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/message", strings.NewReader(`{"channel_id":"browser-channel","text":"hello","sender_id":"bob","thread_id":"bob"}`))
value, ok := (&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
value, ok := newChatAPI(&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
if !ok {
t.Fatal("message refused")
}
+1 -16
View File
@@ -34,11 +34,6 @@ type Server struct {
Accounts identity.Accounts
accountRateLimit *ratelimit.Limiter
// 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
@@ -371,17 +366,7 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
}
func (s *Server) registerChatRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/chat/sessions", s.handleChatSessions)
mux.HandleFunc("GET /api/chat/sessions/{id}/messages", s.handleChatMessages)
mux.HandleFunc("GET /api/chat/sessions/{id}/turns", s.handleChatTurns)
mux.HandleFunc("POST /api/chat/message", s.handleChatMessage)
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("GET /api/chat/update", instanceOnly(s.handleChatUpdate))
mux.HandleFunc("POST /api/chat/update/defer", instanceOnly(s.handleChatUpdateDefer))
mux.HandleFunc("POST /api/chat/update/install", instanceOnly(s.handleChatUpdateInstall))
newChatAPI(s).register(mux)
}
func (s *Server) Handler() http.Handler {