Skip to content

Build integrations-update from @agent-relay/integration-prompts + suppress idle integrations#380

Merged
khaliqgant merged 2 commits into
mainfrom
gate-integrations-update-via-package
Jun 18, 2026
Merged

Build integrations-update from @agent-relay/integration-prompts + suppress idle integrations#380
khaliqgant merged 2 commits into
mainfrom
gate-integrations-update-via-package

Conversation

@khaliqgant

@khaliqgant khaliqgant commented Jun 18, 2026

Copy link
Copy Markdown
Member

Why

Two issues with the <integrations-update> context injected on agent spawn:

  1. Consume @agent-relay/integration-prompts for adapter doc parsing #379 didn't actually shorten it. That PR brought in @agent-relay/integration-prompts for adapter-doc parsing only. The verbose spawn narrative was still produced by a ~75-line hand-maintained copy of the package's fullInjectInstructions in src/main/integrations.ts.
  2. It showed up even when nothing was connected-and-active. A project full of visible-but-idle integrations (no history sync, no event subscription, no narrow writeback resources) still got the full narrative at spawn — pure noise.

What

  • Use the package. buildSystemMessageSnippet now maps each ConnectedIntegration into the package's IntegrationDescriptor and calls fullInjectInstructions, deleting the local duplicate. The opencode prescriptiveSpawnInstructions table is unchanged (it's more capable than the package's generic builder).

  • Gate idle integrations. New buildActiveIntegrationDescriptors keeps only integrations that are:

    • syncingdownloadHistoricalData on, or
    • listening — has an event subscription (subscribeAgent + event globs), or
    • actionable — narrow writeback command roots mounted.

    When none qualify, the message is suppressed entirely — at spawn (initialSpawnInstructions returns undefined) and on state-change broadcasts — instead of injecting an empty - none snippet.

  • Removes the now-unused subscriptionsReady plumbing; "listening" is derived from integration config directly (the package has no readiness concept). This also drops the old "subscriptions requested but not registered yet" warning.

Notes / tradeoffs

  • "actionable" is a deliberate extension of the literal "syncing or events listening" ask: a mounted writeback root is the only place a Claude agent learns it can write back, so hiding it would remove a capability the user explicitly scoped. It doesn't affect the idle case (still suppressed).
  • Test fixtures that used idle/empty integrations as stable broadcast/dedup baselines were updated to active fixtures (subscription summaries are mocked to [] in tests, so fixtures activate via narrow paths / history).

Test plan

  • vitest run src/main/integrations.test.ts — 56/56
  • vitest run src/main/ipc-handlers.test.ts — 25/25
  • tsc --noEmit clean, eslint clean

🤖 Generated with Claude Code

Review in cubic

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@khaliqgant, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 42 minutes and 11 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f81132ec-d212-4b20-9dd7-48d6178d461b

📥 Commits

Reviewing files that changed from the base of the PR and between 241c24c and e7f72f2.

📒 Files selected for processing (2)
  • src/main/integrations.test.ts
  • src/main/integrations.ts
📝 Walkthrough

Walkthrough

The PR refactors system message snippet generation in integrations.ts from a hand-built narrative to a descriptor-driven approach using a new buildActiveIntegrationDescriptors helper and buildIntegrationsUpdateSnippet. The subscriptionsReady boolean state and parameter are removed throughout. Tests are updated to match the new signatures and fixture baselines.

Changes

Descriptor-driven integration snippet builder

