Skip to content

Consolidate duplicated patterns in openclaw bridge#81

Merged
batuhan merged 1 commit intomainfrom
worktree-agent-a6068dfe
Mar 26, 2026
Merged

Consolidate duplicated patterns in openclaw bridge#81
batuhan merged 1 commit intomainfrom
worktree-agent-a6068dfe

Conversation

@batuhan
Copy link
Copy Markdown
Member

@batuhan batuhan commented Mar 26, 2026

Summary

  • Extract applyOpenClawSessionMetadata (5 call sites)
  • Consolidate seq-extraction between manager.go and gateway_client.go
  • Replace clone-via-JSON with jsonutil.DeepCloneMap
  • Extract parsedTokenUsage, unify URL normalization, extract supportsFeature
  • Net: -34 lines

Test plan

  • go build ./... passes
  • go test ./... passes
  • go vet ./... passes

🤖 Generated with Claude Code

Extract applyOpenClawSessionMetadata (5 call sites), consolidate seq-extraction,
replace clone-via-JSON with jsonutil.DeepCloneMap, extract parsedTokenUsage,
unify URL normalization pair, and extract supportsFeature helper. ~34 lines removed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 26, 2026

📝 Walkthrough

Summary by CodeRabbit

  • Refactor
    • Improved internal code organization for the OpenClaw gateway integration through consolidation of utility functions and streamlined handling of URL schemes, feature validation, and metadata management.

Walkthrough

These changes refactor the openclaw bridge by extracting helper functions and types to consolidate duplicated logic. Gateway client refactoring introduces helpers for feature matching, sequence number computation, and URL normalization. Manager refactoring extracts helpers for session metadata population and token usage parsing.

Changes

Cohort / File(s) Summary
Gateway client helpers
bridges/openclaw/gateway_client.go
Introduced supportsFeature helper for case-insensitive feature matching; extracted openClawHistoryMessageSeq for sequence number extraction; replaced local cloneGatewayHistoryMap with jsonutil.DeepCloneMap; unified URL scheme normalization via new normalizeGatewayURL helper function.
Manager refactoring
bridges/openclaw/manager.go
Extracted applyOpenClawSessionMetadata helper to consolidate UI metadata population; introduced parsedTokenUsage type and parseTokenUsage function to centralize token field extraction; updated applyUsageToMessageMetadata and applyNormalizedUsageToParams to use token parsing helper.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: consolidating duplicated patterns across the openclaw bridge codebase.
Description check ✅ Passed The description is directly related to the changeset, providing specific details about extracted helpers, consolidated logic, and test verification.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-agent-a6068dfe

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
bridges/openclaw/manager.go (2)

1376-1412: Reuse parseTokenUsage in the terminal accounting path too.

parseTokenUsage now centralizes normalized-key parsing, but Lines 1857-1873 still unpack the same fields manually. A small TotalOrDerived() follow-up would let that block share the same parser and avoid drift.

Also applies to: 1428-1437

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bridges/openclaw/manager.go` around lines 1376 - 1412, Replace the duplicated
manual unpacking of token fields in the terminal accounting code with the
centralized parseTokenUsage function: call parseTokenUsage(usage) to populate a
parsedTokenUsage, then assign the fields into the existing MessageMetadata (or
use a small helper TotalOrDerived() on parsedTokenUsage if the total needs to be
computed when missing). Update both places that manually extract
prompt_tokens/completion_tokens/reasoning_tokens/total_tokens to use
parseTokenUsage and then set metadata.PromptTokens, metadata.CompletionTokens,
metadata.ReasoningTokens and metadata.TotalTokens (or use
parsed.TotalOrDerived() if you implement that helper) so the parsing logic is
shared with applyUsageToMessageMetadata.

1308-1328: Trim inside applyOpenClawSessionMetadata.

Now that this helper is the single write path for session_id / session_key / error_text, normalize here too. payload.SessionKey is still passed through raw at Line 2060, so metadata can drift from the trimmed values the rest of the manager uses.

✂️ Suggested cleanup
func applyOpenClawSessionMetadata(m map[string]any, sessionID, sessionKey, errorText string) {
+	if m == nil {
+		return
+	}
+	sessionID = strings.TrimSpace(sessionID)
+	sessionKey = strings.TrimSpace(sessionKey)
+	errorText = strings.TrimSpace(errorText)
 	if sessionID != "" {
 		m["session_id"] = sessionID
 	}

Also applies to: 2033-2033, 2060-2060, 2404-2404, 2658-2662

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bridges/openclaw/manager.go` around lines 1308 - 1328,
applyOpenClawSessionMetadata currently writes session_id/session_key/error_text
without normalizing, which allows untrimmed values to persist; update
applyOpenClawSessionMetadata (the function taking m map[string]any, sessionID,
sessionKey, errorText string) to trim whitespace from sessionID, sessionKey, and
errorText (e.g., strings.TrimSpace) before checking for emptiness and setting
m["session_id"], m["session_key"], and m["error_text"] so all call sites can
pass raw values and metadata will remain normalized.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@bridges/openclaw/manager.go`:
- Around line 1376-1412: Replace the duplicated manual unpacking of token fields
in the terminal accounting code with the centralized parseTokenUsage function:
call parseTokenUsage(usage) to populate a parsedTokenUsage, then assign the
fields into the existing MessageMetadata (or use a small helper TotalOrDerived()
on parsedTokenUsage if the total needs to be computed when missing). Update both
places that manually extract
prompt_tokens/completion_tokens/reasoning_tokens/total_tokens to use
parseTokenUsage and then set metadata.PromptTokens, metadata.CompletionTokens,
metadata.ReasoningTokens and metadata.TotalTokens (or use
parsed.TotalOrDerived() if you implement that helper) so the parsing logic is
shared with applyUsageToMessageMetadata.
- Around line 1308-1328: applyOpenClawSessionMetadata currently writes
session_id/session_key/error_text without normalizing, which allows untrimmed
values to persist; update applyOpenClawSessionMetadata (the function taking m
map[string]any, sessionID, sessionKey, errorText string) to trim whitespace from
sessionID, sessionKey, and errorText (e.g., strings.TrimSpace) before checking
for emptiness and setting m["session_id"], m["session_key"], and m["error_text"]
so all call sites can pass raw values and metadata will remain normalized.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bf420b95-91b4-423b-be0e-5ae564f1c069

📥 Commits

Reviewing files that changed from the base of the PR and between ec2b8a9 and a87bfe8.

📒 Files selected for processing (2)
  • bridges/openclaw/gateway_client.go
  • bridges/openclaw/manager.go
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: build-agentremote-docker (arm64)
  • GitHub Check: build-agentremote-docker (amd64)
  • GitHub Check: Lint
  • GitHub Check: build-docker
🔇 Additional comments (3)
bridges/openclaw/gateway_client.go (3)

608-635: Nice feature-gating cleanup.

supportsFeature keeps the trim/case-insensitive matching logic in one place for both methods and events.


27-27: History sequence/cloning dedupe looks good.

Reusing the shared sequence parser and jsonutil.DeepCloneMap removes two parallel implementations while preserving the existing fallback behavior in this path.

Also applies to: 1161-1175


1371-1405: URL normalization consolidation looks solid.

The shared helper keeps the HTTP↔WS scheme translation rules consistent across both entry points.

@batuhan batuhan merged commit 77f3f0a into main Mar 26, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant