Skip to content

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

Go

fix(taskfailure): retry confirmed Trae response stream disconnects (#11313)

Frezc56aab1c8ee4f
diff --git a/apps/docs/content/docs/tasks.fr.mdx b/apps/docs/content/docs/tasks.fr.mdx
index 1ae69347c4..4637cdfad9 100644
--- a/apps/docs/content/docs/tasks.fr.mdx
+++ b/apps/docs/content/docs/tasks.fr.mdx
@@ -171,6 +171,8 @@ Les valeurs ci-dessous sont celles de la configuration par défaut du serveur.
| `waiting_local_directory` | En attente du répertoire local et de la capacité d'exécution | Pas de délai propre ; reprend le démarrage lorsque le répertoire et un slot d'exécution du daemon sont disponibles |
| `running` | L'outil de codage IA est en cours d'exécution | Pas de durée maximale fixe ; la vivacité suit le signal de vie du runtime — un toutes les 15 secondes ; un runtime qui perd son signal de vie est marqué hors ligne au plus tard en 3 minutes environ. Ses exécutions n'échouent qu'une fois le signal de vie absent au-delà du délai de grâce de reconnexion (`MULTICA_RUNTIME_RECONNECT_GRACE`, 3 heures par défaut) ; un redémarrage du daemon les récupère directement |
+En cas de coupure confirmée du flux Trae CLI avec l’erreur `llm response empty stream`, le daemon doit aussi vérifier qu’aucun appel d’outil n’a démarré pendant ce tour avant de relancer automatiquement l’exécution. Si un appel a démarré ou si l’historique est indisponible, consultez le journal d’exécution avant de relancer manuellement.
+
La relance automatique ne couvre que les défaillances transitoires ci-dessous, et ne s'applique qu'aux exécutions rattachées à une tâche ou à une discussion (hors mode **Exécution seule** des automatisations) :
| Motif d'échec relancé automatiquement | Nombre maximal de tentatives |
diff --git a/apps/docs/content/docs/tasks.ja.mdx b/apps/docs/content/docs/tasks.ja.mdx
index eb7013d622..1606a923f6 100644
--- a/apps/docs/content/docs/tasks.ja.mdx
+++ b/apps/docs/content/docs/tasks.ja.mdx
@@ -171,6 +171,8 @@ multica issue rerun-task <run-id>
| `waiting_local_directory` | ローカルディレクトリと実行容量の待機 | 独自のタイムアウトはなし。ディレクトリとデーモンの実行スロットが利用可能になると起動を再開する |
| `running` | AI コーディングツールが実行中 | 固定の時間上限はなし。生存はランタイムのハートビート(15 秒ごと)で判定し、ハートビートを失ったランタイムは遅くとも約 3 分でオフラインと判定される。その上の実行が失敗するのは、ハートビートの途絶が再接続猶予(`MULTICA_RUNTIME_RECONNECT_GRACE`、デフォルト 3 時間)を超えたとき。デーモンが再起動した場合は、これらの実行を直接回収する |
+Trae CLI で `llm response empty stream` による切断が確認された場合、自動再試行は、そのターンでツール呼び出しが一度も開始されなかったことをデーモンが確認できた場合に限ります。ツール呼び出しが開始された場合や実行履歴を確認できない場合は、手動で再試行する前に実行ログを確認してください。
+
自動リトライは以下の一時的な障害のみを対象とし、タスクまたはチャットに紐づく実行にのみ適用されます(オートパイロットの**実行のみ**モードを除く):
| 自動リトライされる失敗原因 | 実行回数の上限 |
diff --git a/apps/docs/content/docs/tasks.ko.mdx b/apps/docs/content/docs/tasks.ko.mdx
index e86e8a774c..b68ac7f6a7 100644
--- a/apps/docs/content/docs/tasks.ko.mdx
+++ b/apps/docs/content/docs/tasks.ko.mdx
@@ -171,6 +171,8 @@ multica issue rerun-task <run-id>
| `waiting_local_directory` | 로컬 디렉터리와 실행 용량을 기다림 | 별도 timeout이 없으며 디렉터리와 데몬 실행 슬롯을 사용할 수 있을 때 시작 과정을 재개합니다. |
| `running` | AI 코딩 도구 실행 중 | 고정 시간 상한이 없습니다. 런타임 하트비트로 생존을 판단하며 15초마다 하트비트를 보냅니다. 하트비트를 잃은 런타임은 늦어도 약 3분 뒤 오프라인으로 판단됩니다. 그 위의 실행은 하트비트가 재연결 유예(`MULTICA_RUNTIME_RECONNECT_GRACE`, 기본 3시간)를 넘겨 끊긴 뒤에야 실패하며, 데몬이 재시작되면 바로 회수됩니다. |
+Trae CLI에서 `llm response empty stream`으로 인한 연결 끊김이 확인되면, 데몬이 해당 턴에서 도구 호출이 시작되지 않았음을 확인한 경우에만 자동으로 재시도합니다. 도구 호출이 이미 시작되었거나 실행 기록을 확인할 수 없다면 수동으로 재시도하기 전에 실행 로그를 확인하세요.
+
자동 재시도는 아래의 일시적 장애만 포함하며 태스크 또는 대화에 연결된 실행에만 적용됩니다. 오토파일럿의 **실행만** 모드는 제외됩니다.
| 자동 재시도 가능한 실패 원인 | 실행 횟수 상한 |
diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdx
index 37eb90cddf..465dc1a3d0 100644
--- a/apps/docs/content/docs/tasks.mdx
+++ b/apps/docs/content/docs/tasks.mdx
@@ -171,6 +171,8 @@ The numbers below are the server's defaults.
| `waiting_local_directory` | Waiting for the local directory and execution capacity | No timeout of its own; resumes startup once the directory and a daemon execution slot are available |
| `running` | The AI coding tool is executing | No fixed duration cap; liveness follows the runtime heartbeat — one every 15 seconds; a runtime that loses its heartbeat is marked offline within about 3 minutes at the latest. Its runs fail only once the heartbeat has been missing longer than the reconnect grace (`MULTICA_RUNTIME_RECONNECT_GRACE`, 3 hours by default); a daemon restart reclaims them directly |
+For a confirmed Trae CLI `llm response empty stream` disconnect, automatic retry also requires the daemon to verify that no tool call started in the turn. If a tool started or the execution history is unavailable, check the execution log before retrying manually.
+
Automatic retry covers only the transient faults below, and only applies to runs attached to an issue or a chat (excluding the Autopilot **run only** mode):
| Auto-retryable failure reason | Attempt ceiling |
diff --git a/apps/docs/content/docs/tasks.zh-Hant.mdx b/apps/docs/content/docs/tasks.zh-Hant.mdx
index 33b07135cf..c0ad0ccdd8 100644
--- a/apps/docs/content/docs/tasks.zh-Hant.mdx
+++ b/apps/docs/content/docs/tasks.zh-Hant.mdx
@@ -171,6 +171,8 @@ multica issue rerun-task <run-id>
| `waiting_local_directory` | 等待本地目錄和執行容量 | 沒有獨立超時;目錄和守護程序執行槽位可用後繼續啟動 |
| `running` | AI 程式設計工具正在執行 | 不設固定時長上限;以執行時心跳判定存活,心跳每 15 秒一次,失去心跳的執行時最遲約 3 分鐘被判為離線。其上的執行要等心跳缺席超過重連寬限期(`MULTICA_RUNTIME_RECONNECT_GRACE`,預設 3 小時)才失敗;守護程序重啟時,會直接回收這些執行 |
+Trae CLI 確認發生 `llm response empty stream` 斷流時,只有 daemon 能確認本輪從未啟動工具呼叫,才會自動重試。如果工具已經啟動,或無法核實執行歷程,請先查看執行記錄,再決定是否手動重試。
+
自動重試只覆蓋以下臨時故障,且僅適用於掛在任務或對話上的執行(自動化**僅執行**模式除外):
| 可自動重試的失敗原因 | 執行次數上限 |
diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdx
index 3cca3a82f7..ad273d1f00 100644
--- a/apps/docs/content/docs/tasks.zh.mdx
+++ b/apps/docs/content/docs/tasks.zh.mdx
@@ -171,6 +171,8 @@ multica issue rerun-task <run-id>
| `waiting_local_directory` | 等待本地目录和执行容量 | 没有独立超时;目录和守护进程执行槽位可用后继续启动 |
| `running` | AI 编程工具正在执行 | 不设固定时长上限;以运行时心跳判定存活,心跳每 15 秒一次,失去心跳的运行时最迟约 3 分钟被判为离线。其上的运行要等心跳缺席超过重连宽限期(`MULTICA_RUNTIME_RECONNECT_GRACE`,默认 3 小时)才失败;守护进程重启时,会直接回收这些运行 |
+Trae CLI 确认发生 `llm response empty stream` 断流时,只有 daemon 能确认本轮从未启动工具调用,才会自动重试。如果工具已经启动,或无法核实执行历史,请先查看执行日志,再决定是否手动重试。
+
自动重试只覆盖以下临时故障,且仅适用于挂在任务或对话上的运行(自动化**仅运行**模式除外):
| 可自动重试的失败原因 | 执行次数上限 |
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 38ff0fdb93..6130bace9d 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -20,6 +20,7 @@ import (
"github.com/multica-ai/multica/server/pkg/httptransport"
"github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/remotemcp"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
// requestError is returned by postJSON/getJSON when the server responds with an error status.
@@ -817,36 +818,30 @@ func (c *Client) ReportTaskUsageSnapshot(ctx context.Context, taskID string, usa
}
func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) error {
- return c.failTaskWithRetrySchedule(ctx, taskID, errMsg, sessionID, workDir, branchName, failureReason, sessionRolloutMissing, retiredSessionID, durableWorkDir, defaultTerminalRetrySchedule)
-}
-
-func (c *Client) failTaskWithRetrySchedule(ctx context.Context, taskID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string, schedule []time.Duration) error {
- body := map[string]any{"error": errMsg}
- if sessionID != "" {
- body["session_id"] = sessionID
- }
- if workDir != "" {
- body["work_dir"] = workDir
- }
- if durableWorkDir != "" {
- body["durable_work_dir"] = durableWorkDir
- }
- // A failed run can still have delivered a branch: worktree mode commits
- // whatever the agent left before removing the worktree, so partial work
- // survives — but only if its name travels with the failure report.
- if branchName != "" {
- body["branch_name"] = branchName
- }
- if failureReason != "" {
- body["failure_reason"] = failureReason
- }
- if sessionRolloutMissing {
- body["session_rollout_missing"] = true
- }
- if retiredSessionID != "" {
- body["retired_session_id"] = retiredSessionID
- }
- return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), body, nil, schedule)
+ return c.failTaskWithRetrySchedule(ctx, terminalTaskReport{
+ taskID: taskID, errorMessage: errMsg, sessionID: sessionID, workDir: workDir, branchName: branchName,
+ failureReason: failureReason, sessionRolloutMissing: sessionRolloutMissing, retiredSessionID: retiredSessionID, durableWorkDir: durableWorkDir,
+ }, defaultTerminalRetrySchedule)
+}
+
+func (c *Client) failTaskWithRetrySchedule(ctx context.Context, report terminalTaskReport, schedule []time.Duration) error {
+ body := protocol.TaskFailRequest{
+ Error: report.errorMessage,
+ SessionID: report.sessionID,
+ WorkDir: report.workDir,
+ DurableWorkDir: report.durableWorkDir,
+ BranchName: report.branchName,
+ FailureReason: report.failureReason,
+ SessionRolloutMissing: report.sessionRolloutMissing,
+ RetiredSessionID: report.retiredSessionID,
+ NoToolCallsStarted: report.noToolCallsStarted,
+ }
+ // Older servers automatically replay a provider_network failure. Keep the
+ // original server-error label on the wire when the turn cannot be verified.
+ if !body.NoToolCallsStarted && body.FailureReason == taskfailure.ReasonAgentProviderNetwork.String() && taskfailure.IsTraePromptStreamDisconnect(body.Error) {
+ body.FailureReason = taskfailure.ReasonAgentProviderServerError.String()
+ }
+ return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", report.taskID), body, nil, schedule)
}
// PinTaskSession persists the agent's session_id and work_dir on the task
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index e81c389eca..c0fb8bf9a7 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -279,6 +279,8 @@ type terminalTaskReport struct {
workDir string
durableWorkDir string
failureReason string
+ // noToolCallsStarted accompanies a verified Trae prompt failure.
+ noToolCallsStarted bool
// sessionRolloutMissing is true when the daemon withheld this task's Codex
// session because its rollout was not in the store (MUL-5305). The server
// clears the resume pointer and flags the continuity gap for the next claim.
@@ -6804,6 +6806,7 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
// they want to see how far it got.
branchName: result.BranchName,
failureReason: failureReason,
+ noToolCallsStarted: result.NoToolCallsStarted,
sessionRolloutMissing: result.SessionRolloutMissing,
retiredSessionID: result.RetiredSessionID,
}); err != nil {
@@ -6907,7 +6910,7 @@ func (d *Daemon) sendTerminalTaskReport(ctx context.Context, report terminalTask
case terminalTaskReportComplete:
return d.client.completeTaskWithRetrySchedule(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.sessionRolloutMissing, report.retiredSessionID, report.durableWorkDir, schedule)
case terminalTaskReportFail:
- return d.client.failTaskWithRetrySchedule(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.branchName, report.failureReason, report.sessionRolloutMissing, report.retiredSessionID, report.durableWorkDir, schedule)
+ return d.client.failTaskWithRetrySchedule(ctx, report, schedule)
default:
return fmt.Errorf("unsupported terminal task report kind %d", report.kind)
}
@@ -9661,7 +9664,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
}
+ // A later repair or fresh-session turn cannot certify the original prompt.
+ noToolCallsStarted := result.NoToolCallsStarted && tools == 0
if shouldRetryWithFreshSession(result, task.PriorSessionID, tools, provider) {
+ noToolCallsStarted = false
firstResult := result
firstUsage := result.Usage
firstTools := tools
@@ -10015,13 +10021,14 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
errMsg = annotateHermesProviderUnconfigured(errMsg, provider, env.HermesHome != "")
errMsg = annotateCodexRetiredCompaction(errMsg, provider)
return TaskResult{
- Status: "blocked",
- Comment: errMsg,
- SessionID: result.SessionID,
- WorkDir: env.WorkDir,
- EnvRoot: env.RootDir,
- Usage: usageEntries,
- FailureReason: failureReason,
+ Status: "blocked",
+ Comment: errMsg,
+ SessionID: result.SessionID,
+ WorkDir: env.WorkDir,
+ EnvRoot: env.RootDir,
+ Usage: usageEntries,
+ FailureReason: failureReason,
+ NoToolCallsStarted: noToolCallsStarted,
}, nil
}
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 9e69418d43..98549aa781 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -5580,14 +5580,24 @@ func TestReportTaskResult_CancelledParentStillReportsTerminalState(t *testing.T)
// actually do anything (e.g. provider 429 / out-of-credit).
func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {
t.Parallel()
+ const disconnect = `traecli session/prompt failed: session/prompt: Internal error (code=-32603, data={"message":"stream disconnected before completion: llm response empty stream","trae_stream_errors":[{"trae_error_info":{"response_stream_disconnected":{"http_status_code":null}}}]})`
cases := []struct {
- name string
- status string
- comment string
- failureReasonIn string
- wantFailureReason string
+ name string
+ status string
+ comment string
+ failureReasonIn string
+ wantFailureReason string
+ noToolCallsStarted bool
}{
+ {
+ name: "Trae disconnect without proof is safe for an older server",
+ status: "blocked", comment: disconnect, failureReasonIn: "agent_error.provider_network", wantFailureReason: "agent_error.provider_server_error",
+ },
+ {
+ name: "Trae disconnect with verified history",
+ status: "blocked", comment: disconnect, failureReasonIn: "agent_error.provider_network", wantFailureReason: "agent_error.provider_network", noToolCallsStarted: true,
+ },
{
name: "blocked with explicit reason preserves it",
status: "blocked",
@@ -5638,11 +5648,12 @@ func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {
d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}
d.reportTaskResult(context.Background(), "task-x", TaskResult{
- Status: tc.status,
- Comment: tc.comment,
- SessionID: "ses-x",
- WorkDir: "/tmp/x",
- FailureReason: tc.failureReasonIn,
+ Status: tc.status,
+ Comment: tc.comment,
+ SessionID: "ses-x",
+ WorkDir: "/tmp/x",
+ FailureReason: tc.failureReasonIn,
+ NoToolCallsStarted: tc.noToolCallsStarted,
}, slog.Default())
rec.mu.Lock()
@@ -5656,6 +5667,9 @@ func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {
if got := rec.payload["failure_reason"]; got != tc.wantFailureReason {
t.Errorf("failure_reason: got %v, want %q", got, tc.wantFailureReason)
}
+ if got, present := rec.payload["no_tool_calls_started"]; present != tc.noToolCallsStarted || (present && got != true) {
+ t.Errorf("no_tool_calls_started = %v, present %t, want present only for a verified turn", got, present)
+ }
if rec.payload["session_id"] != "ses-x" {
t.Errorf("session_id should be forwarded on failure paths so chat resume keeps working, got %v", rec.payload["session_id"])
}
diff --git a/server/internal/daemon/terminal_report_queue.go b/server/internal/daemon/terminal_report_queue.go
index b548e6b3ff..4b095c29a2 100644
--- a/server/internal/daemon/terminal_report_queue.go
+++ b/server/internal/daemon/terminal_report_queue.go
@@ -55,6 +55,7 @@ type persistedTerminalTaskReport struct {
WorkDir string `json:"work_dir,omitempty"`
DurableWorkDir string `json:"durable_work_dir,omitempty"`
FailureReason string `json:"failure_reason,omitempty"`
+ NoToolCallsStarted bool `json:"no_tool_calls_started,omitempty"`
SessionRolloutMissing bool `json:"session_rollout_missing,omitempty"`
RetiredSessionID string `json:"retired_session_id,omitempty"`
@@ -146,6 +147,7 @@ func persistedTerminalReport(report terminalTaskReport, createdAt time.Time) (pe
WorkDir: report.workDir,
DurableWorkDir: report.durableWorkDir,
FailureReason: report.failureReason,
+ NoToolCallsStarted: report.noToolCallsStarted,
SessionRolloutMissing: report.sessionRolloutMissing,
RetiredSessionID: report.retiredSessionID,
}, nil
@@ -177,6 +179,7 @@ func (record persistedTerminalTaskReport) terminalReport() (terminalTaskReport,
workDir: record.WorkDir,
durableWorkDir: record.DurableWorkDir,
failureReason: record.FailureReason,
+ noToolCallsStarted: record.NoToolCallsStarted,
sessionRolloutMissing: record.SessionRolloutMissing,
retiredSessionID: record.RetiredSessionID,
}, nil
diff --git a/server/internal/daemon/terminal_report_queue_test.go b/server/internal/daemon/terminal_report_queue_test.go
index 6a8b679312..1f63ee56b0 100644
--- a/server/internal/daemon/terminal_report_queue_test.go
+++ b/server/internal/daemon/terminal_report_queue_test.go
@@ -204,11 +204,12 @@ func TestTerminalReportReplaysAfterDaemonRestart(t *testing.T) {
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
report := terminalTaskReport{
- kind: terminalTaskReportFail,
- taskID: "task-restart",
- errorMessage: "provider failed after doing useful work",
- branchName: "agent/partial-work",
- failureReason: "agent_error.process_failure",
+ kind: terminalTaskReportFail,
+ taskID: "task-restart",
+ errorMessage: "stream disconnected before any tool calls",
+ branchName: "agent/partial-work",
+ failureReason: "agent_error.provider_network",
+ noToolCallsStarted: true,
}
beforeRestart := New(cfg, logger)
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 19487fd0cb..920e048841 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -345,9 +345,10 @@ type TaskResult struct {
WorkDir string `json:"work_dir,omitempty"` // working directory used during execution
// DurableWorkDir replaces WorkDir only after a disposable local worktree
// was finalized and its removal was confirmed. Empty keeps WorkDir authoritative.
- DurableWorkDir string `json:"durable_work_dir,omitempty"`
- EnvRoot string `json:"-"` // env root dir for writing GC metadata (not sent to server)
- FailureReason string `json:"-"` // classifier forwarded to FailTask on the blocked path; empty falls back to 'agent_error'
+ DurableWorkDir string `json:"durable_work_dir,omitempty"`
+ EnvRoot string `json:"-"` // env root dir for writing GC metadata (not sent to server)
+ FailureReason string `json:"-"` // classifier forwarded to FailTask on the blocked path; empty falls back to 'agent_error'
+ NoToolCallsStarted bool `json:"-"` // positive evidence from the original prompt
// SessionRolloutMissing is set when the daemon withheld this task's Codex
// session because its rollout was not in the store (MUL-5305). Forwarded to
// the terminal report so the server clears the resume pointer and flags the
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 11d909d7de..a4df9fad17 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -5067,7 +5067,7 @@ func sanitizeTaskCompleteRequest(req *TaskCompleteRequest) {
req.RetiredSessionID = util.SanitizeTextForPostgres(req.RetiredSessionID)
}
-func sanitizeTaskFailRequest(req *TaskFailRequest) {
+func sanitizeTaskFailRequest(req *protocol.TaskFailRequest) {
req.Error = util.SanitizeTextForPostgres(req.Error)
req.SessionID = util.SanitizeTextForPostgres(req.SessionID)
req.WorkDir = util.SanitizeTextForPostgres(req.WorkDir)
@@ -5117,7 +5117,7 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
"task_id", taskID,
"failure_reason", taskfailure.ReasonAgentContextOverflow,
)
- h.failTask(w, r, taskID, workspaceID, TaskFailRequest{
+ h.failTask(w, r, taskID, workspaceID, protocol.TaskFailRequest{
Error: req.Output,
FailureReason: string(taskfailure.ReasonAgentContextOverflow),
SessionID: req.SessionID,
@@ -5842,28 +5842,6 @@ func (h *Handler) GetTaskStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": task.Status})
}
-// FailTask marks a running task as failed.
-type TaskFailRequest struct {
- Error string `json:"error"`
- SessionID string `json:"session_id,omitempty"`
- WorkDir string `json:"work_dir,omitempty"`
- DurableWorkDir string `json:"durable_work_dir,omitempty"`
- FailureReason string `json:"failure_reason,omitempty"`
- // BranchName: a failed run can still have produced a branch — worktree mode
- // commits whatever the agent left before tearing the worktree down. Report
- // it so a partially-successful run is still findable.
- BranchName string `json:"branch_name,omitempty"`
- // SessionRolloutMissing: the daemon withheld this task's Codex session
- // because its rollout was missing (MUL-5305). Clear the resume pointer and
- // flag the continuity gap for the next claim.
- SessionRolloutMissing bool `json:"session_rollout_missing,omitempty"`
- // RetiredSessionID: a session this run proved unresumable and abandoned
- // (GH #6066). Distinct from an empty SessionID, which only means "nothing
- // to report" — this says "never hand this id to a later run". Older
- // daemons omit it, which is exactly the pre-fix behaviour.
- RetiredSessionID string `json:"retired_session_id,omitempty"`
-}
-
func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskId")
@@ -5873,7 +5851,7 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
return
}
- var req TaskFailRequest
+ var req protocol.TaskFailRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
@@ -5891,13 +5869,13 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
// run re-classified at the /complete boundary lands through exactly the same
// transaction, token revocation and runtime wake-up as one the daemon reported
// as failed itself.
-func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, workspaceID string, req TaskFailRequest) {
+func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, workspaceID string, req protocol.TaskFailRequest) {
// MUL-5305: SessionRolloutMissing is applied inside FailTask's terminal
// transaction — forcing session_id NULL (overriding the COALESCE that would
// keep a stale mid-flight pin) and flagging the row in the same commit that
// creates and wakes the auto-retry, so the retry can never claim the withheld
// pointer or miss the continuity gap.
- task, transitioned, err := h.TaskService.FailTaskWithTransition(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.BranchName, req.FailureReason, req.SessionRolloutMissing, req.RetiredSessionID, req.DurableWorkDir)
+ task, transitioned, err := h.TaskService.FailTaskWithTransition(r.Context(), parseUUID(taskID), req)
if err != nil {
// A FailTask error is an infrastructure failure (the terminal
// transaction that also clears the withheld session, writes the
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
index 85d67c9ce7..5dca900d2d 100644
--- a/server/internal/service/retry_deferred_test.go
+++ b/server/internal/service/retry_deferred_test.go
@@ -10,6 +10,7 @@ import (
"github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
// TestCreateRetryTaskFireAtControlsDeferral locks in the SQL half of the
@@ -353,3 +354,40 @@ func TestFailTaskProviderNetworkBudget(t *testing.T) {
})
}
}
+
+func TestFailTaskTraeDisconnectNeedsToolHistory(t *testing.T) {
+ const disconnect = `traecli session/prompt failed: session/prompt: Internal error (code=-32603, data={"message":"stream disconnected before completion: llm response empty stream","trae_stream_errors":[{"trae_error_info":{"response_stream_disconnected":{"http_status_code":null}}}]})`
+ pool := newResolveOriginatorPool(t)
+ ws, user, agentID, _ := seedAttributionFixture(t, pool)
+ fx := testutil.New(pool, ws, user)
+ svc := NewTaskService(db.New(pool), pool, nil, events.New())
+ var runtimeID string
+ fx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)
+ for _, tc := range []struct {
+ name, reason string
+ noToolCallsStarted bool
+ wantChildren int
+ }{
+ {"missing history from an older daemon", "agent_error.provider_server_error", false, 0},
+ {"network classification alone", "agent_error.provider_network", false, 0},
+ {"verified tool-free turn", "agent_error.provider_network", true, 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ issue := fx.Issue(t, tc.name)
+ id := fx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": issue, "status": "running", "max_attempts": 2})
+ t.Cleanup(func() { fx.Exec(t, `DELETE FROM agent_task_queue WHERE parent_task_id = $1`, id) })
+ failed, _, err := svc.FailTaskWithTransition(context.Background(), util.MustParseUUID(id), protocol.TaskFailRequest{
+ Error: disconnect, SessionID: "test-session", FailureReason: tc.reason, NoToolCallsStarted: tc.noToolCallsStarted,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if failed.Status != "failed" || failed.FailureReason.String != "agent_error.provider_network" {
+ t.Fatalf("parent = %s / %s", failed.Status, failed.FailureReason.String)
+ }
+ if got := fx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE parent_task_id = $1`, id); got != tc.wantChildren {
+ t.Fatalf("retry children = %d, want %d", got, tc.wantChildren)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index b45a1ade32..55e3f4d949 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -5349,20 +5349,24 @@ func (s *TaskService) observeChatOutputLocalPath(task db.AgentTaskQueue, body st
// (via classifyPoisonedError, the timeout / runtime classifier, etc.)
// will have their value preserved untouched.
func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) (*db.AgentTaskQueue, error) {
- task, _, err := s.FailTaskWithTransition(ctx, taskID, errMsg, sessionID, workDir, branchName, failureReason, sessionRolloutMissing, retiredSessionID, durableWorkDir)
+ task, _, err := s.FailTaskWithTransition(ctx, taskID, protocol.TaskFailRequest{
+ Error: errMsg, SessionID: sessionID, WorkDir: workDir, BranchName: branchName, FailureReason: failureReason,
+ SessionRolloutMissing: sessionRolloutMissing, RetiredSessionID: retiredSessionID, DurableWorkDir: durableWorkDir,
+ })
return task, err
}
// FailTaskWithTransition is the failure counterpart to
// CompleteTaskWithTransition. The bool is false for an idempotent replay that
// observed an already-terminal row.
-func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) (*db.AgentTaskQueue, bool, error) {
+func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.UUID, report protocol.TaskFailRequest) (*db.AgentTaskQueue, bool, error) {
// Strip bytes PostgreSQL cannot store before anything else reads errMsg, so
// the classifier, the transaction and every downstream consumer see the one
// text we will actually persist (GH #7098). Kept at the service boundary
// rather than only in the /fail handler because failClaimedTaskBeforeLaunch
// reaches FailTask without going through request decoding.
- errMsg = util.SanitizeTextForPostgres(errMsg)
+ errMsg := util.SanitizeTextForPostgres(report.Error)
+ failureReason := report.FailureReason
// MUL-2946: synthesise a refined reason from the error text whenever the
// caller didn't supply one. This is the last write-path guard against
@@ -5397,7 +5401,9 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.
retryFireAt pgtype.Timestamptz
retryMaxAttempts pgtype.Int4
)
- if retryableReasons[failureReason] {
+ // Restoring a Trae session replays history, but the next prompt can still
+ // execute the same tool again. Older reporters cannot certify this turn.
+ if retryableReasons[failureReason] && (report.NoToolCallsStarted || !taskfailure.IsTraePromptStreamDisconnect(errMsg)) {
if parent, perr := s.Queries.GetAgentTask(ctx, taskID); perr != nil {
slog.Warn("fail task auto-retry: load parent failed",
"task_id", util.UUIDToString(taskID), "error", perr)
@@ -5436,16 +5442,16 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.
ID: taskID,
Error: pgtype.Text{String: errMsg, Valid: true},
FailureReason: pgtype.Text{String: failureReason, Valid: failureReason != ""},
- SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
- WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
- DurableWorkDir: pgtype.Text{String: durableWorkDir, Valid: durableWorkDir != ""},
+ SessionID: pgtype.Text{String: report.SessionID, Valid: report.SessionID != ""},
+ WorkDir: pgtype.Text{String: report.WorkDir, Valid: report.WorkDir != ""},
+ DurableWorkDir: pgtype.Text{String: report.DurableWorkDir, Valid: report.DurableWorkDir != ""},
// A failed run can still have produced a branch: worktree mode
// commits whatever the agent left before tearing the worktree down,
// precisely so partial work survives. Dropping the name here would
// leave that commit with no pointer to it.
- BranchName: pgtype.Text{String: branchName, Valid: branchName != ""},
- SessionRolloutMissing: sessionRolloutMissing,
- RetiredSessionID: pgtype.Text{String: retiredSessionID, Valid: retiredSessionID != ""},
+ BranchName: pgtype.Text{String: report.BranchName, Valid: report.BranchName != ""},
+ SessionRolloutMissing: report.SessionRolloutMissing,
+ RetiredSessionID: pgtype.Text{String: report.RetiredSessionID, Valid: report.RetiredSessionID != ""},
})
if errors.Is(err, pgx.ErrNoRows) && failureReason == taskfailure.ReasonProcessCleanupUnconfirmed.String() {
t, err = qtx.FailCancelledTaskProcessCleanup(ctx, db.FailCancelledTaskProcessCleanupParams{ID: taskID, ErrorMessage: errMsg})
@@ -5468,7 +5474,7 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.
// un-upgraded daemon's agent_error.unknown row is caught by the error
// text too.
if t.ChatSessionID.Valid && ResumeUnsafeFailure(failureReason, errMsg) {
- deadSession := sessionID
+ deadSession := report.SessionID
if deadSession == "" {
deadSession = t.SessionID.String
}
@@ -5486,10 +5492,10 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.
// terminal status: the fresh-session retry that replaced it may well
// have succeeded, and the pointer would otherwise still name the
// transcript it retried away from.
- if t.ChatSessionID.Valid && retiredSessionID != "" {
+ if t.ChatSessionID.Valid && report.RetiredSessionID != "" {
if err := qtx.ClearChatSessionSessionIfMatches(ctx, db.ClearChatSessionSessionIfMatchesParams{
ID: t.ChatSessionID,
- SessionID: pgtype.Text{String: retiredSessionID, Valid: true},
+ SessionID: pgtype.Text{String: report.RetiredSessionID, Valid: true},
RuntimeID: t.RuntimeID,
}); err != nil {
return fmt.Errorf("clear retired chat session resume pointer: %w", err)
@@ -5505,13 +5511,13 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.
// when there's no session_id to record, leave runtime_id untouched
// (NULL → COALESCE keeps the existing value).
var sessionRuntimeID pgtype.UUID
- if sessionID != "" {
+ if report.SessionID != "" {
sessionRuntimeID = t.RuntimeID
}
if err := qtx.UpdateChatSessionSession(ctx, db.UpdateChatSessionSessionParams{
ID: t.ChatSessionID,
- SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
- WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ SessionID: pgtype.Text{String: report.SessionID, Valid: report.SessionID != ""},
+ WorkDir: pgtype.Text{String: report.WorkDir, Valid: report.WorkDir != ""},
RuntimeID: sessionRuntimeID,
}); err != nil {
return fmt.Errorf("update chat session resume pointer: %w", err)
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 8953c9548d..54a96862b7 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
@@ -155,7 +156,7 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, transitioned, err := svc.FailTaskWithTransition(context.Background(), taskID, "agent crashed", "", "", "", "", false, "", "")
+ got, transitioned, err := svc.FailTaskWithTransition(context.Background(), taskID, protocol.TaskFailRequest{Error: "agent crashed"})
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 9e910343b9..79b5f49d85 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -329,6 +329,9 @@ type Result struct {
DurationMs int64
SessionID string
Usage map[string]TokenUsage // keyed by model name
+ // NoToolCallsStarted is set only for a failed prompt whose complete native
+ // turn history was observed without a tool call. Missing evidence is false.
+ NoToolCallsStarted bool
// ResumeRejected is positive evidence that this run's requested resume
// was permanently refused — the transcript is gone, the session belongs to
// another provider account, OR the session still exists but its history
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index 26c05b7f33..7820ac3537 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -1388,7 +1388,10 @@ func (c *hermesClient) handleLine(line string) {
if err := json.Unmarshal([]byte(line), &raw); err != nil {
return
}
+ c.handleEnvelope(raw)
+}
+func (c *hermesClient) handleEnvelope(raw map[string]json.RawMessage) {
// Agent → client request: has id + method (no result / error yet).
// Kimi and Hermes both use session/request_permission; if we don't
// answer, the agent blocks for its internal timeout and the task
diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.go
index 22078d5152..e9a4782307 100644
--- a/server/pkg/agent/traecli.go
+++ b/server/pkg/agent/traecli.go
@@ -2,6 +2,7 @@ package agent
import (
"context"
+ "encoding/json"
"fmt"
"io"
"os/exec"
@@ -9,6 +10,8 @@ import (
"sync"
"sync/atomic"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
// traecliBlockedArgs are flags hardcoded by the daemon that must not be
@@ -211,6 +214,8 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
},
}
+ var history traePromptHistory
+ var readerErr error
readerDone := make(chan struct{})
go func() {
defer close(readerDone)
@@ -220,18 +225,30 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
if line == "" {
continue
}
- c.handleLine(line)
+ var frame map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(line), &frame); err != nil {
+ if streamingCurrentTurn.Load() {
+ history.uncertain = true
+ }
+ continue
+ }
+ if streamingCurrentTurn.Load() {
+ history.observe(c.sessionID, frame)
+ }
+ c.handleEnvelope(frame)
}
+ readerErr = scanner.Err()
c.closeAllPending(fmt.Errorf("traecli process exited"))
}()
go func() {
+ wait := sync.OnceValue(cmd.Wait)
defer cancel()
defer msgStream.close()
defer close(resCh)
defer func() {
stdin.Close()
- _ = cmd.Wait()
+ _ = wait()
releaseProcessGroup(cmd)
}()
@@ -404,7 +421,10 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
b.cfg.Logger.Info("traecli finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
stdin.Close()
- cancel()
+ checkHistory := taskfailure.IsTraePromptStreamDisconnect(finalError)
+ if !checkHistory {
+ cancel()
+ }
// traecli ACP may keep the process — and the stdout/stderr pipes — open
// briefly after session/prompt returns. The prompt response is already
@@ -413,15 +433,26 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
// cancellation tears the process down). Draining stderr is what makes
// the provider-error promotion below see a terminal marker.
drainCtx, drainCancel := context.WithTimeout(context.Background(), traecliReaderDrainGrace)
+ stopDrain := context.AfterFunc(drainCtx, cancel)
+ var noToolCallsStarted bool
select {
case <-readerDone:
+ // Closing stdin lets Trae flush late notifications. A forced stop or
+ // incomplete stdout cannot certify the absence of a tool call.
+ noToolCallsStarted = checkHistory && runCtx.Err() == nil && readerErr == nil && history.sawTurn && !history.uncertain
case <-drainCtx.Done():
}
select {
case <-stderrDone:
+ if noToolCallsStarted {
+ noToolCallsStarted = wait() == nil && runCtx.Err() == nil && drainCtx.Err() == nil
+ }
case <-drainCtx.Done():
+ noToolCallsStarted = false
}
+ stopDrain()
drainCancel()
+ cancel()
// Flip the gate before the defer closes msgStream; a late reader that
// already passed the gate is serialized by traecliMessageStream so the
// late send is dropped instead of panicking.
@@ -447,15 +478,69 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: sessionID,
- ResumeRejected: resumeRejected,
- Usage: usageMap,
+ Status: finalStatus,
+ NoToolCallsStarted: noToolCallsStarted,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
}
}()
return &Session{Messages: msgStream.ch, Result: resCh}, nil
}
+
+// The ACP reader owns this state. Observe frames before the lossy display stream,
+// from session/prompt through EOF, so an orphan update or a late tool start counts.
+type traePromptHistory struct {
+ sawTurn bool
+ uncertain bool
+}
+
+func (h *traePromptHistory) observe(sessionID string, frame map[string]json.RawMessage) {
+ if h.uncertain {
+ return
+ }
+ if frame["id"] != nil {
+ // Agent requests (permission, terminal or filesystem access) can start
+ // work even if no matching tool notification reaches the client.
+ if frame["method"] != nil || (frame["result"] == nil && frame["error"] == nil) {
+ h.uncertain = true
+ }
+ return
+ }
+ var method string
+ _ = json.Unmarshal(frame["method"], &method)
+ var params struct {
+ SessionID string `json:"sessionId"`
+ Update json.RawMessage `json:"update"`
+ }
+ if method != "session/update" && method != "session/notification" {
+ h.uncertain = true
+ return
+ }
+ if json.Unmarshal(frame["params"], &params) != nil || params.SessionID != sessionID {
+ h.uncertain = true
+ return
+ }
+ kind, _ := normalizeACPUpdate(params.Update)
+ switch kind {
+ case "agent_message_chunk", "agent_thought_chunk", "usage_update", "turn_end":
+ h.sawTurn = true
+ case "":
+ // These session-level updates carry no evidence about turn execution.
+ var meta struct {
+ Kind string `json:"sessionUpdate"`
+ }
+ _ = json.Unmarshal(params.Update, &meta)
+ if meta.Kind == "available_commands_update" || meta.Kind == "session_info_update" {
+ return
+ }
+ h.uncertain = true
+ default:
+ // Includes tool_call and tool_call_update, even without a start.
+ h.uncertain = true
+ }
+}
diff --git a/server/pkg/agent/traecli_test.go b/server/pkg/agent/traecli_test.go
index c3c3da109f..e4a04ecc4f 100644
--- a/server/pkg/agent/traecli_test.go
+++ b/server/pkg/agent/traecli_test.go
@@ -38,6 +38,7 @@ while IFS= read -r line; do
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_new","models":{"availableModels":[{"modelId":"Doubao-Seed-2.1-Pro","name":"Doubao-Seed-2.1-Pro","description":""},{"modelId":"GLM-5.2","name":"GLM-5.2","description":""}]}}}\n' "$id"
;;
*'"method":"session/load"'*)
+ [ -z "$TRAE_TEST_HISTORY" ] || printf '%s\n' "$TRAE_TEST_HISTORY"
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_loaded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"history replay ignored"}}}}\n'
printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
;;
@@ -53,6 +54,13 @@ while IFS= read -r line; do
esac
;;
*'"method":"session/prompt"'*)
+ if [ -n "$TRAE_TEST_ERROR" ]; then
+ [ -z "$TRAE_TEST_UPDATES" ] || printf '%s\n' "$TRAE_TEST_UPDATES"
+ printf '{"jsonrpc":"2.0","id":%s,"error":%s}\n' "$id" "$TRAE_TEST_ERROR"
+ [ -z "$TRAE_TEST_TRAILING" ] || printf '%s\n' "$TRAE_TEST_TRAILING"
+ [ -z "$TRAE_TEST_HOLD_OPEN" ] || sleep 4
+ exit "${TRAE_TEST_EXIT:-0}"
+ fi
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"thinking about it"}}}}\n'
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call","toolCallId":"tc-1","name":"Shell","status":"pending","parameters":{"command":"echo hi"}}}}\n'
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-1","status":"completed","name":"Shell","output":"hi\\n"}}}\n'
@@ -408,3 +416,66 @@ func TestTraecliDrainsNotificationsAfterPromptResponse(t *testing.T) {
t.Fatalf("late output was truncated: %q", result.Output)
}
}
+
+func TestTraecliDisconnectToolHistory(t *testing.T) {
+ const failure = `{"code":-32603,"message":"Internal error","data":{"message":"stream disconnected before completion: llm response empty stream","trae_stream_errors":[{"trae_error_info":{"response_stream_disconnected":{"http_status_code":null}}}]}}`
+ update := func(body string) string {
+ return `{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":` + body + `}}`
+ }
+ usage := update(`{"sessionUpdate":"usage_update","used":1,"size":32}`)
+ start := update(`{"sessionUpdate":"tool_call","toolCallId":"a","status":"in_progress","title":"Bash"}`)
+ done := update(`{"sessionUpdate":"tool_call_update","toolCallId":"a","status":"completed"}`)
+ fake := filepath.Join(t.TempDir(), "traecli")
+ writeTestExecutable(t, fake, []byte(fakeTraecliACPScript()))
+ for _, tc := range []struct {
+ name, updates, trailing string
+ resume, holdOpen, crash, want bool
+ }{
+ {name: "verified clean turn", updates: usage, want: true},
+ {name: "previous turn tool replay", updates: usage, resume: true, want: true},
+ {name: "unfinished tool", updates: usage + "\n" + start},
+ {name: "completed tool", updates: start + "\n" + done + "\n" + usage},
+ {name: "orphan tool result", updates: usage + "\n" + done},
+ {name: "late tool start", updates: usage, trailing: start},
+ {name: "history absent"},
+ {name: "session metadata only", updates: update(`{"sessionUpdate":"available_commands_update"}`)},
+ {name: "agent request without a tool event", updates: usage + "\n" + `{"jsonrpc":"2.0","id":10,"method":"session/request_permission","params":{}}`},
+ {name: "malformed history", updates: usage + "\n{"},
+ {name: "unrecognised update", updates: usage + "\n" + update(`{"sessionUpdate":"new_activity"}`)},
+ {name: "history for another session", updates: strings.Replace(usage, "ses_new", "another", 1)},
+ {name: "stream never drained", updates: usage, holdOpen: true},
+ {name: "provider crashed after sending the error", updates: usage, crash: true},
+ {name: "tool start after display buffer fills", updates: strings.Repeat(update(`{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"a"}}`)+"\n", 270) + start},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ env := map[string]string{"TRAE_TEST_ERROR": failure, "TRAE_TEST_UPDATES": tc.updates, "TRAE_TEST_TRAILING": tc.trailing}
+ opts := ExecOptions{}
+ if tc.resume {
+ opts.ResumeSessionID = "ses_loaded"
+ env["TRAE_TEST_HISTORY"] = strings.Replace(start, "ses_new", "ses_loaded", 1)
+ env["TRAE_TEST_UPDATES"] = strings.Replace(tc.updates, "ses_new", "ses_loaded", 1)
+ }
+ if tc.crash {
+ env["TRAE_TEST_EXIT"] = "1"
+ }
+ if tc.holdOpen {
+ env["TRAE_TEST_HOLD_OPEN"] = "1"
+ }
+ b, err := New("traecli", Config{ExecutablePath: fake, Env: env, Logger: slog.Default()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ result := <-session.Result
+ if result.Status != "failed" || !strings.Contains(result.Error, "llm response empty stream") || result.NoToolCallsStarted != tc.want {
+ t.Fatalf("status=%q, no tool calls started=%t (want %t), error=%q", result.Status, result.NoToolCallsStarted, tc.want, result.Error)
+ }
+ })
+ }
+}
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 7085276e44..7e639fc329 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -237,6 +237,23 @@ type TaskUsageUpdatedPayload struct {
TaskID string `json:"task_id"`
}
+// TaskFailRequest reports the terminal failure of a daemon task.
+type TaskFailRequest struct {
+ Error string `json:"error"`
+ SessionID string `json:"session_id,omitempty"`
+ WorkDir string `json:"work_dir,omitempty"`
+ DurableWorkDir string `json:"durable_work_dir,omitempty"`
+ FailureReason string `json:"failure_reason,omitempty"`
+ // A worktree can produce a branch even when its task fails.
+ BranchName string `json:"branch_name,omitempty"`
+ // A missing rollout invalidates the withheld session's resume pointer.
+ SessionRolloutMissing bool `json:"session_rollout_missing,omitempty"`
+ // A known unresumable session must also be retired for subsequent tasks.
+ RetiredSessionID string `json:"retired_session_id,omitempty"`
+ // Older daemons and incomplete transcripts leave this proof unset.
+ NoToolCallsStarted bool `json:"no_tool_calls_started,omitempty"`
+}
+
// TaskCompletedPayload is sent from daemon to server when a task finishes.
type TaskCompletedPayload struct {
TaskID string `json:"task_id"`
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index 0738704eb9..6183af6f40 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -131,6 +131,9 @@ func Classify(rawError string) Reason {
return ReasonAgentUnknown
}
lower := strings.ToLower(trimmed)
+ if reason := classifyTraePromptStreamFailure(lower); reason != "" {
+ return reason
+ }
// Cursor's adapter adds event counts to known transport failures. Those
// numbers are not HTTP status codes (event_count=429 is not a rate limit).
// Apply the existing precedence to the provider stderr, keeping real auth
@@ -150,6 +153,10 @@ func Classify(rawError string) Reason {
lower = strings.Join(lines, "\n")
}
+ return classifyAgentErrorText(lower)
+}
+
+func classifyAgentErrorText(lower string) Reason {
switch {
// A concurrent-request rejection can contain both "access token" and HTTP
// 403. Its specific semantic witness must beat the broader context and auth
@@ -770,6 +777,12 @@ func NormalizeDaemonReason(reason, rawError string) Reason {
// flaky provider. Upgrading here makes the retry work the moment the server
// deploys, without waiting on the daemon fleet.
lowerError := strings.ToLower(strings.TrimSpace(rawError))
+ switch Reason(reason) {
+ case "", "agent_error", ReasonAgentUnknown, ReasonAgentProviderServerError:
+ if refined := classifyTraePromptStreamFailure(lowerError); refined != "" {
+ return refined
+ }
+ }
// Normalize before retry eligibility is evaluated so installed daemons
// receive the same bounded, resume-safe recovery as current ones. Retain
// Classify's precedence if a more specific provider failure is present.
diff --git a/server/pkg/taskfailure/trae_stream.go b/server/pkg/taskfailure/trae_stream.go
new file mode 100644
index 0000000000..7c4b4311d3
--- /dev/null
+++ b/server/pkg/taskfailure/trae_stream.go
@@ -0,0 +1,67 @@
+package taskfailure
+
+import (
+ "encoding/json"
+ "strings"
+)
+
+// IsTraePromptStreamDisconnect identifies the provider failure whose replay needs
+// a separate check of tool activity for the failed turn.
+func IsTraePromptStreamDisconnect(raw string) bool {
+ return classifyTraePromptStreamFailure(strings.ToLower(strings.TrimSpace(WithoutCodebuddyProtocolSummary(raw)))) == ReasonAgentProviderNetwork
+}
+
+// Trae wraps prompt errors in the same ACP internal error. Only discard that
+// wrapper when every recorded reconnect points to an interrupted response.
+func classifyTraePromptStreamFailure(lower string) Reason {
+ const prefix = "traecli session/prompt failed: session/prompt: internal error (code=-32603, data="
+ data, ok := strings.CutPrefix(lower, prefix)
+ if !ok {
+ return ""
+ }
+ data, ok = strings.CutSuffix(data, ")")
+ if !ok {
+ return ""
+ }
+
+ const emptyStream = "stream disconnected before completion: llm response empty stream"
+ var payload struct {
+ Message string `json:"message"`
+ Cause json.RawMessage `json:"trae_error_info"`
+ Retries []struct {
+ Cause json.RawMessage `json:"trae_error_info"`
+ Details string `json:"additional_details"`
+ } `json:"trae_stream_errors"`
+ }
+ if json.Unmarshal([]byte(data), &payload) != nil || payload.Message != emptyStream || len(payload.Retries) == 0 {
+ return ""
+ }
+
+ switch string(payload.Cause) {
+ case "", "null", `"other"`:
+ default:
+ if !traeResponseDisconnected(payload.Cause) {
+ return classifyAgentErrorText(lower)
+ }
+ }
+ for _, retry := range payload.Retries {
+ if !traeResponseDisconnected(retry.Cause) || (retry.Details != "" && retry.Details != emptyStream) {
+ return classifyAgentErrorText(lower)
+ }
+ }
+ // Keep the provider data so specific errors retain their normal precedence.
+ return classifyAgentErrorText(payload.Message + " " + data)
+}
+
+func traeResponseDisconnected(cause json.RawMessage) bool {
+ var info struct {
+ Disconnect *struct {
+ HTTPStatus int `json:"http_status_code"`
+ } `json:"response_stream_disconnected"`
+ }
+ if json.Unmarshal(cause, &info) != nil || info.Disconnect == nil {
+ return false
+ }
+ status := info.Disconnect.HTTPStatus
+ return status == 0 || (status >= 200 && status < 300)
+}
diff --git a/server/pkg/taskfailure/trae_stream_test.go b/server/pkg/taskfailure/trae_stream_test.go
new file mode 100644
index 0000000000..4c92523b3e
--- /dev/null
+++ b/server/pkg/taskfailure/trae_stream_test.go
@@ -0,0 +1,63 @@
+package taskfailure
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestTraePromptStreamDisconnect(t *testing.T) {
+ const prefix = "traecli session/prompt failed: session/prompt: Internal error (code=-32603, data="
+ const emptyStream = "stream disconnected before completion: llm response empty stream"
+ const cut = `{"trae_error_info":{"response_stream_disconnected":{"http_status_code":null}}}`
+ const cutAfterOK = `{"trae_error_info":{"response_stream_disconnected":{"http_status_code":200}},"additional_details":"` + emptyStream + `"}`
+ const forbidden = `{"trae_error_info":{"response_stream_disconnected":{"http_status_code":403}}}`
+ const unavailable = `{"trae_error_info":{"response_stream_disconnected":{"http_status_code":503}}}`
+ const limited = `{"trae_error_info":{"response_stream_disconnected":{}},"additional_details":"rate limit exceeded"}`
+ prompt := func(attempts ...string) string {
+ return prefix + `{"message":"` + emptyStream + `","trae_error_info":"other","trae_stream_errors":[` + strings.Join(attempts, ",") + `]})`
+ }
+ confirmed := prompt(cut, cutAfterOK)
+ for _, tc := range []struct {
+ name string
+ raw string
+ want Reason
+ }{
+ {"confirmed disconnects", confirmed, ReasonAgentProviderNetwork},
+ {"typed primary cause", strings.Replace(confirmed, `"other"`, `{"response_stream_disconnected":{}}`, 1), ReasonAgentProviderNetwork},
+ {"different primary cause", strings.Replace(confirmed, `"other"`, `"invalid_request"`, 1), ReasonAgentProviderServerError},
+ {"primary HTTP error", strings.Replace(confirmed, `"other"`, `{"response_stream_disconnected":{"http_status_code":503}}`, 1), ReasonAgentProviderServerError},
+ {"earlier access denial", prompt(forbidden, cut), ReasonAgentProviderAuthOrAccess},
+ {"later HTTP failure", prompt(cut, unavailable), ReasonAgentProviderServerError},
+ {"provider error alongside confirmed disconnects", strings.Replace(confirmed, `"trae_stream_errors"`, `"detail":"HTTP 503","trae_stream_errors"`, 1), ReasonAgentProviderServerError},
+ {"rate limit in reconnect details", prompt(limited, cut), ReasonAgentProviderCapacityOrRateLimit},
+ {"different reconnect cause", prompt(cut, `{"trae_error_info":"other"}`), ReasonAgentProviderServerError},
+ {"different reconnect details", prompt(`{"trae_error_info":{"response_stream_disconnected":{}},"additional_details":"invalid request"}`), ReasonAgentProviderServerError},
+ {"empty reconnect history", prompt(), ReasonAgentProviderServerError},
+ {"missing cause", prompt(`{"additional_details":"` + emptyStream + `"}`), ReasonAgentProviderServerError},
+ {"different prompt error", strings.Replace(confirmed, emptyStream, "invalid request", 1), ReasonAgentProviderServerError},
+ {"wrong RPC code", strings.Replace(confirmed, "-32603", "-32602", 1), ReasonAgentProviderServerError},
+ {"different method", strings.ReplaceAll(confirmed, "session/prompt", "session/load"), ReasonAgentProviderServerError},
+ {"quoted tool output", "tool output: " + confirmed, ReasonAgentProviderServerError},
+ {"malformed data", strings.TrimSuffix(confirmed, "})") + ")", ReasonAgentProviderServerError},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := Classify(tc.raw); got != tc.want {
+ t.Errorf("Classify() = %q, want %q", got, tc.want)
+ }
+ if got := NormalizeDaemonReason(ReasonAgentProviderServerError.String(), tc.raw); got != tc.want {
+ t.Errorf("NormalizeDaemonReason() = %q, want %q", got, tc.want)
+ }
+ })
+ }
+
+ for _, legacy := range []string{"", "agent_error", ReasonAgentUnknown.String()} {
+ if got := NormalizeDaemonReason(legacy, confirmed); got != ReasonAgentProviderNetwork {
+ t.Errorf("NormalizeDaemonReason(%q) = %q, want %q", legacy, got, ReasonAgentProviderNetwork)
+ }
+ }
+ for _, specific := range []Reason{ReasonTimeout, ReasonAgentProviderAuthOrAccess, ReasonAgentProviderCapacityOrRateLimit} {
+ if got := NormalizeDaemonReason(specific.String(), confirmed); got != specific {
+ t.Errorf("NormalizeDaemonReason(%q) = %q, want %q", specific, got, specific)
+ }
+ }
+}