@agent-deck/backend 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AgentDeckMCPServer = exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = exports.MCP_INITIALIZE_RATE_WINDOW_MS = exports.MCP_INITIALIZE_RATE_LIMIT = exports.MCP_REQUIRE_BEARER_ENV_VAR = void 0;
6
+ exports.AgentDeckMCPServer = exports.DEFAULT_UNREGISTER_CONCURRENCY = exports.DEFAULT_TRANSPORT_SWEEP_INTERVAL_MS = exports.DEFAULT_TRANSPORT_IDLE_TTL_MS = exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = exports.MCP_INITIALIZE_RATE_WINDOW_MS = exports.MCP_INITIALIZE_RATE_LIMIT = exports.MCP_REQUIRE_BEARER_ENV_VAR = void 0;
7
7
  exports.isBearerGrantRequired = isBearerGrantRequired;
8
8
  exports.resolveLiveTouchKeepAliveMs = resolveLiveTouchKeepAliveMs;
9
9
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
@@ -48,6 +48,16 @@ function readCorrelationIdHeader(req) {
48
48
  const value = typeof raw === 'string' ? raw.trim() : '';
49
49
  return value || undefined;
50
50
  }
51
+ /**
52
+ * NOT-191: whether the request comes from a heartbeat-capable bridge. The
53
+ * marker rides every request the new bridge sends (handshake, tool calls,
54
+ * pulses, stream, close); legacy clients never send it, so absence means
55
+ * "unknown/legacy" and keeps the server-owned keep-alive touch.
56
+ */
57
+ function hasBridgeLivenessHeader(req) {
58
+ const raw = req.headers[shared_1.AGENT_DECK_BRIDGE_LIVENESS_HEADER];
59
+ return typeof raw === 'string' && raw.trim() === shared_1.AGENT_DECK_BRIDGE_LIVENESS_V1;
60
+ }
51
61
  /**
52
62
  * NOT-318: hosted-mode flag. When `AGENT_DECK_MCP_REQUIRE_BEARER=1`, every
53
63
  * `/mcp` request requires a valid per-agent grant secret, regardless of
@@ -90,6 +100,24 @@ function readBearerToken(req) {
90
100
  */
91
101
  exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = 5 * 60_000;
92
102
  exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = 'AGENT_DECK_MCP_LIVE_TOUCH_KEEPALIVE_MS';
