dsh-ws-recency 0.25.1 → 0.26.0

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.
Files changed (4) hide show
  1. package/README.md +15 -2
  2. package/client.js +320 -0
  3. package/index.js +271 -4
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-ws-recency
2
2
 
3
- DSH 侧栏的六件事:**工作区分组按最近活跃排序**、**过期历史自动折叠**、**运行中/未读/需跟进三色标记**、**所有置顶会话汇总到顶部一个区**、**删除会话到可恢复的回收站(归档会话也在同一个面板里管理)**、**按来源拆分、并将参数与结果分段的 token 消耗统计**、**把会话移动到另一个工作区**。单独装上就有效,不依赖其它插件。
3
+ DSH 侧栏的七件事:**工作区分组按最近活跃排序**、**过期历史自动折叠**、**运行中/未读/需跟进三色标记**、**所有置顶会话汇总到顶部一个区**、**删除会话到可恢复的回收站(归档会话也在同一个面板里管理)**、**按来源拆分、并将参数与结果分段的 token 消耗统计**、**把会话移动到另一个工作区**,外加**跨会话的内容搜索(点结果直接跳到说过那句话的那一轮)**。单独装上就有效,不依赖其它插件。
4
4
 
5
5
  ## 一、分组排序
6
6
 
@@ -146,6 +146,16 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
146
146
  卡片只在**这一轮结束之后**才出现(0.24.2 修):轮询会比对回复的日志序号与「本轮是否还在跑」,只认点击之后产生、且已经收尾的那条回复——之前它读的是「全日志最后一条非空回复」,只要新轮先落一条工具步骤,就会把上一轮里的旧交接块当成答案,交接刚开始还在处理就弹卡;卡片也只挂在产生它的那一轮下面,不再在每个旧轮下面重复出现。
147
147
 
148
148
 
149
+ ## 九、会话内容搜索
150
+
151
+ 会话一长,靠滚动是找不回来的。侧栏的放大镜打开搜索页,输词回车:
152
+
153
+ - 搜的是**对话正文**:你的提问 + 助手的回复;不搜思维链、不搜工具参数和工具结果(那些会让命中被日志噪声淹没);
154
+ - 多个词用空格分隔,**要求同时出现在同一条消息里**(AND);大小写不敏感,纯字面匹配,不支持正则;
155
+ - 结果按新到旧排列,每条给出角色、会话标题、所属工作区、第几轮,以及带高亮的片段;
156
+ - 点一条结果:打开那个会话 → 滚到对应那一轮 → 闪一下蓝色描边。老会话的历史是懒加载的,插件会自己往上翻直到那一轮出现,最多等 8 秒;
157
+ - 第一次搜索要为每个会话建一次正文索引(存在 `~/.hypers-work/.wsr/search/<sessionId>.json`,按日志大小 + revision 决定是否失效)。面板顶部会显示「还有 N 个会话正在建立索引」,每轮补一批、结果自动刷新,之后同一份日志不再重复解码。
158
+
149
159
  ## 设置
150
160
 
151
161
  **设置 → 通用**:
@@ -164,6 +174,9 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
164
174
  - “未分组”桶永远排在真实工作区之后。
165
175
  - 只在按工作区分组(含工作区树顶层)时生效。
166
176
  - **可选互操作**:如果你另外装着 `dsh-plugin-busy-workspace`,本插件会尊重它写在分组上的 `data-busy-rank`,把它的紧急度当主键、档位内部再按活跃度排。没装就是纯最近活跃排序——本插件不依赖它。
177
+ - 搜索是**字面匹配**,不是全文检索:不支持正则、不排序相关性,结果只按时间倒序;正文外的内容(思维链、工具参数、工具结果、附件)不参与匹配。
178
+ - 搜索索引是插件自己的缓存(`~/.hypers-work/.wsr/search/`),删掉只会让下一次搜索重新建;宿主自带的 SQLite 全文索引默认关闭,本插件没有去改那个开关。
179
+ - 跳到某一轮靠宿主的 `data-chat-turn` 行和 `[data-conversation-scroll]` 滚动容器:宿主改这两个标识,跳转就会失效,搜索本身不受影响。
167
180
 
168
181
  ## 安装
169
182
 
@@ -182,7 +195,7 @@ dsh plugin --profile <profile> add github:chyxhtc/dsh-ws-recency
182
195
  或固定版本的预构建包:
183
196
 
184
197
  ```powershell
185
- dsh plugin --profile <profile> add https://github.com/chyxhtc/dsh-ws-recency/releases/download/v0.25.1/dsh-ws-recency-0.25.1.tgz
198
+ dsh plugin --profile <profile> add https://github.com/chyxhtc/dsh-ws-recency/releases/download/v0.26.0/dsh-ws-recency-0.26.0.tgz
186
199
  ```
187
200
 
188
201
  装完把 `dsh-ws-recency` 加进 `~/.hypers-work/profiles/<profile>/package.json` 的 `dsh.profile.bundles`,重启应用。
