@mrciphersmith/roomyx 0.5.0 → 0.6.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.
@@ -54,7 +54,20 @@ export async function serveMcpOverHttp(
54
54
  );
55
55
  }
56
56
 
57
- const sessions = new Map<string, StreamableHTTPServerTransport>();
57
+ /**
58
+ * Live sessions, with the time each was last used.
59
+ *
60
+ * A session used to leave this map only via `onsessionclosed`, which the SDK
61
+ * fires on an HTTP DELETE — and nothing in roomyx sends one. `Client.close()`
62
+ * aborts the local controller; `terminateSession()` is the method that sends
63
+ * the DELETE, and it had no callers. So every session the process ever
64
+ * accepted was retained for the life of the process, at roughly 70-78 KB
65
+ * each, fed by ordinary use: one per `rooms list`, one per `room append`, one
66
+ * per client start, one per reconnect. Each abandoned id also stayed a fully
67
+ * routable handle to the room — three clients closed, then a raw POST
68
+ * replaying their recorded ids still returned a full `tools/list`.
69
+ */
70
+ const sessions = new Map<string, { transport: StreamableHTTPServerTransport; lastSeenMs: number }>();
58
71
 
59
72
  // Filled in after listen(). Sessions are only ever created while handling a
60
73
  // request, so by the time createSession runs this is the real bound port —
