diff --git a/internal/webui/authorization_surfaces_test.go b/internal/webui/authorization_surfaces_test.go index 84b7dcde2..27257725a 100644 --- a/internal/webui/authorization_surfaces_test.go +++ b/internal/webui/authorization_surfaces_test.go @@ -101,7 +101,6 @@ func TestHTTPPolicyCannotBeBypassed(t *testing.T) { {"POST", "/api/channels/7/reload"}, {"POST", "/api/chat/answer"}, {"POST", "/api/chat/cancel"}, - {"POST", "/api/chat/message"}, {"POST", "/api/chat/stream"}, {"POST", "/api/chat/update/defer"}, {"POST", "/api/chat/update/install"}, diff --git a/internal/webui/authorize_test.go b/internal/webui/authorize_test.go index eead7f397..2da5fb353 100644 --- a/internal/webui/authorize_test.go +++ b/internal/webui/authorize_test.go @@ -235,7 +235,6 @@ func TestChatRouteMapping(t *testing.T) { }{ {http.MethodPost, "/api/chat/update/install", access.ActionUpdate, access.KindDashboard, "update"}, {http.MethodPost, "/api/chat/update/defer", access.ActionUpdate, access.KindDashboard, "update"}, - {http.MethodPost, "/api/chat/message", access.ActionRun, access.KindWorkflow, ""}, {http.MethodPost, "/api/chat/stream", access.ActionRun, access.KindWorkflow, ""}, {http.MethodPost, "/api/chat/cancel", access.ActionRun, access.KindWorkflow, ""}, {http.MethodPost, "/api/chat/answer", access.ActionRun, access.KindWorkflow, ""}, diff --git a/internal/webui/chat.go b/internal/webui/chat.go index 84873857f..b8351a4b0 100644 --- a/internal/webui/chat.go +++ b/internal/webui/chat.go @@ -155,7 +155,6 @@ 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) @@ -329,23 +328,6 @@ func (a *chatAPI) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mes }, true } -func (a *chatAPI) handleChatMessage(w http.ResponseWriter, r *http.Request) { - chat, ok := a.chatReady(w) - if !ok { - return - } - msg, ok := a.decodeChatMessage(w, r) - if !ok { - return - } - reply, err := chat.Contract.Route(r.Context(), msg) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - writeJSON(w, map[string]string{"reply": reply.Text, "session_id": reply.SessionID}) -} - // chatStreamEvent is one frame of the chat stream. Text is always emitted. type chatStreamEvent struct { Type string `json:"type"` diff --git a/internal/webui/chat_ownership_test.go b/internal/webui/chat_ownership_test.go index 76f1aeee3..9ef692409 100644 --- a/internal/webui/chat_ownership_test.go +++ b/internal/webui/chat_ownership_test.go @@ -64,7 +64,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"}`)) + req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/stream", strings.NewReader(`{"channel_id":"browser-channel","text":"hello","sender_id":"bob","thread_id":"bob"}`)) value, ok := newChatAPI(&Server{}).decodeChatMessage(httptest.NewRecorder(), req) if !ok { t.Fatal("message refused") diff --git a/ui/src/chat/state.ts b/ui/src/chat/state.ts index eeab5acaa..e4be9b63c 100644 --- a/ui/src/chat/state.ts +++ b/ui/src/chat/state.ts @@ -1,6 +1,7 @@ import { onMounted, onUnmounted, ref, watch, type Ref } from "vue"; import { api } from "@/lib/api"; +import { randomUUID } from "@/lib/uuid"; import { channelID } from "./channel"; import { matchesFor } from "./commands"; import { @@ -270,6 +271,50 @@ export async function refreshSessions(): Promise { } } +/** + * Sends a server command over the chat stream, the same path as any message, + * and reads the stream to its end. Resolves with the reply and the session the + * server reports. + */ +async function sendCommand( + text: string, +): Promise<{ reply: string; session_id: string }> { + const response = await api.chatStream({ + channel_id: channelID(), + source_id: randomUUID(), + text, + page: currentPage(), + }); + if (!response.body) throw new Error("the chat stream returned no body"); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + let reply = ""; + let session = ""; + let finished = false; + for (;;) { + const { value, done } = await reader.read(); + buffer += decoder.decode(value || new Uint8Array(), { stream: !done }); + const frames = buffer.split("\n\n"); + buffer = frames.pop() || ""; + for (const frame of frames) { + const line = frame.split("\n").find((part) => part.startsWith("data: ")); + if (!line) continue; + const event = JSON.parse(line.slice(6)) as ChatStreamFrame; + if (event.session_id) session = event.session_id; + if (event.type === "error") throw new Error(event.text); + if (event.type === "delta") reply += event.text; + if (event.type === "done") { + finished = true; + if (!reply) reply = event.text || ""; + } + } + if (done) break; + } + if (!finished) throw new Error("chat stream ended before completion"); + return { reply, session_id: session }; +} + export async function selectSession(id: string): Promise { if (!id) return; // Switching conversation detaches the running turn: abort its stream and @@ -287,7 +332,7 @@ export async function selectSession(id: string): Promise { try { // Resuming is the server's own command, so the transcript read below is of // a conversation the server considers current rather than a stale one. - await api.chatMessage(channelID(), `/resume ${id}`); + await sendCommand(`/resume ${id}`); const transcript = await readTranscript(id); if (isCurrentSession(id)) messages.value = transcript; } catch (err) { @@ -360,10 +405,7 @@ export async function runSessionCommand(command: string): Promise { if (!currentSession.value) return; try { statusText.value = "Working…"; - const result = await api.chatMessage<{ - session_id?: string; - reply?: string; - }>(channelID(), command); + const result = await sendCommand(command); if (result.session_id) currentSession.value = result.session_id; statusText.value = result.reply || "Session updated"; await refreshSessions(); @@ -383,10 +425,7 @@ export async function setModel(model: string): Promise { if (!model) return; const previous = selectedModel.value; try { - const result = await api.chatMessage<{ reply?: string }>( - channelID(), - `/model ${model}`, - ); + const result = await sendCommand(`/model ${model}`); selectedModel.value = model; statusText.value = result.reply || "Model updated"; await refreshSessions(); diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 67941cc9d..fe48b6311 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -4,7 +4,6 @@ // this one file. import { streamStateFor, type StreamState } from "./stream-state.ts"; import { streamURL } from "./stream-url.ts"; -import { randomUUID } from "./uuid.ts"; // DEFAULT_TIMEOUT_MS bounds a request so a daemon that accepts the connection // but never answers cannot leave the UI in a loading state with no way back. @@ -452,18 +451,6 @@ export const api = { method: "POST", body: { session_id: sessionID }, }), - // The page the operator was on when they asked, so a chat answer can be - // about what they were looking at. History routing makes that the pathname. - chatMessage: (channelID: string, text: string) => - request("/api/chat/message", { - method: "POST", - body: { - channel_id: channelID, - source_id: randomUUID(), - text, - page: location.pathname + location.search || "/", - }, - }), // A server-sent event stream cannot be parsed as JSON and outlives a normal // request, so the caller owns the abort controller and the timeout, and // reads the body itself. Only the URL, headers, and failure shape are shared.