Layer / File(s) Summary
Core snippet builder rewrite and state removal
src/main/integrations.ts
Imports fullInjectInstructions (aliased as buildIntegrationsUpdateSnippet) and IntegrationDescriptor; removes lastSubscriptionsReady state; updates syncAgentState to drop the readiness-result capture; rewrites buildSystemMessageSnippet with a new buildActiveIntegrationDescriptors helper that computes active descriptors from historical-download enablement, writeback mounts, and subscription summaries, then renders via buildIntegrationsUpdateSnippet; returns '' when no descriptors are active; skips the spawn integration-update message in initialSpawnInstructions when the snippet is empty.
Test fixture updates and call-site alignment
src/main/integrations.test.ts
Updates the default initialIntegration() fixture to scope to channel C123 with subscribeAgent: true; removes the subscriptionsReady field from the SystemMessageSnippetBuilder type cast and drops the extra boolean argument from three buildSystemMessageSnippet call sites; pins non-empty Slack integration state via makeIntegration() in broadcast-retry, newly-arrived-agent, rebroadcast-cooldown, and dedupe-window scenarios; narrows Linear fixture mountPaths to /linear/issues and aligns subscribeAgent/downloadHistoricalData across staged-churn tests.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • AgentWorkforce/pear#154: Both PRs modify buildSystemMessageSnippet and Slack integration mount-path logic in src/main/integrations.ts.
  • AgentWorkforce/pear#375: Both PRs touch IntegrationsManager's spawn instruction generation path (initialSpawnInstructions / system-message snippet construction).

Poem

🐰 No more booleans to track,
The subscriptions ready knack —
Descriptors now lead the way,
Active integrations hold sway.
Empty snippets? Skip the spawn!
A cleaner narrative is drawn. 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the two main changes: using @agent-relay/integration-prompts for the integrations-update builder and suppressing idle integrations from appearing in the spawn narrative.
Description check ✅ Passed The description is directly related to the changeset, providing clear rationale for the changes (eliminating duplicate code and suppressing idle integrations), implementation details, and test coverage confirmation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch gate-integrations-update-via-package

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.

@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 refactors the generation of integration system message snippets by delegating the narrative construction to a shared builder from @agent-relay/integration-prompts. It also introduces filtering to omit idle integrations (those without historical downloads, active event subscriptions, or narrow writeback command roots) to prevent noisy or empty messages. The review feedback identifies a bug in buildActiveIntegrationDescriptors where checking subscribedProviders.has(integration.provider) incorrectly marks all integrations of a provider as active if at least one has an active subscription, and provides a code suggestion to check each integration's subscribeAgent status directly.

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/integrations.ts Outdated
Comment on lines +2288 to +2302
const subscriptionSummaries = integrationSubscriptionSummaries(integrations)
const subscribedProviders = new Set(subscriptionSummaries.map((summary) => summary.provider))