@@ -86,23 +99,60 @@ export async function serveMcpOverHttp(
86
99
  allowedHosts: [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`],
87
100
  allowedOrigins: [`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`],
88
101
  onsessioninitialized: (sessionId) => {
89
- sessions.set(sessionId, transport);
102
+ sessions.set(sessionId, { transport, lastSeenMs: Date.now() });
90
103
  },
91
104
  onsessionclosed: (sessionId) => {
92
105
  sessions.delete(sessionId);
93
106
  },
94
107
  });
108
+ // The DELETE is one way a session can end; the transport closing for any
109
+ // other reason is another, and only the first was being listened for.
110
+ transport.onclose = () => {
111
+ const id = transport.sessionId;
112
+ if (id !== undefined) sessions.delete(id);
113
+ };
95
114
  const mcpServer = options.createMcpServer();
96
115
  await mcpServer.connect(transport);
97
116
  return transport;
98
117
  }
99
118
 
119
+ /**
120
+ * Closes sessions nothing has touched for a while.
121
+ *
122
+ * A well-behaved client polls every second or three, so a minute of silence
123
+ * means it is gone — and the ones that are gone are precisely the ones that
124
+ * never sent the DELETE that would have said so. `unref()` so an idle sweeper
125
+ * cannot be the reason a process stays alive.
126
+ */
127
+ const IDLE_SESSION_MS = 60_000;
128
+ const sweeper = setInterval(() => {
129
+ const cutoff = Date.now() - IDLE_SESSION_MS;
130
+ for (const [id, entry] of sessions) {
131
+ if (entry.lastSeenMs < cutoff) {
132
+ sessions.delete(id);
133
+ void entry.transport.close().catch(() => undefined);
134
+ }
135
+ }
136
+ }, IDLE_SESSION_MS / 2);
137
+ sweeper.unref();
138
+
100
139
  const httpServer = createHttpServer((req, res) => {
101
140
  const sessionIdHeader = req.headers["mcp-session-id"];
102
141
  const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
103
142
  const existing = sessionId ? sessions.get(sessionId) : undefined;
143
+ if (existing) existing.lastSeenMs = Date.now();
144
+
145
+ // A request naming a session that does not exist is answered, not granted a
146
+ // new one. Minting a transport for an unknown id created one that never
147
+ // entered `sessions`, so it could not be closed even by `closeSessions` on
148
+ // shutdown — a leak reachable by anyone sending a random header.
149
+ if (sessionId !== undefined && existing === undefined) {
150
+ res.writeHead(404, { "content-type": "application/json" });
151
+ res.end(JSON.stringify({ error: `Unknown session ${sessionId}` }));
152
+ return;
153
+ }
104
154
 
105
- const transportPromise = existing ? Promise.resolve(existing) : createSession();
155
+ const transportPromise = existing ? Promise.resolve(existing.transport) : createSession();
106
156
  transportPromise
107
157
  .then((transport) => transport.handleRequest(req, res))
108
158
  .catch((error) => {
@@ -120,6 +170,7 @@ export async function serveMcpOverHttp(
120
170
  httpServer.listen(port, host, () => resolve());
121
171
  });
122
172
  } catch (error) {
173
+ clearInterval(sweeper);
123
174
  await closeSessions(sessions);
124
175
  throw error;
125
176
  }
@@ -131,19 +182,36 @@ export async function serveMcpOverHttp(
131
182
  return {
132
183
  url: `http://${host}:${actualPort}/mcp`,
133
184
  port: actualPort,
134
- close: () =>
135
- new Promise<void>((resolve, reject) => {
136
- httpServer.close(async (error) => {
137
- // The management server used to skip this, so its sessions outlived
138
- // the process that owned them. One implementation, one behaviour.
139
- await closeSessions(sessions);
185
+ close: async () => {
186
+ // Order matters and it used to be inverted. `httpServer.close()`'s
187
+ // callback fires only once every connection has ended, and the code that
188
+ // ends them — `closeSessions` — was *inside* that callback. An MCP client
189
+ // holds a keep-alive socket, so with anyone attached the callback never
190
+ // fired: `roomyx serve` did not exit on SIGTERM at all, the port stayed
191
+ // bound, and the only way out was SIGKILL. Measured with a control: with
192
+ // a client attached, still running after 12s; with none, clean.
193
+ //
194
+ // The management server used to skip closing sessions entirely, so its
195
+ // sessions outlived the process. One implementation, one behaviour.
196
+ clearInterval(sweeper);
197
+ await closeSessions(sessions);
198
+
199
+ await new Promise<void>((resolve, reject) => {
200
+ httpServer.close((error) => {
140
201
  if (error) reject(error);
141
202
  else resolve();
142
203
  });
143
- }),
204
+ // A client that ignores the stream ending must not be able to pin the
205
+ // process open. Closing sessions first is the polite half; this is the
206
+ // half that means shutdown is bounded whatever the client does.
207
+ httpServer.closeAllConnections();
208
+ });
209
+ },
144
210
  };
145
211
  }
146
212
 
147
- function closeSessions(sessions: Map<string, StreamableHTTPServerTransport>): Promise<unknown[]> {
148
- return Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
213
+ function closeSessions(
214
+ sessions: Map<string, { transport: StreamableHTTPServerTransport; lastSeenMs: number }>,
215
+ ): Promise<unknown[]> {
216
+ return Promise.all([...sessions.values()].map((entry) => entry.transport.close().catch(() => undefined)));
149
217
  }
@@ -1,59 +0,0 @@
1
- import { BoxRenderable, ScrollBoxRenderable, TextRenderable } from "@opentui/core";
2
- import type { RenderContext } from "@opentui/core";
3
- import { createMessageRow } from "../components/message-row";
4
- import type { AgentDetail } from "../../log/types";
5
-
6
- /**
7
- * Modal overlay for one participant's own messages (R4 / AC2 — shows only
8
- * that participant's data, not the full transcript). Drawn over the chat
9
- * view, not a screen replacement, matching the pattern observed in keryx's
10
- * own mcp-inspector.ts (background stays visible, modal on top).
11
- */
12
- export class AgentModal {
13
- readonly node: BoxRenderable;
14
- private readonly title: TextRenderable;
15
- private readonly scroll: ScrollBoxRenderable;
16
- private readonly ctx: RenderContext;
17
-
18
- constructor(ctx: RenderContext, options: { width: number; height: number }) {
19
- this.ctx = ctx;
20
- this.node = new BoxRenderable(ctx, {
21
- width: options.width,
22
- height: options.height,
23
- flexDirection: "column",
24
- border: true,
25
- visible: false,
26
- position: "absolute",
27
- top: 2,
28
- left: 2,
29
- zIndex: 10,
30
- backgroundColor: "#000000",
31
- });
32
- this.title = new TextRenderable(ctx, { content: "", height: 1 });
33
- this.node.add(this.title);
34
- this.scroll = new ScrollBoxRenderable(ctx, { flexGrow: 1 });
35
- this.node.add(this.scroll);
36
- }
37
-
38
- show(detail: AgentDetail): void {
39
- for (const child of this.scroll.getChildren()) this.scroll.remove(child);
40
- if (!detail.found) {
41
- this.title.content = "Agent not found";
42
- this.node.visible = true;
43
- return;
44
- }
45
- this.title.content = `${detail.agent.name} — last seen at seq ${detail.lastSeenSeq}`;
46
- for (const message of detail.messages) {
47
- this.scroll.add(createMessageRow(this.ctx, message, detail.agent.name));
48
- }
49
- this.node.visible = true;
50
- }
51
-
52
- hide(): void {
53
- this.node.visible = false;
54
- }
55
-
56
- isVisible(): boolean {
57
- return this.node.visible;
58
- }
59
- }