dsh-ws-recency 0.25.0 → 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 +16 -2
  2. package/client.js +367 -8
  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
 
@@ -45,6 +45,7 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
45
45
  - 用的是**宿主原生置顶集合**,不是第二套置顶:会话「…」菜单里的置顶/取消置顶照旧;
46
46
  - 置顶区每行显示标题 + 所属工作区名,点行直接打开;hover 出现「取消置顶」;
47
47
  - 置顶期间它在原工作区分组里的那一行**隐藏**(不重复出现),取消置顶后原行回到原位;
48
+ - 置顶行沿用同一套状态色(运行中蓝 / 完成未读绿 / 需要跟进琥珀),运行状态变化即时更新(0.25.1 修);
48
49
  - 工作区分组、组内顺序、折叠、颜色全部照旧;
49
50
  - 只在按工作区分组时出现;搜索、扁平视图、侧栏收起时自动隐藏。
50
51
 
@@ -145,6 +146,16 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
145
146
  卡片只在**这一轮结束之后**才出现(0.24.2 修):轮询会比对回复的日志序号与「本轮是否还在跑」,只认点击之后产生、且已经收尾的那条回复——之前它读的是「全日志最后一条非空回复」,只要新轮先落一条工具步骤,就会把上一轮里的旧交接块当成答案,交接刚开始还在处理就弹卡;卡片也只挂在产生它的那一轮下面,不再在每个旧轮下面重复出现。
146
147
 
147
148
 
149
+ ## 九、会话内容搜索
150
+
151
+ 会话一长,靠滚动是找不回来的。侧栏的放大镜打开搜索页,输词回车:
152
+
153
+ - 搜的是**对话正文**:你的提问 + 助手的回复;不搜思维链、不搜工具参数和工具结果(那些会让命中被日志噪声淹没);
154
+ - 多个词用空格分隔,**要求同时出现在同一条消息里**(AND);大小写不敏感,纯字面匹配,不支持正则;
155
+ - 结果按新到旧排列,每条给出角色、会话标题、所属工作区、第几轮,以及带高亮的片段;
156
+ - 点一条结果:打开那个会话 → 滚到对应那一轮 → 闪一下蓝色描边。老会话的历史是懒加载的,插件会自己往上翻直到那一轮出现,最多等 8 秒;
157
+ - 第一次搜索要为每个会话建一次正文索引(存在 `~/.hypers-work/.wsr/search/<sessionId>.json`,按日志大小 + revision 决定是否失效)。面板顶部会显示「还有 N 个会话正在建立索引」,每轮补一批、结果自动刷新,之后同一份日志不再重复解码。
158
+
148
159
  ## 设置
149
160
 
150
161
  **设置 → 通用**:
@@ -163,6 +174,9 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
163
174
  - “未分组”桶永远排在真实工作区之后。
164
175
  - 只在按工作区分组(含工作区树顶层)时生效。
165
176
  - **可选互操作**:如果你另外装着 `dsh-plugin-busy-workspace`,本插件会尊重它写在分组上的 `data-busy-rank`,把它的紧急度当主键、档位内部再按活跃度排。没装就是纯最近活跃排序——本插件不依赖它。
177
+ - 搜索是**字面匹配**,不是全文检索:不支持正则、不排序相关性,结果只按时间倒序;正文外的内容(思维链、工具参数、工具结果、附件)不参与匹配。
178
+ - 搜索索引是插件自己的缓存(`~/.hypers-work/.wsr/search/`),删掉只会让下一次搜索重新建;宿主自带的 SQLite 全文索引默认关闭,本插件没有去改那个开关。
179
+ - 跳到某一轮靠宿主的 `data-chat-turn` 行和 `[data-conversation-scroll]` 滚动容器:宿主改这两个标识,跳转就会失效,搜索本身不受影响。
166
180
 
167
181
  ## 安装
168
182
 
@@ -181,7 +195,7 @@ dsh plugin --profile <profile> add github:chyxhtc/dsh-ws-recency
181
195
  或固定版本的预构建包:
182
196
 
183
197
  ```powershell
184
- dsh plugin --profile <profile> add https://github.com/chyxhtc/dsh-ws-recency/releases/download/v0.25.0/dsh-ws-recency-0.25.0.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
185
199
  ```
186
200
 
187
201
  装完把 `dsh-ws-recency` 加进 `~/.hypers-work/profiles/<profile>/package.json` 的 `dsh.profile.bundles`,重启应用。
package/client.js CHANGED
@@ -107,6 +107,9 @@
107
107
  ".wsr-pin-ws{flex:none;max-width:40%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:var(--dsw-alias-label-tertiary)}",
