Repository navigation
perf(main): MCP deadlines and caching, bounded background work - #328
Conversation
…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>
There was a problem hiding this comment.
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.
gpt-6.1-sol | 𝕏
| 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 }); |
There was a problem hiding this comment.
[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.| const live = this.clients.isConnected(server.id, client) | ||
| ? client | ||
| : await this.ensureConnected(server, generation); | ||
| return await request(live); |
There was a problem hiding this comment.
[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>
Hermes Review BotConfidence: 5 Engine: SummaryThis 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/5Every 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
FindingsNo findings. 📊 Sequence DiagramsequenceDiagram
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
Machine-Readable Findings[]
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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)
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)
There was a problem hiding this comment.
ℹ️ 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 messageto 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.
gpt-6.1-sol | 𝕏
…#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>

Summary
Test plan
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-testsreports 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/111412327316Part 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