Repository navigation
fix(agents): heartbeat always targets main session — prevent routing to active subagent sessions - #61526
fix(agents): heartbeat always targets main session — prevent routing to active subagent sessions#61526100yenadmin wants to merge 220 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR aims to ensure the built-in heartbeat always runs against the configured main agent session (typically agent:main:main), preventing accidental routing into active subagent sessions that can corrupt subagent task results.
Changes:
- Removes
agentIdinference fromopts.sessionKeyinrunHeartbeatOnce. - Replaces prior “session override routing” coverage with a regression test intended to prove subagent-scoped session overrides still run heartbeats through the main session.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| src/infra/heartbeat-runner.ts | Changes how agentId is derived for a heartbeat run (no longer inferred from sessionKey). |
| src/infra/heartbeat-runner.returns-default-unset.test.ts | Adds/rewrites a regression test asserting heartbeats remain anchored to the main session even with subagent session keys present. |
| }): Promise<HeartbeatRunResult> { | ||
| const cfg = opts.cfg ?? loadConfig(); | ||
| const explicitAgentId = typeof opts.agentId === "string" ? opts.agentId.trim() : ""; | ||
| const forcedSessionAgentId = | ||
| explicitAgentId.length > 0 ? undefined : parseAgentSessionKey(opts.sessionKey)?.agentId; | ||
| const agentId = normalizeAgentId( | ||
| explicitAgentId || forcedSessionAgentId || resolveDefaultAgentId(cfg), | ||
| ); | ||
| const agentId = normalizeAgentId(explicitAgentId || resolveDefaultAgentId(cfg)); | ||
| const heartbeat = opts.heartbeat ?? resolveHeartbeatConfig(cfg, agentId); |
There was a problem hiding this comment.
This change stops deriving agentId from opts.sessionKey, but opts.sessionKey is still forwarded into resolveHeartbeatPreflight as forcedSessionKey (and resolveHeartbeatSession will prefer it when it matches the agent). That means a subagent session key like agent:main:subagent:... can still become the heartbeat sessionKey/lane and corrupt subagent runs, so this doesn’t actually implement the PR’s stated goal by itself. Consider explicitly ignoring/overriding subagent-scoped session keys (e.g., via isSubagentSessionKey) for heartbeat session resolution so heartbeats always use the agent main session key.
| const agentId = normalizeAgentId( | ||
| explicitAgentId || forcedSessionAgentId || resolveDefaultAgentId(cfg), | ||
| ); | ||
| const agentId = normalizeAgentId(explicitAgentId || resolveDefaultAgentId(cfg)); |
There was a problem hiding this comment.
By removing the fallback parseAgentSessionKey(opts.sessionKey)?.agentId, callers that pass only sessionKey (no agentId) to target a non-default agent will now silently run the heartbeat under the default agent’s config/session. If this is an intentional API change, it should be enforced explicitly (e.g., require agentId when sessionKey belongs to a different agent, or log/throw) to avoid surprising plugin/runtime callers.
| const agentId = normalizeAgentId(explicitAgentId || resolveDefaultAgentId(cfg)); | |
| const normalizedExplicitAgentId = explicitAgentId ? normalizeAgentId(explicitAgentId) : ""; | |
| const sessionAgentId = | |
| typeof opts.sessionKey === "string" && opts.sessionKey.trim() | |
| ? normalizeAgentId( | |
| resolveAgentIdFromSessionKey(opts.sessionKey) ?? | |
| parseAgentSessionKey(opts.sessionKey)?.agentId ?? | |
| "", | |
| ) | |
| : ""; | |
| if ( | |
| normalizedExplicitAgentId && | |
| sessionAgentId && | |
| normalizedExplicitAgentId !== sessionAgentId | |
| ) { | |
| throw new Error( | |
| `runHeartbeatOnce received mismatched agentId "${normalizedExplicitAgentId}" and sessionKey for agent "${sessionAgentId}"`, | |
| ); | |
| } | |
| const agentId = normalizeAgentId( | |
| normalizedExplicitAgentId || sessionAgentId || resolveDefaultAgentId(cfg), | |
| ); |
| const subagentSessionKey = `agent:${agentId}:subagent:test-heartbeat-routing`; | ||
| if (cfg.agents?.defaults?.heartbeat) { | ||
| cfg.agents.defaults.heartbeat.session = subagentSessionKey; | ||
| } |
There was a problem hiding this comment.
This test configures cfg.agents.defaults.heartbeat.session to a subagent session key (agent:...:subagent:...). With the current resolveHeartbeatSession logic, that value is treated as a valid session override and will be selected as the heartbeat session, so the later expectations that SessionKey is the main session key won’t hold unless production code is also updated to reject subagent keys for heartbeat session overrides.
| }); | ||
| await runHeartbeatOnce({ | ||
| cfg, | ||
| sessionKey: subagentSessionKey, |
There was a problem hiding this comment.
This call passes sessionKey: subagentSessionKey, but the assertions below expect the heartbeat to run and reply under mainSessionKey. As implemented, resolveHeartbeatSession prefers the forced session key when provided (and same-agent), so this will continue to route the heartbeat through the subagent session unless the runner filters/normalizes subagent session keys before preflight.
| sessionKey: subagentSessionKey, | |
| sessionKey: mainSessionKey, |
| every: "5m", | ||
| target: "last", | ||
| }, | ||
| it("keeps heartbeat runs on the main session even when heartbeat.session targets a peer session", async () => { |
There was a problem hiding this comment.
The test description says "peer session" but the override used is a subagent session key. Either the test name should reflect subagent routing explicitly, or the setup should use an actual peer session key (e.g. a channel/group session) to match the wording.
| it("keeps heartbeat runs on the main session even when heartbeat.session targets a peer session", async () => { | |
| it("keeps heartbeat runs on the main session even when heartbeat.session targets a subagent session", async () => { |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 558d7d1577
ℹ️ 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".
| "[email protected]", | ||
| "Main alert", |
There was a problem hiding this comment.
Assert the session chosen by heartbeat preflight
This test now expects heartbeat delivery to stay on mainSessionKey, but the implementation still honors same-agent sessionKey / heartbeat.session overrides via resolveHeartbeatSession in src/infra/heartbeat-runner.ts, so runHeartbeatOnce({ sessionKey: subagentSessionKey, ... }) resolves to the subagent session entry instead. That makes this expectation inconsistent with runtime behavior and causes the regression test to fail rather than validate the intended fix.
Useful? React with 👍 / 👎.
Greptile SummaryThis PR removes the inferred- Key changes:
Issues found:
Confidence Score: 1/5Not safe to merge: a confirmed unused import will break the lint gate, and the routing fix appears incomplete — the new regression test likely fails as written. Score of 1 reflects two concrete issues found during review: (1) removing the
|
…agent sessions Fixes #58878 runHeartbeatOnce() was inferring the heartbeat agent from opts.sessionKey, causing heartbeat turns to route into active subagent sessions instead of the main session. Now anchored to the configured/default main agent. Test added: seeds both main and subagent sessions, verifies heartbeat stays on main even when given a subagent session key.
100yenadmin
left a comment
There was a problem hiding this comment.
Subagent session keys are never valid heartbeat targets. Stripping them is intentional and safe.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d105922f64
ℹ️ 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".
|
|
||
| const forced = forcedSessionKey?.trim(); | ||
| if (forced) { | ||
| if (forced && !isSubagentSessionKey(forced)) { |
There was a problem hiding this comment.
Reject subagent heartbeat.session overrides too
This change only blocks subagent keys in the forcedSessionKey path, but heartbeat.session is still resolved through the same-agent canonicalization path below, which continues to accept agent:<id>:subagent:*. In that configuration, heartbeat preflight still binds to the subagent session entry and routes/delivers from that lane instead of the agent main session, so the fix does not actually enforce main-session routing and the new regression scenario remains broken.
Useful? React with 👍 / 👎.
* memory: add REM preview and safe promotion replay thanks @mbelinky * changelog: note REM preview and promotion replay --------- Co-authored-by: Vignesh <[email protected]>
Fixes #60555 - resolveSessionKeyForRequest() called with sessionId only (not agentId) - consolidated to single early backfill path - whitespace normalization for sessionKey - warn log on backfill failure - e2e test for resolver failure fallback - SSE seq assertion corrected after NO_REPLY
…eplay splitting Fixes #61476 Untagged text blocks in mixed assistant messages were forced to undefined phase when any sibling had an explicit textSignature phase. Now they correctly inherit the message-level assistantMessagePhase, preventing commentary leaks during history replay. Removes the hasExplicitBlockPhase scan — untagged blocks always inherit m.phase. Blocks with explicit textSignature.phase still use their own. 94/94 tests pass. Regression test added for mixed explicit/untagged blocks.
|
Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch. |
|
Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7a497f0b72
ℹ️ 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".
| channel: | ||
| entry.deliveryContext?.channel ?? | ||
| entry.lastChannel ?? | ||
| entry.channel ?? | ||
| entry.origin?.provider, |
There was a problem hiding this comment.
Keep last-session fields as primary announce origin
This extracted deliveryContextFromSession now prioritizes entry.deliveryContext over lastChannel/lastTo/lastThreadId, which reverses the previous behavior from src/utils/delivery-context.ts where last* fields were the primary route and deliveryContext was fallback. When those fields diverge (for example legacy or partially migrated session rows), subagent completion announces can be routed to an older channel/thread instead of the most recent conversation, causing user-visible misdelivery.
Useful? React with 👍 / 👎.
| return requesterTarget !== entryTarget; | ||
| } | ||
| } | ||
| return false; |
There was a problem hiding this comment.
Preserve plugin thread-strip hook in announce origin
The new shouldStripThreadFromAnnounceEntry implementation only handles Telegram and then unconditionally returns false, so channel plugins' conversationBindings.shouldStripThreadFromAnnounceOrigin callback is no longer consulted. That regresses the public channel-plugin contract (see src/channels/plugins/types.adapters.ts) and can keep stale thread IDs for non-Telegram channels, causing subagent announce messages to post into the wrong thread/conversation.
Useful? React with 👍 / 👎.
Fixes #58878
Summary
Fixes #58878