108
108
  ".wsr-pin-unpin{flex:none;border:none;background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer;font-size:11px;padding:2px 4px;border-radius:4px;visibility:hidden}",
109
109
  ".wsr-pin-row:hover .wsr-pin-unpin{visibility:visible}",
110
+ ".wsr-pin-row[" + STATE_ATTR + '="running"] .wsr-pin-title{color:#4f8ef7}',
111
+ ".wsr-pin-row[" + STATE_ATTR + '="unread"] .wsr-pin-title{color:#3fae6b}',
112
+ ".wsr-pin-row[" + STATE_ATTR + '="followup"] .wsr-pin-title{color:#d99a2b}',
110
113
  ".wsr-pin-unpin:hover{color:var(--dsw-alias-label-primary)}",
111
114
  ".wsr-pill{box-sizing:border-box;border:none;background:0 0;color:var(--dsw-alias-label-tertiary);font:inherit;font-variant-numeric:tabular-nums;line-height:inherit;white-space:nowrap;border-radius:var(--dsw-radius-sm,6px);display:inline-flex;align-items:center;gap:6px;padding:1px 8px;cursor:pointer}",
112
115
  ".wsr-pill:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08));color:var(--dsw-alias-label-secondary,#cfd3d8)}",
@@ -276,6 +279,20 @@
276
279
  '[' + STATE_ATTR + '="running"] [class*="_title"]{color:#4f8ef7}',
277
280
  '[' + STATE_ATTR + '="unread"] [class*="_title"]{color:#3fae6b}',
278
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}',
279
296
  ".wsr-dot{display:block;width:7px;height:7px;border-radius:50%;margin:0 auto;background:#d99a2b;cursor:pointer}",
280
297
  ".wsr-dot:hover{outline:2px solid var(--dsw-alias-border-l2)}",
281
298
  ".wsr-setRow{display:flex;align-items:center;gap:16px;justify-content:space-between;padding:12px 0}",
@@ -371,6 +388,17 @@
371
388
  "adopt.done": "已补登记 {n} 个会话。",
372
389
  "adopt.cleaned": "清理了 {n} 处重复/失效的工作区归属。",
373
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} 轮",
374
402
  "ui.reload": "刷新界面",
375
403
  "ui.refresh": "刷新列表",
376
404
  "trash.title": "回收站",
@@ -519,6 +547,17 @@
519
547
  "adopt.done": "Re-attached {n} session(s).",
520
548
  "adopt.cleaned": " Cleared {n} stale membership(s).",
521
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}",
522
561
  "ui.reload": "Reload UI",
523
562
  "ui.refresh": "Refresh",
524
563
  "trash.title": "Trash",
@@ -1090,10 +1129,11 @@
1090
1129
  return false;
1091
1130
  }
1092
1131
 
1093
- function pinnedRowElement(item) {
1132
+ function pinnedRowElement(item, state) {
1094
1133
  var row = document.createElement("div");
1095
1134
  row.className = "wsr-pin-row";
1096
1135
  row.setAttribute("data-row-key", "pin:" + item.id);
1136
+ setRowState(row, state === undefined ? null : state);
1097
1137
  var title = document.createElement("span");
1098
1138
  title.className = "wsr-pin-title";
1099
1139
  title.textContent = item.title;
@@ -1122,8 +1162,7 @@
1122
1162
  }
1123
1163
 
1124
1164
  /** Hide the copies inside their own groups so nothing is listed twice. */
1125
- function hideOriginalRows(entries, pinnedIds) {
1126
- for (var i = 0; i < entries.length; i += 1) {
1165
+ function hideOriginalRows(entries, pinnedIds) { for (var i = 0; i < entries.length; i += 1) {
1127
1166
  var rows = rowElements(entries[i].section);
1128
1167
  for (var j = 0; j < rows.length; j += 1) {
1129
1168
  var id = sessionIdOf(rows[j]);
@@ -1138,6 +1177,30 @@
1138
1177
  }
1139
1178
  }
1140
1179
 
1180
+ /** One session's running / unread / follow-up state, or null. */
1181
+ function statesOfId(states, id) {
1182
+ if (states === null || states === undefined || id === null || id === undefined || id === "") return null;
1183
+ var state = states[id];
1184
+ return state === undefined ? null : state;
1185
+ }
1186
+
1187
+ /**
1188
+ * Push the current state onto the pin rows already in the DOM.
1189
+ *
1190
+ * The section is rebuilt only when the pinned set or its labels change, so
1191
+ * a session that starts running has to be recoloured in place - otherwise
1192
+ * its row would keep the state it had when the section was last built.
1193
+ */
1194
+ function applyPinStates(host, states) {
1195
+ if (host === null || typeof host.querySelectorAll !== "function") return;
1196
+ var rows = host.querySelectorAll('[data-row-key^="pin:"]');
1197
+ for (var i = 0; i < rows.length; i += 1) {
1198
+ var key = rows[i].getAttribute("data-row-key");
1199
+ var id = key === null ? "" : key.slice("pin:".length);
1200
+ setRowState(rows[i], statesOfId(states, id));
1201
+ }
1202
+ }
1203
+
1141
1204
  /**
1142
1205
  * Render the "pinned" section above every workspace group.
1143
1206
  *
@@ -1145,7 +1208,7 @@
1145
1208
  * (flex order -1), rebuilt only when the pinned set or its labels change. The
1146
1209
  * host keeps owning the list; the workspace grouping below is untouched.
1147
1210
  */
1148
- function renderPinned(entries, sessions, workspaces, settings) {
1211
+ function renderPinned(entries, sessions, workspaces, settings, states) {
1149
1212
  if (typeof document === "undefined") return;
1150
1213
  var items = pinnedItemsOf(sessions, workspaces, settings);
1151
1214
 
@@ -1184,8 +1247,10 @@
1184
1247
  head.className = "wsr-pin-head";
1185
1248
  head.textContent = t("pin.head");
1186
1249
  pinHost.appendChild(head);
1187
- for (var i = 0; i < items.length; i += 1) pinHost.appendChild(pinnedRowElement(items[i]));
1250
+ for (var i = 0; i < items.length; i += 1) pinHost.appendChild(pinnedRowElement(items[i], statesOfId(states, items[i].id)));
1188
1251
  }
1252
+ /* The state can change while the pinned set stays the same. */
1253
+ applyPinStates(pinHost, states);
1189
1254
  var pinnedIds = new Set(items.map(function (item) { return item.id; }));
1190
1255
  hideOriginalRows(entries, pinnedIds);
1191
1256
  }
@@ -1217,7 +1282,13 @@
1217
1282
  * is never inferred, and only an explicit clear removes it. Running and
1218
1283
  * unread outrank it on screen; once they pass, amber comes back.
1219
1284
  */
1220
- function decorateRows(entries, sessions, statuses, settings) {
1285
+ /**
1286
+ * running / unread / follow-up per session id.
1287
+ *
1288
+ * Both the host's rows and the plugin's own pinned rows read this, so a
1289
+ * pinned session keeps the same colour it had inside its group.
1290
+ */
1291
+ function statesOf(sessions, statuses, settings) {
1221
1292
  var flags = settings.followUps;
1222
1293
  var byId = sessions.byId || {};
1223
1294
  var states = {};
@@ -1238,7 +1309,10 @@
1238
1309
  var flagged = flags[id] !== undefined;
1239
1310
  states[id] = running ? "running" : unread ? "unread" : flagged ? "followup" : null;
1240
1311
  }
1312
+ return states;
1313
+ }
1241
1314
 
1315
+ function decorateRows(entries, states) {
1242
1316
  for (var i = 0; i < entries.length; i += 1) {
1243
1317
  var rows = rowElements(entries[i].section);
1244
1318
  for (var j = 0; j < rows.length; j += 1) {
@@ -1425,8 +1499,9 @@
1425
1499
 
1426
1500
  orderGroups(entries, latestByWorkspace(sessions, workspaces));
1427
1501
  foldRows(entries, settings, sessions, Date.now());
1428
- renderPinned(entries, sessions, workspaces, settings);
1429
- if (settings.colors) decorateRows(entries, sessions, data.statuses, settings);
1502
+ var states = settings.colors ? statesOf(sessions, data.statuses, settings) : null;
1503
+ renderPinned(entries, sessions, workspaces, settings, states);
1504
+ if (states !== null) decorateRows(entries, states);
1430
1505
  decorateComposerStats();
1431
1506
  }
1432
1507
 
@@ -3171,6 +3246,263 @@
3171
3246
  });
3172
3247
  }
3173
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
+
3174
3506
  /** The sidebar's trash entry glyph. */
3175
3507
  function TrashPanelIcon(props) {
3176
3508
  var Icon = ui.IconTrashOutlineRegular;
@@ -3650,6 +3982,24 @@
3650
3982
  }, ColorsRow);
3651
3983
  });
3652
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
+
3653
4003
  ctx.slots.inject("sidebar.panellist", function () {
3654
4004
  return ctx.slots.register({
3655
4005
  name: "sidebar.panellist",
@@ -3788,6 +4138,15 @@
3788
4138
  send: sendToSession,
3789
4139
  };
3790
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
+
3791
4150
  exports.name = "dsh-ws-recency";
3792
4151
  exports.inject = inject;
3793
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.0";
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.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, 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": {