Skip to content

fix: MemoryBusTui never upgrades + spawn lock #13#14

Merged
four-bytes-robby merged 11 commits into
mainfrom
fix/13-memory-bus-upgrade
Jun 14, 2026
Merged

fix: MemoryBusTui never upgrades + spawn lock #13#14
four-bytes-robby merged 11 commits into
mainfrom
fix/13-memory-bus-upgrade

Conversation

@four-bytes-robby

@four-bytes-robby four-bytes-robby commented Jun 14, 2026

Copy link
Copy Markdown
Member

Throws clear error instead of silent fallback. Adds spawn lock.


Summary by cubic

Fail fast when the Go bus isn’t available and prevent duplicate spawns. Add SolidJS hooks for safe, reactive subscriptions (including project-scoped channels) and make TUI reconnect switch to new ports after restarts.

  • New Features

    • useServiceBus for reactive, session-scoped subscriptions; cancellation-safe with 5s connect retry and 2s ping until the worker responds.
    • useProjectBus for project-scoped channels using deriveProjectId(directory).
    • Export MemoryBusTui and deriveProjectId.
  • Bug Fixes

    • BusTui.connect() now throws a clear error if the Go bus can’t be reached.
    • Module-level spawn lock in BusClient with a split spawnBus() prevents concurrent spawns.
    • Reconnects re-read the discovery file and switch to a new port after restarts.
    • Externalized solid-js and @opentui/solid in the TUI build.

Written for commit 335bf0e. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features

    • Added service bus hook for managing connections with automatic reconnection and keep-alive messaging.
    • Added project bus hook that derives stable project identifiers for scoped subscriptions.
  • Bug Fixes

    • Improved connection error messages to include port and underlying error details.
    • Fixed lifecycle issues with reconnection, concurrent spawns, and bus availability retries.
  • Documentation

    • Updated documentation and known issues guide for connection behavior and lifecycle patterns.

Closes #13

Removes the automatic fallback to MemoryBusTui when the Go bus is
not reachable. Callers that want in-process mode can now instantiate
'new MemoryBusTui()' explicitly. This prevents silent subscription
failures where a TUI subscribes to a pattern via MemoryBusTui, never
sees any messages (because the server-side plugin publishes via the
real Go bus), and the user has no idea why.

After this change:
- BusTui.connect() throws a clear error if the Go bus is unreachable
- MemoryBusTui is still exported for callers that want it explicitly
- Both consumers (brain, tbguard) already have try/catch or .catch
  handlers, so they degrade gracefully and log a warning
- Tests are not affected (integration test runs the real Go bus;
  scoped-close test also runs the real Go bus)

Updates MemoryBusTui JSDoc to note opt-in usage and the integration
test header comment to reflect the new contract.
@coderabbitai

coderabbitai Bot commented Jun 14, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

Recent review info
Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9b4a11bf-b370-4c90-a5e3-468fbd24542b

Commits

Reviewing files that changed from the base of the PR and between c306c23 and 335bf0e.

Files ignored due to path filters (7)
  • dist/derive-project-id.d.ts is excluded by !**/dist/**
  • dist/index.d.ts is excluded by !**/dist/**
  • dist/index.js is excluded by !**/dist/**
  • dist/index.js.map is excluded by !**/dist/**, !**/*.map
  • dist/tui.d.ts is excluded by !**/dist/**
  • dist/tui.js is excluded by !**/dist/**
  • dist/tui.js.map is excluded by !**/dist/**, !**/*.map
Files selected for processing (4)
  • package.json
  • src/derive-project-id.ts
  • src/index.ts
  • src/tui.ts
💤 Files with no reviewable changes (1)
  • src/derive-project-id.ts
✅ Files skipped from review due to trivial changes (1)
  • package.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/index.ts

Walkthrough

Walkthrough

