Repository navigation
feat(agent): align Go agent behavior with Python (except retrieval component) - #16225
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughThis PR updates Stagehand packaging, canvas normalization and compilation, agent runtime events and reset handling, component execution and routing behavior, related tests, and web canvas/chat rendering. ChangesAgent runtime and canvas flow
Sequence Diagram(s)sequenceDiagram
participant ChatUI
participant AgentHandler
participant AgentService
participant Runner
participant Workflow
ChatUI->>AgentHandler: AgentChatCompletions(query/messages)
AgentHandler->>AgentService: RunAgent(canvasID, userInput, sessionID)
AgentService->>Runner: Run(root, buildRunFunc)
Runner->>Workflow: invoke or resume workflow
Workflow-->>Runner: message / waiting_for_user / done events
Runner-->>AgentHandler: RunEvent stream
AgentHandler-->>ChatUI: SSE data frames + [DONE]
sequenceDiagram
participant BrowserComponent
participant TenantLLMResolver
participant StagehandRuntime
participant StagehandClient
BrowserComponent->>TenantLLMResolver: resolve llm_id credentials
TenantLLMResolver-->>BrowserComponent: model config
BrowserComponent->>StagehandRuntime: RunExtract(url, instruction, schema)
StagehandRuntime->>StagehandClient: start session and extract
StagehandClient-->>StagehandRuntime: JSON result
StagehandRuntime-->>BrowserComponent: raw JSON
Estimated code review effort🎯 5 (Critical) | ⏱️ ~110 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
Note
Due to the large number of review comments, Critical severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
web/src/components/next-message-item/group-button.tsx (1)
84-89:⚠️ Potential issue | 🟠 MajorAdd onClick handler to ToggleGroupItem for keyboard support.
The copy action is handled by
react-copy-to-clipboardvia click events on a nested span. When the ToggleGroupItem is keyboard-activated (Enter/Space), it may toggle without copying. Wire the copy handler to the ToggleGroupItem itself via onClick, matching the pattern used for other items in the group (see lines 92, 106, 109, 115, 120, 127).Also applies to: 192-193
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/next-message-item/group-button.tsx` around lines 84 - 89, The ToggleGroupItem wrapping the CopyToClipboard component is missing an onClick handler, which means keyboard activation (Enter/Space) may toggle the item without triggering the copy action. Add an onClick handler to the ToggleGroupItem that calls the copy function directly, matching the pattern already implemented for other toggle items in the same group (such as those at lines 92, 106, 109, 115, 120, 127). Also apply the same fix to the duplicate instance mentioned at lines 192-193 to ensure consistent keyboard support across all copy buttons in the component.internal/agent/component/llm.go (1)
226-232:⚠️ Potential issue | 🟠 Major | ⚡ Quick winWire the new penalty fields into the default chat config.
presence_penaltyandfrequency_penaltyare parsed intoChatInvokeRequest, buteinoChatInvokeronly copies temperature/top-p/max_tokens intomodels.ChatConfig; the default invoker therefore ignores the new parameters.Proposed fix, assuming ChatConfig exposes these fields
chatCfg := &models.ChatConfig{ - Temperature: req.Temperature, - TopP: req.TopP, - MaxTokens: req.MaxTokens, + Temperature: req.Temperature, + TopP: req.TopP, + PresencePenalty: req.PresencePenalty, + FrequencyPenalty: req.FrequencyPenalty, + MaxTokens: req.MaxTokens, }If
models.ChatConfigdoes not expose these fields yet, add the mapping in the wrapper/driver layer that builds the provider request.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/llm.go` around lines 226 - 232, The chatCfg variable creation in this code block is missing the presence_penalty and frequency_penalty fields that are available in the ChatInvokeRequest. Add PresencePenalty and FrequencyPenalty fields to the ChatConfig struct initialization by mapping them from the corresponding req fields (req.PresencePenalty and req.FrequencyPenalty), similar to how Temperature, TopP, and MaxTokens are currently being mapped. If models.ChatConfig does not already expose these fields, add them to the ChatConfig struct definition in the models package first.internal/agent/sandbox/self_managed.go (2)
300-312:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDo not let
present:falsemask the stdout fallback.
handleRunand likely executor defaults can return a non-empty result map like{"present": false, ...}. Withlen(raw.Result) > 0, that overwrites theExtractStructuredResult(raw.Stdout)fallback even when the HTTP result explicitly says no structured result was present.🐛 Proposed fix
- // Prefer the server-side result whenever it is present in the - // HTTP payload. executor_manager already parsed the canonical - // result marker; this is the most reliable source of truth. - if len(raw.Result) > 0 { + // Prefer the server-side result only when it actually contains + // a parsed structured value; otherwise keep the stdout fallback. + if present, _ := raw.Result["present"].(bool); present { + structured = raw.Result + } else if _, hasPresent := raw.Result["present"]; !hasPresent && len(raw.Result) > 0 { structured = raw.Result }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/sandbox/self_managed.go` around lines 300 - 312, The condition `if len(raw.Result) > 0` incorrectly prioritizes the HTTP result even when it contains a map like `{"present": false, ...}`, which explicitly indicates no structured result was present. This causes the stdout fallback from `ExtractStructuredResult(raw.Stdout)` to be overwritten incorrectly. Modify the condition to check not only that `raw.Result` is non-empty but also verify that it actually contains a valid structured result (check for a "present" field being true or similar indicator) before preferring it over the stdout fallback.
235-249:⚠️ Potential issue | 🟠 MajorApply the per-call timeout to the context, not the payload—executor_manager ignores timeout fields.
timeoutSecis validated and defaulted into a localtimeoutvariable (lines 235–240), but this value is never used. The context passed top.helper.Do()(line 266) is unchanged, so the per-call timeout does not affect the request.The Python
CodeExecutionRequestmodel accepts onlycode_b64,language, andarguments—no timeout field. The executor_manager uses a fixedTIMEOUTfrom the environment variableSANDBOX_TIMEOUT(default 10 seconds).To honor the per-call timeout, wrap the context before the request:
Proposed fix
timeout, err := validateTimeout(timeoutSec) if err != nil { return nil, err } if timeout == 0 { timeout = int(p.timeout.Seconds()) } + ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second) + defer cancel() payload := map[string]any{🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/sandbox/self_managed.go` around lines 235 - 249, The timeout variable computed by validateTimeout is never applied to the context passed to p.helper.Do(), so the per-call timeout setting is ignored. Remove the unused timeout variable assignment and instead use context.WithTimeout() to wrap the context with the computed timeout value before passing it to the p.helper.Do() call. This ensures the per-call timeout is actually enforced on the request, since the Python executor_manager does not accept a timeout field in the payload.
🟡 Minor comments (11)
internal/handler/agent_wait_for_user_test.go-388-389 (1)
388-389:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAllow the true done-only stream shape in this assertion.
Line 388 currently rejects a valid one-frame
[DONE]stream, which contradicts the updated contract comment on Lines 376-378.Suggested fix
- if len(frames) < 1 || (!sawMessage && len(frames) != 2) { + if len(frames) < 1 || (!sawMessage && len(frames) != 1 && len(frames) != 2) { t.Errorf("expected either a message frame or a minimal clean done stream, got frames: %v", frames) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/agent_wait_for_user_test.go` around lines 388 - 389, The assertion on line 388 in the test file currently rejects a valid one-frame [DONE] stream by requiring exactly 2 frames when no message was observed (!sawMessage && len(frames) != 2). Update this condition to allow either 1 or 2 frames when no message is observed, since according to the contract comment on lines 376-378, both a true done-only stream (1 frame) and a minimal clean done stream (2 frames) are valid. Change the logic to permit len(frames) to be 1 or 2 when sawMessage is false, rather than requiring it to be exactly 2.internal/agent/component/string_transform_test.go-90-94 (1)
90-94:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDon’t ignore constructor errors in this test
Ignoring
NewStringTransformComponenterrors can mask setup failures and produce noisier downstream failures.Suggested fix
- c, _ := NewStringTransformComponent(map[string]any{ + c, err := NewStringTransformComponent(map[string]any{ "method": "merge", "delimiters": []string{","}, "script": "{index}: {item}", }) + if err != nil { + t.Fatalf("NewStringTransformComponent: %v", err) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/string_transform_test.go` around lines 90 - 94, The NewStringTransformComponent constructor call in the test is ignoring the error return value using the blank identifier, which can mask setup failures and cause confusing failures later in the test. Instead of using _, capture the error return value and add an assertion to verify that the error is nil, or handle it appropriately to ensure the constructor succeeded before proceeding with the test.internal/agent/component/list_operations_test.go-497-520 (1)
497-520:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUnsupported-operation doc assertions are incomplete
Line 499’s comment includes unsupported
takeanddeduplicate, but the banned list assertion does not check them. This weakens the UI/doc guard.Suggested test adjustment
- for _, banned := range []string{"slice", "shuffle", "reverse"} { + for _, banned := range []string{"slice", "shuffle", "take", "reverse", "deduplicate"} { if strings.Contains(doc["operations"], banned) { t.Errorf("Inputs()[operations] doc must not mention %q (not in allowlist): %q", banned, doc["operations"]) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/list_operations_test.go` around lines 497 - 520, The comment in TestListOperations_InputsDocMatchesAllowlist mentions five unsupported operations (slice, shuffle, take, reverse, deduplicate), but the banned list assertion only checks for three of them (slice, shuffle, reverse). Add "take" and "deduplicate" to the banned slice in the loop that validates these operations are not mentioned in the Inputs() docstring to make the assertion complete and match the documented intent.internal/agent/component/list_operations_test.go-215-305 (1)
215-305:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winTiebreak behavior is described but not actually exercised
The
sort_by="score,title"case currently has uniquescorevalues, sotitlenever participates in ordering. That leaves the tiebreak path unverified.Suggested test adjustment
state.Outputs["cpn_0"] = map[string]any{ "rows": []any{ map[string]any{"id": 1, "score": 0.91, "title": "Alpha"}, map[string]any{"id": 2, "score": 0.88, "title": "Beta"}, + map[string]any{"id": 4, "score": 0.88, "title": "Aardvark"}, map[string]any{"id": 3, "score": 0.76, "title": "Gamma"}, }, } @@ wantTiebreak := []any{ map[string]any{"id": 3, "score": 0.76, "title": "Gamma"}, + map[string]any{"id": 4, "score": 0.88, "title": "Aardvark"}, map[string]any{"id": 2, "score": 0.88, "title": "Beta"}, map[string]any{"id": 1, "score": 0.91, "title": "Alpha"}, }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/list_operations_test.go` around lines 215 - 305, The tiebreak test case with sort_by="score,title" currently has unique score values (0.91, 0.88, 0.76) in the test data, so the title field never participates in ordering. To properly exercise the tiebreak logic in the TestListOperations_SortByFieldList function, modify the test data to include at least two rows with identical score values but different titles, so that the secondary sort_by field (title) is actually used for ordering and the tiebreak behavior can be verified.internal/agent/component/variable_aggregator.go-250-250 (1)
250-250:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
groupsis documented as an input override butInvoke()does not consume it.
Inputs()now advertises agroupsruntime override, but the implementation only readsinputs["variables"]. This can mislead callers into sending a no-op field.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/variable_aggregator.go` at line 250, The Inputs() method advertises a groups runtime override but the Invoke() method does not actually read or use inputs["groups"]. Update the Invoke() method to consume the groups input field when provided, similar to how it handles inputs["variables"]. This will ensure the documented interface matches the actual implementation and callers can properly override the group configuration at runtime.internal/agent/component/stagehand_runtime_test.go-195-199 (1)
195-199:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winConcurrent cache tests should assert
clientForerrors instead of discarding them.Both concurrent tests ignore per-goroutine errors, so runtime failures can be missed while assertions still pass.
✅ Suggested tightening for concurrent assertions
var wg sync.WaitGroup var calls atomic.Int32 + errCh := make(chan error, N) for i := 0; i < N; i++ { wg.Add(1) go func() { defer wg.Done() - _, _ = r.clientFor(req) + _, err := r.clientFor(req) + errCh <- err calls.Add(1) }() } wg.Wait() + close(errCh) + for err := range errCh { + if err != nil { + t.Fatalf("clientFor: %v", err) + } + } @@ const N = 32 var wg sync.WaitGroup + errCh := make(chan error, N) for i := 0; i < N; i++ { i := i wg.Add(1) go func() { defer wg.Done() - _, _ = r.clientFor(RunTaskRequest{ + _, err := r.clientFor(RunTaskRequest{ ModelName: "openai/gpt-4o", BaseURL: "https://api.openai.com/v1", APIKey: "sk-" + string(rune('a'+i%26)) + string(rune('A'+(i/26)%26)), }) + errCh <- err }() } wg.Wait() + close(errCh) + for err := range errCh { + if err != nil { + t.Fatalf("clientFor: %v", err) + } + }Also applies to: 223-227
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/stagehand_runtime_test.go` around lines 195 - 199, The concurrent goroutines in the test are ignoring errors returned by the clientFor method call by using blank identifiers. Instead of discarding these errors with _, _, capture the error return value from r.clientFor(req) in both goroutine blocks (around lines 195-199 and 223-227) and assert that no errors occur, ensuring runtime failures are caught instead of being silently missed during test execution.internal/agent/component/data_operations.go-263-268 (1)
263-268:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Inputs()["operations"]documents names that the component does not accept.The docs list
filter/update/remove/rename, butCheck()only acceptsfilter_values/append_or_update/remove_keys/rename_keys(plusselect_keys,literal_eval,combine).🧭 Suggested fix for input-surface docs
- "operations": "Operation name: literal_eval, select_keys, filter, update, remove, rename. Overrides DSL param.", + "operations": "Operation name: literal_eval, select_keys, combine, filter_values, append_or_update, remove_keys, rename_keys. Overrides DSL param.", @@ - "filter_values": "List of {key, op, value} filters (for filter operation). Overrides DSL param.", - "updates": "List of {key, value} updates (for update operation). Overrides DSL param.", - "remove_keys": "List of keys to remove (for remove operation). Overrides DSL param.", - "rename_keys": "List of {old_key, new_key} mappings (for rename operation). Overrides DSL param.", + "filter_values": "List of {key, op, value} filters (for filter_values operation). Overrides DSL param.", + "updates": "List of {key, value} updates (for append_or_update operation). Overrides DSL param.", + "remove_keys": "List of keys to remove (for remove_keys operation). Overrides DSL param.", + "rename_keys": "List of {old_key, new_key} mappings (for rename_keys operation). Overrides DSL param.",🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/data_operations.go` around lines 263 - 268, The documentation string for the "operations" input in the Inputs() method lists operation names that do not match what the Check() method actually accepts. Update the "operations" key documentation to list only the operation names that Check() truly validates against. Instead of documenting `filter`, `update`, `remove`, and `rename`, document the actual parameter names that Check() accepts such as `filter_values`, `append_or_update`, `remove_keys`, and `rename_keys`, plus any other operations like `literal_eval`, `select_keys`, and `combine` that Check() validates.internal/agent/component/stagehand_runtime_integration_test.go-196-200 (1)
196-200:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUse the configured integration model.
OPENAI_MODELis required for this test, but the Browser component still hardcodesgpt-4o@OpenAI. That makes the test fail or validate the wrong model when the integration environment is configured for another compatible model.🐛 Proposed fix
c, err := NewBrowserComponent(map[string]any{ - "llm_id": "gpt-4o@OpenAI", + "llm_id": fmt.Sprintf("%s@OpenAI", model), "prompts": prompt, "headless": &headless, })Also applies to: 237-241
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/stagehand_runtime_integration_test.go` around lines 196 - 200, The test reads the OPENAI_MODEL environment variable into the model variable but the Browser component still uses a hardcoded model name gpt-4o@OpenAI instead of the configured value. Replace all instances where the Browser component is initialized with the hardcoded gpt-4o@OpenAI model name with the model variable that was read from the environment. Also check the area around lines 237-241 for similar hardcoded model references and apply the same fix there.internal/agent/component/invoke.go-167-176 (1)
167-176:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winKeep the Invoke surface aligned with actual behavior.
datatypeis returned verbatim when provided, inferred only via a case-sensitiveapplication/jsoncheck when omitted, andvariablesis documented but not read by this component. Normalize/allowlistdatatype, inferhtml/+json, and either wirevariablesinterpolation or remove that input from the docs.🐛 Proposed fix
- datatype, _ := inputs["datatype"].(string) + datatype, _ := inputs["datatype"].(string) + datatype = strings.ToLower(strings.TrimSpace(datatype)) if datatype == "" { // Infer from Content-Type header. - ct := resp.Header.Get("Content-Type") - if strings.Contains(ct, "application/json") { + ct := strings.ToLower(resp.Header.Get("Content-Type")) + switch { + case strings.Contains(ct, "application/json") || strings.Contains(ct, "+json"): datatype = "json" - } else { + case strings.Contains(ct, "text/html"): + datatype = "html" + default: datatype = "text" } + } else { + switch datatype { + case "json", "text", "html": + default: + return nil, fmt.Errorf("Invoke: invalid datatype %q (want json/text/html)", datatype) + } }- "datatype": "Expected response datatype: 'json', 'text', or 'html'. Default 'json'.", - "variables": "Optional template variables for URL/body interpolation.", + "datatype": "Expected response datatype: 'json', 'text', or 'html'. Default inferred from Content-Type.",Also applies to: 209-211
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/invoke.go` around lines 167 - 176, The datatype inference logic needs three improvements: first, normalize and allowlist the datatype value when provided as input to ensure only valid values are accepted, second, enhance the Content-Type header matching to handle additional patterns including "html" and "+json" suffixes with case-insensitive matching instead of just the exact "application/json" substring check in the strings.Contains call, and third, address the variables input which is documented but not actually used in the component logic by either implementing interpolation support for it or removing it from the input documentation. The changes primarily affect the datatype inference block starting with the inputs["datatype"] read and the Content-Type conditional logic, as well as checking the variables handling at the other location mentioned (lines 209-211).internal/agent/component/invoke.go-243-268 (1)
243-268:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winRemove script/style blocks before tag stripping.
clean_html=truecurrently removes only the tags, leaving JavaScript/CSS text in the response body. That makes “cleaned” output noisy for downstream LLM nodes on normal web pages.🧹 Proposed fix
Add
regexpto the imports, then replace the helper body with block removal before tag removal:+var ( + htmlScriptBlockRE = regexp.MustCompile(`(?is)<script\b[^>]*>.*?</script\s*>`) + htmlStyleBlockRE = regexp.MustCompile(`(?is)<style\b[^>]*>.*?</style\s*>`) + htmlTagRE = regexp.MustCompile(`(?s)<[^>]*>`) +) + func stripHTMLTags(s string) string { - // Simple regexp-based approach: remove everything between < and > - re := strings.NewReplacer( - "<script", "\n<script", - "</script>", "</script>\n", - "<style", "\n<style", - "</style>", "</style>\n", - ) - s = re.Replace(s) - for { - start := strings.Index(s, "<") - if start == -1 { - break - } - end := strings.Index(s[start:], ">") - if end == -1 { - break - } - s = s[:start] + s[start+end+1:] - } + s = htmlScriptBlockRE.ReplaceAllString(s, "\n") + s = htmlStyleBlockRE.ReplaceAllString(s, "\n") + s = htmlTagRE.ReplaceAllString(s, "") // Collapse multiple newlines for strings.Contains(s, "\n\n\n") {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/component/invoke.go` around lines 243 - 268, The stripHTMLTags function currently removes HTML tags but leaves JavaScript and CSS code from script and style blocks in the output. To fix this, import the regexp package at the top of the file, then modify the function body to first use regex to remove entire script and style blocks (including their content) before applying the existing tag removal logic. Specifically, use regexp.MustCompile to create patterns that match complete <script>...</script> and <style>...</style> blocks case-insensitively, then call ReplaceAllString on the input string with these patterns before proceeding with the existing for loop that removes remaining HTML tags.internal/agent/sandbox/manager_client.go-38-41 (1)
38-41:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winTreat non-positive timeout as default to avoid invalid provider input.
At Lines 38-41, only
timeout == 0is normalized. Negative timeouts currently pass through to providers and can produce undefined behavior.Suggested fix
timeout := req.Timeout - if timeout == 0 { + if timeout <= 0 { timeout = 30 }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/sandbox/manager_client.go` around lines 38 - 41, The timeout validation at Lines 38-41 only checks for timeout == 0 but does not handle negative timeout values, which can cause undefined behavior in providers. Modify the condition to check for non-positive timeouts by changing the comparison from timeout == 0 to timeout <= 0, so that both zero and negative timeout values are normalized to the default value of 30.
🧹 Nitpick comments (4)
internal/agent/canvas/scheduler.go (1)
232-262: 🧹 Nitpick | 🔵 Trivial | 💤 Low valueConsider removing or gating the DEBUG log statement.
Line 236 contains a
log.Printf("DEBUG node_started: ...")call that will emit to stdout/stderr on every node execution in production. Consider either removing this debug log or gating it behind a debug flag / log level check.♻️ Suggested removal
func nodeStartedAt(ctx context.Context, state *CanvasState, cpnID, componentName, componentType string) { - log.Printf("DEBUG node_started: cpnID=%s componentName=%s", cpnID, componentName) if state == nil { return }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/canvas/scheduler.go` around lines 232 - 262, Remove or gate the unconditional log.Printf debug statement in the nodeStartedAt function. Either delete the log.Printf("DEBUG node_started: cpnID=%s componentName=%s", cpnID, componentName) line entirely, or wrap it behind a debug flag or log level check to prevent it from executing in production. This will prevent the debug statement from being emitted to stdout/stderr on every node execution.internal/handler/agent_test.go (1)
278-280: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winUse an assertion (or remove this branch) instead of a log-only mismatch check.
At Line 278, mismatched node type only logs and still passes, so this check can’t catch regressions.
Suggested tweak
- if node["type"] != "parallelNode" { - t.Logf("handler preserved stored node type %v; this fixture only verifies dsl field presence", node["type"]) - } + if node["type"] != "parallelNode" { + t.Errorf("expected node type %q, got %v", "parallelNode", node["type"]) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/agent_test.go` around lines 278 - 280, The condition checking if node["type"] is not equal to "parallelNode" only logs a message without failing the test, which means regressions won't be caught. Replace this log-only check with a proper assertion using t.Fatalf or t.Errorf to fail the test when the node type doesn't match the expected "parallelNode" value, or remove the branch entirely if this validation is not necessary for the test.internal/agent/sandbox/self_managed_test.go (1)
245-284: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winAdd coverage for
present:falseplus stdout fallback.The new tests cover HTTP
result.present=true, but not the regression-prone case where the server returns its default non-emptypresent:falseresult while stdout still contains a structured result marker. Add that case so the fallback parser cannot be accidentally masked.Also applies to: 475-485
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/sandbox/self_managed_test.go` around lines 245 - 284, Add a new test function to cover the regression-prone case where the HTTP response has result.present set to false but stdout still contains a structured result marker. This test should verify that the fallback parser correctly extracts and uses the result from stdout when the HTTP result field indicates it is not present. Model it similarly to TestSelfManaged_ExecuteCode_PrefersHTTPResultField but configure the mock HTTP server to return present:false and include the structured result in stdout instead of the result field, then assert that the fallback parser correctly processes the stdout value.internal/agent/tool/exesql_unsupported_test.go (1)
32-38: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winAssert the expected unknown-driver failure mode explicitly.
The test currently checks
err != niland!errors.Is(err, ErrExeSQLUnsupportedDB), but that still allows unrelated errors to pass.Suggested fix
_, err := tool.InvokableRun(context.Background(), `{"sql":"SELECT 1"}`) if err == nil { t.Fatal("expected driver error for trino") } if errors.Is(err, ErrExeSQLUnsupportedDB) { t.Fatalf("err=%v, did not want ErrExeSQLUnsupportedDB after trino wiring", err) } + if !strings.Contains(strings.ToLower(err.Error()), "unknown driver") { + t.Fatalf("err=%v, want unknown-driver error path", err) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/tool/exesql_unsupported_test.go` around lines 32 - 38, The test in the InvokableRun call is currently using negative assertions (checking that err is not nil and not ErrExeSQLUnsupportedDB), which allows unrelated errors to pass the test. Instead of checking what error it should NOT be, explicitly assert the expected driver error type that should occur when trino driver wiring is in place. Replace the negative checks with a positive assertion using errors.Is() to verify the error matches the specific expected unknown-driver failure mode.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: acc836df-b818-4ef4-9964-395b597d2d20
⛔ Files ignored due to path filters (2)
go.sumis excluded by!**/*.sumweb/pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (118)
.dockerignoreAGENTS.mdCLAUDE.mdDockerfileREADME.mdREADME_ar.mdREADME_fr.mdREADME_id.mdREADME_ja.mdREADME_ko.mdREADME_pt_br.mdREADME_tr.mdREADME_tzh.mdREADME_zh.mdagent/component/list_operations.pycmd/server_main.goconf/all_models.jsondocs/develop/agent-go-port-design.mdgo.modinternal/agent/canvas/canvas.gointernal/agent/canvas/fixture_compile_test.gointernal/agent/canvas/interrupt_resume.gointernal/agent/canvas/interrupt_resume_test.gointernal/agent/canvas/loop_subgraph.gointernal/agent/canvas/loop_subgraph_test.gointernal/agent/canvas/multibranch.gointernal/agent/canvas/multibranch_test.gointernal/agent/canvas/parallel_subgraph.gointernal/agent/canvas/parallel_subgraph_test.gointernal/agent/canvas/runner.gointernal/agent/canvas/scheduler.gointernal/agent/canvas/scheduler_test.gointernal/agent/canvas/variable_test.gointernal/agent/component/agent.gointernal/agent/component/browser.gointernal/agent/component/browser_test.gointernal/agent/component/categorize.gointernal/agent/component/categorize_test.gointernal/agent/component/data_operations.gointernal/agent/component/fixture_stubs.gointernal/agent/component/invoke.gointernal/agent/component/list_operations.gointernal/agent/component/list_operations_test.gointernal/agent/component/llm.gointernal/agent/component/llm_credentials.gointernal/agent/component/llm_id.gointernal/agent/component/loop.gointernal/agent/component/message.gointernal/agent/component/production_chain_fixes_test.gointernal/agent/component/retrieval_swap_test.gointernal/agent/component/stagehand_runtime.gointernal/agent/component/stagehand_runtime_integration_test.gointernal/agent/component/stagehand_runtime_test.gointernal/agent/component/string_transform.gointernal/agent/component/string_transform_test.gointernal/agent/component/switch.gointernal/agent/component/switch_test.gointernal/agent/component/universe_a_wrappers.gointernal/agent/component/variable_aggregator.gointernal/agent/dsl/normalize.gointernal/agent/dsl/normalize_test.gointernal/agent/dsl/reset.gointernal/agent/dsl/reset_test.gointernal/agent/dsl/testdata/agent_msg.jsoninternal/agent/dsl/testdata/all.jsoninternal/agent/dsl/testdata/browser.jsoninternal/agent/runtime/state.gointernal/agent/runtime/template.gointernal/agent/sandbox/manager_client.gointernal/agent/sandbox/manager_client_test.gointernal/agent/sandbox/self_managed.gointernal/agent/sandbox/self_managed_test.gointernal/agent/tool/code_exec.gointernal/agent/tool/code_exec_client.gointernal/agent/tool/code_exec_contract.gointernal/agent/tool/code_exec_test.gointernal/agent/tool/exesql.gointernal/agent/tool/exesql_test.gointernal/agent/tool/exesql_trino_stub.gointernal/agent/tool/exesql_unsupported_test.gointernal/agent/workflowx/parallel.gointernal/entity/models/siliconflow.gointernal/handler/agent.gointernal/handler/agent_test.gointernal/handler/agent_wait_for_user_test.gointernal/router/agent_routes.gointernal/router/agent_routes_test.gointernal/service/agent.gointernal/service/agent_run_e2e_test.gointernal/service/agent_test.gointernal/service/canvas_decode.gointernal/service/canvas_decode_test.gointernal/service/document_test.goragflow_deps/Dockerfileragflow_deps/download_deps.pytest/unit_test/conftest.pyweb/__mocks__/human-id.jsweb/jest.config.tsweb/src/components/collapse.tsxweb/src/components/copy-to-clipboard.tsxweb/src/components/message-item/group-button.tsxweb/src/components/next-message-item/group-button.tsxweb/src/components/ui/input-select.tsxweb/src/components/ui/modal/modal.tsxweb/src/components/ui/tooltip.tsxweb/src/hooks/use-send-message.tsweb/src/pages/agent/canvas/index.module.lessweb/src/pages/agent/canvas/index.tsxweb/src/pages/agent/chat/box.tsxweb/src/pages/agent/constant/index.tsxweb/src/pages/agent/empty-dsl.tsweb/src/pages/agent/form/components/prompt-editor/variable-node.tsxweb/src/pages/agent/hooks/use-stop-message.tsweb/src/pages/agent/log-sheet/workflow-timeline.tsxweb/src/pages/agent/utils/dsl-bridge.tsweb/src/pages/agent/utils/tests/dsl-bridge.test.tsweb/src/pages/agents/hooks/use-create-agent.tsweb/src/pages/user-setting/setting-model/index.tsx
💤 Files with no reviewable changes (2)
- internal/agent/dsl/testdata/browser.json
- internal/agent/component/retrieval_swap_test.go
Accept 5 reasonable review comments; reject 1 (false duplicate-declaration claim).
- canvas/parallel_subgraph: when cloneCanvasState fails, fall back to a
fresh per-item state (shallow-copy of Sys/Globals) so parallel workers
never share the same parent CanvasState.
- canvas/runner: move panic recovery from the outer goroutine into the
inner safeInvoke goroutine (it cannot catch panics from run when
safeInvoke spawns it). Convert panic to a regular error. Also emit the
terminal 'done' SSE event on the normal-error branch to match the
channel-end contract used by completed and waiting-for-user paths.
- component/agent: return an error from Invoke when agentRunner returns
(nil, nil) instead of dereferencing msg.Content.
- component/categorize: check params['items'].([]any) (object-style)
before sliceFrom, otherwise sliceFrom matches the same input with an
empty slice and the object branch is unreachable.
- entity/models/siliconflow: use the boolean 'enable_thinking' field
(SiliconFlow API contract) instead of the DeepSeek-style
'thinking: {type: ...}' map, which the API silently ignores.
Reject: list_operations.go duplicate listOpPanic declaration — the type
is declared exactly once at line 55; CodeRabbit hallucinated the second
declaration.
Co-Authored-By: Claude <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16225 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
Aligns the Go agent runtime/canvas/components/tools behavior with the Python
agent/implementation so the same stored canvas DSL produces the same execution result on either side. Every component, tool, and runtime primitive ininternal/agent/is now driven by the same semantics as its Python counterpart — variable resolution, template substitution, control flow, error reporting, retry/cancel, and stream event shapes.The retrieval component is the one explicit exception in this PR. It is being reworked in a separate change and is excluded from this alignment pass; the wrapper slot (
universe_a_wrappers.go → newRetrievalComponent) is preserved.Scope of alignment
Components (all aligned with
agent/component/)Begin·Message·LLM(incl. ChatTemplateKwargs, MessageHistoryWindowSize, VisualFiles, Cite, OutputStructure, JSONOutput, TopP, MaxRetries, DelayAfterError, credentials) ·Agent(react + tool artifact capture +Reset()interface-assert) ·Switch(12/12 operators, Python-equivalent semantics) ·Categorize·Invoke·Iteration·Loop(macro-expansion throughworkflowx.AddLoopNode) ·UserFillUp(Python-equivalent interrupt/resume via einocompose.Interrupt/ResumeWithData) ·FillUp·DataOperations·ListOperations·StringTransform·VariableAggregator·VariableAssigner·Browser(full stagehand runtime parity) ·DocsGenerator·ExcelProcessor.Tools (all aligned with
agent/tools/)Retrieval(wrapper slot only — logic out of scope) ·MCPToolAdapter(streamable-HTTP) ·CodeExec(sandbox bridge withcode_exec_contract.gomatching Python contract) ·AkShare·ArXiv·Crawler·DeepL·DuckDuckGo·Email·ExeSQL·GitHub·Google·GoogleScholar·Jin10·PubMed·QWeather·SearXNG·Tavily·Tushare·Wencai·Wikipedia·YahooFinance— uniformeino tool.InvokableToolinterface, SSRF protection, shared HTTP client.Canvas execution engine (
internal/agent/canvas/)Aligned with Python's
agent/canvas.py:scheduler.go): state pre/post handlers, node lambdas, per-component timeout resolver (4-level: per-class env → per-class table → uniform env → 600s fallback),legacyNoOpNames.loop_subgraph.go): Python-equivalentAddLoopNodemacro expansion + condition translation.multibranch.go):Switch/Categorizerouting viacompose.NewGraphMultiBranch— same branch selection semantics as Python.parallel_subgraph.go): matches Python's parallel fan-out contract.interrupt_resume.go):UserFillUpNodeBody/IsInterruptError/ExtractInterruptContexts— replaces the deprecated Python sentinel chain with eino's native interrupt API, preserving the same external behavior.checkpoint_store.go):RedisCheckPointStoreGet/Set/Delete, with business metadata (status / canvas_id / parent_run_id) on a parallel Redis Hash.run_tracker.go): Start / MarkSucceeded / MarkFailed / MarkCancelled / AttachCheckpoint — same lifecycle as the Python run record.cancel.go): Redis pub/sub watch.stream.go): SSE channel withmessages/waiting/errors/doneevents, same shape as Python'sagent.canvas.RunEventpayload.DSL bridge (
internal/agent/dsl/)normalize.go: v1↔v2 collapsed into a single wire format — Python and Go consume the same stored JSON.reset.go: per-run state reset matches Python'sCanvas.reset()semantics.agent_msg.json/all.json/ etc.Runtime (
internal/agent/runtime/)CanvasState/NewCanvasState/GetVar/SetVar/ReadVars: same{{cpn_id@param}}resolution model.ResolveTemplate(regex fast path + gonja fallback) — Python Jinja-style semantics.selector.go,metrics.go,component.go: shared runtime contracts.Out of scope (intentionally)
Retrievalcomponent logic — wrapped only; full parity lands in a follow-up PR.How alignment is verified
internal/service/agent_run_e2e_test.goexercises the full production chain against real Python-shaped DSL fixtures:using in-memory SQLite + miniredis (no Docker). Covers:
TestRunAgent_RealCanvas_BeginMessage— happy path,{{sys.query}}resolutionTestRunAgent_RealCanvas_WaitForUserResume— two-run resume cycle (Python-equivalent)TestRunAgent_RealCanvas_CompileFails— unknown component name → sanitized error (Python-equivalent)TestRunAgent_RealCanvas_InvokeFails— unresolvable template ref (Python-equivalent)TestRunAgent_RunTracker_AttachCheckpoint_CallSequence— Start→AttachCheckpoint→MarkSucceeded lifecycleinternal/handler/agent_test.go— SSE streaming parity (Content-Type: text/event-stream,data: {…}\n\n, trailingdata: [DONE]\n\n, OpenAI-compatible non-streamchoices).internal/agent/canvas/fixture_compile_test.go+ per-component tests pin the Python-equivalent outputs.Design reference
docs/develop/agent-go-port-design.md(1329 lines, last cross-checked 2026-06-17) — module layout, per-component / per-tool inventory, corner-case catalogue, and the actionable backlog (Section 14, including the retrieval alignment follow-up).