Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions internal/agentengine/image_generation.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ import (

type imageGenerator func(context.Context, *modelprovider.ImageGenerationConfig, string, modelprovider.ImageGenerationOptions, ...modelprovider.ReferenceImage) (modelprovider.GeneratedImage, error)

var errImageModelNotConfigured = errors.New("image_model_not_configured")

func checkImageModel(ref *modelprovider.ImageGenerationConfig) error {
if ref == nil || strings.TrimSpace(ref.ProviderID) == "" || strings.TrimSpace(ref.ModelID) == "" {
return errImageModelNotConfigured
}
return nil
}

func (c *conversations) imageHandler(turn *activeTurn, sink EventSink, ref *modelprovider.ImageGenerationConfig, input []InputPart) (contract.ImageGenerationHandler, func(bool) error) {
var mu sync.Mutex
tasks := map[string]error{}
Expand All @@ -28,6 +37,9 @@ func (c *conversations) imageHandler(turn *activeTurn, sink EventSink, ref *mode
if editFailed && !edit {
return fmt.Errorf("image_edit_fallback_blocked: editing the original failed; ask the user before generating a replacement in a new turn")
}
if err := checkImageModel(ref); err != nil {
return err
}
if c.engine.imageGenerationModes != nil {
modes := c.engine.imageGenerationModes(ref)
if err := modelprovider.ValidateImageGenerationMode(modes, edit); err != nil {
Expand Down Expand Up @@ -76,6 +88,11 @@ func (c *conversations) generateImage(ctx context.Context, turn *activeTurn, sin
if task.ID == "" || strings.TrimSpace(task.Prompt) == "" || len(task.Prompt) > 32000 {
return fmt.Errorf("invalid image prompt")
}
if task.File == nil {
if err := checkImageModel(task.Model); err != nil {
return err
}
}
emit := func() error {
copy := task
return c.engine.recordAndEmit(ctx, turn, sink, TurnEvent{Kind: TurnEventOutputItem, Output: &OutputItem{Kind: contract.OutputItemImageGeneration, Payload: copy}})
Expand Down
39 changes: 35 additions & 4 deletions internal/agentengine/image_generation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func TestSuccessfulImageRetryParticipatesInCompletedTurnEviction(t *testing.T) {
}}
t.Cleanup(func() { engine.files.DeleteAgent("agent-image") })
conversation := engine.Conversations("agent-image")
request := TurnRequest{ID: "image-retry", ConversationKey: "room-image", Input: []InputPart{{Kind: InputPartText, Text: "blue sky"}}, ImageGeneration: &contract.ImageGenerationTask{ID: "image-call", Prompt: "blue sky"}}
request := TurnRequest{ID: "image-retry", ConversationKey: "room-image", Input: []InputPart{{Kind: InputPartText, Text: "blue sky"}}, ImageGeneration: &contract.ImageGenerationTask{ID: "image-call", Prompt: "blue sky", Model: testImageModel()}}
var fileID string
sink := contract.ImageGenerationSink{EventSink: EventSinkFunc(func(_ context.Context, event TurnEvent) error {
if task, ok := event.Output.Payload.(contract.ImageGenerationTask); ok && task.State == "completed" {
Expand Down Expand Up @@ -121,7 +121,7 @@ func TestImageHandlerStopsAfterBadRequestForTurn(t *testing.T) {
conversation := &conversations{engine: engine, agentID: "agent-1"}
turn := &activeTurn{request: TurnRequest{ID: "turn-1", ConversationKey: "room-1"}}
sink := contract.ImageGenerationSink{EventSink: EventSinkFunc(func(context.Context, TurnEvent) error { return nil })}
handle, preflight := conversation.imageHandler(turn, sink, nil, nil)
handle, preflight := conversation.imageHandler(turn, sink, testImageModel(), nil)
first := handle(context.Background(), "call-1", "blue sky", nil, modelprovider.ImageGenerationOptions{})
second := handle(context.Background(), "call-2", "blue sky", nil, modelprovider.ImageGenerationOptions{Size: "1024x1024"})
var providerErr *modelprovider.ImageGenerationError
Expand All @@ -137,7 +137,7 @@ func TestImageHandlerDoesNotGenerateReplacementAfterEditFails(t *testing.T) {
return modelprovider.GeneratedImage{}, errors.New("unexpected provider call")
}}
conversation := &conversations{engine: engine, agentID: "agent-1"}
handle, preflight := conversation.imageHandler(&activeTurn{}, nil, nil, nil)
handle, preflight := conversation.imageHandler(&activeTurn{}, nil, testImageModel(), nil)
if err := handle(context.Background(), "edit", "add a sheep", []int{1}, modelprovider.ImageGenerationOptions{}); err == nil {
t.Fatal("expected the missing reference to fail")
}
Expand All @@ -154,7 +154,7 @@ func TestImageHandlerPreflightRejectsEditWithTextOnlyModel(t *testing.T) {
return modelcap.ImageGeneration{TextToImage: true}
}}
conversation := &conversations{engine: engine}
_, preflight := conversation.imageHandler(&activeTurn{}, nil, nil, nil)
_, preflight := conversation.imageHandler(&activeTurn{}, nil, testImageModel(), nil)
if err := preflight(false); err != nil {
t.Fatalf("text-to-image should be allowed: %v", err)
}
Expand All @@ -167,3 +167,34 @@ func TestImageHandlerPreflightRejectsEditWithTextOnlyModel(t *testing.T) {
t.Fatal("text-to-image must not replace the rejected edit in the same turn")
}
}

func testImageModel() *modelprovider.ImageGenerationConfig {
return &modelprovider.ImageGenerationConfig{ProviderID: "codex", ModelID: "gpt-image-2"}
}

func TestImageGenerationMissingModelReturnsToolErrorWithoutOutput(t *testing.T) {
ctx := context.Background()
engine := &Engine{generateImage: func(context.Context, *modelprovider.ImageGenerationConfig, string, modelprovider.ImageGenerationOptions, ...modelprovider.ReferenceImage) (modelprovider.GeneratedImage, error) {
t.Fatal("provider called without a model")
return modelprovider.GeneratedImage{}, nil
}}
conversation := &conversations{engine: engine}
turn := &activeTurn{}
sink := contract.ImageGenerationSink{EventSink: EventSinkFunc(func(context.Context, TurnEvent) error {
t.Fatal("missing model should not create an image status message")
return nil
})}
for _, model := range []*modelprovider.ImageGenerationConfig{nil, {ProviderID: "codex"}, {ModelID: "gpt-image-2"}} {
handle, preflight := conversation.imageHandler(turn, sink, model, nil)
if err := preflight(false); !errors.Is(err, errImageModelNotConfigured) {
t.Fatalf("preflight: %v", err)
}
if err := handle(ctx, "call-1", "blue sky", []int{1}, modelprovider.ImageGenerationOptions{}); !errors.Is(err, errImageModelNotConfigured) {
t.Fatalf("tool: %v", err)
}
task := contract.ImageGenerationTask{ID: "call-1", Prompt: "blue sky", Model: model}
if err := conversation.generateImage(ctx, turn, sink, task); !errors.Is(err, errImageModelNotConfigured) {
t.Fatalf("retry: %v", err)
}
}
}
1 change: 1 addition & 0 deletions internal/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ func (h *Handler) registerCoreRoutes(router chi.Router) {
r.Get("/attachments/{id}", h.handleAttachmentByID)
r.Head("/attachments/{id}", h.handleAttachmentByID)
r.Get("/conversations", h.listTaskConversations)
r.Get("/conversations/filters", h.listTaskConversationFilters)
r.Route("/rooms", func(r chi.Router) {
r.Get("/", h.listRooms)
r.Post("/", h.createRoom)
Expand Down
160 changes: 142 additions & 18 deletions internal/api/task_conversations.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ func (h *Handler) listTaskConversations(w http.ResponseWriter, r *http.Request)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
currentUserID := h.im.CurrentUserID()
query := r.URL.Query()
limit, offset := 20, 0
for key, dst := range map[string]*int{"limit": &limit, "offset": &offset} {
Expand All @@ -146,28 +145,31 @@ func (h *Handler) listTaskConversations(w http.ResponseWriter, r *http.Request)
}
archived := query.Get("archived") == "true"
terms := strings.Fields(strings.ToLower(query.Get("q")))
rooms := make([]im.Room, 0)
for _, room := range h.im.ListRoomsWithOptions(im.ListMessagesOptions{IncludeThreadReplies: true}) {
if !slices.Contains(room.Members, currentUserID) {
continue
}
if room.IsAutonomous() {
messages := make([]im.Message, 0, len(room.Messages))
for _, message := range room.Messages {
if !im.IsAutonomousCoordinationNotice(message) {
messages = append(messages, message)
}
owner, directory := query.Get("owner"), query.Get("directory")
currentUserID := taskConversationLocalUser(h.im.CurrentUserID())
legacyPeers := make(map[string]bool)
if directory != "" {
for _, peer := range query["legacy_peer"] {
if id := taskConversationLocalUser(peer); id != "" {
legacyPeers[id] = true
}
room.Messages = messages
}
// Automatically provisioned agent DMs are preparation, not task history.
if room.IsDirect && !room.TaskSession && !room.CustomTitle && !room.Pinned && !room.Archived && !hasConversationHistory(room) {
continue
}
rooms := make([]im.Room, 0)
h.visitTaskConversations(archived, func(room im.Room) {
if owner != "" || directory != "" {
key := taskConversationDimensions(room, currentUserID)
if owner != "" && owner != key.owner() {
return
}
if directory != "" && !key.matchesDirectory(directory, legacyPeers) {
return
}
}
if room.Archived == archived && conversationMatches(room, terms) {
if conversationMatches(room, terms) {
rooms = append(rooms, room)
}
}
})
sort.Slice(rooms, func(i, j int) bool {
if rooms[i].Pinned != rooms[j].Pinned {
return rooms[i].Pinned
Expand Down Expand Up @@ -196,6 +198,128 @@ func (h *Handler) listTaskConversations(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, taskConversationPage{Rooms: page, Total: total, HasMore: end < total})
}

// Group history by the dimensions the filter needs. A nil directory allows the
// client to apply the current Agent directory to rooms predating task configuration.
type taskConversationFilterGroup struct {
Direct bool `json:"is_direct"`
Peer string `json:"peer,omitempty"`
CloudUser *string `json:"cloud_user,omitempty"`
WorkspaceDir *string `json:"workspace_dir,omitempty"`
Count int `json:"count"`
}

func (h *Handler) listTaskConversationFilters(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireLocalChannel(w); !ok {
return
}
if err := h.reloadIM(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
currentUserID := taskConversationLocalUser(h.im.CurrentUserID())
counts := make(map[taskConversationFilterKey]int)
h.visitTaskConversations(r.URL.Query().Get("archived") == "true", func(room im.Room) {
counts[taskConversationDimensions(room, currentUserID)]++
})
groups := make([]taskConversationFilterGroup, 0, len(counts))
for key, count := range counts {
group := taskConversationFilterGroup{Direct: key.direct, Peer: key.peer, Count: count}
if key.cloud {
group.CloudUser = &key.cloudUser
}
if key.configured {
group.WorkspaceDir = &key.directory
}
groups = append(groups, group)
}
writeJSON(w, http.StatusOK, groups)
}

type taskConversationFilterKey struct {
direct, cloud, configured bool
peer, cloudUser, directory string
}

func taskConversationDimensions(room im.Room, currentUserID string) taskConversationFilterKey {
key := taskConversationFilterKey{direct: room.IsDirect}
if room.CloudAgent != nil {
key.cloud, key.cloudUser = true, room.CloudAgent.UserID
} else if room.IsDirect {
for _, member := range room.Members {
if id := taskConversationLocalUser(member); id != "" && id != currentUserID {
key.peer = member
break
}
}
}
if room.Configuration != nil {
key.configured, key.directory = true, room.Configuration.WorkspaceDir
}
return key
}

func (key taskConversationFilterKey) owner() string {
switch {
case key.cloud && key.cloudUser != "":
return "cloud:" + key.cloudUser
case key.cloud:
return ""
case !key.direct:
return "collaboration"
case key.peer != "":
return "direct:" + taskConversationLocalUser(key.peer)
default:
return ""
}
}

func (key taskConversationFilterKey) matchesDirectory(directory string, legacyPeers map[string]bool) bool {
if key.configured {
return key.directory == directory
}
// The sidebar resolves legacy directories from the current Agent catalog.
return !key.cloud && legacyPeers[taskConversationLocalUser(key.peer)]
}

// Keep local owner IDs aligned with the sidebar's legacy identity aliases.
func taskConversationLocalUser(id string) string {
id = localIdentitySuffix(id)
for {
index := strings.LastIndexByte(id, '-')
if index <= 0 || len(id)-index-1 != 8 || strings.Trim(id[index+1:], "0123456789abcdef") != "" {
break
}
id = localIdentitySuffix(id[:index])
}
if id == "" {
return ""
}
return "user-" + id
}

func (h *Handler) visitTaskConversations(archived bool, visit func(im.Room)) {
currentUserID := h.im.CurrentUserID()
for _, room := range h.im.ListUnsortedRooms(im.ListMessagesOptions{IncludeThreadReplies: true}) {
if room.Archived != archived || !slices.Contains(room.Members, currentUserID) {
continue
}
if room.IsAutonomous() {
messages := make([]im.Message, 0, len(room.Messages))
for _, message := range room.Messages {
if !im.IsAutonomousCoordinationNotice(message) {
messages = append(messages, message)
}
}
room.Messages = messages
}
// Automatically provisioned agent DMs are preparation, not task history.
if room.IsDirect && !room.TaskSession && !room.CustomTitle && !room.Pinned && !room.Archived && !hasConversationHistory(room) {
continue
}
visit(room)
}
}

func hasConversationHistory(room im.Room) bool {
for _, message := range room.Messages {
if message.Event != nil && message.Event.Key == "task_assigned" {
Expand Down
Loading
Loading