const descriptors: IntegrationDescriptor[] = []
for (const integration of integrations) {
const historyEnabled = integration.downloadHistoricalData === true
const eventScopePaths = this.canonicalMountPathsForIntegration(integration)
.map(projectIntegrationPathForRelayfilePath)
const writebackCommandPaths = writebackCommandMountPathsForIntegration(integration)
.map(projectIntegrationPathForRelayfilePath)

if (integrations.length === 0) {
lines.push('- none')
} else {
for (const integration of integrations) {
const scopeLabels = collectScopeLabels(integration.scope)
const scopeSummary = scopeLabels.length > 0 ? scopeLabels.join(', ') : 'all configured scope'
const mountPaths = this.canonicalMountPathsForIntegration(integration)
.map(projectIntegrationPathForRelayfilePath)
const discoveryPath = projectIntegrationPathForRelayfilePath(discoveryMountPathForProvider(integration.provider))
const writebackCommandPaths = writebackCommandMountPathsForIntegration(integration)
.map(projectIntegrationPathForRelayfilePath)
const liveContextPaths = integration.downloadHistoricalData === true
? []
: slackThreadContextMountPathsForIntegration(integration)
.map(projectIntegrationPathForRelayfilePath)
const historyEnabled = integration.downloadHistoricalData === true
const writebackPaths = historyEnabled
? mountPaths.join(', ') || 'the configured provider paths'
: writebackCommandPaths.join(', ')
const writebackInstruction = writebackPaths
? `create writeback files under ${writebackPaths}, not under discovery`
: 'select narrower resources before creating local writeback files; discovery is schema-only'
const skippedHistoryPaths = skippedHistoricalMountPathsForIntegration(integration)
.map(projectIntegrationPathForRelayfilePath)
const skippedCappedPaths = skippedCappedLocalSyncMountPathsForIntegration(integration)
const isActive = historyEnabled
|| writebackCommandPaths.length > 0
|| subscribedProviders.has(integration.provider)
if (!isActive) continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

When a project has multiple integrations of the same provider (e.g., multiple Slack workspaces), checking subscribedProviders.has(integration.provider) will incorrectly mark all integrations of that provider as active if at least one of them has an active subscription. This defeats the purpose of suppressing idle integrations. Instead, we should check the subscribeAgent status of the specific integration directly.

    const subscriptionSummaries = integrationSubscriptionSummaries(integrations)

    const descriptors: IntegrationDescriptor[] = []
    for (const integration of integrations) {
      const historyEnabled = integration.downloadHistoricalData === true
      const eventScopePaths = this.canonicalMountPathsForIntegration(integration)
        .map(projectIntegrationPathForRelayfilePath)
      const writebackCommandPaths = writebackCommandMountPathsForIntegration(integration)
        .map(projectIntegrationPathForRelayfilePath)

      const isListening = integration.subscribeAgent === true && (
        eventScopePaths.length > 0 ||
        (toRelayfileProvider(integration.provider) === 'slack' && slackListenDms(integration))
      )
      const isActive = historyEnabled
        || writebackCommandPaths.length > 0
        || isListening
      if (!isActive) continue

@khaliqgant khaliqgant force-pushed the gate-integrations-update-via-package branch from 241c24c to ad13f63 Compare June 18, 2026 13:10

@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 `@src/main/integrations.test.ts`:
- Around line 1173-1175: The makeIntegration helper function currently returns a
hardcoded empty scope object, but the type system now expects integrations with
provider-specific scope shapes (like scope with channels for Slack). Update the
makeIntegration function to accept an optional scope parameter as a second
argument, and set provider-appropriate default values: for the 'slack' provider,
default to scope with an empty channels array if no scope is provided, and for
other providers use an empty scope. Then update the calls to makeIntegration at
lines 1175, 1207, 1313, and 1355 to pass the required scope data (such as the
channels array ['C123']) as the second argument where needed.
🪄 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: 79ae12cf-39e0-4161-b765-b1af203790e2

📥 Commits

Reviewing files that changed from the base of the PR and between d56abd5 and 241c24c.

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

Comment thread src/main/integrations.test.ts

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 241c24ce31

ℹ️ 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".

Comment thread src/main/integrations.ts
// entirely — a visible-but-idle integration adds only noise at spawn.
private buildSystemMessageSnippet(integrations: ConnectedIntegration[]): string {
const descriptors = this.buildActiveIntegrationDescriptors(integrations)
if (descriptors.length === 0) return ''

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Send a clearing update when integrations become inactive

When the last active integration is removed or disabled, callers such as disconnect() still invoke syncAgentState(..., true), but this early return turns the broadcast into a no-op. Existing agents that previously received an integrations update never get the old clearing/- none message, so they can keep attempting stale writebacks or waiting on subscriptions after the integration is gone; suppressing idle context should only apply to spawn/no-op cases, not state transitions that clear prior state.

Useful? React with 👍 / 👎.

Comment thread src/main/integrations.ts
const integrations = this.visibleIntegrationsForProject(projectId)
const subscriptionsReady = await this.syncEventSubscriptions(projectId)
this.lastSubscriptionsReady.set(projectId, subscriptionsReady)
await this.syncEventSubscriptions(projectId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve failed subscription registration in the prompt

When syncEventSubscriptions returns false for Relayfile/account auth failures or reconcile errors, this result is now discarded and the later descriptor builder still renders subscriptions from config as active. That regresses the previous warning path for “requested but not registered yet,” so agents can be told to wait for integration events that were not actually registered, and the prompt text no longer changes when registration later recovers.

Useful? React with 👍 / 👎.

…+ gate idle integrations

The <integrations-update> spawn narrative was a ~75-line hand-maintained
copy of @agent-relay/integration-prompts' fullInjectInstructions. Map
ConnectedIntegration -> the package's IntegrationDescriptor and call the
shared builder instead, deleting the duplicate.

Also stop emitting the message for integrations that aren't doing
anything. buildActiveIntegrationDescriptors keeps only integrations that
are syncing (downloadHistoricalData), listening (event subscription), or
actionable (narrow writeback roots mounted). When none qualify the whole
message is suppressed at both spawn (initialSpawnInstructions) and on
state-change broadcasts, instead of injecting an empty "- none" snippet.

Drops the unused subscriptionsReady plumbing; listening is derived from
integration config directly (matching the package, which has no
readiness concept). Test fixtures that used idle/empty integrations as
stable broadcast/dedup baselines now use active fixtures.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@khaliqgant khaliqgant force-pushed the gate-integrations-update-via-package branch from ad13f63 to 4474091 Compare June 18, 2026 13:16
- Fix per-provider listening collision (gemini): derive "listening" per
  integration via integrationSubscriptionSummaries([integration]) instead
  of a provider-keyed set, so one subscribed Slack workspace no longer
  marks every Slack integration active. Also de-duplicates the rendered
  subscription list across same-provider descriptors.
- Fix CI typecheck failure (coderabbit / GitHub checks): revert the
  default test fixture scope to {} (it activates via its narrow channel
  mountPath, not scope) so the mock store's inferred element type stops
  rejecting the {} / { listenDms } fixtures elsewhere. tsconfig.node.json
  includes tests; tsconfig.json does not, which is why it was missed.
- Send one clearing update on active->none transitions (codex P2): when
  the last active integration is disconnected, already-notified agents now
  get a "- none" update instead of silence, so they stop relying on stale
  context. Idle suppression still applies to spawn/no-op.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@khaliqgant

Copy link
Copy Markdown
Member Author

Addressed review feedback in e7f72f2:

✅ Gemini (HIGH) — per-provider listening collision (integrations.ts): switched from a provider-keyed Set to a per-integration check, integrationSubscriptionSummaries([integration]).length > 0. One subscribed Slack workspace no longer marks every Slack integration active, and it also de-duplicates the rendered subscription list across same-provider descriptors. Used the canonical summary fn (rather than re-deriving subscribeAgent + globs inline) to avoid drift with how subscriptions are actually computed.

✅ CodeRabbit / GitHub checks — typecheck failure: real failure I missed locally — tsconfig.node.json includes test files but the tsconfig.json I'd been checking does not. Root cause was changing the default fixture's scope to { channels: [...] }, which narrowed the mock store's inferred element type and rejected the {} / { listenDms } fixtures elsewhere. Fixed by reverting that scope to {} — the fixture activates via its narrow channel mountPath, not scope — which is simpler than threading a scope param through makeIntegration (and avoids the Record<string, unknown> widening that wouldn't satisfy the inferred type anyway).

✅ Codex (P2) — clearing update on disconnect: good catch. Added a one-time clearing broadcast on active→none transitions: a project that previously broadcast/spawned a non-empty update now sends a - none update when its last active integration is removed, so already-notified agents stop relying on stale context. Idle suppression still applies to spawn/no-op. Covered by a new test.

↩️ Codex (P2) — preserve failed subscription-registration warning: declining intentionally. Dropping the subscriptionsReady "requested but not registered yet" branch was a deliberate part of this change — the shared @agent-relay/integration-prompts builder has no readiness concept, and re-introducing the warning would mean forking the builder's output again (the whole point was to stop hand-maintaining that text). The accuracy gap is real but narrow (a transient window where config says subscribed but Relayfile hasn't ack'd registration); the agent reconciles from the mounted files regardless. If this proves to matter in practice, the right fix is to add a readiness signal to the package, not to re-fork the narrative here.

New test coverage: per-integration listening path + active→none clearing. Suite 58/58, ipc-handlers 25/25, typecheck:node + typecheck:web clean, eslint clean.

@khaliqgant khaliqgant merged commit 6d52cdd into main Jun 18, 2026
5 checks passed
@khaliqgant khaliqgant deleted the gate-integrations-update-via-package branch June 18, 2026 13:28
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