Skip to content

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

Go

MUL-7625: feat(antigravity): stream live tool execution events (#8734)

mrlonely0516dd57c3e8
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
index b00548e8e1..a45e56c93d 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -270,17 +270,13 @@ describe("AgentTranscriptDialog", () => {
expect(screen.queryByText("A finished", { selector: "pre" })).not.toBeInTheDocument();
});
- it("explains unavailable live events for an empty Antigravity transcript", async () => {
+ it("waits for live events from Antigravity", async () => {
vi.mocked(api.listRuntimes).mockResolvedValue([runtimeFor("antigravity")]);
renderDialog([], { task: liveTask, isLive: true });
- expect(
- await screen.findByText(
- "Antigravity does not currently provide live execution events. The transcript will be available after the run completes.",
- ),
- ).toBeInTheDocument();
- expect(screen.queryByText("Waiting for events...")).not.toBeInTheDocument();
+ await screen.findByRole("button", { name: "Run details" });
+ expect(screen.getByText("Waiting for events...")).toBeInTheDocument();
});
it("keeps waiting for live events from other runtimes", async () => {
@@ -294,6 +290,19 @@ describe("AgentTranscriptDialog", () => {
expect(screen.getByText("Waiting for events...")).toBeInTheDocument();
});
+ it("shows live Antigravity tool events", async () => {
+ vi.mocked(api.listRuntimes).mockResolvedValue([runtimeFor("antigravity")]);
+
+ renderDialog([
+ { seq: 1, type: "tool_use", tool: "run_command", input: { CommandLine: "echo hello" } },
+ { seq: 2, type: "tool_result", tool: "run_command", output: "hello" },
+ ], { task: liveTask, isLive: true });
+
+ await screen.findByRole("button", { name: "Run details" });
+ expect(screen.queryByText("Waiting for events...")).not.toBeInTheDocument();
+ expect(screen.getAllByText(/run_command/).length).toBeGreaterThan(0);
+ });
+
it("preserves selected filters across dialog remounts unconditionally", () => {
const first = renderDialog();
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 367bc8950b..3beeda987b 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -12,7 +12,6 @@ import {
XCircle,
X,
Loader2,
- Clock,
Copy,
Check,
ChevronRight,
@@ -555,11 +554,6 @@ export function AgentTranscriptDialog({
? Math.max(0, (timeMs(selectedStep.startedAt) ?? runStartMs) - runStartMs)
: undefined;
- // Keyed on the run having produced nothing at all, not on the filtered view
- // being empty — a filter that hides every step is not a runtime limitation.
- const isAntigravityLiveEmpty =
- isLive && steps.length === 0 && runtimeInfo?.provider === "antigravity";
-
// Newest-first shows live events as PREPENDS, and Virtuoso items opt out of
// native scroll anchoring (`overflow-anchor: none`), so without compensation
// every 500ms flush shifts the reading position. Virtuoso's contract: a
@@ -1220,12 +1214,7 @@ export function AgentTranscriptDialog({
<div className="flex min-w-0 flex-1 flex-col">
{contentState ? <div className="flex h-full items-center justify-center p-4">{contentState}</div> : displayRows.length === 0 ? (
<div className="flex h-full items-center justify-center text-body text-muted-foreground">
- {isAntigravityLiveEmpty ? (
- <div className="flex max-w-md items-center gap-2 px-4 text-center">
- <Clock className="h-4 w-4 shrink-0" />
- {t(($) => $.transcript.antigravity_live_unavailable)}
- </div>
- ) : isLive && steps.length === 0 ? (
+ {isLive && steps.length === 0 ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
{t(($) => $.transcript.waiting_events)}
diff --git a/packages/views/common/task-transcript/run-outcome.test.ts b/packages/views/common/task-transcript/run-outcome.test.ts
index 99c8714b2f..bb0262beee 100644
--- a/packages/views/common/task-transcript/run-outcome.test.ts
+++ b/packages/views/common/task-transcript/run-outcome.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { buildRunOutcome } from "./run-outcome";
-import { buildSteps } from "./build-steps";
+import { buildSteps, groupSteps, toolKindTotals } from "./build-steps";
+import { traceEventDetail, traceToolArgSummary } from "./trace-event-presenter";
import type { TimelineItem } from "./build-timeline";
let seq = 0;
@@ -24,6 +25,76 @@ function read(path: string): TimelineItem {
}
describe("buildRunOutcome", () => {
+ it("keeps normalized Antigravity commands visible and counts each command", () => {
+ const calls: TimelineItem[] = ["pwd", "git status", "go test ./..."].map((command) => ({
+ seq: ++seq,
+ type: "tool_use",
+ tool: "run_command",
+ input: {
+ Cwd: "/workspace",
+ command: `/bin/sh -c '${command}'`,
+ },
+ }));
+ const steps = buildSteps(calls);
+
+ expect(groupSteps(steps).map((row) => row.kind)).toEqual(["call", "call", "call"]);
+ expect(buildRunOutcome(steps)?.commandCount).toBe(3);
+ expect(calls.map((call) => traceToolArgSummary(call.input))).toEqual([
+ "pwd",
+ "git status",
+ "go test ./...",
+ ]);
+ expect(traceToolArgSummary({ file_path: "/workspace/a.go" })).toBe("/workspace/a.go");
+ });
+
+ it.each([
+ { name: "write", tool: "write_to_file", input: { content: "hello" }, kind: "file" },
+ { name: "empty file", tool: "write_to_file", input: { content: "" }, kind: "file" },
+ {
+ name: "edit",
+ tool: "replace_file_content",
+ input: { old_string: "before", new_string: "after" },
+ kind: "diff",
+ },
+ {
+ name: "deletion",
+ tool: "replace_file_content",
+ input: { old_string: "before", new_string: "" },
+ kind: "diff",
+ },
+ {
+ name: "insertion",
+ tool: "replace_file_content",
+ input: { old_string: "", new_string: "after" },
+ kind: "diff",
+ },
+ ])(
+ "renders a normalized Antigravity $name and classifies its time as writing",
+ ({ tool, input, kind }) => {
+ const call: TimelineItem = {
+ seq: ++seq,
+ type: "tool_use",
+ tool,
+ input: { file_path: "/workspace/a.go", ...input },
+ created_at: "2026-09-23T00:00:00.000Z",
+ };
+ const steps = buildSteps([
+ call,
+ {
+ seq: ++seq,
+ type: "tool_result",
+ tool,
+ output: "ok",
+ created_at: "2026-09-23T00:00:01.000Z",
+ },
+ ]);
+
+ expect(traceEventDetail(call)).toMatchObject({ kind, path: "/workspace/a.go" });
+ expect(toolKindTotals(steps)).toEqual({ command: 0, write: 1000, read: 0, other: 0 });
+ expect(buildRunOutcome(steps)?.paths).toEqual(["/workspace/a.go"]);
+ },
+ );
+
it("counts changed lines from an edit", () => {
const outcome = buildRunOutcome(buildSteps([edit("a.ts", "one\ntwo", "one\ntwo\nthree")]))!;
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 786d654b95..5cfbacc427 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -835,7 +835,6 @@
"copy_filtered": "Copy filtered",
"copied": "Copied",
"waiting_events": "Waiting for events...",
- "antigravity_live_unavailable": "Antigravity does not currently provide live execution events. The transcript will be available after the run completes.",
"no_data": "No execution data recorded.",
"sort_chronological": "Oldest first",
"sort_newest_first": "Newest first",
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index a7631100c6..c927ec6cc7 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -835,7 +835,6 @@
"copy_filtered": "Copier la sélection filtrée",
"copied": "Copié",
"waiting_events": "En attente d'événements...",
- "antigravity_live_unavailable": "Antigravity ne fournit pas encore d'événements d'exécution en direct. La transcription sera disponible une fois l'exécution terminée.",
"no_data": "Aucune donnée d'exécution enregistrée.",
"sort_chronological": "Plus anciens d'abord",
"sort_newest_first": "Plus récents d'abord",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 902b8bc64c..daa62c718d 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -718,7 +718,6 @@
"copy_filtered": "フィルター結果をコピー",
"copied": "コピーしました",
"waiting_events": "イベントを待機中...",
- "antigravity_live_unavailable": "Antigravity は現在、リアルタイム実行イベントを提供していません。実行完了後に実行記録を確認できます。",
"no_data": "記録された実行データがありません。",
"sort_chronological": "古い順",
"sort_newest_first": "新しい順",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 41f896e72a..2a206c585d 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -726,7 +726,6 @@
"copy_filtered": "필터 결과 복사",
"copied": "복사했습니다",
"waiting_events": "이벤트를 기다리는 중...",
- "antigravity_live_unavailable": "Antigravity는 현재 실시간 실행 이벤트를 제공하지 않습니다. 실행이 완료되면 실행 기록을 확인할 수 있습니다.",
"no_data": "기록된 실행 데이터가 없습니다.",
"sort_chronological": "오래된 순",
"sort_newest_first": "최신 순",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 05542b1495..9201492fd3 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -820,7 +820,6 @@
"copy_filtered": "复制筛选结果",
"copied": "已复制",
"waiting_events": "等待事件中...",
- "antigravity_live_unavailable": "Antigravity 暂不提供实时执行事件。运行完成后即可查看执行记录。",
"no_data": "未记录执行数据。",
"sort_chronological": "最早在前",
"sort_newest_first": "最新在前",
diff --git a/server/pkg/agent/antigravity.go b/server/pkg/agent/antigravity.go
index 19ad25a5c7..49cfb2f94e 100644
--- a/server/pkg/agent/antigravity.go
+++ b/server/pkg/agent/antigravity.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
+ "maps"
"os"
"os/exec"
"path/filepath"
@@ -50,11 +51,120 @@ type antigravityStreamUsage struct {
type antigravityStreamStepUpdate struct {
ConversationID string `json:"conversation_id"`
- StepIndex int `json:"step_index"`
+ StepIndex *int `json:"step_index"`
State string `json:"state"`
StepType string `json:"step_type"`
TextDelta string `json:"text_delta"`
Usage *antigravityStreamUsage `json:"usage"`
+ ToolName string `json:"tool_name"`
+ ToolInfo *antigravityStreamTool `json:"tool_info"`
+}
+
+type antigravityStreamTool struct {
+ Name string `json:"name"`
+ Parameters map[string]any `json:"parameters"`
+ Output json.RawMessage `json:"output"`
+ Error *struct {
+ Type string `json:"type"`
+ Message string `json:"message"`
+ } `json:"error"`
+}
+
+type antigravityToolState struct {
+ name string
+ done bool
+}
+
+// Normalize the shared transcript input without duplicating commands or file
+// bodies. Preserve collisions and unknown fields, and do not mutate the snapshot.
+func antigravityToolInput(parameters map[string]any) map[string]any {
+ input := maps.Clone(parameters)
+ for _, alias := range []struct {
+ from, to string
+ allowEmpty bool
+ }{
+ {"CommandLine", "command", false},
+ {"AbsolutePath", "file_path", false},
+ {"TargetFile", "file_path", false},
+ {"CodeContent", "content", true},
+ {"TargetContent", "old_string", true},
+ {"ReplacementContent", "new_string", true},
+ } {
+ if _, exists := input[alias.to]; exists {
+ continue
+ }
+ if value, ok := parameters[alias.from].(string); ok && (value != "" || alias.allowEmpty) {
+ input[alias.to] = value
+ delete(input, alias.from)
+ }
+ }
+ return input
+}
+
+// Each step has one tool lifecycle, even when agy repeats state snapshots or
+// only emits DONE. The existing daemon uploader handles these normal messages;
+// tool output must never be appended to the assistant's final answer.
+func antigravityToolMessages(step *antigravityStreamStepUpdate, states map[int]antigravityToolState) []Message {
+ if step.StepType != "tool" || step.StepIndex == nil || *step.StepIndex < 0 {
+ return nil
+ }
+ active := strings.EqualFold(step.State, "active")
+ done := strings.EqualFold(step.State, "done")
+ if !active && !done {
+ return nil
+ }
+ index := *step.StepIndex
+ state := states[index]
+ if state.done {
+ return nil
+ }
+ callID := fmt.Sprintf("agy-step-%d", index)
+ var messages []Message
+ if state.name == "" {
+ name := step.ToolName
+ var input map[string]any
+ if step.ToolInfo != nil {
+ if name == "" {
+ name = step.ToolInfo.Name
+ }
+ input = antigravityToolInput(step.ToolInfo.Parameters)
+ }
+ if name == "" {
+ return nil // A later snapshot may provide the missing metadata.
+ }
+ state.name = name
+ messages = append(messages, Message{Type: MessageToolUse, Tool: name, CallID: callID, Input: input})
+ }
+ if done {
+ var output string
+ if info := step.ToolInfo; info != nil {
+ if len(info.Output) > 0 && string(info.Output) != "null" {
+ if err := json.Unmarshal(info.Output, &output); err != nil {
+ output = string(info.Output)
+ }
+ }
+ if info.Error != nil {
+ detail := info.Error.Message
+ if info.Error.Type != "" {
+ if detail != "" {
+ detail = info.Error.Type + ": " + detail
+ } else {
+ detail = info.Error.Type
+ }
+ }
+ // The daemon uploads a bounded prefix of tool output. Put the
+ // error first so verbose stdout cannot hide the failure detail.
+ if output != "" {
+ output = "\n" + output
+ }
+ output = "Tool error: " + detail + output
+ }
+ }
+ messages = append(messages, Message{Type: MessageToolResult, Tool: state.name, CallID: callID, Output: output})
+ state.done = true
+ }
+ states[index] = state
+ return messages
}
type antigravityStreamResult struct {
@@ -237,6 +347,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex
var streamResponse string
var streamResultUsage *antigravityStreamUsage
streamStepUsage := make(map[int]TokenUsage)
+ streamTools := make(map[int]antigravityToolState)
streamLatestAgentResponseStep := -1
streamLatestAgentResponseDone := false
finalStatus := "completed"
@@ -246,6 +357,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex
trySend(msgCh, Message{Type: MessageStatus, Status: "running"})
+ streamLoop:
for scanner.Scan() {
line := scanner.Text()
var event antigravityStreamEvent
@@ -261,22 +373,32 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex
if event.StepUpdate.ConversationID != "" {
streamSessionID = event.StepUpdate.ConversationID
}
- if event.StepUpdate.StepType == "agent_response" && event.StepUpdate.StepIndex >= streamLatestAgentResponseStep {
+ for _, message := range antigravityToolMessages(event.StepUpdate, streamTools) {
+ // Tool lifecycle events also drive the daemon's in-flight
+ // counter. Unlike best-effort text, neither half may be
+ // dropped when a transcript consumer temporarily falls behind.
+ select {
+ case msgCh <- message:
+ case <-runCtx.Done():
+ break streamLoop
+ }
+ }
+ if event.StepUpdate.StepType == "agent_response" && event.StepUpdate.StepIndex != nil && *event.StepUpdate.StepIndex >= streamLatestAgentResponseStep {
// Only the latest response step determines whether the answer
// completed. A prior DONE response may be followed by a newer
// ACTIVE response that is cut off by the network error.
- streamLatestAgentResponseStep = event.StepUpdate.StepIndex
+ streamLatestAgentResponseStep = *event.StepUpdate.StepIndex
streamLatestAgentResponseDone = strings.EqualFold(event.StepUpdate.State, "done")
}
if event.StepUpdate.StepType == "agent_response" && event.StepUpdate.TextDelta != "" {
output.WriteString(event.StepUpdate.TextDelta)
trySend(msgCh, Message{Type: MessageText, Content: event.StepUpdate.TextDelta})
}
- if strings.EqualFold(event.StepUpdate.State, "done") && event.StepUpdate.Usage != nil && event.StepUpdate.Usage.hasTokens() {
+ if strings.EqualFold(event.StepUpdate.State, "done") && event.StepUpdate.StepIndex != nil && event.StepUpdate.Usage != nil && event.StepUpdate.Usage.hasTokens() {
// A step may be re-emitted as its state changes. Keying by
// index makes the final DONE snapshot replace, not duplicate,
// an earlier copy of the same step.
- streamStepUsage[event.StepUpdate.StepIndex] = event.StepUpdate.Usage.tokenUsage()
+ streamStepUsage[*event.StepUpdate.StepIndex] = event.StepUpdate.Usage.tokenUsage()
}
case "result":
if event.Result == nil {
diff --git a/server/pkg/agent/antigravity_tools_test.go b/server/pkg/agent/antigravity_tools_test.go
new file mode 100644
index 0000000000..67fb05c5bd
--- /dev/null
+++ b/server/pkg/agent/antigravity_tools_test.go
@@ -0,0 +1,318 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAntigravityToolsWithSlowConsumer(t *testing.T) {
+ for _, cancelWhileFull := range []bool{false, true} {
+ t.Run(fmt.Sprintf("cancel=%v", cancelWhileFull), func(t *testing.T) {
+ t.Parallel()
+ const calls = 400 // More lifecycle events than the message buffer holds.
+ var script strings.Builder
+ script.WriteString("#!/bin/sh\n")
+ for i := 0; i < calls; i++ {
+ fmt.Fprintf(&script, "printf '%%s\\n' '{\"event\":\"step_update\",\"step_update\":{\"step_index\":%d,\"state\":\"DONE\",\"step_type\":\"tool\",\"tool_name\":\"read_file\",\"tool_info\":{\"output\":\"ok\"}}}'\n", i)
+ }
+ script.WriteString("printf '%s\\n' '{\"event\":\"result\",\"result\":{\"status\":\"SUCCESS\",\"response\":\"Finished\"}}'\n")
+ fakePath := filepath.Join(t.TempDir(), "agy")
+ writeTestExecutable(t, fakePath, []byte(script.String()))
+ backend, err := New("antigravity", Config{ExecutablePath: fakePath, Logger: quietAntigravityLogger()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "ignored", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for len(session.Messages) < cap(session.Messages) {
+ select {
+ case <-ctx.Done():
+ t.Fatal("message buffer never filled")
+ case <-time.After(time.Millisecond):
+ }
+ }
+ if cancelWhileFull {
+ cancel()
+ select {
+ case result := <-session.Result:
+ if result.Status != "aborted" {
+ t.Fatalf("result = %+v, want cancellation", result)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("cancellation blocked behind the full message buffer")
+ }
+ return
+ }
+ // Without backpressure the process completes here, having discarded
+ // most tool events. A live consumer may temporarily pause just like this.
+ select {
+ case <-session.Result:
+ t.Fatal("execution completed while its tool events could not be delivered")
+ case <-time.After(100 * time.Millisecond):
+ }
+ uses, results := map[string]bool{}, map[string]bool{}
+ for message := range session.Messages {
+ var seen map[string]bool
+ switch message.Type {
+ case MessageToolUse:
+ seen = uses
+ case MessageToolResult:
+ seen = results
+ default:
+ continue
+ }
+ if message.CallID == "" || seen[message.CallID] {
+ t.Fatalf("missing or duplicate call identity: %+v", message)
+ }
+ seen[message.CallID] = true
+ }
+ if len(uses) != calls || !reflect.DeepEqual(uses, results) {
+ t.Fatalf("tool events lost: uses=%d results=%d, want %d matched pairs", len(uses), len(results), calls)
+ }
+ if result := <-session.Result; result.Status != "completed" {
+ t.Fatalf("unexpected result: %+v", result)
+ }
+ })
+ }
+}
+
+func TestAntigravityToolInputNormalization(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name, tool string
+ input, want map[string]any
+ }{
+ {"shell command", "run_command", map[string]any{"CommandLine": "echo hello", "Cwd": "/workspace"}, map[string]any{"Cwd": "/workspace", "command": "echo hello"}},
+ {"file read", "view_file", map[string]any{"AbsolutePath": "/workspace/a.go"}, map[string]any{"file_path": "/workspace/a.go"}},
+ {
+ name: "file write", tool: "write_to_file",
+ input: map[string]any{"TargetFile": "/workspace/a.go", "CodeContent": "package main\n"},
+ want: map[string]any{"file_path": "/workspace/a.go", "content": "package main\n"},
+ },
+ {
+ name: "file edit", tool: "replace_file_content",
+ input: map[string]any{"TargetFile": "/workspace/a.go", "TargetContent": "before", "ReplacementContent": "after"},
+ want: map[string]any{"file_path": "/workspace/a.go", "old_string": "before", "new_string": "after"},
+ },
+ {
+ name: "empty file", tool: "write_to_file",
+ input: map[string]any{"TargetFile": "/workspace/empty.go", "CodeContent": ""},
+ want: map[string]any{"file_path": "/workspace/empty.go", "content": ""},
+ },
+ {
+ name: "delete text", tool: "replace_file_content",
+ input: map[string]any{"TargetFile": "/workspace/a.go", "TargetContent": "before", "ReplacementContent": ""},
+ want: map[string]any{"file_path": "/workspace/a.go", "old_string": "before", "new_string": ""},
+ },
+ {
+ name: "insert text", tool: "replace_file_content",
+ input: map[string]any{"TargetContent": "", "ReplacementContent": "after"},
+ want: map[string]any{"old_string": "", "new_string": "after"},
+ },
+ {
+ name: "content collisions retained", tool: "custom",
+ input: map[string]any{"CodeContent": "other", "content": "", "TargetContent": "before", "old_string": nil, "ReplacementContent": "after", "new_string": false},
+ want: map[string]any{"CodeContent": "other", "content": "", "TargetContent": "before", "old_string": nil, "ReplacementContent": "after", "new_string": false},
+ },
+ {
+ name: "invalid content retained", tool: "custom",
+ input: map[string]any{"CodeContent": 123, "TargetContent": nil, "ReplacementContent": false},
+ want: map[string]any{"CodeContent": 123, "TargetContent": nil, "ReplacementContent": false},
+ },
+ {
+ name: "replacement chunks remain opaque", tool: "multi_replace_file_content",
+ input: map[string]any{"TargetFile": "/workspace/a.go", "ReplacementChunks": []any{map[string]any{"TargetContent": "before", "ReplacementContent": ""}}},
+ want: map[string]any{"file_path": "/workspace/a.go", "ReplacementChunks": []any{map[string]any{"TargetContent": "before", "ReplacementContent": ""}}},
+ },
+ {"empty command retained", "run_command", map[string]any{"CommandLine": ""}, map[string]any{"CommandLine": ""}},
+ {"empty path retained", "view_file", map[string]any{"AbsolutePath": ""}, map[string]any{"AbsolutePath": ""}},
+ {"canonical fields win", "run_command", map[string]any{"CommandLine": "other", "command": "original", "AbsolutePath": "other", "file_path": "original"}, map[string]any{"CommandLine": "other", "command": "original", "AbsolutePath": "other", "file_path": "original"}},
+ {"explicit canonical null retained", "run_command", map[string]any{"CommandLine": "other", "command": nil}, map[string]any{"CommandLine": "other", "command": nil}},
+ {"invalid aliases ignored", "custom", map[string]any{"CommandLine": 123, "AbsolutePath": nil, "TargetFile": ""}, map[string]any{"CommandLine": 123, "AbsolutePath": nil, "TargetFile": ""}},
+ {"unknown parameters retained", "custom", map[string]any{"custom": true}, map[string]any{"custom": true}},
+ {"missing parameters", "run_command", nil, nil},
+ }
+ for _, tt := range tests {
+ for _, state := range []string{"ACTIVE", "DONE"} {
+ t.Run(tt.name+"/"+state, func(t *testing.T) {
+ before, err := json.Marshal(tt.input)
+ if err != nil {
+ t.Fatal(err)
+ }
+ index := 0
+ step := antigravityStreamStepUpdate{
+ StepIndex: &index, State: state, StepType: "tool", ToolName: tt.tool,
+ ToolInfo: &antigravityStreamTool{Parameters: tt.input},
+ }
+ messages := antigravityToolMessages(&step, make(map[int]antigravityToolState))
+ if len(messages) == 0 || messages[0].Type != MessageToolUse || !reflect.DeepEqual(messages[0].Input, tt.want) {
+ t.Fatalf("messages = %+v, want tool use input %#v", messages, tt.want)
+ }
+ after, err := json.Marshal(tt.input)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(before) != string(after) {
+ t.Fatalf("provider parameters mutated: %s -> %s", before, after)
+ }
+ if got := antigravityToolInput(messages[0].Input); !reflect.DeepEqual(got, tt.want) {
+ t.Fatalf("normalization is not idempotent: %#v", got)
+ }
+ })
+ }
+ }
+}
+
+func TestAntigravityToolMessages(t *testing.T) {
+ t.Parallel()
+ verboseOutput := strings.Repeat("x", 9000)
+ tests := []struct {
+ name string
+ steps []string
+ want []Message
+ }{
+ {
+ name: "repeated and interleaved snapshots",
+ steps: []string{
+ `{"step_index":0,"state":"ACTIVE","step_type":"tool","tool_name":"read_file","tool_info":{"parameters":{"path":"a.go"}}}`,
+ `{"step_index":0,"state":"ACTIVE","step_type":"tool","tool_name":"read_file"}`,
+ `{"step_index":1,"state":"ACTIVE","step_type":"tool","tool_info":{"name":"run_command"}}`,
+ `{"step_index":1,"state":"DONE","step_type":"tool","tool_info":{"output":"ok"}}`,
+ `{"step_index":0,"state":"DONE","step_type":"tool","tool_info":{"output":{"text":"source"}}}`,
+ `{"step_index":0,"state":"DONE","step_type":"tool","tool_name":"read_file"}`,
+ `{"step_index":1,"state":"ACTIVE","step_type":"tool","tool_name":"run_command"}`,
+ },
+ want: []Message{
+ {Type: MessageToolUse, CallID: "agy-step-0", Tool: "read_file", Input: map[string]any{"path": "a.go"}},
+ {Type: MessageToolUse, CallID: "agy-step-1", Tool: "run_command"},
+ {Type: MessageToolResult, CallID: "agy-step-1", Tool: "run_command", Output: "ok"},
+ {Type: MessageToolResult, CallID: "agy-step-0", Tool: "read_file", Output: `{"text":"source"}`},
+ },
+ },
+ {
+ name: "done only tool failure remains a tool result",
+ steps: []string{`{"step_index":2,"state":"DONE","step_type":"tool","tool_info":{"name":"run_command","output":"partial","error":{"type":"exit","message":"exit 1"}}}`},
+ want: []Message{
+ {Type: MessageToolUse, CallID: "agy-step-2", Tool: "run_command"},
+ {Type: MessageToolResult, CallID: "agy-step-2", Tool: "run_command", Output: "Tool error: exit: exit 1\npartial"},
+ },
+ },
+ {
+ name: "failure detail survives prefix truncation of verbose output",
+ steps: []string{fmt.Sprintf(`{"step_index":2,"state":"DONE","step_type":"tool","tool_name":"run_command","tool_info":{"output":%q,"error":{"message":"exit 1"}}}`, verboseOutput)},
+ want: []Message{
+ {Type: MessageToolUse, CallID: "agy-step-2", Tool: "run_command"},
+ {Type: MessageToolResult, CallID: "agy-step-2", Tool: "run_command", Output: "Tool error: exit 1\n" + verboseOutput},
+ },
+ },
+ {
+ name: "missing metadata can arrive later",
+ steps: []string{
+ `{"step_index":3,"state":"ACTIVE","step_type":"tool"}`,
+ `{"step_index":3,"state":"DONE","step_type":"tool","tool_name":"list_dir","tool_info":{"output":null}}`,
+ },
+ want: []Message{
+ {Type: MessageToolUse, CallID: "agy-step-3", Tool: "list_dir"},
+ {Type: MessageToolResult, CallID: "agy-step-3", Tool: "list_dir"},
+ },
+ },
+ {
+ name: "ignore missing indices unknown states and non tools",
+ steps: []string{
+ `{"state":"DONE","step_type":"tool","tool_name":"read_file"}`,
+ `{"step_index":-1,"state":"DONE","step_type":"tool","tool_name":"read_file"}`,
+ `{"step_index":0,"state":"QUEUED","step_type":"tool","tool_name":"read_file"}`,
+ `{"step_index":0,"state":"DONE","step_type":"agent_response","text_delta":"hello"}`,
+ },
+ },
+ {
+ name: "unfinished tool is not fabricated as complete",
+ steps: []string{`{"step_index":4,"state":"ACTIVE","step_type":"tool","tool_name":"read_file"}`},
+ want: []Message{{Type: MessageToolUse, CallID: "agy-step-4", Tool: "read_file"}},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ states := make(map[int]antigravityToolState)
+ var got []Message
+ for _, raw := range tt.steps {
+ var step antigravityStreamStepUpdate
+ if err := json.Unmarshal([]byte(raw), &step); err != nil {
+ t.Fatal(err)
+ }
+ got = append(got, antigravityToolMessages(&step, states)...)
+ }
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Fatalf("messages = %#v, want %#v", got, tt.want)
+ }
+ })
+ }
+}
+
+// The fake stays alive until the test receives its tool event. This proves
+// delivery is live, rather than reconstructed after process completion.
+func TestAntigravityToolsStreamBeforeProcessExit(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ release := filepath.Join(dir, "release")
+ fakePath := filepath.Join(dir, "agy")
+ writeTestExecutable(t, fakePath, []byte(fmt.Sprintf(`#!/bin/sh
+printf '%%s\n' '{"event":"step_update","step_update":{"step_index":4,"state":"ACTIVE","step_type":"tool","tool_name":"run_command","tool_info":{"name":"run_command","parameters":{"CommandLine":"echo hello"}}}}'
+while [ ! -f %q ]; do sleep 0.01; done
+printf '%%s\n' '{"event":"step_update","step_update":{"step_index":4,"state":"DONE","step_type":"tool","tool_name":"run_command","tool_info":{"output":"hello\n"}}}'
+printf '%%s\n' '{"event":"result","result":{"status":"SUCCESS","response":"Finished"}}'
+`, release)))
+ backend, err := New("antigravity", Config{ExecutablePath: fakePath, Logger: quietAntigravityLogger()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "ignored", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var use, result *Message
+ for msg := range session.Messages {
+ switch msg.Type {
+ case MessageToolUse:
+ if use != nil {
+ t.Fatal("duplicate tool use")
+ }
+ copy := msg
+ use = &copy
+ if err := os.WriteFile(release, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ case MessageToolResult:
+ copy := msg
+ result = &copy
+ }
+ }
+ if use == nil || result == nil {
+ t.Fatalf("missing live tool lifecycle: use=%+v result=%+v", use, result)
+ }
+ if use.Tool != "run_command" || use.Input["command"] != "echo hello" || use.CallID == "" {
+ t.Fatalf("unexpected tool use: %+v", use)
+ }
+ if _, exists := use.Input["CommandLine"]; exists {
+ t.Fatalf("provider command was duplicated in normalized input: %+v", use.Input)
+ }
+ if result.CallID != use.CallID || result.Tool != use.Tool || result.Output != "hello\n" {
+ t.Fatalf("unexpected tool result: %+v", result)
+ }
+ if got := <-session.Result; got.Status != "completed" || got.Output != "Finished" {
+ t.Fatalf("unexpected execution result: %+v", got)
+ }
+}