Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(ai): add compact and max_bytes to the chat messages endpoint

rcourtman3029db3bcf56
diff --git a/internal/api/ai_chat_transport.go b/internal/api/ai_chat_transport.go
new file mode 100644
index 0000000000..598e7b6d23
--- /dev/null
+++ b/internal/api/ai_chat_transport.go
@@ -0,0 +1,91 @@
+package api
+
+import (
+ "encoding/json"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
+)
+
+// chatMessageTruncationNotice is appended to a message whose content had to be
+// cut to fit a transport byte budget. The full text stays available in the
+// Pulse web UI, which does not go through the size-capped relay proxy.
+const chatMessageTruncationNotice = "\n\n[Message shortened for mobile. Open Pulse in a browser for the full text.]"
+
+// compactChatMessageForTransport strips message fields that constrained
+// clients (the mobile app behind the relay proxy's 47KB response cap) never
+// render: tool outputs, tool result bodies, and provider thought signatures.
+// Tool identity and the tool_use_id linkage used to mark tools completed are
+// preserved.
+func compactChatMessageForTransport(m chat.Message) chat.Message {
+ for i := range m.ToolCalls {
+ m.ToolCalls[i].Output = ""
+ m.ToolCalls[i].ThoughtSignature = nil
+ }
+ if m.ToolResult != nil {
+ m.ToolResult = &chat.ToolResult{
+ ToolUseID: m.ToolResult.ToolUseID,
+ IsError: m.ToolResult.IsError,
+ }
+ }
+ return m
+}
+
+// trimChatMessagesToByteBudget returns the newest messages whose combined JSON
+// encoding fits within budget bytes (including array brackets and separators).
+// The newest message is always returned; if it alone exceeds the budget its
+// content is truncated to fit.
+func trimChatMessagesToByteBudget(messages []chat.Message, budget int) []chat.Message {
+ if len(messages) == 0 || budget <= 0 {
+ return messages
+ }
+
+ total := 2 // array brackets
+ kept := 0
+ for i := len(messages) - 1; i >= 0; i-- {
+ encoded, err := json.Marshal(messages[i])
+ if err != nil {
+ break
+ }
+ cost := len(encoded)
+ if kept > 0 {
+ cost++ // separating comma
+ }
+ if total+cost > budget {
+ break
+ }
+ total += cost
+ kept++
+ }
+
+ if kept == 0 {
+ return []chat.Message{truncateChatMessageContent(messages[len(messages)-1], budget-2)}
+ }
+ return messages[len(messages)-kept:]
+}
+
+// truncateChatMessageContent shrinks a message's content until its JSON
+// encoding fits within budget bytes. Non-content fields are left intact, so a
+// message dominated by other fields may still exceed the budget; callers treat
+// the result as best effort.
+func truncateChatMessageContent(m chat.Message, budget int) chat.Message {
+ original := m
+ for {
+ encoded, err := json.Marshal(m)
+ if err != nil {
+ return original
+ }
+ if len(encoded) <= budget {
+ return m
+ }
+ content := strings.TrimSuffix(m.Content, chatMessageTruncationNotice)
+ if len(content) == 0 {
+ return m
+ }
+ cut := len(content) - (len(encoded) - budget) - len(chatMessageTruncationNotice)
+ if cut < 0 {
+ cut = 0
+ }
+ m.Content = strings.ToValidUTF8(content[:cut], "") + chatMessageTruncationNotice
+ }
+}
diff --git a/internal/api/ai_chat_transport_test.go b/internal/api/ai_chat_transport_test.go
new file mode 100644
index 0000000000..290fef479e
--- /dev/null
+++ b/internal/api/ai_chat_transport_test.go
@@ -0,0 +1,162 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/mock"
+)
+
+func TestCompactChatMessageForTransportStripsBulkFields(t *testing.T) {
+ isError := true
+ msg := chat.Message{
+ ID: "m1",
+ Role: "assistant",
+ Content: "ran a tool",
+ ToolCalls: []chat.ToolCall{
+ {
+ ID: "tool-1",
+ Name: "run_command",
+ Output: strings.Repeat("x", 10_000),
+ ThoughtSignature: json.RawMessage(`"sig"`),
+ },
+ },
+ ToolResult: &chat.ToolResult{
+ ToolUseID: "tool-1",
+ Content: strings.Repeat("y", 10_000),
+ IsError: isError,
+ },
+ }
+
+ compacted := compactChatMessageForTransport(msg)
+
+ if compacted.ToolCalls[0].Output != "" {
+ t.Errorf("expected tool output stripped, got %d bytes", len(compacted.ToolCalls[0].Output))
+ }
+ if compacted.ToolCalls[0].ThoughtSignature != nil {
+ t.Error("expected thought signature stripped")
+ }
+ if compacted.ToolCalls[0].ID != "tool-1" || compacted.ToolCalls[0].Name != "run_command" {
+ t.Error("expected tool identity preserved")
+ }
+ if compacted.ToolResult == nil {
+ t.Fatal("expected tool result retained")
+ }
+ if compacted.ToolResult.Content != "" {
+ t.Errorf("expected tool result content stripped, got %d bytes", len(compacted.ToolResult.Content))
+ }
+ if compacted.ToolResult.ToolUseID != "tool-1" {
+ t.Error("expected tool_use_id linkage preserved")
+ }
+ if !compacted.ToolResult.IsError {
+ t.Error("expected is_error preserved")
+ }
+ if compacted.Content != "ran a tool" {
+ t.Error("expected content untouched")
+ }
+}
+
+func TestTrimChatMessagesToByteBudgetKeepsNewestThatFit(t *testing.T) {
+ messages := []chat.Message{
+ {ID: "old", Role: "user", Content: strings.Repeat("a", 500)},
+ {ID: "mid", Role: "assistant", Content: strings.Repeat("b", 500)},
+ {ID: "new", Role: "user", Content: strings.Repeat("c", 500)},
+ }
+
+ // Budget fits roughly two messages, not three.
+ trimmed := trimChatMessagesToByteBudget(messages, 1400)
+
+ if len(trimmed) != 2 {
+ t.Fatalf("expected 2 messages, got %d", len(trimmed))
+ }
+ if trimmed[0].ID != "mid" || trimmed[1].ID != "new" {
+ t.Errorf("expected newest messages kept in order, got %s, %s", trimmed[0].ID, trimmed[1].ID)
+ }
+
+ encoded, err := json.Marshal(trimmed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(encoded) > 1400 {
+ t.Errorf("encoded result exceeds budget: %d bytes", len(encoded))
+ }
+}
+
+func TestTrimChatMessagesToByteBudgetTruncatesSingleOversizedMessage(t *testing.T) {
+ messages := []chat.Message{
+ {ID: "huge", Role: "assistant", Content: strings.Repeat("z", 100_000)},
+ }
+
+ trimmed := trimChatMessagesToByteBudget(messages, 2000)
+
+ if len(trimmed) != 1 {
+ t.Fatalf("expected the newest message returned, got %d", len(trimmed))
+ }
+ if !strings.HasSuffix(trimmed[0].Content, chatMessageTruncationNotice) {
+ t.Error("expected truncation notice appended")
+ }
+
+ encoded, err := json.Marshal(trimmed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(encoded) > 2000 {
+ t.Errorf("encoded result exceeds budget: %d bytes", len(encoded))
+ }
+}
+
+func TestTrimChatMessagesToByteBudgetNoBudgetReturnsAll(t *testing.T) {
+ messages := []chat.Message{
+ {ID: "a", Role: "user", Content: "one"},
+ {ID: "b", Role: "assistant", Content: "two"},
+ }
+
+ if got := trimChatMessagesToByteBudget(messages, 0); len(got) != 2 {
+ t.Errorf("zero budget should return input unchanged, got %d messages", len(got))
+ }
+ if got := trimChatMessagesToByteBudget(nil, 1000); got != nil {
+ t.Errorf("nil input should stay nil")
+ }
+}
+
+func TestHandleMessagesCompactAndByteBudget(t *testing.T) {
+ cfg := &config.Config{}
+ h := newTestAIHandler(cfg, nil, nil)
+ mockSvc := new(MockAIService)
+ h.defaultService = mockSvc
+
+ mockSvc.On("IsRunning").Return(true)
+ messages := []chat.Message{
+ {ID: "old", Role: "user", Content: strings.Repeat("a", 30_000)},
+ {
+ ID: "tools",
+ Role: "assistant",
+ Content: "ran a tool",
+ ToolCalls: []chat.ToolCall{
+ {ID: "t1", Name: "run_command", Output: strings.Repeat("o", 20_000)},
+ },
+ },
+ {ID: "new", Role: "user", Content: "latest question"},
+ }
+ mockSvc.On("GetMessages", mock.Anything, "s1").Return(messages, nil)
+
+ req := httptest.NewRequest("GET", "/api/ai/sessions/s1/messages?limit=30&compact=1&max_bytes=4096", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleMessages(w, req, "s1")
+
+ assert.Equal(t, http.StatusOK, w.Code)
+ if w.Body.Len() > 4096 {
+ t.Fatalf("response exceeds byte budget: %d", w.Body.Len())
+ }
+ assert.Contains(t, w.Body.String(), "latest question")
+ assert.Contains(t, w.Body.String(), `"tools"`)
+ assert.NotContains(t, w.Body.String(), strings.Repeat("o", 100))
+ assert.NotContains(t, w.Body.String(), `"old"`)
+}
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 31fe3ddef0..55e311d26c 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -2930,8 +2930,19 @@ func (h *AIHandler) HandleMessages(w http.ResponseWriter, r *http.Request, sessi
messages = messages[len(messages)-limit:]
}
}
+ compact := r.URL.Query().Get("compact") == "1"
for i := range messages {
messages[i] = messages[i].ClientSafe()
+ if compact {
+ messages[i] = compactChatMessageForTransport(messages[i])
+ }
+ }
+ // Optional byte budget — the relay proxy caps responses at 47KB, so
+ // constrained clients ask for the newest messages that fit.
+ if budgetStr := r.URL.Query().Get("max_bytes"); budgetStr != "" {
+ if budget, err := strconv.Atoi(budgetStr); err == nil && budget > 0 {
+ messages = trimChatMessagesToByteBudget(messages, budget)
+ }
}
w.Header().Set("Content-Type", "application/json")