Skip to content

pathing - #94

Merged
khaliqgant merged 2 commits into
mainfrom
broker-fix
Jun 5, 2026
Merged

khaliqgant merged 2 commits into
mainfrom
broker-fix

Conversation

@khaliqgant

@khaliqgant khaliqgant commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

CodeAnt-AI Description

Reuse existing broker connections from the current workspace path

What Changed

  • The app now looks for broker connection files in the current .agentworkforce/relay location, while still supporting the older .agent-relay path.
  • When reconnecting to an existing broker, it tries each available connection file instead of starting a new broker right away.
  • Cleanup now covers both the current and legacy broker file locations, reducing leftover files from older runs.

Impact

✅ Fewer duplicate broker startups
✅ Smoother reconnects after workspace restarts
✅ Fewer failures with older broker files

🔄 Retrigger CodeAnt AI Review

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

@codeant-ai

codeant-ai Bot commented Jun 5, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Free

Run ID: 27b5b2b9-732f-4ce4-8ba3-2f38c9c350c7

📥 Commits

Reviewing files that changed from the base of the PR and between 8dff373 and b218297.

📒 Files selected for processing (2)
  • src/main/broker.test.ts
  • src/main/broker.ts

📝 Walkthrough

Walkthrough

The broker discovery now checks prioritized candidate connection paths (current .agentworkforce/relay/ then legacy .agent-relay/), runtime cleanup targets both roots, reconnection tries candidates in order and disconnects failed probes, and tests/mocks were extended to validate reuse and fallback behavior.

Changes

Broker connection migration to dual-layout support

Layer / File(s) Summary
Connection path resolution with fallback
src/main/broker.ts
Iterates prioritized connection.json candidates and returns the first matching or existing candidate; replaces single legacy-path lookup.
brokerConnectionPathCandidates & resolver
src/main/broker.ts
Adds brokerConnectionPathCandidates(cwd) and resolveBrokerConnectionPath(cwd) to generate and pick prioritized candidate paths.
Runtime cleanup for both layouts
src/main/broker.ts
getBrokerRuntimeCleanupPaths expanded to return connection, lock, state, and pending file targets under both .agentworkforce/relay/ and .agent-relay/.
Multi-candidate broker reconnection
src/main/broker.ts
connectExistingBroker now tries existing candidate connection.json paths in order, calls AgentRelayClient.connect({ cwd, connectionPath }) per candidate, logs per-candidate failures, disconnects failed clients, and returns the first successful client.
Test mock surface and state
src/main/broker.test.ts
MockClient added getStatus and baseUrl; shared test state adds connectedClients, nextConnectedAgents, and nextConnectedSessionErrors.
HarnessDriverClient.connect mock & per-test reset
src/main/broker.test.ts
HarnessDriverClient.connect replaced to consume queued agents, optionally program one-time getSession rejection, register clients in connectedClients; suite beforeEach clears queues and mock.
Connection-selection and fallback tests
src/main/broker.test.ts
New tests assert BrokerManager.start(...) reuses on-disk connection.json (connect called with explicit connectionPath, no spawn), legacy file selection when current is stale, and that failed broker probe clients are disconnected before trying next candidates.

🎯 3 (Moderate) | ⏱️ ~20 minutes

🐰 The broker hops between two homes—new nest and old burrow—/
Finding connection files with a fallback whisper,/
Cleanup sweeps both dens with equal care,/
Tests ensure the warren reuses its path—no spawn to spare!


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@codeant-ai codeant-ai Bot added the size:M This PR changes 30-99 lines, ignoring generated files label Jun 5, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request updates the broker manager to support a new connection path (.agentworkforce/relay/connection.json) alongside the legacy path (.agent-relay/connection.json), including updates to connection resolution, cleanup paths, and existing broker reuse logic. Feedback on these changes highlights a potential false-positive status in getBrokerConnectionFileInfo when both connection files exist and one is stale, and suggests a minor optimization in resolveBrokerConnectionPath to avoid redundant array allocations.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/main/broker.ts Outdated
}

const connectionPath = join(cwd, '.agent-relay', 'connection.json')
const connectionPath = resolveBrokerConnectionPath(cwd)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Potential false-positive 'different' status in getBrokerConnectionFileInfo