package/client.js CHANGED
@@ -279,6 +279,20 @@
279
279
  '[' + STATE_ATTR + '="running"] [class*="_title"]{color:#4f8ef7}',
280
280
  '[' + STATE_ATTR + '="unread"] [class*="_title"]{color:#3fae6b}',
281
281
  '[' + STATE_ATTR + '="followup"] [class*="_title"]{color:#d99a2b}',
282
+ ".wsr-search-bar{display:flex;gap:8px;align-items:center}",
283
+ ".wsr-search-input{flex:1;min-width:0;height:30px;padding:0 10px;border-radius:6px;border:.5px solid var(--dsw-alias-border-l2);background:transparent;color:inherit;font-size:13px}",
284
+ ".wsr-hit{display:flex;flex-direction:column;gap:4px;padding:8px 10px;border-radius:8px;cursor:pointer}",
285
+ ".wsr-hit:hover{background:var(--dsw-alias-bg-layer-2)}",
286
+ ".wsr-hit-head{display:flex;align-items:center;gap:8px;font-size:11px;color:var(--dsw-alias-label-tertiary)}",
287
+ ".wsr-hit-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-primary);font-size:13px}",
288
+ ".wsr-hit-role{flex:none;padding:0 6px;border-radius:4px;background:var(--dsw-alias-bg-layer-2);font-size:10px}",
289
+ ".wsr-hit-user{color:#4f8ef7}",
290
+ ".wsr-hit-agent{color:#3fae6b}",
291
+ ".wsr-hit-ws{flex:none;max-width:30%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
292
+ ".wsr-hit-turn{flex:none}",
293
+ ".wsr-hit-snippet{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);word-break:break-word}",
294
+ ".wsr-mark{background:rgba(79,142,247,.28);color:inherit;border-radius:2px}",
295
+ '[data-wsr-flash="true"]{outline:2px solid #4f8ef7;outline-offset:2px;border-radius:8px}',
282
296
  ".wsr-dot{display:block;width:7px;height:7px;border-radius:50%;margin:0 auto;background:#d99a2b;cursor:pointer}",
283
297
  ".wsr-dot:hover{outline:2px solid var(--dsw-alias-border-l2)}",
284
298
  ".wsr-setRow{display:flex;align-items:center;gap:16px;justify-content:space-between;padding:12px 0}",
@@ -374,6 +388,17 @@
374
388
  "adopt.done": "已补登记 {n} 个会话。",
375
389
  "adopt.cleaned": "清理了 {n} 处重复/失效的工作区归属。",
376
390
  "adopt.failed": "扫描失败:",
391
+ "search.title": "搜索会话内容",
392
+ "search.placeholder": "输入关键词后回车;多个词用空格分隔,要求同时出现",
393
+ "search.run": "搜索",
394
+ "search.searching": "搜索中…",
395
+ "search.indexing": "还有 {n} 个会话正在建立索引,结果会陆续补上…",
396
+ "search.summary": "{hits} 处命中 · 共 {sessions} 个会话 · {ms} ms",
397
+ "search.empty": "没有匹配的内容。",
398
+ "search.failed": "搜索失败:",
399
+ "search.you": "你",
400
+ "search.assistant": "助手",
401
+ "search.turn": "第 {n} 轮",
377
402
  "ui.reload": "刷新界面",
378
403
  "ui.refresh": "刷新列表",
379
404
  "trash.title": "回收站",
@@ -522,6 +547,17 @@
522
547
  "adopt.done": "Re-attached {n} session(s).",
523
548
  "adopt.cleaned": " Cleared {n} stale membership(s).",
524
549
  "adopt.failed": "Scan failed: ",
550
+ "search.title": "Search session content",
551
+ "search.placeholder": "Type a word and press Enter; separate words with spaces to require all of them",
552
+ "search.run": "Search",
553
+ "search.searching": "Searching\u2026",
554
+ "search.indexing": "Still indexing {n} session(s); results will fill in\u2026",
555
+ "search.summary": "{hits} hit(s) across {sessions} session(s) \u00b7 {ms} ms",
556
+ "search.empty": "Nothing matched.",
557
+ "search.failed": "Search failed: ",
558
+ "search.you": "You",
559
+ "search.assistant": "Assistant",
560
+ "search.turn": "turn {n}",
525
561
  "ui.reload": "Reload UI",
526
562
  "ui.refresh": "Refresh",
527
563
  "trash.title": "Trash",
@@ -3210,6 +3246,263 @@
3210
3246
  });
3211
3247
  }
3212
3248
 
