Skip to content

Commit e576e2d

Browse files
committed
fix: halt failed computer batches in the chat loop and drop the batch-end screenshot
Match the Anthropic SDK tool runners: the chat loop, not the computer tool, stops the later computer calls of a step after one fails or is rejected before it runs. Halted calls get an error result and are not billed. The computer tool keeps no per-step state. With computer_toolset_20260801, every action except screenshot answers with text, and no screenshot follows the last call of a batch. The model asks for a screenshot when it needs one. Older versions still screenshot after every action. Bump the fantasy replace to 7882f906a89a (coder/fantasy#82).
1 parent 0cdb545 commit e576e2d

9 files changed

Lines changed: 324 additions & 310 deletions

File tree

‎coderd/x/chatd/chatd_test.go‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10326,14 +10326,14 @@ func TestComputerUseSubagentToolsAndModel(t *testing.T) {
1032610326
"computer use subagent should NOT get the advisor guidance")
1032710327
}
1032810328

10329-
// 7. Verify both batch actions ran in order and only the last one
10330-
// was followed by a screenshot.
10329+
// 7. Verify both batch actions ran in order and no screenshot
10330+
// followed them.
1033110331
desktopMu.Lock()
1033210332
actions := append([]string(nil), desktopActions...)
1033310333
desktopMu.Unlock()
1033410334
clickIndex := slices.Index(actions, "left_click")
1033510335
require.GreaterOrEqual(t, clickIndex, 0, "desktop actions: %v", actions)
10336-
require.Equal(t, []string{"left_click", "type", "screenshot"}, actions[clickIndex:])
10336+
require.Equal(t, []string{"left_click", "type"}, actions[clickIndex:])
1033710337

1033810338
// 8. Verify the follow-up request replays both member calls and
1033910339
// their results as toolset members.
@@ -10380,9 +10380,10 @@ func TestComputerUseSubagentToolsAndModel(t *testing.T) {
1038010380
require.Contains(t, results, id)
1038110381
require.Equal(t, "computer", results[id].ToolsetName, "tool_result %s", id)
1038210382
}
10383-
require.Contains(t, string(results["toolu_click"].Content), "left_click action performed")
10384-
require.NotContains(t, string(results["toolu_click"].Content), `"image"`)
10385-
require.Contains(t, string(results["toolu_type"].Content), `"image"`)
10383+
for id, action := range map[string]string{"toolu_click": "left_click", "toolu_type": "type"} {
10384+
require.Contains(t, string(results[id].Content), action+" action performed")
10385+
require.NotContains(t, string(results[id].Content), `"image"`)
10386+
}
1038610387

1038710388
// 9. Verify the child chat has Mode = computer_use in
1038810389
// the DB.

