dsh-ws-recency 0.30.2 → 0.31.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 +5 -2
  2. package/client.js +75 -193
  3. package/index.js +129 -7
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -167,8 +167,11 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
167
167
 
168
168
  - 搜的是**对话正文**:你的提问 + 助手的回复;不搜思维链、不搜工具参数和工具结果(那些会让命中被日志噪声淹没);
169
169
  - 多个词用空格分隔,**要求同时出现在同一条消息里**(AND);大小写不敏感,纯字面匹配,不支持正则;
170
- - 结果按新到旧排列,每条给出角色、会话标题、所属工作区、第几轮,以及带高亮的片段;
171
- - 点一条结果:打开那个会话 → 滚到对应那一轮 → 闪一下蓝色描边。老会话的历史是懒加载的,插件会自己往上翻直到那一轮出现,最多等 8 秒;
170
+ - 查询里还可以写:`"一个词组"`(整句匹配)、`a|b` 或 `a or b`(任一即可)、`-词`(排除)、`ws:工作区`、`in:会话标题`、`role:user|assistant`(过滤范围而不是文本)。中文别名 `工作区:` / `会话:` / `角色:` 同样可用;
171
+ - 结果按新到旧排列,每条给出角色、会话标题、所属工作区、第几轮/第几步,以及带高亮的片段;
172
+ - 每条结果有两个动作:`看上下文` 在行内展开命中处前后各约 400 字(不碰聊天区,长会话也不卡),`打开会话` 才真的跳转;
173
+ - 搜索过的词会记进「最近搜索」,点一下重搜、点 × 删一条、右侧「清空」全清,重启后还在。
174
+ - 点「打开会话」:打开那个会话 → 点右侧竖条上对应轮次的格子(这是宿主自己的跳转入口,会连带加载那一段历史)→ 关键词在正文里高亮。**跳转本身可能等几秒到十几秒**,那是宿主加载历史的时间;插件自己在浮标里报的那点是几十毫秒级。
172
175
  - 第一次搜索要为每个会话建一次正文索引(存在 `~/.hypers-work/.wsr/search/<sessionId>.json`,按日志大小 + revision 决定是否失效)。面板顶部会显示「还有 N 个会话正在建立索引」,每轮补一批、结果自动刷新,之后同一份日志不再重复解码。
173
176
 
174
177
  ## 设置
package/client.js CHANGED
@@ -362,6 +362,7 @@
362
362
  ".wsr-hit-context-toggle,.wsr-hit-context-jump{border:.5px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));background:0 0;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:11px;line-height:18px;padding:0 8px;border-radius:9px;cursor:pointer}",
363
363
  ".wsr-hit-context-toggle:hover,.wsr-hit-context-jump:hover{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l3,rgba(255,255,255,.24))}",
364
364
  ".wsr-hit-context{max-height:38vh;overflow:auto;margin-top:4px;padding:6px 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.04));color:var(--dsw-alias-label-secondary);font-size:11px;line-height:1.65;white-space:pre-wrap;word-break:break-word}",
365
+ ".wsr-search-hint{font-size:11px;line-height:1.5;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums}",
365
366
  ".wsr-search-history{display:flex;align-items:center;flex-wrap:wrap;gap:6px;font-size:11px;color:var(--dsw-alias-label-tertiary)}",
366
367
  ".wsr-search-history-label{flex:none}",
367
368
  ".wsr-search-chip{display:inline-flex;align-items:center;border-radius:9px;background:var(--dsw-alias-bg-layer-3,rgba(255,255,255,.07));overflow:hidden}",
@@ -511,6 +512,7 @@
511
512
  "search.contextShow": "看上下文",
512
513
  "search.contextHide": "收起",
513
514
  "search.openSession": "打开会话",
515
+ "search.hint": "空格=都要有 · \"词组\" · a|b 或 · -排除 · ws:工作区 · in:会话 · role:user",
514
516
  "search.history": "最近搜索",
515
517
  "search.historyRun": "再搜一次:{query}",
516
518
  "search.historyDrop": "从历史里删除",
@@ -578,6 +580,10 @@
578
580
  "stats.argModeNote": "当前把工具参数计入主 agent:每个工具只算返回结果,表格里「参数」列显示为淡色(那些 token 记在主 agent 那一行)。",
579
581
  "stats.amplified.title": "放大成本(账单归因)",
