From 2f57c1b55a144e7f2a78349fbeb72cf16b8cdbb2 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Sat, 22 Aug 2026 00:39:04 +0200 Subject: [PATCH] Wait on the room the caller is actually delivered on A thread delivers to one of two surfaces depending on what the participant is: users and apps get a message recipient and are notified on thread_participant:me, agent instances get an inbox item and are notified on instance_inbox:me. The two are mutually exclusive. This command spoke only the first, for every caller. Run inside an agent workload it subscribed to a room its events never reach and then read a table its messages are never written to, so waiting on a reply from another agent could only ever time out -- the reply arrives, and the waiter is watching the wrong two places for it. Pick the surface from the caller: an agent instance reads and acks its inbox and subscribes to instance_inbox:me, everyone else is unchanged. The ack addresses the item rather than the message inside it, so the surface remembers which item each message arrived in. --- internal/cmd/threads.go | 38 +++--- internal/cmd/threads_inbox.go | 201 +++++++++++++++++++++++++++++ internal/cmd/threads_inbox_test.go | 123 ++++++++++++++++++ 3 files changed, 345 insertions(+), 17 deletions(-) create mode 100644 internal/cmd/threads_inbox.go create mode 100644 internal/cmd/threads_inbox_test.go diff --git a/internal/cmd/threads.go b/internal/cmd/threads.go index 13c8162..ee7c0ed 100644 --- a/internal/cmd/threads.go +++ b/internal/cmd/threads.go @@ -245,7 +245,7 @@ func runThreadsCreate(cmd *cobra.Command, args *threadsCreateArgs) error { } if args.wait > 0 { - return waitOutputAndAck(cmd.Context(), cmd, runContext, threadsClient, []threadTarget{{ID: threadID, Ref: args.ref}}, agentID, refs, time.Duration(args.wait)*time.Second, false) + return waitOutputAndAck(cmd.Context(), cmd, runContext, unreadSurfaceFor(runContext, agentID), []threadTarget{{ID: threadID, Ref: args.ref}}, refs, time.Duration(args.wait)*time.Second, false) } if runContext.OutputFormat == output.FormatTable { @@ -318,7 +318,7 @@ func runThreadsSend(cmd *cobra.Command, args *threadsSendArgs) error { return fmt.Errorf("send message: response missing thread id") } targets := []threadTarget{{ID: sentThreadID, Ref: refFor(refs, sentThreadID)}} - return waitOutputAndAck(cmd.Context(), cmd, runContext, threadsClient, targets, senderID, refs, time.Duration(args.wait)*time.Second, false) + return waitOutputAndAck(cmd.Context(), cmd, runContext, unreadSurfaceFor(runContext, senderID), targets, refs, time.Duration(args.wait)*time.Second, false) } if runContext.OutputFormat == output.FormatTable { @@ -356,14 +356,15 @@ func runThreadsRead(cmd *cobra.Command, args *threadsReadArgs) error { if err != nil { return err } - protoMessages, err := fetchUnreadMessages(cmd.Context(), threadsClient, threadTargets, participantID) + surface := unreadSurfaceFor(runContext, participantID) + protoMessages, err := surface.fetch(cmd.Context(), threadTargets) if err != nil { return err } if len(protoMessages) == 0 && args.wait > 0 { - return waitOutputAndAck(cmd.Context(), cmd, runContext, threadsClient, threadTargets, participantID, refs, time.Duration(args.wait)*time.Second, includeThreadLine) + return waitOutputAndAck(cmd.Context(), cmd, runContext, surface, threadTargets, refs, time.Duration(args.wait)*time.Second, includeThreadLine) } - return outputAndAck(cmd.Context(), cmd, runContext.OutputFormat, threadsClient, participantID, protoMessages, refs, includeThreadLine) + return outputAndAck(cmd.Context(), cmd, runContext.OutputFormat, surface, protoMessages, refs, includeThreadLine) } messages, err := fetchMessages(cmd.Context(), threadsClient, threadTargets) @@ -374,6 +375,7 @@ func runThreadsRead(cmd *cobra.Command, args *threadsReadArgs) error { messages, err = waitForMessages( cmd.Context(), runContext, + callerRoom(), threadTargets, time.Duration(args.wait)*time.Second, func(ctx context.Context) ([]*threadsv1.Message, error) { @@ -754,7 +756,7 @@ func renderMessages(w io.Writer, messages []messageView, includeThreadLine bool) return nil } -func outputAndAck(ctx context.Context, cmd *cobra.Command, format output.Format, client gatewayv1connect.ThreadsGatewayClient, participantID string, messages []*threadsv1.Message, refs map[string]string, includeThreadLine bool) error { +func outputAndAck(ctx context.Context, cmd *cobra.Command, format output.Format, surface unreadSurface, messages []*threadsv1.Message, refs map[string]string, includeThreadLine bool) error { view, err := toMessageViews(messages, refs) if err != nil { return err @@ -765,15 +767,15 @@ func outputAndAck(ctx context.Context, cmd *cobra.Command, format output.Format, if len(view) == 0 { return nil } - return ackMessages(ctx, client, participantID, view) + return surface.ack(ctx, view) } -func waitOutputAndAck(ctx context.Context, cmd *cobra.Command, runContext *RunContext, client gatewayv1connect.ThreadsGatewayClient, targets []threadTarget, participantID string, refs map[string]string, timeout time.Duration, includeThreadLine bool) error { - protoMessages, err := waitForUnreadMessages(ctx, runContext, targets, participantID, timeout) +func waitOutputAndAck(ctx context.Context, cmd *cobra.Command, runContext *RunContext, surface unreadSurface, targets []threadTarget, refs map[string]string, timeout time.Duration, includeThreadLine bool) error { + protoMessages, err := waitForUnreadMessages(ctx, runContext, surface, targets, timeout) if err != nil { return err } - return outputAndAck(ctx, cmd, runContext.OutputFormat, client, participantID, protoMessages, refs, includeThreadLine) + return outputAndAck(ctx, cmd, runContext.OutputFormat, surface, protoMessages, refs, includeThreadLine) } func ackMessages(ctx context.Context, client gatewayv1connect.ThreadsGatewayClient, participantID string, messages []messageView) error { @@ -799,16 +801,16 @@ func ackMessages(ctx context.Context, client gatewayv1connect.ThreadsGatewayClie return nil } -func waitForUnreadMessages(ctx context.Context, runContext *RunContext, targets []threadTarget, participantID string, timeout time.Duration) ([]*threadsv1.Message, error) { - threadsClient := gatewayv1connect.NewThreadsGatewayClient(runContext.Clients.HTTPClient, runContext.Clients.BaseURL, runContext.Clients.ConnectOpts()...) - return waitForMessages(ctx, runContext, targets, timeout, func(ctx context.Context) ([]*threadsv1.Message, error) { - return fetchUnreadMessages(ctx, threadsClient, targets, participantID) +func waitForUnreadMessages(ctx context.Context, runContext *RunContext, surface unreadSurface, targets []threadTarget, timeout time.Duration) ([]*threadsv1.Message, error) { + return waitForMessages(ctx, runContext, surface.room(), targets, timeout, func(ctx context.Context) ([]*threadsv1.Message, error) { + return surface.fetch(ctx, targets) }) } func waitForMessages( ctx context.Context, runContext *RunContext, + room string, targets []threadTarget, timeout time.Duration, fetch func(context.Context) ([]*threadsv1.Message, error), @@ -824,7 +826,7 @@ func waitForMessages( waitCtx, cancel = context.WithTimeout(ctx, timeout) defer cancel() } - messages, err := waitForNotificationMessages(waitCtx, notificationsClient, threadSet, fetch) + messages, err := waitForNotificationMessages(waitCtx, notificationsClient, room, threadSet, fetch) if err != nil { if errors.Is(err, context.DeadlineExceeded) { return nil, fmt.Errorf("wait timed out") @@ -837,10 +839,11 @@ func waitForMessages( func waitForNotificationMessages( ctx context.Context, client gatewayv1connect.NotificationsGatewayClient, + room string, targetThreads map[string]struct{}, fetch func(context.Context) ([]*threadsv1.Message, error), ) ([]*threadsv1.Message, error) { - events, errs, err := subscribeMessageNotifications(ctx, client, targetThreads) + events, errs, err := subscribeMessageNotifications(ctx, client, room, targetThreads) if err != nil { return nil, err } @@ -889,10 +892,11 @@ func waitForNotificationMessages( func subscribeMessageNotifications( ctx context.Context, client gatewayv1connect.NotificationsGatewayClient, + room string, targetThreads map[string]struct{}, ) (<-chan messageNotification, <-chan error, error) { stream, err := client.Subscribe(ctx, connect.NewRequest(¬ificationsv1.SubscribeRequest{ - Rooms: []string{threadParticipantSelfRoom}, + Rooms: []string{room}, })) if err != nil { return nil, nil, formatNotificationStreamError(err) diff --git a/internal/cmd/threads_inbox.go b/internal/cmd/threads_inbox.go new file mode 100644 index 0000000..27ec493 --- /dev/null +++ b/internal/cmd/threads_inbox.go @@ -0,0 +1,201 @@ +package cmd + +import ( + "context" + "fmt" + "os" + "strings" + "sync" + + "connectrpc.com/connect" + + agentsv1 "github.com/agynio/agyn-cli/gen/agynio/api/agents/v1" + "github.com/agynio/agyn-cli/gen/agynio/api/gateway/v1/gatewayv1connect" + threadsv1 "github.com/agynio/agyn-cli/gen/agynio/api/threads/v1" +) + +// A thread delivers to one of two consumer surfaces, and which one is a +// property of the participant rather than a choice: users and apps get a +// message recipient and are notified on thread_participant:me, while an agent +// instance gets an inbox item and is notified on instance_inbox:me. The two are +// mutually exclusive -- what is delivered to one is absent from the other. +// +// This command spoke only the first, for every caller. Run inside an agent +// workload it subscribed to a room its events never reach and then read a table +// its messages are never written to, so waiting on a reply from another agent +// could only ever time out. +const instanceInboxSelfRoom = "instance_inbox:me" + +// unreadSurface is one participant's side of that split: the room its arrivals +// are announced on, and the read and ack that go with it. +type unreadSurface interface { + room() string + fetch(ctx context.Context, targets []threadTarget) ([]*threadsv1.Message, error) + ack(ctx context.Context, messages []messageView) error +} + +// runningAsAgentInstance reports whether this process is an agent's own CLI. +// The workload sets AGYN_IDENTITY_ID to the instance it runs as, and an +// instance's identity id is that instance -- the same value the inbox +// authorizes against. Nothing but a workload sets it. +func runningAsAgentInstance() bool { + return strings.TrimSpace(os.Getenv(agynIdentityIDEnv)) != "" +} + +// callerRoom is the room this caller's own message.created events arrive on, +// for waits that read the thread itself rather than a delivery to them. +func callerRoom() string { + if runningAsAgentInstance() { + return instanceInboxSelfRoom + } + return threadParticipantSelfRoom +} + +// unreadSurfaceFor picks the surface this caller is actually delivered on. +func unreadSurfaceFor(runContext *RunContext, participantID string) unreadSurface { + if !runningAsAgentInstance() { + return &participantSurface{ + client: gatewayv1connect.NewThreadsGatewayClient( + runContext.Clients.HTTPClient, runContext.Clients.BaseURL, runContext.Clients.ConnectOpts()...), + participantID: participantID, + } + } + return &inboxSurface{ + client: gatewayv1connect.NewAgentsGatewayClient( + runContext.Clients.HTTPClient, runContext.Clients.BaseURL, runContext.Clients.ConnectOpts()...), + instanceID: participantID, + itemIDs: map[string]string{}, + } +} + +// participantSurface is the user and app side: message recipients. +type participantSurface struct { + client gatewayv1connect.ThreadsGatewayClient + participantID string +} + +func (s *participantSurface) room() string { return threadParticipantSelfRoom } + +func (s *participantSurface) fetch(ctx context.Context, targets []threadTarget) ([]*threadsv1.Message, error) { + return fetchUnreadMessages(ctx, s.client, targets, s.participantID) +} + +func (s *participantSurface) ack(ctx context.Context, messages []messageView) error { + return ackMessages(ctx, s.client, s.participantID, messages) +} + +// inboxSurface is the agent-instance side: inbox items. +// +// An ack addresses the item, not the message inside it, so the surface +// remembers which item each message arrived in. +type inboxSurface struct { + client gatewayv1connect.AgentsGatewayClient + instanceID string + + mu sync.Mutex + itemIDs map[string]string // message id -> inbox item id +} + +func (s *inboxSurface) room() string { return instanceInboxSelfRoom } + +// fetch reads this instance's unacked items and presents the thread-sourced +// ones as the messages they were made from, so the rest of the command sees +// what a user would. Items from anywhere but a thread belong to no thread and +// are left for the daemon: this command is about threads. +func (s *inboxSurface) fetch(ctx context.Context, targets []threadTarget) ([]*threadsv1.Message, error) { + allowed := make(map[string]struct{}, len(targets)) + for _, target := range targets { + allowed[target.ID] = struct{}{} + } + + pageToken := "" + all := []*threadsv1.Message{} + for { + resp, err := s.client.GetUnackedInboxItems(ctx, connect.NewRequest(&agentsv1.GetUnackedInboxItemsRequest{ + AgentInstanceId: s.instanceID, + PageSize: defaultPageSize, + PageToken: pageToken, + })) + if err != nil { + return nil, fmt.Errorf("get unread inbox items: %w", err) + } + for _, item := range resp.Msg.GetItems() { + if item == nil { + return nil, fmt.Errorf("unread inbox item is nil") + } + if item.GetSourceKind() != agentsv1.InboxItemSourceKind_INBOX_ITEM_SOURCE_KIND_THREAD { + continue + } + if len(allowed) > 0 { + if _, ok := allowed[item.GetThreadId()]; !ok { + continue + } + } + message, err := s.messageFromItem(item) + if err != nil { + return nil, err + } + all = append(all, message) + } + pageToken = resp.Msg.GetNextPageToken() + if pageToken == "" { + break + } + } + return all, nil +} + +func (s *inboxSurface) messageFromItem(item *agentsv1.InboxItem) (*threadsv1.Message, error) { + itemID := item.GetId() + if itemID == "" { + return nil, fmt.Errorf("inbox item.id is required") + } + messageID := item.GetMessageId() + if messageID == "" { + return nil, fmt.Errorf("inbox item %s is thread-sourced but names no message", itemID) + } + s.mu.Lock() + s.itemIDs[messageID] = itemID + s.mu.Unlock() + + return &threadsv1.Message{ + Id: messageID, + ThreadId: item.GetThreadId(), + SenderId: item.GetSenderId(), + Body: item.GetBody(), + FileIds: item.GetFileIds(), + CreatedAt: item.GetAcceptedAt(), + }, nil +} + +func (s *inboxSurface) ack(ctx context.Context, messages []messageView) error { + if len(messages) == 0 { + return nil + } + itemIDs := make([]string, 0, len(messages)) + seen := map[string]struct{}{} + s.mu.Lock() + for _, message := range messages { + itemID, ok := s.itemIDs[message.ID] + if !ok { + continue + } + if _, done := seen[itemID]; done { + continue + } + seen[itemID] = struct{}{} + itemIDs = append(itemIDs, itemID) + } + s.mu.Unlock() + if len(itemIDs) == 0 { + return nil + } + _, err := s.client.AckInboxItems(ctx, connect.NewRequest(&agentsv1.AckInboxItemsRequest{ + AgentInstanceId: s.instanceID, + ItemIds: itemIDs, + })) + if err != nil { + return fmt.Errorf("ack inbox items: %w", err) + } + return nil +} diff --git a/internal/cmd/threads_inbox_test.go b/internal/cmd/threads_inbox_test.go new file mode 100644 index 0000000..f059676 --- /dev/null +++ b/internal/cmd/threads_inbox_test.go @@ -0,0 +1,123 @@ +package cmd + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "connectrpc.com/connect" + "google.golang.org/protobuf/types/known/timestamppb" + + agentsv1 "github.com/agynio/agyn-cli/gen/agynio/api/agents/v1" + "github.com/agynio/agyn-cli/gen/agynio/api/gateway/v1/gatewayv1connect" +) + +type recordingAgentsGateway struct { + gatewayv1connect.UnimplementedAgentsGatewayHandler + items []*agentsv1.InboxItem + ackReq *agentsv1.AckInboxItemsRequest + fetched *agentsv1.GetUnackedInboxItemsRequest +} + +func (s *recordingAgentsGateway) GetUnackedInboxItems(ctx context.Context, req *connect.Request[agentsv1.GetUnackedInboxItemsRequest]) (*connect.Response[agentsv1.GetUnackedInboxItemsResponse], error) { + s.fetched = req.Msg + return connect.NewResponse(&agentsv1.GetUnackedInboxItemsResponse{Items: s.items}), nil +} + +func (s *recordingAgentsGateway) AckInboxItems(ctx context.Context, req *connect.Request[agentsv1.AckInboxItemsRequest]) (*connect.Response[agentsv1.AckInboxItemsResponse], error) { + s.ackReq = req.Msg + return connect.NewResponse(&agentsv1.AckInboxItemsResponse{AckedCount: int32(len(req.Msg.GetItemIds()))}), nil +} + +func newInboxSurfaceForTest(t *testing.T, service *recordingAgentsGateway) *inboxSurface { + t.Helper() + path, handler := gatewayv1connect.NewAgentsGatewayHandler(service) + mux := http.NewServeMux() + mux.Handle(path, handler) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + return &inboxSurface{ + client: gatewayv1connect.NewAgentsGatewayClient(server.Client(), server.URL), + instanceID: "instance-1", + itemIDs: map[string]string{}, + } +} + +func threadItem(itemID, messageID, threadID string) *agentsv1.InboxItem { + return &agentsv1.InboxItem{ + Id: itemID, + ThreadId: &threadID, + MessageId: &messageID, + SourceKind: agentsv1.InboxItemSourceKind_INBOX_ITEM_SOURCE_KIND_THREAD, + SenderId: "sender-1", + Body: "hello", + AcceptedAt: timestamppb.Now(), + } +} + +func TestUnreadSurfaceFollowsCallerKind(t *testing.T) { + t.Setenv(agynIdentityIDEnv, "") + if room := callerRoom(); room != threadParticipantSelfRoom { + t.Fatalf("user caller waits on %q, want %q", room, threadParticipantSelfRoom) + } + t.Setenv(agynIdentityIDEnv, "instance-1") + if room := callerRoom(); room != instanceInboxSelfRoom { + t.Fatalf("agent caller waits on %q, want %q", room, instanceInboxSelfRoom) + } +} + +func TestInboxSurfaceFetchesThreadItems(t *testing.T) { + direct := &agentsv1.InboxItem{ + Id: "item-direct", + SourceKind: agentsv1.InboxItemSourceKind_INBOX_ITEM_SOURCE_KIND_DIRECT, + SenderId: "sender-1", + Body: "direct", + AcceptedAt: timestamppb.Now(), + } + service := &recordingAgentsGateway{items: []*agentsv1.InboxItem{ + threadItem("item-1", "message-1", "thread-1"), + threadItem("item-2", "message-2", "thread-other"), + direct, + }} + surface := newInboxSurfaceForTest(t, service) + + messages, err := surface.fetch(context.Background(), []threadTarget{{ID: "thread-1"}}) + if err != nil { + t.Fatalf("fetch: %v", err) + } + if len(messages) != 1 { + t.Fatalf("got %d messages, want only the one on thread-1", len(messages)) + } + if messages[0].GetId() != "message-1" || messages[0].GetThreadId() != "thread-1" { + t.Fatalf("got message %q on thread %q, want message-1 on thread-1", messages[0].GetId(), messages[0].GetThreadId()) + } + if messages[0].GetBody() != "hello" || messages[0].GetSenderId() != "sender-1" { + t.Fatalf("message lost its body or sender: %+v", messages[0]) + } + if service.fetched.GetAgentInstanceId() != "instance-1" { + t.Fatalf("read as %q, want instance-1", service.fetched.GetAgentInstanceId()) + } +} + +// The ack addresses the item, not the message inside it. Sending message ids +// here acks nothing and the caller is handed the same message forever. +func TestInboxSurfaceAcksItemIDs(t *testing.T) { + service := &recordingAgentsGateway{items: []*agentsv1.InboxItem{threadItem("item-1", "message-1", "thread-1")}} + surface := newInboxSurfaceForTest(t, service) + + ctx := context.Background() + if _, err := surface.fetch(ctx, nil); err != nil { + t.Fatalf("fetch: %v", err) + } + if err := surface.ack(ctx, []messageView{{ID: "message-1"}, {ID: "message-1"}}); err != nil { + t.Fatalf("ack: %v", err) + } + if service.ackReq == nil { + t.Fatal("ack never reached the inbox") + } + got := service.ackReq.GetItemIds() + if len(got) != 1 || got[0] != "item-1" { + t.Fatalf("acked %v, want [item-1]", got) + } +}