3249
+ /* ---------- session content search -------------------------------- */
3250
+
3251
+ /** What the uncontrolled input holds; the panel keeps only results in state. */
3252
+ var searchDraft = "";
3253
+ /** Bumped per search so a slow answer cannot overwrite a newer one. */
3254
+ var searchGeneration = 0;
3255
+
3256
+ function searchPost(body) {
3257
+ return fetch("/ws-recency/search", {
3258
+ method: "POST",
3259
+ headers: { "content-type": "application/json" },
3260
+ body: JSON.stringify(body || {}),
3261
+ }).then(function (response) {
3262
+ return response.text().then(function (text) {
3263
+ var parsed = null;
3264
+ try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
3265
+ return { status: response.status, text: text, json: parsed };
3266
+ });
3267
+ });
3268
+ }
3269
+
3270
+ function SearchPanelIcon(props) {
3271
+ var Icon = ui.IconSearchOutlineRegular;
3272
+ if (typeof Icon !== "function") return null;
3273
+ var size = props !== undefined && props !== null && typeof props.size === "number" ? props.size : 16;
3274
+ return h(Icon, { size: size });
3275
+ }
3276
+
3277
+ function conversationScroller() {
3278
+ if (typeof document === "undefined") return null;
3279
+ try {
3280
+ var direct = document.querySelector("[data-conversation-scroll]");
3281
+ if (direct !== null) return direct;
3282
+ /* The marker is the documented hook; without it, take the nearest
3283
+ ancestor that actually scrolls rather than giving up. */
3284
+ var anyRow = document.querySelector("[data-chat-turn]");
3285
+ var node = anyRow === null ? null : anyRow.parentElement;
3286
+ while (node !== null && node !== undefined) {
3287
+ if (typeof node.scrollHeight === "number" && node.scrollHeight > node.clientHeight && node.clientHeight > 0) return node;
3288
+ node = node.parentElement;
3289
+ }
3290
+ return null;
3291
+ } catch (error) {
3292
+ return null;
3293
+ }
3294
+ }
3295
+
3296
+ function turnRowOf(turn) {
3297
+ if (typeof document === "undefined" || !isFinite(turn)) return null;
3298
+ try {
3299
+ return document.querySelector('[data-chat-turn="' + String(turn) + '"]');
3300
+ } catch (error) {
3301
+ return null;
3302
+ }
3303
+ }
3304
+
3305
+ /** Ring the row the search sent the user to, without taking keyboard focus. */
3306
+ function flashTurnRow(row) {
3307
+ try {
3308
+ if (typeof row.scrollIntoView === "function") row.scrollIntoView({ block: "center" });
3309
+ } catch (error) {
3310
+ /* some engines only accept the boolean form */
3311
+ }
3312
+ try {
3313
+ row.setAttribute("data-wsr-flash", "true");
3314
+ window.setTimeout(function () {
3315
+ if (row.getAttribute("data-wsr-flash") !== null) row.removeAttribute("data-wsr-flash");
3316
+ }, 2600);
3317
+ } catch (error) {
3318
+ /* the conversation may have been replaced while we waited */
3319
+ }
3320
+ }
3321
+
3322
+ /**
3323
+ * Bring one turn of one session into view.
3324
+ *
3325
+ * The chat mounts recent turns first and loads older history as the
3326
+ * scroller approaches its top, so this walks the scroller upwards until
3327
+ * the turn exists, then centres it. Every step is DOM-only: nothing here
3328
+ * steals focus or synthesises keystrokes.
3329
+ */
3330
+ function revealTurn(sessionId, turn) {
3331
+ if (typeof document === "undefined" || !isFinite(turn)) return;
3332
+ var deadline = Date.now() + 8000;
3333
+ var steps = 0;
3334
+ var tick = function () {
3335
+ if (Date.now() > deadline) return;
3336
+ if (currentConversationId() !== sessionId) {
3337
+ window.setTimeout(tick, 150);
3338
+ return;
3339
+ }
3340
+ var row = turnRowOf(turn);
3341
+ if (row !== null) {
3342
+ flashTurnRow(row);
3343
+ return;
3344
+ }
3345
+ var scroller = conversationScroller();
3346
+ if (scroller === null) {
3347
+ window.setTimeout(tick, 150);
3348
+ return;
3349
+ }
3350
+ if (steps >= 24) {
3351
+ window.setTimeout(tick, 300);
3352
+ return;
3353
+ }
3354
+ steps += 1;
3355
+ var height = typeof scroller.clientHeight === "number" && scroller.clientHeight > 0 ? scroller.clientHeight : 600;
3356
+ var top = Number(scroller.scrollTop) || 0;
3357
+ scroller.scrollTop = Math.max(0, top - Math.max(240, height * 0.8));
3358
+ window.setTimeout(tick, 260);
3359
+ };
3360
+ window.setTimeout(tick, 120);
3361
+ }
3362
+
3363
+ function jumpToSearchHit(hit) {
3364
+ openSessionRow(hit.sessionId);
3365
+ revealTurn(hit.sessionId, hit.turn);
3366
+ }
3367
+
3368
+ /** Snippet text with every query term wrapped in a mark. */
3369
+ function highlightSnippet(snippet, terms) {
3370
+ var text = typeof snippet === "string" ? snippet : "";
3371
+ var lower = text.toLowerCase();
3372
+ var ranges = [];
3373
+ for (var i = 0; i < terms.length; i += 1) {
3374
+ var term = String(terms[i] || "").toLowerCase();
3375
+ if (term === "") continue;
3376
+ var from = 0;
3377
+ while (from < lower.length) {
3378
+ var at = lower.indexOf(term, from);
3379
+ if (at < 0) break;
3380
+ ranges.push({ start: at, end: at + term.length });
3381
+ from = at + term.length;
3382
+ }
3383
+ }
3384
+ ranges.sort(function (a, b) { return a.start - b.start; });
3385
+ var pieces = [];
3386
+ var cursor = 0;
3387
+ for (var j = 0; j < ranges.length; j += 1) {
3388
+ var range = ranges[j];
3389
+ if (range.start < cursor) continue;
3390
+ if (range.start > cursor) pieces.push(h("span", { key: "t" + j }, text.slice(cursor, range.start)));
3391
+ pieces.push(h("mark", { key: "m" + j, className: "wsr-mark" }, text.slice(range.start, range.end)));
3392
+ cursor = range.end;
3393
+ }
3394
+ if (cursor < text.length) pieces.push(h("span", { key: "tail" }, text.slice(cursor)));
3395
+ return pieces;
3396
+ }
3397
+
3398
+ /**
3399
+ * The search page: one input, one list of hits.
3400
+ *
3401
+ * The host answers with the sessions it managed to index inside its time
3402
+ * budget plus how many are still pending, so this asks again until the
3403
+ * index has caught up instead of making the user press search twice.
3404
+ */
3405
+ function SearchPanelPage() {
3406
+ var state = react.useState({ loaded: false, query: "", hits: [], terms: [], scanned: 0, total: 0, pending: 0, took: 0, busy: false, error: "" });
3407
+ var view = state[0];
3408
+ var setView = state[1];
3409
+
3410
+ var run = function (text, refresh) {
3411
+ var query = typeof text === "string" ? text.trim() : "";
3412
+ searchGeneration += 1;
3413
+ var generation = searchGeneration;
3414
+ if (query === "") {
3415
+ setView({ loaded: true, query: "", hits: [], terms: [], scanned: 0, total: 0, pending: 0, took: 0, busy: false, error: "" });
3416
+ return;
3417
+ }
3418
+ setView({ loaded: true, query: query, hits: view.hits, terms: view.terms, scanned: view.scanned, total: view.total, pending: view.pending, took: view.took, busy: true, error: "" });
3419
+ var ask = function (needRefresh) {
3420
+ searchPost({ query: query, refresh: needRefresh === true }).then(function (answer) {
3421
+ if (generation !== searchGeneration) return;
3422
+ var json = answer.json;
3423
+ if (json === null || json.ok !== true) {
3424
+ setView({ loaded: true, query: query, hits: [], terms: [], scanned: 0, total: 0, pending: 0, took: 0, busy: false, error: t("search.failed") + "HTTP " + answer.status });
3425
+ return;
3426
+ }
3427
+ setView({
3428
+ loaded: true,
3429
+ query: query,
3430
+ hits: Array.isArray(json.hits) ? json.hits : [],
3431
+ terms: Array.isArray(json.terms) ? json.terms : [],
3432
+ scanned: json.scanned || 0,
3433
+ total: json.total || 0,
3434
+ pending: json.pending || 0,
3435
+ took: json.took || 0,
3436
+ busy: false,
3437
+ error: "",
3438
+ });
3439
+ if (json.pending > 0) {
3440
+ window.setTimeout(function () {
3441
+ if (generation === searchGeneration) ask(false);
3442
+ }, 150);
3443
+ }
3444
+ }).catch(function (error) {
3445
+ if (generation !== searchGeneration) return;
3446
+ setView({ loaded: true, query: query, hits: [], terms: [], scanned: 0, total: 0, pending: 0, took: 0, busy: false, error: t("search.failed") + (error && error.message ? error.message : error) });
3447
+ });
3448
+ };
3449
+ ask(refresh === true);
3450
+ };
3451
+
3452
+ var input = h("input", {
3453
+ className: "wsr-search-input",
3454
+ type: "search",
3455
+ placeholder: t("search.placeholder"),
3456
+ defaultValue: "",
3457
+ onChange: function (event) {
3458
+ searchDraft = event !== undefined && event.target !== undefined ? String(event.target.value || "") : "";
3459
+ },
3460
+ onKeyDown: function (event) {
3461
+ if (event !== undefined && event.key === "Enter") {
3462
+ if (typeof event.preventDefault === "function") event.preventDefault();
3463
+ run(searchDraft, false);
3464
+ }
3465
+ },
3466
+ });
3467
+
3468
+ var rows = view.hits.map(function (hit, index) {
3469
+ return h("div", {
3470
+ className: "wsr-hit",
3471
+ key: String(hit.sessionId || "") + ":" + String(hit.seq || 0) + ":" + String(index),
3472
+ title: hit.cwd || "",
3473
+ onClick: function () { jumpToSearchHit(hit); },
3474
+ },
3475
+ h("div", { className: "wsr-hit-head" },
3476
+ h("span", { className: "wsr-hit-role " + (hit.role === "user" ? "wsr-hit-user" : "wsr-hit-agent") }, hit.role === "user" ? t("search.you") : t("search.assistant")),
3477
+ h("span", { className: "wsr-hit-title" }, hit.title || hit.sessionId || ""),
3478
+ typeof hit.workspace === "string" && hit.workspace !== "" ? h("span", { className: "wsr-hit-ws" }, hit.workspace) : null,
3479
+ h("span", { className: "wsr-hit-turn" }, t("search.turn", { n: String(hit.turn) })),
3480
+ ),
3481
+ h("div", { className: "wsr-hit-snippet" },
3482
+ hit.lead === true ? "\u2026" : null,
3483
+ highlightSnippet(hit.snippet || "", view.terms),
3484
+ hit.tail === true ? "\u2026" : null,
3485
+ ),
3486
+ );
3487
+ });
3488
+
3489
+ return h("div", { className: "wsr-page wsr-search-page" },
3490
+ h("div", { className: "wsr-page-head" },
3491
+ h("div", { className: "wsr-page-heading" }, t("search.title")),
3492
+ ),
3493
+ h("div", { className: "wsr-search-bar" },
3494
+ input,
3495
+ h("button", { type: "button", className: "wsr-btn", onClick: function () { run(searchDraft, false); } }, t("search.run")),
3496
+ ),
3497
+ view.busy ? h("div", { className: "wsr-page-note" }, t("search.searching")) : null,
3498
+ view.error !== "" ? h("div", { className: "wsr-page-note wsr-page-error" }, view.error) : null,
3499
+ view.pending > 0 ? h("div", { className: "wsr-page-note" }, t("search.indexing", { n: String(view.pending) })) : null,
3500
+ view.loaded && !view.busy ? h("div", { className: "wsr-page-note" }, t("search.summary", { hits: String(view.hits.length), sessions: String(view.total), ms: String(view.took) })) : null,
3501
+ view.loaded && !view.busy && view.hits.length === 0 ? h("div", { className: "wsr-page-note" }, t("search.empty")) : null,
3502
+ h("div", { className: "wsr-page-list" }, rows),
3503
+ );
3504
+ }
3505
+
3213
3506
  /** The sidebar's trash entry glyph. */
