@cortexkit/opencode-magic-context 0.31.1 → 0.31.3

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.
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Persistent WebSocket to the server plugin's RPC server, replacing the old
3
+ * 500ms HTTP notification poll.
4
+ *
5
+ * Why this exists: the TUI plugin and the server plugin run in separate Bun
6
+ * runners in the same process, so they bridge over a localhost socket. The old
7
+ * bridge polled `pending-notifications` over HTTP every 500ms — and each poll
8
+ * opened a NEW loopback TCP connection (Bun's fetch isn't pooled to our server),
9
+ * which was the entire source of idle TUI CPU (#200). A single long-lived WS
10
+ * carries server→TUI pushes with zero per-event connection cost, and the server
11
+ * pushes notifications the instant they're queued (no polling latency).
12
+ *
13
+ * Session scope: the socket carries the TUI's active session in its `hello` so
14
+ * the server delivers only that session's (plus global) notifications and its
15
+ * `isTuiConnected(session)` routing stays correct. The active session is tracked
16
+ * with a cheap watcher that only reads `api.route.current` (a property access,
17
+ * no IPC) and re-scopes the socket ONLY when the session actually changes — so
18
+ * unlike the old poll it does no network work at idle.
19
+ */
20
+
21
+ import { getRpcClient, getRpcGeneration } from "./context-db";
22
+
23
+ export interface SocketNotification {
24
+ id: number;
25
+ type: string;
26
+ payload: Record<string, unknown>;
27
+ sessionId?: string;
28
+ }
29
+
30
+ interface NotificationSocketOptions {
31
+ /** Current active session id (re-read cheaply to follow session switches). */
32
+ getSessionId: () => string | null;
33
+ /** Handle one delivered notification. Returns true if it was consumed (so its
34
+ * id can advance the ack cursor). Async because dialog handlers await. */
35
+ onNotification: (notification: SocketNotification) => boolean | Promise<boolean>;
36
+ }
37
+
38
+ const RECONNECT_BASE_MS = 500;
39
+ const RECONNECT_MAX_MS = 10_000;
40
+ /** Cheap session-watch interval. Reads a property only; no network. The CPU bug
41
+ * was the per-tick fetch, not the timer — this tick does zero IPC at idle. */
42
+ const SESSION_WATCH_MS = 1_000;
43
+
44
+ let socket: WebSocket | null = null;
45
+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
46
+ let sessionWatchTimer: ReturnType<typeof setInterval> | undefined;
47
+ let reconnectAttempt = 0;
48
+ let closed = false;
49
+ let helloedSession: string | null = null;
50
+ let opts: NotificationSocketOptions | null = null;
51
+ /** Generation of the rpc client at connect time; a dispose/reinit bumps it and
52
+ * invalidates an in-flight socket so its late callbacks are ignored. */
53
+ let connectGeneration = 0;
54
+ /** Highest handled notification id (sent in hello so a reconnect re-delivers the
55
+ * unhandled backlog; sent in ack so the server prunes the queue). */
56
+ let lastHandledId = 0;
57
+
58
+ /** Open the persistent notification socket. Idempotent: a second call while open
59
+ * is a no-op. Reconnects on its own after any drop. */
60
+ export function startNotificationSocket(options: NotificationSocketOptions): void {
61
+ opts = options;
62
+ closed = false;
63
+ connectGeneration = getRpcGeneration();
64
+ connect();
65
+ if (!sessionWatchTimer) {
66
+ sessionWatchTimer = setInterval(watchSession, SESSION_WATCH_MS);
67
+ }
68
+ }
69
+
70
+ /** Close the socket and stop reconnecting. Call on TUI dispose. */
71
+ export function stopNotificationSocket(): void {
72
+ closed = true;
73
+ if (reconnectTimer) {
74
+ clearTimeout(reconnectTimer);
75
+ reconnectTimer = undefined;
76
+ }
77
+ if (sessionWatchTimer) {
78
+ clearInterval(sessionWatchTimer);
79
+ sessionWatchTimer = undefined;
80
+ }
81
+ try {
82
+ socket?.close();
83
+ } catch {
84
+ // best-effort
85
+ }
86
+ socket = null;
87
+ helloedSession = null;
88
+ reconnectAttempt = 0;
89
+ }
90
+
91
+ function scheduleReconnect(): void {
92
+ if (closed) return;
93
+ if (reconnectTimer) return;
94
+ const delay = Math.min(RECONNECT_BASE_MS * 2 ** reconnectAttempt, RECONNECT_MAX_MS);
95
+ reconnectAttempt += 1;
96
+ reconnectTimer = setTimeout(() => {
97
+ reconnectTimer = undefined;
98
+ connect();
99
+ }, delay);
100
+ }
101
+
102
+ async function connect(): Promise<void> {
103
+ if (closed) return;
104
+ if (socket) return; // already connected/connecting
105
+
106
+ const client = getRpcClient();
107
+ if (!client) {
108
+ scheduleReconnect();
109
+ return;
110
+ }
111
+ const endpoint = await client.resolveEndpoint();
112
+ // The generation may have bumped (dispose/reinit) while resolving — abandon.
113
+ if (closed || getRpcGeneration() !== connectGeneration) return;
114
+ if (!endpoint) {
115
+ scheduleReconnect();
116
+ return;
117
+ }
118
+
119
+ let ws: WebSocket;
120
+ try {
121
+ ws = new WebSocket(`ws://127.0.0.1:${endpoint.port}/ws`);
122
+ } catch {
123
+ scheduleReconnect();
124
+ return;
125
+ }
126
+ socket = ws;
127
+
128
+ ws.addEventListener("open", () => {
129
+ if (socket !== ws) return;
130
+ reconnectAttempt = 0;
131
+ sendHello(ws, endpoint.token);
132
+ });
133
+
134
+ ws.addEventListener("message", (event) => {
135
+ if (socket !== ws) return;
136
+ void handleSocketMessage(ws, String((event as MessageEvent).data));
137
+ });
138
+
139
+ const onDown = () => {
140
+ if (socket === ws) {
141
+ socket = null;
142
+ helloedSession = null;
143
+ }
144
+ scheduleReconnect();
145
+ };
146
+ ws.addEventListener("close", onDown);
147
+ ws.addEventListener("error", onDown);
148
+ }
149
+
150
+ function sendHello(ws: WebSocket, token: string | null): void {
151
+ const sessionId = opts?.getSessionId() ?? undefined;
152
+ helloedSession = sessionId ?? null;
153
+ ws.send(
154
+ JSON.stringify({
155
+ type: "hello",
156
+ token: token ?? "",
157
+ sessionId,
158
+ lastReceivedId: lastHandledId,
159
+ }),
160
+ );
161
+ }
162
+
163
+ async function handleSocketMessage(ws: WebSocket, raw: string): Promise<void> {
164
+ let msg: { type?: string; notification?: SocketNotification; error?: string };
165
+ try {
166
+ msg = JSON.parse(raw);
167
+ } catch {
168
+ return;
169
+ }
170
+
171
+ if (msg.type === "notification" && msg.notification) {
172
+ const notification = msg.notification;
173
+ // Client-side session filter mirrors the old poller's per-message re-check:
174
+ // a session-scoped notification is only acted on while the TUI is actually
175
+ // viewing that session (the active session can change between queueing and
176
+ // delivery). Global (session-less) notifications always apply.
177
+ const active = opts?.getSessionId() ?? null;
178
+ if (notification.sessionId && active && notification.sessionId !== active) {
179
+ // Not for the session we're viewing — do NOT ack it (a TUI on the right
180
+ // session, or a later switch back, should still get it). Just skip.
181
+ return;
182
+ }
183
+ let consumed = false;
184
+ try {
185
+ consumed = await Promise.resolve(opts?.onNotification(notification) ?? false);
186
+ } catch {
187
+ consumed = false;
188
+ }
189
+ // A dispose/reinit during an awaited dialog handler invalidates this socket.
190
+ if (socket !== ws || getRpcGeneration() !== connectGeneration) return;
191
+ if (consumed && notification.id > lastHandledId) {
192
+ lastHandledId = notification.id;
193
+ // Ack so the server prunes the queue during this long-lived connection.
194
+ // (The id also rides the next reconnect hello via lastReceivedId, so a
195
+ // dropped ack just re-delivers an already-consumed item, which the
196
+ // handlers are idempotent against.)
197
+ try {
198
+ ws.send(JSON.stringify({ type: "ack", lastReceivedId: lastHandledId }));
199
+ } catch {
200
+ // best-effort; reconnect hello re-syncs via lastReceivedId
201
+ }
202
+ }
203
+ return;
204
+ }
205
+
206
+ if (msg.type === "error") {
207
+ // Server rejected us (bad token, etc.). Close and let backoff retry after
208
+ // rediscovering the port/token (the server may have been replaced).
209
+ try {
210
+ ws.close();
211
+ } catch {
212
+ // best-effort
213
+ }
214
+ }
215
+ }
216
+
217
+ /** Cheap session-change watcher: re-scope the socket only when the active session
218
+ * actually changes. Reads a property; no network at idle. */
219
+ function watchSession(): void {
220
+ if (closed || !socket || socket.readyState !== WebSocket.OPEN) return;
221
+ const current = opts?.getSessionId() ?? null;
222
+ if (current === helloedSession) return;
223
+ // Re-hello with the new session; the server replaces this socket's sink scope.
224
+ const client = getRpcClient();
225
+ void client?.resolveEndpoint().then((endpoint) => {
226
+ if (!socket || socket.readyState !== WebSocket.OPEN) return;
227
+ sendHello(socket, endpoint?.token ?? null);
228
+ });
229
+ }