Skip to content

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

Go

fix(agent): drain trailing ACP notifications in kimi, kiro, qoder, and traecli (#5951)

Otis Cuicee985592e65
diff --git a/server/pkg/agent/grok.go b/server/pkg/agent/grok.go
index 0199a1d614..8f9eded4df 100644
--- a/server/pkg/agent/grok.go
+++ b/server/pkg/agent/grok.go
@@ -565,31 +565,7 @@ func selectGrokAuthMethod(methods []string, haveAPIKey bool) (string, error) {
// session/prompt response. Without this window, cancelling the process at the
// response boundary can truncate the final text or usage update.
func waitForGrokNotificationQuiescence(ctx context.Context, activity <-chan struct{}, readerDone <-chan struct{}) {
- quiet := time.NewTimer(grokNotificationQuietTime)
- defer quiet.Stop()
- hard := time.NewTimer(grokReaderDrainGrace)
- defer hard.Stop()
-
- for {
- select {
- case <-activity:
- if !quiet.Stop() {
- select {
- case <-quiet.C:
- default:
- }
- }
- quiet.Reset(grokNotificationQuietTime)
- case <-quiet.C:
- return
- case <-readerDone:
- return
- case <-hard.C:
- return
- case <-ctx.Done():
- return
- }
- }
+ waitForACPNotificationQuiescence(ctx, activity, readerDone, grokNotificationQuietTime, grokReaderDrainGrace)
}
// envHasNonEmpty reports whether an `os/exec`-style env slice
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index f730688224..c04f18c408 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -675,26 +675,45 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// may deliver the final agent_message_chunk after the response; closing stdin
// or cancelling immediately at that boundary loses the user-visible answer.
func waitForHermesNotificationQuiescence(ctx context.Context, activity <-chan struct{}, readerDone <-chan struct{}) {
- quiet := time.NewTimer(hermesNotificationQuietTime)
- defer quiet.Stop()
- hard := time.NewTimer(hermesReaderDrainGrace)
- defer hard.Stop()
+ waitForACPNotificationQuiescence(ctx, activity, readerDone, hermesNotificationQuietTime, hermesReaderDrainGrace)
+}
+
+// acpNotificationQuietTime is the default lull the shared drain waits out
+// before concluding an ACP agent has stopped emitting notifications. It is a
+// protocol-level heuristic rather than a per-backend trait, so backends that
+// have no reason to differ share it; the hard bound stays per-backend.
+const acpNotificationQuietTime = 250 * time.Millisecond
+
+// waitForACPNotificationQuiescence gives the shared ACP stdout reader a
+// bounded chance to consume notifications a backend may emit just after its
+// session/prompt response returns. Closing stdin and cancelling the context at
+// the response boundary otherwise races the reader and silently truncates the
+// final text or usage update.
+//
+// It returns as soon as any of these happens, so an agent that holds stdout
+// open forever cannot stall the turn: no notification arrived for quiet, the
+// reader finished, hard elapsed, or ctx was cancelled.
+func waitForACPNotificationQuiescence(ctx context.Context, activity <-chan struct{}, readerDone <-chan struct{}, quiet, hard time.Duration) {
+ quietTimer := time.NewTimer(quiet)
+ defer quietTimer.Stop()
+ hardTimer := time.NewTimer(hard)
+ defer hardTimer.Stop()
for {
select {
case <-activity:
- if !quiet.Stop() {
+ if !quietTimer.Stop() {
select {
- case <-quiet.C:
+ case <-quietTimer.C:
default:
}
}
- quiet.Reset(hermesNotificationQuietTime)
- case <-quiet.C:
+ quietTimer.Reset(quiet)
+ case <-quietTimer.C:
return
case <-readerDone:
return
- case <-hard.C:
+ case <-hardTimer.C:
return
case <-ctx.Done():
return
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index 1266d15323..f0c8b8b310 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -18,6 +18,11 @@ var kimiBlockedArgs = map[string]blockedArgMode{
"acp": blockedStandalone,
}
+// kimiReaderDrainGrace bounds how long the turn waits for trailing ACP
+// notifications after the session/prompt response. A var, not a const, so
+// tests can shorten it. Mirrors qoderReaderDrainGrace / traecliReaderDrainGrace.
+var kimiReaderDrainGrace = 2 * time.Second
+
// kimiBackend implements Backend by spawning `kimi acp` and communicating
// via the ACP (Agent Client Protocol) JSON-RPC 2.0 over stdin/stdout.
//
@@ -116,6 +121,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
var deliverable acpDeliverableTracker
promptDone := make(chan hermesPromptResult, 1)
+ activity := make(chan struct{}, 1)
// Reuse the hermesClient ACP transport — Kimi speaks the same protocol.
c := &hermesClient{
@@ -123,6 +129,12 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
stdin: stdin,
pending: make(map[int]*pendingRPC),
pendingTools: make(map[string]*pendingToolCall),
+ onActivity: func() {
+ select {
+ case activity <- struct{}{}:
+ default:
+ }
+ },
onMessage: func(msg Message) {
// hermesClient.handleToolCallStart has already mapped
// the raw ACP title via hermesToolNameFromTitle — which
@@ -350,6 +362,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
c.usageMu.Unlock()
default:
}
+ waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, kimiReaderDrainGrace)
}
duration := time.Since(startTime)
diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.go
index 5734908130..6f17390666 100644
--- a/server/pkg/agent/kimi_test.go
+++ b/server/pkg/agent/kimi_test.go
@@ -66,7 +66,7 @@ func fakeKimiACPScript() string {
#
# Writes the full argv (one arg per line) to $KIMI_ARGS_FILE if that env
# var is set, so tests can assert that the daemon invokes us with the
-# right flags (`+"`--yolo acp`"+`, not bare `+"`acp`"+`).
+# right flags (` + "`--yolo acp`" + `, not bare ` + "`acp`" + `).
#
# Then reads one JSON-RPC request per line from stdin, matches on the
# method name, and writes back a canned response. Exits after set_model
@@ -156,6 +156,38 @@ func TestKimiBackendSetModelFailureFailsTask(t *testing.T) {
// actually does — RequestError.invalid_params (-32602) with
// {"session_id": "Session not found"} in data
// (src/kimi_cli/acp/server.py, set_session_model).
+// fakeKimiACPPromptScript is a fake `kimi` binary that completes a full
+// ACP turn: initialize, session/new, session/prompt with a streamed
+// message chunk, then the prompt response. When $KIMI_LATE_CHUNK is set
+// it emits one more chunk shortly AFTER the session/prompt response, the
+// way a real ACP agent can, so tests can prove the backend drains
+// trailing notifications instead of cutting the process off at the
+// response boundary.
+func fakeKimiACPPromptScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"pong"}}}}\n'
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ if [ -n "$KIMI_LATE_CHUNK" ]; then
+ sleep 0.05
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tail"}}}}\n'
+ fi
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
func fakeKimiACPStaleResumeSetModelScript() string {
return `#!/bin/sh
while IFS= read -r line; do
@@ -335,3 +367,42 @@ func TestKimiResumeIncludesMcpServers(t *testing.T) {
t.Fatalf("session/resume.mcpServers: got %v, want one entry named fetch", servers)
}
}
+
+// TestKimiDrainsNotificationsAfterPromptResponse pins the trailing-notification
+// drain. kimi ACP can emit a final session update just after the
+// session/prompt response returns; closing stdin and cancelling the context at
+// that boundary raced the stdout reader and silently truncated the last chunk.
+// The same defect was fixed for the sibling ACP backends in #5440 (grok) and
+// #5675 (hermes).
+func TestKimiDrainsNotificationsAfterPromptResponse(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ writeTestExecutable(t, fakePath, []byte(fakeKimiACPPromptScript()))
+
+ backend, err := New("kimi", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"KIMI_LATE_CHUNK": "1"},
+ })
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "pong tail") {
+ t.Fatalf("late output was truncated: %q", result.Output)
+ }
+}
diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.go
index e2faac4873..6235ce52e2 100644
--- a/server/pkg/agent/kiro.go
+++ b/server/pkg/agent/kiro.go
@@ -13,6 +13,11 @@ import (
"time"
)
+// kiroReaderDrainGrace bounds how long the turn waits for trailing ACP
+// notifications after the session/prompt response. A var, not a const, so
+// tests can shorten it. Mirrors qoderReaderDrainGrace / traecliReaderDrainGrace.
+var kiroReaderDrainGrace = 2 * time.Second
+
// kiroBlockedArgs are flags hardcoded by the daemon that must not be
// overridden by user-configured custom_args. `acp` is the protocol subcommand,
// and --trust-all-tools covers Kiro's CLI-level tool gate while
@@ -134,6 +139,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
var lastFinishingResultStatus string // "", "completed", or "failed"
promptDone := make(chan hermesPromptResult, 1)
+ activity := make(chan struct{}, 1)
c := &hermesClient{
cfg: b.cfg,
@@ -143,6 +149,12 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
acceptNotification: func(string) bool {
return streamingCurrentTurn.Load()
},
+ onActivity: func() {
+ select {
+ case activity <- struct{}{}:
+ default:
+ }
+ },
onMessage: func(msg Message) {
if !streamingCurrentTurn.Load() {
return
@@ -430,6 +442,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
c.usageMu.Unlock()
default:
}
+ waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, kiroReaderDrainGrace)
}
duration := time.Since(startTime)
diff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.go
index e955f2b18e..43ce2589bc 100644
--- a/server/pkg/agent/kiro_test.go
+++ b/server/pkg/agent/kiro_test.go
@@ -107,6 +107,10 @@ while IFS= read -r line; do
printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_loaded","update":{"type":"ToolCallUpdate","toolCallId":"tc-current","status":"completed","name":"Shell","parameters":{"command":"echo current"},"output":"current tool output\\n"}}}\n'
printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_loaded","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"loaded"}}}}\n'
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":2,"outputTokens":1,"cacheReadTokens":7,"cacheWriteTokens":3}}}\n' "$id"
+ if [ -n "$KIRO_LATE_CHUNK" ]; then
+ sleep 0.05
+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_loaded","update":{"type":"AgentMessageChunk","content":{"type":"text","text":" tail"}}}}\n'
+ fi
exit 0
;;
esac
@@ -1104,7 +1108,6 @@ func TestKiroLoadIncludesMcpServersFromConfig(t *testing.T) {
}
}
-
// TestIsKiroOversizedHistoryImage pins the detector for the GH #5975 shape: a
// resumed conversation whose history replays an image exceeding the provider's
// max pixel dimensions, rejected at session/prompt as a -32603 that names the
@@ -1278,3 +1281,43 @@ func TestKiroFreshOversizedHistoryImageDoesNotSignalResumeRejected(t *testing.T)
t.Fatalf("expected the fresh session id, got %q", result.SessionID)
}
}
+
+// TestKiroDrainsNotificationsAfterPromptResponse pins the trailing-notification
+// drain. kiro ACP can emit a final session update just after the
+// session/prompt response returns; closing stdin and cancelling the context at
+// that boundary raced the stdout reader and silently truncated the last chunk.
+// The same defect was fixed for the sibling ACP backends in #5440 (grok) and
+// #5675 (hermes).
+func TestKiroDrainsNotificationsAfterPromptResponse(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kiro-cli")
+ writeTestExecutable(t, fakePath, []byte(fakeKiroACPScript()))
+
+ backend, err := New("kiro", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"KIRO_LATE_CHUNK": "1"},
+ })
+ if err != nil {
+ t.Fatalf("new kiro backend: %v", err)
+ }
+
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "loaded tail") {
+ t.Fatalf("late output was truncated: %q", result.Output)
+ }
+}
diff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.go
index cd64c4e915..bdc5bce64c 100644
--- a/server/pkg/agent/qoder.go
+++ b/server/pkg/agent/qoder.go
@@ -148,6 +148,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
var streamingCurrentTurn atomic.Bool
promptDone := make(chan hermesPromptResult, 1)
+ activity := make(chan struct{}, 1)
c := &hermesClient{
cfg: b.cfg,
@@ -157,6 +158,12 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
acceptNotification: func(string) bool {
return streamingCurrentTurn.Load()
},
+ onActivity: func() {
+ select {
+ case activity <- struct{}{}:
+ default:
+ }
+ },
onMessage: func(msg Message) {
if !streamingCurrentTurn.Load() {
return
@@ -371,6 +378,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
c.usageMu.Unlock()
default:
}
+ waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, qoderReaderDrainGrace)
}
duration := time.Since(startTime)
diff --git a/server/pkg/agent/qoder_test.go b/server/pkg/agent/qoder_test.go
index 21b03529af..b309448fcd 100644
--- a/server/pkg/agent/qoder_test.go
+++ b/server/pkg/agent/qoder_test.go
@@ -35,6 +35,10 @@ while IFS= read -r line; do
*'"method":"session/prompt"'*)
printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"ok"}}}}\n'
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":2}}}\n' "$id"
+ if [ -n "$QODER_LATE_CHUNK" ]; then
+ sleep 0.05
+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":" tail"}}}}\n'
+ fi
exit 0
;;
esac
@@ -975,3 +979,42 @@ func TestQoderBackendClearsSessionIDWhenResumedSessionNotFoundAtSetModel(t *test
t.Fatal("timeout waiting for result")
}
}
+
+// TestQoderDrainsNotificationsAfterPromptResponse pins the trailing-notification
+// drain. qoder ACP can emit a final session update just after the
+// session/prompt response returns; closing stdin and cancelling the context at
+// that boundary raced the stdout reader and silently truncated the last chunk.
+// The same defect was fixed for the sibling ACP backends in #5440 (grok) and
+// #5675 (hermes).
+func TestQoderDrainsNotificationsAfterPromptResponse(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "qoder")
+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScript()))
+
+ backend, err := New("qoder", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"QODER_LATE_CHUNK": "1"},
+ })
+ if err != nil {
+ t.Fatalf("new qoder backend: %v", err)
+ }
+
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "ok tail") {
+ t.Fatalf("late output was truncated: %q", result.Output)
+ }
+}
diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.go
index eb1468d6f4..da9d7f0baa 100644
--- a/server/pkg/agent/traecli.go
+++ b/server/pkg/agent/traecli.go
@@ -165,6 +165,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
var streamingCurrentTurn atomic.Bool
promptDone := make(chan hermesPromptResult, 1)
+ activity := make(chan struct{}, 1)
c := &hermesClient{
cfg: b.cfg,
@@ -174,6 +175,12 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
acceptNotification: func(string) bool {
return streamingCurrentTurn.Load()
},
+ onActivity: func() {
+ select {
+ case activity <- struct{}{}:
+ default:
+ }
+ },
onMessage: func(msg Message) {
if !streamingCurrentTurn.Load() {
return
@@ -379,6 +386,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
c.usageMu.Unlock()
default:
}
+ waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, traecliReaderDrainGrace)
}
duration := time.Since(startTime)
diff --git a/server/pkg/agent/traecli_test.go b/server/pkg/agent/traecli_test.go
index 6528bffe42..af3a98f9b0 100644
--- a/server/pkg/agent/traecli_test.go
+++ b/server/pkg/agent/traecli_test.go
@@ -68,6 +68,10 @@ while IFS= read -r line; do
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'
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"pong"}}}}\n'
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ if [ -n "$TRAECLI_LATE_CHUNK" ]; then
+ sleep 0.05
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tail"}}}}\n'
+ fi
exit 0
;;
esac
@@ -287,3 +291,42 @@ func TestTraecliUsesSessionLoadForResume(t *testing.T) {
t.Fatalf("traecli must use session/load (loadSession:true), not session/resume:\n%s", requests)
}
}
+
+// TestTraecliDrainsNotificationsAfterPromptResponse pins the trailing-notification
+// drain. traecli ACP can emit a final session update just after the
+// session/prompt response returns; closing stdin and cancelling the context at
+// that boundary raced the stdout reader and silently truncated the last chunk.
+// The same defect was fixed for the sibling ACP backends in #5440 (grok) and
+// #5675 (hermes).
+func TestTraecliDrainsNotificationsAfterPromptResponse(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "trae")
+ writeTestExecutable(t, fakePath, []byte(fakeTraecliACPScript()))
+
+ backend, err := New("traecli", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"TRAECLI_LATE_CHUNK": "1"},
+ })
+ if err != nil {
+ t.Fatalf("new traecli backend: %v", err)
+ }
+
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "pong tail") {
+ t.Fatalf("late output was truncated: %q", result.Output)
+ }
+}