Skip to content

[Communication] PR4: IAgent and AgentBase Supports Mailbox Delivery#215

Open
Joseph0120 wants to merge 9 commits into
joseph/communication_delay_PR3from
joseph/communication_delay_PR4
Open

[Communication] PR4: IAgent and AgentBase Supports Mailbox Delivery#215
Joseph0120 wants to merge 9 commits into
joseph/communication_delay_PR3from
joseph/communication_delay_PR4

Conversation

@Joseph0120

Copy link
Copy Markdown
Collaborator

Files Modified:

AgentBase -> TryRegisterMailbox() when Start() or Awake(). Unsubscribe to mailbox when OnDestroy().
TryRegisterMailbox() subscribes to the mailbox, and prevents redundant registration.
HandleMailboxDelivery(IAgent receiver, Message message) Check if self is the right receiver, if so then handle the message. Because a popped message is broadcasted to all subscribed agents and it is the agent's responsibility to check if it is the recipient. (Mailbox sends mail to everyone, and only the right recipient has the "key" to unlock that message)

IAgent -> Added NodeType, which tells the mailbox what type of Agent it is reading from.

@stacklane-pr-stack-visualizer

stacklane-pr-stack-visualizer Bot commented Apr 1, 2026

Copy link
Copy Markdown

@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 implements a messaging system for agents by integrating AgentBase with a Mailbox service. It adds registration logic, message handling, and a new NodeType property to the IAgent interface. Feedback was provided regarding the performance of the broadcast-based message delivery and the need for a null check to handle destroyed Unity objects in the message handler.

Comment thread Assets/Scripts/Agents/AgentBase.cs
@coderabbitai

coderabbitai Bot commented Apr 1, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 223790bd-0af0-41a1-bc71-3e6978c6de6f

📥 Commits

Reviewing files that changed from the base of the PR and between a2a4c9e and 5ce599b.

📒 Files selected for processing (2)
  • Assets/Scripts/Communication/Mailbox.cs
  • Assets/Tests/EditMode/MailboxTests.cs

📝 Walkthrough

Walkthrough

AgentBase adds mailbox subscription state (_mailboxRegistered, _mailboxInstance), a protected virtual OnMessage(Message) hook, TryRegisterMailbox() called from Awake() and Start() to idempotently subscribe HandleMailboxDelivery to Mailbox.Instance.OnMessageDelivered, and unsubscription/reset in OnDestroy(). HandleMailboxDelivery forwards messages to OnMessage only when the delivered receiver equals the agent. Tests add a MailboxAwareAgentBase harness, reflection helpers to set singletons, and tests for idempotent registration, receiver filtering, unsubscription behavior, plus an edit-mode Mailbox creation test avoiding DontDestroyOnLoad.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • tryuan99
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.03% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title '[Communication] PR4: IAgent and AgentBase Supports Mailbox Delivery' directly describes the main change: adding mailbox delivery support to IAgent and AgentBase components.
Description check ✅ Passed The description explains the key modifications to AgentBase (TryRegisterMailbox, subscription management, HandleMailboxDelivery logic) and IAgent (NodeType addition), all of which are present in the changeset.
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 joseph/communication_delay_PR4

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.

