dsh-marker 0.1.2 → 0.1.4

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/client.js CHANGED
@@ -25,8 +25,19 @@ window.__ModuleLoader__.load({
25
25
  /** Sticky matcher for one canonical mention; shared shape with the Host parser. */
26
26
  const WIRE = /@\[((?:\\.|[^\\\]\n])*)\]\(dsh-anno:([A-Za-z0-9_-]+)\)/uy
27
27
 
28
- /** How often the page checks for mentions waiting on an open Session. */
29
- const QUEUE_POLL_MS = 4_000
28
+ /** The Host's push channel: one stream per page, however many Sessions it shows. */
29
+ const EVENTS_PATH = '/ext/anno/events'
30
+
31
+ /**
32
+ * The repair interval, not the delivery path.
33
+ *
34
+ * A nudge from {@link EVENTS_PATH} is what makes a queued mention arrive
35
+ * immediately; this poll only exists for the case a nudge cannot cover — a
36
+ * stream that was down (or absent) while something was queued. It is slow on
37
+ * purpose: it is a safety net, so a missed event costs a wait instead of a
38
+ * lost delivery.
39
+ */
40
+ const REPAIR_POLL_MS = 30_000
30
41
 
31
42
  /** Queue, focus, and annotation reads the Host serves to the page it serves. */
32
43
  const QUEUE_PATH = '/ext/anno/queue'
@@ -177,6 +188,89 @@ window.__ModuleLoader__.load({
177
188
  mark('data-dsh-anno-trace', reason)
178
189
  }
179
190
 
191
+ /**
192
+ * One event stream per page, shared by every mounted Session dock.
193
+ *
194
+ * The stream carries an event *name*, never the queue's contents: a `mention`
195
+ * frame says "this Session has something waiting", and the reader still
196
+ * fetches `GET /ext/anno/queue?session=…` and acknowledges it. That keeps one
197
+ * delivery path — the pushed frame only decides *when* it runs — so a lost
198
+ * frame degrades to the repair poll instead of a lost mention.
199
+ *
200
+ * @type {Set<(event: any) => void>}
201
+ */
202
+ const STREAM_LISTENERS = new Set()
203
+ /** @type {any} */
204
+ let stream = null
205
+
206
+ /** @param {any} payload */
207
+ function emitStreamEvent(payload) {
208
+ for (const listener of [...STREAM_LISTENERS]) {
209
+ try {
210
+ listener(payload)
211
+ } catch {
212
+ // One listener's failure must not silence the others.
213
+ }
214
+ }
215
+ }
216
+
217
+ /** Open the stream if it is not open yet. */
218
+ function openStream() {
219
+ if (stream !== null) return
220
+ const Source = window.EventSource
221
+ if (typeof Source !== 'function') {
222
+ trace('no-eventsource')
223
+ return
224
+ }
225
+ const opened = new Source(EVENTS_PATH)
226
+ stream = opened
227
+ opened.onmessage = (message) => {
228
+ let payload
229
+ try {
230
+ payload = JSON.parse(message.data)
231
+ } catch {
232
+ return
233
+ }
234
+ if (payload === null || typeof payload !== 'object') return
235
+ emitStreamEvent(payload)
236
+ }
237
+ // A reconnection is a first-class moment, not a retry: it is exactly when
238
+ // events may have been missed, so listeners catch up on `open`.
239
+ opened.onopen = () => {
240
+ trace('events-open')
241
+ emitStreamEvent({ t: 'open' })
242
+ }
243
+ // `EventSource` retries on its own; recording it is all this needs to do.
244
+ opened.onerror = () => {
245
+ trace('events-error')
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Listen for the Host's nudges, opening the stream on first use.
251
+ * @param {(event: any) => void} listener
252
+ * @returns {() => void} unsubscribe
253
+ */
254
+ function listenForEvents(listener) {
255
+ STREAM_LISTENERS.add(listener)
256
+ openStream()
257
+ return () => {
258
+ STREAM_LISTENERS.delete(listener)
259
+ }
260
+ }
261
+
262
+ /** Close the page's stream (plugin disposal). */
263
+ function closeStream() {
264
+ STREAM_LISTENERS.clear()
265
+ const opened = stream
266
+ stream = null
267
+ try {
268
+ opened?.close()
269
+ } catch {
270
+ // A stream that already failed has nothing left to close.
271
+ }
272
+ }
273
+
180
274
  /**
181
275
  * Find the nearest annotation mention at or after `from`. Mentions carry
182
276
  * their own label, so no Host read is needed to draw one.
@@ -508,6 +602,10 @@ window.__ModuleLoader__.load({
508
602
  * counts, and nothing is sent. A Session the user is not looking at is never
509
603
  * touched, and its entries simply wait in the queue.
510
604
  *
605
+ * Delivery is event-driven: the Host's stream says *when* to read, and the
606
+ * queue says *what*. A slow repair poll plus the mount and visibility pulls
607
+ * cover the case where no event arrives at all.
608
+ *
511
609
  * Being mounted is also what the Host needs to know, so the same effect
512
610
  * reports the focus.
513
611
  */
@@ -552,9 +650,20 @@ window.__ModuleLoader__.load({
552
650
  if (document.visibilityState === 'hidden') return
553
651
  void reportFocus(sessionId).catch((error) => trace(`focus-${String(error).slice(0, 40)}`))
554
652
  }
653
+ const onStreamEvent = (event) => {
654
+ if (event?.t === 'open') {
655
+ // A (re)connected stream is the one moment events may have been
656
+ // missed, so it re-announces the focus and catches up.
657
+ announce()
658
+ void pull()
659
+ return
660
+ }
661
+ if (event?.t === 'mention' && event.sessionId === sessionId) void pull()
662
+ }
663
+ const stopListening = listenForEvents(onStreamEvent)
555
664
  announce()
556
665
  void pull()
557
- const timer = setInterval(() => void pull(), QUEUE_POLL_MS)
666
+ const timer = setInterval(() => void pull(), REPAIR_POLL_MS)
558
667
  // A hidden tab has its timers frozen, so the moment the user comes back
559
668
  // is also the moment to look.
560
669
  const onVisible = () => {
@@ -566,6 +675,7 @@ window.__ModuleLoader__.load({
566
675
  window.addEventListener('focus', onVisible)
567
676
  return () => {
568
677
  cancelled = true
678
+ stopListening()
569
679
  clearInterval(timer)
570
680
  document.removeEventListener('visibilitychange', onVisible)
571
681
  window.removeEventListener('focus', onVisible)
@@ -575,11 +685,66 @@ window.__ModuleLoader__.load({
575
685
  return null
576
686
  }
577
687
 
688
+ /**
689
+ * Follow the Host's "a session was created" nudge by switching the page to
690
+ * that session, when the build exposes a way to do it.
691
+ *
692
+ * The overlay's "new session" target creates a conversation the user is not
693
+ * looking at; without this the mention chip waits in the queue until they
694
+ * find it in the sidebar. Navigation is best-effort: the primary path is
695
+ * the `uiWorkspace` service (its `openSession` is what the workspace
696
+ * browser itself calls); `uiConversation` fallbacks are duck-typed because
697
+ * their selection APIs are not part of any stable contract, and a build
698
+ * with none keeps the queued delivery — the chip lands the moment the user
699
+ * opens the session by hand.
700
+ * @param {string} sessionId
701
+ */
702
+ function navigateToSession(sessionId) {
703
+ if (typeof sessionId === 'string' && sessionId !== '') {
704
+ try {
705
+ const navigation = window.__DSH_ANNO_CONTEXT__?.get?.('uiWorkspace')
706
+ if (navigation && typeof navigation.openSession === 'function') {
707
+ navigation.openSession(sessionId)
708
+ trace('session-nav')
709
+ return
710
+ }
711
+ } catch {
712
+ // A closed-over service that threw is the same as none.
713
+ }
714
+ }
715
+ try {
716
+ const conversation = window.__DSH_ANNO_CONTEXT__?.uiConversation
717
+ const opener =
718
+ conversation && (conversation.openSession ?? conversation.selectSession ?? conversation.navigateToSession)
719
+ if (typeof opener === 'function') {
720
+ opener(sessionId)
721
+ trace('session-nav')
722
+ return
723
+ }
724
+ } catch {
725
+ // A closed-over service that threw is the same as none.
726
+ }
727
+ trace('session-nav-unavailable')
728
+ }
729
+
730
+ /**
731
+ * The page-level listener for created sessions. It is deliberately outside
732
+ * {@link QueuedMentions}: that component only exists for a session the page
733
+ * is already showing, and this event is about one it is not.
734
+ * @returns {() => void} unsubscribe
735
+ */
736
+ function followCreatedSessions() {
737
+ return listenForEvents((event) => {
738
+ if (event?.t === 'session') navigateToSession(String(event.sessionId ?? ''))
739
+ })
740
+ }
741
+
578
742
  return {
579
743
  inject: ['slots', 'uiConversation'],
580
744
  /** The draft composition this plugin owns; exported for its unit test. */
581
745
  composeDraft,
582
746
  apply(ctx) {
747
+ window.__DSH_ANNO_CONTEXT__ = ctx
583
748
  mark('data-dsh-anno-hovercard', HoverCard === undefined ? 'unavailable' : 'primitives')
584
749
  // One stylesheet for the whole page, removed when the plugin disposes.
585
750
  ctx.effect(() => {
@@ -593,6 +758,17 @@ window.__ModuleLoader__.load({
593
758
  }, 'dsh-marker: chip styles')
594
759
 
595
760
  ctx.effect(() => ctx.uiConversation.userText.register(annoRule), 'dsh-marker: user-text rule')
761
+ // The page's stream outlives any one Session: it is opened on the first
762
+ // mounted dock and closed here, with the plugin.
763
+ ctx.effect(
764
+ () => () => {
765
+ closeStream()
766
+ },
767
+ 'dsh-marker: event stream',
768
+ )
769
+ // "A session was created for something you marked" — switch to it when
770
+ // the build allows, so the chip is in the composer the user lands on.
771
+ ctx.effect(() => followCreatedSessions(), 'dsh-marker: created-session follow')
596
772
  ctx.slots.inject('conversation.user.text.node', function* () {
597
773
  yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'anno', priority: 100 }, AnnoReference)
598
774
  })
package/docs/DETAIL.md CHANGED
@@ -14,9 +14,10 @@
14
14
  - `http://127.0.0.1:3080/ext/anno/health` —— 健康检查与协议版本;带 `instanceId`(本进程的十六进制短 id)。
15
15
  - `http://127.0.0.1:30810-30812/ext/anno/locate` —— 发现端口:只在宿主端口不是 `3080` 时监听(Desktop、`--port 0`、自定义端口),只答一个 `GET`,内容是当前 `origin`、`wsUrl`、`instanceId` 和时间戳;不含任何批注、会话或令牌。`POST`/`HEAD` 返回 `405`,`Host` 不是 `127.0.0.1`/`localhost` 返回 `403`,不发 CORS 头。
16
16
  - `GET /ext/anno/sessions?token=…` —— 目标选择器的会话目录,`defaultSessionId` 跟随网页里正在看的会话。
17
- - 下面四条只服务宿主自己的页面(要求 `sec-fetch-site: same-origin`),扩展永远看不到它们:
17
+ - 下面五条只服务宿主自己的页面(要求 `sec-fetch-site: same-origin`),扩展永远看不到它们:
18
18
  - `POST /ext/anno/focus` —— 网页汇报它当前显示的会话。
19
19
  - `GET /ext/anno/queue?session=…` / `POST /ext/anno/queue/ack` —— 待插入编辑框的引用。
20
+ - `GET /ext/anno/events` —— 服务端事件流(SSE):告诉页面「这个会话有新东西了」,只带会话 id,不带正文;页面据此立刻去读队列,读不到也不会丢。
20
21
  - `GET /ext/anno/item?id=…` —— 一条批注的展示投影(chip hover 卡片用)。
21
22
  - `GET /ext/anno/image?id=…` —— 那条批注的裁剪截图 PNG。
22
23
 
package/icon.svg CHANGED
@@ -1,8 +1,5 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32" role="img" aria-label="dsh-marker">
2
- <rect width="32" height="32" rx="8" fill="#1f6feb"/>
3
- <rect x="8" y="6" width="16" height="20" rx="2.5" fill="#ffffff" fill-opacity="0.94"/>
4
- <rect x="11" y="11" width="10" height="3" rx="1.5" fill="#1f6feb" fill-opacity="0.35"/>
5
- <rect x="11" y="16.5" width="7" height="3" rx="1.5" fill="#1f6feb" fill-opacity="0.2"/>
6
- <circle cx="21.5" cy="22.5" r="4.5" fill="#f0883e"/>
7
- <circle cx="21.5" cy="22.5" r="1.8" fill="#ffffff"/>
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="32" height="32" role="img" aria-label="dsh-marker">
2
+ <rect x="0" y="0" width="128" height="128" rx="30" fill="#1f6feb"/>
3
+ <polygon points="31.8,26.3 76.45,44.2 82.25,46.5 76.3,48.4 60.7,53.35 54.75,55.25 52.75,61.2 48,75.55 46,81.5 43.95,75.6 28.05,29.9 26,24" fill="#ffffff"/>
4
+ <circle cx="89" cy="93" r="18" fill="#f0883e"/>
8
5
  </svg>
package/index.js CHANGED
@@ -18,9 +18,11 @@ import { ensureToken, annotationsDir } from './src/paths.js'
18
18
  import { AnnotationStore } from './src/store.js'
19
19
  import { createBridge, tokenMatches } from './src/bridge.js'
20
20
  import { createDiscovery, isIpv4Loopback, shouldLocate } from './src/discovery.js'
21
+ import { createEventStream, registerEventsRoute } from './src/events.js'
21
22
  import { createFocusStore, focusedSession, registerFocusRoute } from './src/focus.js'
22
23
  import { startLocator } from './src/locator.js'
23
24
  import { createAnnotationMentions } from './src/mentions.js'
25
+ import { createProvisioner, registerProvisionRoutes } from './src/provision.js'
24
26
  import { registerPresentationRoutes } from './src/presentation.js'
25
27
  import { createMentionQueue, registerQueueRoutes } from './src/queue.js'
26
28
  import { createSessionCatalog, registerSessionsRoute } from './src/sessions.js'
@@ -60,6 +62,28 @@ export async function apply(ctx, config = {}) {
60
62
  const focus = createFocusStore({ dir: annotationsDir(), logger })
61
63
  await focus.load()
62
64
 
65
+ // The page's push channel. Created before the bridge because the delivery
66
+ // that follows an accepted create is what it publishes.
67
+ const events = createEventStream({ logger })
68
+
69
+ // The overlay's target catalog. Created here rather than at its route so the
70
+ // warm-up below can wait for the Session services it reads.
71
+ const catalog = createSessionCatalog({ get: (service) => ctx.get(service), logger })
72
+
73
+ // The picker's other arm: create a Session (in the default, an existing, or a
74
+ // brand-new workspace) so an annotation can start a conversation. Created
75
+ // before its route so the sessions catalog can share the workspace read.
76
+ const provisioner = createProvisioner({
77
+ get: (service) => ctx.get(service),
78
+ logger,
79
+ catalog,
80
+ onCreated: ({ sessionId }) => {
81
+ // Same knock as a queued mention: the page that should show this Session
82
+ // learns to look for it now, and a missed event costs latency, not state.
83
+ events.publish({ t: 'session', sessionId })
84
+ },
85
+ })
86
+
63
87
  const bridge = createBridge({
64
88
  store,
65
89
  token,
@@ -89,6 +113,10 @@ export async function apply(ctx, config = {}) {
89
113
  const mention = formatAnnoMention({ id: patched.id, label })
90
114
  if (mention === '') return
91
115
  await queue.enqueue({ id: patched.id, sessionId, mention, label })
116
+ // The queue is the truth and this is only the knock: a page whose Session
117
+ // this is reads the queue immediately instead of waiting for its next
118
+ // poll, and a missed nudge costs latency rather than a delivery.
119
+ events.publish({ t: 'mention', sessionId })
92
120
  logger.info?.(`annotations: ${patched.id} queued for ${sessionId}`)
93
121
  },
94
122
  saveImage: async ({ data, mediaType, name }) => {
@@ -125,14 +153,26 @@ export async function apply(ctx, config = {}) {
125
153
  webCtx.effect(
126
154
  () =>
127
155
  registerSessionsRoute(webCtx.webServer, {
128
- catalog: createSessionCatalog({ get: (service) => ctx.get(service), logger }),
156
+ catalog,
129
157
  token,
130
158
  matchesToken: tokenMatches,
159
+ logger,
131
160
  preferred: () => focusedSession(focus),
161
+ workspaces: () => provisioner.listWorkspaces(),
132
162
  }),
133
163
  'dsh-marker: /ext/anno/sessions catalog',
134
164
  )
165
+ webCtx.effect(
166
+ () =>
167
+ registerProvisionRoutes(webCtx.webServer, {
168
+ provisioner,
169
+ token,
170
+ matchesToken: tokenMatches,
171
+ }),
172
+ 'dsh-marker: /ext/anno/session-create',
173
+ )
135
174
  webCtx.effect(() => registerQueueRoutes(webCtx.webServer, { queue }), 'dsh-marker: /ext/anno/queue hand-off')
175
+ webCtx.effect(() => registerEventsRoute(webCtx.webServer, { events }), 'dsh-marker: /ext/anno/events push')
136
176
  webCtx.effect(() => registerFocusRoute(webCtx.webServer, { store: focus }), 'dsh-marker: /ext/anno/focus report')
137
177
  webCtx.effect(
138
178
  () =>
@@ -194,9 +234,21 @@ export async function apply(ctx, config = {}) {
194
234
  }
195
235
  })
196
236
 
237
+ // Pay the picker's first title fold before anyone is looking. The child
238
+ // scope waits for the controller rather than failing once at boot, and a
239
+ // warm-up failure only means a slow first open.
240
+ ctx.inject(['sessionController'], (warmCtx) => {
241
+ warmCtx.effect(() => {
242
+ void catalog.warm()
243
+ }, 'dsh-marker: catalog warm-up')
244
+ })
245
+
197
246
  ctx.effect(
198
247
  () => () => {
199
248
  bridge.cancelAllPicks()
249
+ // A page still holding an event stream would wait on a Host that is gone;
250
+ // closing it makes `EventSource` reconnect to the next one instead.
251
+ events.close()
200
252
  void store.flush()
201
253
  },
202
254
  'dsh-marker: shutdown',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-marker",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Visual annotation bridge: mark text, elements, or regions in Firefox/Zen and hand them to DeepSeek Harness as first-class context",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/events.js ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * The Web Client's push channel.
3
+ *
4
+ * Everything the browser half needs is a *pull*: the extension owns a socket,
5
+ * the page reads HTTP. That is right for data — the queue is authoritative and
6
+ * a read can always repair a missed event — but it left the one human-visible
7
+ * step, "this Session just received something", waiting on a poll.
8
+ *
9
+ * So the Host says *when* to read. Each frame is a nudge naming the Session it
10
+ * concerns (`{ t: 'mention', sessionId }`), never the payload: the page still
11
+ * reads `GET /ext/anno/queue?session=…` and still acknowledges it. A dropped
12
+ * stream therefore costs latency, not a delivery.
13
+ *
14
+ * Server-sent events rather than a websocket because the page needs one
15
+ * direction, one stream, and no handshake: `EventSource` reconnects on its own,
16
+ * the Host webserver already turns compression off for `text/event-stream`, and
17
+ * no new protocol surface has to be owned here.
18
+ *
19
+ * @module dsh-marker/events
20
+ */
21
+
22
+ import { EVENTS_PATH } from './protocol.js'
23
+
24
+ /** How long a quiet stream is kept visibly alive; a dead socket is dropped. */
25
+ const HEARTBEAT_MS = 25_000
26
+
27
+ /** One page holds one stream, so this is a runaway guard rather than a limit. */
28
+ const MAX_CLIENTS = 32
29
+
30
+ /** A client this far behind is not reading; keeping it only grows the Host. */
31
+ const MAX_BACKLOG_BYTES = 64 * 1024
32
+
33
+ /**
34
+ * @typedef {object} StreamClient
35
+ * @property {any} response The node response the stream writes to.
36
+ * @property {number} id Stable per connection, for diagnostics.
37
+ */
38
+
39
+ /**
40
+ * @param {object} [options]
41
+ * @param {{ warn?: (...args: any[]) => void, debug?: (...args: any[]) => void }} [options.logger]
42
+ * @param {number} [options.heartbeatMs]
43
+ * @param {number} [options.maxClients]
44
+ */
45
+ export function createEventStream({ logger, heartbeatMs = HEARTBEAT_MS, maxClients = MAX_CLIENTS } = {}) {
46
+ /** @type {Set<StreamClient>} */
47
+ const clients = new Set()
48
+ let heartbeat = null
49
+ let sequence = 0
50
+
51
+ /** @param {StreamClient} client @param {string} chunk */
52
+ function write(client, chunk) {
53
+ const { response } = client
54
+ if (response.writableEnded === true || response.destroyed === true) {
55
+ clients.delete(client)
56
+ return false
57
+ }
58
+ if (response.writableLength > MAX_BACKLOG_BYTES) {
59
+ // A page that stopped reading its own event stream will reconnect when it
60
+ // comes back; buffering for it here is how a Host leaks memory.
61
+ drop(client, 'backlog')
62
+ return false
63
+ }
64
+ try {
65
+ response.write(chunk)
66
+ return true
67
+ } catch (error) {
68
+ logger?.warn?.(`annotations: event stream write failed (${messageOf(error)})`)
69
+ clients.delete(client)
70
+ return false
71
+ }
72
+ }
73
+
74
+ /** @param {StreamClient} client @param {string} reason */
75
+ function drop(client, reason) {
76
+ clients.delete(client)
77
+ logger?.debug?.(`annotations: event client ${client.id} dropped (${reason})`)
78
+ try {
79
+ client.response.end()
80
+ } catch {
81
+ // The socket is already gone in every case worth reaching here.
82
+ }
83
+ }
84
+
85
+ /** Keep a quiet stream visibly alive and prove the peer is still reading. */
86
+ function pulse() {
87
+ for (const client of [...clients]) write(client, ': ping\n\n')
88
+ }
89
+
90
+ function start() {
91
+ if (heartbeat !== null) return
92
+ heartbeat = setInterval(pulse, heartbeatMs)
93
+ heartbeat.unref?.()
94
+ }
95
+
96
+ /**
97
+ * Open one stream. The caller has already checked the method and origin.
98
+ * @param {any} request
99
+ * @param {any} response
100
+ * @returns {() => void} closes just this stream
101
+ */
102
+ function subscribe(request, response) {
103
+ if (clients.size >= maxClients) {
104
+ // Oldest first: a stale page that never closed its stream loses, because
105
+ // the page that is actually being looked at is the one that reconnects.
106
+ const [oldest] = clients
107
+ if (oldest !== undefined) drop(oldest, 'evicted')
108
+ }
109
+ response.writeHead(200, {
110
+ 'content-type': 'text/event-stream; charset=utf-8',
111
+ 'cache-control': 'no-store',
112
+ connection: 'keep-alive',
113
+ // A reverse proxy that buffers would hold every event until the stream
114
+ // ends, which is the whole latency this route exists to remove.
115
+ 'x-accel-buffering': 'no',
116
+ vary: 'sec-fetch-site',
117
+ })
118
+ response.flushHeaders?.()
119
+
120
+ sequence += 1
121
+ const client = { response, id: sequence }
122
+ clients.add(client)
123
+ // The browser's own reconnect delay; a Host restart is the common case.
124
+ write(client, 'retry: 2000\n\n')
125
+ start()
126
+
127
+ const forget = () => {
128
+ clients.delete(client)
129
+ }
130
+ request.on?.('close', forget)
131
+ request.on?.('aborted', forget)
132
+ response.on?.('close', forget)
133
+ return forget
134
+ }
135
+
136
+ /**
137
+ * Tell every open page that one Session has something waiting. A page whose
138
+ * Session this is not ignores it; the payload is a hint, so fan-out is free.
139
+ * @param {{ t: string, sessionId?: string }} event
140
+ */
141
+ function publish(event) {
142
+ if (clients.size === 0) return
143
+ const chunk = `data: ${JSON.stringify(event)}\n\n`
144
+ for (const client of [...clients]) write(client, chunk)
145
+ }
146
+
147
+ /** End every stream and stop the heartbeat (plugin shutdown). */
148
+ function close() {
149
+ if (heartbeat !== null) {
150
+ clearInterval(heartbeat)
151
+ heartbeat = null
152
+ }
153
+ for (const client of [...clients]) drop(client, 'closing')
154
+ }
155
+
156
+ return {
157
+ subscribe,
158
+ publish,
159
+ close,
160
+ stats() {
161
+ return { clients: clients.size }
162
+ },
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Serve the event stream to the page this Host serves.
168
+ *
169
+ * The gate is the browser's own same-origin header, exactly like the queue and
170
+ * focus routes: the GUI is this Host's page, and the extension's bridge token
171
+ * has no business in it (D12). Anything else gets an honest 403.
172
+ *
173
+ * @param {any} webServer
174
+ * @param {object} options
175
+ * @param {ReturnType<typeof createEventStream>} options.events
176
+ * @param {string} [options.path]
177
+ * @returns {() => void} disposer
178
+ */
179
+ export function registerEventsRoute(webServer, { events, path = EVENTS_PATH }) {
180
+ return webServer.register({
181
+ kind: 'exact',
182
+ path,
183
+ auth: 'anonymous',
184
+ handler: (request, response) => {
185
+ if (!sameOrigin(request)) {
186
+ response.writeHead(403, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
187
+ response.end(JSON.stringify({ ok: false, error: 'origin' }))
188
+ return
189
+ }
190
+ if (request.method !== 'GET') {
191
+ response.writeHead(405, {
192
+ 'content-type': 'application/json; charset=utf-8',
193
+ 'cache-control': 'no-store',
194
+ allow: 'GET',
195
+ })
196
+ response.end(JSON.stringify({ ok: false, error: 'method' }))
197
+ return
198
+ }
199
+ events.subscribe(request, response)
200
+ },
201
+ })
202
+ }
203
+
204
+ /**
205
+ * The GUI is served by this Host, so the browser marks its own requests
206
+ * `same-origin`. A request without the header is not the page.
207
+ * @param {any} request
208
+ */
209
+ function sameOrigin(request) {
210
+ return request.headers?.['sec-fetch-site'] === 'same-origin'
211
+ }
212
+
213
+ /** @param {unknown} error */
214
+ function messageOf(error) {
215
+ return error instanceof Error ? error.message : String(error)
216
+ }
package/src/focus.js CHANGED
@@ -22,6 +22,17 @@ import { FOCUS_PATH } from './protocol.js'
22
22
  /** How long a focus report stays believable. */
23
23
  export const FOCUS_TTL_MS = 6 * 60 * 60 * 1_000
24
24
 
25
+ /**
26
+ * The same Session reported again is a keep-alive, not news.
27
+ *
28
+ * The Client reports on mount and on every window focus, which is a file write
29
+ * per focus change for a value that usually did not change. Re-reporting the
30
+ * same Session therefore only rewrites the record once per window of this
31
+ * length — often enough to keep {@link FOCUS_TTL_MS} alive for a long-lived
32
+ * page, rare enough that alt-tabbing is not I/O.
33
+ */
34
+ const FOCUS_REFRESH_MS = 10 * 60 * 1_000
35
+
25
36
  /** A focus report carries one id; anything larger is not our Client. */
26
37
  const MAX_BODY_BYTES = 1_024
27
38
 
@@ -46,11 +57,14 @@ export function createFocusStore({ dir, logger, file = 'focus.json' }) {
46
57
  let entry = null
47
58
  /** @type {Promise<void> | null} */
48
59
  let writing = null
60
+ /** When the currently stored record was last written. */
61
+ let persistedAt = 0
49
62
 
50
63
  async function load() {
51
64
  try {
52
65
  const parsed = JSON.parse(await readFile(path, 'utf8'))
53
66
  entry = isEntry(parsed) ? parsed : null
67
+ persistedAt = entry?.at ?? 0
54
68
  } catch (error) {
55
69
  if (error?.code !== 'ENOENT') logger?.warn?.(`annotations: focus report unreadable (${messageOf(error)})`)
56
70
  entry = null
@@ -65,21 +79,35 @@ export function createFocusStore({ dir, logger, file = 'focus.json' }) {
65
79
 
66
80
  /**
67
81
  * Record that the Client is showing one Session.
82
+ *
83
+ * The in-memory answer changes immediately; the durable copy is written when
84
+ * the report is news, and otherwise only often enough to keep the record
85
+ * fresh. Nothing here is a decision — {@link focusedSession} already treats an
86
+ * old report as no report.
87
+ *
68
88
  * @param {string} sessionId
69
89
  * @returns {Promise<FocusEntry>}
70
90
  */
71
91
  async function set(sessionId) {
72
92
  const next = { sessionId: String(sessionId), at: Date.now() }
93
+ const changed = entry === null || entry.sessionId !== next.sessionId
73
94
  entry = next
95
+ if (!changed && next.at - persistedAt < FOCUS_REFRESH_MS) return next
96
+ await persist(next)
97
+ return next
98
+ }
99
+
100
+ /** @param {FocusEntry} next */
101
+ async function persist(next) {
74
102
  // Serialized the same way the queue is: two overlapping renames would
75
103
  // interleave and leave one report half-written.
76
104
  writing = (writing ?? Promise.resolve()).then(async () => {
77
105
  const temporary = `${path}.tmp`
78
106
  await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
79
107
  await rename(temporary, path)
108
+ persistedAt = next.at
80
109
  })
81
110
  await writing
82
- return next
83
111
  }
84
112
 
85
113
  return { load, get, set, flush: () => writing ?? Promise.resolve(), path }