BusTui.connect() is changed to throw on failure instead of falling back to MemoryBusTui, which is now exported for explicit opt-in use. A new useServiceBus SolidJS hook is added with connection retry, reactive channel subscription, and ping-until-confirmed behavior. A deriveProjectId FNV-1a utility and a useProjectBus wrapper are added and wired through the TUI and main entry points. Build configuration, documentation, and package version are updated throughout.

Changes

Bus lifecycle fixes, useServiceBus hook, and deriveProjectId

Layer / File(s) Summary
BusTui.connect() error handling and MemoryBusTui export
src/bus-tui.ts
BusTui class doc is updated to state connect() throws when the Go bus is unavailable. connect() removes the fallback path and always throws a descriptive error including the port and original message. MemoryBusTui is exported and documented as the explicit opt-in for in-process mode.
deriveProjectId utility
src/derive-project-id.ts
New deriveProjectId function performs FNV-1a 32-bit hashing over a directory string and returns the result as an 8-character zero-padded hex string.
useServiceBus hook implementation
src/tui-hooks.ts
useServiceBus hook manages BusTui.connect() on mount with a disposal guard and 5-second retry on failure. A reactive effect subscribes to the provided service/session/channel once both the bus handle and session ID are available, forwards envelope payloads to the callback, publishes a ping every 2 seconds until the first message is received, and cleans up the interval and subscription on dependency change or unmount.
TUI and main entry point exports, useProjectBus, and build config
src/tui.ts, src/index.ts, scripts/build.ts
TUI entry point re-exports MemoryBusTui, useServiceBus, and deriveProjectId, and adds useProjectBus which derives a stable project ID from a directory and delegates to useServiceBus. Main entry point re-exports deriveProjectId. Build script adds solid-js and @opentui/solid as externals for the TUI bundle.
Test comment, ISSUES.md, and version bump
test/integration.test.ts, ISSUES.md, package.json
Integration test header is updated to document that BusTui.connect() throws when the binary is unreachable. ISSUES.md is replaced with Known Issues entries for three lifecycle bugs (marked fixed), root causes, commit references, and a Lifecycle patterns summary. Package version is bumped from 0.6.0 to 0.6.6.

Sequence Diagram(s)

