Files
ai/controllers/message.go
zeekay 43c4b66ef5 the paginator takes a page, and the stream owns the connection
Three structural pieces of the move off web.

SSE. The chat-completions stream and the single-chunk reply now run inside
SendStreamWriter: zip hands the handler a writer and flushes each frame as it is
written, so a chunk reaches the client when it is produced. The billing capture
runs inside that same closure, so the usage it settles on is the usage of the
bytes the client actually received.

Pagination. NewPaginator wanted an *http.Request for exactly one thing: reading
"p". It takes the page as a number now, and the parameter name is read by the
caller — 22 call sites, and util no longer imports net/http for this. pageAsked
is a pure function so the name and the not-a-number cases are assertable without
a live request; its table moved with it.

Per-request values. Input.SetParam/GetData are Locals, which is where a request
carries something for a later filter to read.

909 compile errors down to 76. Left: 14 bare Request values, 28 ResponseWriter
in the remaining streamers, the session, and routers/ + app.go + the tests.
2026-08-16 22:00:37 -07:00

500 lines
12 KiB
Go

// Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.
// Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"fmt"
"github.com/hanzoai/ai/object"
"github.com/hanzoai/ai/util"
)
// GetGlobalMessages
// @Title GetGlobalMessages
// @Tag Message API
// @Description get global messages
// @Success 200 {array} object.Message The Response object
// @router /get-global-messages [get]
func (c *ApiController) GetGlobalMessages() {
_, ok := c.RequireSignedIn()
if !ok {
return
}
if !c.IsAdmin() {
c.ResponseForbidden(c.T("auth:this operation requires admin privilege"))
return
}
owner := c.GetSessionOwner()
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
store := c.Input().Get("store")
if limit == "" || page == "" {
messages, err := object.GetGlobalMessages()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(messages)
} else {
limit := util.ParseInt(limit)
count, err := object.GetMessageCount(owner, field, value, store)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := util.NewPaginator(c.PageAsked(), limit, count)
messages, err := object.GetPaginationMessages(owner, paginator.Offset(), limit, field, value, sortField, sortOrder, store)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(messages, paginator.Nums())
}
}
// GetMessages
// @Title GetMessages
// @Tag Message API
// @Description get Messages
// @Param user query string true "The user of message"
// @Param chat query string true "The chat of message"
// @Success 200 {array} object.Message The Response object
// @router /get-Messages [get]
func (c *ApiController) GetMessages() {
_, ok := c.RequireSignedIn()
if !ok {
return
}
user := c.Input().Get("user")
chat := c.Input().Get("chat")
selectedUser := c.Input().Get("selectedUser")
if c.IsAdmin() {
user = ""
}
if selectedUser != "" && selectedUser != "null" && c.IsAdmin() {
user = selectedUser
}
if !c.IsAdmin() && user != selectedUser && selectedUser != "" {
c.ResponseError(c.T("controllers:You can only view your own messages"))
return
}
if chat == "" {
owner := c.GetSessionOwner()
messages, err := object.GetMessages(owner, user, "")
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(messages)
return
}
messages, err := object.GetChatMessages(chat)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(messages)
}
// GetMessage
// @Title GetMessage
// @Tag Message API
// @Description get message
// @Param id query string true "The id of message"
// @Success 200 {object} object.Message The Response object
// @router /get-message [get]
func (c *ApiController) GetMessage() {
id := c.Input().Get("id")
message, err := object.GetMessage(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if message == nil {
c.ResponseError("Message not found")
return
}
// Check if user has permission to view this message
if !c.IsAdmin() && !c.IsPreviewMode() {
username := c.GetSessionUsername()
if username != message.User {
c.ResponseForbidden(c.T("auth:Unauthorized operation"))
return
}
}
c.ResponseOk(message)
}
// UpdateMessage
// @Title UpdateMessage
// @Tag Message API
// @Description update message
// @Param id query string true "The id (owner/name) of the message"
// @Param body body object.Message true "The details of the message"
// @Success 200 {object} controllers.Response The Response object
// @router /update-message [post]
func (c *ApiController) UpdateMessage() {
id := c.Input().Get("id")
isHitOnly := c.Input().Get("isHitOnly")
var message object.Message
err := json.Unmarshal(c.Body(), &message)
if err != nil {
c.ResponseError(err.Error())
return
}
ok := c.IsCurrentUser(message.User)
if !ok {
return
}
_, name, err := util.GetOwnerAndNameFromIdWithError(id)
if err != nil {
c.ResponseError(err.Error())
return
}
id = util.GetIdFromOwnerAndName(chatOwner, name)
message.Owner = chatOwner
// The STORED row says whose turn this is. `message.User` above is a value the
// request CARRIES, so it cannot be what authorizes writing over someone else's.
storedMessage, err := object.GetMessage(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if storedMessage == nil {
c.ResponseError(fmt.Sprintf("The message: %s is not found", id))
return
}
if ok = c.IsCurrentUser(storedMessage.User); !ok {
return
}
// A turn's org is the org the usage plane books it to; an update does not move it.
message.Organization = storedMessage.Organization
if message.NeedNotify {
err = message.SendEmail(c.GetAcceptLanguage(), c.GetOrg())
if err != nil {
c.ResponseError(err.Error())
return
}
message.NeedNotify = false
}
success, err := object.UpdateMessage(id, &message, isHitOnly == "true")
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(success)
}
// AddMessage
// @Title AddMessage
// @Tag Message API
// @Description add message
// @Param body body object.Message true "The details of the message"
// @Success 200 {object} object.Chat The Response object
// @router /add-message [post]
func (c *ApiController) AddMessage() {
var message object.Message
err := json.Unmarshal(c.Body(), &message)
if err != nil {
c.ResponseError(err.Error())
return
}
ok := c.IsCurrentUser(message.User)
if !ok {
return
}
message.Owner = chatOwner
id := util.GetIdFromOwnerAndName(message.Owner, message.Name)
originMessage, err := object.GetMessage(id)
if err != nil {
c.ResponseError(err.Error())
return
}
// if originMessage not nil, means edit message, delete all later messages
if originMessage != nil {
// An edit rewrites a STORED turn and drops every turn after it, so the row's
// own user authorizes it — not the user this request carries.
if ok = c.IsCurrentUser(originMessage.User); !ok {
return
}
err = object.DeleteAllLaterMessages(id)
if err != nil {
c.ResponseError(err.Error())
return
}
}
addMessageAfterSuccess := true
if message.IsRegenerated {
messages, err := object.GetChatMessages(message.Chat)
if err != nil {
c.ResponseError(err.Error())
return
}
var lastAIMessage *object.Message
var lastUserMessage *object.Message
for i := len(messages) - 1; i >= 0; i-- {
if messages[i].Author == "AI" && messages[i].ErrorText != "" {
lastAIMessage = messages[i]
break
}
}
if lastAIMessage == nil {
for i := len(messages) - 1; i >= 0; i-- {
if messages[i].Author == "AI" {
lastAIMessage = messages[i]
break
}
}
}
for i := len(messages) - 1; i >= 0; i-- {
if messages[i].Author != "AI" {
lastUserMessage = messages[i]
break
}
}
if lastAIMessage != nil {
if lastAIMessage.ReplyTo == "Welcome" {
message.Author = "AI"
message.ReplyTo = "Welcome"
addMessageAfterSuccess = false
}
_, err = object.DeleteMessage(lastAIMessage)
if err != nil {
c.ResponseError(err.Error())
return
}
}
if lastUserMessage != nil {
_, err = object.DeleteMessage(lastUserMessage)
if err != nil {
c.ResponseError(err.Error())
return
}
}
}
var chat *object.Chat
if message.Chat == "" {
chat, err = c.addInitialChat(c.GetOrg(), message.User, message.Store)
if err != nil {
c.ResponseError(err.Error())
return
}
message.Chat = chat.Name
} else {
chatId := util.GetId(message.Owner, message.Chat)
chat, err = object.GetChat(chatId)
if err != nil {
c.ResponseError(err.Error())
return
}
if chat == nil {
c.ResponseError(fmt.Sprintf("chat:The chat: %s is not found", chatId))
return
}
}
// A turn's org is its CHAT's org — the chat is the row the usage plane reads, and
// a turn cannot be booked to a different tenant than the conversation it is in.
message.Organization = chat.Organization
host := c.Host()
origin := getOriginFromHost(host)
err = object.RefineMessageFiles(&message, origin, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
message.CreatedTime = util.GetCurrentTimeWithMilli()
if message.Text == "" {
c.ResponseError(fmt.Sprintf("The question should not be empty for message: %v", message))
return
}
// Check for forbidden words
storeId := util.GetId(message.Owner, message.Store)
store, err := object.GetStore(storeId)
if err != nil {
c.ResponseError(err.Error())
return
}
if store != nil {
contains, forbiddenWord := store.ContainsForbiddenWords(message.Text)
if contains {
c.ResponseError(fmt.Sprintf("Your message contains a forbidden word: \"%s\"", forbiddenWord))
return
}
}
success, err := object.AddMessage(&message)
if err != nil {
c.ResponseError(err.Error())
return
}
if success && addMessageAfterSuccess {
chatId := util.GetId(message.Owner, message.Chat)
chat, err = object.GetChat(chatId)
if err != nil {
c.ResponseError(err.Error())
return
}
if chat != nil && chat.Type == "AI" {
modelProvider := chat.ModelProvider
if modelProvider == "" {
// Fallback to store's model provider if chat doesn't have one
storeId := util.GetId(chat.Owner, chat.Store)
store, storeErr := object.GetStore(storeId)
if storeErr == nil && store != nil {
modelProvider = store.ModelProvider
}
}
answerMessage := &object.Message{
Owner: message.Owner,
Name: fmt.Sprintf("message_%s", util.GetRandomName()),
CreatedTime: util.GetCurrentTimeEx(message.CreatedTime),
Organization: message.Organization,
Store: chat.Store,
User: message.User,
Chat: message.Chat,
ReplyTo: message.Name,
Author: "AI",
Text: "",
FileName: message.FileName,
VectorScores: []object.VectorScore{},
ModelProvider: modelProvider,
}
_, err = object.AddMessage(answerMessage)
if err != nil {
c.ResponseError(err.Error())
return
}
}
}
c.ResponseOk(chat)
}
// DeleteMessage
// @Title DeleteMessage
// @Tag Message API
// @Description delete message
// @Param body body object.Message true "The details of the message"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-message [post]
func (c *ApiController) DeleteMessage() {
var message object.Message
err := json.Unmarshal(c.Body(), &message)
if err != nil {
c.ResponseError(err.Error())
return
}
message.Owner = chatOwner
success, err := object.DeleteMessage(&message)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(success)
}
func (c *ApiController) DeleteWelcomeMessage() {
var message *object.Message
err := json.Unmarshal(c.Body(), &message)
if err != nil {
c.ResponseError(err.Error())
return
}
id := util.GetIdFromOwnerAndName(chatOwner, message.Name)
message, err = object.GetMessage(id)
if err != nil {
c.ResponseError(err.Error())
return
}
// GetMessage answers (nil, nil) for an id no row matches, so a miss arrives here as
// a nil message rather than as an error. Reading message.User off it panics the
// process, and this route serves callers with no session at all.
if message == nil {
c.ResponseError(fmt.Sprintf("The message: %s is not found", id))
return
}
user := c.GetSessionUsername()
if user != "" && user != message.User {
c.ResponseError(c.T("controllers:No permission"))
return
}
if user == "" {
clientIp := c.getClientIp()
userAgent := c.getUserAgent()
hash := getContentHash(fmt.Sprintf("%s|%s", clientIp, userAgent))
username := fmt.Sprintf("u-%s", hash)
if username != message.User {
c.ResponseError(c.T("controllers:No permission"))
return
}
}
if message.Author != "AI" || message.ReplyTo != "Welcome" {
c.ResponseError(c.T("controllers:No permission"))
return
}
success, err := object.DeleteMessage(message)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(success)
}