Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): recover Antigravity reply from transcript when agy stdout is empty (#4744)
Bohan Jiang9ee2bd4c34ed
diff --git a/server/pkg/agent/antigravity.go b/server/pkg/agent/antigravity.goindex f26ba20f88..eb4ce31292 100644--- a/server/pkg/agent/antigravity.go+++ b/server/pkg/agent/antigravity.go@@ -3,6 +3,7 @@ package agentimport ("bufio""context"+ "encoding/json""fmt""log/slog""os"@@ -23,6 +24,15 @@ import (// therefore streams stdout line-by-line as `MessageText` events and accumulates// the same text as the final `Result.Output`.//+// agy 1.0.14's print mode regressed this stdout contract: a turn can run tools+// and produce a final reply while emitting ZERO bytes to stdout (the log shows+// "PlannerResponse without ModifiedResponse encountered"). Exit code is 0 and+// no error is logged, so a blank-but-"completed" run reaches the daemon and the+// user sees an empty result even though the work happened (MUL-3726, #4595).+// When stdout comes back empty on an otherwise-completed turn, the backend+// therefore recovers the assistant text agy durably wrote to its per-+// conversation transcript (see readAntigravityTranscriptOutput).+//// Session resumption uses `--conversation <id>`. The conversation id is not// emitted on stdout; we capture it by routing `--log-file` to a temp file and// scanning its glog-formatted lines for the `conversation=<uuid>` token that@@ -170,11 +180,24 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts ExfinalError = withAgentStderr(finalError, "agy", stderrBuf.Tail())}+ finalOutput := output.String()+ if finalStatus == "completed" && strings.TrimSpace(finalOutput) == "" {+ // agy 1.0.14 print mode can finish a turn (tools executed, reply+ // produced) without writing anything to stdout, leaving a blank but+ // "completed" run none of the guards above catch (MUL-3726). Recover+ // the assistant text agy persisted to its conversation transcript so+ // the user sees the actual answer instead of an empty result.+ if recovered := readAntigravityTranscriptOutput(logPath, sessionID); recovered != "" {+ finalOutput = recovered+ b.cfg.Logger.Info("agy recovered empty stdout from transcript", "bytes", len(recovered))+ }+ }+b.cfg.Logger.Info("agy finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())resCh <- Result{Status: finalStatus,- Output: output.String(),+ Output: finalOutput,Error: finalError,DurationMs: duration.Milliseconds(),SessionID: sessionID,@@ -265,6 +288,118 @@ func readAntigravityConversationID(logPath string) string {return string(matches[len(matches)-1][1])}+// antigravityAppDataDirRe matches the glog line agy writes at startup naming its+// CLI app data directory — the root under which per-conversation transcripts+// live. Reading the path from the log (which the daemon owns via --log-file)+// is more robust than guessing $HOME, and follows agy through a custom data dir.+//+// Example: `I0630 14:19:40.582492 88197 common.go:156] CLI app data directory:+// /Users/me/.gemini/antigravity-cli`+var antigravityAppDataDirRe = regexp.MustCompile(`CLI app data directory:\s*(.+)`)++// antigravityTranscriptRecord is the minimal shape of one line in agy's+// per-conversation transcript.jsonl. A turn opens with a USER_INPUT record; the+// assistant's replies are PLANNER_RESPONSE records with source=MODEL and (once+// settled) status=DONE. Content holds the text, or JSON null for a tool-only+// step — it is RawMessage so a null or non-string value is skipped rather than+// failing the whole line.+type antigravityTranscriptRecord struct {+ Type string `json:"type"`+ Source string `json:"source"`+ Status string `json:"status"`+ Content json.RawMessage `json:"content"`+}++// readAntigravityTranscriptOutput recovers the assistant's text from agy's+// per-conversation transcript when stdout carried nothing. agy 1.0.14's print+// mode can finish a turn (tools executed, final reply produced) while emitting+// zero bytes to stdout, leaving the daemon with a blank but "completed" run+// (MUL-3726, #4595). The full reply is still durably written to:+//+// <appDataDir>/brain/<conversation-id>/.system_generated/logs/transcript.jsonl+//+// as PLANNER_RESPONSE / source=MODEL records.+//+// The transcript is per-conversation and ACCUMULATES across resumed turns+// (daemon reuses the conversation via --conversation / ResumeSessionID), so we+// must return only the CURRENT turn's reply — otherwise a later empty-stdout+// turn would re-emit prior turns' answers. Each turn opens with a USER_INPUT+// record, so we reset on every USER_INPUT and keep only the model text that+// follows the last one. We also require status=DONE to skip any future+// streaming/partial planner records. The remaining text is joined in order+// (intermediate narration + final reply), mirroring what stdout would have+// streamed for this turn. Best-effort: returns "" if the app data dir or+// conversation id is unknown, the transcript is missing, or it holds no model+// text for the current turn.+func readAntigravityTranscriptOutput(logPath, conversationID string) string {+ if logPath == "" || conversationID == "" {+ return ""+ }+ appDataDir := readAntigravityAppDataDir(logPath)+ if appDataDir == "" {+ return ""+ }+ transcriptPath := filepath.Join(+ appDataDir, "brain", conversationID, ".system_generated", "logs", "transcript.jsonl",+ )+ f, err := os.Open(transcriptPath)+ if err != nil {+ return ""+ }+ defer f.Close()++ var parts []string+ scanner := bufio.NewScanner(f)+ scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024)+ for scanner.Scan() {+ line := scanner.Bytes()+ if len(line) == 0 {+ continue+ }+ var rec antigravityTranscriptRecord+ if err := json.Unmarshal(line, &rec); err != nil {+ continue+ }+ if rec.Type == "USER_INPUT" {+ // New turn boundary: drop anything collected for prior turns so a+ // resumed conversation yields only the current turn's reply.+ parts = parts[:0]+ continue+ }+ if rec.Type != "PLANNER_RESPONSE" || rec.Source != "MODEL" || rec.Status != "DONE" {+ continue+ }+ var text string+ // Content is JSON null for tool-only steps; unmarshal leaves text "".+ // A non-string value (object) errors and is skipped.+ if err := json.Unmarshal(rec.Content, &text); err != nil {+ continue+ }+ if strings.TrimSpace(text) != "" {+ parts = append(parts, text)+ }+ }+ return strings.Join(parts, "\n\n")+}++// readAntigravityAppDataDir extracts agy's CLI app data directory from the+// per-run log. Best-effort: returns "" if the log is missing or the marker+// format changes upstream.+func readAntigravityAppDataDir(logPath string) string {+ if logPath == "" {+ return ""+ }+ data, err := os.ReadFile(logPath)+ if err != nil {+ return ""+ }+ m := antigravityAppDataDirRe.FindSubmatch(data)+ if m == nil {+ return ""+ }+ return strings.TrimSpace(string(m[1]))+}+// antigravityBlockedArgs are flags hardcoded by the daemon that must not be// overridden by user-configured custom_args. Overriding these would break// non-interactive operation or the daemon's session-resume bookkeeping.diff --git a/server/pkg/agent/antigravity_test.go b/server/pkg/agent/antigravity_test.goindex 36f98991b4..152da8d30d 100644--- a/server/pkg/agent/antigravity_test.go+++ b/server/pkg/agent/antigravity_test.go@@ -503,3 +503,192 @@ func TestAntigravityModelError(t *testing.T) {t.Error("near-miss model (dropped suffix) should be rejected")}}++// seedAntigravityTranscript writes a transcript.jsonl under appDataDir for the+// given conversation id, at the real path agy uses+// (<appDataDir>/brain/<cid>/.system_generated/logs/transcript.jsonl).+func seedAntigravityTranscript(t *testing.T, appDataDir, conversationID string, records []string) {+ t.Helper()+ dir := filepath.Join(appDataDir, "brain", conversationID, ".system_generated", "logs")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ body := strings.Join(records, "\n") + "\n"+ if err := os.WriteFile(filepath.Join(dir, "transcript.jsonl"), []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+}++func TestReadAntigravityTranscriptOutput(t *testing.T) {+ t.Parallel()++ appDataDir := t.TempDir()+ cid := "d1637a93-20c7-4d90-8edb-7395e71280d2"++ // The app data dir + conversation id both come from the per-run log, the+ // same source the daemon already owns via --log-file.+ logPath := filepath.Join(t.TempDir(), "agy.log")+ if err := os.WriteFile(logPath, []byte(strings.Join([]string{+ `I0630 14:19:40.582492 1 common.go:156] CLI app data directory: ` + appDataDir,+ `I0630 14:19:46.755801 1 printmode.go:179] Print mode: conversation=` + cid + `, sending message`,+ }, "\n")), 0o644); err != nil {+ t.Fatal(err)+ }++ seedAntigravityTranscript(t, appDataDir, cid, []string{+ // USER_INPUT (source=USER_EXPLICIT in practice) opens the turn.+ `{"type":"USER_INPUT","source":"USER_EXPLICIT","status":"DONE","step_index":0,"content":"the user's prompt — must be ignored"}`,+ // Tool-only model steps carry content=null and must be skipped.+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":2,"content":null}`,+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":3,"content":"First I will read the file."}`,+ // Tool records can also be source=MODEL — excluded by the type check.+ `{"type":"VIEW_FILE","source":"MODEL","status":"DONE","step_index":4}`,+ // Non-MODEL planner text must be excluded.+ `{"type":"PLANNER_RESPONSE","source":"SYSTEM","status":"DONE","step_index":5,"content":"non-model planner text — must be ignored"}`,+ // A non-DONE (streaming/partial) model record must be excluded.+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"IN_PROGRESS","step_index":6,"content":"partial streaming text — must be ignored"}`,+ `{"type":"CODE_ACTION","source":"MODEL","status":"DONE","step_index":7}`,+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":8,"content":"Done: created result.txt and verified it."}`,+ })++ // MODEL/DONE text is joined in order; null/tool/non-model/non-DONE records+ // are all dropped.+ got := readAntigravityTranscriptOutput(logPath, cid)+ want := "First I will read the file.\n\nDone: created result.txt and verified it."+ if got != want {+ t.Fatalf("readAntigravityTranscriptOutput mismatch\n got: %q\nwant: %q", got, want)+ }++ // Every soft-failure path must yield "" rather than erroring.+ if got := readAntigravityTranscriptOutput(logPath, "ffffffff-0000-0000-0000-000000000000"); got != "" {+ t.Errorf("unknown conversation id should yield empty, got %q", got)+ }+ if got := readAntigravityTranscriptOutput("/nonexistent/agy.log", cid); got != "" {+ t.Errorf("missing log (no app data dir) should yield empty, got %q", got)+ }+ if got := readAntigravityTranscriptOutput(logPath, ""); got != "" {+ t.Errorf("empty conversation id should yield empty, got %q", got)+ }+ if got := readAntigravityTranscriptOutput("", cid); got != "" {+ t.Errorf("empty log path should yield empty, got %q", got)+ }+}++// TestReadAntigravityTranscriptOutputResumeReturnsCurrentTurnOnly is the+// regression guard for the PR #4744 review must-fix: the transcript accumulates+// across resumed turns (daemon reuses the conversation via --conversation), so+// recovery must return ONLY the current turn's reply. Without the USER_INPUT+// turn boundary, a second empty-stdout turn would re-emit the previous turn's+// answer alongside the new one.+func TestReadAntigravityTranscriptOutputResumeReturnsCurrentTurnOnly(t *testing.T) {+ t.Parallel()++ appDataDir := t.TempDir()+ cid := "9e18418b-a431-4523-9616-75a94904554e"++ logPath := filepath.Join(t.TempDir(), "agy.log")+ if err := os.WriteFile(logPath, []byte(strings.Join([]string{+ `I0630 14:19:40.582492 1 common.go:156] CLI app data directory: ` + appDataDir,+ `I0630 14:19:46.755801 1 printmode.go:179] Print mode: conversation=` + cid + `, sending message`,+ }, "\n")), 0o644); err != nil {+ t.Fatal(err)+ }++ // Two turns in one accumulated transcript, matching real agy resume output:+ // each turn opens with its own USER_INPUT.+ seedAntigravityTranscript(t, appDataDir, cid, []string{+ // --- turn 1 ---+ `{"type":"USER_INPUT","source":"USER_EXPLICIT","status":"DONE","step_index":0,"content":"read marker.txt"}`,+ `{"type":"VIEW_FILE","source":"MODEL","status":"DONE","step_index":1}`,+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":2,"content":"The two values are alpha-1 and beta-2."}`,+ // --- turn 2 (resumed) ---+ `{"type":"USER_INPUT","source":"USER_EXPLICIT","status":"DONE","step_index":3,"content":"what is 7 times 8?"}`,+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":4,"content":"56"}`,+ })++ got := readAntigravityTranscriptOutput(logPath, cid)+ if got != "56" {+ t.Fatalf("expected only the current turn's reply %q, got %q (prior turn leaked?)", "56", got)+ }+}++// fakeAgyEmptyStdoutScript reproduces agy 1.0.14's regressed print mode: the+// process logs its CLI app data directory and the conversation id, writes+// NOTHING to stdout, and exits 0 — the "PlannerResponse without ModifiedResponse"+// case (MUL-3726). The real reply lives only in the conversation transcript,+// which the test seeds under appDataDir.+func fakeAgyEmptyStdoutScript(appDataDir, conversationID string) string {+ return `#!/bin/sh+log=""+while [ $# -gt 0 ]; do+ case "$1" in+ --log-file) log="$2"; shift 2 ;;+ *) shift ;;+ esac+done+if [ -n "$log" ]; then+ printf 'I0630 14:19:40.582492 1 common.go:156] CLI app data directory: ` + appDataDir + `\n' >> "$log"+ printf 'I0630 14:19:46.755801 1 printmode.go:179] Print mode: conversation=` + conversationID + `, sending message\n' >> "$log"+fi+exit 0+`+}++// TestAntigravityBackendRecoversEmptyStdoutFromTranscript is the end-to-end+// guard for MUL-3726: agy 1.0.14 can complete a turn with empty stdout while the+// real reply lives only in the conversation transcript. The backend must recover+// that text into Result.Output instead of returning a blank "completed" run.+func TestAntigravityBackendRecoversEmptyStdoutFromTranscript(t *testing.T) {+ t.Parallel()++ appDataDir := t.TempDir()+ cid := "44a57718-801c-41e7-9691-3225be2b1cb8"+ seedAntigravityTranscript(t, appDataDir, cid, []string{+ `{"type":"USER_INPUT","source":"USER_EXPLICIT","status":"DONE","step_index":0,"content":"create result.txt"}`,+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":2,"content":null}`,+ `{"type":"VIEW_FILE","source":"MODEL","status":"DONE","step_index":3}`,+ `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":4,"content":"I read marker.txt and created result.txt with VERIFIED=yes."}`,+ })++ fakePath := filepath.Join(t.TempDir(), "agy")+ writeTestExecutable(t, fakePath, []byte(fakeAgyEmptyStdoutScript(appDataDir, cid)))++ backend, err := New("antigravity", Config{ExecutablePath: fakePath, Logger: quietAntigravityLogger()})+ if err != nil {+ t.Fatalf("new antigravity backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "completed" {+ t.Fatalf("expected status=completed, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Output, "created result.txt with VERIFIED=yes") {+ t.Fatalf("expected transcript reply recovered into output, got %q", result.Output)+ }+ // content=null tool steps must not leak the literal "null" into output.+ if strings.Contains(result.Output, "null") {+ t.Errorf("null tool-step content leaked into output: %q", result.Output)+ }+ if result.SessionID != cid {+ t.Errorf("expected session id %q recovered from log, got %q", cid, result.SessionID)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}