Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8496 feat(qoder): run issues with attachments through Qoder Files and image blocks (#9814)

Shi Peipeied7c001778c0
diff --git a/server/cmd/qoder-runtime/README.md b/server/cmd/qoder-runtime/README.md
index 876cfc706f..5e4ab7fbcc 100644
--- a/server/cmd/qoder-runtime/README.md
+++ b/server/cmd/qoder-runtime/README.md
@@ -106,6 +106,13 @@ GitHub integration links the pull request back to the issue.
a fresh session starts with the current issue and triggering/coalesced comment
context, or with the current chat message. Do not send additional messages
directly to a bridge-owned session while its run is active.
+- Issue attachments: text files (Qoder Files' accepted types, up to 5 MB) are
+ uploaded through Qoder Files and mounted under `/data/attachments/`, which
+ always starts a fresh session. PNG, JPEG, WebP and GIF images (at most 8000 px
+ per side, about 4.5 MB in total per run so Qoder's echo of the message stays
+ readable) are sent as base64 image blocks in the task message;
+ use a Qoder Agent model with image input. Other files are listed in the prompt
+ as unavailable. Uploaded Qoder files are not deleted by the bridge.
- Progress uses cursor-paginated persisted events, polled every three seconds.
Event IDs and opaque page cursors are tracked separately. A turn is successful
only after its user message and `session.status_idle` with `end_turn`, without
@@ -138,7 +145,7 @@ GitHub integration links the pull request back to the issue.
## Current boundaries
This is a PoC for issue runs and chat turns. Squad coordination, local
-directories, attachments (on issues and chat messages), arbitrary Git hosts,
+directories, chat message attachments, binary non-image issue attachments, arbitrary Git hosts,
tag/commit checkout, full comment-history hydration, interactive tool approval, custom client-side tools, terminal access,
file transfer and billing/usage conversion are not implemented. Set up a Qoder
Agent that can execute autonomously with its configured tools. `requires_action`
diff --git a/server/internal/qoderruntime/attachments.go b/server/internal/qoderruntime/attachments.go
new file mode 100644
index 0000000000..a8c148d6c7
--- /dev/null
+++ b/server/internal/qoderruntime/attachments.go
@@ -0,0 +1,202 @@
+package qoderruntime
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "image"
+ _ "image/gif"
+ _ "image/jpeg"
+ _ "image/png"
+ "path"
+ "strings"
+)
+
+type issueAttachment struct {
+ ID string `json:"id"`
+ Filename string `json:"filename"`
+ ContentType string `json:"content_type"`
+ SizeBytes int64 `json:"size_bytes"`
+ DownloadURL string `json:"download_url"`
+}
+
+const (
+ // Qoder's file upload accepts about 5 MB of text.
+ maxAttachmentFileBytes = 5 << 20
+ // Qoder echoes the submitted message in the send response and in the event
+ // list, and the bridge reads at most 8 MiB per response. Keep the encoded
+ // images of one message well below that so the echo stays readable.
+ maxAttachmentImageEncoded = 6 << 20
+ maxAttachmentImageBytes = maxAttachmentImageEncoded / 4 * 3
+ // Qoder rejects base64 images with a side longer than this.
+ maxAttachmentImageSide = 8000
+ attachmentMountDir = "/data/attachments/"
+)
+
+var imageMediaTypes = map[string]bool{"image/png": true, "image/jpeg": true, "image/webp": true, "image/gif": true}
+
+var textMediaTypes = map[string]bool{"application/json": true, "application/xml": true, "application/javascript": true, "application/x-yaml": true, "application/x-toml": true}
+
+// Extensions Qoder's file upload accepts when the stored MIME type is generic.
+var textExtensions = map[string]bool{}
+
+func init() {
+ for _, ext := range strings.Fields(".txt .md .csv .json .xml .yaml .yml .toml .ini .conf .cfg .env .log .html .htm .css .scss .less .js .jsx .ts .tsx .vue .svelte .py .go .rs .java .kt .scala .c .cpp .cc .h .hpp .rb .php .swift .r .lua .pl .sh .bash .zsh .fish .ps1 .sql .graphql .gql .proto .dockerfile .makefile .gitignore .editorconfig .eslintrc .prettierrc .tex .rst .adoc .org .svg") {
+ textExtensions[ext] = true
+ }
+}
+
+func isTextAttachment(a issueAttachment) bool {
+ mediaType := strings.ToLower(strings.TrimSpace(strings.Split(a.ContentType, ";")[0]))
+ return strings.HasPrefix(mediaType, "text/") || textMediaTypes[mediaType] || textExtensions[strings.ToLower(path.Ext(a.Filename))]
+}
+
+// attachIssueFiles hands issue attachments to the Qoder session: text files are
+// uploaded through Qoder Files and mounted into the session, and images are
+// sent as image blocks with the task message. Other files are listed in the
+// prompt as unavailable so the agent knows they exist.
+func (b *Bridge) attachIssueFiles(ctx context.Context, taskAPI *api, attachments []issueAttachment, r *run, p *strings.Builder) error {
+ if len(attachments) == 0 {
+ return nil
+ }
+ var mounted, images, skipped []string
+ used := map[string]bool{}
+ imageEncoded := 0
+ for _, a := range attachments {
+ name := attachmentName(a, used)
+ mediaType := strings.ToLower(strings.TrimSpace(strings.Split(a.ContentType, ";")[0]))
+ switch {
+ case imageMediaTypes[mediaType]:
+ data, err := b.downloadAttachment(ctx, taskAPI, a, maxAttachmentImageBytes)
+ if errors.Is(err, errTooLarge) || err == nil && imageEncoded+base64.StdEncoding.EncodedLen(len(data)) > maxAttachmentImageEncoded {
+ skipped = append(skipped, name+" (image too large)")
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ width, height, ok := imageSize(mediaType, data)
+ if !ok {
+ skipped = append(skipped, name+" (unreadable image)")
+ continue
+ }
+ if width > maxAttachmentImageSide || height > maxAttachmentImageSide {
+ skipped = append(skipped, fmt.Sprintf("%s (image larger than %d px per side)", name, maxAttachmentImageSide))
+ continue
+ }
+ encoded := base64.StdEncoding.EncodeToString(data)
+ imageEncoded += len(encoded)
+ r.Images = append(r.Images, map[string]string{"type": "base64", "media_type": mediaType, "data": encoded})
+ images = append(images, name)
+ case isTextAttachment(a):
+ data, err := b.downloadAttachment(ctx, taskAPI, a, maxAttachmentFileBytes)
+ if errors.Is(err, errTooLarge) {
+ skipped = append(skipped, name+" (file too large)")
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ var file struct {
+ ID string `json:"id"`
+ }
+ if err := b.qoder.upload(ctx, "/files", name, data, &file); err != nil {
+ var rejected *apiError
+ if errors.As(err, &rejected) && (rejected.Status == 400 || rejected.Status == 413 || rejected.Status == 415) {
+ skipped = append(skipped, name+" (rejected by Qoder Files)")
+ continue
+ }
+ return fmt.Errorf("upload attachment %s to Qoder: %w", name, err)
+ }
+ if file.ID == "" {
+ return fmt.Errorf("Qoder file upload returned no file ID")
+ }
+ mountPath := attachmentMountDir + name
+ r.Files = append(r.Files, map[string]any{"type": "file", "file_id": file.ID, "mount_path": mountPath})
+ mounted = append(mounted, mountPath)
+ default:
+ skipped = append(skipped, name+" (unsupported file type)")
+ }
+ }
+ p.WriteString("\nIssue attachments:\n")
+ for _, m := range mounted {
+ fmt.Fprintf(p, "- %s (mounted file)\n", m)
+ }
+ for _, name := range images {
+ fmt.Fprintf(p, "- %s (image attached to this message)\n", name)
+ }
+ for _, s := range skipped {
+ fmt.Fprintf(p, "- %s: not available in this session\n", s)
+ }
+ return nil
+}
+
+func (b *Bridge) downloadAttachment(ctx context.Context, taskAPI *api, a issueAttachment, limit int64) ([]byte, error) {
+ if a.SizeBytes > limit {
+ return nil, errTooLarge
+ }
+ if a.DownloadURL == "" {
+ return nil, fmt.Errorf("attachment %s has no download URL", a.Filename)
+ }
+ data, err := taskAPI.download(ctx, a.DownloadURL, limit)
+ if err != nil && !errors.Is(err, errTooLarge) {
+ return nil, fmt.Errorf("download attachment %s: %w", a.Filename, err)
+ }
+ return data, err
+}
+
+// attachmentName returns a unique, path-free file name for the mount path.
+func attachmentName(a issueAttachment, used map[string]bool) string {
+ name := strings.Map(func(r rune) rune {
+ if r == '/' || r == '\\' || r < 0x20 {
+ return '_'
+ }
+ return r
+ }, strings.TrimSpace(a.Filename))
+ if name == "" || name == "." || name == ".." {
+ name = "attachment"
+ }
+ if len(name) > 200 {
+ name = name[len(name)-200:]
+ }
+ unique := name
+ for i := 2; used[unique]; i++ {
+ ext := path.Ext(name)
+ unique = fmt.Sprintf("%s-%d%s", strings.TrimSuffix(name, ext), i, ext)
+ }
+ used[unique] = true
+ return unique
+}
+
+// imageSize reads the pixel dimensions from the image header. The standard
+// library has no WebP decoder, so WebP headers are parsed directly.
+func imageSize(mediaType string, data []byte) (int, int, bool) {
+ if mediaType != "image/webp" {
+ cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
+ return cfg.Width, cfg.Height, err == nil
+ }
+ if len(data) < 30 || string(data[0:4]) != "RIFF" || string(data[8:12]) != "WEBP" {
+ return 0, 0, false
+ }
+ switch string(data[12:16]) {
+ case "VP8 ":
+ if data[23] != 0x9d || data[24] != 0x01 || data[25] != 0x2a {
+ return 0, 0, false
+ }
+ return int(binary.LittleEndian.Uint16(data[26:28]) & 0x3fff), int(binary.LittleEndian.Uint16(data[28:30]) & 0x3fff), true
+ case "VP8L":
+ if data[20] != 0x2f {
+ return 0, 0, false
+ }
+ bits := binary.LittleEndian.Uint32(data[21:25])
+ return int(bits&0x3fff) + 1, int(bits>>14&0x3fff) + 1, true
+ case "VP8X":
+ width := int(data[24]) | int(data[25])<<8 | int(data[26])<<16
+ height := int(data[27]) | int(data[28])<<8 | int(data[29])<<16
+ return width + 1, height + 1, true
+ }
+ return 0, 0, false
+}
diff --git a/server/internal/qoderruntime/bridge.go b/server/internal/qoderruntime/bridge.go
index 2683eddee0..abc181e3dd 100644
--- a/server/internal/qoderruntime/bridge.go
+++ b/server/internal/qoderruntime/bridge.go
@@ -375,7 +375,8 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {
return b.reject(ctx, r, err.Error())
}
fingerprint := resourceFingerprint(resources)
- if r.PriorSessionID != "" {
+ resources = append(resources, r.Files...)
+ if r.PriorSessionID != "" && len(r.Files) == 0 {
continued, err := b.continueSession(ctx, r, fingerprint)
if err != nil {
return err
@@ -398,6 +399,19 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {
if err := b.taskCall(ctx, r, "/session", map[string]string{"session_id": r.SessionID}, nil); err != nil {
return err
}
+ if r.Phase == "created" && r.Continued && r.Cursor == "" {
+ latest, err := b.latestEventID(ctx, r.SessionID)
+ if definitelyRejected(err) {
+ // The earlier session is gone; nothing was sent yet, so start fresh.
+ r.SessionID, r.PriorSessionID, r.Continued = "", "", false
+ r.Phase = "prepared"
+ return b.persist()
+ }
+ if err != nil {
+ return err
+ }
+ r.Cursor = latest
+ }
if r.Phase == "created" {
// Save intent before POST. After an ambiguous response/restart, never resend automatically.
r.Phase = "sending"
@@ -405,7 +419,11 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {
if err := b.persist(); err != nil {
return err
}
- if err := b.qoder.call(ctx, http.MethodPost, "/sessions/"+url.PathEscape(r.SessionID)+"/events", map[string]any{"events": []map[string]any{{"type": "user.message", "content": []map[string]string{{"type": "text", "text": r.Prompt}}}}}, nil); err != nil {
+ content := []map[string]any{{"type": "text", "text": r.Prompt}}
+ for _, source := range r.Images {
+ content = append(content, map[string]any{"type": "image", "source": source})
+ }
+ if err := b.qoder.call(ctx, http.MethodPost, "/sessions/"+url.PathEscape(r.SessionID)+"/events", map[string]any{"events": []map[string]any{{"type": "user.message", "content": content}}}, nil); err != nil {
if rateLimited(err) {
r.Phase = "created"
r.SubmissionDeadline = time.Time{}
@@ -415,7 +433,7 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {
if definitelyRejected(err) && r.Continued {
// The earlier session can no longer take messages; a definite
// rejection means nothing was delivered, so start a fresh session.
- r.SessionID, r.PriorSessionID, r.Continued = "", "", false
+ r.SessionID, r.PriorSessionID, r.Continued, r.Cursor = "", "", false, ""
r.Phase = "prepared"
r.SubmissionDeadline = time.Time{}
return b.persist()
@@ -426,6 +444,7 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {
return err
}
r.Phase = "running"
+ r.Images = nil
if err := b.persist(); err != nil {
return err
}
diff --git a/server/internal/qoderruntime/bridge_test.go b/server/internal/qoderruntime/bridge_test.go
index 411317fc8b..9360c69846 100644
--- a/server/internal/qoderruntime/bridge_test.go
+++ b/server/internal/qoderruntime/bridge_test.go
@@ -1,14 +1,20 @@
package qoderruntime
import (
+ "bytes"
"context"
+ "encoding/base64"
"encoding/json"
"fmt"
+ "image"
+ "image/png"
"io"
+ "math/rand"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
+ "strconv"
"strings"
"sync/atomic"
"testing"
@@ -87,6 +93,11 @@ type harness struct {
issueStatus int
issueBody string
issuePosts int
+ issueGet string
+ downloads map[string]string
+ uploads map[string]string
+ sessionResources []map[string]any
+ sentContent []map[string]any
}
func setup(t *testing.T) *harness {
@@ -99,7 +110,7 @@ func setup(t *testing.T) *harness {
t.Error("missing workspace")
}
auth := "Bearer multica-secret"
- if strings.HasPrefix(r.URL.Path, "/api/issues") {
+ if strings.HasPrefix(r.URL.Path, "/api/issues") || strings.HasPrefix(r.URL.Path, "/api/attachments/") {
auth = "Bearer mat_task"
}
if r.Header.Get("Authorization") != auth {
@@ -124,7 +135,18 @@ func setup(t *testing.T) *harness {
io.WriteString(w, `{"identifier":"MUL-7"}`)
}
case strings.HasPrefix(r.URL.Path, "/api/issues/"):
- io.WriteString(w, `{"title":"Fix bug","description":"Use repository context"}`)
+ if h.issueGet != "" {
+ io.WriteString(w, h.issueGet)
+ } else {
+ io.WriteString(w, `{"title":"Fix bug","description":"Use repository context"}`)
+ }
+ case strings.HasPrefix(r.URL.Path, "/api/attachments/"):
+ body, ok := h.downloads[r.URL.Path]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ io.WriteString(w, body)
case strings.HasSuffix(r.URL.Path, "/status"):
json.NewEncoder(w).Encode(map[string]string{"status": h.status})
case strings.HasSuffix(r.URL.Path, "/start"):
@@ -162,41 +184,57 @@ func setup(t *testing.T) *harness {
case r.URL.Path == "/sessions" && r.Method == "POST":
h.creates++
var input struct {
- Agent string `json:"agent"`
+ Agent string `json:"agent"`
+ Resources []map[string]any `json:"resources"`
}
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
t.Fatal(err)
}
h.sessionAgent = input.Agent
+ h.sessionResources = input.Resources
io.WriteString(w, `{"id":"sess_1","status":"idle"}`)
case r.URL.Path == "/sessions/sess_1/events" && r.Method == "POST":
h.sends++
+ raw, _ := io.ReadAll(r.Body)
var req struct {
Events []event `json:"events"`
}
- json.NewDecoder(r.Body).Decode(&req)
+ json.Unmarshal(raw, &req)
+ var content struct {
+ Events []struct {
+ Content []map[string]any `json:"content"`
+ } `json:"events"`
+ }
+ json.Unmarshal(raw, &content)
+ h.sentContent = content.Events[0].Content
h.prompt = req.Events[0].text()
- h.events = append(h.events, map[string]any{"id": "evt_user", "type": "user.message", "content": []map[string]string{{"type": "text", "text": h.prompt}}})
+ // Like Qoder, echo the full submitted content on send and in the event list.
+ userEvent := map[string]any{"id": "evt_user", "type": "user.message", "content": h.sentContent}
+ h.events = append(h.events, userEvent)
if h.lostSend {
http.Error(w, "unknown", 502)
return
}
- io.WriteString(w, `{"data":[]}`)
+ json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{userEvent}})
case r.URL.Path == "/sessions/sess_1/events" && r.Method == "GET":
- if r.URL.Query().Get("page") != "" {
+ if page := r.URL.Query().Get("page"); page != "" && !strings.HasPrefix(page, "next:") {
t.Error("event ID used as page cursor")
}
- events := h.events
- after := r.URL.Query().Get("after_id")
- if after != "" {
- for i, e := range events {
- if e["id"] == after {
- events = events[i+1:]
- break
- }
- }
+ json.NewEncoder(w).Encode(eventListPage(r, h.events))
+ case r.URL.Path == "/files" && r.Method == "POST":
+ file, header, err := r.FormFile("file")
+ if err != nil {
+ t.Fatal(err)
}
- json.NewEncoder(w).Encode(map[string]any{"data": events, "has_more": false})
+ data, _ := io.ReadAll(file)
+ if r.FormValue("name") != header.Filename {
+ t.Error("upload name mismatch")
+ }
+ if h.uploads == nil {
+ h.uploads = map[string]string{}
+ }
+ h.uploads[header.Filename] = string(data)
+ fmt.Fprintf(w, `{"id":"file_%d","type":"file"}`, len(h.uploads))
case strings.HasSuffix(r.URL.Path, "/cancel"):
h.cancels++
io.WriteString(w, `{"status":"canceling"}`)
@@ -330,6 +368,132 @@ func TestQuickCreateAttachmentsFailBeforeExecution(t *testing.T) {
t.Fatalf("quick-create attachment ignored: creates=%d posts=%d failure=%#v", h.creates, h.issuePosts, h.failure)
}
}
+func testPNG(t *testing.T, width, height int, noise bool) string {
+ t.Helper()
+ img := image.NewNRGBA(image.Rect(0, 0, width, height))
+ if noise {
+ rand.New(rand.NewSource(1)).Read(img.Pix)
+ }
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, img); err != nil {
+ t.Fatal(err)
+ }
+ return buf.String()
+}
+
+func (h *harness) attach(t *testing.T, files ...[3]string) {
+ t.Helper()
+ var atts []map[string]any
+ h.downloads = map[string]string{}
+ for i, f := range files {
+ u := fmt.Sprintf("/api/attachments/a%d/download", i)
+ atts = append(atts, map[string]any{"id": fmt.Sprint("a", i), "filename": f[0], "content_type": f[1], "size_bytes": len(f[2]), "download_url": u})
+ h.downloads[u] = f[2]
+ }
+ raw, _ := json.Marshal(map[string]any{"title": "Fix bug", "description": "See attachments", "attachments": atts})
+ h.issueGet = string(raw)
+}
+
+func TestIssueAttachmentsReachSession(t *testing.T) {
+ h := setup(t)
+ screen := testPNG(t, 4, 4, false)
+ h.attach(t,
+ [3]string{"notes.md", "text/markdown", "hello"},
+ [3]string{"screen.png", "image/png", screen},
+ [3]string{"spec.pdf", "application/pdf", "%PDF"},
+ [3]string{"notes.md", "text/plain", "bye"},
+ [3]string{"page.png", "image/png", testPNG(t, 400, 9000, false)},
+ [3]string{"broken.png", "image/png", "\x89PNG"})
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.failure != nil || h.sends != 1 {
+ t.Fatalf("run failed: %#v", h.failure)
+ }
+ if h.uploads["notes.md"] != "hello" || h.uploads["notes-2.md"] != "bye" || len(h.uploads) != 2 {
+ t.Fatalf("uploads: %#v", h.uploads)
+ }
+ want := []string{"file_1 /data/attachments/notes.md", "file_2 /data/attachments/notes-2.md"}
+ var got []string
+ for _, res := range h.sessionResources {
+ if res["type"] == "file" {
+ got = append(got, fmt.Sprint(res["file_id"], " ", res["mount_path"]))
+ }
+ }
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Fatalf("mounted resources: %v", h.sessionResources)
+ }
+ if len(h.sentContent) != 2 || h.sentContent[1]["type"] != "image" {
+ t.Fatalf("message content: %#v", h.sentContent)
+ }
+ source, _ := h.sentContent[1]["source"].(map[string]any)
+ if source["type"] != "base64" || source["media_type"] != "image/png" || source["data"] != base64.StdEncoding.EncodeToString([]byte(screen)) {
+ t.Fatalf("image source: %#v", source)
+ }
+ for _, s := range []string{"/data/attachments/notes.md (mounted file)", "screen.png (image attached", "spec.pdf (unsupported file type): not available", "page.png (image larger than 8000 px per side): not available", "broken.png (unreadable image): not available"} {
+ if !strings.Contains(h.prompt, s) {
+ t.Fatalf("prompt missing %q: %s", s, h.prompt)
+ }
+ }
+ if r := h.b.state.first(); r == nil || len(r.Images) != 0 {
+ t.Fatal("sent images kept in the journal")
+ }
+ h.finish("end_turn")
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete == nil {
+ t.Fatalf("run did not complete: %#v", h.failure)
+ }
+}
+
+// The submitted images come back in the send response and the event list;
+// both must stay readable for the run to be confirmed and completed.
+func TestIssueImagesFitEchoedEvents(t *testing.T) {
+ h := setup(t)
+ img := testPNG(t, 700, 700, true)
+ h.attach(t, [3]string{"a.png", "image/png", img}, [3]string{"b.png", "image/png", img}, [3]string{"c.png", "image/png", img})
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if r := h.b.state.first(); r == nil || r.Phase != "running" {
+ t.Fatalf("send not confirmed: %#v", r)
+ }
+ if len(h.sentContent) != 3 || !strings.Contains(h.prompt, "c.png (image too large): not available") {
+ t.Fatalf("image budget not applied: %d blocks, prompt %s", len(h.sentContent), h.prompt)
+ }
+ h.finish("end_turn")
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete == nil {
+ t.Fatalf("run did not complete: %#v", h.failure)
+ }
+}
+
+func TestWebPImageSize(t *testing.T) {
+ header := func(chunk string, body ...byte) []byte {
+ b := append([]byte("RIFF\x00\x00\x00\x00WEBP"+chunk+"\x00\x00\x00\x00"), body...)
+ return append(b, make([]byte, 32)...)
+ }
+ cases := map[string][]byte{
+ "VP8": header("VP8 ", 0, 0, 0, 0x9d, 0x01, 0x2a, 0x90, 0x01, 0x28, 0x23), // 400x9000
+ "VP8L": header("VP8L", 0x2f, 0x8f, 0xc1, 0xc9, 0x08), // 400x9000
+ "VP8X": header("VP8X", 0, 0, 0, 0, 0x8f, 0x01, 0x00, 0x27, 0x23, 0x00), // 400x9000
+ }
+ for name, data := range cases {
+ w, hgt, ok := imageSize("image/webp", data)
+ if !ok || w != 400 || hgt != 9000 {
+ t.Errorf("%s: got %dx%d ok=%v", name, w, hgt, ok)
+ }
+ }
+ if _, _, ok := imageSize("image/webp", []byte("RIFF")); ok {
+ t.Error("truncated WebP accepted")
+ }
+}
+
// lostCreate leaves a quick-create run whose first create request failed
// after it was marked submitted, as when the response is lost.
func lostCreate(t *testing.T, h *harness) {
@@ -882,3 +1046,145 @@ func TestJournalStorageConfig(t *testing.T) {
}
}
}
+
+// eventListPage serves GET /sessions/{id}/events from the full event list,
+// honouring after_id, order and limit, and the opaque "next:<id>" page cursor
+// it hands out itself.
+func eventListPage(r *http.Request, events []map[string]any) map[string]any {
+ q := r.URL.Query()
+ after := q.Get("after_id")
+ if page := q.Get("page"); page != "" {
+ after = strings.TrimPrefix(page, "next:")
+ }
+ if after != "" {
+ for i, e := range events {
+ if e["id"] == after {
+ events = events[i+1:]
+ break
+ }
+ }
+ }
+ if q.Get("order") == "desc" {
+ reversed := make([]map[string]any, 0, len(events))
+ for i := len(events) - 1; i >= 0; i-- {
+ reversed = append(reversed, events[i])
+ }
+ events = reversed
+ }
+ limit, err := strconv.Atoi(q.Get("limit"))
+ if err != nil || limit <= 0 {
+ limit = 20
+ }
+ response := map[string]any{"data": events, "has_more": false}
+ if len(events) > limit {
+ response["data"] = events[:limit]
+ response["has_more"] = true
+ response["next_page"] = fmt.Sprint("next:", events[limit-1]["id"])
+ }
+ return response
+}
+
+// Each event fits the response limit, but a full page of them does not; the
+// bridge must fall back to smaller pages instead of failing the run.
+func TestOversizedEventPageIsReadInSmallerPages(t *testing.T) {
+ h := setup(t)
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ big := strings.Repeat("x", 5<<20)
+ for i := 0; i < 2; i++ {
+ h.events = append(h.events, map[string]any{"id": fmt.Sprint("evt_tool_", i), "type": "agent.tool_result", "content": []map[string]string{{"type": "text", "text": big}}})
+ }
+ h.finish("end_turn")
+ for i := 0; i < 5 && h.complete == nil; i++ {
+ if err := h.b.step(ctx); err != nil {
+ t.Fatalf("step %d: %v", i, err)
+ }
+ }
+ if h.complete == nil || h.failure != nil {
+ t.Fatalf("run did not complete: %#v", h.failure)
+ }
+}
+
+// A follow-up on a session whose earlier turn carried images must read only
+// its own turn: the two turns' images together exceed the response limit.
+func TestImageFollowUpReadsOnlyItsOwnTurn(t *testing.T) {
+ h := setup(t)
+ img := testPNG(t, 700, 700, true)
+ h.attach(t, [3]string{"a.png", "image/png", img}, [3]string{"b.png", "image/png", img})
+ var events []map[string]any
+ var metadata map[string]string
+ creates, posts, fullReads := 0, 0, 0
+ q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case r.URL.Path == "/sessions" && r.Method == http.MethodPost:
+ creates++
+ var req struct {
+ Metadata map[string]string `json:"metadata"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Error(err)
+ }
+ metadata = req.Metadata
+ json.NewEncoder(w).Encode(map[string]string{"id": "sess_1"})
+ case r.URL.Path == "/sessions/sess_1" && r.Method == http.MethodGet:
+ json.NewEncoder(w).Encode(map[string]any{"status": "idle", "agent": "agent_1", "environment_id": "env_1", "metadata": metadata})
+ case r.URL.Path == "/sessions/sess_1/events" && r.Method == http.MethodPost:
+ var req struct {
+ Events []map[string]any `json:"events"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Error(err)
+ return
+ }
+ posts++
+ req.Events[0]["id"] = fmt.Sprint("evt_user_", posts)
+ events = append(events, req.Events[0])
+ json.NewEncoder(w).Encode(map[string]any{"data": req.Events})
+ case r.URL.Path == "/sessions/sess_1/events" && r.Method == http.MethodGet:
+ if posts > 1 && r.URL.Query().Get("after_id") == "" && r.URL.Query().Get("page") == "" && r.URL.Query().Get("order") != "desc" {
+ fullReads++
+ }
+ json.NewEncoder(w).Encode(eventListPage(r, events))
+ default:
+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ defer q.Close()
+ h.b.qoder.base = q.URL
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatalf("first turn: %v", err)
+ }
+ events = append(events, map[string]any{"id": "evt_idle_1", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}})
+ if err := h.b.step(ctx); err != nil {
+ t.Fatalf("finish first turn: %v", err)
+ }
+ if h.complete == nil || h.b.state.first() != nil {
+ t.Fatal("first turn did not complete")
+ }
+
+ h.task = newTask("task-2", "sess_1")
+ h.task.IssueID = "issue-1"
+ h.status, h.complete = "dispatched", nil
+ if err := h.b.step(ctx); err != nil {
+ t.Fatalf("follow-up: %v", err)
+ }
+ run := h.b.state.first()
+ if creates != 1 || posts != 2 || run == nil || !run.Continued || !run.Started {
+ t.Fatalf("follow-up not continued and confirmed: creates=%d posts=%d run=%#v", creates, posts, run)
+ }
+ if fullReads != 0 {
+ t.Fatalf("follow-up re-read the session history %d times", fullReads)
+ }
+ events = append(events, map[string]any{"id": "evt_idle_2", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}})
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete == nil || h.failure != nil {
+ t.Fatalf("follow-up did not complete: %#v", h.failure)
+ }
+}
diff --git a/server/internal/qoderruntime/concurrency_test.go b/server/internal/qoderruntime/concurrency_test.go
index 99c59dd2f9..186c89c644 100644
--- a/server/internal/qoderruntime/concurrency_test.go
+++ b/server/internal/qoderruntime/concurrency_test.go
@@ -112,16 +112,7 @@ func setupMulti(t *testing.T, limit int, tasks ...*daemon.Task) *multiHarness {
h.sessions[parts[1]] = append(h.sessions[parts[1]], map[string]any{"id": fmt.Sprintf("evt_%s_%d", parts[1], len(h.sessions[parts[1]])), "type": "user.message", "content": []map[string]string{{"type": "text", "text": req.Events[0].text()}}})
io.WriteString(w, `{"data":[]}`)
case len(parts) == 3 && parts[2] == "events":
- events := h.sessions[parts[1]]
- if after := r.URL.Query().Get("after_id"); after != "" {
- for i, e := range events {
- if e["id"] == after {
- events = events[i+1:]
- break
- }
- }
- }
- json.NewEncoder(w).Encode(map[string]any{"data": events, "has_more": false})
+ json.NewEncoder(w).Encode(eventListPage(r, h.sessions[parts[1]]))
case len(parts) == 2 && r.Method == http.MethodGet:
status, ok := h.sessionStatus[parts[1]]
if !ok {
diff --git a/server/internal/qoderruntime/events.go b/server/internal/qoderruntime/events.go
index e83a61470d..2339c42b4b 100644
--- a/server/internal/qoderruntime/events.go
+++ b/server/internal/qoderruntime/events.go
@@ -39,19 +39,38 @@ func (e event) text() string {
}
return strings.Join(parts, "\n")
}
+
+// eventPageLimits are tried in order. Qoder returns image blocks in full in
+// user.message events, so a page of them can exceed the response limit even
+// though each message fits; a smaller page is read instead.
+var eventPageLimits = []string{"100", "10", "1"}
+
+type eventPage struct {
+ Data []event `json:"data"`
+ HasMore bool `json:"has_more"`
+ NextPage string `json:"next_page"`
+}
+
func (b *Bridge) events(ctx context.Context, r *run) error {
- q := url.Values{"limit": {"100"}, "order": {"asc"}}
- if r.Page != "" {
- q.Set("page", r.Page)
- } else if r.Cursor != "" {
- q.Set("after_id", r.Cursor)
- }
- var page struct {
- Data []event `json:"data"`
- HasMore bool `json:"has_more"`
- NextPage string `json:"next_page"`
+ var q url.Values
+ var page eventPage
+ var err error
+ for i, limit := range eventPageLimits {
+ q = url.Values{"limit": {limit}, "order": {"asc"}}
+ // An opaque page cursor may carry its own page size, so a smaller
+ // retry resumes after the last processed event instead.
+ if r.Page != "" && (i == 0 || r.Cursor == "") {
+ q.Set("page", r.Page)
+ } else if r.Cursor != "" {
+ q.Set("after_id", r.Cursor)
+ }
+ page = eventPage{}
+ err = b.qoder.call(ctx, http.MethodGet, "/sessions/"+url.PathEscape(r.SessionID)+"/events?"+q.Encode(), nil, &page)
+ if !errors.Is(err, errResponseTooLarge) {
+ break
+ }
}
- if err := b.qoder.call(ctx, http.MethodGet, "/sessions/"+url.PathEscape(r.SessionID)+"/events?"+q.Encode(), nil, &page); err != nil {
+ if err != nil {
var ae *apiError
if errors.As(err, &ae) && ae.Status == http.StatusNotFound {
return b.reject(ctx, r, "Qoder session no longer exists")
@@ -145,3 +164,22 @@ func (b *Bridge) events(ctx context.Context, r *run) error {
}
return nil
}
+
+// latestEventID returns the newest event of a session, or "" when it has none.
+// A continued session starts reading after it, so the new turn never re-reads
+// earlier turns (whose images alone may exceed the response limit) and never
+// mistakes an earlier idle event for its own completion.
+func (b *Bridge) latestEventID(ctx context.Context, sessionID string) (string, error) {
+ q := url.Values{"limit": {"1"}, "order": {"desc"}}
+ var page eventPage
+ if err := b.qoder.call(ctx, http.MethodGet, "/sessions/"+url.PathEscape(sessionID)+"/events?"+q.Encode(), nil, &page); err != nil {
+ return "", err
+ }
+ if len(page.Data) == 0 {
+ return "", nil
+ }
+ if page.Data[0].ID == "" {
+ return "", fmt.Errorf("Qoder event has no ID")
+ }
+ return page.Data[0].ID, nil
+}
diff --git a/server/internal/qoderruntime/http.go b/server/internal/qoderruntime/http.go
index 6cc8791807..32769e8aba 100644
--- a/server/internal/qoderruntime/http.go
+++ b/server/internal/qoderruntime/http.go
@@ -5,8 +5,10 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "mime/multipart"
"net/http"
"net/url"
"strings"
@@ -58,12 +60,36 @@ func (a *api) call(ctx context.Context, method, path string, in, out any) error
}
body = bytes.NewReader(b)
}
+ return a.do(ctx, method, path, "application/json", body, out)
+}
+
+// upload posts one file as multipart/form-data under the "file" field.
+func (a *api) upload(ctx context.Context, path, name string, data []byte, out any) error {
+ var body bytes.Buffer
+ w := multipart.NewWriter(&body)
+ part, err := w.CreateFormFile("file", name)
+ if err != nil {
+ return err
+ }
+ if _, err := part.Write(data); err != nil {
+ return err
+ }
+ if err := w.WriteField("name", name); err != nil {
+ return err
+ }
+ if err := w.Close(); err != nil {
+ return err
+ }
+ return a.do(ctx, http.MethodPost, path, w.FormDataContentType(), &body, out)
+}
+
+func (a *api) do(ctx context.Context, method, path, contentType string, body io.Reader, out any) error {
req, err := http.NewRequestWithContext(ctx, method, a.base+path, body)
if err != nil {
return fmt.Errorf("build API request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+a.token)
- req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Content-Type", contentType)
req.Header.Set("Accept", "application/json")
if a.workspace != "" {
req.Header.Set("X-Workspace-ID", a.workspace)
@@ -93,7 +119,7 @@ func (a *api) call(ctx context.Context, method, path string, in, out any) error
return fmt.Errorf("read API response failed")
}
if len(b) > 8<<20 {
- return fmt.Errorf("API response exceeds 8 MiB")
+ return errResponseTooLarge
}
if out != nil {
if err := json.Unmarshal(b, out); err != nil {
@@ -102,3 +128,52 @@ func (a *api) call(ctx context.Context, method, path string, in, out any) error
}
return nil
}
+
+// download fetches at most limit bytes. A site-relative URL is served by this
+// API and carries its credential; an absolute URL is presigned and does not.
+// Redirects are followed (Go drops the credential on cross-host hops) because
+// attachment downloads redirect to the storage provider.
+func (a *api) download(ctx context.Context, rawURL string, limit int64) ([]byte, error) {
+ relative := strings.HasPrefix(rawURL, "/") && !strings.HasPrefix(rawURL, "//")
+ target := rawURL
+ if relative {
+ target = a.base + rawURL
+ } else if u, err := url.Parse(rawURL); err != nil || u.Scheme != "https" && !(u.Scheme == "http" && strings.HasPrefix(a.base, "http://")) {
+ return nil, fmt.Errorf("invalid download URL")
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
+ if err != nil {
+ return nil, fmt.Errorf("invalid download URL")
+ }
+ if relative {
+ req.Header.Set("Authorization", "Bearer "+a.token)
+ if a.workspace != "" {
+ req.Header.Set("X-Workspace-ID", a.workspace)
+ }
+ }
+ client := &http.Client{Timeout: 2 * time.Minute, Transport: a.client.Transport}
+ resp, err := client.Do(req)
+ if err != nil {
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ return nil, fmt.Errorf("download transport failed")
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return nil, &apiError{Status: resp.StatusCode}
+ }
+ b, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
+ if err != nil {
+ return nil, fmt.Errorf("read download failed")
+ }
+ if int64(len(b)) > limit {
+ return nil, errTooLarge
+ }
+ return b, nil
+}
+
+var errTooLarge = errors.New("file too large")
+
+// errResponseTooLarge reports a response body larger than api.do reads.
+var errResponseTooLarge = errors.New("API response exceeds 8 MiB")
diff --git a/server/internal/qoderruntime/prompt.go b/server/internal/qoderruntime/prompt.go
index ba1ef5b2cb..1c17c615c1 100644
--- a/server/internal/qoderruntime/prompt.go
+++ b/server/internal/qoderruntime/prompt.go
@@ -38,8 +38,7 @@ func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {
}
r.AgentID = binding.AgentID
if quickCreate {
- // The created issue would carry the attachments, and the run on it
- // would then fail below; refuse before creating anything.
+ // Quick-create attachments stay blocked, matching the modal and API guards.
if len(t.QuickCreateAttachmentIDs) > 0 {
return nil, fmt.Errorf("attachments are not supported by the Qoder bridge; create the issue without them")
}
@@ -136,14 +135,11 @@ func (b *Bridge) issuePrompt(ctx context.Context, t *claimedTask, r *run, p *str
var issue struct {
Title string `json:"title"`
Description string `json:"description"`
- Attachments []json.RawMessage `json:"attachments"`
+ Attachments []issueAttachment `json:"attachments"`
}
if err := taskAPI.call(ctx, http.MethodGet, "/api/issues/"+url.PathEscape(t.IssueID), nil, &issue); err != nil {
return fmt.Errorf("read issue: %w", err)
}
- if len(issue.Attachments) > 0 {
- return fmt.Errorf("issue attachments are not supported by the Qoder bridge")
- }
p.WriteString("Complete the following Multica issue in your Qoder environment. Return a final summary including code changes, tests and branch/PR/MR links when available. This bridge does not expose a local Multica daemon.\n")
if t.PriorSessionID != "" {
r.PriorSessionID = t.PriorSessionID
@@ -153,7 +149,7 @@ func (b *Bridge) issuePrompt(ctx context.Context, t *claimedTask, r *run, p *str
if t.IssueIdentifier != "" {
fmt.Fprintf(p, "\nWhen you change code, push a new branch named %s (never the default branch), open a pull request whose title starts with \"%s: \", and put the pull request link in your final summary. Multica links the pull request to this issue through that identifier.\n", BranchName(t.IssueIdentifier, issue.Title), t.IssueIdentifier)
}
- return nil
+ return b.attachIssueFiles(ctx, &taskAPI, issue.Attachments, r, p)
}
// Repository is a GitHub repository and optional branch mounted into a session.
diff --git a/server/internal/qoderruntime/state.go b/server/internal/qoderruntime/state.go
index 8e83d9863e..f0d63aeca7 100644
--- a/server/internal/qoderruntime/state.go
+++ b/server/internal/qoderruntime/state.go
@@ -35,14 +35,18 @@ type run struct {
SessionID string `json:"session_id,omitempty"`
Prompt string `json:"prompt,omitempty"`
Resources []map[string]any `json:"resources,omitempty"`
- Phase string `json:"phase"`
- Cursor string `json:"cursor,omitempty"`
- Seq int `json:"seq"`
- Started bool `json:"started"`
- Output string `json:"output,omitempty"`
- Failure string `json:"failure,omitempty"`
- Outcome string `json:"outcome,omitempty"`
- QuickCreate *quickCreate `json:"quick_create,omitempty"`
+ // Files are issue attachments uploaded to Qoder Files; a session that
+ // lacks them cannot be continued. Images go into the task message.
+ Files []map[string]any `json:"files,omitempty"`
+ Images []map[string]string `json:"images,omitempty"`
+ Phase string `json:"phase"`
+ Cursor string `json:"cursor,omitempty"`
+ Seq int `json:"seq"`
+ Started bool `json:"started"`
+ Output string `json:"output,omitempty"`
+ Failure string `json:"failure,omitempty"`
+ Outcome string `json:"outcome,omitempty"`
+ QuickCreate *quickCreate `json:"quick_create,omitempty"`
}
func save(path string, j *journal) error {