3214
3507
  function TrashPanelIcon(props) {
3215
3508
  var Icon = ui.IconTrashOutlineRegular;
@@ -3689,6 +3982,24 @@
3689
3982
  }, ColorsRow);
3690
3983
  });
3691
3984
 
3985
+ ctx.slots.inject("sidebar.panellist", function () {
3986
+ return ctx.slots.register({
3987
+ name: "sidebar.panellist",
3988
+ id: "ws-recency-search",
3989
+ order: 19,
3990
+ locale: NS,
3991
+ label: function () { return t("search.title"); },
3992
+ }, SearchPanelIcon);
3993
+ });
3994
+
3995
+ ctx.slots.inject("main", function () {
3996
+ return ctx.slots.register({
3997
+ name: "main",
3998
+ key: "ws-recency-search",
3999
+ locale: NS,
4000
+ }, SearchPanelPage);
4001
+ });
4002
+
3692
4003
  ctx.slots.inject("sidebar.panellist", function () {
3693
4004
  return ctx.slots.register({
3694
4005
  name: "sidebar.panellist",
@@ -3827,6 +4138,15 @@
3827
4138
  send: sendToSession,
3828
4139
  };
3829
4140
 
4141
+ /* Test hook: the jump and the highlighting are pure DOM helpers. */
4142
+ exports.__search = {
4143
+ draft: function () { return searchDraft; },
4144
+ highlight: highlightSnippet,
4145
+ reveal: revealTurn,
4146
+ jump: jumpToSearchHit,
4147
+ turnRow: turnRowOf,
4148
+ };
4149
+
3830
4150
  exports.name = "dsh-ws-recency";
3831
4151
  exports.inject = inject;
3832
4152
  exports.apply = apply_;
package/index.js CHANGED
@@ -32,7 +32,7 @@ import { dirname, join } from "node:path";
32
32
  export const name = "ws-recency";
33
33
 
34
34
  /** Version marker reported by the health route. */
35
- export const HOST_VERSION = "0.25.1";
35
+ export const HOST_VERSION = "0.26.0";
36
36
 
37
37
  /**
38
38
  * Exact routes the client half calls. Registered on the bare web server, so they
@@ -44,6 +44,7 @@ export const HEALTH_PATH = "/ws-recency/health";
44
44
  export const MOVE_SESSION_PATH = "/ws-recency/session-move";
45
45
  export const ADOPT_SESSION_PATH = "/ws-recency/session-adopt";
46
46
  export const TRASH_LIST_PATH = "/ws-recency/trash";
47
+ export const SEARCH_CONTENT_PATH = "/ws-recency/search";
47
48
 
48
49
  export const HANDOFF_PATH = "/ws-recency/handoff";
49
50
 
@@ -599,9 +600,245 @@ async function readSessionEvents(ctx, sessionId) {
599
600
  return all;
600
601
  }
601
602
 
603
+ /* ------------------------------------------------------------------------- *
604
+ * Session content search
605
+ *
606
+ * Literal search over what was actually said: the user's prompts and the
607
+ * assistant's text blocks. Each session keeps a small cache of that text keyed
608
+ * by the log's size+revision, so a query only decodes sessions that changed;
609
+ * it stops when its time budget is spent and reports how many are still
610
+ * pending, which is what the panel shows as "still indexing".
611
+ * ------------------------------------------------------------------------- */
612
+
613
+ const SEARCH_INDEX_VERSION = 1;
614
+ /** Longer messages are cut for the cache: snippets never need the tail. */
615
+ const SEARCH_MESSAGE_CAP = 200000;
616
+ const SEARCH_PER_SESSION = 3;
617
+ const SEARCH_TOTAL_CAP = 60;
618
+ const SEARCH_BUDGET_MS = 6000;
619
+ const SEARCH_NEW_PER_QUERY = 8;
620
+
621
+ /** Same normalisation on both sides of a cwd comparison. */
622
+ function normalizedPath(value) {
623
+ return typeof value === "string" ? value.replace(/[\\/]+$/, "").toLowerCase() : "";
624
+ }
625
+
626
+ async function searchIndexDirectory() {
627
+ return join(await dshHome(), ".wsr", "search");
628
+ }
629
+
630
+ function searchCacheKey(stat) {
631
+ const size = Number(stat !== null && stat !== undefined ? stat.sizeBytes : 0) || 0;
632
+ const revision = stat !== null && stat !== undefined && stat.revision !== undefined && stat.revision !== null ? String(stat.revision) : "";
633
+ return `${size}:${revision}`;
634
+ }
635
+
636
+ /** The cached text of one session, or null when it is missing or stale. */
637
+ async function readSearchCache(directory, sessionId) {
638
+ try {
639
+ const raw = await readFile(join(directory, `${sessionId}.json`), "utf8");
640
+ const parsed = JSON.parse(raw);
641
+ if (parsed === null || typeof parsed !== "object") return null;
642
+ if (parsed.v !== SEARCH_INDEX_VERSION || typeof parsed.key !== "string" || !Array.isArray(parsed.messages)) return null;
643
+ return parsed;
644
+ } catch {
645
+ return null;
646
+ }
647
+ }
648
+
649
+ async function writeSearchCache(directory, sessionId, payload) {
650
+ try {
651
+ await mkdir(directory, { recursive: true });
652
+ const target = join(directory, `${sessionId}.json`);
653
+ const temporary = `${target}.${process.pid}.tmp`;
654
+ await writeFile(temporary, JSON.stringify(payload), "utf8");
655
+ await rename(temporary, target);
656
+ } catch {
657
+ /* the cache is best effort: a failed write only costs a re-decode */
658
+ }
659
+ }
660
+
661
+ /**
662
+ * The prose of one message.
663
+ *
664
+ * Deliberately narrower than `blockText`: reasoning and tool-call arguments are
665
+ * not conversation text, and indexing them would make the search hit things the
666
+ * user never read.
667
+ */
668
+ function conversationText(content) {
669
+ if (typeof content === "string") return content;
670
+ if (!Array.isArray(content)) return "";
671
+ const parts = [];
672
+ for (const block of content) {
673
+ if (block === null || typeof block !== "object") continue;
674
+ if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
675
+ }
676
+ return parts.join("\n");
677
+ }
678
+
679
+ /**
680
+ * One session's searchable transcript.
681
+ *
682
+ * Turns come from `data.turn` when the event carries it and from the running
683
+ * `turn/start` count otherwise, so a hit can name the turn the chat view uses
684
+ * for its own anchors.
685
+ */
686
+ function extractSearchMessages(events) {
687
+ const messages = [];
688
+ let turn = 0;
689
+ for (const event of events) {
690
+ if (event === null || typeof event !== "object") continue;
691
+ if (event.type === "turn/start") {
692
+ turn += 1;
693
+ continue;
694
+ }
695
+ if (event.type !== "user/message" && event.type !== "assistant/message") continue;
696
+ const data = event.data ?? {};
697
+ const content = data.message !== null && data.message !== undefined ? data.message.content : data.content;
698
+ let text = conversationText(content).trim();
699
+ if (text === "") continue;
700
+ if (text.length > SEARCH_MESSAGE_CAP) text = text.slice(0, SEARCH_MESSAGE_CAP);
701
+ const declared = Number(data.turn);
702
+ messages.push({
703
+ turn: Number.isSafeInteger(declared) ? declared : turn,
704
+ seq: Number.isSafeInteger(Number(event.seq)) ? Number(event.seq) : 0,
705
+ at: Number.isFinite(Number(event.time)) ? Number(event.time) : 0,
706
+ role: event.type === "user/message" ? "user" : "assistant",
707
+ text,
708
+ });
709
+ }
710
+ return messages;
711
+ }
712
+
713
+ function searchSnippet(text, needle) {
714
+ const haystack = text.toLowerCase();
715
+ const index = needle === "" ? -1 : haystack.indexOf(needle);
716
+ if (index < 0) return { snippet: text.slice(0, 160), lead: true, tail: text.length > 160 };
717
+ const start = Math.max(0, index - 60);
718
+ const end = Math.min(text.length, index + needle.length + 120);
719
+ const body = text.slice(start, end).replace(/\s+/g, " ").trim();
720
+ return { snippet: body, lead: start > 0, tail: end < text.length };
721
+ }
722
+
723
+ /**
724
+ * Search every session's transcript.
725
+ *
726
+ * `terms` are the whitespace-separated pieces of the query; all of them have to
727
+ * appear in the same message, so a two-word query narrows instead of widening.
728
+ */
729
+ export async function searchSessions(ctx, query, options = {}) {
730
+ const started = Date.now();
731
+ const terms = String(query ?? "").toLowerCase().split(/\s+/).filter((term) => term !== "");
732
+ if (terms.length === 0) return { ok: true, query: "", terms: [], hits: [], scanned: 0, total: 0, pending: 0, took: 0 };
733
+
734
+ const directory = await searchIndexDirectory();
735
+ const workspaces = typeof ctx.workspaceRegistry?.list === "function" ? ctx.workspaceRegistry.list() : [];
736
+ const workspaceByPath = new Map();
737
+ for (const workspace of Array.isArray(workspaces) ? workspaces : []) {
738
+ const path = normalizedPath(workspace?.path ?? workspace?.cwd);
739
+ if (path !== "") workspaceByPath.set(path, typeof workspace.name === "string" ? workspace.name : workspace.title || "");
740
+ }
741
+
742
+ let snapshots = [];
743
+ try {
744
+ snapshots = await ctx.sessionPersistence.list();
745
+ } catch {
746
+ snapshots = [];
747
+ }
748
+ const sessions = [];
749
+ for (const snapshot of Array.isArray(snapshots) ? snapshots : []) {
750
+ const header = snapshot?.header;
751
+ if (header === null || header === undefined || typeof header.id !== "string") continue;
752
+ sessions.push({ id: header.id, header, sizeBytes: Number(snapshot.sizeBytes) || 0, updatedAt: Number(header.updatedAt ?? header.createdAt ?? 0) });
753
+ }
754
+ sessions.sort((a, b) => b.updatedAt - a.updatedAt);
755
+
756
+ const refresh = options.refresh === true;
757
+ const hits = [];
758
+ let scanned = 0;
759
+ let pending = 0;
760
+ let decoded = 0;
761
+
762
+ for (const session of sessions) {
763
+ if (hits.length >= SEARCH_TOTAL_CAP) break;
764
+ scanned += 1;
765
+ let stat = null;
766
+ try {
767
+ stat = await ctx.sessionPersistence.stat(session.id);
768
+ } catch {
769
+ stat = null;
770
+ }
771
+ const key = searchCacheKey(stat);
772
+ let cached = refresh ? null : await readSearchCache(directory, session.id);
773
+ if (cached !== null && cached.key !== key) cached = null;
774
+ if (cached === null) {
775
+ if (decoded >= SEARCH_NEW_PER_QUERY || Date.now() - started > SEARCH_BUDGET_MS) {
776
+ pending += 1;
777
+ continue;
778
+ }
779
+ decoded += 1;
780
+ let messages = [];
781
+ try {
782
+ messages = extractSearchMessages(await readSessionEvents(ctx, session.id));
783
+ } catch {
784
+ messages = [];
785
+ }
786
+ await writeSearchCache(directory, session.id, { v: SEARCH_INDEX_VERSION, key, messages });
787
+ cached = { key, messages };
788
+ }
789
+
790
+ let found = 0;
791
+ for (const message of cached.messages) {
792
+ if (message === null || typeof message !== "object" || typeof message.text !== "string") continue;
793
+ const haystack = message.text.toLowerCase();
794
+ if (!terms.every((term) => haystack.indexOf(term) !== -1)) continue;
795
+ const { snippet, lead, tail } = searchSnippet(message.text, terms[0]);
796
+ const title = session.header.title ?? "";
797
+ const cwd = normalizedPath(session.header.cwd);
798
+ hits.push({
799
+ sessionId: session.id,
800
+ title: typeof title === "string" && title.trim() !== "" ? title.trim() : titleFromMessages(cached.messages, session.id),
801
+ workspace: workspaceByPath.get(cwd) ?? "",
802
+ cwd: typeof session.header.cwd === "string" ? session.header.cwd : "",
803
+ turn: message.turn,
804
+ seq: message.seq,
805
+ at: message.at,
806
+ role: message.role,
807
+ snippet,
808
+ lead: lead === true,
809
+ tail: tail === true,
810
+ });
811
+ found += 1;
812
+ if (found >= SEARCH_PER_SESSION || hits.length >= SEARCH_TOTAL_CAP) break;
813
+ }
814
+ }
815
+
816
+ hits.sort((a, b) => b.at - a.at);
817
+ return {
818
+ ok: true,
819
+ query: String(query ?? "").trim(),
820
+ terms,
821
+ hits,
822
+ scanned: sessions.length,
823
+ total: sessions.length,
824
+ pending,
825
+ decoded,
826
+ took: Date.now() - started,
827
+ };
828
+ }
829
+
830
+ /** First prompt line, the same fallback the sidebar uses for an untitled session. */
831
+ function titleFromMessages(messages, sessionId) {
832
+ for (const message of Array.isArray(messages) ? messages : []) {
833
+ if (message?.role !== "user" || typeof message.text !== "string") continue;
834
+ const first = message.text.split("\n")[0].trim();
835
+ if (first !== "") return first.slice(0, 80);
836
+ }
837
+ return sessionId;
838
+ }
839
+
602
840
  /** Statistics for one session, cached briefly so re-opening the panel is cheap. */
603
- export async function sessionStatistics(ctx, sessionId) {
604
- let stat;
841
+ export async function sessionStatistics(ctx, sessionId) { let stat;
605
842
  try {
606
843
  stat = await ctx.sessionPersistence.stat(sessionId);
607
844
  } catch {
@@ -1656,6 +1893,26 @@ export async function handleMoveRequest(ctx, req, res) {
1656
1893
  }
1657
1894
  }
1658
1895
 
1896
+ /** POST { query, refresh? } -> matching snippets across every session's transcript. */
1897
+ export async function handleSearchRequest(ctx, req, res) {
1898
+ if ((req.method ?? "POST").toUpperCase() !== "POST") {
1899
+ sendJson(res, 405, { ok: false, error: "method not allowed" });
1900
+ return;
1901
+ }
1902
+ if (!loopbackOrigin(req)) {
1903
+ sendJson(res, 403, { ok: false, error: "origin not trusted" });
1904
+ return;
1905
+ }
1906
+ try {
1907
+ const body = await readJsonBody(req);
1908
+ const query = body !== null && typeof body.query === "string" ? body.query : "";
1909
+ const result = await searchSessions(ctx, query, { refresh: body !== null && body.refresh === true });
1910
+ sendJson(res, 200, result);
1911
+ } catch (error) {
1912
+ sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
1913
+ }
1914
+ }
1915
+
1659
1916
  /** POST { sessionId } -> token statistics for that session. */
1660
1917
  export async function handleStatsRequest(ctx, req, res) {
1661
1918
  if ((req.method ?? "POST").toUpperCase() !== "POST") {
@@ -1701,7 +1958,7 @@ export function apply(ctx) {
1701
1958
  handler: (req, res) => sendJson(res, 200, {
1702
1959
  ok: true,
1703
1960
  version: HOST_VERSION,
1704
- routes: { stats: statsMounted, trash: trashMounted, move: moveMounted },
1961
+ routes: { stats: statsMounted, trash: trashMounted, move: moveMounted, search: searchMounted },
1705
1962
  }),
1706
1963
  }), "ws-recency: health route");
1707
1964
 
@@ -1733,6 +1990,15 @@ export function apply(ctx) {
1733
1990
  }), "ws-recency: adopt route");
1734
1991
  });
1735
1992
 
1993
+ webCtx.inject(["sessionPersistence", "workspaceRegistry"], (searchCtx) => {
1994
+ searchMounted = true;
1995
+ webCtx.effect(() => server.register({
1996
+ kind: "exact",
1997
+ path: SEARCH_CONTENT_PATH,
1998
+ handler: (req, res) => handleSearchRequest(searchCtx, req, res),
1999
+ }), "ws-recency: search route");
2000
+ });
2001
+
1736
2002
  webCtx.inject(["sessionPersistence"], (handoffCtx) => {
1737
2003
  webCtx.effect(() => server.register({
1738
2004
  kind: "exact",
@@ -1758,3 +2024,4 @@ export function apply(ctx) {
1758
2024
  let statsMounted = false;
1759
2025
  let trashMounted = false;
1760
2026
  let moveMounted = false;
2027
+ let searchMounted = false;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-ws-recency",
3
- "version": "0.25.1",
4
- "description": "Sidebar session management for DeepSeek Harness: workspace groups sorted by latest activity, stale history folded, a global pinned section, follow-up marks, session delete into a recoverable trash, archived sessions managed from that same trash panel, per-session token statistics with an argument/result split and an option to count tool arguments as the agent's writing, and moving a session to another workspace.",
3
+ "version": "0.26.0",
4
+ "description": "Sidebar session management for DeepSeek Harness: workspace groups sorted by latest activity, stale history folded, a global pinned section, follow-up marks, session delete into a recoverable trash, archived sessions managed from that same trash panel, per-session token statistics with an argument/result split and an option to count tool arguments as the agent's writing, moving a session to another workspace, and a literal content search that jumps to the turn a word was said in.",
5
5
  "license": "MIT",
6
6
  "author": "chyxhtc",
7
7
  "repository": {