‎coderd/x/chatd/chatloop/chatloop.go‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,9 @@ type ExecuteLocalToolsOptions struct {
155155
// ObservedToolCalls optionally carries the step's full assistant
156156
// tool-call batch, including calls denied before execution, so
157157
// step observers account for denied siblings that derivation will
158-
// still count. Defaults to ToolCalls.
158+
// still count, and halting tools skip the calls after a denied
159+
// call. Calls missing from ToolCalls count as denied. Defaults to
160+
// ToolCalls.
159161
ObservedToolCalls []fantasy.ToolCallContent
160162

161163
ExclusiveToolNames map[string]bool
@@ -1328,14 +1330,34 @@ func (b *toolBatch) run(ctx context.Context, localToolCalls []fantasy.ToolCallCo
13281330
}
13291331
b.notifyStepToolResultObservers(localToolCalls, observed, settled)
13301332

1333+
// failed holds the halting tools with a call that failed in this batch.
1334+
failed := make(map[string]bool)
1335+
afterRejection := b.callsAfterRejection(localToolCalls, observed)
13311336
for _, i := range serialIndexes {
1337+
tc := localToolCalls[i]
1338+
name := b.resolve(tc.ToolName)
1339+
haltedText, halts := b.haltedCallError(name)
1340+
if halts && (failed[name] || afterRejection[tc.ToolCallID]) {
1341+
// The call never runs, so it records no start and is not billed.
1342+
executions[i].content = fantasy.ToolResultContent{
1343+
ToolCallID: tc.ToolCallID,
1344+
ToolName: tc.ToolName,
1345+
Result: fantasy.ToolResultOutputContentError{Error: xerrors.New(haltedText)},
1346+
}
1347+
executions[i].interval.End = clockNow(b.opts.Clock)
1348+
recordToolResultMetrics(b.opts.Metrics, b.provider, b.model, executions[i].content)
1349+
continue
1350+
}
13321351
// Stamp serial calls at launch, not batch start.
13331352
startedAt := clockNow(b.opts.Clock)
13341353
executions[i].interval.Start = startedAt
13351354
if recorder != nil {
13361355
recorder.RecordStart(i, startedAt)
13371356
}
1338-
runCall(i, localToolCalls[i])
1357+
runCall(i, tc)
1358+
if _, isErr := executions[i].content.Result.(fantasy.ToolResultOutputContentError); halts && isErr {
1359+
failed[name] = true
1360+
}
13391361
}
13401362

13411363
return executions
@@ -1589,6 +1611,48 @@ func isToolActive(name string, activeTools []string) bool {
15891611
// must execute in tool-call order because they claim from shared state.
15901612
type serialToolCaller interface{ SerialToolCalls() bool }
15911613

1614+
// haltingToolCaller is implemented by serial tools whose calls in one step
1615+
// build on each other, for example computer actions that the model plans
1616+
// against one screen. After a call of the tool fails, or is rejected before
1617+
// it runs, no later call of the tool runs in the step. Each later call gets
1618+
// an error result with the returned text. ok is false if the tool does not
1619+
// halt.
1620+
type haltingToolCaller interface {
1621+
HaltedToolCallError() (text string, ok bool)
1622+
}
1623+
1624+
// haltedCallError returns the error text for the calls of the tool name that
1625+
// follow a failed call, and false if the tool does not halt.
1626+
func (b *toolBatch) haltedCallError(name string) (string, bool) {
1627+
halting, ok := b.tools[name].(haltingToolCaller)
1628+
if !ok {
1629+
return "", false
1630+
}
1631+
return halting.HaltedToolCallError()
1632+
}
1633+
1634+
// callsAfterRejection returns the IDs of the calls that follow, in observed
1635+
// order, a rejected call of the same tool. Observed calls missing from calls
1636+
// were rejected before execution.
1637+
func (b *toolBatch) callsAfterRejection(calls, observed []fantasy.ToolCallContent) map[string]bool {
1638+
executed := make(map[string]bool, len(calls))
1639+
for _, tc := range calls {
1640+
executed[tc.ToolCallID] = true
1641+
}
1642+
rejectedTools := make(map[string]bool)
1643+
after := make(map[string]bool)
1644+
for _, tc := range observed {
1645+
name := b.resolve(tc.ToolName)
1646+
switch {
1647+
case !executed[tc.ToolCallID]:
1648+
rejectedTools[name] = true
1649+
case rejectedTools[name]:
1650+
after[tc.ToolCallID] = true
1651+
}
1652+
}
1653+
return after
1654+
}
1655+
15921656
// stepToolCallObserver is implemented by tools that need to see every
15931657
// tool-call name in the step before any call executes, for example so
15941658
// find_tools can charge same-step direct calls against its budget.

‎coderd/x/chatd/chatloop/chatloop_run_internal_test.go‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,6 +1129,108 @@ func TestExecuteToolsReconcilesResultsBeforeSerialCalls(t *testing.T) {
11291129
require.Equal(t, "1", results[0].content.ToolCallID, "results keep original call order")
11301130
}
11311131

1132+
type haltingMarkerTool struct{ fantasy.AgentTool }
1133+
1134+
func (haltingMarkerTool) SerialToolCalls() bool { return true }
1135+
1136+
func (haltingMarkerTool) HaltedToolCallError() (string, bool) { return "halted", true }
1137+
1138+
func TestExecuteToolsHaltsToolAfterFailedCall(t *testing.T) {
1139+
t.Parallel()
1140+
1141+
const (
1142+
succeed = `{}`
1143+
fail = `{"fail":true}`
1144+
)
1145+
halting := func(id, input string) fantasy.ToolCallContent {
1146+
return fantasy.ToolCallContent{ToolCallID: id, ToolName: "halting_tool", Input: input}
1147+
}
1148+
other := fantasy.ToolCallContent{ToolCallID: "3", ToolName: "other_tool", Input: succeed}
1149+
1150+
tests := []struct {
1151+
name string
1152+
observed []fantasy.ToolCallContent
1153+
executed []fantasy.ToolCallContent
1154+
wantRan []string
1155+
// wantResults maps each executed call ID to its result text.
1156+
wantResults map[string]string
1157+
}{
1158+
{
1159+
name: "FailedCall",
1160+
executed: []fantasy.ToolCallContent{halting("1", succeed), halting("2", fail), other, halting("4", succeed)},
1161+
wantRan: []string{"1", "2", "3"},
1162+
wantResults: map[string]string{"1": "ok", "2": "error: failed", "3": "ok", "4": "error: halted"},
1163+
},
1164+
{
1165+
name: "RejectedCall",
1166+
observed: []fantasy.ToolCallContent{halting("1", succeed), halting("2", succeed), other, halting("4", succeed)},
1167+
executed: []fantasy.ToolCallContent{halting("1", succeed), other, halting("4", succeed)},
1168+
wantRan: []string{"1", "3"},
1169+
wantResults: map[string]string{"1": "ok", "3": "ok", "4": "error: halted"},
1170+
},
1171+
}
1172+
for _, tt := range tests {
1173+
t.Run(tt.name, func(t *testing.T) {
1174+
t.Parallel()
1175+
1176+
var mu sync.Mutex
1177+
var ran []string
1178+
record := func(id string) {
1179+
mu.Lock()
1180+
defer mu.Unlock()
1181+
ran = append(ran, id)
1182+
}
1183+
haltingTool := haltingMarkerTool{AgentTool: fantasy.NewAgentTool(
1184+
"halting_tool",
1185+
"fails when asked",
1186+
func(_ context.Context, input struct {
1187+
Fail bool `json:"fail"`
1188+
}, call fantasy.ToolCall,
1189+
) (fantasy.ToolResponse, error) {
1190+
record(call.ID)
1191+
if input.Fail {
1192+
return fantasy.NewTextErrorResponse("failed"), nil
1193+
}
1194+
return fantasy.NewTextResponse("ok"), nil
1195+
},
1196+
)}
1197+
otherTool := serialMarkerTool{AgentTool: fantasy.NewAgentTool(
1198+
"other_tool",
1199+
"runs between halting calls",
1200+
func(_ context.Context, _ struct{}, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
1201+
record(call.ID)
1202+
return fantasy.NewTextResponse("ok"), nil
1203+
},
1204+
)}
1205+
1206+
outcome, err := ExecuteLocalTools(context.Background(), ExecuteLocalToolsOptions{
1207+
Tools: []fantasy.AgentTool{haltingTool, otherTool},
1208+
ToolCalls: tt.executed,
1209+
ObservedToolCalls: tt.observed,
1210+
Clock: quartz.NewReal(),
1211+
})
1212+
require.NoError(t, err)
1213+
1214+
require.Equal(t, tt.wantRan, ran)
1215+
results := make(map[string]string)
1216+
for _, content := range outcome.Content {
1217+
result, ok := content.(fantasy.ToolResultContent)
1218+
require.True(t, ok, "%T", content)
1219+
switch output := result.Result.(type) {
1220+
case fantasy.ToolResultOutputContentText:
1221+
results[result.ToolCallID] = output.Text
1222+
case fantasy.ToolResultOutputContentError:
1223+
results[result.ToolCallID] = "error: " + output.Error.Error()
1224+
default:
1225+
t.Fatalf("unexpected result %T", result.Result)
1226+
}
1227+
}
1228+
require.Equal(t, tt.wantResults, results)
1229+
require.Equal(t, len(tt.wantRan), outcome.BatchBilledCalls, "halted calls are not billed")
1230+
})
1231+
}
1232+
}
1233+
11321234
func TestExecuteToolsSerialToolCallOrder(t *testing.T) {
11331235
t.Parallel()
11341236

0 commit comments

Comments
 (0)