580
582
  "stats.amplified.kindTitle": "账单构成",
583
+ "stats.amplified.repeatTitle": "重复读取合计",
584
+ "stats.amplified.repeatMeta": "{count} 次 · 合计 {tokens}",
585
+ "stats.amplified.repeatTitle": "Repeated reads",
586
+ "stats.amplified.repeatMeta": "{count} times · {tokens} total",
581
587
  "stats.amplified.lead": "按「内容大小 × 之后重读次数」排序:一块内容读进来一次,之后每一步都会再发一遍,乘上重读次数才是它真正的开销。上面的分布统计只算内容本身多大,两个数不能直接比。",
582
588
  "stats.amplified.summary": "账单 {bill} token;可归因内容经重读放大后占 {share}({attributed})",
583
589
  "stats.amplified.contextCaption": "每步上下文(面积≈账单):一步=一次模型调用,越早进入的内容被重读越多",
@@ -712,6 +718,7 @@
712
718
  "search.contextShow": "Show context",
713
719
  "search.contextHide": "Hide",
714
720
  "search.openSession": "Open session",
721
+ "search.hint": "space = all of them · \"phrase\" · a|b either · -exclude · ws:workspace · in:session · role:user",
715
722
  "search.history": "Recent",
716
723
  "search.historyRun": "Search again: {query}",
717
724
  "search.historyDrop": "Remove from history",
@@ -1168,7 +1175,20 @@
1168
1175
  var hostButton = overflowButtonOf(section);
1169
1176
  markHeader(entry.header, entry.key);
1170
1177
 
1171
- var expanded = expandedSections.has(entry.key);
1178
+ /* Everything this project holds is history: no session inside it is
1179
+ recent, so the user's expansion of the project is itself the
1180
+ request to see its sessions. Folding here only adds a second click
1181
+ for a group the user has already gone looking for. */
1182
+ var onlyHistory = rows.length > 0;
1183
+ for (var scan = 0; scan < rows.length; scan += 1) {
1184
+ var scannedAt = updatedAtOf(rows[scan], sessions);
1185
+ var covers = scannedAt === null || scannedAt >= cutoff;
1186
+ if (covers && !isBlankRow(rows[scan], sessions)) {
1187
+ onlyHistory = false;
1188
+ break;
1189
+ }
1190
+ }
1191
+ var expanded = expandedSections.has(entry.key) || onlyHistory;
1172
1192
  var hostHidden = hostButton === null ? 0 : labelNumber(hostButton);
1173
1193
  var hostExpanded = hostButton !== null
1174
1194
  && typeof hostButton.getAttribute === "function"
@@ -1217,7 +1237,9 @@
1217
1237
  folded. Expanding drives the hidden host button until nothing is left
1218
1238
  unrendered, so one click reveals the whole group. */
1219
1239
  var remaining = folded + hostHidden;
