feat(gateway): flip channel boundary onto messaging.Message
Replaced gateway.Message as the currency at the channel-facing boundary with the canonical internal/domain/messaging.Message. Channel adapters now build the record directly (RoleUser, ConversationID, Sender) and the Router hands it back unchanged, so nothing converts between two shapes in process. gateway.Message is deleted; the dashboard route that had no home in the record lives in a new Inbound envelope (Message + transport-only Page), which reaches the system prompt and is never persisted. Role is now set at construction instead of derived at the store boundary, and the assistant reply is a direct messaging.Message (RoleAssistant, Sender=botUser). The gRPC proto is unchanged: pb.Message still carries no role, and both sides keep deriving it from the owning session's bot identity via gateway.RoleForSender (ToStoredMessage/FromStoredMessage are deleted). Adds tests that the old shape could not express: Page reaches the system prompt but not the persisted record, and a channel-built Inbound round-trips with the Role the channel set. Refs: archie-core-9g5e
This commit is contained in:
1 parent
0ec4ececd5
commit
7c8f625f0e
47 files changed
+755
-699
No files matched your search
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
@@ -826,8 +827,8 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) {
|
||||
router := gateway.NewRouter(st, nil, "test")
|
||||
configureTaskCommands(router, creator, controller, chatTaskListerAdapter{tasks: st.Tasks}, defaultIdentity)
|
||||
|
||||
reply, err := router.Route(ctx, gateway.Message{
|
||||
Text: "/spawn identity=reviewer workflow=feasibility Design native tasks",
|
||||
reply, err := router.Route(ctx, gateway.Inbound{
|
||||
Message: messaging.Message{Role: messaging.RoleUser, Text: "/spawn identity=reviewer workflow=feasibility Design native tasks"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -853,7 +854,7 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) {
|
||||
if err != nil || task == nil || task.Status != workflow.StatusWaitingHuman {
|
||||
t.Fatalf("waiting task = (%+v, %v)", task, err)
|
||||
}
|
||||
reply, err = router.Route(ctx, gateway.Message{Text: fmt.Sprintf("/approve identity=reviewer %d", taskID)})
|
||||
reply, err = router.Route(ctx, gateway.Inbound{Message: messaging.Message{Role: messaging.RoleUser, Text: fmt.Sprintf("/approve identity=reviewer %d", taskID)}})
|
||||
if err != nil || !strings.Contains(reply, "approved") {
|
||||
t.Fatalf("approve = (%q, %v)", reply, err)
|
||||
}
|
||||
@@ -862,7 +863,7 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) {
|
||||
t.Fatalf("approved task = (%+v, %v)", task, err)
|
||||
}
|
||||
|
||||
reply, err = router.Route(ctx, gateway.Message{Text: "/spawn identity=reviewer Cancel me"})
|
||||
reply, err = router.Route(ctx, gateway.Inbound{Message: messaging.Message{Role: messaging.RoleUser, Text: "/spawn identity=reviewer Cancel me"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -870,11 +871,11 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) {
|
||||
if _, err := fmt.Sscanf(reply, "Created task %d:", &cancelID); err != nil {
|
||||
t.Fatalf("cancel spawn reply = %q, parse error = %v", reply, err)
|
||||
}
|
||||
reply, err = router.Route(ctx, gateway.Message{Text: fmt.Sprintf("/cancel identity=builder %d", cancelID)})
|
||||
reply, err = router.Route(ctx, gateway.Inbound{Message: messaging.Message{Role: messaging.RoleUser, Text: fmt.Sprintf("/cancel identity=builder %d", cancelID)}})
|
||||
if err != nil || !strings.Contains(reply, "different identity") {
|
||||
t.Fatalf("cross-identity cancel = (%q, %v)", reply, err)
|
||||
}
|
||||
reply, err = router.Route(ctx, gateway.Message{Text: fmt.Sprintf("/cancel identity=reviewer %d", cancelID)})
|
||||
reply, err = router.Route(ctx, gateway.Inbound{Message: messaging.Message{Role: messaging.RoleUser, Text: fmt.Sprintf("/cancel identity=reviewer %d", cancelID)}})
|
||||
if err != nil || !strings.Contains(reply, "cancelled") {
|
||||
t.Fatalf("cancel = (%q, %v)", reply, err)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
@@ -39,7 +40,7 @@ func (f *fakeChat) GetSession(context.Context, string) (gateway.SessionContext,
|
||||
return gateway.SessionContext{}, false, nil
|
||||
}
|
||||
|
||||
func (f *fakeChat) RecentMessages(context.Context, string, int) ([]gateway.Message, error) {
|
||||
func (f *fakeChat) RecentMessages(context.Context, string, int) ([]messaging.Message, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -47,11 +48,11 @@ func (f *fakeChat) RecentTurns(context.Context, string, int) ([]gateway.TurnReco
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeChat) Route(context.Context, gateway.Message) (gateway.ChatReply, error) {
|
||||
func (f *fakeChat) Route(context.Context, gateway.Inbound) (gateway.ChatReply, error) {
|
||||
return gateway.ChatReply{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeChat) Stream(context.Context, gateway.Message) (<-chan gateway.ChatEvent, error) {
|
||||
func (f *fakeChat) Stream(context.Context, gateway.Inbound) (<-chan gateway.ChatEvent, error) {
|
||||
ch := make(chan gateway.ChatEvent)
|
||||
close(ch)
|
||||
return ch, nil
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
@@ -201,11 +202,12 @@ func (g *Gateway) processMessage(ctx context.Context, from, to, raw string) {
|
||||
// following Content-Type or headers.
|
||||
text := extractBody(raw)
|
||||
|
||||
msg := gateway.Message{
|
||||
ChannelID: to,
|
||||
From: from,
|
||||
Text: text,
|
||||
}
|
||||
msg := gateway.Inbound{Message: messaging.Message{
|
||||
ConversationID: messaging.ConversationID{ChannelID: to},
|
||||
Sender: from,
|
||||
Role: messaging.RoleUser,
|
||||
Text: text,
|
||||
}}
|
||||
reply, err := router.Route(ctx, msg)
|
||||
if err != nil {
|
||||
g.log.Error("email route", "err", err, "from", from)
|
||||
|
||||
@@ -65,9 +65,9 @@ func TestSMTPReceiveAndRoute(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
g := New(":0", "", log)
|
||||
|
||||
router := gateway.NewRouter(nil, func(ctx context.Context, msg gateway.Message) (string, error) {
|
||||
if msg.From != "sender@test.com" {
|
||||
return "", fmt.Errorf("unexpected sender: %s", msg.From)
|
||||
router := gateway.NewRouter(nil, func(ctx context.Context, in gateway.Inbound) (string, error) {
|
||||
if in.Message.Sender != "sender@test.com" {
|
||||
return "", fmt.Errorf("unexpected sender: %s", in.Message.Sender)
|
||||
}
|
||||
return "got it", nil
|
||||
}, "email")
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
@@ -425,12 +426,12 @@ func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.M
|
||||
// turns is only built by launch, so a gateway that has never started
|
||||
// simply has nothing to stop. Report that rather than failing.
|
||||
if g.turns != nil && router != nil {
|
||||
session, err := router.ResolveSessionKey(ctx, gateway.Message{
|
||||
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
||||
ThreadID: threadIDString(msg.MessageThreadID),
|
||||
From: msg.From.Username,
|
||||
Text: msg.Text,
|
||||
})
|
||||
session, err := router.ResolveSessionKey(ctx, gateway.Inbound{Message: messaging.Message{
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
Text: msg.Text,
|
||||
}})
|
||||
if err != nil {
|
||||
g.log.Error("resolve session for stop", "error", err)
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "❌ Could not resolve this conversation's session.")
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
@@ -211,7 +212,9 @@ func (g *Gateway) sendModelSelector(
|
||||
router *gateway.Router,
|
||||
) {
|
||||
if router.Models == nil || len(router.Models.Models()) == 0 {
|
||||
reply, err := router.Route(ctx, gateway.Message{Text: "/model"})
|
||||
reply, err := router.Route(ctx, gateway.Inbound{
|
||||
Message: messaging.Message{Role: messaging.RoleUser, Text: "/model"},
|
||||
})
|
||||
if err != nil {
|
||||
g.log.Error("model selector fallback failed", "error", err)
|
||||
return
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
@@ -469,12 +470,12 @@ func (g *Gateway) resumeHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reply, err := router.Route(ctx, gateway.Message{
|
||||
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
||||
ThreadID: threadIDString(msg.MessageThreadID),
|
||||
From: msg.From.Username,
|
||||
Text: msg.Text,
|
||||
})
|
||||
reply, err := router.Route(ctx, gateway.Inbound{Message: messaging.Message{
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
Text: msg.Text,
|
||||
}})
|
||||
if err != nil {
|
||||
g.log.Error("resume handler failed", "error", err)
|
||||
return
|
||||
@@ -491,12 +492,12 @@ func (g *Gateway) routeCmdHandler(router *gateway.Router, cmd string) bot.Handle
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reply, err := router.Route(ctx, gateway.Message{
|
||||
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
||||
ThreadID: threadIDString(msg.MessageThreadID),
|
||||
From: msg.From.Username,
|
||||
Text: cmd,
|
||||
})
|
||||
reply, err := router.Route(ctx, gateway.Inbound{Message: messaging.Message{
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
Text: cmd,
|
||||
}})
|
||||
if err != nil {
|
||||
g.log.Error("command handler failed", "command", cmd, "error", err)
|
||||
return
|
||||
@@ -606,19 +607,19 @@ func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models
|
||||
// /stop meant to cancel it, which would sit unread until the turn it was
|
||||
// aimed at had already finished.
|
||||
func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, router *gateway.Router) {
|
||||
gm := gateway.Message{
|
||||
gm := gateway.Inbound{Message: messaging.Message{
|
||||
// Telegram's message ID makes persistence idempotent: the store
|
||||
// derives a canonical ID from it, so a redelivered update is a
|
||||
// no-op rather than appending a duplicate or overwriting the
|
||||
// stored record, which must stay immutable. Date is the sender's
|
||||
// clock reading and is what history should be ordered by.
|
||||
SourceID: fmt.Sprintf("%d", msg.ID),
|
||||
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
||||
ThreadID: threadIDString(msg.MessageThreadID),
|
||||
From: msg.From.Username,
|
||||
Text: msg.Text,
|
||||
At: time.Unix(int64(msg.Date), 0).UTC(),
|
||||
}
|
||||
SourceID: fmt.Sprintf("%d", msg.ID),
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
Text: msg.Text,
|
||||
At: time.Unix(int64(msg.Date), 0).UTC(),
|
||||
}}
|
||||
|
||||
// The lane key must be the session, so that /stop -- which resolves
|
||||
// the same key -- reaches the turn the sender is actually watching.
|
||||
@@ -678,9 +679,18 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────
|
||||
|
||||
// conversationID addresses the chat a Telegram message arrived in: the
|
||||
// chat ID, and the topic thread within it for supergroups.
|
||||
func conversationID(msg *models.Message) messaging.ConversationID {
|
||||
return messaging.ConversationID{
|
||||
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
||||
ThreadID: threadIDString(msg.MessageThreadID),
|
||||
}
|
||||
}
|
||||
|
||||
// threadIDString converts a Telegram message_thread_id to a string suitable
|
||||
// for gateway.Message.ThreadID and SessionSource.ThreadID. A zero value
|
||||
// (no topic thread, or the General topic) maps to empty string so that
|
||||
// for messaging.ConversationID.ThreadID and SessionSource.ThreadID. A zero
|
||||
// value (no topic thread, or the General topic) maps to empty string so that
|
||||
// flat-chat routing continues to work without changes.
|
||||
func threadIDString(id int) string {
|
||||
if id == 0 {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
@@ -169,11 +170,12 @@ func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
msg := gateway.Message{
|
||||
ChannelID: route.Path,
|
||||
From: "webhook",
|
||||
Text: text,
|
||||
}
|
||||
msg := gateway.Inbound{Message: messaging.Message{
|
||||
ConversationID: messaging.ConversationID{ChannelID: route.Path},
|
||||
Sender: "webhook",
|
||||
Role: messaging.RoleUser,
|
||||
Text: text,
|
||||
}}
|
||||
reply, err := router.Route(r.Context(), msg)
|
||||
if err != nil {
|
||||
g.log.Error("webhook route", "err", err, "path", route.Path)
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestBranchGivesInheritedMessagesTheirOwnIdentity(t *testing.T) {
|
||||
t.Fatalf("RecentMessages(parent): %v", err)
|
||||
}
|
||||
|
||||
reply, err := r.Route(ctx, Message{Text: "/branch side-quest", ChannelID: "chat-1"})
|
||||
reply, err := r.Route(ctx, inbound("chat-1", "/branch side-quest"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route(/branch): %v", err)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package gateway
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -11,12 +12,12 @@ import (
|
||||
type ChatContract interface { //nolint:interfacebloat // wire contract intentionally covers the complete Gateway facade
|
||||
Snapshot(context.Context) (ChatSnapshot, error)
|
||||
GetSession(context.Context, string) (SessionContext, bool, error)
|
||||
RecentMessages(context.Context, string, int) ([]Message, error)
|
||||
RecentMessages(context.Context, string, int) ([]messaging.Message, error)
|
||||
RecentTurns(context.Context, string, int) ([]TurnRecord, error)
|
||||
Route(context.Context, Message) (ChatReply, error)
|
||||
Route(context.Context, Inbound) (ChatReply, error)
|
||||
// Stream emits started, delta/tool/media, then done or error, in order.
|
||||
// Callers must drain the stream or cancel the context. Cancellation closes it.
|
||||
Stream(context.Context, Message) (<-chan ChatEvent, error)
|
||||
Stream(context.Context, Inbound) (<-chan ChatEvent, error)
|
||||
Cancel(context.Context, string) (ChatCancellation, error)
|
||||
SetPersona(context.Context, string, string) (bool, error)
|
||||
ChatTaskActionContract
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -67,19 +68,16 @@ func (a *LocalChatAdapter) GetSession(ctx context.Context, id string) (SessionCo
|
||||
return *session, true, nil
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) RecentMessages(ctx context.Context, id string, n int) ([]Message, error) {
|
||||
// The ChatContract still speaks the channel-facing Message (dashboard
|
||||
// JSON, channel frontends); migrating those consumers is follow-up
|
||||
// work (bd label messaging-migration). Convert at this boundary.
|
||||
func (a *LocalChatAdapter) RecentMessages(ctx context.Context, id string, n int) ([]messaging.Message, error) {
|
||||
stored, err := a.Sessions.RecentMessages(ctx, id, n)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Message, 0, len(stored))
|
||||
for _, m := range stored {
|
||||
out = append(out, FromStoredMessage(m))
|
||||
}
|
||||
return out, nil
|
||||
// A snapshot, and non-nil even when the session is empty: the contract
|
||||
// promises callers a slice they own, and an empty history renders as []
|
||||
// rather than null.
|
||||
out := make([]messaging.Message, 0, len(stored))
|
||||
return append(out, stored...), nil
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) RecentTurns(ctx context.Context, id string, n int) ([]TurnRecord, error) {
|
||||
@@ -89,12 +87,12 @@ func (a *LocalChatAdapter) RecentTurns(ctx context.Context, id string, n int) ([
|
||||
return []TurnRecord{}, nil
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) Route(ctx context.Context, msg Message) (ChatReply, error) {
|
||||
reply, err := a.Router.Route(ctx, msg)
|
||||
func (a *LocalChatAdapter) Route(ctx context.Context, in Inbound) (ChatReply, error) {
|
||||
reply, err := a.Router.Route(ctx, in)
|
||||
if err != nil {
|
||||
return ChatReply{}, err
|
||||
}
|
||||
id, err := a.Router.ResolveSessionKey(ctx, msg)
|
||||
id, err := a.Router.ResolveSessionKey(ctx, in)
|
||||
return ChatReply{Text: reply, SessionID: id}, err
|
||||
}
|
||||
|
||||
@@ -126,31 +124,31 @@ func (a *LocalChatAdapter) ApplyTaskAction(ctx context.Context, identity string,
|
||||
return a.TaskActor.ApplyChatTaskAction(ctx, identity, taskID, action)
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) Stream(ctx context.Context, msg Message) (<-chan ChatEvent, error) {
|
||||
func (a *LocalChatAdapter) Stream(ctx context.Context, in Inbound) (<-chan ChatEvent, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := a.Router.ResolveSessionKey(ctx, msg)
|
||||
id, err := a.Router.ResolveSessionKey(ctx, in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
events := make(chan ChatEvent, 32)
|
||||
events <- ChatEvent{Kind: "started", SessionID: id}
|
||||
go a.stream(ctx, msg, id, events)
|
||||
go a.stream(ctx, in, id, events)
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) stream(ctx context.Context, msg Message, id string, events chan ChatEvent) {
|
||||
func (a *LocalChatAdapter) stream(ctx context.Context, in Inbound, id string, events chan ChatEvent) {
|
||||
defer close(events)
|
||||
pending := make(chan ChatEvent, 32)
|
||||
stream := localChatStream{done: ctx.Done(), events: pending, sessionID: id}
|
||||
run := func(turnCtx context.Context) ChatEvent {
|
||||
reply, err := a.Router.RouteStream(turnCtx, msg, stream)
|
||||
reply, err := a.Router.RouteStream(turnCtx, in, stream)
|
||||
if err != nil {
|
||||
return ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}
|
||||
}
|
||||
resolvedID := id
|
||||
if resolved, err := a.Router.ResolveSessionKey(ctx, msg); err == nil {
|
||||
if resolved, err := a.Router.ResolveSessionKey(ctx, in); err == nil {
|
||||
resolvedID = resolved
|
||||
}
|
||||
return ChatEvent{Kind: "done", Text: reply, SessionID: resolvedID}
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestLocalChatSnapshotAndStream(t *testing.T) {
|
||||
if _, found, err := chat.GetSession(ctx, "absent"); err != nil || found {
|
||||
t.Fatalf("missing session = %v, %v", found, err)
|
||||
}
|
||||
events, err := chat.Stream(ctx, Message{ChannelID: "browser", From: "web", Text: "/help"})
|
||||
events, err := chat.Stream(ctx, inboundFrom("browser", "web", "/help"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func TestLocalChatSnapshotAndStream(t *testing.T) {
|
||||
}
|
||||
cancelCtx, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err := chat.Stream(cancelCtx, Message{}); err == nil {
|
||||
if _, err := chat.Stream(cancelCtx, inbound("", "")); err == nil {
|
||||
t.Fatal("cancelled context accepted")
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,7 @@ func TestCompressCommandDispatch(t *testing.T) {
|
||||
const seeded = 40
|
||||
seedForCompress(t, store, sessionID, seeded)
|
||||
|
||||
reply, err := r.handleCompress(ctx, Message{ChannelID: "chat-1"}, tc.rest)
|
||||
reply, err := r.handleCompress(ctx, inbound("chat-1", "").Message, tc.rest)
|
||||
if err != nil {
|
||||
t.Fatalf("handleCompress(%q): %v", tc.rest, err)
|
||||
}
|
||||
|
||||
+38
-63
@@ -20,53 +20,28 @@ import (
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// Message is an inbound message from a gateway connection.
|
||||
type Message struct {
|
||||
// MessageID is the canonical, application-generated identifier for
|
||||
// this message. It is assigned by the message store, stable, and the
|
||||
// handle branch points and related records correlate on.
|
||||
//
|
||||
// Populated on read, and HONOURED on write: saving a message that
|
||||
// already carries one keeps that identity, which is what lets a
|
||||
// read-modify-write of a history preserve identities rather than
|
||||
// minting new ones. A caller copying messages into a different session
|
||||
// must therefore clear it, or two sessions end up claiming one
|
||||
// identity -- see handleBranch.
|
||||
//
|
||||
// Leave it empty for a newly received message: the store derives one,
|
||||
// from SourceID when there is one.
|
||||
MessageID string
|
||||
// SourceID is the channel-native identifier (e.g. a Telegram
|
||||
// message_id). It is external correlation metadata, never the
|
||||
// canonical identity: the store derives a stable MessageID from it so
|
||||
// redelivering an update is idempotent rather than duplicating. Empty
|
||||
// for messages with no upstream identity, which are always appended.
|
||||
SourceID string
|
||||
// ChannelID identifies the conversation within the channel (e.g. a
|
||||
// Telegram chat ID). Replies are sent back to this ID.
|
||||
ChannelID string
|
||||
// ThreadID identifies the topic thread within the conversation, for
|
||||
// platforms that support threading (Telegram supergroup topics,
|
||||
// Slack threads, Discord forum posts). Empty for flat chats.
|
||||
ThreadID string
|
||||
// From identifies the sender (channel-specific: username, user ID).
|
||||
From string
|
||||
// Text is the raw message text, including any leading slash command.
|
||||
Text string
|
||||
// Page is the dashboard route the operator is on when they sent this
|
||||
// message (e.g. "/tasks", "/logs"). It is per-message, not per-session:
|
||||
// the operator navigates freely while a conversation stays open, so the
|
||||
// agent is told where they are right now. Empty for non-web channels,
|
||||
// which have no page context.
|
||||
// Inbound is a message arriving from a channel together with the
|
||||
// transport context that is not part of the canonical record.
|
||||
//
|
||||
// Message is the record itself, exactly as it will be persisted. Channels
|
||||
// construct it directly: ConversationID addresses the chat (a Telegram
|
||||
// chat ID and topic thread, an email recipient, a webhook path), Sender is
|
||||
// the channel-native attribution, and Role is always messaging.RoleUser --
|
||||
// a channel only ever carries what a person said. ID is left empty for a
|
||||
// newly received message so the store derives one from SourceID, and
|
||||
// honoured when set, which is what lets a read-modify-write of a history
|
||||
// keep its identities rather than minting new ones.
|
||||
type Inbound struct {
|
||||
Message messaging.Message
|
||||
// Page is the dashboard route the operator is on when they sent
|
||||
// this message. Transport-only: it reaches the system prompt and
|
||||
// is never persisted. Empty for non-web channels.
|
||||
Page string
|
||||
// At is when the message happened in application time and is the sole
|
||||
// ordering key for conversation history. A zero value is stamped with the
|
||||
// current time at save.
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// Lifecycle receives adapter-owned startup facts. Callbacks are optional.
|
||||
@@ -108,7 +83,7 @@ type StatusReader interface {
|
||||
// nil (not yet wired -- see abg.13), non-command messages get a static
|
||||
// "LLM not configured" response. Gateways call this for any message the
|
||||
// router did not handle directly.
|
||||
type LLMResponder func(ctx context.Context, msg Message) (string, error)
|
||||
type LLMResponder func(ctx context.Context, in Inbound) (string, error)
|
||||
|
||||
// LLMStreamResponder is the streaming counterpart of LLMResponder. It
|
||||
// reports the turn's progress -- text fragments and completed tool calls
|
||||
@@ -120,7 +95,7 @@ type LLMResponder func(ctx context.Context, msg Message) (string, error)
|
||||
// Router falls back to the blocking LLMResponder. stream is called from the
|
||||
// generating goroutine and must not block for long -- adapters should
|
||||
// throttle their own network writes rather than stall the stream.
|
||||
type LLMStreamResponder func(ctx context.Context, msg Message, stream TurnStream) (string, error)
|
||||
type LLMStreamResponder func(ctx context.Context, in Inbound, stream TurnStream) (string, error)
|
||||
|
||||
// ModelManager provides access to available models and allows switching the
|
||||
// active LLM model. The daemon supplies an implementation backed by its
|
||||
@@ -326,11 +301,11 @@ func (r *Router) SessionTracker() *sessionTracker {
|
||||
|
||||
// Route dispatches msg and returns the reply. Gateway-local commands
|
||||
// are handled directly; everything else goes to the LLM responder.
|
||||
func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
|
||||
text := strings.TrimSpace(msg.Text)
|
||||
func (r *Router) Route(ctx context.Context, in Inbound) (string, error) {
|
||||
text := strings.TrimSpace(in.Message.Text)
|
||||
cmd, _ := parseCmd(text, r.gatewayName)
|
||||
|
||||
if reply, handled, err := r.dispatchLocal(ctx, msg, text, cmd); handled {
|
||||
if reply, handled, err := r.dispatchLocal(ctx, in.Message, text, cmd); handled {
|
||||
return reply, err
|
||||
}
|
||||
|
||||
@@ -340,16 +315,16 @@ func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
|
||||
if r.LLM == nil {
|
||||
return "I'm running but LLM processing isn't wired yet. Try /status.", nil
|
||||
}
|
||||
reply, err := r.LLM(ctx, msg)
|
||||
reply, err := r.LLM(ctx, in)
|
||||
if err == nil {
|
||||
r.maybeAutoTitle(ctx, msg)
|
||||
r.maybeAutoTitle(ctx, in.Message)
|
||||
}
|
||||
return reply, err
|
||||
}
|
||||
|
||||
// dispatchLocal handles recognized local commands. Returns (reply,
|
||||
// true) when the command was recognized and handled.
|
||||
func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd string) (string, bool, error) {
|
||||
func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, text, cmd string) (string, bool, error) {
|
||||
rest := restAfter(text, cmd, r.gatewayName)
|
||||
|
||||
switch cmd {
|
||||
@@ -391,7 +366,7 @@ func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd strin
|
||||
// dispatchLocalMisc handles the remaining recognized local commands not
|
||||
// covered by dispatchLocal's first switch. Split out to keep cyclomatic
|
||||
// complexity down.
|
||||
func (r *Router) dispatchLocalMisc(ctx context.Context, msg Message, cmd, rest string) (string, bool, error) {
|
||||
func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, cmd, rest string) (string, bool, error) {
|
||||
switch cmd {
|
||||
case "/sessions":
|
||||
reply, err := r.handleSessions(ctx, msg)
|
||||
@@ -468,7 +443,7 @@ func (r *Router) handleRestartAdapter(ctx context.Context) string {
|
||||
// (/new, /topic, /retry, /undo, /title, /branch, /compress and their
|
||||
// aliases). Split out from dispatchLocal to keep cyclomatic complexity
|
||||
// down.
|
||||
func (r *Router) dispatchSessionCommand(ctx context.Context, msg Message, cmd, rest string) (string, bool, error) {
|
||||
func (r *Router) dispatchSessionCommand(ctx context.Context, msg messaging.Message, cmd, rest string) (string, bool, error) {
|
||||
switch cmd {
|
||||
case "/new", "/reset":
|
||||
reply, err := r.handleNew(ctx, msg, rest)
|
||||
@@ -509,17 +484,17 @@ func (r *Router) dispatchSessionCommand(ctx context.Context, msg Message, cmd, r
|
||||
// configured, RouteStream is exactly Route -- callers get the whole reply
|
||||
// at the end and simply never see a delta, so an adapter can always call
|
||||
// RouteStream without checking first.
|
||||
func (r *Router) RouteStream(ctx context.Context, msg Message, stream TurnStream) (string, error) {
|
||||
func (r *Router) RouteStream(ctx context.Context, in Inbound, stream TurnStream) (string, error) {
|
||||
if r.LLMStream == nil || stream == nil {
|
||||
return r.Route(ctx, msg)
|
||||
return r.Route(ctx, in)
|
||||
}
|
||||
cmd, _ := parseCmd(strings.TrimSpace(msg.Text), r.gatewayName)
|
||||
cmd, _ := parseCmd(strings.TrimSpace(in.Message.Text), r.gatewayName)
|
||||
if isLocalCommand(cmd) || strings.HasPrefix(cmd, "/") {
|
||||
return r.Route(ctx, msg)
|
||||
return r.Route(ctx, in)
|
||||
}
|
||||
reply, err := r.LLMStream(ctx, msg, stream)
|
||||
reply, err := r.LLMStream(ctx, in, stream)
|
||||
if err == nil {
|
||||
r.maybeAutoTitle(ctx, msg)
|
||||
r.maybeAutoTitle(ctx, in.Message)
|
||||
}
|
||||
return reply, err
|
||||
}
|
||||
@@ -1048,7 +1023,7 @@ func (r *Router) handleProfile() (string, error) {
|
||||
return strings.TrimSpace(b.String()), nil
|
||||
}
|
||||
|
||||
func (r *Router) handleSessions(ctx context.Context, msg Message) (string, error) {
|
||||
func (r *Router) handleSessions(ctx context.Context, msg messaging.Message) (string, error) {
|
||||
if r.Sessions == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
@@ -1058,7 +1033,7 @@ func (r *Router) handleSessions(ctx context.Context, msg Message) (string, error
|
||||
}
|
||||
active := ""
|
||||
if r.sessionTracker != nil {
|
||||
active = r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
active = r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
}
|
||||
return renderSessionList(sessions, active, time.Now()), nil
|
||||
}
|
||||
@@ -1172,7 +1147,7 @@ func relativeAge(t, now time.Time) string {
|
||||
|
||||
// handleResume switches the active session for the current channel+thread
|
||||
// to the session whose ID matches or is uniquely prefixed by arg.
|
||||
func (r *Router) handleResume(ctx context.Context, msg Message, arg string) (string, error) {
|
||||
func (r *Router) handleResume(ctx context.Context, msg messaging.Message, arg string) (string, error) {
|
||||
arg = strings.TrimSpace(arg)
|
||||
if arg == "" {
|
||||
return "Usage: /resume <session-id>", nil
|
||||
@@ -1194,9 +1169,9 @@ func (r *Router) handleResume(ctx context.Context, msg Message, arg string) (str
|
||||
return r.resumeSession(msg, *match), nil
|
||||
}
|
||||
|
||||
func (r *Router) resumeSession(msg Message, s SessionContext) string {
|
||||
func (r *Router) resumeSession(msg messaging.Message, s SessionContext) string {
|
||||
if r.sessionTracker != nil {
|
||||
r.sessionTracker.setActive(msg.ChannelID, msg.ThreadID, s.SessionID)
|
||||
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, s.SessionID)
|
||||
}
|
||||
return fmt.Sprintf("Resumed session %s.", s.SessionID)
|
||||
}
|
||||
|
||||
@@ -9,12 +9,12 @@ import (
|
||||
// RouteStream must degrade to Route when no streaming responder is set, so
|
||||
// adapters can always call it without first checking for support.
|
||||
func TestRouteStreamFallsBackWhenNoStreamResponder(t *testing.T) {
|
||||
r := NewRouter(nil, func(context.Context, Message) (string, error) {
|
||||
r := NewRouter(nil, func(context.Context, Inbound) (string, error) {
|
||||
return "blocking reply", nil
|
||||
}, "telegram")
|
||||
|
||||
var deltas []string
|
||||
got, err := r.RouteStream(context.Background(), Message{Text: "hello"}, DeltaFunc(func(d string) {
|
||||
got, err := r.RouteStream(context.Background(), inbound("", "hello"), DeltaFunc(func(d string) {
|
||||
deltas = append(deltas, d)
|
||||
}))
|
||||
if err != nil {
|
||||
@@ -30,7 +30,7 @@ func TestRouteStreamFallsBackWhenNoStreamResponder(t *testing.T) {
|
||||
|
||||
func TestRouteStreamStreamsFreeText(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "telegram")
|
||||
r.LLMStream = func(_ context.Context, _ Message, stream TurnStream) (string, error) {
|
||||
r.LLMStream = func(_ context.Context, _ Inbound, stream TurnStream) (string, error) {
|
||||
for _, d := range []string{"a", "b", "c"} {
|
||||
stream.Delta(d)
|
||||
}
|
||||
@@ -38,7 +38,7 @@ func TestRouteStreamStreamsFreeText(t *testing.T) {
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
got, err := r.RouteStream(context.Background(), Message{Text: "hello"}, DeltaFunc(func(d string) {
|
||||
got, err := r.RouteStream(context.Background(), inbound("", "hello"), DeltaFunc(func(d string) {
|
||||
sb.WriteString(d)
|
||||
}))
|
||||
if err != nil {
|
||||
@@ -54,12 +54,12 @@ func TestRouteStreamStreamsFreeText(t *testing.T) {
|
||||
func TestRouteStreamDoesNotStreamLocalCommands(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "telegram")
|
||||
streamed := false
|
||||
r.LLMStream = func(context.Context, Message, TurnStream) (string, error) {
|
||||
r.LLMStream = func(context.Context, Inbound, TurnStream) (string, error) {
|
||||
streamed = true
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if _, err := r.RouteStream(context.Background(), Message{Text: "/status"}, DeltaFunc(func(string) {})); err != nil {
|
||||
if _, err := r.RouteStream(context.Background(), inbound("", "/status"), DeltaFunc(func(string) {})); err != nil {
|
||||
t.Fatalf("RouteStream: %v", err)
|
||||
}
|
||||
if streamed {
|
||||
@@ -70,12 +70,12 @@ func TestRouteStreamDoesNotStreamLocalCommands(t *testing.T) {
|
||||
func TestRouteStreamRejectsUnknownCommandLocally(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "telegram")
|
||||
streamed := false
|
||||
r.LLMStream = func(context.Context, Message, TurnStream) (string, error) {
|
||||
r.LLMStream = func(context.Context, Inbound, TurnStream) (string, error) {
|
||||
streamed = true
|
||||
return "ok", nil
|
||||
}
|
||||
|
||||
reply, err := r.RouteStream(context.Background(), Message{Text: "/commands"}, DeltaFunc(func(string) {}))
|
||||
reply, err := r.RouteStream(context.Background(), inbound("", "/commands"), DeltaFunc(func(string) {}))
|
||||
if err != nil {
|
||||
t.Fatalf("RouteStream: %v", err)
|
||||
}
|
||||
|
||||
@@ -21,13 +21,13 @@ func (f *fakeStore) StatusCounts(ctx context.Context) (map[string]int, error) {
|
||||
return f.counts, f.err
|
||||
}
|
||||
|
||||
func fakeLLM(ctx context.Context, msg Message) (string, error) {
|
||||
return "llm: " + msg.Text, nil
|
||||
func fakeLLM(ctx context.Context, in Inbound) (string, error) {
|
||||
return "llm: " + in.Message.Text, nil
|
||||
}
|
||||
|
||||
func TestRouteStatusShowsQueueDepthNotPerTaskCounts(t *testing.T) {
|
||||
r := NewRouter(&fakeStore{counts: map[string]int{"queued": 2, "pr_open": 1}}, nil, "test")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/status"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/status"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func TestRouteStatusIncludesActiveProviderAndModel(t *testing.T) {
|
||||
r := NewRouter(&fakeStore{counts: map[string]int{"running": 1}}, nil, "test")
|
||||
r.Models = manager
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/status"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/status"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -59,7 +59,7 @@ func TestRouteStatusIncludesActiveProviderAndModel(t *testing.T) {
|
||||
|
||||
func TestRouteStatusAtMention(t *testing.T) {
|
||||
r := NewRouter(&fakeStore{counts: map[string]int{"running": 3}}, nil, "archie")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/status@archie"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/status@archie"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -70,7 +70,7 @@ func TestRouteStatusAtMention(t *testing.T) {
|
||||
|
||||
func TestRouteStatusEmpty(t *testing.T) {
|
||||
r := NewRouter(&fakeStore{counts: map[string]int{}}, nil, "test")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/status"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/status"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -191,7 +191,7 @@ func TestFormatStatus(t *testing.T) {
|
||||
|
||||
func TestRouteStatusError(t *testing.T) {
|
||||
r := NewRouter(&fakeStore{err: errors.New("db down")}, nil, "test")
|
||||
if _, err := r.Route(context.Background(), Message{Text: "/status"}); err == nil {
|
||||
if _, err := r.Route(context.Background(), inbound("", "/status")); err == nil {
|
||||
t.Error("expected error from Route when StatusCounts fails")
|
||||
}
|
||||
}
|
||||
@@ -209,7 +209,7 @@ func (f *fakeChatTaskLister) ListChatTasks(ctx context.Context, identity string,
|
||||
|
||||
func TestRouteTasksNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/tasks"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/tasks"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -221,7 +221,7 @@ func TestRouteTasksNotConfigured(t *testing.T) {
|
||||
func TestRouteTasksEmpty(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test")
|
||||
r.TaskLister = &fakeChatTaskLister{}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/tasks"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/tasks"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -234,7 +234,7 @@ func TestRouteTasksEmpty(t *testing.T) {
|
||||
func TestRouteTasksError(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test")
|
||||
r.TaskLister = &fakeChatTaskLister{err: errors.New("store unavailable")}
|
||||
if _, err := r.Route(context.Background(), Message{Text: "/tasks"}); err == nil {
|
||||
if _, err := r.Route(context.Background(), inbound("", "/tasks")); err == nil {
|
||||
t.Error("expected error from Route when ListChatTasks fails")
|
||||
}
|
||||
}
|
||||
@@ -298,7 +298,7 @@ func TestFormatTasks(t *testing.T) {
|
||||
|
||||
func TestRouteNonCommandWithLLM(t *testing.T) {
|
||||
r := NewRouter(nil, fakeLLM, "test")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "hello"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -309,7 +309,7 @@ func TestRouteNonCommandWithLLM(t *testing.T) {
|
||||
|
||||
func TestRouteNonCommandWithoutLLM(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "hello"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -327,16 +327,16 @@ func TestRouterRejectsUnknownCommand(t *testing.T) {
|
||||
for _, text := range tests {
|
||||
t.Run(text, func(t *testing.T) {
|
||||
llmCalls := 0
|
||||
r := NewRouter(nil, func(context.Context, Message) (string, error) {
|
||||
r := NewRouter(nil, func(context.Context, Inbound) (string, error) {
|
||||
llmCalls++
|
||||
return "fabricated command behavior", nil
|
||||
}, "test")
|
||||
r.LLMStream = func(context.Context, Message, TurnStream) (string, error) {
|
||||
r.LLMStream = func(context.Context, Inbound, TurnStream) (string, error) {
|
||||
llmCalls++
|
||||
return "fabricated streaming behavior", nil
|
||||
}
|
||||
|
||||
reply, err := r.RouteStream(context.Background(), Message{Text: text}, DeltaFunc(func(string) {}))
|
||||
reply, err := r.RouteStream(context.Background(), inbound("", text), DeltaFunc(func(string) {}))
|
||||
if err != nil {
|
||||
t.Fatalf("RouteStream: %v", err)
|
||||
}
|
||||
@@ -413,7 +413,7 @@ func (f *fakeModelManager) SetActiveModel(_ context.Context, ref string) error {
|
||||
|
||||
func TestRouteModelsIsNoLongerACommand(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/models"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/models"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -428,7 +428,7 @@ func TestRouteModelSwitch(t *testing.T) {
|
||||
}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Models = mgr
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/model a/b"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/model a/b"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -446,7 +446,7 @@ func TestRouteModelAtMention(t *testing.T) {
|
||||
}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Models = mgr
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/model@test-gw a/b"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/model@test-gw a/b"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -461,7 +461,7 @@ func TestRouteModelUnknown(t *testing.T) {
|
||||
}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Models = mgr
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/model unknown/unknown"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/model unknown/unknown"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -476,7 +476,7 @@ func TestRouteModelNoArg(t *testing.T) {
|
||||
}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Models = mgr
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/model"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/model"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -487,7 +487,7 @@ func TestRouteModelNoArg(t *testing.T) {
|
||||
|
||||
func TestRouteModelNoManager(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/model a/b"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/model a/b"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -517,7 +517,7 @@ func TestRouteSpawnCreatesTask(t *testing.T) {
|
||||
tc := &fakeTaskCreator{}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Tasks = tc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/spawn Fix the login bug"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn Fix the login bug"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -533,7 +533,7 @@ func TestRouteSpawnAtMention(t *testing.T) {
|
||||
tc := &fakeTaskCreator{}
|
||||
r := NewRouter(nil, nil, "archie-bot")
|
||||
r.Tasks = tc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/spawn@archie-bot Deploy the release"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn@archie-bot Deploy the release"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -546,7 +546,7 @@ func TestRouteSpawnNoTitle(t *testing.T) {
|
||||
tc := &fakeTaskCreator{}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Tasks = tc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/spawn"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -560,7 +560,7 @@ func TestRouteSpawnNoTitle(t *testing.T) {
|
||||
|
||||
func TestRouteSpawnNoManager(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/spawn something"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn something"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -577,7 +577,7 @@ func TestRouteSpawnHandlesCreationError(t *testing.T) {
|
||||
}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Tasks = tc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/spawn Break things"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn Break things"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -591,7 +591,7 @@ func TestRouteSpawnParsesRepoAndWorkflow(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Tasks = tc
|
||||
r.Identity = "archie"
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/spawn repo=acme/example-service workflow=tdd Fix the flaky test"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn repo=acme/example-service workflow=tdd Fix the flaky test"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -613,9 +613,7 @@ func TestRouteSpawnParsesIdentity(t *testing.T) {
|
||||
r.Tasks = tc
|
||||
r.Identity = "default"
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{
|
||||
Text: "/spawn identity=reviewer repo=acme/example-service workflow=tdd Fix the flaky test",
|
||||
})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn identity=reviewer repo=acme/example-service workflow=tdd Fix the flaky test"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -632,7 +630,7 @@ func TestRouteSpawnWithoutRepoOrWorkflowUsesDefaults(t *testing.T) {
|
||||
tc := &fakeTaskCreator{}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Tasks = tc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/spawn Fix the login bug"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/spawn Fix the login bug"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -651,7 +649,7 @@ func TestRouteSpawnTitleLooksLikeKeyValueIsPreserved(t *testing.T) {
|
||||
tc := &fakeTaskCreator{}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Tasks = tc
|
||||
if _, err := r.Route(context.Background(), Message{Text: "/spawn repo=acme/example-service Fix x=y in config"}); err != nil {
|
||||
if _, err := r.Route(context.Background(), inbound("", "/spawn repo=acme/example-service Fix x=y in config")); err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
got := tc.requests[0]
|
||||
@@ -703,7 +701,7 @@ func TestRouteApproveParsesIdentity(t *testing.T) {
|
||||
r.Controller = fc
|
||||
r.Identity = "default"
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/approve identity=reviewer 42"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/approve identity=reviewer 42"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -719,7 +717,7 @@ func TestRouteApproveSuccess(t *testing.T) {
|
||||
fc := &fakeTaskController{}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Controller = fc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/approve 42"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/approve 42"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -733,7 +731,7 @@ func TestRouteApproveSuccess(t *testing.T) {
|
||||
|
||||
func TestRouteApproveNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/approve 1"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/approve 1"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -746,7 +744,7 @@ func TestRouteApproveBadID(t *testing.T) {
|
||||
fc := &fakeTaskController{}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Controller = fc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/approve notanumber"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/approve notanumber"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -766,7 +764,7 @@ func TestRouteApproveWrongStateSurfacesError(t *testing.T) {
|
||||
}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Controller = fc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/approve 7"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/approve 7"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -779,7 +777,7 @@ func TestRouteCancelSuccess(t *testing.T) {
|
||||
fc := &fakeTaskController{}
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Controller = fc
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/cancel 5"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/cancel 5"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -797,7 +795,7 @@ func TestRouteCancelParsesIdentity(t *testing.T) {
|
||||
r.Controller = fc
|
||||
r.Identity = "default"
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/cancel identity=reviewer 5"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/cancel identity=reviewer 5"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -821,7 +819,7 @@ func TestRouteCancelCrossIdentityRejected(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Controller = fc
|
||||
r.Identity = "winter"
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/cancel 9"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/cancel 9"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -832,7 +830,7 @@ func TestRouteCancelCrossIdentityRejected(t *testing.T) {
|
||||
|
||||
func TestRouteCancelNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/cancel 1"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/cancel 1"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -846,7 +844,7 @@ func TestRouteCancelNotConfigured(t *testing.T) {
|
||||
func TestRouteWhoami(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Identity = "archie"
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/whoami"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/whoami"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -857,7 +855,7 @@ func TestRouteWhoami(t *testing.T) {
|
||||
|
||||
func TestRouteWhoamiNoIdentity(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/whoami"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/whoami"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -873,7 +871,7 @@ func TestRouteWhoamiWithModel(t *testing.T) {
|
||||
models: []string{"a/b", "c/d"},
|
||||
activeModel: "a/b",
|
||||
}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/whoami"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/whoami"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -891,7 +889,7 @@ func TestRouteProfile(t *testing.T) {
|
||||
models: []string{"a/b", "c/d"},
|
||||
activeModel: "a/b",
|
||||
}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/profile"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/profile"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -902,7 +900,7 @@ func TestRouteProfile(t *testing.T) {
|
||||
|
||||
func TestRouteProfileNoIdentity(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/profile"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/profile"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -926,7 +924,7 @@ func (f *fakeSessionLister) List(ctx context.Context) ([]SessionContext, error)
|
||||
func TestRouteSessionsEmpty(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore()}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/sessions"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/sessions"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -937,7 +935,7 @@ func TestRouteSessionsEmpty(t *testing.T) {
|
||||
|
||||
func TestRouteSessionsNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/sessions"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/sessions"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -949,7 +947,7 @@ func TestRouteSessionsNotConfigured(t *testing.T) {
|
||||
func TestRouteSessionsError(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore(), err: fmt.Errorf("store unavailable")}
|
||||
_, err := r.Route(context.Background(), Message{Text: "/sessions"})
|
||||
_, err := r.Route(context.Background(), inbound("", "/sessions"))
|
||||
if err == nil {
|
||||
t.Error("expected error from Route when List fails")
|
||||
}
|
||||
@@ -960,7 +958,7 @@ func TestRouteSessionsError(t *testing.T) {
|
||||
func TestRouteResumeNoArg(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore()}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/resume"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/resume"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -971,7 +969,7 @@ func TestRouteResumeNoArg(t *testing.T) {
|
||||
|
||||
func TestRouteResumeNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/resume abc"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/resume abc"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -988,7 +986,7 @@ func TestRouteResumeNoMatch(t *testing.T) {
|
||||
{SessionID: "session-1"},
|
||||
},
|
||||
}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/resume xyz"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/resume xyz"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -1006,7 +1004,7 @@ func TestRouteResumeAmbiguous(t *testing.T) {
|
||||
{SessionID: "abc-456"},
|
||||
},
|
||||
}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/resume abc"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/resume abc"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -1024,7 +1022,7 @@ func TestRouteResumeExactMatch(t *testing.T) {
|
||||
{SessionID: "abc-456"},
|
||||
},
|
||||
}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/resume abc-123"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/resume abc-123"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -1050,7 +1048,7 @@ func (f *fakeAgentReader) AgentList(ctx context.Context) ([]AgentInfo, error) {
|
||||
func TestRouteAgentsEmpty(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Agents = &fakeAgentReader{}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/agents"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/agents"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -1061,7 +1059,7 @@ func TestRouteAgentsEmpty(t *testing.T) {
|
||||
|
||||
func TestRouteAgentsNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/agents"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/agents"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -1078,7 +1076,7 @@ func TestRouteAgentsWithTasks(t *testing.T) {
|
||||
{ID: 2, Title: "Add tests", Status: "waiting_human", Identity: "archie"},
|
||||
},
|
||||
}
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/agents"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/agents"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -1093,7 +1091,7 @@ func TestRouteAgentsWithTasks(t *testing.T) {
|
||||
func TestRouteAgentsError(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.Agents = &fakeAgentReader{err: fmt.Errorf("store unavailable")}
|
||||
_, err := r.Route(context.Background(), Message{Text: "/agents"})
|
||||
_, err := r.Route(context.Background(), inbound("", "/agents"))
|
||||
if err == nil {
|
||||
t.Error("expected error from Route when AgentList fails")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// inbound is what a channel hands the Router: a user message in channelID's
|
||||
// chat. Tests that also need a source ID, thread or timestamp set those on
|
||||
// the returned value's Message.
|
||||
func inbound(channelID, text string) Inbound {
|
||||
return Inbound{Message: messaging.Message{
|
||||
ConversationID: messaging.ConversationID{ChannelID: channelID},
|
||||
Role: messaging.RoleUser,
|
||||
Text: text,
|
||||
}}
|
||||
}
|
||||
|
||||
// inboundFrom is inbound with the channel-native sender attribution set.
|
||||
func inboundFrom(channelID, sender, text string) Inbound {
|
||||
in := inbound(channelID, text)
|
||||
in.Message.Sender = sender
|
||||
return in
|
||||
}
|
||||
|
||||
// TestPageReachesThePromptButNotTheRecord pins the reason Inbound exists.
|
||||
// Page is the dashboard route the operator is looking at: it belongs in the
|
||||
// system prompt and nowhere else, and the record the turn persists is the
|
||||
// canonical messaging.Message, which has no field that could carry it.
|
||||
func TestPageReachesThePromptButNotTheRecord(t *testing.T) {
|
||||
prepared := &turnTestPreparedModel{reply: "you are on the tasks page"}
|
||||
store := NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
router := NewRouter(nil, nil, "web")
|
||||
router.Identity = "archie"
|
||||
router.InitSessions(store)
|
||||
runner := NewTurnRunner(TurnRunnerConfig{
|
||||
Router: router,
|
||||
Sessions: store,
|
||||
Models: &fakeModelManager{models: []string{"test/model"}, activeModel: "test/model"},
|
||||
Model: &turnTestModel{prepared: prepared},
|
||||
BotUser: "archie",
|
||||
Channel: "web",
|
||||
})
|
||||
|
||||
in := inboundFrom("browser-1", "web", "where am I?")
|
||||
in.Message.SourceID = "web-1"
|
||||
in.Page = "/tasks"
|
||||
if _, err := runner.Run(t.Context(), in, nil); err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
|
||||
system := prepared.lastRequest.Messages[0]
|
||||
if system.Role != "system" || !strings.Contains(system.Content, "/tasks") {
|
||||
t.Fatalf("system prompt = %q, want the operator's page in it", system.Content)
|
||||
}
|
||||
|
||||
history, err := store.RecentMessages(t.Context(), "browser-1", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("RecentMessages() error = %v", err)
|
||||
}
|
||||
if len(history) != 2 {
|
||||
t.Fatalf("history = %#v, want the user message and its reply", history)
|
||||
}
|
||||
for _, stored := range history {
|
||||
if strings.Contains(stored.Text, "/tasks") || stored.Sender == "/tasks" {
|
||||
t.Fatalf("page leaked into the persisted record: %+v", stored)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChannelInboundRoundTripsWithItsRole pins the other half of the flip:
|
||||
// the role a channel sets at construction is the role that comes back out
|
||||
// of the store, on both sides of the exchange. Role used to be derived at
|
||||
// the store boundary by comparing the sender against the bot identity, so a
|
||||
// user whose channel name matched the bot's was filed as the assistant
|
||||
// however the message had arrived.
|
||||
func TestChannelInboundRoundTripsWithItsRole(t *testing.T) {
|
||||
prepared := &turnTestPreparedModel{reply: "on it"}
|
||||
store := NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
router := NewRouter(nil, nil, "telegram")
|
||||
router.Identity = "archie"
|
||||
router.InitSessions(store)
|
||||
runner := NewTurnRunner(TurnRunnerConfig{
|
||||
Router: router,
|
||||
Sessions: store,
|
||||
Models: &fakeModelManager{models: []string{"test/model"}, activeModel: "test/model"},
|
||||
Model: &turnTestModel{prepared: prepared},
|
||||
BotUser: "archie",
|
||||
Channel: "telegram",
|
||||
})
|
||||
|
||||
in := inboundFrom("chat-1", "archie", "deploy it")
|
||||
in.Message.SourceID = "tg-7"
|
||||
in.Message.At = time.Date(2026, 9, 8, 9, 0, 0, 0, time.UTC)
|
||||
if _, err := runner.Run(t.Context(), in, nil); err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
|
||||
history, err := store.RecentMessages(t.Context(), "chat-1", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("RecentMessages() error = %v", err)
|
||||
}
|
||||
if len(history) != 2 {
|
||||
t.Fatalf("history = %#v, want the user message and its reply", history)
|
||||
}
|
||||
user, reply := history[0], history[1]
|
||||
if user.Role != messaging.RoleUser || user.Text != "deploy it" || user.Sender != "archie" {
|
||||
t.Fatalf("stored user message = %+v, want the role the channel set", user)
|
||||
}
|
||||
if user.SourceID != "tg-7" || user.ID == "" {
|
||||
t.Fatalf("stored user message lost its correlation: %+v", user)
|
||||
}
|
||||
if reply.Role != messaging.RoleAssistant || reply.Sender != "archie" {
|
||||
t.Fatalf("stored reply = %+v, want an assistant message from the bot", reply)
|
||||
}
|
||||
}
|
||||
@@ -48,8 +48,9 @@ type MediaAttachment struct {
|
||||
}
|
||||
|
||||
// MessageEvent is the rich message model for all gateway channels. It
|
||||
// extends the 3-field Message struct for new adapters while
|
||||
// remaining backward-compatible via the Text() and FromID() helpers.
|
||||
// carries the platform detail an adapter needs beyond the persisted
|
||||
// record, and keeps the Text() and FromID() helpers for callers that only
|
||||
// want a sender and a body.
|
||||
//
|
||||
// Every field except Type is optional. A minimal text message needs
|
||||
// only Type=MsgText, Text, ChannelID, Platform, and SenderID.
|
||||
@@ -133,6 +134,6 @@ type MessageEvent struct {
|
||||
Raw map[string]any `json:"raw,omitempty"`
|
||||
}
|
||||
|
||||
// FromID returns the sender identifier. Backward-compatible alias for
|
||||
// code that uses Message.From.
|
||||
// FromID returns the sender identifier, under the name callers that only
|
||||
// need a sender use.
|
||||
func (e MessageEvent) FromID() string { return e.SenderID }
|
||||
@@ -4,56 +4,30 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// This file is the single boundary between the gateway's channel-facing
|
||||
// Message and the canonical messaging.Message persisted by the session
|
||||
// store.
|
||||
// This file holds the one piece of the old channel-facing Message that
|
||||
// outlived it: the role derivation.
|
||||
//
|
||||
// CURRENT: gateway.Message is built by channel adapters (Telegram, email,
|
||||
// webhook, web UI) and carries transport-only routing context (ChannelID,
|
||||
// ThreadID, Page) alongside the persisted fields. SessionStore persists the
|
||||
// stored subset; see scanMessages, which leaves the transport fields empty
|
||||
// on read.
|
||||
// messaging.Message is the canonical persisted record and is now also the
|
||||
// currency at the channel-facing boundary. Channel adapters build it
|
||||
// directly and set Role themselves (always messaging.RoleUser -- a channel
|
||||
// carries only what a person said), and the gateway sets
|
||||
// messaging.RoleAssistant on the reply it generates, so nothing converts
|
||||
// between two shapes of a message in process any more.
|
||||
//
|
||||
// TARGET (migration-decisions.md section 2): messaging.Message is the
|
||||
// canonical persisted record. The store speaks it; channel adapters are
|
||||
// migrated onto it one by one (bd label messaging-migration), after which
|
||||
// gateway.Message is deleted. Until then, every conversion goes through
|
||||
// these two functions -- no caller maps the fields by hand.
|
||||
//
|
||||
// Role derivation matches the comparisons this package already performs
|
||||
// (compressTurnHistory, messagesToCompressed, PriorReply, and the
|
||||
// sessioncurator adapter): a message sent by the session's bot identity is
|
||||
// the assistant's, anything else is the user's.
|
||||
// The wire is the exception. pb.Message carries no role, so both sides of
|
||||
// the gRPC contract derive it from the owning session's bot identity
|
||||
// instead of adding a field to the proto -- see
|
||||
// internal/infrastructure/gatewayrpc. Because both derive from the same
|
||||
// session, they agree.
|
||||
|
||||
// ToStoredMessage converts a channel-facing message into its canonical
|
||||
// stored form. botUser is the session's bot identity. The message's
|
||||
// channel/thread address its conversation; Page is transport-only and does
|
||||
// not enter the record.
|
||||
func ToStoredMessage(msg Message, botUser string) messaging.Message {
|
||||
role := messaging.RoleUser
|
||||
if msg.From == botUser {
|
||||
role = messaging.RoleAssistant
|
||||
}
|
||||
return messaging.Message{
|
||||
ID: messaging.MessageID(msg.MessageID),
|
||||
ConversationID: messaging.ConversationID{ChannelID: msg.ChannelID, ThreadID: msg.ThreadID},
|
||||
SourceID: msg.SourceID,
|
||||
Sender: msg.From,
|
||||
Role: role,
|
||||
Text: msg.Text,
|
||||
At: msg.At,
|
||||
}
|
||||
}
|
||||
|
||||
// FromStoredMessage converts a canonical stored record back to the gateway
|
||||
// view. The result carries exactly the fields the store persists today:
|
||||
// transport-only fields stay empty, as scanMessages leaves them.
|
||||
func FromStoredMessage(stored messaging.Message) Message {
|
||||
return Message{
|
||||
MessageID: string(stored.ID),
|
||||
SourceID: stored.SourceID,
|
||||
From: stored.Sender,
|
||||
Text: stored.Text,
|
||||
At: stored.At,
|
||||
// RoleForSender reports the role of a message written by sender in a
|
||||
// session whose bot identity is botUser. It is the comparison this package
|
||||
// already makes elsewhere (compressTurnHistory, messagesToCompressed,
|
||||
// PriorReply, and the sessioncurator adapter): a message sent by the
|
||||
// session's bot is the assistant's, anything else is the user's.
|
||||
func RoleForSender(sender, botUser string) messaging.Role {
|
||||
if sender == botUser {
|
||||
return messaging.RoleAssistant
|
||||
}
|
||||
return messaging.RoleUser
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// TestStoredMessageRoundTrip pins the store boundary contract: converting a
|
||||
// gateway message to its canonical stored form and back preserves every
|
||||
// field the store persists today (identity, conversation address, source
|
||||
// correlation, sender, role, text, timestamp). Page is transport-only and
|
||||
// never enters the record. The gateway view back leaves ChannelID/ThreadID
|
||||
// empty, exactly as scanMessages does today -- the conversation address
|
||||
// lives on the stored record, repopulated from the session on read.
|
||||
func TestStoredMessageRoundTrip(t *testing.T) {
|
||||
at := time.Date(2026, 8, 3, 12, 0, 0, 0, time.UTC)
|
||||
tests := []struct {
|
||||
name string
|
||||
msg Message
|
||||
botUser string
|
||||
want messaging.Message
|
||||
}{
|
||||
{
|
||||
name: "user message keeps sender and role",
|
||||
msg: Message{MessageID: "m-1", SourceID: "tg-1", From: "alice", Text: "hello", At: at},
|
||||
botUser: "archie",
|
||||
want: messaging.Message{
|
||||
ID: messaging.MessageID("m-1"), SourceID: "tg-1",
|
||||
Role: messaging.RoleUser, Sender: "alice", Text: "hello", At: at,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "assistant message derives role from bot identity",
|
||||
msg: Message{MessageID: "m-2", From: "archie", Text: "hi", At: at},
|
||||
botUser: "archie",
|
||||
want: messaging.Message{
|
||||
ID: messaging.MessageID("m-2"),
|
||||
Role: messaging.RoleAssistant, Sender: "archie", Text: "hi", At: at,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "empty sender stays user role",
|
||||
msg: Message{MessageID: "m-3", Text: "anon", At: at},
|
||||
botUser: "archie",
|
||||
want: messaging.Message{
|
||||
ID: messaging.MessageID("m-3"),
|
||||
Role: messaging.RoleUser, Text: "anon", At: at,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "channel and thread address the conversation; page does not persist",
|
||||
msg: Message{MessageID: "m-4", ChannelID: "chat-1", ThreadID: "t-1", Page: "/tasks", From: "alice", Text: "x", At: at},
|
||||
botUser: "archie",
|
||||
want: messaging.Message{
|
||||
ID: messaging.MessageID("m-4"),
|
||||
ConversationID: messaging.ConversationID{ChannelID: "chat-1", ThreadID: "t-1"},
|
||||
Role: messaging.RoleUser, Sender: "alice", Text: "x", At: at,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := ToStoredMessage(tt.msg, tt.botUser)
|
||||
if got != tt.want {
|
||||
t.Fatalf("ToStoredMessage() = %+v, want %+v", got, tt.want)
|
||||
}
|
||||
back := FromStoredMessage(got)
|
||||
if back.MessageID != tt.msg.MessageID || back.SourceID != tt.msg.SourceID ||
|
||||
back.From != tt.msg.From || back.Text != tt.msg.Text || !back.At.Equal(tt.msg.At) {
|
||||
t.Fatalf("FromStoredMessage() = %+v, want stored fields of %+v", back, tt.msg)
|
||||
}
|
||||
if back.ChannelID != "" || back.ThreadID != "" || back.Page != "" {
|
||||
t.Fatalf("FromStoredMessage() carries transport fields: %+v", back)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// Persona is a named communication style that modifies the system prompt.
|
||||
@@ -121,7 +123,7 @@ func (r *PersonaRegistry) Get(name string) (Persona, bool) {
|
||||
return p, ok
|
||||
}
|
||||
|
||||
func (r *Router) handlePersonality(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handlePersonality(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
if r.Personas == nil {
|
||||
return "Personality switching is not configured.", nil
|
||||
}
|
||||
@@ -135,13 +137,13 @@ func (r *Router) handlePersonality(ctx context.Context, msg Message, rest string
|
||||
return fmt.Sprintf("Personality set to %q.", name), nil
|
||||
}
|
||||
|
||||
func (r *Router) sessionKey(ctx context.Context, msg Message) string {
|
||||
func (r *Router) sessionKey(ctx context.Context, msg messaging.Message) string {
|
||||
if r.sessionTracker == nil {
|
||||
return msg.ChannelID
|
||||
return msg.ConversationID.ChannelID
|
||||
}
|
||||
key, err := r.ResolveSessionKey(ctx, msg)
|
||||
key, err := r.ResolveSessionKey(ctx, Inbound{Message: msg})
|
||||
if err != nil {
|
||||
return msg.ChannelID
|
||||
return msg.ConversationID.ChannelID
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
@@ -126,13 +126,11 @@ func TestPriorReply(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
history := make([]messaging.Message, 0, len(tc.history))
|
||||
for i, h := range tc.history {
|
||||
m := ToStoredMessage(Message{
|
||||
MessageID: newMessageIDFor(sessionID, h.sourceID, i),
|
||||
SourceID: h.sourceID,
|
||||
From: h.from,
|
||||
Text: h.text,
|
||||
At: time.Now().Add(time.Duration(i) * time.Second),
|
||||
}, identity)
|
||||
role := messaging.RoleUser
|
||||
if h.from == identity {
|
||||
role = messaging.RoleAssistant
|
||||
}
|
||||
m := messaging.Message{ID: messaging.MessageID(newMessageIDFor(sessionID, h.sourceID, i)), SourceID: h.sourceID, Sender: h.from, Role: role, Text: h.text, At: time.Now().Add(time.Duration(i) * time.Second)}
|
||||
history = append(history, m)
|
||||
}
|
||||
|
||||
|
||||
@@ -267,19 +267,12 @@ func sessionTrackerKey(channelID, threadID string) string {
|
||||
// ResolveSessionKey resolves or creates a session for a message and
|
||||
// returns the session ID. This is the entry point the LLM responder
|
||||
// in main.go should call instead of its inline sessionKey helper.
|
||||
func (r *Router) ResolveSessionKey(ctx context.Context, msg Message) (string, error) {
|
||||
func (r *Router) ResolveSessionKey(ctx context.Context, in Inbound) (string, error) {
|
||||
conv := in.Message.ConversationID
|
||||
if r.sessionTracker == nil {
|
||||
return sessionKeyFromMsg(msg), nil
|
||||
return sessionKeyFromFields(conv.ChannelID, conv.ThreadID), nil
|
||||
}
|
||||
return r.sessionTracker.resolve(ctx, r.gatewayName, r.Identity, msg.ChannelID, msg.ThreadID)
|
||||
}
|
||||
|
||||
// sessionKeyFromMsg is the fallback when no session tracker is configured.
|
||||
func sessionKeyFromMsg(msg Message) string {
|
||||
if msg.ThreadID != "" {
|
||||
return msg.ChannelID + ":" + msg.ThreadID
|
||||
}
|
||||
return msg.ChannelID
|
||||
return r.sessionTracker.resolve(ctx, r.gatewayName, r.Identity, conv.ChannelID, conv.ThreadID)
|
||||
}
|
||||
|
||||
// ── Router session command handlers ────────────────────────────────────────
|
||||
@@ -291,7 +284,7 @@ func (r *Router) handleStart() (string, error) {
|
||||
|
||||
// handleNew creates a fresh session for the current channel+thread,
|
||||
// optionally setting a title.
|
||||
func (r *Router) handleNew(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handleNew(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
if r.sessionTracker == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
@@ -305,8 +298,8 @@ func (r *Router) handleNew(ctx context.Context, msg Message, rest string) (strin
|
||||
Source: SessionSource{
|
||||
Platform: r.gatewayName,
|
||||
BotUser: r.Identity,
|
||||
ChannelID: msg.ChannelID,
|
||||
ThreadID: msg.ThreadID,
|
||||
ChannelID: msg.ConversationID.ChannelID,
|
||||
ThreadID: msg.ConversationID.ThreadID,
|
||||
},
|
||||
Title: title,
|
||||
CreatedAt: now,
|
||||
@@ -315,7 +308,7 @@ func (r *Router) handleNew(ctx context.Context, msg Message, rest string) (strin
|
||||
if err := r.sessionTracker.sessions.Save(ctx, sc); err != nil {
|
||||
return "", fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
r.sessionTracker.setActive(msg.ChannelID, msg.ThreadID, id)
|
||||
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, id)
|
||||
|
||||
if title != "" {
|
||||
return fmt.Sprintf("New session created: %s (%s)", title, shortSessionID(id)), nil
|
||||
@@ -326,14 +319,14 @@ func (r *Router) handleNew(ctx context.Context, msg Message, rest string) (strin
|
||||
// handleTopic manages topic/session switching for threaded conversations.
|
||||
// "off" disables topic routing (reverts to flat), "help" shows info,
|
||||
// and a session-id switches to that session.
|
||||
func (r *Router) handleTopic(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handleTopic(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
if r.sessionTracker == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
|
||||
switch rest {
|
||||
case "off":
|
||||
r.sessionTracker.flattenTopic(msg.ChannelID, msg.ThreadID)
|
||||
r.sessionTracker.flattenTopic(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
return "Topic routing disabled. Messages will use the General topic.", nil
|
||||
case "help":
|
||||
return topicHelpText(), nil
|
||||
@@ -351,9 +344,9 @@ func topicHelpText() string {
|
||||
" <session-id> — switch to a session by the ID shown in /topic"
|
||||
}
|
||||
|
||||
func (r *Router) topicListSessions(ctx context.Context, msg Message) (string, error) {
|
||||
active := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ChannelID)
|
||||
func (r *Router) topicListSessions(ctx context.Context, msg messaging.Message) (string, error) {
|
||||
active := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ConversationID.ChannelID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("list sessions: %w", err)
|
||||
}
|
||||
@@ -374,8 +367,8 @@ func (r *Router) topicListSessions(ctx context.Context, msg Message) (string, er
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func (r *Router) topicSwitchSession(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ChannelID)
|
||||
func (r *Router) topicSwitchSession(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ConversationID.ChannelID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("list sessions: %w", err)
|
||||
}
|
||||
@@ -384,7 +377,7 @@ func (r *Router) topicSwitchSession(ctx context.Context, msg Message, rest strin
|
||||
return fmt.Sprintf("Multiple sessions match %q. Use more of the session ID.", rest), nil
|
||||
}
|
||||
if match != nil {
|
||||
r.sessionTracker.setActive(msg.ChannelID, msg.ThreadID, match.SessionID)
|
||||
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, match.SessionID)
|
||||
return fmt.Sprintf("Switched to session %s: %s",
|
||||
shortSessionID(match.SessionID), sessionDisplayTitle(*match)), nil
|
||||
}
|
||||
@@ -393,12 +386,12 @@ func (r *Router) topicSwitchSession(ctx context.Context, msg Message, rest strin
|
||||
|
||||
// handleRetry removes the last assistant message from history and replays
|
||||
// the last user message through the LLM.
|
||||
func (r *Router) handleRetry(ctx context.Context, msg Message) (string, error) {
|
||||
func (r *Router) handleRetry(ctx context.Context, msg messaging.Message) (string, error) {
|
||||
if r.sessionTracker == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
|
||||
sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
if sessionID == "" {
|
||||
return "No active session. Send a message first.", nil
|
||||
}
|
||||
@@ -424,29 +417,29 @@ func (r *Router) handleRetry(ctx context.Context, msg Message) (string, error) {
|
||||
if r.LLM == nil {
|
||||
return "LLM is not configured. The last response has been removed; send another message to continue.", nil
|
||||
}
|
||||
// Replay the stored text, but route it with the live message's
|
||||
// addressing. The gateway view of stored history carries no channel
|
||||
// or thread -- a session already is one -- so replaying the stored
|
||||
// value verbatim would resolve to an empty session key and strand
|
||||
// the reply.
|
||||
lastUserMsg := FromStoredMessage(msgs[0])
|
||||
lastUserMsg.ChannelID = msg.ChannelID
|
||||
lastUserMsg.ThreadID = msg.ThreadID
|
||||
reply, err := r.LLM(ctx, lastUserMsg)
|
||||
// Replay the stored record, but route it with the live message's
|
||||
// addressing. Stored history is read back with the conversation
|
||||
// address of the session that holds it, which for a replay must be
|
||||
// the chat the /retry was typed in. A replay carries no page: the
|
||||
// operator's route is transport context of the message they sent,
|
||||
// and this message is not one they just sent.
|
||||
replay := msgs[0]
|
||||
replay.ConversationID = msg.ConversationID
|
||||
reply, err := r.LLM(ctx, Inbound{Message: replay})
|
||||
if err == nil {
|
||||
r.maybeAutoTitle(ctx, lastUserMsg)
|
||||
r.maybeAutoTitle(ctx, replay)
|
||||
}
|
||||
return reply, err
|
||||
}
|
||||
|
||||
// handleUndo removes the last N messages (default 1) from the session
|
||||
// history.
|
||||
func (r *Router) handleUndo(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handleUndo(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
if r.sessionTracker == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
|
||||
sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
if sessionID == "" {
|
||||
return "No active session. Send a message first.", nil
|
||||
}
|
||||
@@ -475,12 +468,12 @@ func (r *Router) handleUndo(ctx context.Context, msg Message, rest string) (stri
|
||||
}
|
||||
|
||||
// handleTitle sets a display title on the current session.
|
||||
func (r *Router) handleTitle(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handleTitle(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
if r.sessionTracker == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
|
||||
sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
if sessionID == "" {
|
||||
return "No active session. Send a message first.", nil
|
||||
}
|
||||
@@ -514,13 +507,13 @@ func (r *Router) handleTitle(ctx context.Context, msg Message, rest string) (str
|
||||
|
||||
// handleBranch creates a new child session that inherits the current
|
||||
// session's history. The new session becomes the active session.
|
||||
func (r *Router) handleBranch(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handleBranch(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
if r.sessionTracker == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
|
||||
channelID := msg.ChannelID
|
||||
threadID := msg.ThreadID
|
||||
channelID := msg.ConversationID.ChannelID
|
||||
threadID := msg.ConversationID.ThreadID
|
||||
parentID := r.sessionTracker.getActive(channelID, threadID)
|
||||
if parentID == "" {
|
||||
// Nothing to branch from. Telegram never reaches this -- submitTurn
|
||||
@@ -600,12 +593,12 @@ func (r *Router) handleBranch(ctx context.Context, msg Message, rest string) (st
|
||||
|
||||
// handleCompress applies context compression to the current session's
|
||||
// history. Sub-commands: here [N], focus <topic>, --preview, --dry-run.
|
||||
func (r *Router) handleCompress(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handleCompress(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
if r.sessionTracker == nil {
|
||||
return "Session management is not configured.", nil
|
||||
}
|
||||
|
||||
sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
if sessionID == "" {
|
||||
return "No active session. Send a message first.", nil
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ func newTestRouter(gatewayName string) *Router {
|
||||
|
||||
func TestRouteStart(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/start"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/start"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -202,9 +202,9 @@ func TestRouteStart(t *testing.T) {
|
||||
|
||||
func TestRouteNewCreatesSession(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
msg := Message{ChannelID: "chat-1", ThreadID: "", From: "alice"}
|
||||
msg := Inbound{Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "chat-1", ThreadID: ""}, Sender: "alice", Role: messaging.RoleUser}}
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-1"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-1", "/new"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -230,7 +230,7 @@ func TestRouteNewCreatesSession(t *testing.T) {
|
||||
func TestRouteNewWithTitle(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/new debugging session", ChannelID: "chat-2"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-2", "/new debugging session"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -252,14 +252,14 @@ func TestRouteResetAlias(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
// /new creates initial session.
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-3"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-3", "/new"))
|
||||
oldSession := r.sessionTracker.getActive("chat-3", "")
|
||||
if oldSession == "" {
|
||||
t.Fatal("expected initial session")
|
||||
}
|
||||
|
||||
// /reset creates a new session.
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/reset", ChannelID: "chat-3"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-3", "/reset"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -275,7 +275,7 @@ func TestRouteResetAlias(t *testing.T) {
|
||||
|
||||
func TestRouteNewNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "telegram")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/new"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/new"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -288,7 +288,7 @@ func TestRouteNewNotConfigured(t *testing.T) {
|
||||
|
||||
func TestRouteTopicHelp(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/topic help", ChannelID: "chat-4"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-4", "/topic help"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -301,10 +301,10 @@ func TestRouteTopicListSessions(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
// Create an initial session via /new.
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new alpha", ChannelID: "chat-5"})
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new beta", ChannelID: "chat-5", ThreadID: "1"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-5", "/new alpha"))
|
||||
_, _ = r.Route(context.Background(), Inbound{Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "chat-5", ThreadID: "1"}, Role: messaging.RoleUser, Text: "/new beta"}})
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/topic", ChannelID: "chat-5"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-5", "/topic"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -320,15 +320,15 @@ func TestRouteTopicSwitch(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
// Create two sessions.
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new first", ChannelID: "chat-6"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-6", "/new first"))
|
||||
firstID := r.sessionTracker.getActive("chat-6", "")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new second", ChannelID: "chat-6"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-6", "/new second"))
|
||||
secondID := r.sessionTracker.getActive("chat-6", "")
|
||||
|
||||
// Switch back to first using prefix.
|
||||
prefix := shortSessionID(firstID)
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/topic " + prefix, ChannelID: "chat-6"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-6", "/topic "+prefix))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -344,12 +344,12 @@ func TestRouteTopicSwitch(t *testing.T) {
|
||||
|
||||
func TestRouteTopicRejectsAmbiguousPrefix(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new first", ChannelID: "chat-ambiguous"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-ambiguous", "/new first"))
|
||||
firstID := r.sessionTracker.getActive("chat-ambiguous", "")
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new second", ChannelID: "chat-ambiguous"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-ambiguous", "/new second"))
|
||||
secondID := r.sessionTracker.getActive("chat-ambiguous", "")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/topic " + firstID[:8], ChannelID: "chat-ambiguous"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-ambiguous", "/topic "+firstID[:8]))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -363,7 +363,7 @@ func TestRouteTopicRejectsAmbiguousPrefix(t *testing.T) {
|
||||
|
||||
func TestRouteTopicUnknown(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/topic nonexist", ChannelID: "chat-7"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-7", "/topic nonexist"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -376,7 +376,7 @@ func TestRouteTopicUnknown(t *testing.T) {
|
||||
|
||||
func TestRouteRetryNoSession(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/retry", ChannelID: "chat-8"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-8", "/retry"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -396,8 +396,8 @@ func TestRouteRetryRemovesLastMessage(t *testing.T) {
|
||||
CreatedAt: time.Now(), LastActiveAt: time.Now(),
|
||||
}
|
||||
_ = r.sessionTracker.sessions.Save(context.Background(), sc)
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "alice", Text: "hello"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "archie", Text: "hi there"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: "hello"})
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "archie", Role: messaging.RoleAssistant, Text: "hi there"})
|
||||
r.sessionTracker.setActive("chat-9", "", sessionID)
|
||||
|
||||
// Verify initial count.
|
||||
@@ -407,7 +407,7 @@ func TestRouteRetryRemovesLastMessage(t *testing.T) {
|
||||
}
|
||||
|
||||
// Retry.
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/retry", ChannelID: "chat-9"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-9", "/retry"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -435,12 +435,12 @@ func TestRouteUndoRemovesOne(t *testing.T) {
|
||||
CreatedAt: time.Now(), LastActiveAt: time.Now(),
|
||||
}
|
||||
_ = r.sessionTracker.sessions.Save(context.Background(), sc)
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "alice", Text: "msg1"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "archie", Text: "reply1"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "alice", Text: "msg2"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: "msg1"})
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "archie", Role: messaging.RoleAssistant, Text: "reply1"})
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: "msg2"})
|
||||
r.sessionTracker.setActive("chat-10", "", sessionID)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/undo", ChannelID: "chat-10"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-10", "/undo"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -465,11 +465,11 @@ func TestRouteUndoRemovesMultiple(t *testing.T) {
|
||||
}
|
||||
_ = r.sessionTracker.sessions.Save(context.Background(), sc)
|
||||
for i := range 5 {
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "alice", Text: fmt.Sprintf("msg%d", i)}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: fmt.Sprintf("msg%d", i)})
|
||||
}
|
||||
r.sessionTracker.setActive("chat-11", "", sessionID)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/undo 3", ChannelID: "chat-11"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-11", "/undo 3"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -496,15 +496,13 @@ func TestRouteUndoReportsActualPartialRemoval(t *testing.T) {
|
||||
t.Fatalf("Save session: %v", err)
|
||||
}
|
||||
for i := range 6 {
|
||||
if err := r.sessionTracker.sessions.SaveMessage(ctx, sessionID, ToStoredMessage(Message{
|
||||
From: "alice", Text: fmt.Sprintf("msg%d", i),
|
||||
}, "archie")); err != nil {
|
||||
if err := r.sessionTracker.sessions.SaveMessage(ctx, sessionID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: fmt.Sprintf("msg%d", i)}); err != nil {
|
||||
t.Fatalf("SaveMessage(%d): %v", i, err)
|
||||
}
|
||||
}
|
||||
r.sessionTracker.setActive("chat-partial", "", sessionID)
|
||||
|
||||
reply, err := r.Route(ctx, Message{Text: "/undo 10", ChannelID: "chat-partial"})
|
||||
reply, err := r.Route(ctx, inbound("chat-partial", "/undo 10"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -525,7 +523,7 @@ func TestRouteUndoNoMessages(t *testing.T) {
|
||||
_ = r.sessionTracker.sessions.Save(context.Background(), sc)
|
||||
r.sessionTracker.setActive("chat-12", "", sessionID)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/undo", ChannelID: "chat-12"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-12", "/undo"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -546,7 +544,7 @@ func TestRouteUndoInvalidN(t *testing.T) {
|
||||
_ = r.sessionTracker.sessions.Save(context.Background(), sc)
|
||||
r.sessionTracker.setActive("chat-13", "", sessionID)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/undo notanumber", ChannelID: "chat-13"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-13", "/undo notanumber"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -560,10 +558,10 @@ func TestRouteUndoInvalidN(t *testing.T) {
|
||||
func TestRouteTitleSet(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-14"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-14", "/new"))
|
||||
sessionID := r.sessionTracker.getActive("chat-14", "")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/title debugging the crash", ChannelID: "chat-14"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-14", "/title debugging the crash"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -580,9 +578,9 @@ func TestRouteTitleSet(t *testing.T) {
|
||||
func TestRouteTitleShow(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new my topic", ChannelID: "chat-15"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-15", "/new my topic"))
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/title", ChannelID: "chat-15"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-15", "/title"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -594,9 +592,9 @@ func TestRouteTitleShow(t *testing.T) {
|
||||
func TestRouteTitleNoTitle(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-16"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-16", "/new"))
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/title", ChannelID: "chat-16"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-16", "/title"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -611,15 +609,15 @@ func TestRouteBranchCreatesChildSession(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
// Create parent with history.
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new parent session", ChannelID: "chat-17"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-17", "/new parent session"))
|
||||
parentID := r.sessionTracker.getActive("chat-17", "")
|
||||
|
||||
// Add messages to parent.
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, ToStoredMessage(Message{From: "alice", Text: "hello"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, ToStoredMessage(Message{From: "archie", Text: "hi"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: "hello"})
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, messaging.Message{Sender: "archie", Role: messaging.RoleAssistant, Text: "hi"})
|
||||
|
||||
// Branch.
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/branch experiment", ChannelID: "chat-17"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-17", "/branch experiment"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -653,11 +651,11 @@ func TestRouteBranchCreatesChildSession(t *testing.T) {
|
||||
func TestRouteForkAlias(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new parent", ChannelID: "chat-18"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-18", "/new parent"))
|
||||
parentID := r.sessionTracker.getActive("chat-18", "")
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, ToStoredMessage(Message{From: "alice", Text: "msg"}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: "msg"})
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/fork", ChannelID: "chat-18"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-18", "/fork"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -671,15 +669,15 @@ func TestRouteForkAlias(t *testing.T) {
|
||||
func TestRouteCompressPreview(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-19"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-19", "/new"))
|
||||
sessionID := r.sessionTracker.getActive("chat-19", "")
|
||||
|
||||
// Add a bunch of messages (not enough to trigger compression by default).
|
||||
for i := range 10 {
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "alice", Text: fmt.Sprintf("message number %d", i)}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: fmt.Sprintf("message number %d", i)})
|
||||
}
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/compress --preview", ChannelID: "chat-19"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-19", "/compress --preview"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -691,14 +689,14 @@ func TestRouteCompressPreview(t *testing.T) {
|
||||
func TestRouteCompactAlias(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-20"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-20", "/new"))
|
||||
sessionID := r.sessionTracker.getActive("chat-20", "")
|
||||
|
||||
for i := range 5 {
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, ToStoredMessage(Message{From: "alice", Text: fmt.Sprintf("msg %d with some content to make it longer than a few chars", i)}, "archie"))
|
||||
_ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, messaging.Message{Sender: "alice", Role: messaging.RoleUser, Text: fmt.Sprintf("msg %d with some content to make it longer than a few chars", i)})
|
||||
}
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/compact --dry-run", ChannelID: "chat-20"})
|
||||
reply, err := r.Route(context.Background(), inbound("chat-20", "/compact --dry-run"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -709,7 +707,7 @@ func TestRouteCompactAlias(t *testing.T) {
|
||||
|
||||
func TestRouteCompressNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "telegram")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/compress"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/compress"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -758,8 +756,8 @@ func TestSessionTrackerResolveCreatesAndReuses(t *testing.T) {
|
||||
func TestRouteResetAndNewAreSame(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
r1, _ := r.Route(context.Background(), Message{Text: "/new test", ChannelID: "chat-a"})
|
||||
r2, _ := r.Route(context.Background(), Message{Text: "/reset test2", ChannelID: "chat-a"})
|
||||
r1, _ := r.Route(context.Background(), inbound("chat-a", "/new test"))
|
||||
r2, _ := r.Route(context.Background(), inbound("chat-a", "/reset test2"))
|
||||
|
||||
// Both should create a new session clearing previous.
|
||||
if !strings.Contains(r1, "test") {
|
||||
@@ -773,10 +771,10 @@ func TestRouteResetAndNewAreSame(t *testing.T) {
|
||||
func TestRouteBranchAndForkAreSame(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-b"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-b", "/new"))
|
||||
|
||||
r1, _ := r.Route(context.Background(), Message{Text: "/branch", ChannelID: "chat-b"})
|
||||
r2, _ := r.Route(context.Background(), Message{Text: "/fork", ChannelID: "chat-b"})
|
||||
r1, _ := r.Route(context.Background(), inbound("chat-b", "/branch"))
|
||||
r2, _ := r.Route(context.Background(), inbound("chat-b", "/fork"))
|
||||
|
||||
if !strings.Contains(r1, "Branched session") {
|
||||
t.Errorf("/branch reply: %q", r1)
|
||||
@@ -789,10 +787,10 @@ func TestRouteBranchAndForkAreSame(t *testing.T) {
|
||||
func TestRouteCompressAndCompactAreSame(t *testing.T) {
|
||||
r := newTestRouter("telegram")
|
||||
|
||||
_, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-c"})
|
||||
_, _ = r.Route(context.Background(), inbound("chat-c", "/new"))
|
||||
|
||||
r1, _ := r.Route(context.Background(), Message{Text: "/compress --dry-run", ChannelID: "chat-c"})
|
||||
r2, _ := r.Route(context.Background(), Message{Text: "/compact --dry-run", ChannelID: "chat-c"})
|
||||
r1, _ := r.Route(context.Background(), inbound("chat-c", "/compress --dry-run"))
|
||||
r2, _ := r.Route(context.Background(), inbound("chat-c", "/compact --dry-run"))
|
||||
|
||||
// Both should show compression info.
|
||||
if !strings.Contains(r1, "Compression") {
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// minDeleteRefLen is the shortest prefix /delete will act on.
|
||||
@@ -21,7 +23,7 @@ const minDeleteRefLen = 4
|
||||
// It is the only way to retire a conversation from chat: /new starts a
|
||||
// fresh one and leaves the old session listed by /sessions forever, so
|
||||
// without this the list only ever grows.
|
||||
func (r *Router) handleDelete(ctx context.Context, msg Message, rest string) (string, error) {
|
||||
func (r *Router) handleDelete(ctx context.Context, msg messaging.Message, rest string) (string, error) {
|
||||
ref := strings.TrimSpace(rest)
|
||||
if ref == "" {
|
||||
// No bare form. Deleting "the current conversation" on an
|
||||
@@ -55,7 +57,7 @@ func (r *Router) handleDelete(ctx context.Context, msg Message, rest string) (st
|
||||
// whether the operator just ended the conversation they are in.
|
||||
active := ""
|
||||
if r.sessionTracker != nil {
|
||||
active = r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
active = r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
}
|
||||
|
||||
if err := r.Sessions.Delete(ctx, target.SessionID); err != nil {
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// deleteFailingStore is a session store whose Delete always fails, used to
|
||||
@@ -46,7 +48,7 @@ func seedSession(t *testing.T, r *Router, store *fakeSessionStore, id, channelID
|
||||
|
||||
func TestRouteDeleteNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/delete abc-123"})
|
||||
reply, err := r.Route(context.Background(), inbound("", "/delete abc-123"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -59,7 +61,7 @@ func TestRouteDeleteNoArgExplainsUsageAndDeletesNothing(t *testing.T) {
|
||||
r, store := newDeleteRouter(t)
|
||||
seedSession(t, r, store, "abc-123", "chan-1", "Work")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete"})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -75,7 +77,7 @@ func TestRouteDeleteRejectsUnknownReference(t *testing.T) {
|
||||
r, store := newDeleteRouter(t)
|
||||
seedSession(t, r, store, "abc-123", "chan-1", "Work")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete zzzz"})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete zzzz"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -92,7 +94,7 @@ func TestRouteDeleteRejectsAmbiguousReference(t *testing.T) {
|
||||
seedSession(t, r, store, "abcd-123", "chan-1", "One")
|
||||
seedSession(t, r, store, "abcd-456", "chan-1", "Two")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd"})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete abcd"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -114,7 +116,7 @@ func TestRouteDeleteRejectsShortPrefixEvenWhenUnique(t *testing.T) {
|
||||
seedSession(t, r, store, "abc-123", "chan-1", "Work")
|
||||
|
||||
for _, ref := range []string{"a", "ab", "abc"} {
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + ref})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete "+ref))
|
||||
if err != nil {
|
||||
t.Fatalf("Route %q: %v", ref, err)
|
||||
}
|
||||
@@ -133,7 +135,7 @@ func TestRouteDeleteAcceptsShortExactID(t *testing.T) {
|
||||
r, store := newDeleteRouter(t)
|
||||
seedSession(t, r, store, "abc", "chan-1", "Work")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abc"})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete abc"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -152,7 +154,7 @@ func TestRouteDeleteExactIDBeatsAmbiguousPrefix(t *testing.T) {
|
||||
seedSession(t, r, store, "abcd-123", "chan-1", "One")
|
||||
seedSession(t, r, store, "abcd-123-extra", "chan-1", "Two")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd-123"})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete abcd-123"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -171,12 +173,12 @@ func TestRouteDeleteRemovesSessionAndItsHistory(t *testing.T) {
|
||||
r, store := newDeleteRouter(t)
|
||||
id := seedSession(t, r, store, "abcd-123", "chan-1", "Work")
|
||||
for _, text := range []string{"first", "second"} {
|
||||
if err := store.SaveMessage(context.Background(), id, ToStoredMessage(Message{From: "sam", Text: text}, "archie")); err != nil {
|
||||
if err := store.SaveMessage(context.Background(), id, messaging.Message{Sender: "sam", Role: messaging.RoleUser, Text: text}); err != nil {
|
||||
t.Fatalf("seed message: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + id})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete "+id))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -200,23 +202,23 @@ func TestRouteDeleteRemovesSessionAndItsHistory(t *testing.T) {
|
||||
// message under an ID the store no longer knows.
|
||||
func TestRouteDeleteActiveSessionClearsTracker(t *testing.T) {
|
||||
r, store := newDeleteRouter(t)
|
||||
msg := Message{ChannelID: "chan-1"}
|
||||
if _, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/new Work"}); err != nil {
|
||||
msg := inbound("chan-1", "")
|
||||
if _, err := r.Route(context.Background(), inbound("chan-1", "/new Work")); err != nil {
|
||||
t.Fatalf("/new: %v", err)
|
||||
}
|
||||
id := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
id := r.sessionTracker.getActive(msg.Message.ConversationID.ChannelID, msg.Message.ConversationID.ThreadID)
|
||||
if id == "" {
|
||||
t.Fatal("/new did not set an active session")
|
||||
}
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + id})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete "+id))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "new conversation") {
|
||||
t.Errorf("reply = %q, want a note that the next message starts fresh", reply)
|
||||
}
|
||||
if active := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID); active != "" {
|
||||
if active := r.sessionTracker.getActive(msg.Message.ConversationID.ChannelID, msg.Message.ConversationID.ThreadID); active != "" {
|
||||
t.Errorf("tracker still points at %q after deleting it", active)
|
||||
}
|
||||
|
||||
@@ -237,12 +239,12 @@ func TestRouteDeleteActiveSessionClearsTracker(t *testing.T) {
|
||||
func TestRouteDeleteOtherSessionKeepsActive(t *testing.T) {
|
||||
r, store := newDeleteRouter(t)
|
||||
other := seedSession(t, r, store, "abcd-999", "chan-1", "Old")
|
||||
if _, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/new Current"}); err != nil {
|
||||
if _, err := r.Route(context.Background(), inbound("chan-1", "/new Current")); err != nil {
|
||||
t.Fatalf("/new: %v", err)
|
||||
}
|
||||
active := r.sessionTracker.getActive("chan-1", "")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + other})
|
||||
reply, err := r.Route(context.Background(), inbound("chan-1", "/delete "+other))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -261,7 +263,7 @@ func TestRouteDeleteReportsStoreFailure(t *testing.T) {
|
||||
seedSession(t, r, store, "abcd-123", "chan-1", "Work")
|
||||
r.Sessions = &deleteFailingStore{fakeSessionStore: store, err: errors.New("store unavailable")}
|
||||
|
||||
_, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd-123"})
|
||||
_, err := r.Route(context.Background(), inbound("chan-1", "/delete abcd-123"))
|
||||
if err == nil {
|
||||
t.Fatal("expected an error when the store cannot delete")
|
||||
}
|
||||
@@ -274,7 +276,7 @@ func TestRouteDeleteReportsListFailure(t *testing.T) {
|
||||
err: errors.New("store unavailable"),
|
||||
}
|
||||
|
||||
_, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd-123"})
|
||||
_, err := r.Route(context.Background(), inbound("chan-1", "/delete abcd-123"))
|
||||
if err == nil {
|
||||
t.Fatal("expected an error when the store cannot list sessions")
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestResolveDoesNotOrphanASessionItLoses(t *testing.T) {
|
||||
// creates a session and makes it active.
|
||||
var newSessionID string
|
||||
store.afterGetByChannel = func() {
|
||||
if _, err := r.Route(ctx, Message{Text: "/new", ChannelID: "chat-y"}); err != nil {
|
||||
if _, err := r.Route(ctx, inbound("chat-y", "/new")); err != nil {
|
||||
t.Errorf("Route(/new): %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -45,8 +45,8 @@ type SessionLifecycle interface {
|
||||
}
|
||||
|
||||
// MessageHistory manages conversation messages within a session. Messages
|
||||
// are canonical messaging.Message records; gateway callers convert at the
|
||||
// boundary with ToStoredMessage/FromStoredMessage.
|
||||
// are canonical messaging.Message records, the same type channel adapters
|
||||
// hand the Router, so nothing converts on the way in or out.
|
||||
type MessageHistory interface {
|
||||
// SaveMessage appends one message with a strictly increasing timestamp.
|
||||
SaveMessage(ctx context.Context, sessionID string, msg messaging.Message) error
|
||||
@@ -165,9 +165,8 @@ func CanonicalMessageID(sessionID, sourceID string) string {
|
||||
}
|
||||
|
||||
// PriorReply returns the reply already produced for an upstream message.
|
||||
// The assistant check reads the record's Role: the stored Role is derived
|
||||
// from the sender at the store boundary (see ToStoredMessage), so this
|
||||
// needs no bot identity.
|
||||
// The assistant check reads the record's Role, which its producer set when
|
||||
// the message was written, so this needs no bot identity.
|
||||
func PriorReply(history []messaging.Message, sessionID, sourceID string) string {
|
||||
if sourceID == "" {
|
||||
return ""
|
||||
|
||||
@@ -765,9 +765,9 @@ func saveMessageAt(ctx context.Context, ex execer, sessionID string, msg messagi
|
||||
legacyID = compatibleLegacyID
|
||||
}
|
||||
}
|
||||
// An empty Role means "user": the boundary derives assistant explicitly
|
||||
// (see ToStoredMessage), and pre-migration rows are backfilled at open,
|
||||
// so only a hand-built record arrives without one.
|
||||
// An empty Role means "user": producers set RoleAssistant explicitly
|
||||
// (see TurnRunner.generateAndComplete), and pre-migration rows are
|
||||
// backfilled at open, so only a hand-built record arrives without one.
|
||||
role := string(msg.Role)
|
||||
if role == "" {
|
||||
role = string(messaging.RoleUser)
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// TitleGenerator proposes a display title for an untitled session.
|
||||
@@ -50,11 +52,11 @@ const titleGenerationTimeout = 30 * time.Second
|
||||
// title. For a fresh session that is its first message; for an older
|
||||
// session that predates automatic titles, it is the first message
|
||||
// observed after this code is deployed, i.e. the current topic.
|
||||
func (r *Router) maybeAutoTitle(ctx context.Context, msg Message) {
|
||||
func (r *Router) maybeAutoTitle(ctx context.Context, msg messaging.Message) {
|
||||
if r.Titles == nil || r.sessionTracker == nil {
|
||||
return
|
||||
}
|
||||
sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
|
||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||
if sessionID == "" || !r.claimTitleInFlight(sessionID) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// stubTitleGenerator records calls and answers from a per-session table.
|
||||
@@ -59,7 +61,7 @@ func (s *stubTitleGenerator) lastText() string {
|
||||
|
||||
// llmResponder is a deterministic LLMResponder for turn-path tests.
|
||||
func llmResponder(reply string) LLMResponder {
|
||||
return func(context.Context, Message) (string, error) { return reply, nil }
|
||||
return func(context.Context, Inbound) (string, error) { return reply, nil }
|
||||
}
|
||||
|
||||
// waitForTitle polls the store until sessionID carries the wanted title.
|
||||
@@ -184,7 +186,7 @@ func TestRouteSessionsRenderedList(t *testing.T) {
|
||||
}
|
||||
}
|
||||
r.InitSessions(store)
|
||||
reply, err := r.Route(ctx, Message{Text: "/sessions"})
|
||||
reply, err := r.Route(ctx, inbound("", "/sessions"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
@@ -208,12 +210,12 @@ func TestRouteAutoTitlesUntitledSession(t *testing.T) {
|
||||
gen := &stubTitleGenerator{titles: map[string]string{}}
|
||||
r.Titles = gen
|
||||
ctx := context.Background()
|
||||
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "Deploy the NATS worker"})
|
||||
sessionID, err := r.ResolveSessionKey(ctx, inboundFrom("ch", "u", "Deploy the NATS worker"))
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
gen.titles[sessionID] = "Deploy NATS worker"
|
||||
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "Deploy the NATS worker"}); err != nil {
|
||||
if _, err := r.Route(ctx, inboundFrom("ch", "u", "Deploy the NATS worker")); err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
waitForTitle(t, store, sessionID, "Deploy NATS worker")
|
||||
@@ -256,7 +258,7 @@ func TestRouteDoesNotRetitleTitledSession(t *testing.T) {
|
||||
gen.block = make(chan struct{})
|
||||
r.Titles = gen
|
||||
ctx := context.Background()
|
||||
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "hello"})
|
||||
sessionID, err := r.ResolveSessionKey(ctx, inboundFrom("ch", "u", "hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
@@ -268,7 +270,7 @@ func TestRouteDoesNotRetitleTitledSession(t *testing.T) {
|
||||
if err := store.Save(ctx, *sc); err != nil {
|
||||
t.Fatalf("save session: %v", err)
|
||||
}
|
||||
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "more text"}); err != nil {
|
||||
if _, err := r.Route(ctx, inboundFrom("ch", "u", "more text")); err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
waitForTitleIdle(t, r)
|
||||
@@ -288,11 +290,11 @@ func TestRouteAutoTitleErrorKeepsUntitled(t *testing.T) {
|
||||
gen := &stubTitleGenerator{err: errors.New("model down"), titles: map[string]string{}}
|
||||
r.Titles = gen
|
||||
ctx := context.Background()
|
||||
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"})
|
||||
sessionID, err := r.ResolveSessionKey(ctx, inboundFrom("ch", "u", "deploy"))
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"}); err != nil {
|
||||
if _, err := r.Route(ctx, inboundFrom("ch", "u", "deploy")); err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
// The proposal is spawned (the session is untitled) and must drain
|
||||
@@ -312,7 +314,7 @@ func TestRouteAutoTitleInFlightGuard(t *testing.T) {
|
||||
gen.block = make(chan struct{})
|
||||
r.Titles = gen
|
||||
ctx := context.Background()
|
||||
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"})
|
||||
sessionID, err := r.ResolveSessionKey(ctx, inboundFrom("ch", "u", "deploy"))
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
@@ -320,7 +322,7 @@ func TestRouteAutoTitleInFlightGuard(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"}); err != nil {
|
||||
if _, err := r.Route(ctx, inboundFrom("ch", "u", "deploy")); err != nil {
|
||||
t.Errorf("Route 1: %v", err)
|
||||
}
|
||||
}()
|
||||
@@ -332,7 +334,7 @@ func TestRouteAutoTitleInFlightGuard(t *testing.T) {
|
||||
<-done
|
||||
// A second turn while the first proposal is still blocked must not
|
||||
// spawn a second call: the guard lets one proposal win the session.
|
||||
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy again"}); err != nil {
|
||||
if _, err := r.Route(ctx, inboundFrom("ch", "u", "deploy again")); err != nil {
|
||||
t.Fatalf("Route 2: %v", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
@@ -349,17 +351,17 @@ func TestRouteStreamAutoTitlesUntitledSession(t *testing.T) {
|
||||
r.InitSessions(store)
|
||||
gen := &stubTitleGenerator{titles: map[string]string{}}
|
||||
r.Titles = gen
|
||||
r.LLMStream = func(_ context.Context, _ Message, stream TurnStream) (string, error) {
|
||||
r.LLMStream = func(_ context.Context, _ Inbound, stream TurnStream) (string, error) {
|
||||
stream.Delta("r")
|
||||
return "reply ok", nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "stream me"})
|
||||
sessionID, err := r.ResolveSessionKey(ctx, inboundFrom("ch", "u", "stream me"))
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
gen.titles[sessionID] = "Stream topic"
|
||||
if _, err := r.RouteStream(ctx, Message{ChannelID: "ch", From: "u", Text: "stream me"}, DeltaFunc(func(string) {})); err != nil {
|
||||
if _, err := r.RouteStream(ctx, inboundFrom("ch", "u", "stream me"), DeltaFunc(func(string) {})); err != nil {
|
||||
t.Fatalf("RouteStream: %v", err)
|
||||
}
|
||||
waitForTitle(t, store, sessionID, "Stream topic")
|
||||
@@ -372,11 +374,11 @@ func TestRouteAutoTitlePanicIsContained(t *testing.T) {
|
||||
gen := &stubTitleGenerator{titles: map[string]string{}, panicMsg: "boom"}
|
||||
r.Titles = gen
|
||||
ctx := context.Background()
|
||||
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"})
|
||||
sessionID, err := r.ResolveSessionKey(ctx, inboundFrom("ch", "u", "deploy"))
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"}); err != nil {
|
||||
if _, err := r.Route(ctx, inboundFrom("ch", "u", "deploy")); err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
// If the recover is ever removed, the panic in the background
|
||||
@@ -395,18 +397,18 @@ func TestRetryAutoTitlesUntitledSession(t *testing.T) {
|
||||
gen := &stubTitleGenerator{titles: map[string]string{}}
|
||||
r.Titles = gen
|
||||
ctx := context.Background()
|
||||
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy the worker"})
|
||||
sessionID, err := r.ResolveSessionKey(ctx, inboundFrom("ch", "u", "deploy the worker"))
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
gen.titles[sessionID] = "Deploy worker"
|
||||
if err := store.SaveMessage(ctx, sessionID, ToStoredMessage(Message{From: "u", Text: "deploy the worker"}, "archie")); err != nil {
|
||||
if err := store.SaveMessage(ctx, sessionID, messaging.Message{Sender: "u", Role: messaging.RoleUser, Text: "deploy the worker"}); err != nil {
|
||||
t.Fatalf("save user message: %v", err)
|
||||
}
|
||||
if err := store.SaveMessage(ctx, sessionID, ToStoredMessage(Message{From: "bot", Text: "sure"}, "archie")); err != nil {
|
||||
if err := store.SaveMessage(ctx, sessionID, messaging.Message{Sender: "bot", Role: messaging.RoleUser, Text: "sure"}); err != nil {
|
||||
t.Fatalf("save reply: %v", err)
|
||||
}
|
||||
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "/retry"}); err != nil {
|
||||
if _, err := r.Route(ctx, inboundFrom("ch", "u", "/retry")); err != nil {
|
||||
t.Fatalf("Route /retry: %v", err)
|
||||
}
|
||||
waitForTitle(t, store, sessionID, "Deploy worker")
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
@@ -79,11 +80,11 @@ type SessionDeleteResult struct {
|
||||
// A nil store omits every tool rather than registering ones that always fail,
|
||||
// so a daemon without session support advertises nothing. A nil tracker omits
|
||||
// the two tools that need it (session_resume and session_delete).
|
||||
func SessionTools(store SessionStore, tracker *sessionTracker, platform string, msg Message) []tools.ToolEntry {
|
||||
func SessionTools(store SessionStore, tracker *sessionTracker, platform string, msg messaging.Message) []tools.ToolEntry {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
channelID := msg.ChannelID
|
||||
channelID := msg.ConversationID.ChannelID
|
||||
var entries []tools.ToolEntry
|
||||
entries = append(entries, sessionListTool(store, platform, channelID))
|
||||
if tracker != nil {
|
||||
@@ -143,7 +144,7 @@ func sessionListTool(store SessionStore, platform, channelID string) tools.ToolE
|
||||
}
|
||||
}
|
||||
|
||||
func sessionResumeTool(store SessionStore, tracker *sessionTracker, platform, channelID string, msg Message) tools.ToolEntry {
|
||||
func sessionResumeTool(store SessionStore, tracker *sessionTracker, platform, channelID string, msg messaging.Message) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "session_resume",
|
||||
Toolset: "session",
|
||||
@@ -182,7 +183,7 @@ func sessionResumeTool(store SessionStore, tracker *sessionTracker, platform, ch
|
||||
// The channel+thread are the ones this tool was built for, never
|
||||
// input. Tracker presence is guaranteed: SessionTools omits the
|
||||
// tool when no tracker is wired.
|
||||
tracker.setActive(msg.ChannelID, msg.ThreadID, match.SessionID)
|
||||
tracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, match.SessionID)
|
||||
return SessionResumeResult{
|
||||
SessionID: match.SessionID,
|
||||
Title: sessionDisplayTitle(*match),
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
@@ -44,7 +45,7 @@ func sessionTool(t *testing.T, entries []tools.ToolEntry, name string) tools.Too
|
||||
func TestSessionToolListReturnsSessions(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_list")
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message), "session_list")
|
||||
|
||||
now := time.Now()
|
||||
seedSessionAt(store, "sess-1", "one", now.Add(-3*time.Hour))
|
||||
@@ -80,7 +81,7 @@ func TestSessionToolListReturnsSessions(t *testing.T) {
|
||||
func TestSessionToolListRespectsLimit(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_list")
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message), "session_list")
|
||||
|
||||
now := time.Now()
|
||||
for i := range 5 {
|
||||
@@ -110,8 +111,8 @@ func TestSessionToolListRespectsLimit(t *testing.T) {
|
||||
func TestSessionToolResumeSwitchesActive(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
msg := Message{ChannelID: "chat-1", ThreadID: "thread-9"}
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", msg), "session_resume")
|
||||
msg := Inbound{Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "chat-1", ThreadID: "thread-9"}, Role: messaging.RoleUser}}
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", msg.Message), "session_resume")
|
||||
|
||||
target := "resume-target"
|
||||
seedSessionAt(store, target, "target session", time.Now())
|
||||
@@ -138,7 +139,7 @@ func TestSessionToolResumeSwitchesActive(t *testing.T) {
|
||||
func TestSessionToolResumeRejectsUnknown(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_resume")
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message), "session_resume")
|
||||
|
||||
_, err := entry.Handler(context.Background(), map[string]any{"session_id": "does-not-exist"})
|
||||
if err == nil {
|
||||
@@ -152,7 +153,7 @@ func TestSessionToolResumeRejectsUnknown(t *testing.T) {
|
||||
func TestSessionToolTitleSetsTitle(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_title")
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message), "session_title")
|
||||
|
||||
target := "title-target"
|
||||
seedSessionAt(store, target, "old title", time.Now())
|
||||
@@ -179,7 +180,7 @@ func TestSessionToolTitleSetsTitle(t *testing.T) {
|
||||
func TestSessionToolTitleReportsPrevious(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_title")
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message), "session_title")
|
||||
|
||||
target := "title-prev"
|
||||
seedSessionAt(store, target, "before", time.Now())
|
||||
@@ -206,7 +207,7 @@ func TestSessionToolTitleReportsPrevious(t *testing.T) {
|
||||
func TestSessionToolDeleteRemovesSession(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_delete")
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message), "session_delete")
|
||||
|
||||
target := "delete-target"
|
||||
seedSessionAt(store, target, "doomed", time.Now())
|
||||
@@ -235,7 +236,7 @@ func TestSessionToolDeleteRemovesSession(t *testing.T) {
|
||||
func TestSessionToolDeleteClearsTracker(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_delete")
|
||||
entry := sessionTool(t, SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message), "session_delete")
|
||||
|
||||
target := "delete-active"
|
||||
seedSessionAt(store, target, "active", time.Now())
|
||||
@@ -257,7 +258,7 @@ func TestSessionToolDeleteClearsTracker(t *testing.T) {
|
||||
func TestSessionToolClassifications(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
tr := newSessionTracker(store)
|
||||
entries := SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"})
|
||||
entries := SessionTools(store, tr, "test-gw", inbound("chat-1", "").Message)
|
||||
if len(entries) != 4 {
|
||||
t.Fatalf("got %d tools, want 4", len(entries))
|
||||
}
|
||||
@@ -293,7 +294,7 @@ func TestSessionToolClassifications(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSessionToolNilStoreOmitsTools(t *testing.T) {
|
||||
if entries := SessionTools(nil, nil, "test-gw", Message{ChannelID: "chat-1"}); len(entries) != 0 {
|
||||
if entries := SessionTools(nil, nil, "test-gw", inbound("chat-1", "").Message); len(entries) != 0 {
|
||||
t.Errorf("SessionTools(nil, ...) = %d entries, want 0", len(entries))
|
||||
}
|
||||
}
|
||||
@@ -304,7 +305,7 @@ func TestSessionToolNilStoreOmitsTools(t *testing.T) {
|
||||
// fails.
|
||||
func TestSessionToolNilTrackerOmitsTrackerTools(t *testing.T) {
|
||||
store := newFakeSessionStore()
|
||||
entries := SessionTools(store, nil, "test-gw", Message{ChannelID: "chat-1"})
|
||||
entries := SessionTools(store, nil, "test-gw", inbound("chat-1", "").Message)
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name)
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestTopicOffDoesNotPoisonTheCache(t *testing.T) {
|
||||
want = id
|
||||
}
|
||||
|
||||
if _, err := r.Route(ctx, Message{Text: "/topic off", ChannelID: "chat-x"}); err != nil {
|
||||
if _, err := r.Route(ctx, inbound("chat-x", "/topic off")); err != nil {
|
||||
t.Fatalf("Route(/topic off): %v", err)
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ func TestBranchWithNoActiveSessionDoesNotPanic(t *testing.T) {
|
||||
r.InitSessions(store)
|
||||
r.Identity = "archie"
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/branch", ChannelID: "inbox-1"})
|
||||
reply, err := r.Route(context.Background(), inbound("inbox-1", "/branch"))
|
||||
if err != nil {
|
||||
t.Fatalf("Route(/branch): %v", err)
|
||||
}
|
||||
|
||||
+40
-37
@@ -131,13 +131,13 @@ func (r *TurnRunner) Recover(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// Respond adapts the runner to Router.LLM.
|
||||
func (r *TurnRunner) Respond(ctx context.Context, msg Message) (string, error) {
|
||||
return r.Run(ctx, msg, nil)
|
||||
func (r *TurnRunner) Respond(ctx context.Context, in Inbound) (string, error) {
|
||||
return r.Run(ctx, in, nil)
|
||||
}
|
||||
|
||||
// RespondStream adapts the runner to Router.LLMStream.
|
||||
func (r *TurnRunner) RespondStream(ctx context.Context, msg Message, stream TurnStream) (string, error) {
|
||||
return r.Run(ctx, msg, stream)
|
||||
func (r *TurnRunner) RespondStream(ctx context.Context, in Inbound, stream TurnStream) (string, error) {
|
||||
return r.Run(ctx, in, stream)
|
||||
}
|
||||
|
||||
// Run executes one turn, reporting progress to stream. A completed duplicate
|
||||
@@ -181,7 +181,7 @@ func (r *TurnRunner) checkConfigured() error {
|
||||
// (text, err); done is false when there is no prior reply to replay and
|
||||
// Run should continue generating one.
|
||||
func (r *TurnRunner) replayPriorReply(
|
||||
ctx context.Context, turn TurnRecord, sessionID string, msg Message, history []messaging.Message, stream TurnStream,
|
||||
ctx context.Context, turn TurnRecord, sessionID string, msg messaging.Message, history []messaging.Message, stream TurnStream,
|
||||
) (string, bool, error) {
|
||||
prior := PriorReply(history, sessionID, msg.SourceID)
|
||||
if prior == "" && msg.SourceID != "" {
|
||||
@@ -217,7 +217,7 @@ func (r *TurnRunner) replayPriorReply(
|
||||
// stream events and rejecting a still-in-progress duplicate. done is true
|
||||
// when Run should return turn.ResponseText immediately without generating.
|
||||
func (r *TurnRunner) claimTurn(
|
||||
ctx context.Context, turnID, sessionID string, msg Message, stream TurnStream,
|
||||
ctx context.Context, turnID, sessionID string, msg messaging.Message, stream TurnStream,
|
||||
) (TurnRecord, bool, error) {
|
||||
turn, claim, err := r.Ledger.ClaimTurn(ctx, TurnRecord{
|
||||
TurnID: turnID,
|
||||
@@ -246,29 +246,27 @@ func (r *TurnRunner) claimTurn(
|
||||
return turn, false, nil
|
||||
}
|
||||
|
||||
// recordInboundMessage assigns msg its canonical MessageID, persists it as
|
||||
// the turn's input on first sight, and folds it into history if it is not
|
||||
// recordInboundMessage assigns msg its canonical ID, persists it as the
|
||||
// turn's input on first sight, and folds it into history if it is not
|
||||
// already present there.
|
||||
func (r *TurnRunner) recordInboundMessage(
|
||||
ctx context.Context, turn *TurnRecord, sessionID string, msg Message, history []messaging.Message,
|
||||
) (Message, []messaging.Message, error) {
|
||||
msg.MessageID = messageIDForTurn(sessionID, msg)
|
||||
stored := ToStoredMessage(msg, r.BotUser)
|
||||
ctx context.Context, turn *TurnRecord, sessionID string, msg messaging.Message, history []messaging.Message,
|
||||
) (messaging.Message, []messaging.Message, error) {
|
||||
msg.ID = messaging.MessageID(messageIDForTurn(sessionID, msg))
|
||||
if turn.InputMessageID == "" {
|
||||
if err := r.Sessions.SaveMessage(ctx, sessionID, stored); err != nil {
|
||||
if err := r.Sessions.SaveMessage(ctx, sessionID, msg); err != nil {
|
||||
return msg, history, fmt.Errorf("save inbound chat message: %w", err)
|
||||
}
|
||||
turn.InputMessageID = msg.MessageID
|
||||
turn.InputMessageID = string(msg.ID)
|
||||
turn.UpdatedAt = time.Now().UTC()
|
||||
if err := r.saveTurn(ctx, *turn); err != nil {
|
||||
return msg, history, fmt.Errorf("save chat turn input: %w", err)
|
||||
}
|
||||
} else {
|
||||
msg.MessageID = turn.InputMessageID
|
||||
stored.ID = messaging.MessageID(turn.InputMessageID)
|
||||
msg.ID = messaging.MessageID(turn.InputMessageID)
|
||||
}
|
||||
if !messageInHistory(history, msg.SourceID) {
|
||||
history = append(history, stored)
|
||||
history = append(history, msg)
|
||||
}
|
||||
return msg, history, nil
|
||||
}
|
||||
@@ -285,11 +283,11 @@ type preparedTurn struct {
|
||||
|
||||
// prepareTurn builds the tools, system prompt, and compressed history view
|
||||
// for one turn's generation call.
|
||||
func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, msg Message, history []messaging.Message) (preparedTurn, error) {
|
||||
func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbound, history []messaging.Message) (preparedTurn, error) {
|
||||
compressed := compressTurnHistory(history)
|
||||
extraTools := append(
|
||||
TaskTools(r.TaskLister, r.Tasks, r.TaskLogs, r.TaskActor, r.TaskIdentity),
|
||||
SessionTools(r.Sessions, r.Router.SessionTracker(), r.Channel, msg)...,
|
||||
SessionTools(r.Sessions, r.Router.SessionTracker(), r.Channel, in.Message)...,
|
||||
)
|
||||
// The dashboard tools (page_index, dashboard_navigate) belong to the web
|
||||
// UI only: a non-web channel has no dashboard to point at.
|
||||
@@ -321,7 +319,7 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, msg Mess
|
||||
Model: modelName,
|
||||
SessionID: sessionID,
|
||||
Now: time.Now(),
|
||||
Page: msg.Page,
|
||||
Page: in.Page,
|
||||
Workspace: r.Workspace,
|
||||
Repos: r.Repos,
|
||||
Operator: r.Operator,
|
||||
@@ -341,8 +339,8 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, msg Mess
|
||||
if r.Log != nil {
|
||||
r.Log.Info("chat turn",
|
||||
"session", sessionID,
|
||||
"channel", msg.ChannelID,
|
||||
"thread", msg.ThreadID,
|
||||
"channel", in.Message.ConversationID.ChannelID,
|
||||
"thread", in.Message.ConversationID.ThreadID,
|
||||
"history_messages", len(history),
|
||||
"model", modelName,
|
||||
"context_window", modelDetails.ContextWindow,
|
||||
@@ -354,7 +352,7 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, msg Mess
|
||||
return preparedTurn{prepared: prepared, modelName: modelName, modelDetails: modelDetails, view: view}, nil
|
||||
}
|
||||
|
||||
func (r *TurnRunner) Run(ctx context.Context, msg Message, stream TurnStream) (string, error) {
|
||||
func (r *TurnRunner) Run(ctx context.Context, in Inbound, stream TurnStream) (string, error) {
|
||||
if err := r.checkConfigured(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -362,18 +360,18 @@ func (r *TurnRunner) Run(ctx context.Context, msg Message, stream TurnStream) (s
|
||||
return "", fmt.Errorf("recover chat turns: %w", err)
|
||||
}
|
||||
|
||||
sessionID, err := r.Router.ResolveSessionKey(ctx, msg)
|
||||
sessionID, err := r.Router.ResolveSessionKey(ctx, in)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve chat session: %w", err)
|
||||
}
|
||||
turnID, err := r.canonicalTurnID(ctx, sessionID, msg.SourceID)
|
||||
turnID, err := r.canonicalTurnID(ctx, sessionID, in.Message.SourceID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve canonical turn ID: %w", err)
|
||||
}
|
||||
if turnID == "" {
|
||||
turnID = NewTurnID()
|
||||
}
|
||||
turn, done, err := r.claimTurn(ctx, turnID, sessionID, msg, stream)
|
||||
turn, done, err := r.claimTurn(ctx, turnID, sessionID, in.Message, stream)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -385,16 +383,16 @@ func (r *TurnRunner) Run(ctx context.Context, msg Message, stream TurnStream) (s
|
||||
if err != nil {
|
||||
return "", r.failTurn(ctx, turn, fmt.Errorf("load chat history: %w", err))
|
||||
}
|
||||
if replayed, done, err := r.replayPriorReply(ctx, turn, sessionID, msg, history, stream); done {
|
||||
if replayed, done, err := r.replayPriorReply(ctx, turn, sessionID, in.Message, history, stream); done {
|
||||
return replayed, err
|
||||
}
|
||||
|
||||
msg, history, err = r.recordInboundMessage(ctx, &turn, sessionID, msg, history)
|
||||
in.Message, history, err = r.recordInboundMessage(ctx, &turn, sessionID, in.Message, history)
|
||||
if err != nil {
|
||||
return "", r.failTurn(ctx, turn, err)
|
||||
}
|
||||
|
||||
prep, err := r.prepareTurn(ctx, sessionID, msg, history)
|
||||
prep, err := r.prepareTurn(ctx, sessionID, in, history)
|
||||
if err != nil {
|
||||
return "", r.failTurn(ctx, turn, err)
|
||||
}
|
||||
@@ -414,12 +412,17 @@ func (r *TurnRunner) generateAndComplete(
|
||||
if err != nil {
|
||||
return "", r.failTurn(ctx, turn, err)
|
||||
}
|
||||
assistant := Message{MessageID: assistantMessageIDForTurn(turn.TurnID), From: r.BotUser, Text: text}
|
||||
if err := r.Sessions.SaveMessage(ctx, sessionID, ToStoredMessage(assistant, r.BotUser)); err != nil {
|
||||
assistant := messaging.Message{
|
||||
ID: messaging.MessageID(assistantMessageIDForTurn(turn.TurnID)),
|
||||
Sender: r.BotUser,
|
||||
Role: messaging.RoleAssistant,
|
||||
Text: text,
|
||||
}
|
||||
if err := r.Sessions.SaveMessage(ctx, sessionID, assistant); err != nil {
|
||||
return "", r.failTurn(ctx, turn, fmt.Errorf("save outbound chat message: %w", err))
|
||||
}
|
||||
turn.Status = TurnStatusCompleted
|
||||
turn.AssistantMessageID = assistant.MessageID
|
||||
turn.AssistantMessageID = string(assistant.ID)
|
||||
turn.ResponseText = text
|
||||
turn.ToolCalls = recorder.events
|
||||
turn.Error = ""
|
||||
@@ -492,9 +495,9 @@ func (r *TurnRunner) saveTurn(ctx context.Context, turn TurnRecord) error {
|
||||
return r.Ledger.SaveTurn(persistCtx, turn)
|
||||
}
|
||||
|
||||
func messageIDForTurn(sessionID string, msg Message) string {
|
||||
if msg.MessageID != "" {
|
||||
return msg.MessageID
|
||||
func messageIDForTurn(sessionID string, msg messaging.Message) string {
|
||||
if msg.ID != "" {
|
||||
return string(msg.ID)
|
||||
}
|
||||
if id := CanonicalMessageID(sessionID, msg.SourceID); id != "" {
|
||||
return id
|
||||
@@ -515,8 +518,8 @@ func messageInHistory(history []messaging.Message, sourceID string) bool {
|
||||
}
|
||||
|
||||
// compressTurnHistory renders stored history as role/content pairs. The
|
||||
// role comes from the record, which the store boundary derives from the
|
||||
// sender when the message is written (see ToStoredMessage).
|
||||
// role comes from the record, which its producer sets when the message is
|
||||
// written -- RoleUser at the channel, RoleAssistant at generateAndComplete.
|
||||
func compressTurnHistory(history []messaging.Message) []CompressedMessage {
|
||||
compressed := make([]CompressedMessage, 0, len(history))
|
||||
for _, message := range history {
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// recordingStream captures everything a turn reports, in arrival order, so a
|
||||
@@ -55,9 +57,7 @@ func TestTurnRunnerForwardsToolCallsInOrderWithText(t *testing.T) {
|
||||
runner := newStreamTestRunner(t, prepared)
|
||||
|
||||
sink := &recordingStream{}
|
||||
reply, err := runner.Run(context.Background(), Message{
|
||||
From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello",
|
||||
}, sink)
|
||||
reply, err := runner.Run(context.Background(), Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}, sink)
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func TestTurnRunnerForwardsToolCallsInOrderWithText(t *testing.T) {
|
||||
func TestTurnRunnerReplayStreamsStoredReplyOnce(t *testing.T) {
|
||||
prepared := &turnTestPreparedModel{reply: "the answer"}
|
||||
runner := newStreamTestRunner(t, prepared)
|
||||
msg := Message{From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello"}
|
||||
msg := Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}
|
||||
|
||||
if _, err := runner.Run(context.Background(), msg, DeltaFunc(nil)); err != nil {
|
||||
t.Fatalf("first Run() error = %v", err)
|
||||
@@ -115,7 +115,7 @@ func TestTurnRunnerReplayCompletedDuplicateReplaysToolCalls(t *testing.T) {
|
||||
return "done", nil
|
||||
}
|
||||
runner := newStreamTestRunner(t, prepared)
|
||||
msg := Message{From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello"}
|
||||
msg := Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}
|
||||
|
||||
if _, err := runner.Run(context.Background(), msg, &recordingStream{}); err != nil {
|
||||
t.Fatalf("first Run() error = %v", err)
|
||||
@@ -161,7 +161,7 @@ func TestTurnRunnerRecordsToolCallsEvenWithoutOriginalStream(t *testing.T) {
|
||||
return "done", nil
|
||||
}
|
||||
runner := newStreamTestRunner(t, prepared)
|
||||
msg := Message{From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello"}
|
||||
msg := Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}
|
||||
|
||||
if _, err := runner.Run(context.Background(), msg, nil); err != nil {
|
||||
t.Fatalf("first Run() error = %v", err)
|
||||
@@ -187,9 +187,7 @@ func TestTurnRunnerAcceptsNoStream(t *testing.T) {
|
||||
prepared := &turnTestPreparedModel{reply: "quiet answer"}
|
||||
runner := newStreamTestRunner(t, prepared)
|
||||
|
||||
reply, err := runner.Run(context.Background(), Message{
|
||||
From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello",
|
||||
}, nil)
|
||||
reply, err := runner.Run(context.Background(), Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
@@ -100,12 +101,7 @@ func TestTurnRunnerPersistsOneTurnAndPublishesCompletion(t *testing.T) {
|
||||
})
|
||||
|
||||
var streamed string
|
||||
reply, err := runner.Run(context.Background(), Message{
|
||||
From: "user",
|
||||
ChannelID: "chat-1",
|
||||
SourceID: "source-1",
|
||||
Text: "hello",
|
||||
}, DeltaFunc(func(delta string) { streamed += delta }))
|
||||
reply, err := runner.Run(context.Background(), Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}, DeltaFunc(func(delta string) { streamed += delta }))
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
@@ -162,9 +158,7 @@ func TestTurnRunnerGenerationFailureLeavesInboundWithoutReply(t *testing.T) {
|
||||
Channel: "telegram",
|
||||
})
|
||||
|
||||
_, err := runner.Run(context.Background(), Message{
|
||||
From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello",
|
||||
}, nil)
|
||||
_, err := runner.Run(context.Background(), Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "provider unavailable") {
|
||||
t.Fatalf("Run() error = %v, want provider error", err)
|
||||
}
|
||||
@@ -205,9 +199,7 @@ func TestTurnRunnerCancellationPersistsCancelledState(t *testing.T) {
|
||||
Channel: "telegram",
|
||||
})
|
||||
|
||||
_, err := runner.Run(runCtx, Message{
|
||||
From: "user", ChannelID: "chat-cancel", SourceID: "source-cancel", Text: "hello",
|
||||
}, nil)
|
||||
_, err := runner.Run(runCtx, Inbound{Message: messaging.Message{SourceID: "source-cancel", ConversationID: messaging.ConversationID{ChannelID: "chat-cancel"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}, nil)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Run() error = %v, want context.Canceled", err)
|
||||
}
|
||||
@@ -244,9 +236,7 @@ func TestTurnRunnerRecoversTurnOwnedByPreviousProcess(t *testing.T) {
|
||||
Channel: "telegram",
|
||||
})
|
||||
|
||||
got, err := runner.Run(context.Background(), Message{
|
||||
From: "user", ChannelID: "chat-recover", SourceID: "source-recover", Text: "resume me",
|
||||
}, nil)
|
||||
got, err := runner.Run(context.Background(), Inbound{Message: messaging.Message{SourceID: "source-recover", ConversationID: messaging.ConversationID{ChannelID: "chat-recover"}, Sender: "user", Role: messaging.RoleUser, Text: "resume me"}}, nil)
|
||||
if err != nil || got != "recovered" {
|
||||
t.Fatalf("Run() = %q, %v; want recovered response", got, err)
|
||||
}
|
||||
@@ -271,9 +261,7 @@ func TestTurnRunnerPreparationFailureLeavesInboundWithoutReply(t *testing.T) {
|
||||
Channel: "telegram",
|
||||
})
|
||||
|
||||
_, err := runner.Run(context.Background(), Message{
|
||||
From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello",
|
||||
}, nil)
|
||||
_, err := runner.Run(context.Background(), Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "tool setup failed") {
|
||||
t.Fatalf("Run() error = %v, want tool setup error", err)
|
||||
}
|
||||
@@ -306,15 +294,13 @@ func TestTurnRunnerReplaysCompletedDuplicateOutsideRecentWindow(t *testing.T) {
|
||||
BotUser: "archie",
|
||||
Channel: "telegram",
|
||||
})
|
||||
msg := Message{From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello"}
|
||||
msg := Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}
|
||||
|
||||
if _, err := runner.Run(context.Background(), msg, nil); err != nil {
|
||||
t.Fatalf("first Run() error = %v", err)
|
||||
}
|
||||
for i := range 110 {
|
||||
if err := store.SaveMessage(context.Background(), "chat-1", ToStoredMessage(Message{
|
||||
From: "user", SourceID: fmt.Sprintf("later-%d", i), Text: "later",
|
||||
}, "archie")); err != nil {
|
||||
if err := store.SaveMessage(context.Background(), "chat-1", messaging.Message{SourceID: fmt.Sprintf("later-%d", i), Sender: "user", Role: messaging.RoleUser, Text: "later"}); err != nil {
|
||||
t.Fatalf("SaveMessage(%d) error = %v", i, err)
|
||||
}
|
||||
}
|
||||
@@ -346,7 +332,7 @@ func TestTurnRunnerReplaysCompletedDuplicateWithoutGenerating(t *testing.T) {
|
||||
BotUser: "archie",
|
||||
Channel: "telegram",
|
||||
})
|
||||
msg := Message{From: "user", ChannelID: "chat-1", SourceID: "source-1", Text: "hello"}
|
||||
msg := Inbound{Message: messaging.Message{SourceID: "source-1", ConversationID: messaging.ConversationID{ChannelID: "chat-1"}, Sender: "user", Role: messaging.RoleUser, Text: "hello"}}
|
||||
|
||||
if _, err := runner.Run(context.Background(), msg, nil); err != nil {
|
||||
t.Fatalf("first Run() error = %v", err)
|
||||
|
||||
@@ -39,37 +39,35 @@ func TestSharedRouterWebParityCommands(t *testing.T) {
|
||||
sessions := NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
r.InitSessions(sessions)
|
||||
msg := Message{ChannelID: "browser", From: "web"}
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/version"})
|
||||
reply, err := r.Route(context.Background(), inbound("browser", "/version"))
|
||||
if err != nil || reply != r.Version {
|
||||
t.Fatalf("/version = %q, %v", reply, err)
|
||||
}
|
||||
reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/personality concise"})
|
||||
reply, err = r.Route(context.Background(), inbound("browser", "/personality concise"))
|
||||
if err != nil || !strings.Contains(reply, `"concise"`) {
|
||||
t.Fatalf("/personality concise = %q, %v", reply, err)
|
||||
}
|
||||
reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/help"})
|
||||
reply, err = r.Route(context.Background(), inbound("browser", "/help"))
|
||||
if err != nil || !strings.Contains(reply, "/personality") || !strings.Contains(reply, "/resume") {
|
||||
t.Fatalf("/help = %q, %v", reply, err)
|
||||
}
|
||||
reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/restart"})
|
||||
reply, err = r.Route(context.Background(), inbound("browser", "/restart"))
|
||||
if err != nil || !restarted || !strings.Contains(reply, "reload requested") {
|
||||
t.Fatalf("/restart = %q, restarted=%v, err=%v", reply, restarted, err)
|
||||
}
|
||||
reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/update"})
|
||||
reply, err = r.Route(context.Background(), inbound("browser", "/update"))
|
||||
if err != nil || !strings.Contains(reply, "v2 available") {
|
||||
t.Fatalf("/update = %q, err=%v", reply, err)
|
||||
}
|
||||
reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/approve action-1"})
|
||||
reply, err = r.Route(context.Background(), inbound("browser", "/approve action-1"))
|
||||
if err != nil || !strings.Contains(reply, "decision applied") || len(dangerous.decisions) != 1 || dangerous.decisions[0] != "action-1:approve" {
|
||||
t.Fatalf("typed /approve = %q, decisions=%v, err=%v", reply, dangerous.decisions, err)
|
||||
}
|
||||
_, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/approve permanent action-2"})
|
||||
_, err = r.Route(context.Background(), inbound("browser", "/approve permanent action-2"))
|
||||
if err != nil || len(dangerous.decisions) != 2 || dangerous.decisions[1] != "action-2:permanent" {
|
||||
t.Fatalf("permanent /approve decisions=%v, err=%v", dangerous.decisions, err)
|
||||
}
|
||||
_, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/deny action-3"})
|
||||
_, err = r.Route(context.Background(), inbound("browser", "/deny action-3"))
|
||||
if err != nil || len(dangerous.decisions) != 3 || dangerous.decisions[2] != "action-3:deny" {
|
||||
t.Fatalf("/deny decisions=%v, err=%v", dangerous.decisions, err)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func (f *authChat) Snapshot(context.Context) (gateway.ChatSnapshot, error) {
|
||||
return f.snapshot, nil
|
||||
}
|
||||
|
||||
func (f *authChat) Stream(context.Context, gateway.Message) (<-chan gateway.ChatEvent, error) {
|
||||
func (f *authChat) Stream(context.Context, gateway.Inbound) (<-chan gateway.ChatEvent, error) {
|
||||
ch := make(chan gateway.ChatEvent)
|
||||
close(ch)
|
||||
return ch, nil
|
||||
@@ -63,7 +63,7 @@ func TestGatewayTokenRoundTrip(t *testing.T) {
|
||||
if _, err := client.Snapshot(t.Context()); err != nil {
|
||||
t.Fatalf("Snapshot with the correct token: %v", err)
|
||||
}
|
||||
events, err := client.Stream(t.Context(), gateway.Message{})
|
||||
events, err := client.Stream(t.Context(), gateway.Inbound{})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream with the correct token: %v", err)
|
||||
}
|
||||
@@ -104,7 +104,7 @@ func TestGatewayStreamWithoutTokenIsRejected(t *testing.T) {
|
||||
t.Fatalf("Dial to a loopback target without a token: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
events, err := client.Stream(t.Context(), gateway.Message{})
|
||||
events, err := client.Stream(t.Context(), gateway.Inbound{})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream without a token: %v", err)
|
||||
}
|
||||
|
||||
@@ -9,16 +9,17 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
var _ gateway.ChatContract = (*Client)(nil)
|
||||
|
||||
// Client implements gateway.ChatContract over the chat service. Session
|
||||
// history crosses in its channel-facing shape (the proto is unchanged by
|
||||
// the messaging migration); StoreClient serves the SessionStore view over
|
||||
// the same RPCs.
|
||||
// Client implements gateway.ChatContract over the chat service. The proto
|
||||
// is unchanged by the messaging migration, so history crosses without its
|
||||
// role and is re-addressed from the owning session on arrival; StoreClient
|
||||
// serves the SessionStore view over the same RPCs.
|
||||
type Client struct{ client pb.ChatServiceClient }
|
||||
|
||||
func NewClient(conn grpc.ClientConnInterface) *Client {
|
||||
@@ -41,12 +42,12 @@ func (c *Client) GetSession(ctx context.Context, id string) (gateway.SessionCont
|
||||
return sessionValue(v.Session), v.Found, nil
|
||||
}
|
||||
|
||||
func (c *Client) RecentMessages(ctx context.Context, id string, n int) ([]gateway.Message, error) {
|
||||
func (c *Client) RecentMessages(ctx context.Context, id string, n int) ([]messaging.Message, error) {
|
||||
v, err := c.client.RecentMessages(ctx, &pb.RecentMessagesRequest{SessionId: id, Limit: int64(n)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return mapValues(v.Messages, messageValue), nil
|
||||
return addressRecords(ctx, c.client, id, v.Messages)
|
||||
}
|
||||
|
||||
func (c *Client) RecentTurns(ctx context.Context, id string, n int) ([]gateway.TurnRecord, error) {
|
||||
@@ -57,8 +58,8 @@ func (c *Client) RecentTurns(ctx context.Context, id string, n int) ([]gateway.T
|
||||
return mapValues(v.Turns, turnValue), nil
|
||||
}
|
||||
|
||||
func (c *Client) Route(ctx context.Context, msg gateway.Message) (gateway.ChatReply, error) {
|
||||
v, err := c.client.Route(ctx, &pb.RouteRequest{Message: messageProto(msg)})
|
||||
func (c *Client) Route(ctx context.Context, in gateway.Inbound) (gateway.ChatReply, error) {
|
||||
v, err := c.client.Route(ctx, &pb.RouteRequest{Message: inboundProto(in)})
|
||||
if err != nil {
|
||||
return gateway.ChatReply{}, err
|
||||
}
|
||||
@@ -89,8 +90,8 @@ func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID in
|
||||
return gateway.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Stream(ctx context.Context, msg gateway.Message) (<-chan gateway.ChatEvent, error) {
|
||||
stream, err := c.client.Stream(ctx, &pb.StreamRequest{Message: messageProto(msg)})
|
||||
func (c *Client) Stream(ctx context.Context, in gateway.Inbound) (<-chan gateway.ChatEvent, error) {
|
||||
stream, err := c.client.Stream(ctx, &pb.StreamRequest{Message: inboundProto(in)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
@@ -45,7 +46,10 @@ func TestChatContractConformance(t *testing.T) {
|
||||
if _, found, err := chat.GetSession(ctx, "missing"); err != nil || found {
|
||||
t.Fatalf("missing session: %v %v", found, err)
|
||||
}
|
||||
msg := gateway.Message{ChannelID: "browser", From: "web", Text: "/help", Page: "/tasks"}
|
||||
msg := gateway.Inbound{
|
||||
Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "browser"}, Sender: "web", Role: messaging.RoleUser, Text: "/help"},
|
||||
Page: "/tasks",
|
||||
}
|
||||
reply, err := chat.Route(ctx, msg)
|
||||
if err != nil || reply.Text == "" || reply.SessionID == "" {
|
||||
t.Fatalf("route: %+v %v", reply, err)
|
||||
@@ -100,7 +104,7 @@ func TestWireValuesPreserveHistoryAndMedia(t *testing.T) {
|
||||
if got := eventValue(eventProto(event)); !reflect.DeepEqual(got, event) {
|
||||
t.Fatalf("event round trip: %+v", got)
|
||||
}
|
||||
if got := messageValue(messageProto(gateway.Message{})); !got.At.IsZero() {
|
||||
t.Fatalf("zero time became %v", got.At)
|
||||
if got := inboundValue(inboundProto(gateway.Inbound{})); !got.Message.At.IsZero() {
|
||||
t.Fatalf("zero time became %v", got.Message.At)
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func (s *server) RecentMessages(ctx context.Context, r *pb.RecentMessagesRequest
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pb.RecentMessagesResponse{Messages: mapValues(v, messageProto)}, nil
|
||||
return &pb.RecentMessagesResponse{Messages: mapValues(v, storedProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) RecentTurns(ctx context.Context, r *pb.RecentTurnsRequest) (*pb.RecentTurnsResponse, error) {
|
||||
@@ -67,7 +67,7 @@ func (s *server) RecentTurns(ctx context.Context, r *pb.RecentTurnsRequest) (*pb
|
||||
}
|
||||
|
||||
func (s *server) Route(ctx context.Context, r *pb.RouteRequest) (*pb.RouteResponse, error) {
|
||||
v, err := s.chat.Route(ctx, messageValue(r.Message))
|
||||
v, err := s.chat.Route(ctx, inboundValue(r.Message))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -141,10 +141,10 @@ func (s *server) ListSessions(ctx context.Context, _ *pb.ListSessionsRequest) (*
|
||||
}
|
||||
|
||||
// storedMessages converts wire messages to canonical records, deriving
|
||||
// roles from the owning session's bot identity -- the same derivation the
|
||||
// in-process boundary applies (see gateway.ToStoredMessage). The wire
|
||||
// carries no role; both sides derive from the same session, so they agree.
|
||||
func (s *server) storedMessages(ctx context.Context, ss gateway.SessionStore, sessionID string, msgs []gateway.Message) ([]messaging.Message, error) {
|
||||
// roles from the owning session's bot identity (see
|
||||
// gateway.RoleForSender). The wire carries no role; both sides derive from
|
||||
// the same session, so they agree.
|
||||
func (s *server) storedMessages(ctx context.Context, ss gateway.SessionStore, sessionID string, msgs []*pb.Message) ([]messaging.Message, error) {
|
||||
var botUser string
|
||||
if sc, err := ss.Get(ctx, sessionID); err != nil {
|
||||
return nil, err
|
||||
@@ -153,7 +153,9 @@ func (s *server) storedMessages(ctx context.Context, ss gateway.SessionStore, se
|
||||
}
|
||||
out := make([]messaging.Message, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
out = append(out, gateway.ToStoredMessage(m, botUser))
|
||||
stored := storedValue(m)
|
||||
stored.Role = gateway.RoleForSender(stored.Sender, botUser)
|
||||
out = append(out, stored)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -163,7 +165,7 @@ func (s *server) SaveMessage(ctx context.Context, r *pb.SaveMessageRequest) (*pb
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
msgs, e := s.storedMessages(ctx, ss, r.SessionId, []gateway.Message{messageValue(r.Message)})
|
||||
msgs, e := s.storedMessages(ctx, ss, r.SessionId, []*pb.Message{r.Message})
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
@@ -193,7 +195,7 @@ func (s *server) SaveMessages(ctx context.Context, r *pb.SaveMessagesRequest) (*
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
msgs, e := s.storedMessages(ctx, ss, r.SessionId, mapValues(r.Messages, messageValue))
|
||||
msgs, e := s.storedMessages(ctx, ss, r.SessionId, r.Messages)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
@@ -205,7 +207,7 @@ func (s *server) ReplaceMessages(ctx context.Context, r *pb.ReplaceMessagesReque
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
msgs, e := s.storedMessages(ctx, ss, r.SessionId, mapValues(r.Messages, messageValue))
|
||||
msgs, e := s.storedMessages(ctx, ss, r.SessionId, r.Messages)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
@@ -222,7 +224,7 @@ func (s *server) SearchMessages(ctx context.Context, r *pb.SearchMessagesRequest
|
||||
}
|
||||
|
||||
func (s *server) Stream(r *pb.StreamRequest, out grpc.ServerStreamingServer[pb.StreamResponse]) error {
|
||||
events, err := s.chat.Stream(out.Context(), messageValue(r.Message))
|
||||
events, err := s.chat.Stream(out.Context(), inboundValue(r.Message))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -14,14 +14,12 @@ var _ gateway.SessionStore = (*StoreClient)(nil)
|
||||
|
||||
// StoreClient implements gateway.SessionStore over the chat service's
|
||||
// session-store RPCs. It is separate from Client (the ChatContract view)
|
||||
// because the two contracts shape history differently: the wire keeps the
|
||||
// channel-facing message (the proto is unchanged by the messaging
|
||||
// migration) while the store speaks canonical records.
|
||||
// because the two contracts serve different reads over the same messages.
|
||||
//
|
||||
// Role and conversation address do not cross the wire. Both sides derive
|
||||
// them from the owning session instead -- the server on write, this client
|
||||
// on read -- so they agree without a proto change. A missing session
|
||||
// yields zero values, matching the store's LEFT JOIN for orphaned rows.
|
||||
// Role does not cross the wire (the proto is unchanged by the messaging
|
||||
// migration). Both sides derive it from the owning session instead -- the
|
||||
// server on write, this client on read -- so they agree without a proto
|
||||
// change.
|
||||
type StoreClient struct{ client pb.ChatServiceClient }
|
||||
|
||||
func NewStoreClient(conn grpc.ClientConnInterface) *StoreClient {
|
||||
@@ -72,7 +70,7 @@ func (c *StoreClient) List(ctx context.Context) ([]gateway.SessionContext, error
|
||||
}
|
||||
|
||||
func (c *StoreClient) SaveMessage(ctx context.Context, id string, m messaging.Message) error {
|
||||
_, e := c.client.SaveMessage(ctx, &pb.SaveMessageRequest{SessionId: id, Message: messageProto(gateway.FromStoredMessage(m))})
|
||||
_, e := c.client.SaveMessage(ctx, &pb.SaveMessageRequest{SessionId: id, Message: storedProto(m)})
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -98,13 +96,13 @@ func (c *StoreClient) ReplaceMessages(ctx context.Context, id string, m []messag
|
||||
|
||||
func (c *StoreClient) RecentMessages(ctx context.Context, id string, n int) ([]messaging.Message, error) {
|
||||
// No store-RecentMessages RPC exists; the chat contract serves the same
|
||||
// gateway view LocalChatAdapter serves in-process. Re-address it into
|
||||
// canonical records (see addressRecords).
|
||||
// history in-process and over the wire. Re-address it (see
|
||||
// addressRecords).
|
||||
v, err := c.client.RecentMessages(ctx, &pb.RecentMessagesRequest{SessionId: id, Limit: int64(n)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.addressRecords(ctx, id, mapValues(v.Messages, messageValue))
|
||||
return addressRecords(ctx, c.client, id, v.Messages)
|
||||
}
|
||||
|
||||
func (c *StoreClient) SearchMessages(ctx context.Context, id string, q gateway.MessageQuery) (gateway.MessagePage, error) {
|
||||
@@ -112,7 +110,7 @@ func (c *StoreClient) SearchMessages(ctx context.Context, id string, q gateway.M
|
||||
if e != nil {
|
||||
return gateway.MessagePage{}, e
|
||||
}
|
||||
msgs, err := c.addressRecords(ctx, id, mapValues(v.Messages, messageValue))
|
||||
msgs, err := addressRecords(ctx, c.client, id, v.Messages)
|
||||
if err != nil {
|
||||
return gateway.MessagePage{}, err
|
||||
}
|
||||
@@ -121,21 +119,27 @@ func (c *StoreClient) SearchMessages(ctx context.Context, id string, q gateway.M
|
||||
|
||||
func (c *StoreClient) Close() error { return nil }
|
||||
|
||||
// addressRecords restores the canonical fields the wire drops (role,
|
||||
// conversation address) from the owning session.
|
||||
func (c *StoreClient) addressRecords(ctx context.Context, id string, msgs []gateway.Message) ([]messaging.Message, error) {
|
||||
// addressRecords restores the canonical fields the wire drops -- role and
|
||||
// conversation address -- from the owning session, which is where the
|
||||
// server derived them from on the way out. A missing session yields zero
|
||||
// values, matching the store's LEFT JOIN for orphaned rows.
|
||||
func addressRecords(ctx context.Context, client pb.ChatServiceClient, id string, msgs []*pb.Message) ([]messaging.Message, error) {
|
||||
var botUser string
|
||||
var conv messaging.ConversationID
|
||||
if sc, err := c.Get(ctx, id); err != nil {
|
||||
v, err := client.GetSession(ctx, &pb.GetSessionRequest{SessionId: id})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if sc != nil {
|
||||
}
|
||||
if v.Found {
|
||||
sc := sessionValue(v.Session)
|
||||
botUser = sc.Source.BotUser
|
||||
conv = messaging.ConversationID{ChannelID: sc.Source.ChannelID, ThreadID: sc.Source.ThreadID}
|
||||
}
|
||||
out := make([]messaging.Message, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
stored := gateway.ToStoredMessage(m, botUser)
|
||||
stored := storedValue(m)
|
||||
stored.ConversationID = conv
|
||||
stored.Role = gateway.RoleForSender(stored.Sender, botUser)
|
||||
out = append(out, stored)
|
||||
}
|
||||
return out, nil
|
||||
|
||||
@@ -24,40 +24,59 @@ func timeValue(t *timestamppb.Timestamp) time.Time {
|
||||
return t.AsTime()
|
||||
}
|
||||
|
||||
func messageProto(v gateway.Message) *pb.Message {
|
||||
return &pb.Message{
|
||||
MessageId: v.MessageID,
|
||||
SourceId: v.SourceID,
|
||||
ChannelId: v.ChannelID,
|
||||
ThreadId: v.ThreadID,
|
||||
From: v.From,
|
||||
Text: v.Text,
|
||||
Page: v.Page, At: timestamp(v.At),
|
||||
}
|
||||
}
|
||||
|
||||
// storedProto renders a canonical record in its wire shape. The role stays
|
||||
// store-side: each side derives it from the owning session (see
|
||||
// gateway.ToStoredMessage), so the wire carries no role.
|
||||
// off the wire: each side derives it from the owning session's bot identity
|
||||
// (see gateway.RoleForSender), so pb.Message needs no role field.
|
||||
func storedProto(m messaging.Message) *pb.Message {
|
||||
return messageProto(gateway.FromStoredMessage(m))
|
||||
return &pb.Message{
|
||||
MessageId: string(m.ID),
|
||||
SourceId: m.SourceID,
|
||||
ChannelId: m.ConversationID.ChannelID,
|
||||
ThreadId: m.ConversationID.ThreadID,
|
||||
From: m.Sender,
|
||||
Text: m.Text,
|
||||
At: timestamp(m.At),
|
||||
}
|
||||
}
|
||||
|
||||
func messageValue(v *pb.Message) gateway.Message {
|
||||
// storedValue is storedProto's inverse. Role is left unset: only a caller
|
||||
// that knows the owning session can derive it (see addressRecords).
|
||||
func storedValue(v *pb.Message) messaging.Message {
|
||||
if v == nil {
|
||||
return gateway.Message{}
|
||||
return messaging.Message{}
|
||||
}
|
||||
return gateway.Message{
|
||||
MessageID: v.MessageId,
|
||||
SourceID: v.SourceId,
|
||||
ChannelID: v.ChannelId,
|
||||
ThreadID: v.ThreadId,
|
||||
From: v.From,
|
||||
Text: v.Text,
|
||||
Page: v.Page, At: timeValue(v.At),
|
||||
return messaging.Message{
|
||||
ID: messaging.MessageID(v.MessageId),
|
||||
SourceID: v.SourceId,
|
||||
ConversationID: messaging.ConversationID{ChannelID: v.ChannelId, ThreadID: v.ThreadId},
|
||||
Sender: v.From,
|
||||
Text: v.Text,
|
||||
At: timeValue(v.At),
|
||||
}
|
||||
}
|
||||
|
||||
// inboundProto renders a channel message and its transport context in wire
|
||||
// shape. Page rides along; the record's role does not, for the reason
|
||||
// storedProto gives.
|
||||
func inboundProto(v gateway.Inbound) *pb.Message {
|
||||
m := storedProto(v.Message)
|
||||
m.Page = v.Page
|
||||
return m
|
||||
}
|
||||
|
||||
// inboundValue reconstructs a channel message from the wire. Role is
|
||||
// RoleUser without consulting the session: this is a message a channel
|
||||
// frontend is delivering on a person's behalf, which is the only kind of
|
||||
// message Route and Stream accept.
|
||||
func inboundValue(v *pb.Message) gateway.Inbound {
|
||||
if v == nil {
|
||||
return gateway.Inbound{}
|
||||
}
|
||||
msg := storedValue(v)
|
||||
msg.Role = messaging.RoleUser
|
||||
return gateway.Inbound{Message: msg, Page: v.Page}
|
||||
}
|
||||
|
||||
func toolProto(v gateway.ToolCallEvent) *pb.ToolCall {
|
||||
return &pb.ToolCall{
|
||||
Id: v.ID,
|
||||
|
||||
@@ -49,13 +49,13 @@ func TestAdapterMessagesReadsRoleFromRecords(t *testing.T) {
|
||||
if err := store.Save(ctx, sess); err != nil {
|
||||
t.Fatalf("Save() = %v", err)
|
||||
}
|
||||
// Roles are derived from the sender at the store boundary; the adapter
|
||||
// reads them from the records, needing no bot identity of its own.
|
||||
for _, m := range []gateway.Message{
|
||||
{From: "user123", Text: "hello", At: time.Unix(1, 0)},
|
||||
{From: "archie", Text: "hi there", At: time.Unix(2, 0)},
|
||||
// Roles are set by whoever produced the message; the adapter reads them
|
||||
// from the records, needing no bot identity of its own.
|
||||
for _, m := range []messaging.Message{
|
||||
{Sender: "user123", Role: messaging.RoleUser, Text: "hello", At: time.Unix(1, 0)},
|
||||
{Sender: "archie", Role: messaging.RoleAssistant, Text: "hi there", At: time.Unix(2, 0)},
|
||||
} {
|
||||
if err := store.SaveMessage(ctx, "s1", gateway.ToStoredMessage(m, "archie")); err != nil {
|
||||
if err := store.SaveMessage(ctx, "s1", m); err != nil {
|
||||
t.Fatalf("SaveMessage(%v) = %v", m, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,11 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
@@ -45,6 +47,18 @@ type chatMessageRequest struct {
|
||||
Page string `json:"page,omitempty"`
|
||||
}
|
||||
|
||||
// chatMessageView is one entry of a session's history as the dashboard
|
||||
// reads it. The persisted record is messaging.Message; this is the shape
|
||||
// the browser has always been served, kept here so the HTTP response owns
|
||||
// its own field names rather than exposing a domain struct's.
|
||||
type chatMessageView struct {
|
||||
MessageID string
|
||||
SourceID string
|
||||
From string
|
||||
Text string
|
||||
At time.Time
|
||||
}
|
||||
|
||||
type chatPersonaRequest struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Name string `json:"name"`
|
||||
@@ -171,7 +185,14 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, messages)
|
||||
views := make([]chatMessageView, 0, len(messages))
|
||||
for _, message := range messages {
|
||||
views = append(views, chatMessageView{
|
||||
MessageID: string(message.ID), SourceID: message.SourceID,
|
||||
From: message.Sender, Text: message.Text, At: message.At,
|
||||
})
|
||||
}
|
||||
writeJSON(w, views)
|
||||
}
|
||||
|
||||
func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -212,23 +233,31 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, views)
|
||||
}
|
||||
|
||||
func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (gateway.Message, bool) {
|
||||
func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (gateway.Inbound, bool) {
|
||||
var req chatMessageRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid chat message", http.StatusBadRequest)
|
||||
return gateway.Message{}, false
|
||||
return gateway.Inbound{}, false
|
||||
}
|
||||
req.Text = strings.TrimSpace(req.Text)
|
||||
if req.Text == "" || req.ChannelID == "" {
|
||||
http.Error(w, "text and channel_id are required", http.StatusBadRequest)
|
||||
return gateway.Message{}, false
|
||||
return gateway.Inbound{}, false
|
||||
}
|
||||
if req.SourceID == "" {
|
||||
req.SourceID = newChatSourceID()
|
||||
}
|
||||
return gateway.Message{
|
||||
SourceID: req.SourceID, ChannelID: req.ChannelID,
|
||||
ThreadID: "", From: "web", Text: req.Text,
|
||||
// The browser has no threading, so the conversation is the channel
|
||||
// alone. Page is the route the operator is looking at, and stays out
|
||||
// of the record.
|
||||
return gateway.Inbound{
|
||||
Message: messaging.Message{
|
||||
SourceID: req.SourceID,
|
||||
ConversationID: messaging.ConversationID{ChannelID: req.ChannelID},
|
||||
Sender: "web",
|
||||
Role: messaging.RoleUser,
|
||||
Text: req.Text,
|
||||
},
|
||||
Page: req.Page,
|
||||
}, true
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
@@ -114,7 +115,7 @@ func TestChatSessionAndMessageEndpoints(t *testing.T) {
|
||||
if err := sessions.Save(context.Background(), session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sessions.SaveMessage(context.Background(), session.SessionID, gateway.ToStoredMessage(gateway.Message{From: "web", Text: "hello"}, "")); err != nil {
|
||||
if err := sessions.SaveMessage(context.Background(), session.SessionID, messaging.Message{Sender: "web", Role: messaging.RoleUser, Text: "hello"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -143,11 +144,14 @@ func TestChatSessionAndMessageEndpoints(t *testing.T) {
|
||||
if res.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", res.Code, res.Body)
|
||||
}
|
||||
var got []gateway.Message
|
||||
var got []struct {
|
||||
MessageID string `json:"MessageID"`
|
||||
Text string `json:"Text"`
|
||||
}
|
||||
if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Text != "hello" {
|
||||
if len(got) != 1 || got[0].Text != "hello" || got[0].MessageID == "" {
|
||||
t.Fatalf("messages = %#v", got)
|
||||
}
|
||||
})
|
||||
@@ -572,7 +576,7 @@ func TestChatStreamEndsWithDone(t *testing.T) {
|
||||
func TestChatStreamDeltas(t *testing.T) {
|
||||
server, sessions := chatTestServer(t)
|
||||
var gotDeltas []string
|
||||
testLocalChat(server.Chat).Router.LLMStream = func(_ context.Context, _ gateway.Message, stream gateway.TurnStream) (string, error) {
|
||||
testLocalChat(server.Chat).Router.LLMStream = func(_ context.Context, _ gateway.Inbound, stream gateway.TurnStream) (string, error) {
|
||||
stream.Delta("part one")
|
||||
stream.Delta("part two")
|
||||
return "full reply", nil
|
||||
@@ -605,7 +609,7 @@ func TestChatStreamDeltas(t *testing.T) {
|
||||
// writes straight to the SSE writer, with one it hands events across a
|
||||
// goroutine, and an ordering that survives only the first is not a fix.
|
||||
func TestChatStreamReportsToolCalls(t *testing.T) {
|
||||
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
|
||||
stream := func(_ context.Context, _ gateway.Inbound, turn gateway.TurnStream) (string, error) {
|
||||
turn.Delta("checking")
|
||||
turn.ToolCall(gateway.ToolCallEvent{ID: "call-1", Name: "shell", Parameters: `{"cmd":"true"}`, Output: "exit 0\nignored trailing line"})
|
||||
turn.ToolCall(gateway.ToolCallEvent{Name: "read", Err: "no such file"})
|
||||
@@ -680,7 +684,7 @@ func TestChatStreamReportsToolCalls(t *testing.T) {
|
||||
// a link in the text stream rather than being silently dropped -- the same
|
||||
// fallback Telegram's liveReply uses when SendMedia itself fails.
|
||||
func TestChatStreamRendersMediaAsALinkFallback(t *testing.T) {
|
||||
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
|
||||
stream := func(_ context.Context, _ gateway.Inbound, turn gateway.TurnStream) (string, error) {
|
||||
turn.Delta("here you go")
|
||||
turn.Media(gateway.MediaEvent{
|
||||
ToolName: "video_gen",
|
||||
@@ -716,7 +720,7 @@ func TestChatStreamRendersMediaAsALinkFallback(t *testing.T) {
|
||||
// An event with no URL has nothing to link to, so it must not add an
|
||||
// empty or broken-looking line to the transcript.
|
||||
func TestChatStreamSkipsMediaWithNoURL(t *testing.T) {
|
||||
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
|
||||
stream := func(_ context.Context, _ gateway.Inbound, turn gateway.TurnStream) (string, error) {
|
||||
turn.Media(gateway.MediaEvent{ToolName: "video_gen", Attachment: gateway.MediaAttachment{Type: "video"}})
|
||||
return "", nil
|
||||
}
|
||||
@@ -747,7 +751,7 @@ func TestChatStreamSkipsMediaWithNoURL(t *testing.T) {
|
||||
// web stream narrated every tool call unconditionally, because nothing here
|
||||
// read this setting at all.
|
||||
func TestChatStreamHidesToolCallsWhenShowToolCallsIsOff(t *testing.T) {
|
||||
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
|
||||
stream := func(_ context.Context, _ gateway.Inbound, turn gateway.TurnStream) (string, error) {
|
||||
turn.Delta("checking")
|
||||
turn.ToolCall(gateway.ToolCallEvent{Name: "shell", Output: "exit 0"})
|
||||
turn.Delta(" and answering")
|
||||
@@ -835,7 +839,7 @@ func postTo(server *Server, body string) *httptest.ResponseRecorder {
|
||||
// send_file was built to end: the model reports a file as sent and
|
||||
// nothing arrives, with no signal either way.
|
||||
func TestChatStreamReportsUndeliverableLocalFile(t *testing.T) {
|
||||
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
|
||||
stream := func(_ context.Context, _ gateway.Inbound, turn gateway.TurnStream) (string, error) {
|
||||
turn.Media(gateway.MediaEvent{
|
||||
ToolName: "send_file",
|
||||
Attachment: gateway.MediaAttachment{
|
||||
@@ -879,8 +883,8 @@ func TestChatStreamReportsUndeliverableLocalFile(t *testing.T) {
|
||||
// Message.Page, so the system prompt can state where the operator is.
|
||||
func TestChatStreamCarriesCurrentPage(t *testing.T) {
|
||||
server, sessions := chatTestServer(t)
|
||||
var got gateway.Message
|
||||
testLocalChat(server.Chat).Router.LLMStream = func(_ context.Context, msg gateway.Message, stream gateway.TurnStream) (string, error) {
|
||||
var got gateway.Inbound
|
||||
testLocalChat(server.Chat).Router.LLMStream = func(_ context.Context, msg gateway.Inbound, stream gateway.TurnStream) (string, error) {
|
||||
got = msg
|
||||
stream.Delta("on it")
|
||||
return "on it", nil
|
||||
@@ -896,7 +900,7 @@ func TestChatStreamCarriesCurrentPage(t *testing.T) {
|
||||
t.Fatalf("status = %d, body = %s", res.Code, res.Body)
|
||||
}
|
||||
if got.Page != "/tasks" {
|
||||
t.Fatalf("Message.Page = %q, want /tasks", got.Page)
|
||||
t.Fatalf("Inbound.Page = %q, want /tasks", got.Page)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -905,7 +909,7 @@ func TestChatStreamCarriesCurrentPage(t *testing.T) {
|
||||
// ShowToolCalls is off, so the browser can render a clickable chip to route
|
||||
// the operator to the page.
|
||||
func TestChatStreamEmitsNavigateChip(t *testing.T) {
|
||||
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
|
||||
stream := func(_ context.Context, _ gateway.Inbound, turn gateway.TurnStream) (string, error) {
|
||||
out, _ := json.Marshal(gateway.DashboardNavigateResult{Path: "/tasks", Label: "Tasks"})
|
||||
turn.ToolCall(gateway.ToolCallEvent{ID: "nav-1", Name: "dashboard_navigate", Output: string(out)})
|
||||
return "That is on the Tasks page.", nil
|
||||
|
||||
Reference in new issue
Block a user