❤️ Share

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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Assets/Scripts/Agents/AgentBase.cs`:
- Around line 358-362: HandleMailboxDelivery is currently invoked for every
subscriber causing O(n) broadcasts; change the Mailbox to dispatch directly to
the intended receiver instead of broadcasting: add a lookup (e.g.,
Dictionary<IAgent, Action<Message>> or Dictionary<IAgent, Queue<Message>>)
inside Mailbox and register agents when they subscribe, update the
Mailbox.Send/Deliver method to find the target IAgent via that dictionary and
call its registered handler (OnMessage) or enqueue the Message, and remove the
broadcast loop so HandleMailboxDelivery is no longer invoked for non-target
agents; ensure the dictionary uses thread-safe access (lock or
ConcurrentDictionary) and update subscription/unsubscription code to maintain
the map.
- Around line 222-225: The unsubscribe uses Mailbox.Instance but registration
used Mailbox.GetOrCreateInstance(), so store the mailbox reference when
registering (e.g., add a private field like _mailboxInstance and set it in
TryRegisterMailbox to Mailbox.GetOrCreateInstance()), use that stored
_mailboxInstance for adding/removing the HandleMailboxDelivery handler and for
null checks, set _mailboxRegistered = false and clear _mailboxInstance after
unsubscribing to avoid stale references and ensure consistent unsubscription.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7a15b87a-74af-4a86-a02b-7e725059abe0

📥 Commits

Reviewing files that changed from the base of the PR and between 66fd29c and 6c361dc.

📒 Files selected for processing (2)
  • Assets/Scripts/Agents/AgentBase.cs
  • Assets/Scripts/Agents/IAgent.cs

Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
@Joseph0120 Joseph0120 force-pushed the joseph/communication_delay_PR4 branch from 51491dc to a2a4c9e Compare June 6, 2026 22:11

@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: 1

🤖 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 `@Assets/Tests/EditMode/AgentBaseTests.cs`:
- Around line 256-257: Add a brief inline comment above the test lines calling
SetMailboxInstance(null) and _agent.InvokeOnDestroyForTest() explaining that the
test nulls the public MailboxInstance to ensure the agent's OnDestroy logic uses
its cached private _mailboxInstance for unsubscription (rather than re-querying
Mailbox.Instance), i.e., this verifies that the implementation unsubscribes from
the cached instance; reference SetMailboxInstance, MailboxInstance,
_mailboxInstance, Mailbox.Instance and InvokeOnDestroyForTest in the comment for
clarity.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 446e9387-893e-4b87-b923-258a3857cea3

📥 Commits

Reviewing files that changed from the base of the PR and between f132eca and a2a4c9e.

📒 Files selected for processing (2)
  • Assets/Scripts/Agents/AgentBase.cs
  • Assets/Tests/EditMode/AgentBaseTests.cs

Comment thread Assets/Tests/EditMode/AgentBaseTests.cs
if (_mailboxRegistered) {
return;
}
_mailboxInstance = Mailbox.GetOrCreateInstance();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There should always be an instance already, or am I missing something?

public class AgentBase : MonoBehaviour, IAgent {
// Make sure the same agent does not subscribe to the mailbox event more than once (keeping
// track).
private bool _mailboxRegistered = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

no need for this flag if you can check whether _mailbox is null?

// Make sure the same agent does not subscribe to the mailbox event more than once (keeping
// track).
private bool _mailboxRegistered = false;
private Mailbox _mailboxInstance;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
private Mailbox _mailboxInstance;
private Mailbox _mailbox;

// Start is called before the first frame update.
protected virtual void Start() {}
protected virtual void Start() {
TryRegisterMailbox();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why in Awake and Start? I think it should just be in Awake

Comment on lines +224 to +225
_mailboxRegistered = false;
_mailboxInstance = null;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

superfluous

Comment on lines +365 to +367
if (!ReferenceEquals(receiver, this)) {
return;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Idt you need this. Mailbox should have done the check already

};
}

protected virtual void OnMessage(Message message) {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'd rename this to be OnReceiveMessage to be precise

// Edit-mode tests can create a mailbox without entering play mode, where DontDestroyOnLoad is
// invalid.
if (Application.isPlaying) {
DontDestroyOnLoad(mailboxObject);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why is this necessary and not in the other singleton instances that use DontDestroyOnLoad(gameObject);?

}

private static void SetMailboxInstance(Mailbox mailbox) {
FieldInfo instanceField = typeof(Mailbox).GetField(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

No, this is not the right approach. I think you might need to use play mode tests for time.

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.

2 participants