103
+ /**
104
+ * NOT-191: idle retention for MCP transport sessions. A session with no
105
+ * client traffic — no tool calls, no heartbeat pulse — is closed and fully
106
+ * cleaned once it has been idle this long. Twenty-four hours keeps a laptop
107
+ * asleep overnight recoverable (the bridge re-initializes on wake) while
108
+ * still reclaiming transports abandoned by crashed hosts. Kept separate
109
+ * from the 30-minute live-display lease on purpose: the display is what the
110
+ * status line reads, the transport is just retained state.
111
+ */
112
+ exports.DEFAULT_TRANSPORT_IDLE_TTL_MS = 24 * 60 * 60_000;
113
+ /** Cadence of the idle-transport sweep. */
114
+ exports.DEFAULT_TRANSPORT_SWEEP_INTERVAL_MS = 60_000;
115
+ /**
116
+ * NOT-191: bound on concurrent live-display unregisters, shared by the idle
117
+ * sweep and server shutdown so a mass expiry cannot fan out into hundreds of
118
+ * simultaneous backend calls.
119
+ */
120
+ exports.DEFAULT_UNREGISTER_CONCURRENCY = 8;
93
121
  function resolveLiveTouchKeepAliveMs(raw, staleMs) {
94
122
  const fallback = staleMs > 0
95
123
  ? Math.max(1, Math.min(exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS, Math.floor(staleMs / 3)))
@@ -122,8 +150,51 @@ class AgentDeckMCPServer {
122
150
  lastTouchAtMs = new Map();
123
151
  /** NOT-309: keep-alive timer proving idle-but-connected sessions still live. */
124
152
  liveTouchKeepAliveTimer = null;
125
- /** In-flight live-display unregisters so `stop()` can drain them before closing. */
126
- unregisterTasks = new Map();
153
+ /**
154
+ * NOT-191: session cleanups in flight, keyed by MCP session id. Doubles as
155
+ * the re-entrancy guard — `transport.onclose` and the sweep/stop paths all
156
+ * funnel through `startCleanupSession`, and a second call for the same id
157
+ * joins the first instead of unregistering twice. Resolves to whether the
158
+ * live-display unregister succeeded (for aggregate batch summaries).
159
+ */
160
+ cleanupTasks = new Map();
161
+ /** NOT-191: clock for activity/TTL bookkeeping (tests inject a fake clock). */
162
+ nowFn;
163
+ /** NOT-191: idle bound for transport retention (24h default; `0` disables). */
164
+ transportIdleTtlMs;
165
+ /** NOT-191: cadence of the idle-transport sweep (`0` disables the timer). */
166
+ transportSweepIntervalMs;
167
+ /** NOT-191: bound on concurrent live-display unregisters (sweep + shutdown). */
168
+ unregisterConcurrency;
169
+ /** NOT-191: bound on one live-display unregister (option or env override). */
170
+ unregisterTimeoutMsValue;
171
+ /** NOT-191: keep-alive override (tests); otherwise the env resolution wins. */
172
+ liveTouchKeepAliveMsOverride;
173
+ /**
174
+ * NOT-191: last real client traffic per session — tool calls, handshakes,
175
+ * stream connects, heartbeat pulses. Server-generated keep-alive touches
176
+ * never write here, so they cannot extend transport retention.
177
+ */
178
+ lastClientActivityAtMs = new Map();
179
+ /** NOT-191: sessions whose bridge owns the heartbeat (no server touch needed). */
180
+ heartbeatCapableSessions = new Set();
181
+ /** NOT-191: POST requests currently inside `transport.handleRequest` per session. */
182
+ inFlightRequests = new Map();
183
+ /**
184
+ * NOT-191: sessions whose `DELETE` arrived while a host request was in
185
+ * flight. The close is deferred — never executed under running work — and
186
+ * runs when the last in-flight request lands or the next sweep finds the
187
+ * session idle.
188
+ */
189
+ pendingSessionClose = new Set();
190
+ /** NOT-191: idle-transport sweep timer. */
191
+ transportSweepTimer = null;
192
+ /** NOT-191: re-entrancy guard so a slow sweep never overlaps the next tick. */
193
+ transportSweepRunning = false;
194
+ /** NOT-191: unregister semaphore state; `unregisterPeak` is read by tests. */
195
+ unregisterActive = 0;
196
+ unregisterPeak = 0;
197
+ unregisterWaiters = [];
127
198
  /** Changes on every process start — how a client detects it outlived the server. */
128
199
  instanceId = (0, node_crypto_1.randomUUID)();
129
200
  startedAt = new Date().toISOString();
@@ -162,6 +233,14 @@ class AgentDeckMCPServer {
162
233
  this.grantStoreOverride = options?.grantStore;
163
234
  this.auditStoreOverride = options?.auditStore;
164
235
  this.initializeLimiter = new request_limiter_1.RequestLimiter(exports.MCP_INITIALIZE_RATE_WINDOW_MS, options?.now);
236
+ this.nowFn = options?.now ?? Date.now;
237
+ this.transportIdleTtlMs = options?.transportIdleTtlMs ?? exports.DEFAULT_TRANSPORT_IDLE_TTL_MS;
238
+ this.transportSweepIntervalMs =
239
+ options?.transportSweepIntervalMs ?? exports.DEFAULT_TRANSPORT_SWEEP_INTERVAL_MS;
240
+ this.unregisterConcurrency = options?.unregisterConcurrency ?? exports.DEFAULT_UNREGISTER_CONCURRENCY;
241
+ this.unregisterTimeoutMsValue =
242
+ options?.unregisterTimeoutMs ?? AgentDeckMCPServer.unregisterTimeoutMs();
243
+ this.liveTouchKeepAliveMsOverride = options?.liveTouchKeepAliveMs;
165
244
  this.app = (0, express_1.default)();
166
245
  this.app.use(process.env.AGENT_DECK_HOSTED_MODE === '1'
167
246
  ? express_1.default.json({ limit: 1024 * 1024 })
@@ -336,6 +415,25 @@ class AgentDeckMCPServer {
336
415
  }
337
416
  }
338
417
  static TOUCH_DEBOUNCE_MS = 5_000;
418
+ /** NOT-191: injected clock for activity/TTL bookkeeping. */
419
+ nowMs() {
420
+ return this.nowFn();
421
+ }
422
+ /**
423
+ * NOT-191: record real client traffic — a tool call, handshake, stream
424
+ * connect, or heartbeat pulse — as transport activity, and adopt the
425
+ * bridge-liveness capability whenever the marker is present. Called only
426
+ * for authenticated requests on a live session; server-generated
427
+ * keep-alive touches never come through here, so they cannot extend the
428
+ * transport idle TTL. A client pulse also refreshes the display lease via
429
+ * the per-request `touchLiveDisplay` at the same call sites.
430
+ */
431
+ noteClientActivity(sessionId, req) {
432
+ this.lastClientActivityAtMs.set(sessionId, this.nowMs());
433
+ if (hasBridgeLivenessHeader(req)) {
434
+ this.heartbeatCapableSessions.add(sessionId);
435
+ }
436
+ }
339
437
  /**
340
438
  * Fire-and-forget lastActivityAt bump; only for sessions this process
341
439
  * registered (badge-holding). `force` bypasses the per-request debounce —
@@ -353,7 +451,7 @@ class AgentDeckMCPServer {
353
451
  if (!this.badgeBySession.has(sessionId)) {
354
452
  return;
355
453
  }
356
- const now = Date.now();
454
+ const now = this.nowMs();
357
455
  if (!force &&
358
456
  now - (this.lastTouchAtMs.get(sessionId) ?? 0) < AgentDeckMCPServer.TOUCH_DEBOUNCE_MS) {
359
457
  return;
@@ -362,7 +460,7 @@ class AgentDeckMCPServer {
362
460
  void this.callBackendAPI(`/api/scope/live-display/${encodeURIComponent(sessionId)}/touch`, {
363
461
  method: 'POST',
364
462
  headers: { 'Content-Type': 'application/json' },
365
- body: JSON.stringify({ at: new Date().toISOString() }),
463
+ body: JSON.stringify({ at: new Date(now).toISOString() }),
366
464
  }, sessionId)
367
465
  .then((result) => {
368
466
  // Guard against the close race: a keep-alive touch in flight when
@@ -392,16 +490,25 @@ class AgentDeckMCPServer {
392
490
  * no tool calls. Only badge-holding (registered) sessions are touched; the
393
491
  * backend ignores touches for sessions it never saw, so unassigned or
394
492
  * half-initialized sessions are harmless no-ops by construction.
493
+ *
494
+ * NOT-191: heartbeat-capable sessions are skipped — their bridge owns the
495
+ * pulse now, and a server-generated touch here is what used to defeat the
496
+ * stale sweep for abandoned bridges. Legacy/unknown sessions keep the
497
+ * compatibility touch, but it never counts as transport activity.
395
498
  */
396
499
  touchAllLiveDisplays() {
397
500
  for (const sessionId of this.sessions.keys()) {
501
+ if (this.heartbeatCapableSessions.has(sessionId)) {
502
+ continue;
503
+ }
398
504
  this.touchLiveDisplay(sessionId, true);
399
505
  }
400
506
  }
401
507
  startLiveDisplayKeepAlive() {
402
508
  this.stopLiveDisplayKeepAlive();
403
509
  const staleMs = (0, live_display_registry_1.resolveLiveDisplayStaleMs)(process.env.LIVE_DISPLAY_STALE_MS);
404
- const intervalMs = resolveLiveTouchKeepAliveMs(process.env[exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR], staleMs);
510
+ const intervalMs = this.liveTouchKeepAliveMsOverride ??
511
+ resolveLiveTouchKeepAliveMs(process.env[exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR], staleMs);
405
512
  if (intervalMs <= 0) {
406
513
  return;
407
514
  }
@@ -417,20 +524,234 @@ class AgentDeckMCPServer {
417
524
  this.liveTouchKeepAliveTimer = null;
418
525
  }
419
526
  }
420
- async unregisterLiveDisplay(sessionId) {
527
+ /**
528
+ * NOT-191: one live-display unregister, bounded and silent. Returns whether
529
+ * it succeeded; failures aggregate into a single batch summary at the sweep
530
+ * and shutdown call sites instead of one stack trace per session. Runs
531
+ * while the session binding still resolves — `runCleanupSession` clears it
532
+ * only after this returns.
533
+ */
534
+ async unregisterLiveDisplayQuiet(sessionId) {
421
535
  const controller = new AbortController();
422
- const timer = setTimeout(() => controller.abort(), AgentDeckMCPServer.unregisterTimeoutMs());
536
+ const timer = setTimeout(() => controller.abort(), this.unregisterTimeoutMsValue);
537
+ timer.unref?.();
423
538
  try {
424
- await this.callBackendAPI(`/api/scope/live-display/${encodeURIComponent(sessionId)}`, { method: 'DELETE', signal: controller.signal }, sessionId);
539
+ await this.callBackendAPI(`/api/scope/live-display/${encodeURIComponent(sessionId)}`, { method: 'DELETE', signal: controller.signal }, sessionId, { quiet: true });
540
+ return true;
425
541
  }
426
542
  catch {
427
- // Best effort when MCP session closes (includes abort on hung backend).
543
+ // Best effort when an MCP session closes (includes abort on hung backend).
544
+ return false;
428
545
  }
429
546
  finally {
430
547
  clearTimeout(timer);
431
548
  }
432
549
  }
433
- async callBackendAPI(endpoint, init = {}, sessionId) {
550
+ /**
551
+ * NOT-191: run `fn` under the shared unregister semaphore so the idle
552
+ * sweep and server shutdown together never exceed the bound, however many
553
+ * sessions expire at once.
554
+ */
555
+ async withUnregisterSlot(fn) {
556
+ const limit = Math.max(1, this.unregisterConcurrency);
557
+ while (this.unregisterActive >= limit) {
558
+ await new Promise((resolve) => {
559
+ this.unregisterWaiters.push(resolve);
560
+ });
561
+ }
562
+ this.unregisterActive += 1;
563
+ this.unregisterPeak = Math.max(this.unregisterPeak, this.unregisterActive);
564
+ try {
565
+ return await fn();
566
+ }
567
+ finally {
568
+ this.unregisterActive -= 1;
569
+ const next = this.unregisterWaiters.shift();
570
+ next?.();
571
+ }
572
+ }
573
+ /**
574
+ * NOT-191: one aggregate line for a batch of unregisters — attempted,
575
+ * succeeded, failed — logged only when something failed. A clean batch
576
+ * stays silent; a failing one never logs per-session stacks.
577
+ */
578
+ logUnregisterSummary(reason, results) {
579
+ const failed = results.filter((ok) => !ok).length;
580
+ if (failed === 0) {
581
+ return;
582
+ }
583
+ console.warn(`[agent-deck] live-display unregister (${reason}): ` +
584
+ `attempted=${results.length} succeeded=${results.length - failed} failed=${failed}`);
585
+ }
586
+ /**
587
+ * NOT-191 session cleanup. Every transport/session end funnels through
588
+ * here — `transport.onclose` (clean `DELETE`), the idle sweep, deferred
589
+ * closes, and server shutdown — so no path can strand part of a session's
590
+ * state. Removes the transport/server entry, unregisters the live display
591
+ * under the shared concurrency bound, then disconnects the trusted
592
+ * runtime session (revoking nothing reusable — the grant row stays valid
593
+ * for the next handshake), and finally clears the binding, badge, touch,
594
+ * activity, capability, and in-flight bookkeeping. The unregister runs
595
+ * before the disconnect because it authenticates with the runtime session
596
+ * the disconnect revokes. Idempotent per session id: a second call joins
597
+ * the first.
598
+ */
599
+ startCleanupSession(sessionId, opts) {
600
+ const existing = this.cleanupTasks.get(sessionId);
601
+ if (existing) {
602
+ return existing;
603
+ }
604
+ if (this.closedSessionIds.has(sessionId)) {
605
+ return Promise.resolve(true);
606
+ }
607
+ const task = this.runCleanupSession(sessionId, opts);
608
+ this.cleanupTasks.set(sessionId, task);
609
+ const release = () => {
610
+ if (this.cleanupTasks.get(sessionId) === task) {
611
+ this.cleanupTasks.delete(sessionId);
612
+ }
613
+ };
614
+ void task.then(release, release);
615
+ return task;
616
+ }
617
+ async runCleanupSession(sessionId, opts) {
618
+ // Synchronous prefix — no awaits before the maps below are updated, so a
619
+ // request interleaving at any later await already sees the session gone.
620
+ const session = this.sessions.get(sessionId);
621
+ this.sessions.delete(sessionId);
622
+ this.rememberClosedSession(sessionId);
623
+ this.pendingSessionClose.delete(sessionId);
624
+ this.lastClientActivityAtMs.delete(sessionId);
625
+ this.heartbeatCapableSessions.delete(sessionId);
626
+ this.inFlightRequests.delete(sessionId);
627
+ if (opts.closeTransport && session) {
628
+ try {
629
+ // The transport's `onclose` re-enters `startCleanupSession`, which
630
+ // joins this run via `cleanupTasks` instead of cleaning twice.
631
+ await session.transport.close();
632
+ }
633
+ catch {
634
+ // Best effort — the maps above are already consistent.
635
+ }
636
+ }
637
+ // Best effort, before the binding is cleared: the live-display DELETE
638
+ // authenticates through the runtime session header, and the disconnect
639
+ // below revokes that session — so the unregister must run first, while
640
+ // the session is still valid. (Disconnect is a public endpoint keyed by
641
+ // mcpSessionId, so it needs no valid session of its own.)
642
+ let unregistered;
643
+ try {
644
+ unregistered = await this.withUnregisterSlot(() => this.unregisterLiveDisplayQuiet(sessionId));
645
+ }
646
+ catch {
647
+ unregistered = false;
648
+ }
649
+ try {
650
+ await this.disconnectTrustedSession(sessionId);
651
+ }
652
+ catch {
653
+ // Best-effort cleanup.
654
+ }
655
+ this.sessionBinding.clearSession(sessionId);
656
+ this.badgeBySession.delete(sessionId);
657
+ this.lastTouchAtMs.delete(sessionId);
658
+ return unregistered;
659
+ }
660
+ /**
661
+ * NOT-191: close every session that is idle past the transport TTL or has
662
+ * a deferred close pending — unless a host request is in flight, in which
663
+ * case it waits for the next sweep. Unregisters run concurrently under the
664
+ * shared bound and their failures collapse into one summary line.
665
+ */
666
+ async sweepIdleTransports() {
667
+ if (this.transportSweepRunning) {
668
+ return;
669
+ }
670
+ this.transportSweepRunning = true;
671
+ try {
672
+ const now = this.nowMs();
673
+ const candidates = [];
674
+ for (const sessionId of this.sessions.keys()) {
675
+ if (this.cleanupTasks.has(sessionId) || this.closedSessionIds.has(sessionId)) {
676
+ continue;
677
+ }
678
+ if ((this.inFlightRequests.get(sessionId) ?? 0) > 0) {
679
+ continue;
680
+ }
681
+ if (this.pendingSessionClose.has(sessionId)) {
682
+ candidates.push(sessionId);
683
+ continue;
684
+ }
685
+ if (this.transportIdleTtlMs <= 0) {
686
+ continue;
687
+ }
688
+ const lastActivity = this.lastClientActivityAtMs.get(sessionId);
689
+ if (lastActivity === undefined) {
690
+ continue;
691
+ }
692
+ // `>=`: a session idle for exactly the TTL is already past retention.
693
+ if (now - lastActivity >= this.transportIdleTtlMs) {
694
+ candidates.push(sessionId);
695
+ }
696
+ }
697
+ if (candidates.length === 0) {
698
+ return;
699
+ }
700
+ const results = await Promise.all(candidates.map((sessionId) => this.startCleanupSession(sessionId, { closeTransport: true })));
701
+ this.logUnregisterSummary('transport-sweep', results);
702
+ }
703
+ finally {
704
+ this.transportSweepRunning = false;
705
+ }
706
+ }
707
+ startTransportSweep() {
708
+ this.stopTransportSweep();
709
+ if (this.transportSweepIntervalMs <= 0) {
710
+ return;
711
+ }
712
+ const timer = setInterval(() => {
713
+ void this.sweepIdleTransports().catch(() => { });
714
+ }, this.transportSweepIntervalMs);
715
+ timer.unref?.();
716
+ this.transportSweepTimer = timer;
717
+ }
718
+ stopTransportSweep() {
719
+ if (this.transportSweepTimer) {
720
+ clearInterval(this.transportSweepTimer);
721
+ this.transportSweepTimer = null;
722
+ }
723
+ }
724
+ /**
725
+ * NOT-191: run one POST inside the per-session in-flight guard. A session
726
+ * with work in flight is never expired or deleted; when the last request
727
+ * lands, a deferred close runs immediately instead of waiting for the
728
+ * sweep. (The long-lived GET stream is deliberately not counted — it stays
729
+ * open for the session's whole life, so counting it would pin every
730
+ * session against the TTL forever.)
731
+ */
732
+ async handleTransportPost(sessionId, req, res) {
733
+ this.inFlightRequests.set(sessionId, (this.inFlightRequests.get(sessionId) ?? 0) + 1);
734
+ try {
735
+ const session = this.sessions.get(sessionId);
736
+ if (session) {
737
+ await session.transport.handleRequest(req, res, req.body);
738
+ }
739
+ }
740
+ finally {
741
+ const remaining = (this.inFlightRequests.get(sessionId) ?? 1) - 1;
742
+ if (remaining <= 0) {
743
+ this.inFlightRequests.delete(sessionId);
744
+ if (this.pendingSessionClose.has(sessionId)) {
745
+ this.pendingSessionClose.delete(sessionId);
746
+ void this.startCleanupSession(sessionId, { closeTransport: true });
747
+ }
748
+ }
749
+ else {
750
+ this.inFlightRequests.set(sessionId, remaining);
751
+ }
752
+ }
753
+ }
754
+ async callBackendAPI(endpoint, init = {}, sessionId, opts) {
434
755
  try {
435
756
  const headers = this.sessionBinding.getAgentHeaders(sessionId);
436
757
  const response = await fetch(`${this.backendUrl}${endpoint}`, {
@@ -459,7 +780,11 @@ class AgentDeckMCPServer {
459
780
  return body;
460
781
  }
461
782
  catch (error) {
462
- console.error(`Failed to call backend API ${endpoint}:`, error);
783
+ // NOT-191: quiet mode keeps best-effort teardown (unregister) from
784
+ // logging one stack trace per session; batch callers log one summary.
785
+ if (!opts?.quiet) {
786
+ console.error(`Failed to call backend API ${endpoint}:`, error);
787
+ }
463
788
  throw error;
464
789
  }
465
790
  }
@@ -1232,8 +1557,16 @@ class AgentDeckMCPServer {
1232
1557
  return;
1233
1558
  }
1234
1559
  }
1560
+ // The auth above awaits, so re-check: a sweep may have expired the
1561
+ // session while it ran, and answering on a dead transport would hang.
1562
+ const live = this.sessions.get(sessionIdHeader);
1563
+ if (!live) {
1564
+ this.sendSessionNotFound(sessionIdHeader, res);
1565
+ return;
1566
+ }
1567
+ this.noteClientActivity(sessionIdHeader, req);
1235
1568
  this.touchLiveDisplay(sessionIdHeader);
1236
- await existing.transport.handleRequest(req, res, req.body);
1569
+ await this.handleTransportPost(sessionIdHeader, req, res);
1237
1570
  return;
1238
1571
  }
1239
1572
  const body = req.body;
@@ -1343,17 +1676,11 @@ class AgentDeckMCPServer {
1343
1676
  transport.onclose = () => {
1344
1677
  const closedSessionId = transport.sessionId;
1345
1678
  if (closedSessionId) {
1346
- this.sessions.delete(closedSessionId);
1347
- this.rememberClosedSession(closedSessionId);
1348
- // Unregister while session headers still resolve — clearSession would drop
1349
- // the runtime session id and live-display DELETE would 401.
1350
- const task = this.unregisterLiveDisplay(closedSessionId).finally(() => {
1351
- this.sessionBinding.clearSession(closedSessionId);
1352
- this.badgeBySession.delete(closedSessionId);
1353
- this.lastTouchAtMs.delete(closedSessionId);
1354
- this.unregisterTasks.delete(closedSessionId);
1355
- });
1356
- this.unregisterTasks.set(closedSessionId, task);
1679
+ // NOT-191: every close funnels through the unified cleanup — the
1680
+ // transport/server entry, trusted runtime session, binding, badge,
1681
+ // touch, activity, and live-display row all go together. A sweep or
1682
+ // deferred close already running for this id is joined, not doubled.
1683
+ void this.startCleanupSession(closedSessionId, { closeTransport: false });
1357
1684
  }
1358
1685
  };
1359
1686
  try {
@@ -1381,6 +1708,9 @@ class AgentDeckMCPServer {
1381
1708
  // The replacement session is live, so the session this client lost to the
1382
1709
  // restart is genuinely recovered and no longer a stranded client.
1383
1710
  this.markStaleSessionRecovered(req);
1711
+ // NOT-191: the handshake is the session's first client activity, and it
1712
+ // is also where a heartbeat-capable bridge is first recognized.
1713
+ this.noteClientActivity(transport.sessionId, req);
1384
1714
  if (!this.sessionBinding.isUnassigned(transport.sessionId)) {
1385
1715
  void this.registerLiveDisplay(transport.sessionId).catch(() => { });
1386
1716
  }
@@ -1418,8 +1748,23 @@ class AgentDeckMCPServer {
1418
1748
  return;
1419
1749
  }
1420
1750
  }
1751
+ // The auth above awaits — same re-check as the POST path.
1752
+ const live = this.sessions.get(sessionId);
1753
+ if (!live) {
1754
+ this.sendSessionNotFound(sessionId, res);
1755
+ return;
1756
+ }
1757
+ this.noteClientActivity(sessionId, req);
1758
+ if (req.method === 'DELETE' && (this.inFlightRequests.get(sessionId) ?? 0) > 0) {
1759
+ // NOT-191: never delete a session under running work. The close is
1760
+ // deferred and runs when the last in-flight request lands (or on the
1761
+ // next sweep); the 200 acknowledges the request, not the teardown.
1762
+ this.pendingSessionClose.add(sessionId);
1763
+ res.status(200).end();
1764
+ return;
1765
+ }
1421
1766
  this.touchLiveDisplay(sessionId);
1422
- await session.transport.handleRequest(req, res);
1767
+ await live.transport.handleRequest(req, res);
1423
1768
  }
1424
1769
  async start() {
1425
1770
  if (this.httpServer) {
@@ -1459,6 +1804,7 @@ class AgentDeckMCPServer {
1459
1804
  this.httpServer = httpServer;
1460
1805
  });
1461
1806
  this.startLiveDisplayKeepAlive();
1807
+ this.startTransportSweep();
1462
1808
  return this.app;
1463
1809
  }
1464
1810
  catch (error) {
@@ -1470,18 +1816,19 @@ class AgentDeckMCPServer {
1470
1816
  async stop() {
1471
1817
  try {
1472
1818
  this.stopLiveDisplayKeepAlive();
1473
- for (const [sessionId, session] of this.sessions) {
1474
- try {
1475
- await session.transport.close();
1476
- }
1477
- catch (error) {
1478
- console.error(`Error closing MCP session ${sessionId}:`, error);
1479
- }
1480
- }
1481
- this.sessions.clear();
1482
- // Drain fire-and-forget live-display unregisters before tearing down HTTP —
1483
- // otherwise tests close the stub backend and see ECONNRESET console.error noise.
1484
- await Promise.all([...this.unregisterTasks.values()]);
1819
+ this.stopTransportSweep();
1820
+ // NOT-191: every open session goes through the unified cleanup, so
1821
+ // shutdown removes the same state a clean DELETE would — transport,
1822
+ // trusted runtime session, binding, badge, and live-display row.
1823
+ // Cleanups run concurrently with unregisters under the shared bound,
1824
+ // and their failures collapse into one summary line.
1825
+ const sessionIds = [...this.sessions.keys()];
1826
+ const results = await Promise.all(sessionIds.map((sessionId) => this.startCleanupSession(sessionId, { closeTransport: true })));
1827
+ // Drain cleanups that started outside the snapshot (a close racing
1828
+ // shutdown) before tearing down HTTP — otherwise tests close the stub
1829
+ // backend and see ECONNRESET console.error noise.
1830
+ await Promise.all([...this.cleanupTasks.values()]);
1831
+ this.logUnregisterSummary('server-shutdown', results);
1485
1832
  // Release the port too, otherwise a restart on the same port races the old
1486
1833
  // listener and the "did it come back?" probe can't tell the two apart.
1487
1834
  await this.closeHttpServer();