When both .agentworkforce/relay/connection.json and .agent-relay/connection.json exist (e.g., during a migration or transition period), resolveBrokerConnectionPath(cwd) will always return the first one that exists (the .agentworkforce path).

However, if that file is stale/invalid, connectExistingBroker will fall back and successfully connect using the legacy .agent-relay path. In this scenario, getBrokerConnectionFileInfo will read the stale .agentworkforce file, compare it against the active session's URL/PID, and incorrectly report the status as 'different' instead of 'matches'.

Recommendation

Consider refactoring getBrokerConnectionFileInfo to iterate over all candidates in brokerConnectionPathCandidates(cwd) and check if any of them match the active session's baseUrl and brokerPid. If a match is found, return that file's info with 'matches' status.

Comment thread src/main/broker.ts
Comment on lines +755 to +758
function resolveBrokerConnectionPath(cwd: string): string {
return brokerConnectionPathCandidates(cwd).find((candidate) => existsSync(candidate)) ??
brokerConnectionPathCandidates(cwd)[0]
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Avoid calling brokerConnectionPathCandidates(cwd) twice to prevent redundant array allocations and path joins. Storing the candidates in a local variable is cleaner and more efficient.

function resolveBrokerConnectionPath(cwd: string): string {
  const candidates = brokerConnectionPathCandidates(cwd)
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]
}

