Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8566 feat(qoder): run chat turns with attachments on Qoder Cloud Agents (#9894)
Xichang(Seacen) Zhao1a720ff91b72
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex eb932bef2b..f98cd694a4 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -294,7 +294,7 @@ Sur la page Qoder Cloud Agents, les administrateurs peuvent modifier la connexioAu-delà de la limite de simultanéité, les exécutions attendent dans la file. Une relance sur le même ticket reprend la session Qoder précédente de l'agent si elle est inactive. Un agent peut définir un dépôt par défaut, utilisé quand le projet du ticket n'en a pas. L'agent est invité à pousser une branche nommée d'après l'identifiant du ticket et à préfixer le titre de la pull request avec cet identifiant, afin que la pull request soit liée au ticket.-Cette première version prend en charge l'exécution des tickets, le suivi de progression, l'annulation et la reprise à partir d'un journal d'exécution persistant. Le chat interactif, les répertoires locaux, les pièces jointes et la création d'agents Qoder Cloud Agents distants depuis Multica ne sont pas pris en charge. La page Runtimes sépare les runtimes distants des ordinateurs connectés.+Cette première version prend en charge l'exécution des tickets, le chat, le suivi de progression, l'annulation et la reprise à partir d'un journal d'exécution persistant. Les fichiers et images joints aux tickets et aux messages de chat sont transmis à la session, PDF et documents Office compris, jusqu'à 5 Mo par fichier ; les fichiers plus volumineux ne le sont pas, et l'agent est informé de leur existence. Les répertoires locaux et la création d'agents Qoder Cloud Agents distants depuis Multica ne sont pas pris en charge. La page Runtimes sépare les runtimes distants des ordinateurs connectés.Pour le déploiement du pont autonome et ses limites opérationnelles, consultez le [README du runtime Qoder](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md).diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex 8efa81f4ee..2b51681c50 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -294,7 +294,7 @@ Qoder Cloud Agents は割り当てられたタスクをリモートセッショ同時実行数の上限を超えたタスクはキューで待機します。同じタスクの後続の実行は、前回のセッションがアイドルであればその Qoder セッションを引き継ぎます。エージェントにはデフォルトのリポジトリを設定でき、タスクのプロジェクトにリポジトリがない場合に使われます。エージェントにはタスク ID を含むブランチ名と、タスク ID で始まる PR タイトルを使うよう指示するため、PR はタスクに自動で紐づきます。-初期版はタスク実行、進捗同期、キャンセル、永続化された実行記録からの復旧に対応します。チャット、ローカルディレクトリ、添付ファイル、Qoder Cloud Agents のエージェントの新規作成は未対応です。詳細は [README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md) を参照してください。+初期版はタスク実行、チャット、進捗同期、キャンセル、永続化された実行記録からの復旧に対応します。タスクやチャットメッセージに添付したファイルと画像は、PDF や Office 文書も含め、1 ファイル 5 MB までセッションに渡されます。それより大きいファイルは渡されず、エージェントにはファイルがあることだけが伝わります。ローカルディレクトリと Qoder Cloud Agents のエージェントの新規作成は未対応です。詳細は [README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md) を参照してください。## ランタイムがオフラインのときの確認手順diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex 146c0a5b28..1914453468 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -294,7 +294,7 @@ Qoder Cloud Agents는 할당된 태스크를 원격 세션으로 실행합니다동시 실행 한도를 넘는 태스크는 대기열에서 기다립니다. 같은 태스크의 후속 실행은 이전 세션이 유휴 상태이면 해당 Qoder 세션을 이어서 사용합니다. 에이전트에 기본 저장소를 설정할 수 있으며, 태스크의 프로젝트에 저장소가 없을 때 사용됩니다. 에이전트는 태스크 식별자가 포함된 브랜치 이름과 식별자로 시작하는 PR 제목을 사용하도록 안내받으므로 PR이 태스크에 자동으로 연결됩니다.-초기 버전은 태스크 실행, 진행 상황 동기화, 취소, 영구 실행 기록을 통한 복구를 지원합니다. 채팅, 로컬 디렉터리, 첨부 파일, Qoder Cloud Agents 에이전트 생성은 지원하지 않습니다. 자세한 내용은 [README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md)를 참고하세요.+초기 버전은 태스크 실행, 채팅, 진행 상황 동기화, 취소, 영구 실행 기록을 통한 복구를 지원합니다. 태스크와 채팅 메시지에 첨부한 파일과 이미지는 PDF와 Office 문서를 포함해 파일당 5 MB까지 세션에 전달됩니다. 그보다 큰 파일은 전달되지 않으며, 에이전트에게는 파일이 있다는 사실만 알립니다. 로컬 디렉터리와 Qoder Cloud Agents 에이전트 생성은 지원하지 않습니다. 자세한 내용은 [README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md)를 참고하세요.## 런타임 오프라인 문제 해결diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex fdf17e0f99..71c18349e2 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -294,7 +294,7 @@ On the Qoder Cloud Agents page, administrators can edit the connection and reposRuns beyond the concurrency limit wait in the queue. A follow-up on the same issue continues the agent's previous Qoder session when it is idle. An agent can set a default repository, used when the issue's project has none. The agent is asked to push a branch named after the issue identifier and to prefix the pull request title with it, so the pull request is linked to the issue.-This first version supports issue runs, chat, creating issues with an agent, progress reporting, cancellation, and recovery from a persisted run journal. Configure models, tools, and skills in Qoder. Local directories, attachments, and creating agents in Qoder Cloud Agents from Multica are not supported. The Runtimes page separates remote runtimes from connected computers.+This first version supports issue runs, chat, creating issues with an agent, progress reporting, cancellation, and recovery from a persisted run journal. Configure models, tools, and skills in Qoder. Files and images attached to issues and chat messages reach the session, PDFs and Office documents included, up to 5 MB per file; larger files are not passed on, and the agent is told they exist. Local directories and creating agents in Qoder Cloud Agents from Multica are not supported. The Runtimes page separates remote runtimes from connected computers.For standalone bridge setup and operational limitations, see the [Qoder runtime README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md).diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 168c5743c4..73aa9d2b02 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -295,7 +295,7 @@ Qoder Cloud Agents 通过远端会话执行分配的任务。Multica 服务端超出并发上限的任务会排队等待。同一任务的后续运行会在上一会话空闲时继续使用该 Qoder 会话。智能体可以设置默认仓库,在任务所属项目未绑定仓库时使用。智能体会被要求以任务标识命名分支,并在 PR 标题前加上任务标识,以便 PR 自动关联到任务。-首版支持任务运行、聊天、通过智能体创建任务、进度同步、取消和基于持久化记录的恢复。模型、工具和 skill 在 Qoder 中配置;暂不支持本地目录、附件,也不支持从 Multica 创建远端 Qoder Cloud Agents 智能体。运行时页面分别展示远端运行时和电脑。+首版支持任务运行、聊天、通过智能体创建任务、进度同步、取消和基于持久化记录的恢复。模型、工具和 skill 在 Qoder 中配置。任务和聊天消息里的附件和图片会交给远端会话,包括 PDF 和 Office 文档,每个文件不超过 5 MB;更大的文件不会传过去,智能体只知道有这些文件。暂不支持本地目录,也不支持从 Multica 创建远端 Qoder Cloud Agents 智能体。运行时页面分别展示远端运行时和电脑。独立桥接进程的配置与限制见 [Qoder runtime README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md)。diff --git a/server/cmd/qoder-runtime/README.md b/server/cmd/qoder-runtime/README.mdindex 5e4ab7fbcc..c16c0ac26a 100644--- a/server/cmd/qoder-runtime/README.md+++ b/server/cmd/qoder-runtime/README.md@@ -106,13 +106,20 @@ GitHub integration links the pull request back to the issue.a fresh session starts with the current issue and triggering/coalesced commentcontext, or with the current chat message. Do not send additional messagesdirectly 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+- Issue and chat attachments: PNG, JPEG, WebP and GIF images (at most 8000 pxper 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.+ readable) are sent as base64 image blocks in the task message; use a Qoder+ Agent model with image input. Other files up to 5 MB, PDFs and Office+ documents included, are uploaded through Qoder Files and mounted under+ `/data/attachments/`, a chat message's files under+ `/data/attachments/<run id>/`. Reading a binary format needs a tool for it in+ the Qoder environment. An issue run uploads every issue attachment again, so+ it always starts a fresh session. A chat turn that continues a session mounts+ its files into that session before sending the message, and starts a fresh+ session if Qoder refuses them. Larger files, files Qoder Files rejects,+ images over the limits, and chat attachments deleted before the run are+ listed in the prompt as unavailable; the run does not fail. 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 successfulonly after its user message and `session.status_idle` with `end_turn`, without@@ -145,7 +152,7 @@ GitHub integration links the pull request back to the issue.## Current boundariesThis is a PoC for issue runs and chat turns. Squad coordination, local-directories, chat message attachments, binary non-image issue attachments, arbitrary Git hosts,+directories, 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 QoderAgent that can execute autonomously with its configured tools. `requires_action`diff --git a/server/internal/qoderruntime/attachments.go b/server/internal/qoderruntime/attachments.goindex a8c148d6c7..415fa1f52c 100644--- a/server/internal/qoderruntime/attachments.go+++ b/server/internal/qoderruntime/attachments.go@@ -11,20 +11,24 @@ import (_ "image/gif"_ "image/jpeg"_ "image/png"+ "net/http"+ "net/url""path""strings")-type issueAttachment struct {+type attachment struct {ID string `json:"id"`Filename string `json:"filename"`ContentType string `json:"content_type"`SizeBytes int64 `json:"size_bytes"`DownloadURL string `json:"download_url"`+ // Chat claims only carry IDs and names; resolve metadata before transfer.+ NeedsMetadata bool `json:"-"`}const (- // Qoder's file upload accepts about 5 MB of text.+ // Qoder's file upload accepts about 5 MB per file.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@@ -38,27 +42,12 @@ const (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 {+// attachFiles hands issue or chat attachments to the Qoder session: images are+// sent as image blocks with the task message, and other files are uploaded+// through Qoder Files and mounted under mountDir. Files that cannot be handed+// over are listed in the prompt under heading as unavailable so the agent+// knows they exist.+func (b *Bridge) attachFiles(ctx context.Context, taskAPI *api, heading, mountDir string, attachments []attachment, r *run, p *strings.Builder) error {if len(attachments) == 0 {return nil}@@ -66,6 +55,21 @@ func (b *Bridge) attachIssueFiles(ctx context.Context, taskAPI *api, attachmentsused := map[string]bool{}imageEncoded := 0for _, a := range attachments {+ if a.NeedsMetadata {+ // Proxy download URLs expire after 60 seconds. Fetch each URL only+ // after the preceding attachment's download and upload have finished.+ var current attachment+ err := taskAPI.call(ctx, http.MethodGet, "/api/attachments/"+url.PathEscape(a.ID), nil, ¤t)+ var missing *apiError+ if errors.As(err, &missing) && missing.Status == http.StatusNotFound {+ skipped = append(skipped, attachmentName(a, used)+" (deleted)")+ continue+ }+ if err != nil {+ return fmt.Errorf("read chat attachment %s: %w", a.Filename, err)+ }+ a = current+ }name := attachmentName(a, used)mediaType := strings.ToLower(strings.TrimSpace(strings.Split(a.ContentType, ";")[0]))switch {@@ -91,7 +95,7 @@ func (b *Bridge) attachIssueFiles(ctx context.Context, taskAPI *api, attachmentsimageEncoded += len(encoded)r.Images = append(r.Images, map[string]string{"type": "base64", "media_type": mediaType, "data": encoded})images = append(images, name)- case isTextAttachment(a):+ default:data, err := b.downloadAttachment(ctx, taskAPI, a, maxAttachmentFileBytes)if errors.Is(err, errTooLarge) {skipped = append(skipped, name+" (file too large)")@@ -114,14 +118,12 @@ func (b *Bridge) attachIssueFiles(ctx context.Context, taskAPI *api, attachmentsif file.ID == "" {return fmt.Errorf("Qoder file upload returned no file ID")}- mountPath := attachmentMountDir + name+ mountPath := mountDir + namer.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")+ fmt.Fprintf(p, "\n%s:\n", heading)for _, m := range mounted {fmt.Fprintf(p, "- %s (mounted file)\n", m)}@@ -134,7 +136,16 @@ func (b *Bridge) attachIssueFiles(ctx context.Context, taskAPI *api, attachmentsreturn nil}-func (b *Bridge) downloadAttachment(ctx context.Context, taskAPI *api, a issueAttachment, limit int64) ([]byte, error) {+// chatAttachments defers metadata reads until each attachment is transferred.+func chatAttachments(claimed []claimedAttachment) []attachment {+ out := make([]attachment, 0, len(claimed))+ for _, c := range claimed {+ out = append(out, attachment{ID: c.ID, Filename: c.Filename, NeedsMetadata: true})+ }+ return out+}++func (b *Bridge) downloadAttachment(ctx context.Context, taskAPI *api, a attachment, limit int64) ([]byte, error) {if a.SizeBytes > limit {return nil, errTooLarge}@@ -149,7 +160,7 @@ func (b *Bridge) downloadAttachment(ctx context.Context, taskAPI *api, a issueAt}// attachmentName returns a unique, path-free file name for the mount path.-func attachmentName(a issueAttachment, used map[string]bool) string {+func attachmentName(a attachment, used map[string]bool) string {name := strings.Map(func(r rune) rune {if r == '/' || r == '\\' || r < 0x20 {return '_'diff --git a/server/internal/qoderruntime/attachments_test.go b/server/internal/qoderruntime/attachments_test.gonew file mode 100644index 0000000000..5b72183e72--- /dev/null+++ b/server/internal/qoderruntime/attachments_test.go@@ -0,0 +1,100 @@+package qoderruntime++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strconv"+ "strings"+ "testing"+)++type attachmentTransport func(*http.Request) (*http.Response, error)++func (f attachmentTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func TestChatAttachmentDownloadURLLifetime(t *testing.T) {+ for _, delay := range []string{"none", "download", "upload"} {+ for _, image := range []bool{false, true} {+ t.Run(fmt.Sprintf("slow_%s/image_%t", delay, image), func(t *testing.T) {+ h := setup(t)+ h.task.IssueID = ""+ h.task.ChatSessionID = "chat-1"+ h.task.ChatMessage = "Read both files"+ second := [3]string{"second.txt", "text/plain", "second"}+ if image {+ second = [3]string{"second.png", "image/png", testPNG(t, 4, 4, false)}+ }+ chatAttach(map[string]string{}, h.task, [3]string{"first.txt", "text/plain", "first"}, second)+ var now int64+ var requests []string+ base := h.b.multica.client.Transport+ h.b.multica.client.Transport = attachmentTransport(func(r *http.Request) (*http.Response, error) {+ if !strings.HasPrefix(r.URL.Path, "/api/attachments/") {+ return base.RoundTrip(r)+ }+ if r.Header.Get("Authorization") != "Bearer mat_task" || r.Header.Get("X-Workspace-ID") != workspaceID {+ t.Error("attachment request missing task credential or workspace")+ }+ requests = append(requests, fmt.Sprintf("t=%d %s", now, r.URL.RequestURI()))+ status, body := http.StatusOK, ""+ if strings.HasSuffix(r.URL.Path, "/signed-download") {+ expires, err := strconv.ParseInt(r.URL.Query().Get("exp"), 10, 64)+ if err != nil {+ t.Errorf("invalid expiry: %v", err)+ }+ if now >= expires {+ status = http.StatusForbidden+ } else if strings.Contains(r.URL.Path, "/c0/") {+ // Model a transfer longer than the proxy URL's 60-second TTL+ // without sleeping or changing the bridge's real timeouts.+ if delay == "download" {+ now += 61+ } else if delay == "upload" {+ now += 40+ }+ body = "first"+ } else {+ body = second[2]+ }+ } else {+ id := strings.TrimPrefix(r.URL.Path, "/api/attachments/")+ file := [3]string{"first.txt", "text/plain", "first"}+ if id == "c1" {+ file = second+ }+ meta, err := json.Marshal(attachment{ID: id, Filename: file[0], ContentType: file[1], SizeBytes: int64(len(file[2])), DownloadURL: fmt.Sprintf("/api/attachments/%s/signed-download?exp=%d", id, now+60)})+ if err != nil {+ t.Error(err)+ }+ body = string(meta)+ }+ return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil+ })+ qoderBase := h.b.qoder.client.Transport+ h.b.qoder.client.Transport = attachmentTransport(func(r *http.Request) (*http.Response, error) {+ resp, err := qoderBase.RoundTrip(r)+ if delay == "upload" && r.URL.Path == "/files" {+ now += 25+ }+ return resp, err+ })+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ wantUploads, wantBlocks := 2, 1+ if image {+ wantUploads, wantBlocks = 1, 2+ }+ if h.failure != nil || h.sends != 1 || len(h.uploads) != wantUploads || len(h.sentContent) != wantBlocks {+ t.Fatalf("valid chat files should reach the agent: failure=%v sends=%d uploads=%d content=%v requests=%v", h.failure, h.sends, len(h.uploads), h.sentContent, requests)+ }+ if h.uploads["first.txt"] != "first" || !image && h.uploads["second.txt"] != "second" {+ t.Fatalf("unexpected uploaded content: %v", h.uploads)+ }+ })+ }+ }+}diff --git a/server/internal/qoderruntime/bridge.go b/server/internal/qoderruntime/bridge.goindex b09f4b1b23..da34bd5bbb 100644--- a/server/internal/qoderruntime/bridge.go+++ b/server/internal/qoderruntime/bridge.go@@ -381,7 +381,7 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {}fingerprint := resourceFingerprint(resources)resources = append(resources, r.Files...)- if r.PriorSessionID != "" && len(r.Files) == 0 {+ if r.PriorSessionID != "" && (len(r.Files) == 0 || r.MountFiles) {continued, err := b.continueSession(ctx, r, fingerprint)if err != nil {return err@@ -418,6 +418,33 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {}r.Cursor = latest}+ if r.Phase == "created" && r.Continued {+ // A continued session lacks this message's files; mount them before the+ // message that names them. The cursor is already set, and events before+ // the message are skipped, so the mounts do not read as this turn.+ for r.MountedFiles < len(r.Files) {+ err := b.qoder.call(ctx, http.MethodPost, "/sessions/"+url.PathEscape(r.SessionID)+"/resources", r.Files[r.MountedFiles], nil)+ if rateLimited(err) {+ r.RetryAt = time.Now().Add(30 * time.Second)+ return b.persist()+ }+ if definitelyRejected(err) {+ // Nothing was sent yet; start a fresh session with the files instead.+ r.SessionID, r.PriorSessionID, r.Continued, r.Cursor = "", "", false, ""+ r.Credits = runCredits{}+ r.MountedFiles = 0+ r.Phase = "prepared"+ return b.persist()+ }+ if err != nil {+ return err+ }+ r.MountedFiles+++ if err := b.persist(); err != nil {+ return err+ }+ }+ }if r.Phase == "created" {// Save intent before POST. After an ambiguous response/restart, never resend automatically.r.Phase = "sending"diff --git a/server/internal/qoderruntime/bridge_test.go b/server/internal/qoderruntime/bridge_test.goindex 3e5bd254ec..0d7fe1a2de 100644--- a/server/internal/qoderruntime/bridge_test.go+++ b/server/internal/qoderruntime/bridge_test.go@@ -96,6 +96,7 @@ type harness struct {issueGet stringdownloads map[string]stringuploads map[string]string+ rejectUploads map[string]intsessionResources []map[string]anysentContent []map[string]anyusage []map[string]any@@ -255,6 +256,11 @@ func setup(t *testing.T) *harness {if r.FormValue("name") != header.Filename {t.Error("upload name mismatch")}+ if status := h.rejectUploads[header.Filename]; status != 0 {+ w.WriteHeader(status)+ io.WriteString(w, `{"error":{"type":"invalid_request_error","message":"unsupported file"}}`)+ return+ }if h.uploads == nil {h.uploads = map[string]string{}}@@ -440,10 +446,10 @@ func TestIssueAttachmentsReachSession(t *testing.T) {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 {+ if h.uploads["notes.md"] != "hello" || h.uploads["spec.pdf"] != "%PDF" || h.uploads["notes-2.md"] != "bye" || len(h.uploads) != 3 {t.Fatalf("uploads: %#v", h.uploads)}- want := []string{"file_1 /data/attachments/notes.md", "file_2 /data/attachments/notes-2.md"}+ want := []string{"file_1 /data/attachments/notes.md", "file_2 /data/attachments/spec.pdf", "file_3 /data/attachments/notes-2.md"}var got []stringfor _, res := range h.sessionResources {if res["type"] == "file" {@@ -460,7 +466,7 @@ func TestIssueAttachmentsReachSession(t *testing.T) {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"} {+ for _, s := range []string{"/data/attachments/notes.md (mounted file)", "screen.png (image attached", "/data/attachments/spec.pdf (mounted file)", "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)}@@ -611,18 +617,68 @@ func TestChatAudience(t *testing.T) {}}}-func TestChatAttachmentsFailBeforeExecution(t *testing.T) {++// chatAttach puts files on the chat message the way the claim does: IDs and+// names only, with metadata and content behind /api/attachments. A file with+// no content was deleted before the run read it.+func chatAttach(downloads map[string]string, task *daemon.Task, files ...[3]string) {+ for i, f := range files {+ id := fmt.Sprint("c", i)+ task.ChatMessageAttachments = append(task.ChatMessageAttachments, daemon.ChatAttachmentMeta{ID: id, Filename: f[0], ContentType: f[1]})+ if f[2] == "" {+ continue+ }+ u := "/api/attachments/" + id + "/download"+ meta, _ := json.Marshal(map[string]any{"id": id, "filename": f[0], "content_type": f[1], "size_bytes": len(f[2]), "download_url": u})+ downloads["/api/attachments/"+id] = string(meta)+ downloads[u] = f[2]+ }+}++func TestChatAttachmentsReachSession(t *testing.T) {h := setup(t)h.task.IssueID = ""h.task.ChatSessionID = "chat-1"- h.task.ChatMessageAttachments = []daemon.ChatAttachmentMeta{{ID: "att-1"}}- if err := h.b.step(context.Background()); err != nil {+ h.task.ChatMessage = "What is in these?"+ screen := testPNG(t, 4, 4, false)+ h.downloads = map[string]string{}+ chatAttach(h.downloads, h.task,+ [3]string{"notes.md", "text/markdown", "hello"},+ [3]string{"screen.png", "image/png", screen},+ [3]string{"report.pdf", "application/pdf", "%PDF"},+ [3]string{"setup.exe", "application/octet-stream", "MZ"},+ [3]string{"old.txt", "text/plain", ""})+ h.rejectUploads = map[string]int{"setup.exe": 400}+ 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["report.pdf"] != "%PDF" || len(h.uploads) != 2 {+ t.Fatalf("uploads: %#v", h.uploads)+ }+ if len(h.sessionResources) != 2 || h.sessionResources[0]["mount_path"] != "/data/attachments/task-1/notes.md" || h.sessionResources[1]["mount_path"] != "/data/attachments/task-1/report.pdf" {+ t.Fatalf("mounted resources: %v", h.sessionResources)+ }+ if len(h.sentContent) != 2 || h.sentContent[1]["type"] != "image" {+ t.Fatalf("message content: %#v", h.sentContent)+ }+ for _, s := range []string{"What is in these?", "Message attachments:", "/data/attachments/task-1/notes.md (mounted file)", "screen.png (image attached", "/data/attachments/task-1/report.pdf (mounted file)", "setup.exe (rejected by Qoder Files): not available", "old.txt (deleted): not available"} {+ if !strings.Contains(h.prompt, s) {+ t.Fatalf("prompt missing %q: %s", s, h.prompt)+ }+ }+ h.finish("end_turn")+ if err := h.b.step(ctx); err != nil {t.Fatal(err)}- if h.creates != 0 || !strings.Contains(fmt.Sprint(h.failure["error"]), "attachments") {- t.Fatalf("chat attachment ignored: %#v", h.failure)+ if h.complete == nil {+ t.Fatalf("run did not complete: %#v", h.failure)}}+func TestAmbiguousSubmitReconcilesAfterRestart(t *testing.T) {h := setup(t)h.lostSend = truediff --git a/server/internal/qoderruntime/claim.go b/server/internal/qoderruntime/claim.goindex a1bf02a7f5..76bb579562 100644--- a/server/internal/qoderruntime/claim.go+++ b/server/internal/qoderruntime/claim.go@@ -5,32 +5,32 @@ import "encoding/json"// Claim payload fields consumed by the remote bridge. Keep this HTTP boundary// independent of the local daemon implementation and its CLI dependencies.type claimedTask struct {- ID string `json:"id"`- RuntimeID string `json:"runtime_id"`- WorkspaceID string `json:"workspace_id"`- IssueID string `json:"issue_id"`- ChatSessionID string `json:"chat_session_id,omitempty"`- ChatMessage string `json:"chat_message,omitempty"`- ChatAttachments []json.RawMessage `json:"chat_message_attachments,omitempty"`- ChatChannelType string `json:"chat_channel_type,omitempty"`- ChatType string `json:"chat_type,omitempty"`- IsLeaderTask bool `json:"is_leader_task,omitempty"`- AuthToken string `json:"auth_token,omitempty"`- RemoteMCPConnections []json.RawMessage `json:"remote_mcp_connections,omitempty"`- ConnectedApps []json.RawMessage `json:"connected_apps,omitempty"`- PluginHookTools []json.RawMessage `json:"plugin_hook_tools,omitempty"`- Agent *claimedAgent `json:"agent,omitempty"`- PriorSessionID string `json:"prior_session_id,omitempty"`- IssueIdentifier string `json:"issue_identifier,omitempty"`- WorkspaceContext string `json:"workspace_context,omitempty"`- ProjectTitle string `json:"project_title,omitempty"`- ProjectDescription string `json:"project_description,omitempty"`- HandoffNote string `json:"handoff_note,omitempty"`- CoalescedComments []claimedComment `json:"coalesced_comments,omitempty"`- TriggerCommentContent string `json:"trigger_comment_content,omitempty"`- TriggerAuthorName string `json:"trigger_author_name,omitempty"`- ProjectResources []claimedResource `json:"project_resources,omitempty"`- Repos []claimedRepo `json:"repos,omitempty"`+ ID string `json:"id"`+ RuntimeID string `json:"runtime_id"`+ WorkspaceID string `json:"workspace_id"`+ IssueID string `json:"issue_id"`+ ChatSessionID string `json:"chat_session_id,omitempty"`+ ChatMessage string `json:"chat_message,omitempty"`+ ChatAttachments []claimedAttachment `json:"chat_message_attachments,omitempty"`+ ChatChannelType string `json:"chat_channel_type,omitempty"`+ ChatType string `json:"chat_type,omitempty"`+ IsLeaderTask bool `json:"is_leader_task,omitempty"`+ AuthToken string `json:"auth_token,omitempty"`+ RemoteMCPConnections []json.RawMessage `json:"remote_mcp_connections,omitempty"`+ ConnectedApps []json.RawMessage `json:"connected_apps,omitempty"`+ PluginHookTools []json.RawMessage `json:"plugin_hook_tools,omitempty"`+ Agent *claimedAgent `json:"agent,omitempty"`+ PriorSessionID string `json:"prior_session_id,omitempty"`+ IssueIdentifier string `json:"issue_identifier,omitempty"`+ WorkspaceContext string `json:"workspace_context,omitempty"`+ ProjectTitle string `json:"project_title,omitempty"`+ ProjectDescription string `json:"project_description,omitempty"`+ HandoffNote string `json:"handoff_note,omitempty"`+ CoalescedComments []claimedComment `json:"coalesced_comments,omitempty"`+ TriggerCommentContent string `json:"trigger_comment_content,omitempty"`+ TriggerAuthorName string `json:"trigger_author_name,omitempty"`+ ProjectResources []claimedResource `json:"project_resources,omitempty"`+ Repos []claimedRepo `json:"repos,omitempty"`QuickCreatePrompt string `json:"quick_create_prompt,omitempty"`QuickCreatePriority string `json:"quick_create_priority,omitempty"`@@ -56,6 +56,11 @@ type claimedAgent struct {RuntimeConfig json.RawMessage `json:"runtime_config,omitempty"`}+type claimedAttachment struct {+ ID string `json:"id"`+ Filename string `json:"filename"`+}+type claimedSkill struct {ID string `json:"id"`}diff --git a/server/internal/qoderruntime/concurrency_test.go b/server/internal/qoderruntime/concurrency_test.goindex 186c89c644..86d81bbd08 100644--- a/server/internal/qoderruntime/concurrency_test.go+++ b/server/internal/qoderruntime/concurrency_test.go@@ -30,6 +30,13 @@ type multiHarness struct {prompts map[string]stringmetadata map[string]map[string]stringresources map[string][]map[string]any+ issue string+ downloads map[string]string+ uploads int+ mounts map[string][]map[string]any+ mountStatus int+ // calls records attachment mounts and message sends in order.+ calls []string}func newTask(id, prior string) *daemon.Task {@@ -38,7 +45,7 @@ func newTask(id, prior string) *daemon.Task {func setupMulti(t *testing.T, limit int, tasks ...*daemon.Task) *multiHarness {t.Helper()- h := &multiHarness{queue: tasks, status: map[string]string{}, completed: map[string]map[string]any{}, failed: map[string]map[string]any{}, sessions: map[string][]map[string]any{}, sessionStatus: map[string]string{}, prompts: map[string]string{}, metadata: map[string]map[string]string{}, resources: map[string][]map[string]any{}}+ h := &multiHarness{queue: tasks, status: map[string]string{}, completed: map[string]map[string]any{}, failed: map[string]map[string]any{}, sessions: map[string][]map[string]any{}, sessionStatus: map[string]string{}, prompts: map[string]string{}, metadata: map[string]map[string]string{}, resources: map[string][]map[string]any{}, downloads: map[string]string{}, mounts: map[string][]map[string]any{}}taskID := func(path string) string {rest := strings.TrimPrefix(path, "/api/daemon/tasks/")return rest[:strings.Index(rest, "/")]@@ -57,7 +64,18 @@ func setupMulti(t *testing.T, limit int, tasks ...*daemon.Task) *multiHarness {}json.NewEncoder(w).Encode(map[string]any{"task": next})case strings.HasPrefix(r.URL.Path, "/api/issues/"):+ if h.issue != "" {+ io.WriteString(w, h.issue)+ return+ }io.WriteString(w, `{"title":"Fix the login 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[taskID(r.URL.Path)]})case strings.HasSuffix(r.URL.Path, "/start"):@@ -101,7 +119,21 @@ func setupMulti(t *testing.T, limit int, tasks ...*daemon.Task) *multiHarness {h.metadata[id] = req.Metadatah.resources[id] = req.Resourcesfmt.Fprintf(w, `{"id":%q}`, id)+ case r.URL.Path == "/files" && r.Method == http.MethodPost:+ h.uploads+++ fmt.Fprintf(w, `{"id":"file_%d"}`, h.uploads)+ case len(parts) == 3 && parts[2] == "resources" && r.Method == http.MethodPost:+ if h.mountStatus != 0 {+ w.WriteHeader(h.mountStatus)+ return+ }+ var res map[string]any+ json.NewDecoder(r.Body).Decode(&res)+ h.mounts[parts[1]] = append(h.mounts[parts[1]], res)+ h.calls = append(h.calls, "mount "+parts[1])+ io.WriteString(w, `{}`)case len(parts) == 3 && parts[2] == "events" && r.Method == http.MethodPost:+ h.calls = append(h.calls, "send "+parts[1])var req struct {Events []event `json:"events"`}@@ -193,6 +225,75 @@ func TestFollowUpContinuesIdleSession(t *testing.T) {}}+func chatFollowUp(h *multiHarness, files ...[3]string) {+ task := h.queue[0]+ task.IssueID, task.IssueIdentifier = "", ""+ task.ChatSessionID = "chat-1"+ task.ChatMessage = "Read the attached notes"+ chatAttach(h.downloads, task, files...)+ h.sessionStatus["sess_prev"] = "idle"+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint(nil)}+}++// A chat follow-up keeps its conversation: the message's files are mounted+// into the earlier session before the message that names them.+func TestChatFollowUpMountsAttachmentsIntoPriorSession(t *testing.T) {+ h := setupMulti(t, 1, newTask("task-1", "sess_prev"))+ chatFollowUp(h, [3]string{"notes.md", "text/markdown", "hello"}, [3]string{"todo.txt", "text/plain", "ship it"})+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if h.creates != 0 || fmt.Sprint(h.calls) != "[mount sess_prev mount sess_prev send sess_prev]" {+ t.Fatalf("creates=%d calls=%v failed=%v", h.creates, h.calls, h.failed)+ }+ var paths []string+ for _, m := range h.mounts["sess_prev"] {+ paths = append(paths, fmt.Sprint(m["type"], " ", m["file_id"], " ", m["mount_path"]))+ }+ if want := "[file file_1 /data/attachments/task-1/notes.md file file_2 /data/attachments/task-1/todo.txt]"; fmt.Sprint(paths) != want {+ t.Fatalf("mounts: %v", paths)+ }+ if !strings.Contains(h.prompts["sess_prev"], "/data/attachments/task-1/notes.md (mounted file)") {+ t.Fatalf("prompt: %s", h.prompts["sess_prev"])+ }+}++// If the earlier session refuses the files, nothing has been sent yet, so the+// message goes to a fresh session that has them.+func TestChatFollowUpStartsFreshWhenMountIsRejected(t *testing.T) {+ h := setupMulti(t, 1, newTask("task-1", "sess_prev"))+ chatFollowUp(h, [3]string{"notes.md", "text/markdown", "hello"})+ h.mountStatus = http.StatusConflict+ ctx := context.Background()+ for i := 0; i < 2 && len(h.sentTo) == 0; i++ {+ if err := h.b.step(ctx); err != nil {+ t.Fatal(err)+ }+ }+ if h.creates != 1 || fmt.Sprint(h.sentTo) != "[sess_new_1]" || len(h.failed) != 0 {+ t.Fatalf("creates=%d sentTo=%v failed=%v", h.creates, h.sentTo, h.failed)+ }+ if res := h.resources["sess_new_1"]; len(res) != 1 || res[0]["mount_path"] != "/data/attachments/task-1/notes.md" {+ t.Fatalf("fresh session resources: %v", res)+ }+}++// An issue run uploads every issue attachment again, so it still starts a+// fresh session instead of mounting duplicates into the earlier one.+func TestIssueFollowUpWithAttachmentsStartsFreshSession(t *testing.T) {+ h := setupMulti(t, 1, newTask("task-1", "sess_prev"))+ h.sessionStatus["sess_prev"] = "idle"+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint(nil)}+ h.downloads["/api/attachments/a0/download"] = "hello"+ h.issue = `{"title":"Fix","description":"See notes","attachments":[{"id":"a0","filename":"notes.md","content_type":"text/markdown","size_bytes":5,"download_url":"/api/attachments/a0/download"}]}`+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if h.creates != 1 || fmt.Sprint(h.sentTo) != "[sess_new_1]" || len(h.mounts) != 0 {+ t.Fatalf("creates=%d sentTo=%v mounts=%v", h.creates, h.sentTo, h.mounts)+ }+}+func TestFollowUpStartsNewSessionWhenPriorIsUnavailable(t *testing.T) {for name, status := range map[string]string{"busy": "running", "deleted": ""} {t.Run(name, func(t *testing.T) {diff --git a/server/internal/qoderruntime/prompt.go b/server/internal/qoderruntime/prompt.goindex 1c17c615c1..aa724730c7 100644--- a/server/internal/qoderruntime/prompt.go+++ b/server/internal/qoderruntime/prompt.go@@ -46,9 +46,6 @@ func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {}var p strings.Builderif chat {- if len(t.ChatAttachments) > 0 {- return nil, fmt.Errorf("chat attachments are not supported by the Qoder bridge")- }p.WriteString("You are chatting with a user of a Multica workspace. Reply directly to their message; your final message is shown to them as your reply. This bridge does not expose a local Multica daemon.\n")p.WriteString(chatAudience(t.ChatChannelType, t.ChatType))if t.PriorSessionID != "" {@@ -56,6 +53,17 @@ func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {p.WriteString("This continues an earlier conversation. If it is not in your context, answer from the message below.\n")}fmt.Fprintf(&p, "\nRun: %s\n\nUser message:\n%s\n", t.ID, t.ChatMessage)+ if len(t.ChatAttachments) > 0 {+ taskAPI := *b.multica+ taskAPI.token = t.AuthToken+ attachments := chatAttachments(t.ChatAttachments)+ // Each message mounts under its own run, so files with the same+ // name from earlier turns of a continued session stay intact.+ r.MountFiles = true+ if err := b.attachFiles(ctx, &taskAPI, "Message attachments", attachmentMountDir+t.ID+"/", attachments, r, &p); err != nil {+ return nil, err+ }+ }} else if err := b.issuePrompt(ctx, t, r, &p); err != nil {return nil, err}@@ -133,9 +141,9 @@ func (b *Bridge) issuePrompt(ctx context.Context, t *claimedTask, r *run, p *strtaskAPI := *b.multicataskAPI.token = t.AuthTokenvar issue struct {- Title string `json:"title"`- Description string `json:"description"`- Attachments []issueAttachment `json:"attachments"`+ Title string `json:"title"`+ Description string `json:"description"`+ Attachments []attachment `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)@@ -149,7 +157,7 @@ func (b *Bridge) issuePrompt(ctx context.Context, t *claimedTask, r *run, p *strif 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 b.attachIssueFiles(ctx, &taskAPI, issue.Attachments, r, p)+ return b.attachFiles(ctx, &taskAPI, "Issue attachments", attachmentMountDir, 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.goindex ba6a634fb3..b99fde117a 100644--- a/server/internal/qoderruntime/state.go+++ b/server/internal/qoderruntime/state.go@@ -35,19 +35,24 @@ type run struct {SessionID string `json:"session_id,omitempty"`Prompt string `json:"prompt,omitempty"`Resources []map[string]any `json:"resources,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"`- Credits runCredits `json:"credits"`+ // Files are attachments uploaded to Qoder Files. An issue run uploads every+ // issue attachment again, so it never continues a session with them. A+ // chat run carries only its message's files (MountFiles), mounted one by+ // one into a continued session; MountedFiles counts those already mounted.+ // Images go into the task message.+ Files []map[string]any `json:"files,omitempty"`+ MountFiles bool `json:"mount_files,omitempty"`+ MountedFiles int `json:"mounted_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"`+ Credits runCredits `json:"credits"`}func save(path string, j *journal) error {