1220
- if (expanded) {
1240
+ /* A project that is entirely history is open because opening it is the
1241
+ request; there is nothing to offer to fold back. */
1242
+ if (expanded && !onlyHistory) {
1221
1243
  (function (entryKey) {
1222
1244
  ensureToggle(section, entryKey, t("fold.hide"), function () {
1223
1245
  expandedSections.delete(entryKey);
@@ -2311,6 +2333,28 @@
2311
2333
  /** The neutral an unknown tool gets: no family, no claim of one. */
2312
2334
  var TOOL_FAMILY_NEUTRAL = { key: "other", hue: 210 };
2313
2335
 
2336
+ /**
2337
+ * A stable hue for a tool that belongs to no family.
2338
+ *
2339
+ * Every unknown tool used to share the neutral hue, so the chart showed
2340
+ * several tools in one colour. A hash of the name spreads them out, and a
2341
+ * nudge keeps the result clear of the family hues it would otherwise
2342
+ * collide with.
2343
+ */
2344
+ function hueOfUnknown(name) {
2345
+ var hash = 2166136261;
2346
+ for (var i = 0; i < name.length; i += 1) {
2347
+ hash ^= name.charCodeAt(i);
2348
+ hash = Math.imul(hash, 16777619) >>> 0;
2349
+ }
2350
+ var hue = hash % 360;
2351
+ for (var f = 0; f < TOOL_FAMILIES.length; f += 1) {
2352
+ var distance = Math.abs(hue - TOOL_FAMILIES[f].hue);
2353
+ if (distance < 16 || distance > 344) hue = (hue + 41) % 360;
2354
+ }
2355
+ return hue;
2356
+ }
2357
+
2314
2358
  function toolFamily(name) {
2315
2359
  if (typeof name !== "string" || name === "") return TOOL_FAMILY_NEUTRAL;
2316
2360
  var key = name.toLowerCase();
@@ -2699,6 +2743,31 @@
2699
2743
  list.appendChild(row);
2700
2744
  }
2701
2745
  ranking.appendChild(list);
2746
+
2747
+ /* Repetition is the actionable part: reading one file twice costs the
2748
+ same as two files, and the list above shows it as two rows. */
2749
+ var repeated = amplified.repeated || [];
2750
+ if (repeated.length > 0) {
2751
+ ranking.appendChild(statsDiv("wsr-amplified-subtitle", t("stats.amplified.repeatTitle")));
2752
+ var repeats = statsDiv("wsr-amplified-list");
2753
+ for (var rp = 0; rp < repeated.length; rp += 1) {
2754
+ var item = repeated[rp];
2755
+ var row = statsDiv("wsr-amplified-row");
2756
+ var main = statsDiv("wsr-amplified-main");
2757
+ main.appendChild(statsDiv("wsr-amplified-name", typeof item.detail === "string" ? item.detail : ""));
2758
+ main.appendChild(statsDiv("wsr-amplified-meta", t("stats.amplified.repeatMeta", {
2759
+ count: String(item.count),
2760
+ tokens: formatTokens(item.tokens),
2761
+ })));
2762
+ row.appendChild(main);
2763
+ var value = statsDiv("wsr-amplified-value", formatTokens(item.amplified));
2764
+ value.setAttribute("title", String(Math.round(Number(item.amplified) || 0)) + " tokens");
2765
+ row.appendChild(value);
2766
+ row.appendChild(statsDiv("wsr-amplified-share", formatShare(item.share || 0)));
2767
+ repeats.appendChild(row);
2768
+ }
2769
+ ranking.appendChild(repeats);
2770
+ }
2702
2771
  return { top: section, ranking: ranking };
2703
2772
  }
2704
2773
 
@@ -3815,149 +3884,7 @@
3815
3884
  }
3816
3885
  }
3817
3886
 
3818
- /** Modal: list the plugin's trash, restore an entry or delete it for good. */
3819
- function openTrashPanel() {
3820
- if (typeof document === "undefined") return;
3821
- closeStatsPanel();
3822
- var backdrop = statsDiv("wsr-modal-backdrop");
3823
- var panel = statsDiv("wsr-modal");
3824
- backdrop.appendChild(panel);
3825
- var head = statsDiv("wsr-modal-head");
3826
- head.appendChild(statsDiv("wsr-modal-title", t("trash.title")));
3827
- var tools = statsDiv("wsr-modal-tools");
3828
- var adopt = document.createElement("button");
3829
- adopt.type = "button";
3830
- adopt.className = "wsr-btn";
3831
- adopt.title = t("adopt.description");
3832
- adopt.textContent = t("adopt.action");
3833
- tools.appendChild(adopt);
3834
- var close = document.createElement("button");
3835
- close.type = "button";
3836
- close.className = "wsr-modal-close";
3837
- close.textContent = "\u00d7";
3838
- close.addEventListener("click", closeStatsPanel);
3839
- tools.appendChild(close);
3840
- head.appendChild(tools);
3841
- panel.appendChild(head);
3842
- var body = statsDiv("wsr-modal-body");
3843
- panel.appendChild(body);
3844
- backdrop.addEventListener("click", function (event) {
3845
- if (event !== undefined && event.target === backdrop) closeStatsPanel();
3846
- });
3847
- document.body.appendChild(backdrop);
3848
- statsModal = backdrop;
3849
- document.addEventListener("keydown", onStatsKey);
3850
-
3851
- var post = function (payload) {
3852
- return fetch("/ws-recency/trash", {
3853
- method: "POST",
3854
- headers: { "content-type": "application/json" },
3855
- body: JSON.stringify(payload),
3856
- }).then(function (response) {
3857
- return response.text().then(function (text) {
3858
- var parsed = null;
3859
- try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
3860
- return { status: response.status, text: text, json: parsed };
3861
- });
3862
- });
3863
- };
3864
-
3865
- var load = function (note) {
3866
- body.textContent = t("trash.loading");
3867
- post({ action: "list" }).then(function (answer) {
3868
- body.textContent = "";
3869
- if (note !== undefined && note !== "") {
3870
- body.appendChild(statsDiv("wsr-stats-detail", note));
3871
- var noteActions = statsDiv("wsr-trash-actions");
3872
- noteActions.appendChild(reloadButton());
3873
- body.appendChild(noteActions);
3874
- }
3875
- if (answer.json === null || answer.json.ok !== true) {
3876
- body.appendChild(statsDiv("wsr-stats-note", t("trash.failed") + "HTTP " + answer.status + " \u00b7 " + (answer.text || "").slice(0, 120)));
3877
- return;
3878
- }
3879
- var entries = Array.isArray(answer.json.entries) ? answer.json.entries : [];
3880
- if (entries.length === 0) {
3881
- body.appendChild(statsDiv("wsr-stats-note", t("trash.empty")));
3882
- return;
3883
- }
3884
- var list = statsDiv("wsr-move-list");
3885
- for (var i = 0; i < entries.length; i += 1) {
3886
- (function (entry) {
3887
- var row = document.createElement("div");
3888
- row.className = "wsr-trash-row";
3889
- var text = statsDiv("wsr-move-text");
3890
- var title = entry.sessionId === null ? entry.name : entry.sessionId;
3891
- text.appendChild(statsDiv("wsr-move-title", title));
3892
- var meta = [];
3893
- if (entry.reason === "delete") meta.push(t("trash.reason.delete"));
3894
- else if (entry.reason === "move") meta.push(t("trash.reason.move"));
3895
- meta.push(formatBytes(entry.sizeBytes));
3896
- var when = formatWhen(entry.at);
3897
- if (when !== "") meta.push(when);
3898
- text.appendChild(statsDiv("wsr-move-path", meta.join(" \u00b7 ")));
3899
- if (typeof entry.cwd === "string" && entry.cwd !== "") {
3900
- text.appendChild(statsDiv("wsr-move-path", entry.cwd));
3901
- }
3902
- row.appendChild(text);
3903
-
3904
- var actions = statsDiv("wsr-trash-actions");
3905
- if (entry.restorable === true) {
3906
- var restore = document.createElement("button");
3907
- restore.type = "button";
3908
- restore.className = "wsr-btn";
3909
- restore.textContent = t("trash.restore");
3910
- restore.addEventListener("click", function () {
3911
- askConfirm(t("trash.confirmRestore"), function () {
3912
- load(t("trash.working"));
3913
- post({ action: "restore", name: entry.name }).then(function (result) {
3914
- var ok = result.json !== null && result.json.ok === true;
3915
- load(ok ? t("trash.restored") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3916
- }).catch(function (error) {
3917
- load(t("trash.failed") + (error && error.message ? error.message : error));
3918
- });
3919
- });
3920
- });
3921
- actions.appendChild(restore);
3922
- }
3923
- var purge = document.createElement("button");
3924
- purge.type = "button";
3925
- purge.className = "wsr-btn wsr-btn-danger";
3926
- purge.textContent = t("trash.purge");
3927
- purge.addEventListener("click", function () {
3928
- askConfirm(t("trash.confirmPurge"), function () {
3929
- load(t("trash.working"));
3930
- post({ action: "purge", name: entry.name }).then(function (result) {
3931
- var ok = result.json !== null && result.json.ok === true;
3932
- load(ok ? t("trash.purged") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3933
- }).catch(function (error) {
3934
- load(t("trash.failed") + (error && error.message ? error.message : error));
3935
- });
3936
- });
3937
- });
3938
- actions.appendChild(purge);
3939
- row.appendChild(actions);
3940
- list.appendChild(row);
3941
- })(entries[i]);
3942
- }
3943
- body.appendChild(list);
3944
- body.appendChild(statsDiv("wsr-stats-note", t("trash.note")));
3945
- }).catch(function (error) {
3946
- body.textContent = t("trash.failed") + (error && error.message ? error.message : error);
3947
- });
3948
- };
3949
- adopt.addEventListener("click", function () {
3950
- adopt.disabled = true;
3951
- adopt.textContent = t("adopt.working");
3952
- adoptUnlistedSessions(function (message) {
3953
- adopt.disabled = false;
3954
- adopt.textContent = t("adopt.action");
3955
- load(message);
3956
- });
3957
- });
3958
- load("");
3959
- }
3960
-
3887
+
3961
3888
  /* --------------------------- trash panel page ------------------------ */
3962
3889
 
3963
3890
  function trashPost(payload) {
@@ -4847,7 +4774,8 @@
4847
4774
  },
4848
4775
  }, t("search.historyClear")),
4849
4776
  ),
4850
- h("div", { className: "wsr-search-bar" },
4777
+ h("div", { className: "wsr-search-hint" }, t("search.hint")),
4778
+ h("div", { className: "wsr-search-bar" },
4851
4779
  input,
4852
4780
  h("button", { type: "button", className: "wsr-btn", onClick: function () { run(searchDraft, false); } }, t("search.run")),
4853
4781
  ),
@@ -5148,53 +5076,7 @@
5148
5076
  );
5149
5077
  }
5150
5078
 
5151
- /**
5152
- * Sidebar footer action: the trash, one click away from the account area.
5153
- *
5154
- * Geometry is the same house rule the official launchers follow
5155
- * (`dshUpdateLauncher` / `dshMarketLauncher`): full-width seat bled 2px
5156
- * per side, 42px tall, 12px radius. `wide` comes from the slot, so the
5157
- * narrow rail keeps its 36px circle instead of a stretched row.
5158
- */
5159
- function TrashFooterAction(props) {
5160
- var wide = props === undefined || props === null || props.wide !== false;
5161
- var label = t("trash.title");
5162
- var Icon = ui.IconTrashOutlineRegular;
5163
- return h("button", {
5164
- type: "button",
5165
- className: "wsr-footer-action",
5166
- title: label,
5167
- "aria-label": label,
5168
- "aria-haspopup": "dialog",
5169
- style: {
5170
- boxSizing: "border-box",
5171
- width: "100%",
5172
- alignSelf: "stretch",
5173
- display: "flex",
5174
- alignItems: "center",
5175
- justifyContent: "flex-start",
5176
- gap: "10px",
5177
- minHeight: "40px",
5178
- padding: "0 10px",
5179
- border: "none",
5180
- background: "transparent",
5181
- color: "var(--dsw-alias-label-primary)",
5182
- borderRadius: "10px",
5183
- font: "inherit",
5184
- fontSize: "14px",
5185
- lineHeight: "22px",
5186
- cursor: "pointer",
5187
- textAlign: "left",
5188
- },
5189
- onClick: function () { openTrashPanel(); },
5190
- },
5191
- h("span", {
5192
- style: { display: "inline-flex", alignItems: "center", justifyContent: "center", width: "20px", height: "20px", flex: "none" },
5193
- "aria-hidden": "true",
5194
- }, typeof Icon === "function" ? h(Icon, { size: 18 }) : null),
5195
- wide ? h("span", { style: { whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, label) : null);
5196
- }
5197
-
5079
+
5198
5080
  /**
5199
5081
  * Re-attach sessions that belong to no workspace.
5200
5082
  *
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.30.2";
35
+ export const HOST_VERSION = "0.31.0";
36
36
 
37
37
  /**
38
38
  * Exact routes the client half calls. Registered on the bare web server, so they
@@ -551,6 +551,35 @@ export function aggregateSession(events) {
551
551
  }
552
552
  }
553
553
  const attributed = [...byKind.values()].reduce((sum, entry) => sum + entry.amplified, 0);
554
+ /* The same file read twice shows up as two entries, so a per-target total
555
+ answers "what content is actually costing me" better than a per-read list
556
+ does. Only repeats are interesting here: a single big read is already in
557
+ the ranking below. */
558
+ const byTarget = new Map();
559
+ for (const block of blocks) {
560
+ if (!(block.amplified > 0)) continue;
561
+ const detail = typeof block.detail === "string" ? block.detail.trim() : "";
562
+ if (detail === "") continue;
563
+ const key = block.kind + "\u0000" + block.name + "\u0000" + detail;
564
+ let entry = byTarget.get(key);
565
+ if (entry === undefined) {
566
+ entry = { kind: block.kind, name: block.name, detail, count: 0, tokens: 0, amplified: 0 };
567
+ byTarget.set(key, entry);
568
+ }
569
+ entry.count += 1;
570
+ entry.tokens += block.tokens;
571
+ entry.amplified += block.amplified;
572
+ }
573
+ const repeated = [...byTarget.values()]
574
+ .filter((entry) => entry.count > 1)
575
+ .sort((a, b) => b.amplified - a.amplified)
576
+ .slice(0, 10)
577
+ .map((entry) => ({
578
+ ...entry,
579
+ share: bill > 0 ? entry.amplified / bill : 0,
580
+ saving: Math.round(entry.amplified * 0.8),
581
+ }));
582
+
554
583
  const ranked = blocks
555
584
  .filter((block) => block.amplified > 0)
556
585
  .sort((a, b) => b.amplified - a.amplified)
@@ -611,6 +640,7 @@ export function aggregateSession(events) {
611
640
  /* Steps after which the window was rewritten. The curve restarts there, so the
612
641
  client reads each segment on its own instead of comparing across a rewrite. */
613
642
  compactions: [...compactions],
643
+ repeated,
614
644
  blocks: ranked,
615
645
  byKind: [...byKind.values()]
616
646
  .map((entry) => ({ ...entry, share: bill > 0 ? entry.amplified / bill : 0 }))
@@ -870,10 +900,78 @@ function searchSnippet(text, needle) {
870
900
  * `terms` are the whitespace-separated pieces of the query; all of them have to
871
901
  * appear in the same message, so a two-word query narrows instead of widening.
872
902
  */
903
+ /**
904
+ * Turn a typed query into groups of alternatives plus filters.
905
+ *
906
+ * Plain words are ANDed, `or` (or `|`) joins alternatives inside one group, a
907
+ * quoted phrase stays whole, a leading `-` excludes, and `ws:` / `in:` / `role:`
908
+ * narrow the sessions rather than the text. Parsing lives on the host because
909
+ * that is where the transcript is matched; the client only shows the result.
910
+ */
911
+ function parseSearchQuery(raw) {
912
+ const filters = { workspace: "", session: "", role: "" };
913
+ const groups = [[]];
914
+ const exclude = [];
915
+ const positive = [];
916
+ const tokens = String(raw ?? "").match(/"[^"]*"|\S+/g) || [];
917
+ let joinNext = false;
918
+ const closeGroup = () => {
919
+ if (groups[groups.length - 1].length > 0) groups.push([]);
920
+ };
921
+ for (const token of tokens) {
922
+ const quoted = token.length > 1 && token.startsWith('"') && token.endsWith('"');
923
+ const text = quoted ? token.slice(1, -1) : token;
924
+ if (text === "") continue;
925
+ const lower = text.toLowerCase();
926
+ const filter = lower.match(/^(ws|in|role|工作区|会话|角色):(.*)$/);
927
+ if (filter !== null && filter[2] !== "") {
928
+ const value = filter[2];
929
+ if (filter[1] === "ws" || filter[1] === "工作区") filters.workspace = value.toLowerCase();
930
+ else if (filter[1] === "in" || filter[1] === "会话") filters.session = value.toLowerCase();
931
+ else filters.role = value.toLowerCase();
932
+ continue;
933
+ }
934
+ if (!quoted && (lower === "or" || text === "|")) {
935
+ /* Reopen the group the previous term closed: `a or b` is one
936
+ requirement satisfied by either, not two requirements. */
937
+ if (groups.length > 0 && groups[groups.length - 1].length === 0) groups.pop();
938
+ joinNext = true;
939
+ continue;
940
+ }
941
+ if (!quoted && text.length > 1 && text.startsWith("-")) {
942
+ exclude.push(text.slice(1).toLowerCase());
943
+ continue;
944
+ }
945
+ const term = text.toLowerCase();
946
+ groups[groups.length - 1].push(term);
947
+ if (positive.indexOf(term) === -1) positive.push(term);
948
+ if (!joinNext) closeGroup();
949
+ joinNext = false;
950
+ }
951
+ const cleaned = groups.filter((group) => group.length > 0);
952
+ return { groups: cleaned, filters, exclude, terms: positive };
953
+ }
954
+
955
+ /** Whether a message satisfies the parsed query. */
956
+ function matchesQuery(parsed, haystack) {
957
+ for (const group of parsed.groups) {
958
+ if (!group.some((term) => haystack.indexOf(term) !== -1)) return false;
959
+ }
960
+ for (const term of parsed.exclude) {
961
+ if (haystack.indexOf(term) !== -1) return false;
962
+ }
963
+ return true;
964
+ }
965
+
873
966
  export async function searchSessions(ctx, query, options = {}) {
874
967
  const started = Date.now();
875
- const terms = String(query ?? "").toLowerCase().split(/\s+/).filter((term) => term !== "");
876
- if (terms.length === 0) return { ok: true, query: "", terms: [], hits: [], scanned: 0, total: 0, pending: 0, took: 0 };
968
+ const parsed = parseSearchQuery(query);
969
+ const terms = parsed.terms;
970
+ const hasFilter = parsed.filters.workspace !== "" || parsed.filters.session !== ""
971
+ || parsed.filters.role !== "";
972
+ if (terms.length === 0 && parsed.groups.length === 0 && !hasFilter) {
973
+ return { ok: true, query: "", terms: [], hits: [], scanned: 0, total: 0, pending: 0, took: 0 };
974
+ }
877
975
 
878
976
  const directory = await searchIndexDirectory();
879
977
  const workspaces = typeof ctx.workspaceRegistry?.list === "function" ? ctx.workspaceRegistry.list() : [];
@@ -934,6 +1032,20 @@ export async function searchSessions(ctx, query, options = {}) {
934
1032
  cached = { key, messages, title };
935
1033
  }
936
1034
 
1035
+ /* Filters narrow the sessions, so a filtered-out one costs nothing beyond
1036
+ the snapshot it was listed in. */
1037
+ if (parsed.filters.workspace !== "") {
1038
+ const cwd = normalizedPath(session.header.cwd);
1039
+ const name = String(workspaceByPath.get(cwd) ?? "").toLowerCase();
1040
+ if (name.indexOf(parsed.filters.workspace) === -1) continue;
1041
+ }
1042
+ if (parsed.filters.session !== "") {
1043
+ const headerTitle = typeof session.header.title === "string" ? session.header.title : "";
1044
+ const cachedTitle = typeof cached.title === "string" ? cached.title : "";
1045
+ const title = (headerTitle + " " + cachedTitle).toLowerCase();
1046
+ if (title.indexOf(parsed.filters.session) === -1) continue;
1047
+ }
1048
+ scanned += 0;
937
1049
  let found = 0;
938
1050
  /* How far down the transcript the last turn sits: the client uses it to jump
939
1051
  to an approximate scroll position before it looks for the text. */
@@ -946,9 +1058,19 @@ export async function searchSessions(ctx, query, options = {}) {
946
1058
  for (const message of cached.messages) {
947
1059
  if (message === null || typeof message !== "object" || typeof message.text !== "string") continue;
948
1060
  const haystack = message.text.toLowerCase();
949
- if (!terms.every((term) => haystack.indexOf(term) !== -1)) continue;
950
- const { snippet, lead, tail } = searchSnippet(message.text, terms[0]);
951
- const seeks = searchSeeks(message.text, terms[0]);
1061
+ if (!matchesQuery(parsed, haystack)) continue;
1062
+ if (parsed.filters.role !== "") {
1063
+ const role = String(message.role || "").toLowerCase();
1064
+ const wanted = parsed.filters.role;
1065
+ const userish = wanted === "user" || wanted === "me" || wanted === "我";
1066
+ const agentish = wanted === "assistant" || wanted === "agent" || wanted === "助手";
1067
+ if (userish && role !== "user") continue;
1068
+ if (agentish && role === "user") continue;
1069
+ }
1070
+ const needle = terms.length > 0 ? terms[0] : "";
1071
+ const { snippet, lead, tail } = searchSnippet(message.text, needle);
1072
+ const seeks = searchSeeks(message.text, needle);
1073
+ const context = searchContext(message.text, needle);
952
1074
  const headerTitle = typeof session.header.title === "string" ? session.header.title.trim() : "";
953
1075
  const cachedTitle = typeof cached.title === "string" ? cached.title.trim() : "";
954
1076
  const cwd = normalizedPath(session.header.cwd);
@@ -968,7 +1090,7 @@ export async function searchSessions(ctx, query, options = {}) {
968
1090
  seek: seeks.length > 0 ? seeks[0] : "",
969
1091
  seeks,
970
1092
  /* The matched neighbourhood, so reading a hit never needs the chat. */
971
- context: searchContext(message.text, terms[0]),
1093
+ context,
972
1094
  /* How many turns the session has, so the client can scroll to a rough
973
1095
  position before looking for the text. */
974
1096
  turns: maxTurn,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ws-recency",
3
- "version": "0.30.2",
3
+ "version": "0.31.0",
4
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",