Comment thread src/main/broker.ts
Comment on lines +1293 to 1302
for (const connectionPath of connectionPaths) {
try {
const client = AgentRelayClient.connect({ cwd, connectionPath })
await client.getSession()
console.log(`[broker] Reusing existing broker for project ${projectId}: ${connectionPath}`)
return client
} catch (err) {
console.warn(`[broker] Existing broker connection is not reusable for project ${projectId}:`, err)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: When probing multiple connection files, a client instance is created before health-checking with getSession(), but the failure path only logs and continues. If connect() allocates sockets/listeners, failed attempts are never torn down, so repeated starts can leak broker connections/resources. Explicitly disconnect/release the temporary client inside the catch path before trying the next candidate. [resource leak]

Severity Level: Major ⚠️
- ❌ Main process can leak AgentRelayClient sockets on failed reuse.
- ⚠️ Repeated broker:start calls may exhaust broker connection resources.
- ⚠️ Long-lived sessions risk instability from accumulated leaked clients.
Steps of Reproduction ✅
1. Open the Electron app and trigger a broker start for a project, which sends the IPC
call `'broker:start'` handled in `src/main/ipc-handlers.ts` (lines 170–199 from tool
output) where `brokerManager.start(projectId, cwd, name, win, channels)` is invoked.

2. Inside `BrokerManager.start` in `src/main/broker.ts` (lines 52–79 from tool output),
the `startBroker` closure is created; its first step is `const existingClient = await
this.connectExistingBroker(normalizedProjectId, cwd)`, which calls
`connectExistingBroker`.

3. Ensure the project `cwd` contains at least one stale or unusable local broker
connection file (for example, `.agentworkforce/relay/connection.json` left over from a
previous run) so that `brokerConnectionPathCandidates(cwd).filter((candidate) =>
existsSync(candidate))` in `connectExistingBroker` (file `src/main/broker.ts`, around
lines 69–75) returns one or more paths that exist but point to a dead or incompatible
broker.

4. When `connectExistingBroker` runs, for each such `connectionPath` it executes the loop
shown in `src/main/broker.ts` lines 1293–1302: it calls `const client =
AgentRelayClient.connect({ cwd, connectionPath })` and then `await client.getSession()`.
If the broker behind that file is unreachable or mismatched, `client.getSession()` throws,
execution enters the `catch (err)` block, and only a warning is logged
(`console.warn('[broker] Existing broker connection is not reusable…')`) without calling
`client.disconnect()` or any shutdown.

5. Because the failing `client` is never stored in `this.sessions` and never explicitly
disconnected in the catch block, any sockets/listeners allocated by
`AgentRelayClient.connect` remain live in the Electron main process. The loop then
continues to the next candidate (if any), or returns `null`, causing `startBroker` to
spawn a new broker via `AgentRelayClient.spawn(opts)` while the failed client instance is
effectively leaked.

6. Repeating the `'broker:start'` IPC for the same project while the stale connection file
remains (for example, reopen the project or let `reviveSession` call `this.start` again
from `src/main/broker.ts` lines 1312–1335) causes `connectExistingBroker` to allocate and
abandon additional `AgentRelayClient` instances, leading to a cumulative leak of broker
client resources over time.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/main/broker.ts
**Line:** 1293:1302
**Comment:**
	*Resource Leak: When probing multiple connection files, a client instance is created before health-checking with `getSession()`, but the failure path only logs and continues. If `connect()` allocates sockets/listeners, failed attempts are never torn down, so repeated starts can leak broker connections/resources. Explicitly disconnect/release the temporary client inside the `catch` path before trying the next candidate.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@codeant-ai

codeant-ai Bot commented Jun 5, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

@khaliqgant
khaliqgant merged commit ae6eacf into main Jun 5, 2026
3 checks passed
@khaliqgant
khaliqgant deleted the broker-fix branch June 5, 2026 13:11
@agent-relay-code

Copy link
Copy Markdown
Contributor

✅ pr-reviewer applied fixes — committed and pushed e009b21 to this PR. The notes below describe what changed.

Fixed a real PR issue: current-format broker connection files using apiKey were being reused but not parsed for broker details because the schema only accepted legacy api_key.

Changes made:

  • src/main/schemas.ts: accepts both apiKey and api_key, preferring apiKey.
  • src/main/broker.test.ts: added regression coverage that current .agentworkforce/relay/connection.json reports matching status and exposes the API key.

Validated locally:

  • npm ci
  • npm run verify:mcp-resources-drift
  • npx vitest run src/main/broker.test.ts
  • npm test
  • npm run build
  • final npm run verify:mcp-resources-drift

No separate bot review artifacts were present under .workforce to validate.

agent-relay-code Bot added a commit that referenced this pull request Jun 5, 2026
@agent-relay-code

Copy link
Copy Markdown
Contributor

Fixed the validated remaining issue: current .agentworkforce/relay/connection.json files using apiKey are now parsed by schemas.ts, while legacy api_key still works. I also extended broker.test.ts to assert the reused current connection reports matching status and exposes that key.

Validated locally:

  • npx vitest run src/main/broker.test.ts
  • npm test
  • npm run verify:mcp-resources-drift
  • npm run build
  • final npm run verify:mcp-resources-drift

I also checked the bot comments: the stale connection-info, duplicate candidate allocation, and failed-probe disconnect findings were already addressed in the current checkout.

@agent-relay-code

Copy link
Copy Markdown
Contributor

✅ pr-reviewer applied fixes — committed and pushed 2567029 to this PR. The notes below describe what changed.

Fixed the validated remaining issue: current .agentworkforce/relay/connection.json files using apiKey are now parsed by schemas.ts, while legacy api_key still works. I also extended broker.test.ts to assert the reused current connection reports matching status and exposes that key.

Validated locally:

  • npx vitest run src/main/broker.test.ts
  • npm test
  • npm run verify:mcp-resources-drift
  • npm run build
  • final npm run verify:mcp-resources-drift

I also checked the bot comments: the stale connection-info, duplicate candidate allocation, and failed-probe disconnect findings were already addressed in the current checkout.

agent-relay-code Bot added a commit that referenced this pull request Jun 5, 2026
@agent-relay-code

Copy link
Copy Markdown
Contributor

Fixed the remaining validated issue in the current checkout: current .agentworkforce/relay/connection.json files using apiKey are now parsed by schemas.ts, while legacy api_key still works.

I also extended the broker regression in broker.test.ts so a reused current connection reports matches and exposes the API key through listBrokerDetails().

Validated:

  • npm ci
  • npx vitest run src/main/broker.test.ts
  • npm test
  • npm run verify:mcp-resources-drift
  • npm run build
  • final npm run verify:mcp-resources-drift

I checked the bot review comments against the current checkout. The stale connection-info selection, duplicate candidate allocation, and failed-probe disconnect findings were already addressed; the schema/API-key gap was the remaining demonstrated issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant