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/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) =>