Skip to content
This repository was archived by the owner on Jan 29, 2026. It is now read-only.

Fix PR review issues: selector fragility, error handling, deprecated APIs#99

Open
Copilot wants to merge 2 commits intoclaude/fix-installation-critical-01VczDJNmP2TxbysummkFEJYfrom
copilot/sub-pr-98
Open

Fix PR review issues: selector fragility, error handling, deprecated APIs#99
Copilot wants to merge 2 commits intoclaude/fix-installation-critical-01VczDJNmP2TxbysummkFEJYfrom
copilot/sub-pr-98

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Nov 15, 2025

Addresses 17 code review findings from automated PR analysis covering selector specificity, error transparency, deprecated method usage, and unused imports.

Playwright Selector Improvements

google-labs.ts: Replaced comma-separated fallback selectors with explicit try-catch chains to prevent ambiguous element matching:

// Before: ambiguous - clicks first match of any selector
await this.page!.click('button:has-text("New"), button:has-text("Create"), a:has-text("New flow")');

// After: explicit fallback order
try {
  await this.page!.click('button:has-text("New")', { timeout: 3000 });
} catch {
  try {
    await this.page!.click('button:has-text("Create")', { timeout: 3000 });
  } catch {
    await this.page!.click('a:has-text("New flow")');
  }
}

Added special character escaping for text-based selectors and role-based selection for action dropdowns.

ai-studio-ultra.ts: Fixed contenteditable handling by using page.evaluate() to set textContent instead of fill(), which doesn't work on non-input elements.

playwright-service-base.ts: Removed hardcoded Chrome 120 user agent string to use Playwright's auto-updated defaults.

Error Handling & Observability

  • communication.ts: Added endpoint URL to fetch error messages for debugging multi-agent communication failures
  • gemini-service.ts: Changed countTokens() to throw instead of returning 0, making API failures explicit to callers

API Modernization

  • protocol-manager.ts: Replaced deprecated substr() with substring() for task ID generation
  • quantum/index.ts: Enhanced Bell state simulation with binomial sampling instead of deterministic 50/50 split for realistic quantum noise

Code Cleanup

Removed 7 unused imports across A2A, AP2, MCP, and quantum modules. Removed unused loop variables in mandate-manager.ts and communication.ts cleanup methods.

Documentation

  • PROTOCOLS.md: Fixed protocol field to match URL scheme (http vs https)
  • README.md: Clarified version output format

💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

…ods, and unused imports