sequenceDiagram
  participant Component
  participant useServiceBus
  participant BusTui
  participant BusChannel

  Component->>useServiceBus: mount(service, sessionId, channel, onMessage)
  useServiceBus->>BusTui: connect()
  alt connect succeeds
    BusTui-->>useServiceBus: bus handle stored in signal
  else connect fails
    useServiceBus->>useServiceBus: schedule retry in 5s
  end

  useServiceBus->>useServiceBus: createEffect waits for bus handle and sessionId()
  useServiceBus->>BusChannel: subscribe(service/sessionId/channel)
  useServiceBus->>BusChannel: publish ping {ts: Date.now()}
  Note over useServiceBus,BusChannel: republish ping every 2s until first message

  BusChannel-->>useServiceBus: envelope received
  useServiceBus->>Component: onMessage(envelope.payload)
  useServiceBus->>useServiceBus: stop ping interval (confirmed)

  Component->>useServiceBus: unmount
  useServiceBus->>BusChannel: unsubscribe
  useServiceBus->>BusTui: close()
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • [FIX] MemoryBusTui never upgrades to real bus #13: This PR directly addresses the issue by removing the implicit MemoryBusTui fallback in BusTui.connect(), exporting MemoryBusTui for explicit opt-in use, and introducing the useServiceBus hook with retry logic to replace the behavior where the TUI would dead-end in the in-memory bus and never upgrade to the real bus connection.
Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: fixing MemoryBusTui upgrade behavior and implementing spawn lock mechanism (#13).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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 fix/13-memory-bus-upgrade
Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch fix/13-memory-bus-upgrade

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

@coderabbitai coderabbitai 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/bus-tui.ts (1)

237-260: ⚠️ Potential issue | 🔴 Critical

Add export keyword to MemoryBusTui class declaration.

The class is not exported, making it inaccessible to users despite documentation instructing them to instantiate MemoryBusTui directly. Change line 237 from class MemoryBusTui extends BusTui { to export class MemoryBusTui extends BusTui {.

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/bus-tui.ts` around lines 237 - 260, The MemoryBusTui class declaration is
not exported, which prevents external code from accessing it even though it is
documented for direct instantiation. Add the export keyword before the class
declaration for MemoryBusTui to make it accessible to users of the module.
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.

Outside diff comments:
In `@src/bus-tui.ts`:
- Around line 237-260: The MemoryBusTui class declaration is not exported, which
prevents external code from accessing it even though it is documented for direct
instantiation. Add the export keyword before the class declaration for
MemoryBusTui to make it accessible to users of the module.

Review info
Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b1ead0bc-b340-4dae-a3d3-3e841d86ea6b

Commits

Reviewing files that changed from the base of the PR and between 7fd6ecc and ccde741.

Files ignored due to path filters (5)
  • dist/bus-tui.d.ts is excluded by !**/dist/**
  • dist/index.js is excluded by !**/dist/**
  • dist/index.js.map is excluded by !**/dist/**, !**/*.map
  • dist/tui.js is excluded by !**/dist/**
  • dist/tui.js.map is excluded by !**/dist/**, !**/*.map
Files selected for processing (2)
  • src/bus-tui.ts
  • test/integration.test.ts

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 7 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread src/bus-tui.ts

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

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.

Inline comments:
In `@src/tui-hooks.ts`:
- Around line 40-42: Remove the explicit `as BusCallback` type cast in the
subscribe method call to enable proper TypeScript type inference. The inline
callback type annotation currently declares only `{ payload: unknown }` but the
actual envelope object contains additional properties (channel, payload, ts).
Delete the type cast and update the inline callback parameter type to accurately
reflect the full BusEnvelope structure that the subscribe method signature
expects, allowing TypeScript to infer the correct types automatically rather
than masking the mismatch with a cast.
- Around line 23-29: Add a disposed flag to track whether the component has been
unmounted before the BusTui.connect() promise resolves. Create this flag within
the onMount hook and set it to true in an onCleanup function. Then in the
.then() callback of the BusTui.connect() promise chain, check the disposed flag
before calling setBusTui(); if disposed is true, explicitly close the bus
connection. This prevents the memory leak where a successfully resolved bus
connection has no cleanup handler if unmounting occurs before the promise
settles.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

Review info
Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d434675b-9d96-4015-ba70-92dd3be75589

Commits

Reviewing files that changed from the base of the PR and between 0956990 and 6fcf394.

Files ignored due to path filters (4)
  • dist/tui-hooks.d.ts is excluded by !**/dist/**
  • dist/tui.d.ts is excluded by !**/dist/**
  • dist/tui.js is excluded by !**/dist/**
  • dist/tui.js.map is excluded by !**/dist/**, !**/*.map
Files selected for processing (3)
  • package.json
  • src/tui-hooks.ts
  • src/tui.ts
✅ Files skipped from review due to trivial changes (2)
  • package.json
  • src/tui.ts

Comment thread src/tui-hooks.ts
Comment thread src/tui-hooks.ts Outdated

@cubic-dev-ai cubic-dev-ai 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.

2 issues found across 7 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/tui-hooks.ts">

<violation number="1" location="src/tui-hooks.ts:25">
P2: Async connect result is not cancellation-safe; unmount-before-resolve can leak an open bus connection.</violation>

<violation number="2" location="src/tui-hooks.ts:26">
P2: Initial connection failures are silently dropped with no retry, so the hook can stay disconnected for the component lifetime.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread src/tui-hooks.ts Outdated
Comment thread src/tui-hooks.ts Outdated

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 1 file (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread ISSUES.md Outdated
Add unmount guard and reconnect-with-backoff to useServiceBus hook.
Prevents leaks when a TUI component unmounts while BusTui.connect()
is still in-flight (the resulting handle is closed immediately).
On connect failure, retries every 5s instead of silently giving up.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant