Skip to content

perf(main): MCP deadlines and caching, bounded background work - #328

Merged
sambitcreate merged 12 commits into
mainfrom
perf/mcp-network-background
Oct 4, 2026
Merged

sambitcreate merged 12 commits into
mainfrom
perf/mcp-network-background

Conversation

@sambitcreate

@sambitcreate sambitcreate commented Oct 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • MCP (MAIN-20, MAIN-21): tool lists are cached, and servers are discovered in parallel under deadlines, so a hung server can't stall a turn.
  • Telegram (MAIN-26): requests are bounded and thinking edits are coalesced.
  • Cloud voice: transcription requests are bounded.
  • Subagents (MAIN-24): process identity is read without blocking the event loop.
  • Scheduled catch-up (MAIN-25): bounded and staggered, at most 2 at once and lock-aware.
  • Background work (MAIN-28):
    • Hidden browser picture-in-picture pauses and skips unchanged frames.
    • Voice status no longer forks the speech worker.
    • Portable-config refresh on window focus is throttled.
  • Deferred: MAIN-33.

Test plan

  • MCP discovery, Telegram, scheduler and transcription suites.
  • Type-check.

Flaky tests

  • tests/e2e/chat-message-queue.spec.ts:372 "Steer on a queued message adds it to the running response once" (Linux x64 E2E). It failed, then passed on retry, which --fail-on-flaky-tests reports as a failure. Symptom: the queue showed 1 item when 2 were expected, at line 385. The test fills and submits the second queued message without waiting for the first to land, and the composer drops an Enter while a submit is still pending. This PR does not touch the queue or composer. Run: https://github.com/sambitcreate/aiden-agent/actions/runs/37194113019/job/111412327316

Part of the October optimization pass. Finding IDs refer to docs/performance/optimization-audit-2026-10-03.md (#320). The branch's .memory/ note has per-finding rationale.

🤖 Generated with Claude Code

sambitcreate and others added 8 commits October 3, 2026 06:49
…deadlines (MAIN-20, MAIN-21)

- Cache tools/list per connected client; notifications/tools/list_changed
  and reconnects invalidate it, so a warm generation issues no tools/list.
- Discover enabled servers concurrently with Promise.allSettled. Connect
  (initialize) is bounded at 10 s, tools/list at 5 s, and each server's
  whole step at 17 s; a server that misses its deadline loses its tools for
  the turn and is reported as a timed-out mcp-degraded diagnostic.
- Tool calls pass an explicit 60 s timeout and maxTotalTimeout alongside
  the caller's signal (unchanged from the SDK default bound).
- closeAll disconnects servers in parallel and shutdown awaits it within a
  2 s budget. Connections idle for 10 minutes are closed without
  superseding their generation, so an older turn's tools reconnect on use.
- Removing a server prunes its generation bookkeeping. Generations now come
  from one monotonic sequence so pruning cannot revive a stale caller.
- The merge step moved into a pure core with behavioral tests, replacing
  the mcp.ts source-grep assertion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-26)

Every Bot API fetch now carries a deadline combined with the caller's
signal: long polls get the poll window plus 10 s, file downloads and
uploads get size-scaled deadlines, and stopping the poller aborts the
in-flight getUpdates socket instead of only abandoning it. Streamed
reasoning edits are coalesced to one per 900 ms with the latest text,
and unchanged renders are skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OpenAI and Gemini transcription now run under a size-scaled deadline
(2 min base, 5 min cap) that covers upload, response and body read, even
for callers without a signal such as Telegram voice notes. A deadline
abort is reported as a timeout; user cancellation passes through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… loop (MAIN-24)

The PID-reuse fence now reads ps asynchronously. Launch keeps its ten
25 ms identity attempts, concurrent reads share one ps, and hard-kill and
exit proofs are awaited by the owner, re-checking the exit flag after the
read. Owner semantics are unchanged: indeterminate proof still fails closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Startup catch-up of missed runs now goes through a queue that runs at
most two at a time, 3 s apart, holds while the screen is locked, and
re-evaluates on resume and unlock. Stopping the service drops queued
entries so a restart starts clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Focus storms now cost one re-read per 2 s plus one trailing pass. An
mtime gate was not used: DataStore.reload deliberately avoids stat
gating because coarse mtimes can drop a second edit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d (MAIN-28)

Whether the native engine loads is fixed for the app's lifetime, so the
first engine answer is reused; transient launch failures are not cached.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

Two lifecycle regressions need attention before merging: deferred catch-up can execute an already-claimed run, and MCP reconnection loses tool-result validation.

Reviewed changes — Reviewed all 27 changed files across the eight commits at 65e31702.

  • MCP discovery and lifecycle: Parallel discovery under deadlines, per-client tool-list caching and invalidation, idle expiry with reconnect, and bounded shutdown.
  • Network requests: Telegram polling, JSON calls, and file transfers gain cancellation/deadlines; cloud transcription gains an audio-size-based deadline.
  • Scheduled catch-up: Missed startup runs use two concurrent slots, staggered starts, and screen-lock deferral.
  • Background activity: Thinking edits coalesce, process-identity checks become asynchronous, config focus refreshes throttle, voice status caches, and browser PiP skips hidden or unchanged frames.

Validation: MCP, scheduler, Telegram, voice, portable-config, and focused subagent-process tests passed, as did npm run type-check; three platform-specific voice tests skipped. Separate behavioral probes reproduced both inline findings. Hosted CI remains pending on this head.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

Comment on lines 451 to +453
const ownsCatchup = () => isCurrent() && jobs.get(latest.id) === job;
const result = dispatch(latest.id, { automatic: true, isCurrent: ownsCatchup });
if (result.kind === "dispatched") {
void result.completion.catch((error) =>
catchUp.enqueue(() => {
const result = dispatch(latest.id, { automatic: true, isCurrent: ownsCatchup });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Recheck the overdue claim when a catch-up leaves the queue

A catch-up deferred while the screen is locked can survive a normal Cron execution, because its ownership predicate only checks the startup revision and job identity. If Cron finishes before unlock, it has already advanced nextRunAt into the future, yet this callback executes the task again, duplicating script/tool side effects and model usage.

Technical details
# A queued catch-up outlives its durable due claim

## Affected sites
- main/services/schedule-service-core.ts:451-458 — queued ownership does not check whether the missed run remains due.
- The existing Cron callback uses dispatch(), whose advanceBeforeRun() consumes the overdue timestamp without replacing the Cron job.

## Reproduction
1. Save an enabled task with nextRunAt in the past.
2. Start the real service with catchUp.shouldDefer returning true.
3. Trigger that task's Cron job and let execution complete. Its stored nextRunAt is now in the future.
4. Clear deferral and call reevaluateCatchUp(). The executor is called a second time.

This reproduced with the real service/store and Croner job.trigger(); it also applies when queue saturation delays catch-up past a normal Cron firing.

## Required outcome
- Dequeue only a still-pending overdue claim. A Cron dispatch that has already consumed that claim must invalidate the queued catch-up.
- Fence the due-state recheck and dispatch against task lifecycle changes; preserve the existing cancellation/publication ownership guarantees.
- Add service-level coverage for a normal Cron run completing while catch-up is deferred.

Queued catch-up at the reviewed head

Comment thread main/services/mcp.ts
Comment on lines +335 to +338
const live = this.clients.isConnected(server.id, client)
? client
: await this.ensureConnected(server, generation);
return await request(live);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Initialize tool metadata on the replacement client

After idle expiry, ensureConnected() creates a fresh SDK client and this path immediately invokes callTool() without listing its tools. The SDK's output-schema validators are populated by listTools(), so the same invalid structured result that failed before expiry is now accepted and passed to the model.

Technical details
# Reconnection skips per-client SDK tool metadata

## Affected sites
- main/services/mcp.ts:335-338 — withLiveClient() invokes requests on a replacement client before any tools/list.
- main/services/mcp.ts:460-472 — retained AgentTool closures call live.callTool() through this path.
- main/services/mcp-tool-discovery-core.ts:148-165 — the normal cached listing invokes SDK listTools(), which populates client-local metadata.

## Evidence
In the pinned SDK 1.30.0, listTools() calls cacheToolMetadata(); callTool() reads the cached output validator. Required-task metadata is also client-local. Client.connect() does not populate either cache.

A real in-memory SDK probe listed a tool whose output schema requires an integer count. A result with structuredContent { count: "invalid" } was rejected by the listed client, but accepted by a replacement client connected without listTools(), matching the new reconnect path.

## Required outcome
- Prime a replacement client's tool metadata with a bounded listing before invoking a server tool, retaining the existing per-client caching.
- Preserve output-schema validation and required-task handling after idle expiry.
- Cover a retained tool executing after idle close with an invalid structured result; it must fail as it does before expiry.

Reconnect path at the reviewed head. The upstream SDK implementation documents and implements the listTools() metadata cache used by callTool().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@very-hermes-bot

very-hermes-bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Hermes Review Bot

Confidence: 5

Engine: agy/gemini-3.8-flash-high
Review mode: full
Head: 47a84fc654ffdc11afd2798726cdf9ef82932e09
Generated: 2026-10-04T13:27:24+00:00
Reviews: 1

Summary

This change bounds latency, concurrency, and resource consumption across several background subsystems identified in the performance audit (MAIN-20, MAIN-21, MAIN-24, MAIN-25, MAIN-26, and MAIN-28). It parallelizes MCP server discovery under explicit timeouts with client-scoped tool list caching and transparent idle reconnection; bounds Telegram API requests, aborts stalled long polls, and throttles thinking preview updates to 900 ms; bounds cloud voice transcription requests; makes subagent process identity checks asynchronous via non-blocking process inspection; staggers overdue scheduled tasks to at most two concurrent runs while deferring during screen lock; and eliminates redundant work in hidden browser PiP, voice engine status reads, and window focus configuration reloads. Maintainers should double-check that third-party MCP servers that are slow to initialize (over 10 seconds) or list tools (over 5 seconds) are intended to be skipped and reported as degraded rather than blocking turns.

Confidence Score: 5/5

Every touched surface was inspected end-to-end against caller/callee contracts, cancellation and failure paths, concurrency semantics, and accompanying unit and behavioral test suites.

📁 Important Files Changed
  • main/services/mcp-tool-discovery-core.ts: Core discovery logic containing McpToolListCache, request deadlines, settleMcpServerDiscovery, mergeMcpServerDiscovery, and McpConnectionActivity.
  • main/services/mcp.ts: Integrates discovery deadlines, tool caching, transparent idle client reconnection in withLiveClient, idle connection sweeps, and bounded parallel shutdown in closeAllWithin.
  • main/services/generation-bound-connection-cache.ts: Introduces monotonic GenerationCounters for safe ID pruning, adds closeIdle for non-superseding drops, and tracks active/connected state.
  • main/services/telegram/telegram-bot-api.ts: Applies size-scaled deadlines to file transfers, bounds JSON requests and long polls, and forwards abort signals directly to underlying fetch requests.
  • main/services/telegram/telegram-activity.ts: Coalesces streaming reasoning updates to at most one edit per 900 ms window, suppressing duplicate HTML and flushing final drafts on settle.
  • main/services/transcription-core.ts & main/services/transcription.ts: Implements startTranscriptionDeadline to bound OpenAI and Gemini transcription requests by audio size even when callers supply no cancellation signal.
  • main/services/subagents/subagent-inference-process.ts & main/services/subagents/subagent-inference-process-core.ts: Replaces synchronous execFileSync process inspection with asynchronous execFile, single-flights identity captures, and awaits asynchronous process proofs during process shutdown.
  • main/services/schedule-service-core.ts: Adds createCatchUpQueue to limit startup catch-up concurrency to 2 with 3-second staggering, deferring execution while the screen is locked and re-evaluating on resume/unlock.
  • main/services/browser/service.ts: Skips frame capture when the Picture-in-Picture window is hidden or minimized, and avoids re-rendering when the frame data has not changed.
  • main/services/parakeet.ts: Caches the initial engine readiness check to avoid repeatedly launching the speech utility process on status polls.
  • main/services/portable-config-watch-core.ts & main/index.ts: Throttles window-focus configuration reload triggers to once every 2 seconds with a trailing edge pass.
  • tests/e2e/chat-message-queue.spec.ts: Stabilizes the queued steer test by waiting for the message list count and button enablement before sending subsequent inputs.

Findings

No findings.

📊 Sequence Diagram
sequenceDiagram
    participant Agent as Agent / LLM
    participant Manager as McpManager
    participant Cache as McpToolListCache
    participant Client as MCP Client
    participant Server as MCP Server

    Agent->>Manager: collectMcpAgentTools(servers)
    par For each enabled server (bounded by discovery budget)
        Manager->>Client: connect(deadline 10s)
        Manager->>Cache: list(client, deadline 5s)
        opt If tool list not cached
            Cache->>Server: tools/list
            Server-->>Cache: tool descriptors
        end
        Cache-->>Manager: cached tools
    end
    Manager-->>Agent: merged AgentTool[]

    Note over Agent,Server: Later, during tool execution
    Agent->>Manager: execute(tool, args)
    Manager->>Client: withLiveClient (transparent reconnect if idle)
    Client->>Server: callTool(args, deadline 60s)
    Server-->>Agent: tool result
Loading

Machine-Readable Findings

[]

Last reviewed commit: 47a84fc654ff
Reviews (1) · Comment /hermes review to trigger a new review · /hermes review full for full re-review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sambitcreate and others added 2 commits October 4, 2026 09:11
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The spec pressed Enter twice right after filling, without the Queue-enabled
check every other queue spec uses, so an Enter could land before the composer
accepted queueing and the queue showed one item instead of two. It failed
this way on #327 and #328.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 57b4896)
sambitcreate added a commit that referenced this pull request Oct 4, 2026
The spec pressed Enter twice right after filling, without the Queue-enabled
check every other queue spec uses, so an Enter could land before the composer
accepted queueing and the queue showed one item instead of two. It failed
this way on #327 and #328.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 57b4896)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues found in this delta. The earlier MCP reconnect and scheduler catch-up findings remain unresolved, so this is not an approval.

Reviewed changes: Reviewed the queue-Steer E2E synchronization added since the previous review, with the current full PR diff and main merges as context.

  • Added Submission-readiness waits: Waited for Queue message to become enabled before each queued Enter, matching the composer's existing pending-submission guard.
  • Added Sequential queue confirmation: Asserted exactly one queued row before submitting the second message, while retaining the queue-content, keyboard Steer, once-only transcript, and model-request assertions.
  • Preserved Test registration: Confirmed the merged npm script and CI registry still include the MCP discovery suite.

Validation passed: npm run type-check:e2e, targeted Playwright collection, npm run test:ci-policy (55 tests), and the queue behavioral suite (25 tests). The Electron test was not executed locally; exact-head Linux checks were still in progress when inspected.

Pullfrog  | Fix it ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

@sambitcreate
sambitcreate merged commit c632529 into main Oct 4, 2026
25 checks passed
@sambitcreate
sambitcreate deleted the perf/mcp-network-background branch October 4, 2026 15:05
sambitcreate added a commit that referenced this pull request Oct 4, 2026
…#327)

* perf(main): create the main window during startup reconciliation (MAIN-1)

The main window used to be created only after ~20 sequential reconcile
awaits. Create it as soon as the theme is known so the renderer bundle loads
in parallel, and hold every renderer invoke behind a startup admission gate
(installed before any ipcMain.handle registration) until reconciliation
finishes, preserving the "no renderer reads before reconcile" invariant.
Tool-output pruning no longer blocks startup. Adds a startup-reconciled
diagnostic milestone.

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

* perf(main): load electron-updater on first update use (MAIN-2)

electron-updater (~37 ms of module evaluation) was imported eagerly on the
startup path, though it is only reachable from start() after the main
window or a user update action. Load it through createRequire on first use
so the protected install handoff stays synchronous.

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

* perf(main): load the read-aloud Markdown parser on first use (MAIN-2)

The unified/remark stack (~44 ms) was evaluated at startup only to back
read-aloud. Load it on the first read-aloud request, before the
reservation check so the synchronous preparation section is unchanged.

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

* perf(main): load bonjour-service only when Linux Remote publishes (MAIN-2)

bonjour-service (~20 ms) was evaluated at every startup although only the
Linux local-discovery publisher uses it (macOS uses dns-sd). Import it when
that publisher starts, keeping the existing stopped-before-ready contract.

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

* perf(main): load the peer OpenAPI contract on first peer response (MAIN-3)

The 289 KB Aiden Remote OpenAPI document and the Ajv 2020 validator were
imported at startup only to validate peer-host responses. Load both on the
first validation; peer response validation becomes async and the handler
awaits it, with identical accept/reject behavior.

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

* perf(main): load preview asset parsers on first discovery (MAIN-2)

parse5, acorn, postcss and postcss-value-parser (~16 ms) were evaluated
at startup only for browser-preview asset discovery. Load them on the
first discovery; reference extraction becomes async with unchanged output.

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

* docs(memory): record startup-path optimizations (MAIN-1, MAIN-2, MAIN-3)

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

* fix(test): anchor startup ordering on renderer admission, not window creation

The startup window is now created while reconciliation runs, and the
startup IPC admission holds every renderer invoke until reconciliation
finishes. The ordering contract still requires private-run and worktree
deletion reconciliation to finish before the renderer is admitted and
before schedules start, so anchor it on openProcessStartupIpcAdmission().

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

* test(e2e): wait for Queue before each queued Enter in the Steer spec

The spec pressed Enter twice right after filling, without the Queue-enabled
check every other queue spec uses, so an Enter could land before the composer
accepted queueing and the queue showed one item instead of two. It failed
this way on #327 and #328.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 57b4896)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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