refactor(main): consolidate shared helpers + decompose broker.ts#384
Conversation
Nine main-process modules each carried a private copy of `toErrorMessage`; eight were byte-identical and one (integration-event-bridge) was a richer variant. Consolidate into: - src/main/errors.ts — `toErrorMessage` (concise) and `describeError` (the rich field-probing fallback, formerly inlined in integration-event-bridge). - src/main/guards.ts — canonical `isRecord` (non-null, non-array). integration-event-bridge now imports `describeError as toErrorMessage` so its call sites are unchanged. Behavior is preserved exactly. Relative value imports of these modules from files in the node:test strip-types runtime graph (burn, integration-event-bridge) use the explicit `.ts` extension with the repo's `@ts-expect-error` idiom; other importers stay extensionless. Verified: npm test (122), vitest (451), typecheck, lint all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J59WsDm4zNGqhW137jEkaG
Eight modules carried private `isRecord` copies across three slightly
different shapes; broker and spawn-coordinator used an array-INCLUDING form
while the rest excluded arrays. Replace all with the canonical
`isRecord` from src/main/guards.ts (non-null, non-array).
The two array-including call sites are pure object-property coercions
(`isRecord(x) ? x : {}`) that only read named string/typed properties, which
an array yields as undefined either way, so switching to the stricter guard is
behavior-preserving.
Verified: npm test (122), vitest (451), typecheck, lint all pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J59WsDm4zNGqhW137jEkaG
The broker binary resolution helpers and the legacy `--name` compatibility shim were ~215 lines of stateless infrastructure embedded in the 4282-line broker.ts. Move them to a dedicated src/main/broker-binary.ts: - resolveBundledBrokerBinary / parseBrokerInitCliFlags (publicly tested) - resolveHarnessBrokerBinary (now exported; consumed by BrokerManager) - the private resolve/inspect/shim helpers broker.ts imports resolveHarnessBrokerBinary from the new module and drops the now-unused fs/promises imports (chmod/mkdir/readFile/writeFile). broker.test.ts imports the two tested helpers from broker-binary. Pure behavior-preserving move (verified by autoreview); __dirname semantics are unchanged since both modules bundle into out/main. Verified: npm test (122), vitest (451), typecheck, lint all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J59WsDm4zNGqhW137jEkaG
…ls.ts The loose-union `BrokerEvent` accessors and delivery/exit/stream predicates (brokerEventString, isDeliveryEventForMessage, deliveryFailureMessage, isWorkerStreamForAgent, isAgentExitEventForAgent, brokerEventChunk, brokerEventNumber) were module-private helpers in broker.ts. Move them to src/main/broker-event-utils.ts; BrokerManager imports what it needs. The AGENT_EXIT_EVENT_KINDS constant stays private to the new module. Pure behavior-preserving move, depends only on the BrokerEvent type and guards.isRecord. Verified: npm test (122), vitest (451), typecheck, lint all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J59WsDm4zNGqhW137jEkaG
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
📝 WalkthroughWalkthroughFour new shared modules are introduced: ChangesShared Helper Extraction and Broker Module Split
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
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. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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.
🧹 Nitpick comments (1)
src/main/broker-binary.ts (1)
68-73: ⚡ Quick winFail fast if the SDK fallback binary is missing or not executable.
The last fallback is returned unvalidated. If that path is absent/non-executable, failure occurs later with less actionable errors. Check executability here and throw a clear error.
Suggested patch
const brokerBinary = join( baseDir, '..', '..', 'node_modules', '`@agent-relay`', 'sdk', 'bin', `agent-relay-broker-${suffix}${process.platform === 'win32' ? '.exe' : ''}` ) - return unpackIfPackaged(brokerBinary) + const finalCandidate = unpackIfPackaged(brokerBinary) + if (canExecute(finalCandidate)) return finalCandidate + if (finalCandidate !== brokerBinary && canExecute(brokerBinary)) return brokerBinary + throw new Error( + `[broker] Unable to locate an executable Agent Relay broker binary. Last checked: ${finalCandidate}` + ) }🤖 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 `@src/main/broker-binary.ts` around lines 68 - 73, The function returns the unpacked brokerBinary path without validating its existence or executability, causing failures downstream with unclear error messages. After calling unpackIfPackaged(brokerBinary), add validation to check that the binary file exists and is executable using appropriate Node.js fs methods. If either validation fails, throw a descriptive error that includes the full brokerBinary path and indicates whether the file is missing or not executable, ensuring users get actionable feedback immediately rather than encountering cryptic errors later.
🤖 Prompt for all review comments with 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.
Nitpick comments:
In `@src/main/broker-binary.ts`:
- Around line 68-73: The function returns the unpacked brokerBinary path without
validating its existence or executability, causing failures downstream with
unclear error messages. After calling unpackIfPackaged(brokerBinary), add
validation to check that the binary file exists and is executable using
appropriate Node.js fs methods. If either validation fails, throw a descriptive
error that includes the full brokerBinary path and indicates whether the file is
missing or not executable, ensuring users get actionable feedback immediately
rather than encountering cryptic errors later.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 569d9278-3603-4fa9-9204-0f861fa247fb
📒 Files selected for processing (17)
src/main/auth.tssrc/main/broker-binary.tssrc/main/broker-event-utils.tssrc/main/broker.test.tssrc/main/broker.tssrc/main/burn.tssrc/main/cloud-agent.tssrc/main/errors.tssrc/main/guards.tssrc/main/integration-event-bridge.tssrc/main/integration-mounts.tssrc/main/integration-symlinks.tssrc/main/integrations.tssrc/main/ipc-handlers.tssrc/main/proactive-agent.tssrc/main/spawn-coordinator.tssrc/main/store.ts
Summary
Two highest-value, lowest-risk architecture improvements, each behavior-preserving and verified green at every step:
broker.ts, 4282 lines) by pulling out cohesive, stateless clusters.No
BrokerManagerbehavior was touched — the stateful PTY/event-duplication paths AGENTS.md warns about are left intact.Changes
extract shared toErrorMessage/describeError + isRecordtoErrorMessagewas duplicated across 9 main-process files (8 byte-identical, 1 richer variant). Newsrc/main/errors.ts(toErrorMessage+describeError) andsrc/main/guards.ts.consolidate isRecord into shared guards moduleisRecordduplicated 8× across 3 semantic variants, unified onguards.ts. The two array-including call sites are pure object-property coercions → behavior-preserving.extract binary resolution into broker-binary.ts--namecompat shim moved out ofbroker.ts.extract BrokerEvent accessors into broker-event-utils.tsBrokerEventpredicate/accessor helpers moved to their own module.broker.ts: 4282 → 4013 lines.Import-extension note
Files in the
npm test(Node--experimental-strip-types) runtime graph (burn.ts,integration-event-bridge.ts) use explicit./x.tsvalue imports with the repo's existing// @ts-expect-erroridiom; all other importers stay extensionless. This matches the pre-existing convention inintegration-event-bridge.ts.Verification (run after every step)
npm test(node:test): 122 passnpx vitest run: 451 passnpm run typecheck: cleannpm run lint: clean🤖 Generated with Claude Code
Generated by Claude Code