Skip to content

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

Go

MUL-8570: feat(qoder): attach files a chat agent delivers to its reply (#9899)

Xichang(Seacen) Zhaoa899b531f6aa
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdx
index f98cd694a4..13ad513831 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 connexio
Au-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 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.
+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. Dans le chat, les fichiers que l’agent livre avec DeliverArtifacts, jusqu’à 10 Mo chacun, sont joints à sa réponse.
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.mdx
index 2b51681c50..7ffd016390 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 はタスクに自動で紐づきます。
-初期版はタスク実行、チャット、進捗同期、キャンセル、永続化された実行記録からの復旧に対応します。タスクやチャットメッセージに添付したファイルと画像は、PDF や Office 文書も含め、1 ファイル 5 MB までセッションに渡されます。それより大きいファイルは渡されず、エージェントにはファイルがあることだけが伝わります。ローカルディレクトリと Qoder Cloud Agents のエージェントの新規作成は未対応です。詳細は [README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md) を参照してください。
+初期版はタスク実行、チャット、進捗同期、キャンセル、永続化された実行記録からの復旧に対応します。タスクやチャットメッセージに添付したファイルと画像は、PDF や Office 文書も含め、1 ファイル 5 MB までセッションに渡されます。それより大きいファイルは渡されず、エージェントにはファイルがあることだけが伝わります。チャットでエージェントが DeliverArtifacts で渡したファイルは、1 ファイル 10 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.mdx
index 1914453468..a9dc74b5c7 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이 태스크에 자동으로 연결됩니다.
-초기 버전은 태스크 실행, 채팅, 진행 상황 동기화, 취소, 영구 실행 기록을 통한 복구를 지원합니다. 태스크와 채팅 메시지에 첨부한 파일과 이미지는 PDF와 Office 문서를 포함해 파일당 5 MB까지 세션에 전달됩니다. 그보다 큰 파일은 전달되지 않으며, 에이전트에게는 파일이 있다는 사실만 알립니다. 로컬 디렉터리와 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)를 참고하세요. 채팅에서 에이전트가 DeliverArtifacts로 전달한 파일은 파일당 10 MB까지 답장에 첨부됩니다.
## 런타임 오프라인 문제 해결
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index 71c18349e2..99dd686de0 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 repos
Runs 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. 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.
+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. In chat, files the agent delivers with DeliverArtifacts, up to 10 MB each, are attached to its reply.
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.mdx
index 73aa9d2b02..9946abeb83 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 中配置。任务和聊天消息里的附件和图片会交给远端会话,包括 PDF 和 Office 文档,每个文件不超过 5 MB;更大的文件不会传过去,智能体只知道有这些文件。暂不支持本地目录,也不支持从 Multica 创建远端 Qoder Cloud Agents 智能体。运行时页面分别展示远端运行时和电脑。
+首版支持任务运行、聊天、通过智能体创建任务、进度同步、取消和基于持久化记录的恢复。模型、工具和 skill 在 Qoder 中配置。任务和聊天消息里的附件和图片会交给远端会话,包括 PDF 和 Office 文档,每个文件不超过 5 MB;更大的文件不会传过去,智能体只知道有这些文件。聊天中智能体用 DeliverArtifacts 交付的文件(每个不超过 10 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.md
index c16c0ac26a..ec9782b2ea 100644
--- a/server/cmd/qoder-runtime/README.md
+++ b/server/cmd/qoder-runtime/README.md
@@ -120,6 +120,28 @@ GitHub integration links the pull request back to the issue.
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.
+- Files returned in chat: files the agent delivers with `DeliverArtifacts`
+ during a chat turn (up to 10 MB each) are downloaded from Qoder Files and
+ uploaded to Multica with the task credential, which attaches them to the
+ agent's reply. Only files Qoder scopes to the run's session are passed on.
+ Each file transfer gets its own guarded poll, alternating with normal run
+ polling so other runs and heartbeats continue. Transfers do not share the
+ event poll's deadline, and the task status check is limited to 5 seconds.
+ One file is transferred per poll, before the reply is completed, with a
+ 20-second budget per attempt and at most three attempts for reads. Uploads
+ are never automatically replayed: a timeout, 5xx, or unreadable response
+ may mean the file was saved, so the reply asks the user to check its
+ attachments before retrying. A successful upload must return a non-empty
+ attachment ID. Larger files, files of another session, files Qoder does
+ not offer for download, files Multica refuses, and files not yet attached
+ when the bridge restarts are logged and skipped. Delivery notices name
+ files not attached or whose delivery could not be confirmed; the reply
+ still completes. Notices survive journal reloads and completion retries.
+ Notices use the direct chat reader's profile language (English, simplified
+ or traditional Chinese, Japanese, Korean, or French). IM rooms use the
+ channel's default language, including WeCom's deployment setting. Missing
+ locale metadata defaults to English; task credentials are never persisted.
+ Issue runs do not return delivered files.
- 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
@@ -154,7 +176,7 @@ GitHub integration links the pull request back to the issue.
This is a PoC for issue runs and chat turns. Squad coordination, local
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 Qoder
+files delivered by issue runs and billing/usage conversion are not implemented. Set up a Qoder
Agent that can execute autonomously with its configured tools. `requires_action`
ends the Multica run as failed with the stop reason; approvals are not granted
implicitly.
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index fd0d8147db..3cc07663f3 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -551,6 +551,7 @@ type AgentTaskResponse struct {
ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Makes the agent channel-aware (read history from the channel, not Multica)
ChatChannelDeliversFiles bool `json:"chat_channel_delivers_files,omitempty"` // server capability: THIS deployment can put a file the agent produced into THIS conversation — the adapter goes back for the bound attachment AND object storage exists to go back to. Absent/false on a server predating it, which is the safe reading: the agent is told to describe its file in words. Never inferred daemon-side from chat_channel_type; see handler.Handler.channelDeliversFiles
ChatType string `json:"chat_type,omitempty"` // channel_chat_session_binding.chat_type — "group" for a shared room, "p2p" for a 1:1 with the bot. Lets the per-turn prompt tell the agent who else can read its replies; empty for a web-only chat
+ ChatNoticeLocale string `json:"chat_notice_locale,omitempty"` // locale for bridge-generated delivery notices; optional and ignored by installed daemons
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`
ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index ed3dddc13e..20317a2b1a 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -3654,6 +3654,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
return resp, deliveredCommentIDs, issueSnapshot, agentSkillCount, builtinSkillCount,
h.rejectClaimSourceLoad(r.Context(), task, deliveryErr, "channel task delivery", uuidToString(task.ID))
}
+ resp.ChatNoticeLocale = h.qoderChatNoticeLocale(r.Context(), runtime, *task, cs, resp.ChatChannelType, resp.ChatType)
// A web chat can opt into the same durable project context as an
// issue-bound task.
projectCtx, projectErr := h.resolveClaimProjectContext(r.Context(), cs.ProjectID, cs.WorkspaceID)
diff --git a/server/internal/handler/qoder_reply_locale.go b/server/internal/handler/qoder_reply_locale.go
new file mode 100644
index 0000000000..6316537729
--- /dev/null
+++ b/server/internal/handler/qoder_reply_locale.go
@@ -0,0 +1,54 @@
+package handler
+
+import (
+ "context"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/integrations/wecom"
+ "github.com/multica-ai/multica/server/internal/qoderruntime"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type chatNoticeUserLookup interface {
+ GetUser(context.Context, pgtype.UUID) (db.User, error)
+}
+
+func (h *Handler) qoderChatNoticeLocale(ctx context.Context, runtime db.AgentRuntime, task db.AgentTaskQueue, session db.ChatSession, channelType, chatType string) string {
+ if runtime.Provider != qoderruntime.Provider {
+ return ""
+ }
+ // A cosmetic lookup cannot hold up a task claim. Never use the runtime
+ // owner's profile to decide what the chat's reader should see.
+ ctx, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+ reader := task.InitiatorUserID
+ if !reader.Valid {
+ reader = session.CreatorID
+ }
+ return chatNoticeLocale(ctx, h.Queries, reader, channelType, chatType)
+}
+
+func chatNoticeLocale(ctx context.Context, q chatNoticeUserLookup, reader pgtype.UUID, channelType, chatType string) string {
+ // A room has no personal profile. Match the channel adapters' existing
+ // defaults; WeCom's room language is explicitly configurable at deployment.
+ fallback := "en"
+ switch channelType {
+ case "wecom":
+ fallback = string(wecom.DeploymentLocale())
+ case "lark", "dingtalk":
+ fallback = "zh-Hans"
+ }
+ if channelType != "" && chatType != "p2p" {
+ return fallback
+ }
+ if q != nil && reader.Valid {
+ if user, err := q.GetUser(ctx, reader); err == nil {
+ if locale := strings.TrimSpace(user.Language.String); locale != "" {
+ return locale
+ }
+ }
+ }
+ return fallback
+}
diff --git a/server/internal/handler/qoder_reply_locale_test.go b/server/internal/handler/qoder_reply_locale_test.go
new file mode 100644
index 0000000000..78e747d8e0
--- /dev/null
+++ b/server/internal/handler/qoder_reply_locale_test.go
@@ -0,0 +1,73 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/integrations/wecom"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type noticeUserLookup struct {
+ language string
+ err error
+ reads []pgtype.UUID
+}
+
+func (q *noticeUserLookup) GetUser(_ context.Context, id pgtype.UUID) (db.User, error) {
+ q.reads = append(q.reads, id)
+ return db.User{Language: pgtype.Text{String: q.language, Valid: q.language != ""}}, q.err
+}
+
+func TestChatNoticeLocaleFollowsDestination(t *testing.T) {
+ previous := wecom.DeploymentLocale()
+ t.Cleanup(func() { wecom.SetDeploymentLocale(string(previous)) })
+ wecom.SetDeploymentLocale("en")
+ reader := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
+ for _, tc := range []struct {
+ name, channel, chatType, language, want string
+ missing, lookupError, reads bool
+ }{
+ {name: "Chinese web reader", language: "zh-Hans", want: "zh-Hans", reads: true},
+ {name: "traditional Chinese IM reader", channel: "wecom", chatType: "p2p", language: "zh-Hant", want: "zh-Hant", reads: true},
+ {name: "French IM reader", channel: "slack", chatType: "p2p", language: "fr", want: "fr", reads: true},
+ {name: "WeCom room ignores personal profile", channel: "wecom", chatType: "group", language: "zh-Hans", want: "en"},
+ {name: "unknown WeCom audience", channel: "wecom", language: "zh-Hans", want: "en"},
+ {name: "Lark room", channel: "lark", chatType: "group", language: "en", want: "zh-Hans"},
+ {name: "DingTalk room", channel: "dingtalk", chatType: "group", language: "en", want: "zh-Hans"},
+ {name: "Slack room", channel: "slack", chatType: "group", language: "zh-Hans", want: "en"},
+ {name: "unset profile", want: "en", reads: true},
+ {name: "missing reader", missing: true, want: "en"},
+ {name: "lookup failure", language: "zh-Hans", lookupError: true, want: "en", reads: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ q := &noticeUserLookup{language: tc.language}
+ if tc.lookupError {
+ q.err = errors.New("profile unavailable")
+ }
+ id := reader
+ if tc.missing {
+ id = pgtype.UUID{}
+ }
+ if got := chatNoticeLocale(context.Background(), q, id, tc.channel, tc.chatType); got != tc.want {
+ t.Fatalf("locale = %q, want %q", got, tc.want)
+ }
+ if tc.reads {
+ if len(q.reads) != 1 || q.reads[0] != reader {
+ t.Fatalf("wrong profile used: %v", q.reads)
+ }
+ } else if len(q.reads) != 0 {
+ t.Fatalf("unexpected personal profile read: %v", q.reads)
+ }
+ })
+ }
+}
+
+func TestOtherRuntimesDoNotLoadChatNoticeLocale(t *testing.T) {
+ h := &Handler{}
+ if got := h.qoderChatNoticeLocale(context.Background(), db.AgentRuntime{Provider: "codex"}, db.AgentTaskQueue{}, db.ChatSession{}, "", ""); got != "" {
+ t.Fatalf("non-Qoder locale = %q", got)
+ }
+}
diff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.go
index bd4c85b808..bbbab48348 100644
--- a/server/internal/integrations/wecom/strings.go
+++ b/server/internal/integrations/wecom/strings.go
@@ -94,6 +94,10 @@ func deploymentLocale() Locale {
return DefaultLocale
}
+// DeploymentLocale exposes the room/default notice language to bridges that
+// append their own system copy to a reply before it reaches this adapter.
+func DeploymentLocale() Locale { return deploymentLocale() }
+
// resolveLocale maps a user's profile language onto a supported Locale. The
// profile validates to en / zh-Hans / ko / ja (handler/auth.go), and there are
// two packs: Chinese for zh*, English for everyone who chose anything else —
diff --git a/server/internal/qoderruntime/attachments.go b/server/internal/qoderruntime/attachments.go
index 415fa1f52c..56b084a474 100644
--- a/server/internal/qoderruntime/attachments.go
+++ b/server/internal/qoderruntime/attachments.go
@@ -107,7 +107,7 @@ func (b *Bridge) attachFiles(ctx context.Context, taskAPI *api, heading, mountDi
var file struct {
ID string `json:"id"`
}
- if err := b.qoder.upload(ctx, "/files", name, data, &file); err != nil {
+ if err := b.qoder.upload(ctx, "/files", name, data, nil, &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)")
diff --git a/server/internal/qoderruntime/bridge.go b/server/internal/qoderruntime/bridge.go
index da34bd5bbb..c000f9c865 100644
--- a/server/internal/qoderruntime/bridge.go
+++ b/server/internal/qoderruntime/bridge.go
@@ -53,6 +53,8 @@ type Bridge struct {
path string
log *slog.Logger
turn int
+ replyTurn int
+ replyStep bool
}
func New(cfg Config, log *slog.Logger) (*Bridge, error) {
@@ -232,11 +234,52 @@ func (b *Bridge) taskCall(ctx context.Context, r *run, suffix string, body, out
return b.multica.call(ctx, http.MethodPost, "/api/daemon/tasks/"+url.PathEscape(r.TaskID)+suffix, body, out)
}
-// step advances every active run, then claims new work while capacity remains.
+// step alternates normal polling with one pending file transfer. Each runs
+// under a separate guard and deadline; transfers cannot spend another run's
+// budget, and normal polling and heartbeats still run between transfers.
+func (b *Bridge) step(ctx context.Context) error {
+ if b.replyStep {
+ b.replyStep = false
+ if r := b.nextReplyRun(); r != nil {
+ b.replyTurn++
+ statusCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ err := b.stepRun(statusCtx, r)
+ cancel()
+ if err != nil {
+ return err
+ }
+ // The status check may have removed a cancelled or completed run.
+ for _, active := range b.state.Runs {
+ if active == r {
+ if pending, err := b.attachReplyFile(ctx, r); err != nil || pending {
+ return err
+ }
+ return b.deliver(ctx, r)
+ }
+ }
+ return nil
+ }
+ }
+ err := b.stepRuns(ctx)
+ b.replyStep = b.nextReplyRun() != nil
+ return err
+}
+
+func (b *Bridge) nextReplyRun() *run {
+ for i := range b.state.Runs {
+ r := b.state.Runs[(b.replyTurn+i)%len(b.state.Runs)]
+ if r.Phase == "final" && r.Outcome == "completed" && r.Reply != nil && r.Reply.Handled < len(r.Reply.Delivered) {
+ return r
+ }
+ }
+ return nil
+}
+
+// stepRuns advances every active run, then claims new work while capacity remains.
// One failing run must not stall the others, so errors are collected and the
// first is returned after all runs had their turn. Rotating the starting run
// keeps a slow provider call from starving the same run on every tick.
-func (b *Bridge) step(ctx context.Context) error {
+func (b *Bridge) stepRuns(ctx context.Context) error {
var firstErr error
keep := func(r *run, err error) error {
var diskErr *persistenceError
@@ -643,6 +686,11 @@ func (b *Bridge) deliver(ctx context.Context, r *run) error {
return err
}
}
+ if r.Reply != nil && r.Outcome == "completed" {
+ if r.Reply.Handled < len(r.Reply.Delivered) {
+ return nil
+ }
+ }
if err := b.reportCredits(ctx, r); err != nil {
return err
}
@@ -650,6 +698,9 @@ func (b *Bridge) deliver(ctx context.Context, r *run) error {
suffix := "/complete"
if r.Outcome == "completed" {
body["output"] = r.Output
+ if r.Reply != nil {
+ body["output"] = r.Reply.output(r.Output)
+ }
} else {
suffix = "/fail"
body["error"] = r.Failure
@@ -703,15 +754,19 @@ func (b *Bridge) Check(ctx context.Context) error {
}
func (b *Bridge) guardedStep(ctx context.Context) error {
- ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
- defer cancel()
if b.cfg.BeforeStep != nil {
- release, err := b.cfg.BeforeStep(ctx)
+ acquireCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ release, err := b.cfg.BeforeStep(acquireCtx)
+ cancel()
if err != nil {
return err
}
defer release()
}
+ // The managed guard's 45-second lease starts when acquisition commits.
+ // Give the work its own 30 seconds after acquisition, within that lease.
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
return b.step(ctx)
}
diff --git a/server/internal/qoderruntime/bridge_test.go b/server/internal/qoderruntime/bridge_test.go
index 0d7fe1a2de..2ddce8a8d6 100644
--- a/server/internal/qoderruntime/bridge_test.go
+++ b/server/internal/qoderruntime/bridge_test.go
@@ -96,6 +96,9 @@ type harness struct {
issueGet string
downloads map[string]string
uploads map[string]string
+ qoderFiles map[string]qoderFile
+ replyUploads []replyUpload
+ replyUploadStatus []int
rejectUploads map[string]int
sessionResources []map[string]any
sentContent []map[string]any
@@ -117,7 +120,7 @@ func setup(t *testing.T) *harness {
t.Error("missing workspace")
}
auth := "Bearer multica-secret"
- if strings.HasPrefix(r.URL.Path, "/api/issues") || strings.HasPrefix(r.URL.Path, "/api/attachments/") {
+ if strings.HasPrefix(r.URL.Path, "/api/issues") || strings.HasPrefix(r.URL.Path, "/api/attachments/") || r.URL.Path == "/api/upload-file" {
auth = "Bearer mat_task"
}
if r.Header.Get("Authorization") != auth {
@@ -154,6 +157,21 @@ func setup(t *testing.T) *harness {
return
}
io.WriteString(w, body)
+ case r.URL.Path == "/api/upload-file" && r.Method == http.MethodPost:
+ if len(h.replyUploadStatus) > 0 {
+ status := h.replyUploadStatus[0]
+ h.replyUploadStatus = h.replyUploadStatus[1:]
+ w.WriteHeader(status)
+ io.WriteString(w, `{"error":"refused"}`)
+ return
+ }
+ file, header, err := r.FormFile("file")
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, _ := io.ReadAll(file)
+ h.replyUploads = append(h.replyUploads, replyUpload{header.Filename, r.FormValue("task_id"), string(data), h.complete != nil})
+ io.WriteString(w, `{"id":"att-1"}`)
case strings.HasSuffix(r.URL.Path, "/status"):
json.NewEncoder(w).Encode(map[string]string{"status": h.status})
case strings.HasSuffix(r.URL.Path, "/start"):
@@ -203,7 +221,7 @@ func setup(t *testing.T) *harness {
t.Cleanup(m.Close)
q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
- if r.Header.Get("Authorization") != "Bearer qoder-secret" {
+ if r.Header.Get("Authorization") != "Bearer qoder-secret" && !strings.HasPrefix(r.URL.Path, "/blob/") {
t.Error("wrong Qoder credential")
}
switch {
@@ -266,6 +284,32 @@ func setup(t *testing.T) *harness {
}
h.uploads[header.Filename] = string(data)
fmt.Fprintf(w, `{"id":"file_%d","type":"file"}`, len(h.uploads))
+ case strings.HasPrefix(r.URL.Path, "/files/") && r.Method == "GET":
+ id, content := strings.CutSuffix(strings.TrimPrefix(r.URL.Path, "/files/"), "/content")
+ f, ok := h.qoderFiles[id]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ if !content {
+ scope := f.scope
+ if scope == "" {
+ scope = "sess_1"
+ }
+ json.NewEncoder(w).Encode(map[string]any{"id": id, "downloadable": f.downloadable, "scope": map[string]string{"id": scope, "type": "session"}})
+ return
+ }
+ if !f.downloadable {
+ w.WriteHeader(http.StatusForbidden)
+ return
+ }
+ json.NewEncoder(w).Encode(map[string]string{"url": "http://" + r.Host + "/blob/" + id, "expires_at": "2026-11-04T00:00:00Z"})
+ case strings.HasPrefix(r.URL.Path, "/blob/"):
+ // A presigned URL carries no credential.
+ if r.Header.Get("Authorization") != "" {
+ t.Error("credential sent to presigned download")
+ }
+ io.WriteString(w, h.qoderFiles[strings.TrimPrefix(r.URL.Path, "/blob/")].data)
case strings.HasSuffix(r.URL.Path, "/cancel"):
h.cancels++
io.WriteString(w, `{"status":"canceling"}`)
diff --git a/server/internal/qoderruntime/claim.go b/server/internal/qoderruntime/claim.go
index 76bb579562..51203b8fe1 100644
--- a/server/internal/qoderruntime/claim.go
+++ b/server/internal/qoderruntime/claim.go
@@ -13,6 +13,7 @@ type claimedTask struct {
ChatMessage string `json:"chat_message,omitempty"`
ChatAttachments []claimedAttachment `json:"chat_message_attachments,omitempty"`
ChatChannelType string `json:"chat_channel_type,omitempty"`
+ ChatNoticeLocale string `json:"chat_notice_locale,omitempty"`
ChatType string `json:"chat_type,omitempty"`
IsLeaderTask bool `json:"is_leader_task,omitempty"`
AuthToken string `json:"auth_token,omitempty"`
diff --git a/server/internal/qoderruntime/events.go b/server/internal/qoderruntime/events.go
index 478303962f..1f77aa7c88 100644
--- a/server/internal/qoderruntime/events.go
+++ b/server/internal/qoderruntime/events.go
@@ -34,6 +34,10 @@ type event struct {
Credits *float64 `json:"credits"`
} `json:"model_usage"`
TotalCredits *float64 `json:"total_credits"`
+ // Set on agent.artifact_delivered.
+ FileID string `json:"file_id"`
+ OriginalFilename string `json:"original_filename"`
+ Size int64 `json:"size"`
}
func (e event) text() string {
@@ -110,6 +114,10 @@ func (b *Bridge) events(ctx context.Context, r *run) error {
if e.TotalCredits != nil {
r.setSessionCredits(*e.TotalCredits)
}
+ case "agent.artifact_delivered":
+ if r.Reply != nil {
+ r.Reply.add(e)
+ }
case "agent.message":
msg["type"] = "text"
msg["content"] = e.text()
diff --git a/server/internal/qoderruntime/http.go b/server/internal/qoderruntime/http.go
index 32769e8aba..134db8a053 100644
--- a/server/internal/qoderruntime/http.go
+++ b/server/internal/qoderruntime/http.go
@@ -63,8 +63,9 @@ func (a *api) call(ctx context.Context, method, path string, in, out any) error
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 {
+// upload posts one file as multipart/form-data under the "file" field, with
+// its name and any extra form fields.
+func (a *api) upload(ctx context.Context, path, name string, data []byte, fields map[string]string, out any) error {
var body bytes.Buffer
w := multipart.NewWriter(&body)
part, err := w.CreateFormFile("file", name)
@@ -77,6 +78,11 @@ func (a *api) upload(ctx context.Context, path, name string, data []byte, out an
if err := w.WriteField("name", name); err != nil {
return err
}
+ for k, v := range fields {
+ if err := w.WriteField(k, v); err != nil {
+ return err
+ }
+ }
if err := w.Close(); err != nil {
return err
}
diff --git a/server/internal/qoderruntime/prompt.go b/server/internal/qoderruntime/prompt.go
index aa724730c7..d1e1f6ae30 100644
--- a/server/internal/qoderruntime/prompt.go
+++ b/server/internal/qoderruntime/prompt.go
@@ -48,6 +48,8 @@ func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {
if chat {
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))
+ r.Reply = &replyFiles{Locale: t.ChatNoticeLocale, token: t.AuthToken}
+ fmt.Fprintf(&p, "Multica attempts to attach files you deliver with DeliverArtifacts to your reply and adds a delivery notice if a transfer fails or cannot be confirmed. A file over %d MB is not attached; tell the user so instead of saying it was sent.\n", maxReplyFileBytes>>20)
if t.PriorSessionID != "" {
r.PriorSessionID = t.PriorSessionID
p.WriteString("This continues an earlier conversation. If it is not in your context, answer from the message below.\n")
diff --git a/server/internal/qoderruntime/replyfiles.go b/server/internal/qoderruntime/replyfiles.go
new file mode 100644
index 0000000000..5c13294e4b
--- /dev/null
+++ b/server/internal/qoderruntime/replyfiles.go
@@ -0,0 +1,187 @@
+package qoderruntime
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// A delivered file is downloaded from Qoder and uploaded to Multica within one
+// 30-second bridge step, so it is kept small.
+const (
+ maxReplyFileBytes = 10 << 20
+ maxReplyFileAttempts = 3
+ replyFileTimeout = 20 * time.Second
+)
+
+// replyFiles carries the files a chat agent delivers with DeliverArtifacts.
+// They are attached to the reply before the run completes.
+type replyFiles struct {
+ Locale string `json:"locale,omitempty"`
+ Delivered []deliveredFile `json:"delivered,omitempty"`
+ // Handled counts delivered files already attached or skipped, so a retry
+ // does not upload one twice.
+ Handled int `json:"handled,omitempty"`
+ // Attempts counts failed reads of the next file, never upload attempts.
+ Attempts int `json:"attempts,omitempty"`
+ Skipped []replyFileSkip `json:"skipped,omitempty"`
+ // The task credential is never persisted; after a restart the remaining
+ // files are not attached and the run completes without them.
+ token string
+}
+
+type replyFileSkip struct {
+ Name string `json:"name"`
+ Reason string `json:"reason"`
+}
+
+type deliveredFile struct {
+ FileID string `json:"file_id"`
+ Name string `json:"name"`
+ Size int64 `json:"size"`
+}
+
+func (f *replyFiles) add(e event) {
+ for _, d := range f.Delivered {
+ if d.FileID == e.FileID {
+ return
+ }
+ }
+ f.Delivered = append(f.Delivered, deliveredFile{FileID: e.FileID, Name: e.OriginalFilename, Size: e.Size})
+}
+
+// attachReplyFile handles the next delivered file and reports whether any
+// remain, one per step so each transfer has the step to itself. A file that
+// cannot be attached is logged and skipped; the reply is still delivered.
+func (b *Bridge) attachReplyFile(ctx context.Context, r *run) (bool, error) {
+ f := r.Reply
+ if f.Handled >= len(f.Delivered) {
+ return false, nil
+ }
+ if err := ctx.Err(); err != nil {
+ return true, err
+ }
+ d := f.Delivered[f.Handled]
+ transferCtx, cancel := context.WithTimeout(ctx, replyFileTimeout)
+ defer cancel()
+ reason, err := b.transferReplyFile(transferCtx, r, d)
+ if err != nil {
+ if errors.Is(ctx.Err(), context.Canceled) {
+ return true, ctx.Err()
+ }
+ f.Attempts++
+ if f.Attempts < maxReplyFileAttempts {
+ if persistErr := b.persist(); persistErr != nil {
+ return true, persistErr
+ }
+ return true, err
+ }
+ reason = fmt.Sprintf("not attached because the file transfer failed after %d attempts", maxReplyFileAttempts)
+ }
+ if reason != "" {
+ name := d.Name
+ if name == "" {
+ name = d.FileID
+ }
+ f.Skipped = append(f.Skipped, replyFileSkip{Name: name, Reason: reason})
+ b.log.WarnContext(ctx, "Qoder file delivery was not confirmed", "task_id", r.TaskID, "file", name, "reason", reason)
+ }
+ f.Handled++
+ f.Attempts = 0
+ return f.Handled < len(f.Delivered), b.persist()
+}
+
+// transferReplyFile retries only reads. Once an upload is attempted, an
+// ambiguous result must not replay a write without an idempotency key.
+func (b *Bridge) transferReplyFile(ctx context.Context, r *run, d deliveredFile) (string, error) {
+ if r.Reply.token == "" {
+ return "not attached because the bridge restarted during the run", nil
+ }
+ if d.Size > maxReplyFileBytes {
+ return "not attached because it exceeds the 10 MB limit", nil
+ }
+ refused := func(err error) bool {
+ var ae *apiError
+ return errors.As(err, &ae) && (ae.Status == http.StatusNotFound || ae.Status == http.StatusForbidden)
+ }
+ // The token reads every file of the Qoder account, so only a file scoped
+ // to this run's session is passed on, never another chat's.
+ filePath := "/files/" + url.PathEscape(d.FileID)
+ var meta struct {
+ Scope *struct {
+ ID string `json:"id"`
+ } `json:"scope"`
+ }
+ if err := b.qoder.call(ctx, http.MethodGet, filePath, nil, &meta); refused(err) {
+ return "not attached because Qoder did not offer the file for download", nil
+ } else if err != nil {
+ return "", err
+ }
+ if meta.Scope == nil || meta.Scope.ID != r.SessionID {
+ return "not attached because access to the file could not be verified", nil
+ }
+ // Qoder answers 403 for a file it keeps for internal use only.
+ var link struct {
+ URL string `json:"url"`
+ }
+ if err := b.qoder.call(ctx, http.MethodGet, filePath+"/content", nil, &link); refused(err) {
+ return "not attached because Qoder did not offer the file for download", nil
+ } else if err != nil {
+ return "", err
+ }
+ data, err := b.qoder.download(ctx, link.URL, maxReplyFileBytes)
+ if errors.Is(err, errTooLarge) {
+ return "not attached because it exceeds the 10 MB limit", nil
+ } else if definitelyRejected(err) {
+ return "not attached because the download was refused", nil
+ } else if err != nil {
+ return "", err
+ }
+ name := d.Name
+ if name == "" {
+ name = d.FileID
+ }
+ taskAPI := *b.multica
+ taskAPI.token = r.Reply.token
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ var attachment struct {
+ ID string `json:"id"`
+ }
+ if err := taskAPI.upload(ctx, "/api/upload-file", name, data, map[string]string{"task_id": r.TaskID}, &attachment); definitelyRejected(err) {
+ return "not attached because Multica refused the upload", nil
+ } else if err != nil {
+ return "delivery could not be confirmed; check the attachments before retrying", nil
+ }
+ if strings.TrimSpace(attachment.ID) == "" {
+ return "not attached because Multica could not save the attachment", nil
+ }
+ return "", nil
+}
+
+// output leaves the agent's text unchanged and adds persisted delivery notices.
+// Building it without mutating run.Output keeps completion retries identical.
+func (f *replyFiles) output(text string) string {
+ if len(f.Skipped) == 0 {
+ return text
+ }
+ var out strings.Builder
+ out.WriteString(text)
+ if text != "" {
+ out.WriteString("\n\n")
+ }
+ copy := replyFileCopyFor(f.Locale)
+ out.WriteString(copy.title + "\n\n")
+ for _, file := range f.Skipped {
+ // Names are data, not links, markup or additional lines in the notice.
+ name := strings.NewReplacer("\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "[", "\\[", "]", "\\]", "<", "\\<", ">", "\\>").Replace(strconv.Quote(file.Name))
+ fmt.Fprintf(&out, "- %s: %s\n", name, copy.reason(file.Reason))
+ }
+ return strings.TrimSuffix(out.String(), "\n")
+}
diff --git a/server/internal/qoderruntime/replyfiles_strings.go b/server/internal/qoderruntime/replyfiles_strings.go
new file mode 100644
index 0000000000..d825c51ff2
--- /dev/null
+++ b/server/internal/qoderruntime/replyfiles_strings.go
@@ -0,0 +1,105 @@
+package qoderruntime
+
+import "strings"
+
+// Reasons remain readable English in the journal and logs. Localize them only
+// when rendering the reply, including reasons saved by an earlier bridge.
+type replyFileCopy struct {
+ title string
+ reasons map[string]string
+}
+
+func (c replyFileCopy) reason(reason string) string {
+ if text, ok := c.reasons[reason]; ok {
+ return text
+ }
+ return reason + "."
+}
+
+func replyFileCopyFor(locale string) replyFileCopy {
+ locale = strings.ToLower(strings.TrimSpace(locale))
+ if locale == "zh-hant" || strings.HasPrefix(locale, "zh-hant-") || locale == "zh-tw" || locale == "zh-hk" {
+ return replyFileCopies["zh-Hant"]
+ }
+ language, _, _ := strings.Cut(locale, "-")
+ if language == "zh" {
+ return replyFileCopies["zh-Hans"]
+ }
+ if copy, ok := replyFileCopies[language]; ok {
+ return copy
+ }
+ return replyFileCopy{title: "Attachment delivery notice:"}
+}
+
+var replyFileCopies = map[string]replyFileCopy{
+ "zh-Hans": {
+ title: "附件发送提示:",
+ reasons: map[string]string{
+ "not attached because the bridge restarted during the run": "运行服务已重启,文件未附上。",
+ "not attached because it exceeds the 10 MB limit": "文件超过 10 MB,未附上。",
+ "not attached because Qoder did not offer the file for download": "Qoder 未提供可下载文件,未附上。",
+ "not attached because access to the file could not be verified": "无法确认文件访问权限,未附上。",
+ "not attached because the download was refused": "文件下载被拒绝,未附上。",
+ "not attached because Multica refused the upload": "Multica 拒绝了文件上传,未附上。",
+ "delivery could not be confirmed; check the attachments before retrying": "无法确认文件是否已附上,请先检查附件再决定是否重试。",
+ "not attached because Multica could not save the attachment": "Multica 未能保存附件,文件未附上。",
+ "not attached because the file transfer failed after 3 attempts": "文件传输尝试 3 次仍未成功,未附上。",
+ },
+ },
+ "zh-Hant": {
+ title: "附件傳送提示:",
+ reasons: map[string]string{
+ "not attached because the bridge restarted during the run": "執行服務已重新啟動,未附上檔案。",
+ "not attached because it exceeds the 10 MB limit": "檔案超過 10 MB,未附上。",
+ "not attached because Qoder did not offer the file for download": "Qoder 未提供可下載的檔案,未附上。",
+ "not attached because access to the file could not be verified": "無法確認檔案存取權限,未附上。",
+ "not attached because the download was refused": "檔案下載遭拒,未附上。",
+ "not attached because Multica refused the upload": "Multica 拒絕了檔案上傳,未附上。",
+ "delivery could not be confirmed; check the attachments before retrying": "無法確認是否已附上檔案,請先檢查附件再決定是否重試。",
+ "not attached because Multica could not save the attachment": "Multica 未能儲存附件,未附上檔案。",
+ "not attached because the file transfer failed after 3 attempts": "檔案傳輸嘗試 3 次仍未成功,未附上。",
+ },
+ },
+ "ja": {
+ title: "添付ファイルの送信状況:",
+ reasons: map[string]string{
+ "not attached because the bridge restarted during the run": "実行サービスが再起動したため、添付されませんでした。",
+ "not attached because it exceeds the 10 MB limit": "10 MB を超えているため、添付されませんでした。",
+ "not attached because Qoder did not offer the file for download": "Qoder からダウンロードできないため、添付されませんでした。",
+ "not attached because access to the file could not be verified": "ファイルへのアクセス権を確認できなかったため、添付されませんでした。",
+ "not attached because the download was refused": "ダウンロードが拒否されたため、添付されませんでした。",
+ "not attached because Multica refused the upload": "Multica がアップロードを拒否したため、添付されませんでした。",
+ "delivery could not be confirmed; check the attachments before retrying": "添付されたか確認できません。再試行する前に添付ファイルを確認してください。",
+ "not attached because Multica could not save the attachment": "Multica が添付ファイルを保存できませんでした。",
+ "not attached because the file transfer failed after 3 attempts": "3 回試行しても転送できなかったため、添付されませんでした。",
+ },
+ },
+ "ko": {
+ title: "첨부 파일 전송 안내:",
+ reasons: map[string]string{
+ "not attached because the bridge restarted during the run": "실행 서비스가 다시 시작되어 파일이 첨부되지 않았습니다.",
+ "not attached because it exceeds the 10 MB limit": "파일이 10 MB를 초과하여 첨부되지 않았습니다.",
+ "not attached because Qoder did not offer the file for download": "Qoder에서 파일을 다운로드할 수 없어 첨부되지 않았습니다.",
+ "not attached because access to the file could not be verified": "파일 접근 권한을 확인할 수 없어 첨부되지 않았습니다.",
+ "not attached because the download was refused": "다운로드가 거부되어 파일이 첨부되지 않았습니다.",
+ "not attached because Multica refused the upload": "Multica에서 업로드를 거부하여 파일이 첨부되지 않았습니다.",
+ "delivery could not be confirmed; check the attachments before retrying": "파일 첨부 여부를 확인할 수 없습니다. 다시 시도하기 전에 첨부 파일을 확인해 주세요.",
+ "not attached because Multica could not save the attachment": "Multica에서 첨부 파일을 저장하지 못했습니다.",
+ "not attached because the file transfer failed after 3 attempts": "3번 시도 후에도 파일을 전송하지 못해 첨부되지 않았습니다.",
+ },
+ },
+ "fr": {
+ title: "État de l’envoi des pièces jointes :",
+ reasons: map[string]string{
+ "not attached because the bridge restarted during the run": "Le service d’exécution a redémarré ; le fichier n’a pas été joint.",
+ "not attached because it exceeds the 10 MB limit": "Le fichier dépasse 10 Mo et n’a pas été joint.",
+ "not attached because Qoder did not offer the file for download": "Qoder ne permet pas de télécharger ce fichier ; il n’a pas été joint.",
+ "not attached because access to the file could not be verified": "L’accès au fichier n’a pas pu être vérifié ; il n’a pas été joint.",
+ "not attached because the download was refused": "Le téléchargement a été refusé ; le fichier n’a pas été joint.",
+ "not attached because Multica refused the upload": "Multica a refusé le téléversement ; le fichier n’a pas été joint.",
+ "delivery could not be confirmed; check the attachments before retrying": "L’envoi n’a pas pu être confirmé. Vérifiez les pièces jointes avant de réessayer.",
+ "not attached because Multica could not save the attachment": "Multica n’a pas pu enregistrer la pièce jointe.",
+ "not attached because the file transfer failed after 3 attempts": "Le transfert a échoué après 3 tentatives ; le fichier n’a pas été joint.",
+ },
+ },
+}
diff --git a/server/internal/qoderruntime/replyfiles_strings_test.go b/server/internal/qoderruntime/replyfiles_strings_test.go
new file mode 100644
index 0000000000..d3c521fb28
--- /dev/null
+++ b/server/internal/qoderruntime/replyfiles_strings_test.go
@@ -0,0 +1,79 @@
+package qoderruntime
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestReplyFileNoticeLocaleSurvivesClaimAndJournal(t *testing.T) {
+ for _, tc := range []struct{ locale, title string }{
+ {"zh-Hans", "附件发送提示:"},
+ {"zh-Hant", "附件傳送提示:"},
+ {"ja", "添付ファイルの送信状況:"},
+ {"ko", "첨부 파일 전송 안내:"},
+ {"fr", "État de l’envoi des pièces jointes :"},
+ {"en", "Attachment delivery notice:"},
+ {"", "Attachment delivery notice:"},
+ {"unknown", "Attachment delivery notice:"},
+ } {
+ t.Run(tc.locale, func(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ raw, err := json.Marshal(h.task)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &fields); err != nil {
+ t.Fatal(err)
+ }
+ if tc.locale != "" {
+ fields["chat_notice_locale"], _ = json.Marshal(tc.locale)
+ }
+ raw, _ = json.Marshal(fields)
+ var task claimedTask
+ if err := json.Unmarshal(raw, &task); err != nil {
+ t.Fatal(err)
+ }
+ r, err := h.b.prepare(context.Background(), &task)
+ if err != nil {
+ t.Fatal(err)
+ }
+ reasons := []string{
+ "not attached because the bridge restarted during the run",
+ "not attached because it exceeds the 10 MB limit",
+ "not attached because Qoder did not offer the file for download",
+ "not attached because access to the file could not be verified",
+ "not attached because the download was refused",
+ "not attached because Multica refused the upload",
+ "delivery could not be confirmed; check the attachments before retrying",
+ "not attached because Multica could not save the attachment",
+ "not attached because the file transfer failed after 3 attempts",
+ }
+ for _, reason := range reasons {
+ r.Reply.Skipped = append(r.Reply.Skipped, replyFileSkip{Name: "report.pdf", Reason: reason})
+ }
+ raw, err = json.Marshal(r.Reply)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var restored replyFiles
+ if err := json.Unmarshal(raw, &restored); err != nil {
+ t.Fatal(err)
+ }
+ output := restored.output("Report")
+ if !strings.Contains(output, tc.title) || strings.Count(output, "report.pdf") != len(reasons) || restored.token != "" || restored.Locale != tc.locale {
+ t.Fatalf("wrong restored notice: locale=%q token persisted=%v output=%s", restored.Locale, restored.token != "", output)
+ }
+ if tc.locale != "en" && tc.locale != "" && tc.locale != "unknown" {
+ for _, reason := range reasons {
+ if strings.Contains(output, reason) {
+ t.Fatalf("untranslated reason %q in %s", reason, output)
+ }
+ }
+ }
+ })
+ }
+}
diff --git a/server/internal/qoderruntime/replyfiles_test.go b/server/internal/qoderruntime/replyfiles_test.go
new file mode 100644
index 0000000000..0a8aee1abd
--- /dev/null
+++ b/server/internal/qoderruntime/replyfiles_test.go
@@ -0,0 +1,531 @@
+package qoderruntime
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+)
+
+type qoderFile struct {
+ data string
+ downloadable bool
+ // scope is the owning session; empty means the run's own session.
+ scope string
+}
+
+type replyUpload struct {
+ name, taskID, data string
+ afterComplete bool
+}
+
+func chatTask(h *harness) {
+ h.task.IssueID = ""
+ h.task.ChatSessionID = "chat-1"
+ h.task.ChatMessage = "Write the report"
+}
+
+// deliver appends an agent.artifact_delivered event and the file Qoder keeps.
+func (h *harness) deliver(eventID, fileID, name, data string, size int, downloadable bool) {
+ if h.qoderFiles == nil {
+ h.qoderFiles = map[string]qoderFile{}
+ }
+ h.qoderFiles[fileID] = qoderFile{data: data, downloadable: downloadable}
+ h.events = append(h.events, map[string]any{"id": eventID, "type": "agent.artifact_delivered", "file_id": fileID, "original_filename": name, "size": size, "content_type": "application/octet-stream"})
+}
+
+// stepUntilDone steps the bridge until the run is reported, as the ticker would.
+func (h *harness) stepUntilDone(t *testing.T) {
+ t.Helper()
+ for i := 0; i < 40 && h.complete == nil && h.failure == nil; i++ {
+ if err := h.b.step(context.Background()); err != nil {
+ t.Logf("step %d: %v", i, err)
+ }
+ }
+ if h.complete == nil {
+ t.Fatalf("run not completed: %#v", h.failure)
+ }
+}
+
+func TestChatReplyCarriesDeliveredFiles(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(h.prompt, "A file over 10 MB is not attached; tell the user so instead of saying it was sent.") {
+ t.Fatalf("prompt does not describe reply files: %s", h.prompt)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.deliver("evt_a2", "file_data", "data.csv", "a,b\n1,2\n", 8, true)
+ // Delivering the same file again does not attach it twice.
+ h.deliver("evt_a3", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.deliver("evt_a4", "file_internal", "scratch.bin", "x", 1, false)
+ h.deliver("evt_a5", "file_big", "big.zip", "", maxReplyFileBytes+1, true)
+ // A file of another session, such as another chat's upload, is not passed on.
+ h.deliver("evt_a6", "file_other", "other.txt", "secret", 6, true)
+ f := h.qoderFiles["file_other"]
+ f.scope = "sess_other"
+ h.qoderFiles["file_other"] = f
+ h.finish("end_turn")
+ h.stepUntilDone(t)
+ want := []replyUpload{{"report.pdf", "task-1", "%PDF-1.7", false}, {"data.csv", "task-1", "a,b\n1,2\n", false}}
+ if fmt.Sprint(h.replyUploads) != fmt.Sprint(want) {
+ t.Fatalf("reply uploads: %#v", h.replyUploads)
+ }
+ if !strings.Contains(fmt.Sprint(h.complete["output"]), "Tests passed") {
+ t.Fatalf("result: %#v", h.complete)
+ }
+}
+
+func TestReplyFileUploadFailuresAreNotRetried(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.deliver("evt_a2", "file_data", "data.csv", "a,b", 3, true)
+ h.deliver("evt_a3", "file_notes", "notes.txt", "notes", 5, true)
+ // Neither an ambiguous 502 nor a definite 400 replays the upload. The
+ // next file must still arrive, with notices for both skipped files.
+ h.replyUploadStatus = []int{502, 400}
+ h.finish("end_turn")
+ h.stepUntilDone(t)
+ if len(h.replyUploads) != 1 || h.replyUploads[0].name != "notes.txt" {
+ t.Fatalf("reply uploads: %#v", h.replyUploads)
+ }
+ output := fmt.Sprint(h.complete["output"])
+ if !strings.Contains(output, "report.pdf") || !strings.Contains(output, "data.csv") || strings.Contains(output, "notes.txt") {
+ t.Fatalf("wrong failed-file notice: %s", output)
+ }
+}
+
+func TestReplyFilesAfterRestartCompleteWithoutThem(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ j, err := readJournal(h.b.path, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.b.state = j
+ h.finish("end_turn")
+ h.stepUntilDone(t)
+ if len(h.replyUploads) != 0 {
+ t.Fatalf("uploaded without the task credential: %#v", h.replyUploads)
+ }
+ if output := fmt.Sprint(h.complete["output"]); !strings.Contains(output, "report.pdf") || !strings.Contains(output, "not attached") {
+ t.Fatalf("restart did not disclose missing file: %s", output)
+ }
+}
+
+func TestIssueRunDoesNotAttachDeliveredFiles(t *testing.T) {
+ h := setup(t)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(h.prompt, "DeliverArtifacts") {
+ t.Fatalf("issue prompt promises reply files: %s", h.prompt)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.finish("end_turn")
+ h.stepUntilDone(t)
+ if len(h.replyUploads) != 0 {
+ t.Fatalf("issue run uploaded reply files: %#v", h.replyUploads)
+ }
+}
+
+type replyTransport func(*http.Request) (*http.Response, error)
+
+func (f replyTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func replyResponse(r *http.Request, status int, body string) *http.Response {
+ if r.Body != nil {
+ r.Body.Close()
+ }
+ return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), Request: r}
+}
+
+func TestReplyFileReadFailuresAreBounded(t *testing.T) {
+ for _, stage := range []string{"metadata", "content", "download", "timeout"} {
+ t.Run(stage, func(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.deliver("evt_a2", "file_data", "data.csv", "a,b", 3, true)
+ h.finish("end_turn")
+ upstream := h.b.qoder.client.Transport
+ attempts := 0
+ h.b.qoder.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if stage == "metadata" && req.URL.Path == "/files/file_report" || stage == "content" && req.URL.Path == "/files/file_report/content" || (stage == "download" || stage == "timeout") && req.URL.Path == "/blob/file_report" {
+ attempts++
+ if stage == "timeout" {
+ return nil, context.DeadlineExceeded
+ }
+ return replyResponse(req, 502, `{}`), nil
+ }
+ return upstream.RoundTrip(req)
+ })
+ // Enter final first, then expire the execution deadline: attachment
+ // failures need their own bound even after remote execution has ended.
+ _ = h.b.step(context.Background())
+ h.b.state.Runs[0].Deadline = time.Now().Add(-time.Hour)
+ h.stepUntilDone(t)
+ if attempts != 3 || len(h.replyUploads) != 1 || h.replyUploads[0].name != "data.csv" {
+ t.Fatalf("attempts=%d uploads=%v", attempts, h.replyUploads)
+ }
+ if !strings.Contains(fmt.Sprint(h.complete["output"]), "report.pdf") {
+ t.Fatalf("missing failed-file notice: %v", h.complete)
+ }
+ })
+ }
+}
+
+func TestReplyFileLostUploadAcknowledgementIsNotReplayed(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.deliver("evt_a2", "file_data", "data.csv", "a,b", 3, true)
+ h.finish("end_turn")
+ upstream := h.b.multica.client.Transport
+ lost := false
+ h.b.multica.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ resp, err := upstream.RoundTrip(req)
+ if err == nil && req.URL.Path == "/api/upload-file" && !lost {
+ lost = true
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ return nil, errors.New("lost acknowledgement after upload committed")
+ }
+ return resp, err
+ })
+ h.stepUntilDone(t)
+ if len(h.replyUploads) != 2 || h.replyUploads[0].name != "report.pdf" || h.replyUploads[1].name != "data.csv" {
+ t.Fatalf("upload replayed or next file lost: %v", h.replyUploads)
+ }
+ output := fmt.Sprint(h.complete["output"])
+ if !strings.Contains(output, "report.pdf") || !strings.Contains(output, "could not be confirmed") {
+ t.Fatalf("missing ambiguous-delivery notice: %s", output)
+ }
+}
+
+func TestReplyFileUploadRequiresAttachmentID(t *testing.T) {
+ for _, body := range []string{`{"id":"","url":"https://storage.example/report.pdf"}`, `{"id":" "}`, `{}`, `not json`} {
+ t.Run(body, func(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.finish("end_turn")
+ upstream := h.b.multica.client.Transport
+ attempts := 0
+ h.b.multica.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if req.URL.Path == "/api/upload-file" {
+ attempts++
+ return replyResponse(req, 200, body), nil
+ }
+ return upstream.RoundTrip(req)
+ })
+ h.stepUntilDone(t)
+ if attempts != 1 || !strings.Contains(fmt.Sprint(h.complete["output"]), "report.pdf") {
+ t.Fatalf("attempts=%d complete=%v", attempts, h.complete)
+ }
+ })
+ }
+}
+
+func TestReplyFileRefusalAddsDeliveryNotice(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, false)
+ h.finish("end_turn")
+ h.events[len(h.events)-2]["content"] = []map[string]string{{"type": "text", "text": "Report attached."}}
+ h.stepUntilDone(t)
+ output := fmt.Sprint(h.complete["output"])
+ if len(h.replyUploads) != 0 || !strings.HasPrefix(output, "Report attached.") || !strings.Contains(output, "report.pdf") || !strings.Contains(output, "not attached") {
+ t.Fatalf("missing truthful delivery notice: %s", output)
+ }
+}
+
+func TestReplyFileReadRecoversWithoutDeliveryNotice(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.finish("end_turn")
+ upstream := h.b.qoder.client.Transport
+ attempts := 0
+ h.b.qoder.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if req.URL.Path == "/files/file_report" {
+ attempts++
+ if attempts == 1 {
+ return replyResponse(req, 502, `{}`), nil
+ }
+ }
+ return upstream.RoundTrip(req)
+ })
+ h.stepUntilDone(t)
+ if attempts != 2 || len(h.replyUploads) != 1 || h.complete["output"] != "Tests passed. PR: https://example.com/pr/1" {
+ t.Fatalf("read recovery: attempts=%d uploaded=%v complete=%v", attempts, h.replyUploads, h.complete)
+ }
+}
+
+func TestReplyFileTransferSharesOneTimeBudget(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.finish("end_turn")
+ var deadlines []time.Time
+ for _, api := range []*api{h.b.qoder, h.b.multica} {
+ upstream := api.client.Transport
+ api.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if strings.HasPrefix(req.URL.Path, "/files/") || strings.HasPrefix(req.URL.Path, "/blob/") || req.URL.Path == "/api/upload-file" {
+ deadline, ok := req.Context().Deadline()
+ if !ok || time.Until(deadline) > 20*time.Second {
+ t.Errorf("file request has no 20-second budget: %v %v", deadline, ok)
+ }
+ deadlines = append(deadlines, deadline)
+ }
+ return upstream.RoundTrip(req)
+ })
+ }
+ h.stepUntilDone(t)
+ if len(deadlines) != 4 || len(h.replyUploads) != 1 {
+ t.Fatalf("file requests=%d uploads=%v", len(deadlines), h.replyUploads)
+ }
+ for _, deadline := range deadlines {
+ if !deadline.Equal(deadlines[0]) {
+ t.Fatalf("transfer reset its time budget: %v", deadlines)
+ }
+ }
+}
+
+func TestReplyFileParentDeadlineStillBoundsReadRetries(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ r := h.b.state.Runs[0]
+ upstream := h.b.qoder.client.Transport
+ attempts := 0
+ h.b.qoder.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if req.URL.Path == "/files/file_report" {
+ attempts++
+ <-req.Context().Done()
+ return nil, req.Context().Err()
+ }
+ return upstream.RoundTrip(req)
+ })
+ // A busy poll can have less time left than the file's own budget. These
+ // deadlines must count as failed attempts too, or a slow file retries forever.
+ for i := 0; i < 3; i++ {
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ _, err := h.b.attachReplyFile(ctx, r)
+ cancel()
+ if err != nil && !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatal(err)
+ }
+ }
+ if attempts != 3 || r.Reply.Handled != 1 {
+ t.Fatalf("parent deadlines not bounded: attempts=%d handled=%d", attempts, r.Reply.Handled)
+ }
+ h.finish("end_turn")
+ h.stepUntilDone(t)
+ if !strings.Contains(fmt.Sprint(h.complete["output"]), "report.pdf") {
+ t.Fatalf("missing timeout notice: %v", h.complete)
+ }
+}
+
+func TestReplyFileNoticeSurvivesRestartAndCompletionRetry(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, false)
+ h.finish("end_turn")
+ upstream := h.b.multica.client.Transport
+ var first map[string]any
+ h.b.multica.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if strings.HasSuffix(req.URL.Path, "/complete") {
+ if err := json.NewDecoder(req.Body).Decode(&first); err != nil {
+ t.Error(err)
+ }
+ return replyResponse(req, 502, `{}`), nil
+ }
+ return upstream.RoundTrip(req)
+ })
+ // The poll that observes end_turn schedules the transfer for its own step.
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.b.step(context.Background()); err == nil {
+ t.Fatal("completion failure was not injected")
+ }
+ j, err := readJournal(h.b.path, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if j.Runs[0].Reply.token != "" {
+ t.Fatal("task credential persisted")
+ }
+ h.b.state = j
+ h.b.multica.client.Transport = upstream
+ h.stepUntilDone(t)
+ output := fmt.Sprint(h.complete["output"])
+ if output != first["output"] || strings.Count(output, "Attachment delivery notice:") != 1 || !strings.Contains(output, "report.pdf") || len(h.replyUploads) != 0 {
+ t.Fatalf("notice changed after retry/restart: first=%v final=%v uploads=%v", first, h.complete, h.replyUploads)
+ }
+}
+
+func TestReplyFileTransferHasItsOwnGuardedStep(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.finish("end_turn")
+ guards, released, transferGuard := 0, 0, 0
+ h.b.cfg.BeforeStep = func(context.Context) (func(), error) {
+ guards++
+ return func() { released++ }, nil
+ }
+ upstream := h.b.qoder.client.Transport
+ h.b.qoder.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if req.URL.Path == "/files/file_report" {
+ transferGuard = guards
+ if released != 1 {
+ t.Errorf("transfer started before the event poll released its guard: %d", released)
+ }
+ deadline, ok := req.Context().Deadline()
+ if !ok || time.Until(deadline) < 19*time.Second {
+ t.Errorf("transfer did not receive its full budget: %v %v", deadline, ok)
+ }
+ }
+ return upstream.RoundTrip(req)
+ })
+ if err := h.b.guardedStep(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.replyUploads) != 0 {
+ t.Fatal("file transfer shared the event poll's time budget")
+ }
+ if err := h.b.guardedStep(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if transferGuard != 2 || guards != 2 || released != 2 || len(h.replyUploads) != 1 || h.complete == nil {
+ t.Fatalf("guards=%d releases=%d transfer=%d uploads=%v completed=%v", guards, released, transferGuard, h.replyUploads, h.complete)
+ }
+}
+
+func TestReplyFileStepRechecksCancellation(t *testing.T) {
+ h := setup(t)
+ chatTask(h)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.deliver("evt_a1", "file_report", "report.pdf", "%PDF-1.7", 8, true)
+ h.finish("end_turn")
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.status = "cancelled"
+ upstream := h.b.qoder.client.Transport
+ h.b.qoder.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if strings.HasPrefix(req.URL.Path, "/files/") {
+ t.Error("cancelled run started a file transfer")
+ }
+ return upstream.RoundTrip(req)
+ })
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.replyUploads) != 0 || len(h.b.state.Runs) != 0 || h.cancelAcks != 1 {
+ t.Fatalf("cancelled file step: uploads=%v runs=%d acks=%d", h.replyUploads, len(h.b.state.Runs), h.cancelAcks)
+ }
+}
+
+func TestConcurrentReplyFilesUseSeparatePolls(t *testing.T) {
+ a, b := newTask("task-a", ""), newTask("task-b", "")
+ a.IssueID, b.IssueID = "", ""
+ a.ChatSessionID, b.ChatSessionID = "chat-a", "chat-b"
+ a.ChatMessage, b.ChatMessage = "Make a report", "Make another report"
+ h := setupMulti(t, 2, a, b)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ for _, session := range []string{"sess_new_1", "sess_new_2"} {
+ h.sessions[session] = append(h.sessions[session], map[string]any{"id": "artifact_" + session, "type": "agent.artifact_delivered", "file_id": "file_" + session, "original_filename": "report.txt", "size": 3})
+ h.finish(session)
+ }
+ upstreamQoder := h.b.qoder.client.Transport
+ h.b.qoder.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ switch {
+ case strings.HasPrefix(req.URL.Path, "/files/"):
+ id, content := strings.CutSuffix(strings.TrimPrefix(req.URL.Path, "/files/"), "/content")
+ if content {
+ return replyResponse(req, 200, fmt.Sprintf(`{"url":%q}`, h.b.qoder.base+"/blob/"+id)), nil
+ }
+ return replyResponse(req, 200, fmt.Sprintf(`{"scope":{"id":%q}}`, strings.TrimPrefix(id, "file_"))), nil
+ case strings.HasPrefix(req.URL.Path, "/blob/"):
+ return replyResponse(req, 200, "abc"), nil
+ }
+ return upstreamQoder.RoundTrip(req)
+ })
+ upstreamMultica := h.b.multica.client.Transport
+ var uploaded []string
+ h.b.multica.client.Transport = replyTransport(func(req *http.Request) (*http.Response, error) {
+ if req.URL.Path == "/api/upload-file" {
+ if err := req.ParseMultipartForm(1 << 20); err != nil {
+ t.Fatal(err)
+ }
+ defer req.MultipartForm.RemoveAll()
+ uploaded = append(uploaded, req.FormValue("task_id"))
+ return replyResponse(req, 200, `{"id":"attachment"}`), nil
+ }
+ return upstreamMultica.RoundTrip(req)
+ })
+ for poll, wantUploads := range []int{0, 1, 1, 2} {
+ if err := h.b.guardedStep(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(uploaded) != wantUploads {
+ t.Fatalf("poll %d: uploads=%v, want %d; normal polls and transfers must alternate", poll, uploaded, wantUploads)
+ }
+ }
+ if uploaded[0] == uploaded[1] || len(h.completed) != 2 {
+ t.Fatalf("concurrent file replies lost fairness: uploads=%v completed=%v", uploaded, h.completed)
+ }
+}
diff --git a/server/internal/qoderruntime/state.go b/server/internal/qoderruntime/state.go
index b99fde117a..5d9cb270af 100644
--- a/server/internal/qoderruntime/state.go
+++ b/server/internal/qoderruntime/state.go
@@ -52,6 +52,7 @@ type run struct {
Failure string `json:"failure,omitempty"`
Outcome string `json:"outcome,omitempty"`
QuickCreate *quickCreate `json:"quick_create,omitempty"`
+ Reply *replyFiles `json:"reply,omitempty"`
Credits runCredits `json:"credits"`
}