dsh-marker 0.1.1 → 0.1.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.
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,53 @@ 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 conversation
695
+ * service is duck-typed because its selection API is not part of any
696
+ * stable contract, and a build without one keeps the queued delivery — the
697
+ * chip lands the moment the user opens the session by hand.
698
+ * @param {string} sessionId
699
+ */
700
+ function navigateToSession(sessionId) {
701
+ if (typeof sessionId !== 'string' || sessionId === '') return
702
+ try {
703
+ const conversation = window.__DSH_ANNO_CONTEXT__?.uiConversation
704
+ const opener =
705
+ conversation && (conversation.openSession ?? conversation.selectSession ?? conversation.navigateToSession)
706
+ if (typeof opener === 'function') {
707
+ opener(sessionId)
708
+ trace('session-nav')
709
+ return
710
+ }
711
+ } catch {
712
+ // A closed-over service that threw is the same as none.
713
+ }
714
+ trace('session-nav-unavailable')
715
+ }
716
+
717
+ /**
718
+ * The page-level listener for created sessions. It is deliberately outside
719
+ * {@link QueuedMentions}: that component only exists for a session the page
720
+ * is already showing, and this event is about one it is not.
721
+ * @returns {() => void} unsubscribe
722
+ */
723
+ function followCreatedSessions() {
724
+ return listenForEvents((event) => {
725
+ if (event?.t === 'session') navigateToSession(String(event.sessionId ?? ''))
726
+ })
727
+ }
728
+
578
729
  return {
579
730
  inject: ['slots', 'uiConversation'],
580
731
  /** The draft composition this plugin owns; exported for its unit test. */
581
732
  composeDraft,
582
733
  apply(ctx) {
734
+ window.__DSH_ANNO_CONTEXT__ = ctx
583
735
  mark('data-dsh-anno-hovercard', HoverCard === undefined ? 'unavailable' : 'primitives')
584
736
  // One stylesheet for the whole page, removed when the plugin disposes.
585
737
  ctx.effect(() => {
@@ -593,6 +745,17 @@ window.__ModuleLoader__.load({
593
745
  }, 'dsh-marker: chip styles')
594
746
 
595
747
  ctx.effect(() => ctx.uiConversation.userText.register(annoRule), 'dsh-marker: user-text rule')
748
+ // The page's stream outlives any one Session: it is opened on the first
749
+ // mounted dock and closed here, with the plugin.
750
+ ctx.effect(
751
+ () => () => {
752
+ closeStream()
753
+ },
754
+ 'dsh-marker: event stream',
755
+ )
756
+ // "A session was created for something you marked" — switch to it when
757
+ // the build allows, so the chip is in the composer the user lands on.
758
+ ctx.effect(() => followCreatedSessions(), 'dsh-marker: created-session follow')
596
759
  ctx.slots.inject('conversation.user.text.node', function* () {
597
760
  yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'anno', priority: 100 }, AnnoReference)
598
761
  })
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,27 @@ 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
+ onCreated: ({ sessionId }) => {
80
+ // Same knock as a queued mention: the page that should show this Session
81
+ // learns to look for it now, and a missed event costs latency, not state.
82
+ events.publish({ t: 'session', sessionId })
83
+ },
84
+ })
85
+
63
86
  const bridge = createBridge({
64
87
  store,
65
88
  token,
@@ -89,6 +112,10 @@ export async function apply(ctx, config = {}) {
89
112
  const mention = formatAnnoMention({ id: patched.id, label })
90
113
  if (mention === '') return
91
114
  await queue.enqueue({ id: patched.id, sessionId, mention, label })
115
+ // The queue is the truth and this is only the knock: a page whose Session
116
+ // this is reads the queue immediately instead of waiting for its next
117
+ // poll, and a missed nudge costs latency rather than a delivery.
118
+ events.publish({ t: 'mention', sessionId })
92
119
  logger.info?.(`annotations: ${patched.id} queued for ${sessionId}`)
93
120
  },
94
121
  saveImage: async ({ data, mediaType, name }) => {
@@ -125,14 +152,26 @@ export async function apply(ctx, config = {}) {
125
152
  webCtx.effect(
126
153
  () =>
127
154
  registerSessionsRoute(webCtx.webServer, {
128
- catalog: createSessionCatalog({ get: (service) => ctx.get(service), logger }),
155
+ catalog,
129
156
  token,
130
157
  matchesToken: tokenMatches,
158
+ logger,
131
159
  preferred: () => focusedSession(focus),
160
+ workspaces: () => provisioner.listWorkspaces(),
132
161
  }),
133
162
  'dsh-marker: /ext/anno/sessions catalog',
134
163
  )
164
+ webCtx.effect(
165
+ () =>
166
+ registerProvisionRoutes(webCtx.webServer, {
167
+ provisioner,
168
+ token,
169
+ matchesToken: tokenMatches,
170
+ }),
171
+ 'dsh-marker: /ext/anno/session-create',
172
+ )
135
173
  webCtx.effect(() => registerQueueRoutes(webCtx.webServer, { queue }), 'dsh-marker: /ext/anno/queue hand-off')
174
+ webCtx.effect(() => registerEventsRoute(webCtx.webServer, { events }), 'dsh-marker: /ext/anno/events push')
136
175
  webCtx.effect(() => registerFocusRoute(webCtx.webServer, { store: focus }), 'dsh-marker: /ext/anno/focus report')
137
176
  webCtx.effect(
138
177
  () =>
@@ -194,9 +233,21 @@ export async function apply(ctx, config = {}) {
194
233
  }
195
234
  })
196
235
 
236
+ // Pay the picker's first title fold before anyone is looking. The child
237
+ // scope waits for the controller rather than failing once at boot, and a
238
+ // warm-up failure only means a slow first open.
239
+ ctx.inject(['sessionController'], (warmCtx) => {
240
+ warmCtx.effect(() => {
241
+ void catalog.warm()
242
+ }, 'dsh-marker: catalog warm-up')
243
+ })
244
+
197
245
  ctx.effect(
198
246
  () => () => {
199
247
  bridge.cancelAllPicks()
248
+ // A page still holding an event stream would wait on a Host that is gone;
249
+ // closing it makes `EventSource` reconnect to the next one instead.
250
+ events.close()
200
251
  void store.flush()
201
252
  },
202
253
  'dsh-marker: shutdown',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-marker",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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 }
package/src/protocol.js CHANGED
@@ -28,6 +28,15 @@ export const HEALTH_PATH = '/ext/anno/health'
28
28
  */
29
29
  export const SESSIONS_PATH = '/ext/anno/sessions'
30
30
 
31
+ /**
32
+ * Online session creation for the overlay's "new session" target.
33
+ *
34
+ * POST only, token-gated like the catalog. Creation is never queued: a session
35
+ * that does not exist yet has no outbox entry to replay, so the route answers
36
+ * or fails while the composer is still open.
37
+ */
38
+ export const SESSION_CREATE_PATH = '/ext/anno/session-create'
39
+
31
40
  /**
32
41
  * Durable hand-off from the extension to the Web Client: mentions waiting to be
33
42
  * appended to one Session's composer. Same-origin only — the GUI is the page
@@ -38,6 +47,15 @@ export const QUEUE_PATH = '/ext/anno/queue'
38
47
  /** Acknowledged queue entries are removed here; POST `{ids}`. */
39
48
  export const QUEUE_ACK_PATH = '/ext/anno/queue/ack'
40
49
 
50
+ /**
51
+ * The page's push channel: one server-sent event stream per Web Client, telling
52
+ * a mounted Session that something it may own just changed. Same-origin only.
53
+ *
54
+ * It carries a *nudge*, never the data — the queue above stays the authority,
55
+ * so a missed event costs a slower delivery rather than a lost one.
56
+ */
57
+ export const EVENTS_PATH = '/ext/anno/events'
58
+
41
59
  /**
42
60
  * The Session the Web Client is showing, reported by that Client so the Host
43
61
  * can answer "where does an annotation go by default?". Same-origin only, for
@@ -147,6 +165,61 @@ export const LIMITS = {
147
165
  sessionsLimit: 100,
148
166
  /** Chip label carried by a routed mention; presentation only, never identity. */
149
167
  labelChars: 200,
168
+ /** Absolute workspace directory path in a session-create request body. */
169
+ workspacePathChars: 1_024,
170
+ /** Workspace title in a session-create request body. */
171
+ workspaceTitleChars: 200,
172
+ /** Whole session-create request body, far below any parser's limits. */
173
+ createBodyChars: 4_096,
174
+ }
175
+
176
+ /** Session-create workspace modes, in the order the picker offers them. */
177
+ export const SESSION_CREATE_MODES = ['default', 'existing', 'new']
178
+
179
+ /**
180
+ * Validate one session-create request body.
181
+ *
182
+ * @param {unknown} body
183
+ * @returns {string[]} human-readable violations; empty means usable
184
+ */
185
+ export function validateSessionCreateRequest(body) {
186
+ if (!isPlainObject(body)) return ['body must be a JSON object']
187
+ /** @type {string[]} */
188
+ const errors = []
189
+ if (!SESSION_CREATE_MODES.includes(body.mode)) {
190
+ return [`mode must be one of ${SESSION_CREATE_MODES.join('|')}`]
191
+ }
192
+ if (body.mode === 'existing') {
193
+ if (!isString(body.workspaceId) || body.workspaceId.length === 0) {
194
+ errors.push('workspaceId is required when mode is existing')
195
+ } else if (body.workspaceId.length > 200) {
196
+ errors.push('workspaceId exceeds 200 characters')
197
+ }
198
+ }
199
+ if (body.mode === 'new') {
200
+ const path = body.path
201
+ if (!isString(path) || path.length === 0) {
202
+ errors.push('path is required when mode is new')
203
+ } else {
204
+ if (path.length > LIMITS.workspacePathChars) {
205
+ errors.push(`path exceeds ${LIMITS.workspacePathChars} characters`)
206
+ }
207
+ // Absolute only: the host resolves it against its own filesystem, and a
208
+ // relative path would silently land wherever the process happens to run.
209
+ if (path.startsWith('/') !== true && path.startsWith('\\') !== true && !/^[A-Za-z]:[\\/]/.test(path)) {
210
+ errors.push('path must be absolute')
211
+ }
212
+ if (path.includes('\0')) errors.push('path must not contain null bytes')
213
+ }
214
+ }
215
+ if (body.title !== undefined) {
216
+ if (!isString(body.title)) errors.push('title must be a string')
217
+ else if (body.title.trim().length === 0) errors.push('title must not be blank')
218
+ else if (body.title.length > LIMITS.workspaceTitleChars) {
219
+ errors.push(`title exceeds ${LIMITS.workspaceTitleChars} characters`)
220
+ }
221
+ }
222
+ return errors
150
223
  }
151
224
 
152
225
  /** Every frame a client may send to the host. */
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Online session creation for the overlay's "new session" target.
3
+ *
4
+ * The overlay's picker lists Sessions that already exist; this module is the
5
+ * other arm — "this annotation starts a new conversation" — which only the
6
+ * Host can honour, because only it owns `sessionController.create` and the
7
+ * workspace registry. Three workspace modes:
8
+ *
9
+ * - `default` no location, exactly what the Client's own new-session button does;
10
+ * - `existing` one registered workspace by id, the Session joins it;
11
+ * - `new` an absolute path (and optional title), registered first — the
12
+ * registry creates missing directories recursively and resolves
13
+ * idempotently when the directory is already registered.
14
+ *
15
+ * Nothing here is queued. A session that does not exist yet has no outbox
16
+ * entry to replay, so a failure is answered while the composer is still open
17
+ * and the annotation stays unsent in the browser.
18
+ *
19
+ * @module dsh-marker/provision
20
+ */
21
+
22
+ import { LIMITS, SESSION_CREATE_PATH, validateSessionCreateRequest } from './protocol.js'
23
+
24
+ /** The Client picks its workspace rows per open; a second of staleness is invisible. */
25
+ const WORKSPACES_TTL_MS = 1_000
26
+
27
+ /**
28
+ * @param {object} options
29
+ * @param {(name: string) => any} options.get Cordis service lookup for the mounting context.
30
+ * @param {(body: any) => void | Promise<void>} options.onCreated Side effect after one created session (push, focus hints).
31
+ * @param {{ warn?: (...args: any[]) => void, info?: (...args: any[]) => void }} [options.logger]
32
+ * @param {() => number} [options.now] Clock, injected by tests.
33
+ */
34
+ export function createProvisioner({ get, onCreated, logger, now = Date.now }) {
35
+ /** @type {{ at: number, items: any[] } | null} */
36
+ let workspaceCache = null
37
+
38
+ /**
39
+ * Every registered workspace, ordered as the registry keeps them (display
40
+ * order). Cached for a moment so the picker's workspaces list and a create
41
+ * that follows in the same gesture do not scan the registry twice.
42
+ * @returns {Promise<any[]>} `{ id, title, path }` rows
43
+ */
44
+ async function listWorkspaces() {
45
+ const registry = get('workspaceRegistry')
46
+ if (registry === undefined) throw new Error('the workspace registry is not mounted in this profile')
47
+ if (workspaceCache !== null && now() - workspaceCache.at < WORKSPACES_TTL_MS) return workspaceCache.items
48
+ const items = []
49
+ try {
50
+ for (const workspace of registry.list()) {
51
+ items.push({ id: workspace.id, title: workspace.title, path: workspace.path })
52
+ }
53
+ } catch (error) {
54
+ throw new Error(`the workspace registry could not be read (${messageOf(error)})`)
55
+ }
56
+ workspaceCache = { at: now(), items }
57
+ return items
58
+ }
59
+
60
+ /**
61
+ * Create one Session in the requested workspace mode.
62
+ *
63
+ * @param {any} body validated request: `{ mode, workspaceId?, path?, title? }`
64
+ * @returns {Promise<{ sessionId: string, workspace: { id: string, title: string, path: string } | null }>}
65
+ */
66
+ async function createSession(body) {
67
+ const controller = get('sessionController')
68
+ if (controller === undefined) throw new Error('the session controller is not mounted in this profile')
69
+
70
+ let workspace = null
71
+ let request = {}
72
+ if (body.mode === 'existing') {
73
+ workspace = await findByWorkspaceId(String(body.workspaceId))
74
+ if (workspace === null) throw new Error('that workspace no longer exists on this host')
75
+ // `workspaceId` joins the Session to the workspace record; `cwd` is the
76
+ // standalone alternative and the two are exclusive by contract.
77
+ request = { workspaceId: workspace.id }
78
+ } else if (body.mode === 'new') {
79
+ workspace = await registerWorkspace(String(body.path), typeof body.title === 'string' ? body.title : undefined)
80
+ request = { workspaceId: workspace.id }
81
+ }
82
+ // `default` sends no location: the controller resolves the deployment's
83
+ // default, the same path the Client's own new-session button takes.
84
+
85
+ const value = await controller.create(request)
86
+ const sessionId = typeof value?.sessionId === 'string' ? value.sessionId : ''
87
+ if (sessionId === '') throw new Error('the host created the session but returned no identity')
88
+ logger?.info?.(`annotations: session ${sessionId} created (mode ${String(body.mode)})`)
89
+ if (onCreated) await onCreated({ sessionId, workspace })
90
+ return { sessionId, workspace }
91
+ }
92
+
93
+ /** @param {string} workspaceId */
94
+ async function findByWorkspaceId(workspaceId) {
95
+ const items = await listWorkspaces()
96
+ return items.find((item) => item.id === workspaceId) ?? null
97
+ }
98
+
99
+ /**
100
+ * Register (or idempotently resolve) one workspace over an absolute path.
101
+ * @param {string} path
102
+ * @param {string | undefined} title
103
+ */
104
+ async function registerWorkspace(path, title) {
105
+ const registry = get('workspaceRegistry')
106
+ if (registry === undefined) throw new Error('the workspace registry is not mounted in this profile')
107
+ try {
108
+ const workspace = await registry.create(path, title)
109
+ workspaceCache = null
110
+ return { id: workspace.id, title: workspace.title, path: workspace.path }
111
+ } catch (error) {
112
+ throw new Error(`the workspace could not be created (${messageOf(error)})`)
113
+ }
114
+ }
115
+
116
+ return { listWorkspaces, createSession }
117
+ }
118
+
119
+ /**
120
+ * Serve session creation on the Host webserver.
121
+ *
122
+ * The bridge token is the only gate, exactly like the catalog: the overlay
123
+ * runs on an arbitrary http(s) page, so no cookie or Origin assumption can
124
+ * hold. POST only; the body is bounded far below anything the parser cares
125
+ * about, and validation happens before any Host service is touched.
126
+ *
127
+ * @param {any} webServer
128
+ * @param {object} options
129
+ * @param {ReturnType<typeof createProvisioner>} options.provisioner
130
+ * @param {string} options.token
131
+ * @param {(presented: unknown, expected: string) => boolean} options.matchesToken
132
+ * @param {string} [options.path]
133
+ * @returns {() => void} disposer
134
+ */
135
+ export function registerProvisionRoutes(webServer, { provisioner, token, matchesToken, path = SESSION_CREATE_PATH }) {
136
+ const headers = {
137
+ 'content-type': 'application/json; charset=utf-8',
138
+ 'cache-control': 'no-store',
139
+ 'access-control-allow-origin': '*',
140
+ 'access-control-allow-headers': 'authorization, content-type, x-anno-token',
141
+ 'access-control-allow-methods': 'POST, OPTIONS',
142
+ }
143
+ /** @param {number} status @param {any} payload @param {any} request @param {any} response */
144
+ const send = (status, payload, request, response) => {
145
+ const body = JSON.stringify(payload)
146
+ response.writeHead(status, headers)
147
+ response.end(request.method === 'HEAD' ? undefined : body)
148
+ }
149
+
150
+ return webServer.register({
151
+ kind: 'exact',
152
+ path,
153
+ auth: 'anonymous',
154
+ handler: (request, response) => {
155
+ if (request.method === 'OPTIONS') {
156
+ response.writeHead(204, headers)
157
+ response.end()
158
+ return
159
+ }
160
+ if (request.method !== 'POST' && request.method !== 'HEAD') {
161
+ send(405, { ok: false, error: 'method' }, request, response)
162
+ return
163
+ }
164
+ if (!matchesToken(presentedToken(request), token)) {
165
+ send(401, { ok: false, error: 'token' }, request, response)
166
+ return
167
+ }
168
+ if (request.method === 'HEAD') {
169
+ send(200, { ok: true }, request, response)
170
+ return
171
+ }
172
+
173
+ readJson(request)
174
+ .then(async (body) => {
175
+ const errors = validateSessionCreateRequest(body)
176
+ if (errors.length > 0) {
177
+ send(400, { ok: false, error: 'request', message: errors.join('; ') }, request, response)
178
+ return
179
+ }
180
+ const value = await provisioner.createSession(body)
181
+ send(200, { ok: true, ...value }, request, response)
182
+ })
183
+ .catch((error) => {
184
+ // A Host service refusing the operation is the expected failure
185
+ // (missing registry, unusable path); answer it, do not log it twice.
186
+ send(500, { ok: false, error: 'create', message: messageOf(error) }, request, response)
187
+ })
188
+ },
189
+ })
190
+ }
191
+
192
+ /** Accept the token from a bearer header, the dedicated header, or the query string. */
193
+ function presentedToken(request) {
194
+ const header = request.headers?.authorization
195
+ if (typeof header === 'string' && header.toLowerCase().startsWith('bearer ')) return header.slice(7).trim()
196
+ const custom = request.headers?.['x-anno-token']
197
+ if (typeof custom === 'string' && custom !== '') return custom
198
+ try {
199
+ return new URL(request.url ?? '/', 'http://127.0.0.1').searchParams.get('token') ?? ''
200
+ } catch {
201
+ return ''
202
+ }
203
+ }
204
+
205
+ /** @param {any} request */
206
+ function readJson(request) {
207
+ return new Promise((resolve, reject) => {
208
+ let size = 0
209
+ const chunks = []
210
+ request.on('data', (chunk) => {
211
+ size += chunk.length
212
+ if (size > LIMITS.createBodyChars) {
213
+ reject(new Error('body too large'))
214
+ request.destroy()
215
+ return
216
+ }
217
+ chunks.push(chunk)
218
+ })
219
+ request.on('end', () => {
220
+ try {
221
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
222
+ } catch (error) {
223
+ reject(error)
224
+ }
225
+ })
226
+ request.on('error', reject)
227
+ })
228
+ }
229
+
230
+ /** @param {unknown} error */
231
+ function messageOf(error) {
232
+ return error instanceof Error ? error.message : String(error)
233
+ }
package/src/sessions.js CHANGED
@@ -7,13 +7,32 @@
7
7
  * Session the Host knows is a candidate, including ones the browser has never
8
8
  * shown; there is no per-Session state here, only reads.
9
9
  *
10
+ * The expensive part of that read is the *title*, which is a fold over a
11
+ * Session's whole log. Folding every log on every picker open is what made a
12
+ * local list take seconds, so a title is answered in three tiers: the Session
13
+ * summary's own projection hints (zero I/O, already folded by the Host), then
14
+ * this module's memo, and only then a bounded fold for the rows that will
15
+ * actually be shown.
16
+ *
10
17
  * @module dsh-marker/sessions
11
18
  */
12
19
 
13
20
  import { LIMITS, SESSIONS_PATH } from './protocol.js'
14
21
 
15
- /** Session titles are optional: an empty catalog row still lists. */
16
- const TITLE_TIMEOUT_MS = 4_000
22
+ /** A bounded fold is a fallback, not a wait: a title never owns the response. */
23
+ const TITLE_READ_BUDGET_MS = 1_500
24
+
25
+ /** Within this window a memoized title is reused without asking again. */
26
+ const TITLE_TTL_MS = 5 * 60 * 1_000
27
+
28
+ /** A failed title read is retried on a later picker open, not on every request. */
29
+ const TITLE_RETRY_MS = 30_000
30
+
31
+ /** Session summaries change on activity; a picker cannot see a sub-second difference. */
32
+ const SUMMARY_TTL_MS = 1_000
33
+
34
+ /** How many rows a warm-up asks for; the extension asks for 50. */
35
+ const WARM_LIMIT = 50
17
36
 
18
37
  /**
19
38
  * @typedef {object} SessionCatalogItem
@@ -31,8 +50,16 @@ const TITLE_TIMEOUT_MS = 4_000
31
50
  * @param {object} options
32
51
  * @param {(name: string) => any} options.get Cordis service lookup for the mounting context.
33
52
  * @param {{ warn?: (...args: any[]) => void }} [options.logger]
53
+ * @param {() => number} [options.now] Clock, injected by tests.
34
54
  */
35
- export function createSessionCatalog({ get, logger }) {
55
+ export function createSessionCatalog({ get, logger, now = Date.now }) {
56
+ /** @type {Map<string, { at: number, title: string }>} */
57
+ const titles = new Map()
58
+ /** @type {{ at: number, rows: readonly any[] } | null} */
59
+ let listing = null
60
+ /** When the last fold failed, or null while folds are worth trying. */
61
+ let titleFailingAt = null
62
+
36
63
  /**
37
64
  * @param {object} [options]
38
65
  * @param {string} [options.query] Case-insensitive substring over title, id, cwd and workspace.
@@ -41,27 +68,22 @@ export function createSessionCatalog({ get, logger }) {
41
68
  * @param {AbortSignal} [options.signal]
42
69
  */
43
70
  async function list(options = {}) {
44
- const controller = get('sessionController')
45
- if (controller === undefined) throw new Error('the session controller is not mounted in this profile')
46
-
47
71
  const limit = clamp(options.limit ?? 20, 1, LIMITS.sessionsLimit)
48
72
  const signal = options.signal ?? AbortSignal.timeout(8_000)
49
- const value = await controller.list({}, signal)
50
- const summaries = (Array.isArray(value?.items) ? value.items : []).filter(
73
+ const rows = (await readSummaries(signal)).filter(
51
74
  (row) => options.includeSubagents === true || row?.origin !== 'subagent',
52
75
  )
53
-
54
- const titles = await readTitles(
55
- summaries.map((row) => row.sessionId),
56
- signal,
57
- )
58
- const workspaces = workspaceIndex()
59
76
  const needle = (options.query ?? '').trim().toLowerCase()
77
+ const ordered = [...rows].sort((left, right) => timestampOf(right) - timestampOf(left))
78
+
79
+ // A search matches on the title, so it has to know all of them; a plain
80
+ // open only needs the rows it is about to draw.
81
+ await ensureTitles(needle === '' ? ordered.slice(0, limit) : ordered, signal)
60
82
 
61
- const items = summaries
62
- .map((row) => describe(row, titles.get(row.sessionId), workspaces.get(row.sessionId)))
83
+ const workspaces = workspaceIndex()
84
+ const items = ordered
85
+ .map((row) => describe(row, titleOf(row), workspaces.get(row.sessionId)))
63
86
  .filter((item) => needle === '' || matches(item, needle))
64
- .sort((left, right) => right.updatedAt - left.updatedAt)
65
87
 
66
88
  return {
67
89
  items: items.slice(0, limit),
@@ -72,31 +94,83 @@ export function createSessionCatalog({ get, logger }) {
72
94
  }
73
95
 
74
96
  /**
75
- * Titles live in a separate fold; a failure here must not hide the catalog.
76
- * @param {string[]} ids
77
- * @param {AbortSignal} outer
78
- * @returns {Promise<Map<string, string>>}
97
+ * Read the Session summaries, reusing the last read for a moment.
98
+ *
99
+ * The rows carry `running`/`updatedAt`, which move during a turn; a second of
100
+ * staleness is invisible in a picker and keeps two quick opens from scanning
101
+ * the corpus twice.
102
+ *
103
+ * @param {AbortSignal} signal
104
+ * @returns {Promise<readonly any[]>}
79
105
  */
80
- async function readTitles(ids, outer) {
81
- const titles = new Map()
106
+ async function readSummaries(signal) {
107
+ const controller = get('sessionController')
108
+ if (controller === undefined) throw new Error('the session controller is not mounted in this profile')
109
+ if (listing !== null && now() - listing.at < SUMMARY_TTL_MS) return listing.rows
110
+ const value = await controller.list({}, signal)
111
+ const rows = Array.isArray(value?.items) ? value.items : []
112
+ listing = { at: now(), rows }
113
+ return rows
114
+ }
115
+
116
+ /**
117
+ * Fill this module's title memo for the rows a response will need.
118
+ *
119
+ * A hint is free and authoritative; a fold is bounded and best-effort. A fold
120
+ * failure costs titles, never the catalog.
121
+ *
122
+ * @param {readonly any[]} rows
123
+ * @param {AbortSignal} signal
124
+ */
125
+ async function ensureTitles(rows, signal) {
126
+ if (rows.length === 0) return
127
+
128
+ /** @type {any[]} */
129
+ const missing = []
130
+ for (const row of rows) {
131
+ const cached = titles.get(row.sessionId)
132
+ if (cached !== undefined && now() - cached.at < TITLE_TTL_MS) continue
133
+ const hinted = projectionTitle(row)
134
+ if (hinted !== undefined) {
135
+ titles.set(row.sessionId, { at: now(), title: hinted })
136
+ continue
137
+ }
138
+ missing.push(row)
139
+ }
140
+ if (missing.length === 0) return
141
+
82
142
  const query = get('sessionQuery')
83
- if (query === undefined || ids.length === 0) return titles
143
+ if (query === undefined) return
144
+ // A failed fold backs off; a hint is not a fold, so the loop above ran first.
145
+ if (titleFailingAt !== null && now() - titleFailingAt < TITLE_RETRY_MS) return
84
146
 
85
- const budget = AbortSignal.timeout(TITLE_TIMEOUT_MS)
147
+ const ids = missing.map((row) => row.sessionId)
148
+ const budget = AbortSignal.timeout(TITLE_READ_BUDGET_MS)
86
149
  try {
87
- const results = await query.readTitleSnapshots(ids, AbortSignal.any([outer, budget]))
150
+ const results = await query.readTitleSnapshots(ids, AbortSignal.any([signal, budget]))
88
151
  for (const [index, result] of (Array.isArray(results) ? results : []).entries()) {
89
152
  // `{sessionId, status, value: {session, title?: SessionTitleSnapshot}}`;
90
153
  // a rejected row carries only a reason and must not drop the others.
91
154
  const title = result?.value?.title?.title ?? result?.title
92
- if (typeof title !== 'string' || title === '') continue
93
155
  const id = typeof result?.sessionId === 'string' ? result.sessionId : ids[index]
94
- if (typeof id === 'string') titles.set(id, title)
156
+ if (typeof id !== 'string') continue
157
+ // An untitled Session is an answer too: memoizing the miss is what
158
+ // keeps a corpus full of new conversations from being re-folded.
159
+ titles.set(id, { at: now(), title: typeof title === 'string' ? title : '' })
95
160
  }
161
+ titleFailingAt = null
96
162
  } catch (error) {
163
+ if (signal.aborted) return
164
+ titleFailingAt = now()
97
165
  logger?.warn?.(`annotations: session titles unavailable (${messageOf(error)})`)
98
166
  }
99
- return titles
167
+ }
168
+
169
+ /** @param {any} row */
170
+ function titleOf(row) {
171
+ const cached = titles.get(row.sessionId)
172
+ if (cached === undefined) return ''
173
+ return now() - cached.at < TITLE_TTL_MS ? cached.title : ''
100
174
  }
101
175
 
102
176
  /** @returns {Map<string, { id: string, title: string, path: string }>} */
@@ -115,7 +189,36 @@ export function createSessionCatalog({ get, logger }) {
115
189
  return index
116
190
  }
117
191
 
118
- return { list }
192
+ /**
193
+ * Pay the first fold before anyone is looking, so the picker's first open is
194
+ * as fast as every later one. Failures are logged and forgotten: a cold
195
+ * catalog is a slow open, not a broken Host.
196
+ * @returns {Promise<void>}
197
+ */
198
+ function warm() {
199
+ return list({ limit: WARM_LIMIT }).then(
200
+ () => undefined,
201
+ (error) => logger?.warn?.(`annotations: catalog warm-up failed (${messageOf(error)})`),
202
+ )
203
+ }
204
+
205
+ return { list, warm }
206
+ }
207
+
208
+ /**
209
+ * A title the Host already folded, when the Session summary carries one.
210
+ *
211
+ * `SessionSummary.projections.values.title` is the title projection's value —
212
+ * a string in the shipped build, a snapshot object in the type. Both are read,
213
+ * because guessing wrong here would silently restore the fold we are removing.
214
+ * @param {any} row
215
+ * @returns {string | undefined}
216
+ */
217
+ function projectionTitle(row) {
218
+ const value = row?.projections?.values?.title
219
+ if (typeof value === 'string') return value
220
+ if (value !== null && typeof value === 'object' && typeof value.title === 'string') return value.title
221
+ return undefined
119
222
  }
120
223
 
121
224
  /**
@@ -129,11 +232,16 @@ export function createSessionCatalog({ get, logger }) {
129
232
  * @param {ReturnType<typeof createSessionCatalog>} options.catalog
130
233
  * @param {string} options.token
131
234
  * @param {(presented: unknown, expected: string) => boolean} options.matchesToken
235
+ * @param {{ warn?: (...args: any[]) => void }} [options.logger]
132
236
  * @param {() => string | undefined} [options.preferred] Session the Client is showing, when it said so
237
+ * @param {() => Promise<any[]>} [options.workspaces] registered workspaces, when a provisioner is mounted
133
238
  * @param {string} [options.path]
134
239
  * @returns {() => void} disposer
135
240
  */
136
- export function registerSessionsRoute(webServer, { catalog, token, matchesToken, preferred, path = SESSIONS_PATH }) {
241
+ export function registerSessionsRoute(
242
+ webServer,
243
+ { catalog, token, matchesToken, logger, preferred, workspaces, path = SESSIONS_PATH },
244
+ ) {
137
245
  return webServer.register({
138
246
  kind: 'exact',
139
247
  path,
@@ -171,8 +279,23 @@ export function registerSessionsRoute(webServer, { catalog, token, matchesToken,
171
279
  ...(Number.isFinite(limit) ? { limit } : {}),
172
280
  includeSubagents: url.searchParams.get('subagents') === '1',
173
281
  })
174
- .then((value) => {
175
- send(200, { ok: true, ...value, defaultSessionId: defaultId(value.items, preferred?.()) })
282
+ .then(async (value) => {
283
+ // The "new session" arm of the picker needs the workspace list on the
284
+ // same open; a failure only loses that arm, never the catalog.
285
+ let rows = []
286
+ if (workspaces !== undefined) {
287
+ try {
288
+ rows = await workspaces()
289
+ } catch (error) {
290
+ logger?.warn?.(`annotations: workspace list unavailable (${messageOf(error)})`)
291
+ }
292
+ }
293
+ send(200, {
294
+ ok: true,
295
+ ...value,
296
+ workspaces: rows,
297
+ defaultSessionId: defaultId(value.items, preferred?.()),
298
+ })
176
299
  })
177
300
  .catch((error) => {
178
301
  send(500, { ok: false, error: 'catalog', message: messageOf(error) })
@@ -207,12 +330,12 @@ function presentedToken(request) {
207
330
  }
208
331
  }
209
332
 
210
- /** @param {any} row @param {string | undefined} title @param {{ id: string, title: string, path: string } | undefined} workspace */
333
+ /** @param {any} row @param {string} title @param {{ id: string, title: string, path: string } | undefined} workspace */
211
334
  function describe(row, title, workspace) {
212
335
  return {
213
336
  id: row.sessionId,
214
- title: typeof title === 'string' ? title : '',
215
- updatedAt: typeof row.updatedAt === 'number' ? row.updatedAt : 0,
337
+ title,
338
+ updatedAt: timestampOf(row),
216
339
  running: row.running === true,
217
340
  blank: row.blank === true,
218
341
  agentAvailable: row.agentAvailable === true,
@@ -221,6 +344,11 @@ function describe(row, title, workspace) {
221
344
  }
222
345
  }
223
346
 
347
+ /** @param {any} row */
348
+ function timestampOf(row) {
349
+ return typeof row?.updatedAt === 'number' ? row.updatedAt : 0
350
+ }
351
+
224
352
  /** @param {SessionCatalogItem} item @param {string} needle */
225
353
  function matches(item, needle) {
226
354
  return [item.title, item.id, item.cwd ?? '', item.workspace?.title ?? '', item.workspace?.path ?? ''].some((value) =>