@pi-chamber/web 0.9.5 → 0.9.7
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.
- package/dist/assets/DiagramView-BvrCkm_z.js +1 -0
- package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DMvRLRN1.js} +1 -1
- package/dist/assets/FileSaveConflictDialog-DGa9u43J.js +3 -0
- package/dist/assets/FilesView-CNHu4RnC.js +6 -0
- package/dist/assets/{GitView-BNkzec7G.js → GitView-Cbepz-bR.js} +3 -3
- package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-C2X5oXQm.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
- package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-i_9BIlgo.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-CDRZswx-.js} +1 -1
- package/dist/assets/SettingsView-hyAGp836.js +2 -0
- package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
- package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-CJ87b80H.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
- package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-DesjbW8a.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-CsAu9rOt.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
- package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-D_31YElh.js} +1 -1
- package/dist/assets/index-BXgR2dKM.css +1 -0
- package/dist/assets/index-BZpvAhrX.js +8 -0
- package/dist/assets/{index-B8Wt2aN3.js → index-CXLVW_GG.js} +1 -1
- package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-BX609Lau.js} +1 -1
- package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-FgBWqu9b.js} +1 -1
- package/dist/assets/{main-DCK6lLCo.js → main-C_pL2r_k.js} +2 -2
- package/dist/assets/{main-C1OSzD-E.js → main-tv2uysSs.js} +7 -7
- package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-D3Ibaffd.js} +1 -1
- package/dist/assets/{miniChat-CXiSlptL.js → miniChat-B0xQlBzZ.js} +2 -2
- package/dist/assets/{mobile-D0HVxiyJ.js → mobile-BmSlVuhn.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
- package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
- package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
- package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-egSD9pqj.js} +1 -1
- package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-C9QQrBIx.js} +104 -104
- package/dist/assets/useFilesViewSearch-BTZutbn-.js +7 -0
- package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
- package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
- package/dist/assets/{web-components-B5sMa_kC.js → web-components-CYngz9Ml.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +17 -3
- package/server/lib/client-auth/DOCUMENTATION.md +184 -0
- package/server/lib/client-auth/live-revocation.test.js +567 -0
- package/server/lib/client-auth/principal-tracker.js +383 -0
- package/server/lib/client-auth/principal-tracker.test.js +321 -0
- package/server/lib/client-auth/remote-clients.js +31 -0
- package/server/lib/client-auth/remote-clients.test.js +44 -0
- package/server/lib/fs/DOCUMENTATION.md +15 -3
- package/server/lib/fs/routes.js +369 -51
- package/server/lib/fs/routes.test.js +565 -3
- package/server/lib/fs/search.js +74 -29
- package/server/lib/pi/event-stream.js +269 -0
- package/server/lib/pi/event-stream.test.js +776 -0
- package/server/lib/pi/routes.js +132 -28
- package/server/lib/pi/routes.test.js +213 -4
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -4
- package/server/lib/pi/session-daemon/ipc-client.js +19 -15
- package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
- package/server/lib/pi/session-daemon/prompt-operations.test.js +9 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
- package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
- package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
- package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
- package/server/lib/pi/session-daemon/session-daemon.js +339 -37
- package/server/lib/pi/session-daemon/session-daemon.test.js +47 -17
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
- package/server/lib/pi/session-daemon/session-replay.test.js +11 -4
- package/server/lib/pi/session-daemon/supervisor.js +30 -5
- package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
- package/server/lib/pi/ui-settings-store.js +1 -1
- package/server/lib/pi/ui-settings-store.test.js +3 -1
- package/server/lib/server/core-routes.js +11 -1
- package/server/lib/server/cors.js +6 -0
- package/server/lib/server/cors.test.js +3 -0
- package/server/lib/stt/DOCUMENTATION.md +2 -0
- package/server/lib/stt/runtime.js +39 -2
- package/server/lib/stt/runtime.test.js +53 -0
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +48 -2
- package/server/lib/terminal/runtime.test.js +35 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
- package/server/lib/ui-auth/ui-auth.js +98 -0
- package/server/lib/ui-auth/ui-auth.test.js +249 -0
- package/server/lib/workspace/host.js +9 -3
- package/server/lib/workspace/host.test.js +15 -0
- package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
- package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
- package/dist/assets/FilesView-CJytSUAX.js +0 -6
- package/dist/assets/SettingsView-z8uf0XyM.js +0 -2
- package/dist/assets/SettingsWindow-CPDmgNg2.js +0 -1
- package/dist/assets/index-DIF8b4bh.css +0 -1
- package/dist/assets/index-jrfQYSvP.js +0 -8
- package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +0 -2
- package/dist/assets/renderMobileApp-B5x_PWlc.js +0 -11
- package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +0 -53
- package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
- package/dist/assets/useSwitcherItems-_RSo3F-A.js +0 -1
package/server/lib/fs/search.js
CHANGED
|
@@ -95,9 +95,20 @@ const fuzzyMatchScoreNormalized = (normalizedQuery, candidate) => {
|
|
|
95
95
|
return score;
|
|
96
96
|
};
|
|
97
97
|
|
|
98
|
-
export const createFsSearchRuntime = ({
|
|
98
|
+
export const createFsSearchRuntime = ({
|
|
99
|
+
fsPromises,
|
|
100
|
+
path,
|
|
101
|
+
spawn,
|
|
102
|
+
resolveGitBinaryForSpawn,
|
|
103
|
+
gitCheckIgnoreTimeoutMs = 2500,
|
|
104
|
+
}) => {
|
|
105
|
+
const effectiveGitCheckIgnoreTimeoutMs = Number.isFinite(gitCheckIgnoreTimeoutMs) && gitCheckIgnoreTimeoutMs > 0
|
|
106
|
+
? gitCheckIgnoreTimeoutMs
|
|
107
|
+
: 2500;
|
|
108
|
+
const inFlightGitignoreChecks = new Map();
|
|
109
|
+
|
|
99
110
|
const searchFilesystemFiles = async (rootPath, options) => {
|
|
100
|
-
const { limit, query, includeHidden, respectGitignore } = options;
|
|
111
|
+
const { limit, query, includeHidden, respectGitignore, type } = options;
|
|
101
112
|
const includeHiddenEntries = Boolean(includeHidden);
|
|
102
113
|
const normalizedQuery = query.trim().toLowerCase();
|
|
103
114
|
const matchAll = normalizedQuery.length === 0;
|
|
@@ -123,18 +134,47 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
123
134
|
return { dir, dirents, ignoredPaths: new Set() };
|
|
124
135
|
}
|
|
125
136
|
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
137
|
+
const checkKey = `${dir}\0${pathsToCheck.join('\0')}`;
|
|
138
|
+
let check = inFlightGitignoreChecks.get(checkKey);
|
|
139
|
+
if (!check) {
|
|
140
|
+
check = new Promise((resolve, reject) => {
|
|
141
|
+
const child = spawn(resolveGitBinaryForSpawn(), ['check-ignore', '--', ...pathsToCheck], {
|
|
142
|
+
cwd: dir,
|
|
143
|
+
windowsHide: true,
|
|
144
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
let stdout = '';
|
|
148
|
+
let settled = false;
|
|
149
|
+
let timeout = null;
|
|
150
|
+
const finish = (callback) => {
|
|
151
|
+
if (settled) return;
|
|
152
|
+
settled = true;
|
|
153
|
+
if (timeout) clearTimeout(timeout);
|
|
154
|
+
callback();
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
timeout = setTimeout(() => {
|
|
158
|
+
try {
|
|
159
|
+
child.kill('SIGKILL');
|
|
160
|
+
} catch {
|
|
161
|
+
}
|
|
162
|
+
finish(() => reject(new Error('Timed out while checking gitignore rules')));
|
|
163
|
+
}, effectiveGitCheckIgnoreTimeoutMs);
|
|
164
|
+
|
|
165
|
+
child.stdout?.on('data', (data) => { stdout += data.toString(); });
|
|
166
|
+
child.on('close', () => finish(() => resolve(stdout)));
|
|
167
|
+
child.on('error', (error) => finish(() => reject(error)));
|
|
131
168
|
});
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
169
|
+
inFlightGitignoreChecks.set(checkKey, check);
|
|
170
|
+
const clearCheck = () => {
|
|
171
|
+
if (inFlightGitignoreChecks.get(checkKey) === check) {
|
|
172
|
+
inFlightGitignoreChecks.delete(checkKey);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
check.then(clearCheck, clearCheck);
|
|
176
|
+
}
|
|
177
|
+
const result = await check;
|
|
138
178
|
|
|
139
179
|
const ignoredNames = new Set(
|
|
140
180
|
String(result)
|
|
@@ -144,8 +184,8 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
144
184
|
);
|
|
145
185
|
|
|
146
186
|
return { dir, dirents, ignoredPaths: ignoredNames };
|
|
147
|
-
} catch {
|
|
148
|
-
|
|
187
|
+
} catch (error) {
|
|
188
|
+
throw new Error(`Failed to apply gitignore rules in ${dir}`, { cause: error });
|
|
149
189
|
}
|
|
150
190
|
})
|
|
151
191
|
);
|
|
@@ -167,6 +207,21 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
167
207
|
if (shouldSkipSearchDirectory(entryName, includeHiddenEntries)) {
|
|
168
208
|
continue;
|
|
169
209
|
}
|
|
210
|
+
|
|
211
|
+
if (type === 'directory') {
|
|
212
|
+
const relativePath = normalizeRelativeSearchPath(rootPath, entryPath, path);
|
|
213
|
+
const score = matchAll ? 0 : fuzzyMatchScoreNormalized(normalizedQuery, relativePath);
|
|
214
|
+
if (score !== null) {
|
|
215
|
+
candidates.push({
|
|
216
|
+
name: entryName,
|
|
217
|
+
path: entryPath,
|
|
218
|
+
relativePath,
|
|
219
|
+
extension: undefined,
|
|
220
|
+
score,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
170
225
|
if (!visited.has(entryPath)) {
|
|
171
226
|
visited.add(entryPath);
|
|
172
227
|
queue.push(entryPath);
|
|
@@ -174,32 +229,22 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
174
229
|
continue;
|
|
175
230
|
}
|
|
176
231
|
|
|
177
|
-
if (!dirent.isFile()) {
|
|
232
|
+
if (!dirent.isFile() || type === 'directory') {
|
|
178
233
|
continue;
|
|
179
234
|
}
|
|
180
235
|
|
|
181
236
|
const relativePath = normalizeRelativeSearchPath(rootPath, entryPath, path);
|
|
182
237
|
const extension = entryName.includes('.') ? entryName.split('.').pop()?.toLowerCase() : undefined;
|
|
238
|
+
const score = matchAll ? 0 : fuzzyMatchScoreNormalized(normalizedQuery, relativePath);
|
|
183
239
|
|
|
184
|
-
if (
|
|
240
|
+
if (score !== null) {
|
|
185
241
|
candidates.push({
|
|
186
242
|
name: entryName,
|
|
187
243
|
path: entryPath,
|
|
188
244
|
relativePath,
|
|
189
245
|
extension,
|
|
190
|
-
score
|
|
246
|
+
score,
|
|
191
247
|
});
|
|
192
|
-
} else {
|
|
193
|
-
const score = fuzzyMatchScoreNormalized(normalizedQuery, relativePath);
|
|
194
|
-
if (score !== null) {
|
|
195
|
-
candidates.push({
|
|
196
|
-
name: entryName,
|
|
197
|
-
path: entryPath,
|
|
198
|
-
relativePath,
|
|
199
|
-
extension,
|
|
200
|
-
score,
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
248
|
}
|
|
204
249
|
|
|
205
250
|
if (candidates.length >= collectLimit) {
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi event stream connection lifecycle.
|
|
3
|
+
*
|
|
4
|
+
* Owns everything one `/api/pi/events` SSE connection needs to run safely, so
|
|
5
|
+
* the route stays a thin adapter:
|
|
6
|
+
*
|
|
7
|
+
* - Cleanup is installed before `subscribe` is awaited, so a client that
|
|
8
|
+
* disconnects while the subscription is still opening cannot leak the daemon
|
|
9
|
+
* subscription; when the late subscription resolves it is closed exactly
|
|
10
|
+
* once.
|
|
11
|
+
* - Every teardown path (client disconnect, subscription error, server
|
|
12
|
+
* shutdown) funnels through one idempotent cleanup, so close/end/heartbeat
|
|
13
|
+
* teardown runs at most once per connection regardless of how many close
|
|
14
|
+
* events race.
|
|
15
|
+
* - An `AbortSignal` is handed through the supervisor to the IPC client, so
|
|
16
|
+
* shutdown can cancel a subscription while its daemon socket is opening.
|
|
17
|
+
* - Named heartbeat events are never written to a dead response, and no late
|
|
18
|
+
* frame is written after cleanup.
|
|
19
|
+
* - The response socket buffer is byte-bounded and enforced BEFORE each
|
|
20
|
+
* write, so no frame ever overshoots the bound by one huge write. A frame
|
|
21
|
+
* that would not fit is never written: the stream ends and the client
|
|
22
|
+
* reconnects from its last accepted sequence, where the daemon replays the
|
|
23
|
+
* missed suffix or issues an authoritative snapshot. Nothing is silently
|
|
24
|
+
* removed from an otherwise contiguous stream, but frames that were never
|
|
25
|
+
* flushed to the socket are NOT promised as delivered — the reconnect
|
|
26
|
+
* replay is the delivery guarantee.
|
|
27
|
+
* - A stalled reader is always released with a bounded deadline. When a
|
|
28
|
+
* write returns false, a drain deadline ends the connection even if the
|
|
29
|
+
* client goes quiet before crossing the byte bound. After `res.end()`, a
|
|
30
|
+
* terminate deadline destroys the response: `end()` alone only queues the
|
|
31
|
+
* FIN behind unflushed data, so a client that never reads would hold the
|
|
32
|
+
* socket (and server shutdown) open forever.
|
|
33
|
+
* - The response `'error'` guard stays attached for the response's lifetime
|
|
34
|
+
* and is idempotent: cleanup can complete while data is still in flight,
|
|
35
|
+
* and a late `'error'` with no listener would crash the process.
|
|
36
|
+
* - A healthy client's connection is independent of a slow one.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
export const DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES = 8 * 1024 * 1024;
|
|
40
|
+
const DEFAULT_EVENT_STREAM_DRAIN_TIMEOUT_MS = 5_000;
|
|
41
|
+
const DEFAULT_EVENT_STREAM_TERMINATE_TIMEOUT_MS = 5_000;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Tracks live event stream connections so the server can end all of them
|
|
45
|
+
* (active or still opening) during shutdown.
|
|
46
|
+
*/
|
|
47
|
+
export const createPiEventStreamRegistry = () => {
|
|
48
|
+
const connections = new Set();
|
|
49
|
+
return {
|
|
50
|
+
get size() {
|
|
51
|
+
return connections.size;
|
|
52
|
+
},
|
|
53
|
+
add: (connection) => {
|
|
54
|
+
connections.add(connection);
|
|
55
|
+
},
|
|
56
|
+
delete: (connection) => {
|
|
57
|
+
connections.delete(connection);
|
|
58
|
+
},
|
|
59
|
+
/** Idempotent per connection: closing twice closes the subscription once. */
|
|
60
|
+
closeAll: () => {
|
|
61
|
+
for (const connection of [...connections]) connection.close();
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Run one SSE event stream connection to completion.
|
|
68
|
+
*
|
|
69
|
+
* The route must have already validated the query, checked the runtime, and
|
|
70
|
+
* flushed the SSE headers. `subscribe` receives `{ onEvent, onError, signal }`
|
|
71
|
+
* and resolves to a close function (or undefined).
|
|
72
|
+
*/
|
|
73
|
+
export const openPiEventStream = ({
|
|
74
|
+
req,
|
|
75
|
+
res,
|
|
76
|
+
subscribe,
|
|
77
|
+
projectFrame,
|
|
78
|
+
heartbeatMs = 15_000,
|
|
79
|
+
maxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
|
|
80
|
+
drainTimeoutMs = DEFAULT_EVENT_STREAM_DRAIN_TIMEOUT_MS,
|
|
81
|
+
terminateTimeoutMs = DEFAULT_EVENT_STREAM_TERMINATE_TIMEOUT_MS,
|
|
82
|
+
registry,
|
|
83
|
+
respondWithError,
|
|
84
|
+
}) => {
|
|
85
|
+
let closed = false;
|
|
86
|
+
let heartbeat;
|
|
87
|
+
let drainTimer;
|
|
88
|
+
let terminateTimer;
|
|
89
|
+
let subscriptionClose;
|
|
90
|
+
let subscriptionClosed = false;
|
|
91
|
+
const abort = new AbortController();
|
|
92
|
+
const connection = { close: () => endConnection() };
|
|
93
|
+
|
|
94
|
+
const closeSubscriptionOnce = (close) => {
|
|
95
|
+
if (subscriptionClosed || typeof close !== 'function') return;
|
|
96
|
+
subscriptionClosed = true;
|
|
97
|
+
try {
|
|
98
|
+
close();
|
|
99
|
+
} catch {
|
|
100
|
+
// A subscriber that throws on close must not break teardown.
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const isDead = () => closed || res.destroyed === true || res.writableEnded === true;
|
|
105
|
+
|
|
106
|
+
const clearHeartbeat = () => {
|
|
107
|
+
if (heartbeat !== undefined) {
|
|
108
|
+
clearInterval(heartbeat);
|
|
109
|
+
heartbeat = undefined;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const clearDrainTimer = () => {
|
|
114
|
+
if (drainTimer !== undefined) {
|
|
115
|
+
clearTimeout(drainTimer);
|
|
116
|
+
drainTimer = undefined;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const clearTerminateTimer = () => {
|
|
121
|
+
if (terminateTimer !== undefined) {
|
|
122
|
+
clearTimeout(terminateTimer);
|
|
123
|
+
terminateTimer = undefined;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
function cleanup() {
|
|
128
|
+
if (closed) return;
|
|
129
|
+
closed = true;
|
|
130
|
+
clearHeartbeat();
|
|
131
|
+
clearDrainTimer();
|
|
132
|
+
clearTerminateTimer();
|
|
133
|
+
abort.abort();
|
|
134
|
+
closeSubscriptionOnce(subscriptionClose);
|
|
135
|
+
req.off('close', onGone);
|
|
136
|
+
res.off('close', onResClose);
|
|
137
|
+
res.off('drain', onDrain);
|
|
138
|
+
// The 'error' guard intentionally stays attached: teardown can complete
|
|
139
|
+
// while data is still in flight, and an unhandled late 'error' would
|
|
140
|
+
// crash the process. It is idempotent (cleanup re-enters as a no-op) and
|
|
141
|
+
// dies with the response object.
|
|
142
|
+
registry?.delete(connection);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const onGone = () => cleanup();
|
|
146
|
+
const onDrain = () => clearDrainTimer();
|
|
147
|
+
|
|
148
|
+
const onResClose = () => {
|
|
149
|
+
// The response fully finished (end flushed or destroyed): no further
|
|
150
|
+
// error can occur, so the guard can be detached now. The terminate
|
|
151
|
+
// deadline is cleared even when cleanup already ran (its early return
|
|
152
|
+
// would otherwise leave the timer pending behind a finished response).
|
|
153
|
+
res.off('error', onGone);
|
|
154
|
+
clearTerminateTimer();
|
|
155
|
+
cleanup();
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* End the stream after teardown so the client reconnects (shutdown, error,
|
|
160
|
+
* backpressure). The response socket may still hold unflushed data for a
|
|
161
|
+
* stalled reader — `res.end()` alone queues the FIN behind it and the
|
|
162
|
+
* socket stays open forever — so a bounded terminate deadline destroys the
|
|
163
|
+
* socket if it does not finish in time.
|
|
164
|
+
*/
|
|
165
|
+
const endConnection = () => {
|
|
166
|
+
cleanup();
|
|
167
|
+
if (!res.writableEnded && !res.destroyed) res.end();
|
|
168
|
+
if (!res.destroyed) {
|
|
169
|
+
// `res.end()` alone only queues the FIN behind unflushed data: a
|
|
170
|
+
// stalled reader never receives it, so the socket (and server
|
|
171
|
+
// shutdown) stays open forever. Bound the wait and destroy. The timer
|
|
172
|
+
// is cleared only by the response's 'close' event — 'finish' fires as
|
|
173
|
+
// soon as the data is handed to the socket, which proves nothing about
|
|
174
|
+
// the socket actually releasing.
|
|
175
|
+
terminateTimer = setTimeout(() => {
|
|
176
|
+
terminateTimer = undefined;
|
|
177
|
+
if (!res.destroyed) res.destroy();
|
|
178
|
+
}, terminateTimeoutMs);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/** Bound the wait for 'drain' after a full socket buffer, even for a client that then goes quiet. */
|
|
183
|
+
const armDrainDeadline = () => {
|
|
184
|
+
if (drainTimer !== undefined) return;
|
|
185
|
+
res.once('drain', onDrain);
|
|
186
|
+
drainTimer = setTimeout(() => {
|
|
187
|
+
drainTimer = undefined;
|
|
188
|
+
res.off('drain', onDrain);
|
|
189
|
+
// A socket that never drains must not hold the connection (and server
|
|
190
|
+
// shutdown) open indefinitely: end it so the client reconnects from its
|
|
191
|
+
// last accepted sequence and the daemon replays or snapshots.
|
|
192
|
+
endConnection();
|
|
193
|
+
}, drainTimeoutMs);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const write = (chunk) => {
|
|
197
|
+
if (isDead()) return false;
|
|
198
|
+
const size = Buffer.byteLength(chunk);
|
|
199
|
+
// Enforce the byte bound BEFORE writing: a frame that would not fit is
|
|
200
|
+
// never written, so the socket buffer never overshoots the bound by one
|
|
201
|
+
// huge frame. Everything after this point is skipped because cleanup ends
|
|
202
|
+
// the stream, so the client never observes a silently missing frame
|
|
203
|
+
// inside an otherwise contiguous stream — it reconnects from its last
|
|
204
|
+
// accepted sequence and the daemon replays or snapshots.
|
|
205
|
+
if (res.writableLength + size > maxBufferedBytes) {
|
|
206
|
+
endConnection();
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
const drained = res.write(chunk);
|
|
210
|
+
if (!drained) armDrainDeadline();
|
|
211
|
+
return drained;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const send = (frame) => {
|
|
215
|
+
if (isDead()) return;
|
|
216
|
+
const event = projectFrame(frame);
|
|
217
|
+
if (event) write(`data: ${JSON.stringify(event)}\n\n`);
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
// Install cleanup before awaiting subscribe so a disconnect during the
|
|
221
|
+
// opening window cannot leak the daemon subscription.
|
|
222
|
+
req.once('close', onGone);
|
|
223
|
+
res.once('close', onResClose);
|
|
224
|
+
res.on('error', onGone);
|
|
225
|
+
registry?.add(connection);
|
|
226
|
+
|
|
227
|
+
void (async () => {
|
|
228
|
+
let attach;
|
|
229
|
+
try {
|
|
230
|
+
attach = await subscribe({
|
|
231
|
+
onEvent: send,
|
|
232
|
+
onError: endConnection,
|
|
233
|
+
signal: abort.signal,
|
|
234
|
+
});
|
|
235
|
+
} catch (error) {
|
|
236
|
+
cleanup();
|
|
237
|
+
if (typeof respondWithError === 'function') respondWithError(error);
|
|
238
|
+
else if (!res.writableEnded && !res.destroyed) res.end();
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
// The client disconnected, the subscription errored, or the server shut
|
|
242
|
+
// down while the subscription was opening: close the late subscription
|
|
243
|
+
// exactly once and never attach a heartbeat to a dead response.
|
|
244
|
+
if (closed) {
|
|
245
|
+
closeSubscriptionOnce(attach);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
subscriptionClose = attach;
|
|
249
|
+
|
|
250
|
+
const sendHeartbeat = () => {
|
|
251
|
+
if (isDead()) return;
|
|
252
|
+
// Named heartbeat events are visible to native EventSource clients.
|
|
253
|
+
// Comment-only SSE heartbeats keep proxies open but are hidden from the
|
|
254
|
+
// EventSource API, so WKWebView cannot use them to detect a silent link.
|
|
255
|
+
write('event: heartbeat\ndata: {}\n\n');
|
|
256
|
+
};
|
|
257
|
+
// Send one immediately so an empty replay still proves the connection is
|
|
258
|
+
// healthy before the client resets its reconnect backoff.
|
|
259
|
+
sendHeartbeat();
|
|
260
|
+
heartbeat = setInterval(sendHeartbeat, heartbeatMs);
|
|
261
|
+
})();
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
get closed() {
|
|
265
|
+
return closed;
|
|
266
|
+
},
|
|
267
|
+
abortSignal: abort.signal,
|
|
268
|
+
};
|
|
269
|
+
};
|