dsh-browser-firefox 0.4.6 → 0.4.8

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/server.ts CHANGED
@@ -23,6 +23,7 @@ import { randomUUID } from 'node:crypto'
23
23
  import type { IncomingMessage } from 'node:http'
24
24
  import type { Duplex } from 'node:stream'
25
25
  import { WebSocket, WebSocketServer } from 'ws'
26
+ import { followedSessionOf } from './session-follow.ts'
26
27
  import {
27
28
  HELLO_TIMEOUT_MS,
28
29
  PING_INTERVAL_MS,
@@ -93,10 +94,20 @@ function delay(ms: number): Promise<void> {
93
94
  /**
94
95
  * Race one promise against an abort signal. Resolves `undefined` when the
95
96
  * signal wins; the loser's handlers are always attached, so a late rejection
96
- * cannot surface as an unhandled rejection.
97
+ * cannot surface as an unhandled rejection — the host loader escalates those
98
+ * to a fatal load failure.
99
+ *
100
+ * Exported for tests.
97
101
  */
98
- function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
99
- if (signal.aborted) return Promise.resolve(undefined)
102
+ export function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
103
+ if (signal.aborted) {
104
+ // `promise` already exists: the caller evaluated it before entering this
105
+ // function, and an in-flight gateway stream rejects it with
106
+ // `gateway/cancelled` once the abort lands. Nobody else can observe it, so
107
+ // absorb the rejection instead of leaking an unhandled one.
108
+ promise.catch(() => undefined)
109
+ return Promise.resolve(undefined)
110
+ }
100
111
  return new Promise<T | undefined>((resolve, reject) => {
101
112
  const onAbort = (): void => { resolve(undefined) }
102
113
  signal.addEventListener('abort', onAbort, { once: true })
@@ -161,6 +172,18 @@ export interface BridgeServerDeps {
161
172
  * rpc result value `{accepted: true} | {accepted: false, reason}`.
162
173
  */
163
174
  answerQuestion: (args: Record<string, unknown>) => unknown
175
+ /**
176
+ * Plugin-local endpoint `bridge/approvalDecision`: settle one pending host
177
+ * approval the bridge pushed to this extension. Answered as the rpc result
178
+ * value `{accepted: true} | {accepted: false, reason}`.
179
+ */
180
+ answerApproval: (args: Record<string, unknown>) => unknown
181
+ /**
182
+ * A `session/follow` stream opened (`open: true`) or ended (`open: false`)
183
+ * for a session: the sidebar is displaying that session while the stream
184
+ * lives, so interaction ownership can follow the visible conversation.
185
+ */
186
+ onFollowChanged?: (sessionId: string, open: boolean) => void
164
187
  /** The active connection was replaced or closed (settle pushed questions). */
165
188
  onConnectionLost?: () => void
166
189
  /**
@@ -371,6 +394,11 @@ export class BridgeServer {
371
394
  return this.current?.clientCaps.questions === true
372
395
  }
373
396
 
397
+ /** @returns whether the connected extension advertised approval-card support. */
398
+ clientSupportsApprovals(): boolean {
399
+ return this.current?.clientCaps.approvals === true
400
+ }
401
+
374
402
  /**
375
403
  * Push one unsolicited server frame (question.requested/question.resolved)
376
404
  * to the connected extension. No-op when no extension is connected or the
@@ -546,6 +574,10 @@ export class BridgeServer {
546
574
  sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: this.deps.answerQuestion(frame.args) })
547
575
  return
548
576
  }
577
+ if (frame.method === 'bridge/approvalDecision') {
578
+ sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: this.deps.answerApproval(frame.args) })
579
+ return
580
+ }
549
581
  try {
550
582
  const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal)
551
583
  if (result.ok) {
@@ -572,6 +604,10 @@ export class BridgeServer {
572
604
  const ws = conn.ws
573
605
  const abort = new AbortController()
574
606
  conn.abort.signal.addEventListener('abort', () => { abort.abort() }, { once: true })
607
+ // A session/follow stream means the sidebar is displaying this session:
608
+ // report the lifetime so interaction ownership can follow the visible
609
+ // conversation (released in the pump's finally below).
610
+ const followedSessionId = frame.method === 'session/follow' ? followedSessionOf(frame.args) : undefined
575
611
  let pump!: Promise<void>
576
612
  pump = (async () => {
577
613
  let iterator: AsyncIterator<unknown> | undefined
@@ -579,6 +615,12 @@ export class BridgeServer {
579
615
  const iterable = await this.deps.openStream(frame.method, frame.args, abort.signal)
580
616
  iterator = iterable[Symbol.asyncIterator]()
581
617
  for (;;) {
618
+ // Never start another pull once the stream is cancelled: the gateway
619
+ // rejects an in-flight next() with `gateway/cancelled`, and a pull
620
+ // started after the abort would have no observer left to handle it
621
+ // (raceAbort stays as the safety net for the narrower race where the
622
+ // promise already exists).
623
+ if (abort.signal.aborted) break
582
624
  // Race every next() against abort: an idle follow stream can sit in
583
625
  // next() for hours, and abort-as-advice alone would leave the pump
584
626
  // (and close()) hanging until the gateway feels like answering.
@@ -590,7 +632,10 @@ export class BridgeServer {
590
632
  }
591
633
  } catch (error: unknown) {
592
634
  if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
593
- sendFrame(ws, { t: 'stream.error', id: frame.id, message: String(error) })
635
+ // Reporting must never throw: the socket can die between the
636
+ // readiness check and the write, and a throw here would escape the
637
+ // pump as an unhandled rejection.
638
+ try { sendFrame(ws, { t: 'stream.error', id: frame.id, message: String(error) }) } catch { /* socket died mid-report */ }
594
639
  }
595
640
  } finally {
596
641
  // Withdraw the subscription explicitly: for-await's implicit return()
@@ -603,9 +648,19 @@ export class BridgeServer {
603
648
  if (current !== null && current.streams.get(frame.id)?.pump === pump) {
604
649
  current.streams.delete(frame.id)
605
650
  }
651
+ if (followedSessionId !== undefined) {
652
+ try { this.deps.onFollowChanged?.(followedSessionId, false) } catch { /* ownership bookkeeping is best-effort */ }
653
+ }
606
654
  }
607
655
  })()
608
656
  conn.streams.set(frame.id, { abort, pump })
657
+ // Last-resort guard: the pump reports its own failures through
658
+ // `stream.error`, but a rejection escaping it would reach the host loader
659
+ // as an unhandled rejection and abort the whole plugin load.
660
+ void pump.catch(() => { /* already reported above */ })
661
+ if (followedSessionId !== undefined) {
662
+ try { this.deps.onFollowChanged?.(followedSessionId, true) } catch { /* ownership bookkeeping is best-effort */ }
663
+ }
609
664
  }
