dsh-project-mcp 0.2.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.
package/src/ui.ts ADDED
@@ -0,0 +1,579 @@
1
+ /**
2
+ * Host HTTP surface for the sidebar panel.
3
+ *
4
+ * `ctx.betterSidebar` exists only in the browser half of a DSH composition, so
5
+ * the panel cannot call the `projectMcp` service in process: it fetches these
6
+ * routes, the same way `dsh-better-sidebar` serves its own `/sidebar/api/*`
7
+ * surface. Every response is `{ ok: true, value }` or `{ ok: false, error }`.
8
+ *
9
+ * @module dsh-project-mcp/ui
10
+ */
11
+
12
+ import type { IncomingMessage, ServerResponse } from 'node:http'
13
+ import type { ProjectMcpService } from './index.ts'
14
+ import { page } from './logs.ts'
15
+ import { isConflictChoice, isToolMode } from './policy.ts'
16
+ import type { PolicyOutcome } from './runtime.ts'
17
+ import type {
18
+ ConflictRequest,
19
+ OperatorRequest,
20
+ PinRequest,
21
+ PolicyRequest,
22
+ SaveErrorCode,
23
+ SaveRequest,
24
+ } from './shared.ts'
25
+ import { ROUTE_PREFIX } from './shared.ts'
26
+ import type { EntrySnapshot, McpSnapshot, SnapshotChange } from './types.ts'
27
+
28
+ /** The subset of the DSH web server this plugin registers on. */
29
+ export interface WebServerLike {
30
+ /** Register one route and return its disposer, in whatever shape the server uses. */
31
+ register(route: { kind: 'prefix'; path: string; handler: RouteHandler }): unknown
32
+ }
33
+
34
+ /** Node HTTP handler signature the web server expects. */
35
+ export type RouteHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>
36
+
37
+ /** Largest request body accepted for a session id. */
38
+ const MAX_BODY_BYTES = 4_096
39
+
40
+ /** Largest request body accepted for a save: one entry body plus its extras. */
41
+ const MAX_SAVE_BYTES = 64 * 1024
42
+
43
+ /**
44
+ * How often a quiet stream is poked.
45
+ *
46
+ * The channel can be silent for minutes — nothing happens in a project, so
47
+ * nothing is announced — and an idle connection is what proxies and browsers
48
+ * reap. A comment frame is not an event: the panel does not see it, the socket
49
+ * stays warm. `unref`'d, so a headless host is never kept alive for it.
50
+ */
51
+ const HEARTBEAT_MS = 15_000
52
+
53
+ /**
54
+ * The status channel: one open `GET events` response per panel, and a frame
55
+ * whenever the picture changes.
56
+ *
57
+ * Server-Sent Events rather than polling: DSH's own web server hands a route the
58
+ * raw response ("owns the full response lifecycle, may hold the response open,
59
+ * e.g. SSE") and exempts `text/event-stream` from its gzip filter, and the
60
+ * browser's `EventSource` reconnects on its own. The subscription is only held
61
+ * while somebody is listening, and the heartbeat only runs with a stream open.
62
+ */
63
+ export interface EventStream {
64
+ /** Serve one `GET events`: the response stays open until the client leaves. */
65
+ serve(req: IncomingMessage, res: ServerResponse): void
66
+ /** Close every open stream and stop listening; the route's disposer calls it. */
67
+ dispose(): void
68
+ }
69
+
70
+ /**
71
+ * Build the status channel of one route registration.
72
+ * @param service - the runtime's published service.
73
+ * @returns the channel's `serve`/`dispose` pair.
74
+ */
75
+ export function createEventStream(service: ProjectMcpService): EventStream {
76
+ const streams = new Set<ServerResponse>()
77
+ let heartbeat: ReturnType<typeof setInterval> | undefined
78
+ let unsubscribe: (() => void) | undefined
79
+ let latest: SnapshotChange | undefined
80
+
81
+ /**
82
+ * Write one frame, dropping a stream that has already gone: a dead socket
83
+ * raises on `write`, and an exception here would reach the pass that
84
+ * announced the change rather than the panel it was meant for.
85
+ */
86
+ const write = (res: ServerResponse, frame: string): void => {
87
+ try {
88
+ res.write(frame)
89
+ } catch {
90
+ streams.delete(res)
91
+ }
92
+ }
93
+
94
+ const frame = (event: 'hello' | 'change', change: SnapshotChange): string =>
95
+ `event: ${event}\ndata: ${JSON.stringify(change)}\n\n`
96
+
97
+ const stop = (): void => {
98
+ if (heartbeat !== undefined) clearInterval(heartbeat)
99
+ heartbeat = undefined
100
+ unsubscribe?.()
101
+ unsubscribe = undefined
102
+ }
103
+
104
+ /**
105
+ * Start listening, if this is the first stream. The subscription answers with
106
+ * the picture as it is now, which is also what a stream opened later replays:
107
+ * every frame carries the whole snapshot, so the newest one is always current.
108
+ */
109
+ const start = (): void => {
110
+ if (unsubscribe !== undefined) return
111
+ unsubscribe = service.subscribe((change) => {
112
+ latest = change
113
+ for (const stream of [...streams]) write(stream, frame('change', change))
114
+ })
115
+ heartbeat = setInterval(() => {
116
+ for (const stream of [...streams]) write(stream, ': ping\n\n')
117
+ }, HEARTBEAT_MS)
118
+ heartbeat.unref?.()
119
+ }
120
+
121
+ return {
122
+ serve(req, res): void {
123
+ res.writeHead(200, {
124
+ 'content-type': 'text/event-stream; charset=utf-8',
125
+ 'cache-control': 'no-cache, no-transform',
126
+ connection: 'keep-alive',
127
+ })
128
+ // A comment first — DSH's own HMR stream does the same — so the browser
129
+ // sees a live channel before anything happens, plus how fast to come back.
130
+ res.write(': connected\nretry: 2000\n\n')
131
+ // Subscribe before joining the fan-out: the subscription answers with the
132
+ // picture as it is, which is this stream's `hello` — a `change` frame for a
133
+ // change that predates the panel would say the same thing twice.
134
+ start()
135
+ streams.add(res)
136
+ if (latest !== undefined) write(res, frame('hello', latest))
137
+ const leave = (): void => {
138
+ streams.delete(res)
139
+ if (streams.size === 0) stop()
140
+ }
141
+ req.on('close', leave)
142
+ res.on('error', leave)
143
+ },
144
+ dispose(): void {
145
+ stop()
146
+ for (const stream of [...streams]) {
147
+ streams.delete(stream)
148
+ try {
149
+ stream.end()
150
+ } catch {
151
+ // The socket is already gone; nothing to end.
152
+ }
153
+ }
154
+ },
155
+ }
156
+ }
157
+
158
+ /**
159
+ * HTTP status each coded refusal answers with. The policy routes reuse the same
160
+ * vocabulary as a save: `invalid`/`not-found` are the panel's 400s, `failed` a
161
+ * 500.
162
+ */
163
+ const SAVE_STATUS: Record<SaveErrorCode, number> = {
164
+ invalid: 400,
165
+ blocked: 400,
166
+ 'not-found': 400,
167
+ conflict: 409,
168
+ failed: 500,
169
+ }
170
+
171
+ /**
172
+ * Read one numeric query parameter.
173
+ *
174
+ * The panel decides the window, so the host refuses rather than guesses: a
175
+ * parameter the URL does not carry is absent, and one it carries as anything but
176
+ * a finite number — `abc`, an empty value — is `'invalid'`, which the route
177
+ * answers with `bad-request`.
178
+ * @param raw - the raw value, `null` when the query string omits it.
179
+ * @returns the number, `undefined` when absent, `'invalid'` when unusable.
180
+ */
181
+ function numberParam(raw: string | null): number | undefined | 'invalid' {
182
+ if (raw === null) return undefined
183
+ const value = Number(raw)
184
+ return raw.trim() === '' || !Number.isFinite(value) ? 'invalid' : value
185
+ }
186
+
187
+ /**
188
+ * Build the route handler for {@link ROUTE_PREFIX}.
189
+ *
190
+ * Both operator actions — `Sync` and `Retry` — answer as soon as they are
191
+ * accepted, never once the servers they touch have settled: the pass they queue
192
+ * runs in the background, and the panel reads the outcome from the status
193
+ * channel. A response held open for a mount that is still connecting is exactly
194
+ * the hang this route no longer produces.
195
+ *
196
+ * @param service - the runtime's published service.
197
+ * @param events - the status channel to serve; built from the service when omitted.
198
+ * @returns a handler for `GET snapshot|events|logs`, `POST sync|retry|release|save`.
199
+ */
200
+ export function createRouteHandler(
201
+ service: ProjectMcpService,
202
+ events: EventStream = createEventStream(service),
203
+ ): RouteHandler {
204
+ const send = (res: ServerResponse, status: number, body: unknown): void => {
205
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
206
+ res.end(JSON.stringify(body))
207
+ }
208
+ const reply = async (
209
+ res: ServerResponse,
210
+ action: () => Promise<void>,
211
+ request: OperatorRequest = {},
212
+ ): Promise<void> => {
213
+ try {
214
+ await action()
215
+ send(res, 200, { ok: true, value: operatorAnswer(service, request) })
216
+ } catch (error) {
217
+ send(res, 500, {
218
+ ok: false,
219
+ error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },
220
+ })
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Answer a pin or mode change with the same envelope a save uses: the fresh
226
+ * snapshot, or the refusal code's status. The service method is synchronous —
227
+ * the policy is not part of any document, so no rescan follows — but a store
228
+ * that still fails answers `500` rather than breaking the route.
229
+ */
230
+ const replyPolicy = (res: ServerResponse, change: () => PolicyOutcome): void => {
231
+ try {
232
+ const outcome = change()
233
+ if (outcome.ok) {
234
+ send(res, 200, { ok: true, value: outcome.snapshot })
235
+ return
236
+ }
237
+ send(res, SAVE_STATUS[outcome.code], {
238
+ ok: false,
239
+ error: {
240
+ code: outcome.code,
241
+ message: outcome.message,
242
+ // The F-48 companions ride the envelope only when the outcome has
243
+ // them: an uncoded refusal's body is byte-identical to before.
244
+ ...(outcome.messageCode === undefined
245
+ ? {}
246
+ : { messageCode: outcome.messageCode, messageParams: outcome.messageParams }),
247
+ },
248
+ })
249
+ } catch (error) {
250
+ send(res, 500, {
251
+ ok: false,
252
+ error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },
253
+ })
254
+ }
255
+ }
256
+ return async (req, res) => {
257
+ const url = new URL(req.url ?? '/', 'http://localhost')
258
+ const action = url.pathname.slice(ROUTE_PREFIX.length).replace(/^\/+|\/+$/g, '')
259
+ const method = req.method ?? 'GET'
260
+ if (method === 'GET' && action === 'snapshot') {
261
+ send(res, 200, { ok: true, value: service.snapshot() })
262
+ return
263
+ }
264
+ if (method === 'POST' && action === 'sync') {
265
+ const request = operatorRequestOf(await readJson(req))
266
+ // The pass is background work from here on, so the answer is the picture
267
+ // as it is now — the status channel carries the rest.
268
+ service.syncSoon(request.projectRoot)
269
+ send(res, 200, { ok: true, value: operatorAnswer(service, request) })
270
+ return
271
+ }
272
+ if (method === 'GET' && action === 'events') {
273
+ events.serve(req, res)
274
+ return
275
+ }
276
+ // The tab is drawn from the snapshot, which carries the newest page of the
277
+ // ring; this route is "show older". It reads the ring directly — the buffer
278
+ // has one owner (`src/logs.ts`) and no runtime state to ask for — and it
279
+ // answers even when the named project is unknown to the runtime: the ring
280
+ // is keyed by the root, and an empty page is an answer, not a refusal.
281
+ if (method === 'GET' && action === 'logs') {
282
+ const projectRoot = url.searchParams.get('projectRoot')
283
+ const before = numberParam(url.searchParams.get('before'))
284
+ const limit = numberParam(url.searchParams.get('limit'))
285
+ if (projectRoot === null || projectRoot === '' || before === 'invalid' || limit === 'invalid') {
286
+ send(res, 400, {
287
+ ok: false,
288
+ error: {
289
+ code: 'bad-request',
290
+ message: 'GET logs needs a projectRoot, and before/limit as finite numbers',
291
+ },
292
+ })
293
+ return
294
+ }
295
+ send(res, 200, {
296
+ ok: true,
297
+ value: page({
298
+ projectRoot,
299
+ ...(before === undefined ? {} : { before }),
300
+ ...(limit === undefined ? {} : { limit }),
301
+ }),
302
+ })
303
+ return
304
+ }
305
+ if (method === 'POST' && action === 'retry') {
306
+ const request = operatorRequestOf(await readJson(req))
307
+ await reply(res, () => service.retry(request.projectRoot), request)
308
+ return
309
+ }
310
+ if (method === 'POST' && action === 'release') {
311
+ const body = await readJson(req)
312
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : undefined
313
+ await reply(res, () => service.release(sessionId))
314
+ return
315
+ }
316
+ if (method === 'POST' && action === 'save') {
317
+ const request = saveRequestOf(await readJson(req, MAX_SAVE_BYTES))
318
+ if (request === undefined) {
319
+ send(res, 400, {
320
+ ok: false,
321
+ error: { code: 'invalid', message: 'the save body is not a well-formed entry request' },
322
+ })
323
+ return
324
+ }
325
+ try {
326
+ const outcome = await service.save(request)
327
+ if (outcome.ok) {
328
+ send(res, 200, { ok: true, value: outcome.snapshot })
329
+ return
330
+ }
331
+ send(res, SAVE_STATUS[outcome.code], {
332
+ ok: false,
333
+ error: {
334
+ code: outcome.code,
335
+ message: outcome.message,
336
+ // The F-48 companions ride the envelope only when the outcome has
337
+ // them: an uncoded refusal's body is byte-identical to before.
338
+ ...(outcome.messageCode === undefined
339
+ ? {}
340
+ : { messageCode: outcome.messageCode, messageParams: outcome.messageParams }),
341
+ },
342
+ })
343
+ } catch (error) {
344
+ send(res, 500, {
345
+ ok: false,
346
+ error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },
347
+ })
348
+ }
349
+ return
350
+ }
351
+ // A pin and a mode are durable plugin state, not document edits: neither
352
+ // route rescans, and both answer with the snapshot rebuilt on the spot.
353
+ if (method === 'POST' && action === 'pin') {
354
+ const request = pinRequestOf(await readJson(req))
355
+ if (request === undefined) {
356
+ send(res, 400, {
357
+ ok: false,
358
+ error: { code: 'invalid', message: 'the pin body is not a well-formed pin request' },
359
+ })
360
+ return
361
+ }
362
+ replyPolicy(res, () => service.setPin(request))
363
+ return
364
+ }
365
+ if (method === 'POST' && action === 'policy') {
366
+ const request = policyRequestOf(await readJson(req))
367
+ if (request === undefined) {
368
+ send(res, 400, {
369
+ ok: false,
370
+ error: { code: 'invalid', message: 'the policy body is not a well-formed mode request' },
371
+ })
372
+ return
373
+ }
374
+ replyPolicy(res, () => service.setPolicy(request))
375
+ return
376
+ }
377
+ if (method === 'POST' && action === 'conflict') {
378
+ const request = conflictRequestOf(await readJson(req))
379
+ if (request === undefined) {
380
+ send(res, 400, {
381
+ ok: false,
382
+ error: {
383
+ code: 'invalid',
384
+ message: 'the conflict body is not a well-formed conflict request',
385
+ },
386
+ })
387
+ return
388
+ }
389
+ replyPolicy(res, () => service.setConflictChoice(request))
390
+ return
391
+ }
392
+ send(res, 404, {
393
+ ok: false,
394
+ error: { code: 'not-found', message: `unknown route ${method} ${url.pathname}` },
395
+ })
396
+ }
397
+ }
398
+
399
+ /**
400
+ * The operator request a `sync` or `retry` body carries. A body that is not an
401
+ * operator request at all — a surface that predates the field, a `{}`, a
402
+ * malformed value — reads as the global call it used to be.
403
+ * @param body - the parsed request body.
404
+ * @returns the project the action applies to, and the answer shape asked for.
405
+ */
406
+ export function operatorRequestOf(body: Record<string, unknown>): OperatorRequest {
407
+ const projectRoot = body.projectRoot
408
+ return {
409
+ ...(typeof projectRoot === 'string' && projectRoot !== '' ? { projectRoot } : {}),
410
+ ...(body.full === true ? { full: true } : {}),
411
+ }
412
+ }
413
+
414
+ /**
415
+ * The snapshot an operator route answers with.
416
+ *
417
+ * A single-project surface (the sidebar tab, a row's own `Retry`) gets that
418
+ * project's slice: it shows one project, and answering with every project made a click in one of them look like it had touched all of them. A
419
+ * surface that lists every project asks for `full`, because a narrowed answer
420
+ * would empty the list it renders.
421
+ * @param service - the runtime's published service.
422
+ * @param request - the operator request the caller sent.
423
+ * @returns the snapshot, narrowed when the caller asked for one project.
424
+ */
425
+ export function operatorAnswer(service: ProjectMcpService, request: OperatorRequest): McpSnapshot {
426
+ const snapshot = service.snapshot()
427
+ if (request.full === true || request.projectRoot === undefined) return snapshot
428
+ return projectSlice(snapshot, request.projectRoot)
429
+ }
430
+
431
+ /**
432
+ * One project's slice of a snapshot: its own project record and the root the
433
+ * panel prints as watched, with the other projects dropped.
434
+ * @param snapshot - the whole snapshot.
435
+ * @param projectRoot - the project to keep.
436
+ * @returns the narrowed snapshot.
437
+ */
438
+ export function projectSlice(snapshot: McpSnapshot, projectRoot: string): McpSnapshot {
439
+ return {
440
+ ...snapshot,
441
+ projects: snapshot.projects.filter((project) => project.projectRoot === projectRoot),
442
+ watchedFiles: snapshot.watchedFiles.filter((file) => file === projectRoot),
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Register the panel routes on the DSH web server.
448
+ * @param webServer - the injected web server service.
449
+ * @param service - the runtime's published service.
450
+ * @returns the disposer: it closes the open status streams, then the routes.
451
+ */
452
+ export function registerRoutes(webServer: WebServerLike, service: ProjectMcpService): () => void {
453
+ const events = createEventStream(service)
454
+ const registration = webServer.register({
455
+ kind: 'prefix',
456
+ path: ROUTE_PREFIX,
457
+ handler: createRouteHandler(service, events),
458
+ })
459
+ return () => {
460
+ events.dispose()
461
+ disposeRegistration(registration)
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Run one registration's disposer, whichever shape the web server hands back:
467
+ * Cordis only ever calls a disposer *function* for an effect, and the server may
468
+ * return a `{ dispose() }` object instead.
469
+ * @param registration - the value `registerRoutes` returned.
470
+ */
471
+ export function disposeRegistration(registration: unknown): void {
472
+ if (typeof registration === 'function') {
473
+ ;(registration as () => void)()
474
+ return
475
+ }
476
+ if (typeof registration !== 'object' || registration === null) return
477
+ const dispose = (registration as { dispose?: unknown }).dispose
478
+ if (typeof dispose === 'function') (dispose as () => void).call(registration)
479
+ }
480
+
481
+ /**
482
+ * Read a bounded JSON body; anything unparseable, oversized or non-object stays
483
+ * an empty object.
484
+ * @param req - the incoming request.
485
+ * @param limit - largest body accepted, in bytes.
486
+ * @returns the parsed object body, or `{}` when there is none.
487
+ */
488
+ async function readJson(req: IncomingMessage, limit: number = MAX_BODY_BYTES): Promise<Record<string, unknown>> {
489
+ const chunks: Buffer[] = []
490
+ let size = 0
491
+ for await (const chunk of req) {
492
+ const buffer = chunk as Buffer
493
+ size += buffer.length
494
+ if (size > limit) return {}
495
+ chunks.push(buffer)
496
+ }
497
+ try {
498
+ const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))
499
+ return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}
500
+ } catch {
501
+ return {}
502
+ }
503
+ }
504
+
505
+ /**
506
+ * Shape one `POST save` body into a {@link SaveRequest}.
507
+ *
508
+ * Only the envelope is checked here: whether the entry itself parses, and
509
+ * whether the document may be written, is the runtime's decision and comes back
510
+ * as a coded refusal.
511
+ * @param body - parsed request body.
512
+ * @returns the request, or `undefined` when a required field is missing.
513
+ */
514
+ function saveRequestOf(body: Record<string, unknown>): SaveRequest | undefined {
515
+ const { projectRoot, server, document, revision, entry } = body
516
+ if (typeof projectRoot !== 'string' || projectRoot === '') return undefined
517
+ if (typeof server !== 'string' || server === '') return undefined
518
+ if (typeof document !== 'string' || document === '') return undefined
519
+ if (typeof revision !== 'string' || revision === '') return undefined
520
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return undefined
521
+ return {
522
+ projectRoot,
523
+ server,
524
+ document,
525
+ revision,
526
+ ...(body.consent === true ? { consent: true } : {}),
527
+ entry: entry as EntrySnapshot,
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Shape one `POST pin` body into a {@link PinRequest}.
533
+ *
534
+ * Only the envelope is checked here: whether the project has a live session is
535
+ * the runtime's decision and comes back as a coded refusal.
536
+ * @param body - parsed request body.
537
+ * @returns the request, or `undefined` when a required field is missing.
538
+ */
539
+ function pinRequestOf(body: Record<string, unknown>): PinRequest | undefined {
540
+ const { projectRoot, tool, pinned } = body
541
+ if (typeof projectRoot !== 'string' || projectRoot === '') return undefined
542
+ if (typeof tool !== 'string' || tool === '') return undefined
543
+ if (typeof pinned !== 'boolean') return undefined
544
+ return { projectRoot, tool, pinned }
545
+ }
546
+
547
+ /**
548
+ * Shape one `POST policy` body into a {@link PolicyRequest}.
549
+ *
550
+ * The mode is validated here as well as in the runtime, so a switch carrying a
551
+ * mode this build does not know is a `400` and never reaches the store.
552
+ * @param body - parsed request body.
553
+ * @returns the request, or `undefined` when a required field is missing.
554
+ */
555
+ function policyRequestOf(body: Record<string, unknown>): PolicyRequest | undefined {
556
+ const { projectRoot, mode } = body
557
+ if (typeof projectRoot !== 'string' || projectRoot === '') return undefined
558
+ if (!isToolMode(mode)) return undefined
559
+ return { projectRoot, mode }
560
+ }
561
+
562
+ /**
563
+ * Shape one `POST conflict` body into a {@link ConflictRequest}.
564
+ *
565
+ * The answer is checked here as well as in the runtime, so a request carrying a
566
+ * choice this build does not know is a `400` and never reaches the store. The
567
+ * name itself is not checked against anything: a project that does not conflict
568
+ * over it yet may still be given an answer, which is what makes the choice
569
+ * survive a declaration that comes and goes.
570
+ * @param body - parsed request body.
571
+ * @returns the request, or `undefined` when a required field is missing.
572
+ */
573
+ function conflictRequestOf(body: Record<string, unknown>): ConflictRequest | undefined {
574
+ const { projectRoot, server, choice } = body
575
+ if (typeof projectRoot !== 'string' || projectRoot === '') return undefined
576
+ if (typeof server !== 'string' || server === '') return undefined
577
+ if (!isConflictChoice(choice)) return undefined
578
+ return { projectRoot, server, choice }
579
+ }