dsh-deepseek-webchat 0.4.8 → 0.4.9

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/README.md CHANGED
@@ -256,6 +256,14 @@ login. Separate DSH Sessions do **not** get separate DeepSeek accounts.
256
256
  when you send something, so a DSH Session stays unbound until you send at least
257
257
  one message in the page. Until then the toolbar dot is hollow.
258
258
 
259
+ **A very long session lists only its newer rows.** The picker pages backwards
260
+ from the newest rows, and a reply larger than ~2 MB of text is not worth moving
261
+ through the HTTP route into a React list, so the host leaves the oldest rows out
262
+ and the list says how many. This only affects sessions in the thousands of rows
263
+ (and, with 高级 on, sessions with tens of megabytes of tool output). Individual
264
+ rows are also capped at 4000 characters — a picker row is one line tall, and the
265
+ outliers are 40–50 KB tool results.
266
+
259
267
  **DeepSeek can change its page.** The composer fill targets
260
268
  `textarea.ds-textarea__textarea`, and the conversation id is read from DeepSeek's
261
269
  `/a/<agent>/s/<id>` route. If DeepSeek redesigns either, the fill or the binding
@@ -291,6 +299,20 @@ It reads messages through `ctx.sessionQuery.readSession()`, which is
291
299
  live-preferred, and reduces the raw event log with the same text-extraction
292
300
  rules the harness itself uses.
293
301
 
302
+ That read is expensive — it decodes and parses the whole log — so the extracted
303
+ rows are cached and revalidated with a cheap token. For a **live** session that
304
+ token is the in-memory `seq` (`ctx.sessions.get()`), which is exact and includes
305
+ events not yet flushed; for a **cold** one it is `ctx.sessionPersistence.stat()`'s
306
+ revision, which reads the stored header and size without decoding anything. An
307
+ unchanged token serves the cached rows without calling `readSession` at all.
308
+ Measured on a real session (10.7 MB zstd log, 7176 frames, 12 188 events): the
309
+ read itself is ~1.2 s of straight-line CPU, and a revalidated reopen is a token
310
+ read plus a JSON write.
311
+
312
+ Responses are bounded: one row carries at most 4000 characters, and a reply is
313
+ capped at ~2 MB of text, dropping the oldest rows (they are reported back as
314
+ `dropped`) because the list opens on the newest ones.
315
+
294
316
  The `advanced` flag is honoured **host-side**, so the default response never
295
317
  contains a reasoning or tool row at all — the browser half cannot accidentally
296
318
  reveal one it was never given. The picker re-requests the list when the switch
package/lib/client.js CHANGED
@@ -151,6 +151,7 @@ window.__ModuleLoader__.load({
151
151
  'picker.loading': '正在读取会话…',
152
152
  'picker.selected': '已选 {count} 条',
153
153
  'picker.hiddenEarlier': '上面还有 {count} 条更早的',
154
+ 'picker.droppedEarlier': '这个会话太长,最前面 {count} 条没有列出',
154
155
  'action.loadEarlier': '加载更早的 {count} 条',
155
156
  'picker.role.user': '用户',
156
157
  'picker.role.assistant': '助手',
@@ -208,6 +209,7 @@ window.__ModuleLoader__.load({
208
209
  'picker.loading': 'Reading the session…',
209
210
  'picker.selected': '{count} selected',
210
211
  'picker.hiddenEarlier': '{count} earlier rows above',
212
+ 'picker.droppedEarlier': 'This session is long: the oldest {count} rows are not listed',
211
213
  'action.loadEarlier': 'Load {count} earlier',
212
214
  'picker.role.user': 'User',
213
215
  'picker.role.assistant': 'Assistant',
@@ -716,10 +718,37 @@ window.__ModuleLoader__.load({
716
718
  // flicker that was still visible after the hide/show loop was fixed.
717
719
  // Rounding makes an unchanged rectangle compare equal, so it is written
718
720
  // once and then left alone.
719
- const left = Math.round(rect.left) + 'px'
720
- const top = Math.round(rect.top) + 'px'
721
- const width = Math.round(rect.width) + 'px'
722
- const height = Math.round(rect.height) + 'px'
721
+ //
722
+ // *Which way* it rounds is load-bearing: inward (ceil the near edges,
723
+ // floor the far ones), never `Math.round`.
724
+ //
725
+ // The right column does not start on a whole CSS pixel — the dock is a
726
+ // `1fr` grid track — and the pane it hosts carries the `.5px`
727
+ // `border-left` that is the vertical divider between the conversation and
728
+ // the sidebar. At this machine's 1.25 device scale that hairline is one
729
+ // device pixel, 0.625 CSS px. `Math.round` moves the overlay's left edge
730
+ // *left* by up to half a CSS pixel whenever the pane lands on x.5–x.99, so
731
+ // this opaque container covers exactly that device pixel and the divider
732
+ // disappears. Measured in the live app: with the overlay parked at
733
+ // `Math.round(rect.left)`, `elementFromPoint` on the border pixel returns
734
+ // the overlay instead of the pane. Only a tab body that parks something
735
+ // over the whole pane — this plugin — can lose the line; every other tab
736
+ // paints strictly inside its border box.
737
+ //
738
+ // Rounding inward keeps the overlay a subset of the measured rectangle, so
739
+ // the border is never painted over. The cost is at most one pixel of
740
+ // unused extent, invisible against the same background.
741
+ const leftEdge = Math.ceil(rect.left)
742
+ const topEdge = Math.ceil(rect.top)
743
+ const rightEdge = Math.floor(rect.left + rect.width)
744
+ const bottomEdge = Math.floor(rect.top + rect.height)
745
+ // A sub-pixel pane rounds to an empty box; refusing to park is better
746
+ // than parking on nothing.
747
+ if (rightEdge - leftEdge < 1 || bottomEdge - topEdge < 1) return
748
+ const left = leftEdge + 'px'
749
+ const top = topEdge + 'px'
750
+ const width = (rightEdge - leftEdge) + 'px'
751
+ const height = (bottomEdge - topEdge) + 'px'
723
752
  const moved = style.left !== left || style.top !== top
724
753
  || style.width !== width || style.height !== height
725
754
  // Written only when it actually changed.
@@ -1648,6 +1677,9 @@ window.__ModuleLoader__.load({
1648
1677
  const [pickerOpen, setPickerOpen] = React.useState(false)
1649
1678
  const [bound, setBound] = React.useState(null)
1650
1679
  const [messages, setMessages] = React.useState(null)
1680
+ // How many of the oldest rows the host left out of the response because
1681
+ // it would have been too large to send. Zero for every ordinary session.
1682
+ const [dropped, setDropped] = React.useState(0)
1651
1683
  const [loadError, setLoadError] = React.useState('')
1652
1684
  const [selected, setSelected] = React.useState(() => new Set())
1653
1685
  const [question, setQuestion] = React.useState('')
@@ -1839,6 +1871,7 @@ window.__ModuleLoader__.load({
1839
1871
  setPageSize(LIST_PAGE_SIZE)
1840
1872
  anchoredRef.current = null
1841
1873
  setMessages(null)
1874
+ setDropped(0)
1842
1875
  setLoadError('')
1843
1876
  void (async () => {
1844
1877
  try {
@@ -1858,10 +1891,18 @@ window.__ModuleLoader__.load({
1858
1891
  }
1859
1892
  const rows = Array.isArray(payload.messages) ? payload.messages : []
1860
1893
  setMessages(rows)
1894
+ // The host bounds the response (per-row and total size), so a
1895
+ // very long session can arrive with its oldest rows already
1896
+ // left out. There is no "load earlier" for those — the picker
1897
+ // pages over what it received — so say how many are missing
1898
+ // rather than let the count look wrong.
1899
+ setDropped(Number.isFinite(payload.dropped) ? payload.dropped : 0)
1861
1900
  diagEvent('picker:loaded', {
1862
1901
  fetchMs: fetched,
1863
1902
  rows: rows.length,
1903
+ dropped: payload.dropped,
1864
1904
  bytes: JSON.stringify(rows).length,
1905
+ cached: payload.cached === true,
1865
1906
  })
1866
1907
  } catch (error) {
1867
1908
  if (cancelled) return
@@ -2111,6 +2152,14 @@ window.__ModuleLoader__.load({
2111
2152
  format(t('picker.hiddenEarlier'), { count: start })),
2112
2153
  ])
2113
2154
  : null,
2155
+ // Rows the host left out of the response entirely (it caps the
2156
+ // total size of a reply). They are older than everything here
2157
+ // and cannot be paged to, so say so once rather than silently
2158
+ // disagreeing with 全选 and 选末尾.
2159
+ dropped === 0
2160
+ ? null
2161
+ : h('div', { key: 'dropped', className: 'dswc-more' },
2162
+ format(t('picker.droppedEarlier'), { count: dropped })),
2114
2163
  ...shown.map((row) => h('label', {
2115
2164
  key: row.seq,
2116
2165
  className: 'dswc-row',
package/lib/index.js CHANGED
@@ -349,6 +349,60 @@ function clip(text, limit = 2000) {
349
349
  return value.length <= limit ? value : value.slice(0, limit) + ' …'
350
350
  }
351
351
 
352
+ /**
353
+ * How much of one row's text is worth sending to the picker.
354
+ *
355
+ * A row is a one-line-tall box that the reader scrolls past; 4000 characters is
356
+ * already far more than anyone reads there, and the rows that exceed it are
357
+ * tool results and reasoning blobs of 40–50 KB. Measured on a real session: the
358
+ * advanced row set was **8.9 MB of JSON** for 8770 rows, dominated by exactly
359
+ * those few huge rows. Capping them at 4000 took it to 6.5 MB, and combined with
360
+ * the payload budget below the panel no longer has to move ten megabytes through
361
+ * the HTTP route and into a React list on every open.
362
+ */
363
+ const MAX_ROW_CHARS = 4000
364
+
365
+ /**
366
+ * Rough cap on the total text a single `messages` response may carry.
367
+ *
368
+ * The picker pages backwards from the newest rows, so when a session is bigger
369
+ * than this the *newest* rows are the ones worth keeping: the oldest are dropped
370
+ * and the count is reported, which is the same information the "load earlier"
371
+ * button already conveys. 2 MB of text is ~5000 default rows or ~500 advanced
372
+ * ones — more than a picker session ever needs to show.
373
+ */
374
+ const MAX_PAYLOAD_CHARS = 2 * 1000 * 1000
375
+
376
+ /**
377
+ * Enforce the per-row cap and the payload budget on extracted rows.
378
+ *
379
+ * The budget drops from the *old* end, because the list opens on the newest rows.
380
+ * @param rows - rows from {@link extractMessages}.
381
+ * @returns `{ rows, dropped }` — the rows to send and how many were left out.
382
+ */
383
+ export function boundRows(rows) {
384
+ if (!Array.isArray(rows)) return { rows: [], dropped: 0 }
385
+ let budget = MAX_PAYLOAD_CHARS
386
+ const kept = []
387
+ let dropped = 0
388
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
389
+ const row = rows[index]
390
+ let text = row.text
391
+ if (text.length > MAX_ROW_CHARS) text = text.slice(0, MAX_ROW_CHARS) + ' …'
392
+ if (text.length > budget && kept.length > 0) {
393
+ // Out of budget: everything older than this is dropped as well, so the
394
+ // surviving rows are always one contiguous newest-first suffix.
395
+ dropped = index + 1
396
+ break
397
+ }
398
+ budget -= text.length
399
+ kept.push(text === row.text ? row : { ...row, text })
400
+ }
401
+ // `kept` was filled newest-first; the caller wants log order.
402
+ kept.reverse()
403
+ return { rows: kept, dropped }
404
+ }
405
+
352
406
  /**
353
407
  * Reduce one Session's raw event log to the rows a human would recognise.
354
408
  *
@@ -709,14 +763,25 @@ export function loadGuestSession() {
709
763
  /**
710
764
  * Cache of extracted rows, keyed by session id and mode.
711
765
  *
712
- * Reading one session costs `sessionQuery.readSession`, which parses the whole
713
- * session log — measured at 2.3 seconds for a 3.6 MB session, and that read is
714
- * synchronous work on the host. Opening the picker did it every time, so the
715
- * panel appeared to freeze for seconds on each open even though nothing was
716
- * looping. The log only ever grows, so a result stays valid while the session's
717
- * event count is unchanged, and that count is cheap to read.
766
+ * Reading one session costs `sessionQuery.readSession`, which decodes and
767
+ * parses the *whole* session log. That is not a cheap call: a real session here
768
+ * holds a 10.7 MB zstd log with 7176 frames and 12 188 events, which measured
769
+ * **~1.2 s of straight-line CPU** (683 ms decode + 485 ms JSON parse) before the
770
+ * harness's own replay validation — and the response the picker then renders was
771
+ * 8.9 MB of JSON for the advanced row set. The earlier version of this cache
772
+ * still called `readSession` on every open just to compare the event count, so
773
+ * the expensive half always ran; that is what made opening the picker feel like
774
+ * a freeze. The freshness check now uses a token read from the session itself —
775
+ * the live `seq`, or `sessionPersistence.stat`'s revision for a cold one — so a
776
+ * repeat open costs a cheap token plus a JSON write.
777
+ *
778
+ * Staleness rule: an entry is trusted when the token observed *before* the log
779
+ * was read is the one observed now. A live `seq` and a stored revision both only
780
+ * advance, so an equal token proves nothing was appended since, and a different
781
+ * one merely costs a re-read — the failure direction is "slow once", never
782
+ * "stale".
718
783
  *
719
- * @type {Map<string, { count: number, messages: object[] }>}
784
+ * @type {Map<string, { token: string | undefined, count: number, messages: object[], dropped: number }>}
720
785
  */
721
786
  const messageCache = new Map()
722
787
 
@@ -732,6 +797,51 @@ function messageCacheKey(sessionId, advanced) {
732
797
  return (advanced ? 'a\u0000' : 'p\u0000') + sessionId
733
798
  }
734
799
 
800
+ /**
801
+ * The log's change token, read without decoding the log.
802
+ *
803
+ * Two sources, because a Session is two things:
804
+ *
805
+ * - **Live** (an open session this Host is driving): `ctx.sessions.get()` hands
806
+ * back the in-memory object and its `seq` is the exact last event, including
807
+ * events that have not reached storage yet. This matters: `persistence.stat`
808
+ * only reports what has been *flushed*, so using it for a live session would
809
+ * let the cache serve rows that predate the last few turns of the very
810
+ * conversation being read. A live `seq` is both exact and free.
811
+ * - **Cold** (persisted, nothing live): `sessionPersistence.stat` — documented
812
+ * for "derived read-model caches keyed off `stat`/`list`" — reads the stored
813
+ * header and byte size without decoding the event stream.
814
+ *
815
+ * Either way this is the difference between a ~1 s freeze and a sub-millisecond
816
+ * lookup on every reopen.
817
+ * @param ctx - Host context.
818
+ * @param sessionId - DSH Session id.
819
+ * @returns an opaque token, or undefined when this profile cannot say.
820
+ */
821
+ async function sessionToken(ctx, sessionId) {
822
+ const sessions = ctx.get('sessions')
823
+ if (sessions !== undefined && typeof sessions.get === 'function') {
824
+ try {
825
+ const live = sessions.get(sessionId)
826
+ const seq = live?.seq
827
+ if (typeof seq === 'number') return 'live:' + seq
828
+ } catch (error) {
829
+ // Fall through to the stored token.
830
+ }
831
+ }
832
+ const persistence = ctx.get('sessionPersistence')
833
+ if (persistence === undefined || typeof persistence.stat !== 'function') return undefined
834
+ try {
835
+ const snapshot = await persistence.stat(sessionId)
836
+ const revision = snapshot?.revision
837
+ return typeof revision === 'string' ? 'stored:' + revision : undefined
838
+ } catch (error) {
839
+ // A session the persistence layer cannot see is not an error: it just means
840
+ // "no cheap freshness signal, go read it".
841
+ return undefined
842
+ }
843
+ }
844
+
735
845
  /**
736
846
  * Read one Session's pickable messages through the Host's own query service.
737
847
  * @param ctx - Host context.
@@ -748,23 +858,39 @@ async function readSessionMessages(ctx, sessionId, advanced = false) {
748
858
  return { ok: false, error: 'a session id is required', messages: [] }
749
859
  }
750
860
  try {
861
+ const key = messageCacheKey(sessionId, advanced)
862
+ // Read the token *before* the expensive call, so a concurrent append during
863
+ // it can only make the recorded token older than the data — which misses
864
+ // the cache next time instead of serving rows that predate the log.
865
+ const token = await sessionToken(ctx, sessionId)
866
+ const cached = messageCache.get(key)
867
+ if (cached !== undefined && token !== undefined && cached.token === token) {
868
+ // Re-insert so this entry is counted as the most recently used.
869
+ messageCache.delete(key)
870
+ messageCache.set(key, cached)
871
+ return { ok: true, error: '', messages: cached.messages, dropped: cached.dropped, cached: true }
872
+ }
751
873
  const session = await query.readSession(sessionId)
752
874
  const events = session?.events
753
875
  const count = Array.isArray(events) ? events.length : 0
754
- const key = messageCacheKey(sessionId, advanced)
755
- const cached = messageCache.get(key)
756
- if (cached !== undefined && cached.count === count) {
757
- return { ok: true, error: '', messages: cached.messages, cached: true }
876
+ // Without a token the only cheap signal is the event count, which still
877
+ // skips extraction but cannot skip the read.
878
+ if (cached !== undefined && token === undefined && cached.count === count) {
879
+ return { ok: true, error: '', messages: cached.messages, dropped: cached.dropped, cached: true }
758
880
  }
759
881
  const messages = extractMessages(events, { advanced })
882
+ // Bounded once, here, so the cached rows are already the rows that get sent:
883
+ // capping at the route instead would redo the work on every request and make
884
+ // the cache store something other than what the caller receives.
885
+ const bounded = boundRows(messages)
760
886
  // Re-inserting moves the key to the end, so the oldest falls out first.
761
887
  messageCache.delete(key)
762
- messageCache.set(key, { count, messages })
888
+ messageCache.set(key, { token, count, messages: bounded.rows, dropped: bounded.dropped })
763
889
  while (messageCache.size > MESSAGE_CACHE_LIMIT) {
764
890
  const oldest = messageCache.keys().next().value
765
891
  messageCache.delete(oldest)
766
892
  }
767
- return { ok: true, error: '', messages, cached: false }
893
+ return { ok: true, error: '', messages: bounded.rows, dropped: bounded.dropped, cached: false }
768
894
  } catch (error) {
769
895
  return { ok: false, error: messageOf(error), messages: [] }
770
896
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-deepseek-webchat",
3
- "version": "0.4.8",
3
+ "version": "0.4.9",
4
4
  "description": "Embeds the official chat.deepseek.com web app in a DSH sidebar tab through the desktop shell's native browser guest, binds one DeepSeek conversation per DSH Session, and sends selected DSH context into the DeepSeek composer as a blockquote.",
5
5
  "keywords": [
6
6
  "dsh",
@@ -151,6 +151,7 @@ window.__ModuleLoader__.load({
151
151
  'picker.loading': '正在读取会话…',
152
152
  'picker.selected': '已选 {count} 条',
153
153
  'picker.hiddenEarlier': '上面还有 {count} 条更早的',
154
+ 'picker.droppedEarlier': '这个会话太长,最前面 {count} 条没有列出',
154
155
  'action.loadEarlier': '加载更早的 {count} 条',
155
156
  'picker.role.user': '用户',
156
157
  'picker.role.assistant': '助手',
@@ -208,6 +209,7 @@ window.__ModuleLoader__.load({
208
209
  'picker.loading': 'Reading the session…',
209
210
  'picker.selected': '{count} selected',
210
211
  'picker.hiddenEarlier': '{count} earlier rows above',
212
+ 'picker.droppedEarlier': 'This session is long: the oldest {count} rows are not listed',
211
213
  'action.loadEarlier': 'Load {count} earlier',
212
214
  'picker.role.user': 'User',
213
215
  'picker.role.assistant': 'Assistant',
@@ -716,10 +718,37 @@ window.__ModuleLoader__.load({
716
718
  // flicker that was still visible after the hide/show loop was fixed.
717
719
  // Rounding makes an unchanged rectangle compare equal, so it is written
718
720
  // once and then left alone.
719
- const left = Math.round(rect.left) + 'px'
720
- const top = Math.round(rect.top) + 'px'
721
- const width = Math.round(rect.width) + 'px'
722
- const height = Math.round(rect.height) + 'px'
721
+ //
722
+ // *Which way* it rounds is load-bearing: inward (ceil the near edges,
723
+ // floor the far ones), never `Math.round`.
724
+ //
725
+ // The right column does not start on a whole CSS pixel — the dock is a
726
+ // `1fr` grid track — and the pane it hosts carries the `.5px`
727
+ // `border-left` that is the vertical divider between the conversation and
728
+ // the sidebar. At this machine's 1.25 device scale that hairline is one
729
+ // device pixel, 0.625 CSS px. `Math.round` moves the overlay's left edge
730
+ // *left* by up to half a CSS pixel whenever the pane lands on x.5–x.99, so
731
+ // this opaque container covers exactly that device pixel and the divider
732
+ // disappears. Measured in the live app: with the overlay parked at
733
+ // `Math.round(rect.left)`, `elementFromPoint` on the border pixel returns
734
+ // the overlay instead of the pane. Only a tab body that parks something
735
+ // over the whole pane — this plugin — can lose the line; every other tab
736
+ // paints strictly inside its border box.
737
+ //
738
+ // Rounding inward keeps the overlay a subset of the measured rectangle, so
739
+ // the border is never painted over. The cost is at most one pixel of
740
+ // unused extent, invisible against the same background.
741
+ const leftEdge = Math.ceil(rect.left)
742
+ const topEdge = Math.ceil(rect.top)
743
+ const rightEdge = Math.floor(rect.left + rect.width)
744
+ const bottomEdge = Math.floor(rect.top + rect.height)
745
+ // A sub-pixel pane rounds to an empty box; refusing to park is better
746
+ // than parking on nothing.
747
+ if (rightEdge - leftEdge < 1 || bottomEdge - topEdge < 1) return
748
+ const left = leftEdge + 'px'
749
+ const top = topEdge + 'px'
750
+ const width = (rightEdge - leftEdge) + 'px'
751
+ const height = (bottomEdge - topEdge) + 'px'
723
752
  const moved = style.left !== left || style.top !== top
724
753
  || style.width !== width || style.height !== height
725
754
  // Written only when it actually changed.
@@ -1648,6 +1677,9 @@ window.__ModuleLoader__.load({
1648
1677
  const [pickerOpen, setPickerOpen] = React.useState(false)
1649
1678
  const [bound, setBound] = React.useState(null)
1650
1679
  const [messages, setMessages] = React.useState(null)
1680
+ // How many of the oldest rows the host left out of the response because
1681
+ // it would have been too large to send. Zero for every ordinary session.
1682
+ const [dropped, setDropped] = React.useState(0)
1651
1683
  const [loadError, setLoadError] = React.useState('')
1652
1684
  const [selected, setSelected] = React.useState(() => new Set())
1653
1685
  const [question, setQuestion] = React.useState('')
@@ -1839,6 +1871,7 @@ window.__ModuleLoader__.load({
1839
1871
  setPageSize(LIST_PAGE_SIZE)
1840
1872
  anchoredRef.current = null
1841
1873
  setMessages(null)
1874
+ setDropped(0)
1842
1875
  setLoadError('')
1843
1876
  void (async () => {
1844
1877
  try {
@@ -1858,10 +1891,18 @@ window.__ModuleLoader__.load({
1858
1891
  }
1859
1892
  const rows = Array.isArray(payload.messages) ? payload.messages : []
1860
1893
  setMessages(rows)
1894
+ // The host bounds the response (per-row and total size), so a
1895
+ // very long session can arrive with its oldest rows already
1896
+ // left out. There is no "load earlier" for those — the picker
1897
+ // pages over what it received — so say how many are missing
1898
+ // rather than let the count look wrong.
1899
+ setDropped(Number.isFinite(payload.dropped) ? payload.dropped : 0)
1861
1900
  diagEvent('picker:loaded', {
1862
1901
  fetchMs: fetched,
1863
1902
  rows: rows.length,
1903
+ dropped: payload.dropped,
1864
1904
  bytes: JSON.stringify(rows).length,
1905
+ cached: payload.cached === true,
1865
1906
  })
1866
1907
  } catch (error) {
1867
1908
  if (cancelled) return
@@ -2111,6 +2152,14 @@ window.__ModuleLoader__.load({
2111
2152
  format(t('picker.hiddenEarlier'), { count: start })),
2112
2153
  ])
2113
2154
  : null,
2155
+ // Rows the host left out of the response entirely (it caps the
2156
+ // total size of a reply). They are older than everything here
2157
+ // and cannot be paged to, so say so once rather than silently
2158
+ // disagreeing with 全选 and 选末尾.
2159
+ dropped === 0
2160
+ ? null
2161
+ : h('div', { key: 'dropped', className: 'dswc-more' },
2162
+ format(t('picker.droppedEarlier'), { count: dropped })),
2114
2163
  ...shown.map((row) => h('label', {
2115
2164
  key: row.seq,
2116
2165
  className: 'dswc-row',
package/src/index.js CHANGED
@@ -349,6 +349,60 @@ function clip(text, limit = 2000) {
349
349
  return value.length <= limit ? value : value.slice(0, limit) + ' …'
350
350
  }
351
351
 
352
+ /**
353
+ * How much of one row's text is worth sending to the picker.
354
+ *
355
+ * A row is a one-line-tall box that the reader scrolls past; 4000 characters is
356
+ * already far more than anyone reads there, and the rows that exceed it are
357
+ * tool results and reasoning blobs of 40–50 KB. Measured on a real session: the
358
+ * advanced row set was **8.9 MB of JSON** for 8770 rows, dominated by exactly
359
+ * those few huge rows. Capping them at 4000 took it to 6.5 MB, and combined with
360
+ * the payload budget below the panel no longer has to move ten megabytes through
361
+ * the HTTP route and into a React list on every open.
362
+ */
363
+ const MAX_ROW_CHARS = 4000
364
+
365
+ /**
366
+ * Rough cap on the total text a single `messages` response may carry.
367
+ *
368
+ * The picker pages backwards from the newest rows, so when a session is bigger
369
+ * than this the *newest* rows are the ones worth keeping: the oldest are dropped
370
+ * and the count is reported, which is the same information the "load earlier"
371
+ * button already conveys. 2 MB of text is ~5000 default rows or ~500 advanced
372
+ * ones — more than a picker session ever needs to show.
373
+ */
374
+ const MAX_PAYLOAD_CHARS = 2 * 1000 * 1000
375
+
376
+ /**
377
+ * Enforce the per-row cap and the payload budget on extracted rows.
378
+ *
379
+ * The budget drops from the *old* end, because the list opens on the newest rows.
380
+ * @param rows - rows from {@link extractMessages}.
381
+ * @returns `{ rows, dropped }` — the rows to send and how many were left out.
382
+ */
383
+ export function boundRows(rows) {
384
+ if (!Array.isArray(rows)) return { rows: [], dropped: 0 }
385
+ let budget = MAX_PAYLOAD_CHARS
386
+ const kept = []
387
+ let dropped = 0
388
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
389
+ const row = rows[index]
390
+ let text = row.text
391
+ if (text.length > MAX_ROW_CHARS) text = text.slice(0, MAX_ROW_CHARS) + ' …'
392
+ if (text.length > budget && kept.length > 0) {
393
+ // Out of budget: everything older than this is dropped as well, so the
394
+ // surviving rows are always one contiguous newest-first suffix.
395
+ dropped = index + 1
396
+ break
397
+ }
398
+ budget -= text.length
399
+ kept.push(text === row.text ? row : { ...row, text })
400
+ }
401
+ // `kept` was filled newest-first; the caller wants log order.
402
+ kept.reverse()
403
+ return { rows: kept, dropped }
404
+ }
405
+
352
406
  /**
353
407
  * Reduce one Session's raw event log to the rows a human would recognise.
354
408
  *
@@ -709,14 +763,25 @@ export function loadGuestSession() {
709
763
  /**
710
764
  * Cache of extracted rows, keyed by session id and mode.
711
765
  *
712
- * Reading one session costs `sessionQuery.readSession`, which parses the whole
713
- * session log — measured at 2.3 seconds for a 3.6 MB session, and that read is
714
- * synchronous work on the host. Opening the picker did it every time, so the
715
- * panel appeared to freeze for seconds on each open even though nothing was
716
- * looping. The log only ever grows, so a result stays valid while the session's
717
- * event count is unchanged, and that count is cheap to read.
766
+ * Reading one session costs `sessionQuery.readSession`, which decodes and
767
+ * parses the *whole* session log. That is not a cheap call: a real session here
768
+ * holds a 10.7 MB zstd log with 7176 frames and 12 188 events, which measured
769
+ * **~1.2 s of straight-line CPU** (683 ms decode + 485 ms JSON parse) before the
770
+ * harness's own replay validation — and the response the picker then renders was
771
+ * 8.9 MB of JSON for the advanced row set. The earlier version of this cache
772
+ * still called `readSession` on every open just to compare the event count, so
773
+ * the expensive half always ran; that is what made opening the picker feel like
774
+ * a freeze. The freshness check now uses a token read from the session itself —
775
+ * the live `seq`, or `sessionPersistence.stat`'s revision for a cold one — so a
776
+ * repeat open costs a cheap token plus a JSON write.
777
+ *
778
+ * Staleness rule: an entry is trusted when the token observed *before* the log
779
+ * was read is the one observed now. A live `seq` and a stored revision both only
780
+ * advance, so an equal token proves nothing was appended since, and a different
781
+ * one merely costs a re-read — the failure direction is "slow once", never
782
+ * "stale".
718
783
  *
719
- * @type {Map<string, { count: number, messages: object[] }>}
784
+ * @type {Map<string, { token: string | undefined, count: number, messages: object[], dropped: number }>}
720
785
  */
721
786
  const messageCache = new Map()
722
787
 
@@ -732,6 +797,51 @@ function messageCacheKey(sessionId, advanced) {
732
797
  return (advanced ? 'a\u0000' : 'p\u0000') + sessionId
733
798
  }
734
799
 
800
+ /**
801
+ * The log's change token, read without decoding the log.
802
+ *
803
+ * Two sources, because a Session is two things:
804
+ *
805
+ * - **Live** (an open session this Host is driving): `ctx.sessions.get()` hands
806
+ * back the in-memory object and its `seq` is the exact last event, including
807
+ * events that have not reached storage yet. This matters: `persistence.stat`
808
+ * only reports what has been *flushed*, so using it for a live session would
809
+ * let the cache serve rows that predate the last few turns of the very
810
+ * conversation being read. A live `seq` is both exact and free.
811
+ * - **Cold** (persisted, nothing live): `sessionPersistence.stat` — documented
812
+ * for "derived read-model caches keyed off `stat`/`list`" — reads the stored
813
+ * header and byte size without decoding the event stream.
814
+ *
815
+ * Either way this is the difference between a ~1 s freeze and a sub-millisecond
816
+ * lookup on every reopen.
817
+ * @param ctx - Host context.
818
+ * @param sessionId - DSH Session id.
819
+ * @returns an opaque token, or undefined when this profile cannot say.
820
+ */
821
+ async function sessionToken(ctx, sessionId) {
822
+ const sessions = ctx.get('sessions')
823
+ if (sessions !== undefined && typeof sessions.get === 'function') {
824
+ try {
825
+ const live = sessions.get(sessionId)
826
+ const seq = live?.seq
827
+ if (typeof seq === 'number') return 'live:' + seq
828
+ } catch (error) {
829
+ // Fall through to the stored token.
830
+ }
831
+ }
832
+ const persistence = ctx.get('sessionPersistence')
833
+ if (persistence === undefined || typeof persistence.stat !== 'function') return undefined
834
+ try {
835
+ const snapshot = await persistence.stat(sessionId)
836
+ const revision = snapshot?.revision
837
+ return typeof revision === 'string' ? 'stored:' + revision : undefined
838
+ } catch (error) {
839
+ // A session the persistence layer cannot see is not an error: it just means
840
+ // "no cheap freshness signal, go read it".
841
+ return undefined
842
+ }
843
+ }
844
+
735
845
  /**
736
846
  * Read one Session's pickable messages through the Host's own query service.
737
847
  * @param ctx - Host context.
@@ -748,23 +858,39 @@ async function readSessionMessages(ctx, sessionId, advanced = false) {
748
858
  return { ok: false, error: 'a session id is required', messages: [] }
749
859
  }
750
860
  try {
861
+ const key = messageCacheKey(sessionId, advanced)
862
+ // Read the token *before* the expensive call, so a concurrent append during
863
+ // it can only make the recorded token older than the data — which misses
864
+ // the cache next time instead of serving rows that predate the log.
865
+ const token = await sessionToken(ctx, sessionId)
866
+ const cached = messageCache.get(key)
867
+ if (cached !== undefined && token !== undefined && cached.token === token) {
868
+ // Re-insert so this entry is counted as the most recently used.
869
+ messageCache.delete(key)
870
+ messageCache.set(key, cached)
871
+ return { ok: true, error: '', messages: cached.messages, dropped: cached.dropped, cached: true }
872
+ }
751
873
  const session = await query.readSession(sessionId)
752
874
  const events = session?.events
753
875
  const count = Array.isArray(events) ? events.length : 0
754
- const key = messageCacheKey(sessionId, advanced)
755
- const cached = messageCache.get(key)
756
- if (cached !== undefined && cached.count === count) {
757
- return { ok: true, error: '', messages: cached.messages, cached: true }
876
+ // Without a token the only cheap signal is the event count, which still
877
+ // skips extraction but cannot skip the read.
878
+ if (cached !== undefined && token === undefined && cached.count === count) {
879
+ return { ok: true, error: '', messages: cached.messages, dropped: cached.dropped, cached: true }
758
880
  }
759
881
  const messages = extractMessages(events, { advanced })
882
+ // Bounded once, here, so the cached rows are already the rows that get sent:
883
+ // capping at the route instead would redo the work on every request and make
884
+ // the cache store something other than what the caller receives.
885
+ const bounded = boundRows(messages)
760
886
  // Re-inserting moves the key to the end, so the oldest falls out first.
761
887
  messageCache.delete(key)
762
- messageCache.set(key, { count, messages })
888
+ messageCache.set(key, { token, count, messages: bounded.rows, dropped: bounded.dropped })
763
889
  while (messageCache.size > MESSAGE_CACHE_LIMIT) {
764
890
  const oldest = messageCache.keys().next().value
765
891
  messageCache.delete(oldest)
766
892
  }
767
- return { ok: true, error: '', messages, cached: false }
893
+ return { ok: true, error: '', messages: bounded.rows, dropped: bounded.dropped, cached: false }
768
894
  } catch (error) {
769
895
  return { ok: false, error: messageOf(error), messages: [] }
770
896
  }