610
665
 
611
666
  /**
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `session/follow` 的参数形状:宿主描述符要求
3
+ * `{request: {address: SessionAddress}}`,其中 address 是
4
+ * `{kind:'session', sessionId}` 或
5
+ * `{kind:'subagent', parentSessionId, childSessionId, mode}`。
6
+ *
7
+ * 扩展用 {@link sessionFollowArgs} 构造订阅参数,插件用
8
+ * {@link followedSessionOf} 从原生 args 里取回「正在展示哪个会话」。两者
9
+ * 同处一个模块,是为了让形状只有**一个**真实来源:0.4.7 曾因插件侧测试用
10
+ * 臆造形状(`request.sessionId`)而没发现 follow 归属在生产环境从未生效。
11
+ *
12
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-follow
13
+ */
14
+
15
+ /** 普通会话的 follow 地址。 */
16
+ export interface SessionFollowAddress {
17
+ kind: 'session'
18
+ sessionId: string
19
+ }
20
+
21
+ /** 直接 subagent 子会话的 follow 地址(宿主 SessionAddress 的另一形态)。 */
22
+ export interface SubagentFollowAddress {
23
+ kind: 'subagent'
24
+ parentSessionId: string
25
+ childSessionId: string
26
+ mode: 'one-shot' | 'continuable' | 'unknown'
27
+ }
28
+
29
+ /** 一次性订阅参数(`stream.open` 的 args)。 */
30
+ export interface SessionFollowArgs {
31
+ request: {
32
+ address: SessionFollowAddress | SubagentFollowAddress
33
+ }
34
+ }
35
+
36
+ /** 订阅一个普通会话(面板当前会话始终用这一形态)。 */
37
+ export function sessionFollowArgs(sessionId: string): SessionFollowArgs {
38
+ return { request: { address: { kind: 'session', sessionId } } }
39
+ }
40
+
41
+ /** 订阅一个 direct subagent 子会话(预留:目前面板不展示子会话)。 */
42
+ export function subagentFollowArgs(
43
+ parentSessionId: string,
44
+ childSessionId: string,
45
+ mode: SubagentFollowAddress['mode'] = 'unknown',
46
+ ): SessionFollowArgs {
47
+ return { request: { address: { kind: 'subagent', parentSessionId, childSessionId, mode } } }
48
+ }
49
+
50
+ /**
51
+ * Session id displayed by a `session/follow` stream, read from the host's
52
+ * `SessionFollowRequest.address`. A subagent address carries the child session
53
+ * on `childSessionId`; ownership then walks up to the parent conversation, so
54
+ * either form routes the card correctly.
55
+ *
56
+ * @param args - native args of the `stream.open` frame.
57
+ * @returns the followed session id, or undefined when absent/malformed.
58
+ */
59
+ export function followedSessionOf(args: Record<string, unknown>): string | undefined {
60
+ const request = args.request
61
+ if (typeof request !== 'object' || request === null || Array.isArray(request)) return undefined
62
+ const address = (request as Record<string, unknown>).address
63
+ if (typeof address !== 'object' || address === null || Array.isArray(address)) return undefined
64
+ const fields = address as Record<string, unknown>
65
+ if (fields.kind === 'session') {
66
+ return nonEmptyString(fields.sessionId)
67
+ }
68
+ if (fields.kind === 'subagent') {
69
+ return nonEmptyString(fields.childSessionId)
70
+ }
71
+ return undefined
72
+ }
73
+
74
+ function nonEmptyString(value: unknown): string | undefined {
75
+ return typeof value === 'string' && value.length > 0 ? value : undefined
76
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Bookkeeping shared by the host waterfalls the bridge claims
3
+ * (`user-questions/request`, `approval/request`).
4
+ *
5
+ * Both bridges need exactly the same lifecycle: one pending entry per
6
+ * generated id, a **single settlement** guarantee against concurrent paths
7
+ * (extension answer vs host abort vs connection loss vs plugin unload), an
8
+ * abort listener that is detached once settled, and the id+session match the
9
+ * uplink must pass before it may touch an entry. Only the outcome vocabulary
10
+ * and the push/settle policy differ, and those stay in the domain modules.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ interface Entry<TOutcome, TPayload> {
16
+ readonly sessionId: string
17
+ /** Domain state the uplink needs (e.g. the question ids one card asked about). */
18
+ readonly payload: TPayload
19
+ /** Domain policy for one settlement; invoked at most once per id. */
20
+ readonly complete: (outcome: TOutcome) => void
21
+ readonly signal: AbortSignal | undefined
22
+ readonly onAbort: (() => void) | undefined
23
+ settled: boolean
24
+ }
25
+
26
+ /** Registry of pending waterfall requests, keyed by the id sent to the extension. */
27
+ export class PendingWaterfalls<TOutcome, TPayload = undefined> {
28
+ private readonly entries = new Map<string, Entry<TOutcome, TPayload>>()
29
+
30
+ /**
31
+ * Track one request pushed to the extension.
32
+ *
33
+ * @param input - id, asking session, host cancellation signal, the domain's
34
+ * settlement policy, and the abort handler (typically: tell the extension
35
+ * the card is gone, then settle).
36
+ */
37
+ register(input: {
38
+ id: string
39
+ sessionId: string
40
+ signal: AbortSignal | undefined
41
+ payload: TPayload
42
+ complete: (outcome: TOutcome) => void
43
+ onAbort: () => void
44
+ }): void {
45
+ const entry: Entry<TOutcome, TPayload> = {
46
+ sessionId: input.sessionId,
47
+ payload: input.payload,
48
+ complete: input.complete,
49
+ signal: input.signal,
50
+ onAbort: input.onAbort,
51
+ settled: false,
52
+ }
53
+ if (input.signal !== undefined) input.signal.addEventListener('abort', input.onAbort, { once: true })
54
+ this.entries.set(input.id, entry)
55
+ }
56
+
57
+ /**
58
+ * Whether an unsettled entry exists for exactly this id and session. The
59
+ * uplink must not be able to settle another session's card.
60
+ */
61
+ matches(id: string, sessionId: string): boolean {
62
+ const entry = this.entries.get(id)
63
+ return entry !== undefined && !entry.settled && entry.sessionId === sessionId
64
+ }
65
+
66
+ /** Domain payload registered with one unsettled entry (undefined once settled). */
67
+ payloadOf(id: string): TPayload | undefined {
68
+ return this.entries.get(id)?.payload
69
+ }
70
+
71
+ /**
72
+ * Settle one request. Later settlements for the same id are no-ops, and the
73
+ * entry is dropped together with its abort listener.
74
+ *
75
+ * @returns true when this call performed the settlement.
76
+ */
77
+ settle(id: string, outcome: TOutcome): boolean {
78
+ const entry = this.entries.get(id)
79
+ if (entry === undefined || entry.settled) return false
80
+ entry.settled = true
81
+ this.entries.delete(id)
82
+ if (entry.onAbort !== undefined) entry.signal?.removeEventListener('abort', entry.onAbort)
83
+ entry.complete(outcome)
84
+ return true
85
+ }
86
+
87
+ /** Every unsettled id, for the connection-loss and unload sweeps. */
88
+ ids(): string[] {
89
+ return [...this.entries.keys()]
90
+ }
91
+ }