package gateway import ( "context" "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history" "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/loop" "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model" ) // This file owns the orchestrator's chat-history persistence hooks (design/16 // §3.3): the user stream is written at submit time and the assistant reply when a // turn settles. Both are silent no-ops when no history store is wired, so the // orchestrator runs unchanged without a store (tests / an unwired gateway). // persistUserMessages writes each RoleUser message of a submitted turn to the // history store so the raw user stream is durable before the turn resolves, then // notifies the transport so every browser of the same account can append it // without a manual refresh (design/16 §3.3, §4.2). deviceID tags the message with // the sending client (design/16 §4.5). It is a no-op when no history store is // wired. Rejected turns (empty, pending-full) never reach it, so nothing vacuous // is persisted. func (o *Orchestrator) persistUserMessages(ctx context.Context, sessionID string, messages []model.Message, deviceID string) { if o.history == nil { return } for _, m := range messages { if m.Role != model.RoleUser { continue } text, image := messageTextImage(m) if text == "" && image == "" { continue } full, err := o.history.AppendFull(ctx, history.Message{SessionID: sessionID, Role: history.RoleUser, Content: text, Image: image, DeviceID: deviceID}) if err != nil { o.log.Error("orchestrator persist user", "err", err, "session", sessionID, "device_id", deviceID) continue } o.notifyPersisted(full) } } // persistAssistantReply writes the final assistant text of a settled turn to the // history store, then notifies the transport (design/16 §3.3, §4.2). deviceID tags // the reply with the client that sent the turn (design/16 §4.5). It is a no-op // when no history store is wired or the turn produced no text (interrupted/errored // turns leave res nil). The write runs under a fresh background context so a // canceled turn context never aborts it. func (o *Orchestrator) persistAssistantReply(sessionID string, res *loop.Result, deviceID string) { if o.history == nil || res == nil || res.Text == "" { return } full, err := o.history.AppendFull(context.Background(), history.Message{SessionID: sessionID, Role: history.RoleAssistant, Content: res.Text, DeviceID: deviceID}) if err != nil { o.log.Error("orchestrator persist assistant", "err", err, "session", sessionID, "device_id", deviceID) return } o.notifyPersisted(full) } // messageTextImage returns the concatenated text and the first image URL of a // message's content parts, for persistence into the chat_messages columns. func messageTextImage(m model.Message) (text, image string) { for _, c := range m.Content { if c.Type == model.ContentTypeText { text += c.Text } else if c.Type == model.ContentTypeImage && image == "" { image = c.ImageURL } } return text, image }