Co-authored-by: clduab11 <185000089+clduab11@users.noreply.github.com>
Copilot AI changed the title [WIP] Refactor A2A protocol implementation and browser automation changes Fix PR review issues: selector fragility, error handling, deprecated APIs Nov 15, 2025
Copilot AI requested a review from clduab11 November 15, 2025 21:43
@clduab11 clduab11 added bug Something isn't working documentation Improvements or additions to documentation codex OpenAI's Codex gen/qol improves General code improvements and cleanup labels Nov 16, 2025
@clduab11 clduab11 marked this pull request as ready for review November 16, 2025 01:32
Copilot AI review requested due to automatic review settings November 16, 2025 01:32
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +146 to +155
const textarea = await this.page!.$('textarea[placeholder*="prompt"]');
if (textarea) {
await this.page!.fill('textarea[placeholder*="prompt"]', params.prompt);
} else {
// For contenteditable elements, use type() or evaluate()
const contentEditable = await this.page!.$('[contenteditable="true"]');
if (contentEditable) {
await this.page!.evaluate((el, text) => {
(el as HTMLElement).textContent = text;
}, contentEditable, params.prompt);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Trigger input events when filling contenteditable prompt

When no <textarea> exists, the prompt is inserted into the contenteditable element by running page.evaluate() and assigning textContent. This bypasses Playwright’s synthetic typing and does not fire input/change events. UIs that rely on those events (React, Angular, etc.) will keep their internal state empty, so pressing Run may submit a blank prompt even though the DOM shows the text. Consider using contentEditable.type() or dispatching an input event after the assignment.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR addresses 17 automated code review findings focused on improving selector robustness in Playwright automation, error handling transparency, API modernization, and code cleanup.

Key changes:

  • Replaced ambiguous comma-separated Playwright selectors with explicit try-catch fallback chains to ensure predictable element selection order
  • Enhanced error observability by including endpoint URLs in error messages and propagating token counting failures instead of silently returning zero
  • Modernized deprecated substr() to substring() and removed hardcoded user agent strings

Reviewed Changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
src/browser/services/google-labs.ts Replaced comma-separated selectors with explicit try-catch chains and added special character escaping
src/browser/services/ai-studio-ultra.ts Fixed contenteditable element handling using evaluate() instead of fill()
src/browser/playwright-service-base.ts Removed hardcoded Chrome 120 user agent to use Playwright defaults
packages/services/quantum/index.ts Changed Bell state simulation from deterministic split to binomial sampling
packages/services/quantum/circuit-builder.ts Removed unused QuantumGate import
packages/services/google-ai/gemini-service.ts Changed countTokens() to throw errors instead of returning 0
packages/core/protocols/mcp/index.ts Removed unused MCPServerConfig import
packages/core/protocols/ap2/transaction-manager.ts Removed unused PaymentAmount import
packages/core/protocols/ap2/mandate-manager.ts Removed unused loop variable in cleanup method
packages/core/protocols/a2a/protocol-manager.ts Replaced deprecated substr() with substring()
packages/core/protocols/a2a/communication.ts Enhanced error logging with endpoint URL and removed unused loop variable
packages/core/protocols/a2a/agent-card.ts Removed unused AgentEndpoint import
README.md Clarified version output format in example
PROTOCOLS.md Fixed protocol field to match URL scheme (http)

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

}

const taskId = `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const taskId = `task-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

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

The substring bounds are incorrect. The original substr(2, 9) extracts 9 characters starting at index 2, but substring(2, 11) extracts 9 characters (indices 2-10 inclusive). However, Math.random().toString(36) typically returns strings of varying lengths (around 11-13 characters including '0.' prefix). After removing '0.' (2 chars), the remaining string may be shorter than 9 characters, making substring(2, 11) potentially return fewer characters than intended. The correct replacement should be substring(2, 2+9) or simply substring(2) if variable length is acceptable.

Suggested change
const taskId = `task-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
const taskId = `task-${Date.now()}-${Math.random().toString(36).substring(2, 2 + 9)}`;

Copilot uses AI. Check for mistakes.
// Select action type
await this.page!.click(`text="${step.action}"`);
// Select action type - escape special characters in selector
const escapedAction = step.action.replace(/["\\]/g, '\\$&');
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

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

The regex escaping only handles double quotes and backslashes, but Playwright text selectors can be broken by other special characters. Consider using a more comprehensive escaping approach or use a different selector strategy (e.g., role-based selectors with accessible names) that's less fragile to special characters.

Copilot uses AI. Check for mistakes.
// Try textarea first
const textarea = await this.page!.$('textarea[placeholder*="prompt"]');
if (textarea) {
await this.page!.fill('textarea[placeholder*="prompt"]', params.prompt);
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

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

The selector textarea[placeholder*="prompt"] is executed twice: once in the $() call to check existence (line 146) and again in the fill() call (line 148). Store the element handle and use it directly, or use a single try-catch with fill() to avoid the redundant query.

Suggested change
await this.page!.fill('textarea[placeholder*="prompt"]', params.prompt);
await textarea.fill(params.prompt);

Copilot uses AI. Check for mistakes.
Comment on lines +43 to +50
// Bell state results - simulate quantum noise with binomial distribution
let count00 = 0;
for (let i = 0; i < shots; i++) {
// Each shot has a 50% chance of being '00' or '11'
if (Math.random() < 0.5) {
count00++;
}
}
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

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

The loop-based binomial sampling is inefficient for large shot counts. For better performance, use a binomial distribution approximation or library function. For example, with a large number of shots, you could approximate using a normal distribution, or use a more efficient algorithm. The current O(n) approach could be slow for shot counts in the thousands.

Copilot uses AI. Check for mistakes.
Comment on lines +149 to +152
await this.page!.click(`[role="option"]:has-text("${escapedAction}")`, { timeout: 5000 }).catch(() => {
// Fallback to less specific selector
return this.page!.click(`text="${escapedAction}"`);
});
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

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

The catch block silently swallows all errors from the first click attempt and tries a fallback selector. If the fallback also fails, the error will propagate, but it won't be clear which selector failed or why. Consider logging which selector is being tried or re-throwing with context about both attempts.

Copilot uses AI. Check for mistakes.
Comment on lines +145 to +157
// Try textarea first
const textarea = await this.page!.$('textarea[placeholder*="prompt"]');
if (textarea) {
await this.page!.fill('textarea[placeholder*="prompt"]', params.prompt);
} else {
// For contenteditable elements, use type() or evaluate()
const contentEditable = await this.page!.$('[contenteditable="true"]');
if (contentEditable) {
await this.page!.evaluate((el, text) => {
(el as HTMLElement).textContent = text;
}, contentEditable, params.prompt);
}
}
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

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

If neither textarea nor contenteditable element is found, the code silently does nothing. This could lead to test failures that are hard to debug. Consider throwing an error or logging a warning when no input element is found.

Copilot uses AI. Check for mistakes.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

bug Something isn't working codex OpenAI's Codex documentation Improvements or additions to documentation gen/qol improves General code improvements and cleanup

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants