pi-session-peek 0.3.0 → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - Search syntax: `"exact phrase"` (whitespace inside the quotes matches any whitespace, including line breaks), `a|b` for either, `-word` to exclude, `name:` / `dir:` (`cwd:`) / `user:` / `ai:` (`assistant:`) to limit a term to one field, and `/regex/` for JavaScript regular expressions. Prefixes stack (`-user:"not now"`), quotes escape everything else, and an invalid regex falls back to plain text.
6
+ - The preview highlights and counts only positive terms, and `user:` / `ai:` terms only inside messages of that role. `name:` / `dir:` terms never touch the conversation.
7
+ - Lines containing a character whose lowercase form has a different length (for example `İ`) are now highlighted too. Before, the whole line was skipped.
8
+
9
+ ## 0.3.1
10
+
11
+ - `scanSessions` is now async: directory walking and file reads go through `fs/promises` with bounded concurrency, so opening `/peek` with hundreds of sessions no longer blocks the TUI.
12
+ - Sessions no longer keep a second, lowercased copy of their full text for searching. Keyword filtering runs case-insensitive regexes over the messages directly, which roughly halves memory per cached session and is faster than the old `toLowerCase().includes()` scan.
13
+
3
14
  ## 0.3.0
4
15
 
5
16
  - Ctrl+D now prefers the system trash on every platform instead of only the `trash` CLI: Windows Recycle Bin via PowerShell, Finder on macOS, `gio trash` / `trash-put` on Linux. The file is deleted permanently only when none of them works, and the notification says which one happened.
package/README.md CHANGED
@@ -14,6 +14,7 @@ Search your [pi](https://pi.dev) session history by what was actually said, read
14
14
  - Renders the conversation with pi's own Markdown renderer, so headings, code blocks with syntax highlighting, tables and lists look the same as in the main transcript.
15
15
  - Filters as you type across conversation text, session name and working directory. Tool call arguments and results are excluded, so a keyword only matches sessions that actually discussed it.
16
16
  - Requires every space-separated keyword to match, and shows a snippet around the first hit in the list.
17
+ - Understands `"exact phrases"`, `either|or`, `-exclude`, `name:` / `dir:` / `user:` / `ai:` prefixes and `/regex/`.
17
18
  - Limits results to recently active sessions with `@7d`, `@24h`, `@2w` or `@1m`.
18
19
  - Highlights every hit in the preview and jumps between them with `Ctrl+N` / `Ctrl+P`.
19
20
  - Resumes with `Enter`, forks into a new session with `Ctrl+O`, renames with `Ctrl+R`, deletes with `Ctrl+D`.
@@ -58,7 +59,7 @@ In TUI mode, run `/peek` and start typing. Press `Enter` on a session to continu
58
59
 
59
60
  | Key | Action |
60
61
  | --- | --- |
61
- | type | Filter. Space-separated words must all match; `@7d` and friends limit by time. |
62
+ | type | Filter. Space-separated words must all match; see [Search syntax](#-search-syntax) for phrases, `-exclude`, prefixes, regex and `@7d`. |
62
63
  | `Tab` | Current directory tree ↔ all projects |
63
64
  | `↑` `↓` | Select session |
64
65
  | `PgUp` `PgDn` | Scroll preview by a page |
@@ -73,13 +74,21 @@ In TUI mode, run `/peek` and start typing. Press `Enter` on a session to continu
73
74
 
74
75
  ## 🔎 Search syntax
75
76
 
76
- The filter is case-insensitive and matches anywhere in the text.
77
+ The filter is case-insensitive and matches anywhere in the text. Whitespace separates terms, and every term must be satisfied.
77
78
 
78
79
  | Input | Meaning |
79
80
  | --- | --- |
80
- | `token undefined` | Sessions containing both `token` and `undefined` |
81
+ | `token undefined` | Sessions containing both `token` and `undefined`, in any order and any message |
82
+ | `"token undefined"` | The exact phrase. Whitespace inside the quotes matches any run of whitespace, including a line break. |
83
+ | `vue\|react` | Sessions containing `vue` or `react` |
84
+ | `-draft` | Sessions that do not contain `draft` anywhere (messages, name or directory) |
85
+ | `name:auth` | Session name only. `dir:` or `cwd:` for the working directory. |
86
+ | `user:deploy` | Only the messages you wrote. `ai:` or `assistant:` for the replies. |
87
+ | `/\bfoo\d+\b/` | JavaScript regular expression, case-insensitive, `^` and `$` match line boundaries. Use `\s` instead of a space. |
81
88
  | `@7d` | Sessions active in the last 7 days. Units: `h`, `d`, `w`, `m` (30 days). |
82
- | `token @2w` | Both combined |
89
+ | `-user:"not now" ai:/todo\|fixme/ @2w` | Prefixes stack, and everything combines |
90
+
91
+ Quotes are the escape hatch: `"-foo"`, `"a|b"`, `"name:x"` and `"/x/"` search for those characters literally. A regex that fails to compile is searched as plain text. Only positive terms are highlighted in the preview, and `name:` / `dir:` terms never touch the conversation, so `name:auth` alone shows the full conversation with no highlights.
83
92
 
84
93
  The search index holds user and assistant messages, the session name and the working directory. It does not hold tool call arguments or tool results.
85
94
 
@@ -139,13 +148,16 @@ One-time setup on npmjs.com: package settings → Trusted Publisher → GitHub A
139
148
  To cut a release:
140
149
 
141
150
  ```bash
142
- # 1. move the "## Unreleased" entries in CHANGELOG.md under the new version and commit
143
- # 2. bump the version, commit and tag in one go (patch / minor / major)
144
- npm version patch -m "chore: release %s"
151
+ # 1. write the release notes under "## Unreleased" in CHANGELOG.md and commit them
152
+ # (npm version refuses to run with uncommitted changes to tracked files)
153
+ # 2. bump the version (patch / minor / major)
154
+ npm version patch
145
155
  # 3. push the commit together with the tag; CI does the rest
146
156
  git push --follow-tags
147
157
  ```
148
158
 
159
+ `npm version` first checks that the working tree is clean and stops with `Git working directory not clean.` otherwise, so everything, including `CHANGELOG.md`, has to be committed before the bump. Untracked files are fine. It then runs the hooks declared in `package.json`: `preversion` checks that `CHANGELOG.md` has a non-empty `## Unreleased` section and runs `npm run check`, aborting the bump before anything is touched if either fails; `version` runs `scripts/release-changelog.mjs`, which renames `## Unreleased` to the new version and stages the file. npm then commits `package.json`, the lockfile and `CHANGELOG.md` as `chore: release X.Y.Z` (message set in `.npmrc`) and tags it `vX.Y.Z`.
160
+
149
161
  ## 📄 License
150
162
 
151
163
  MIT. See [`LICENSE`](./LICENSE).
package/README.zh-CN.md CHANGED
@@ -14,6 +14,7 @@
14
14
  - 右栏用 pi 自己的 Markdown 渲染器画,标题、带语法高亮的代码块、表格、列表和主界面里的对话一个样子。
15
15
  - 边打字边过滤,搜的是对话正文、会话名和工作目录。工具调用的参数和结果不进索引,所以只会命中真正讨论过这个词的会话。
16
16
  - 空格分隔多个关键词,全部命中才显示;列表里直接显示第一个命中处的片段。
17
+ - 支持 `"精确短语"`、`a|b` 任一命中、`-排除`、`name:` / `dir:` / `user:` / `ai:` 限定范围,以及 `/正则/`。
17
18
  - `@7d`、`@24h`、`@2w`、`@1m` 只看最近活动过的会话。
18
19
  - 预览里所有命中都高亮,`Ctrl+N` / `Ctrl+P` 在命中间跳。
19
20
  - `Enter` 进入会话,`Ctrl+O` 分叉成新会话,`Ctrl+R` 重命名,`Ctrl+D` 删除。
@@ -58,7 +59,7 @@ pi 扩展以你的用户权限运行,只装信得过的包。
58
59
 
59
60
  | 按键 | 作用 |
60
61
  | --- | --- |
61
- | 打字 | 过滤。空格分隔的词都要命中;`@7d` 等限定时间。 |
62
+ | 打字 | 过滤。空格分隔的词都要命中;短语、`-排除`、前缀、正则和 `@7d` 见[搜索语法](#-搜索语法)。 |
62
63
  | `Tab` | 当前目录树 ↔ 全部项目 |
63
64
  | `↑` `↓` | 选会话 |
64
65
  | `PgUp` `PgDn` | 预览翻页 |
@@ -73,13 +74,21 @@ pi 扩展以你的用户权限运行,只装信得过的包。
73
74
 
74
75
  ## 🔎 搜索语法
75
76
 
76
- 大小写不敏感,匹配文本中任意位置。
77
+ 大小写不敏感,匹配文本中任意位置。空白分隔多个词,每个词都要满足。
77
78
 
78
79
  | 输入 | 含义 |
79
80
  | --- | --- |
80
- | `token undefined` | 同时包含 `token` 和 `undefined` 的会话 |
81
+ | `token undefined` | 同时包含 `token` 和 `undefined` 的会话,顺序不限,可以在不同的消息里 |
82
+ | `"token undefined"` | 精确短语。引号里的空白可以匹配正文里的任意一段空白,包括换行 |
83
+ | `vue\|react` | 包含 `vue` 或 `react` 的会话 |
84
+ | `-draft` | 哪里都不含 `draft` 的会话(消息、会话名、目录都算) |
85
+ | `name:auth` | 只在会话名里找。`dir:` 或 `cwd:` 只看工作目录 |
86
+ | `user:deploy` | 只看你发的消息。`ai:` 或 `assistant:` 只看回复 |
87
+ | `/\bfoo\d+\b/` | JavaScript 正则,大小写不敏感,`^` 和 `$` 匹配行首行尾。空格用 `\s` 代替 |
81
88
  | `@7d` | 最近 7 天活动过的会话。单位:`h` 小时、`d` 天、`w` 周、`m` 月(按 30 天算) |
82
- | `token @2w` | 两者组合 |
89
+ | `-user:"not now" ai:/todo\|fixme/ @2w` | 前缀可以叠加,所有条件一起组合 |
90
+
91
+ 引号是万能转义:`"-foo"`、`"a|b"`、`"name:x"`、`"/x/"` 都按字面搜这些字符。正则写错了就当普通文字搜。预览里只高亮正向的词,`name:` / `dir:` 的词不碰对话正文,所以只输入 `name:auth` 时右栏显示完整对话、没有高亮。
83
92
 
84
93
  索引里有用户和助手的消息、会话名、工作目录。没有工具调用的参数和结果。
85
94
 
@@ -139,13 +148,16 @@ npm 侧需要一次性配置:包设置 → Trusted Publisher → GitHub Action
139
148
  发一个版本:
140
149
 
141
150
  ```bash
142
- # 1. 把 CHANGELOG.md 里 "## Unreleased" 下的条目挪到新版本号下面,提交
143
- # 2. 升版本号、提交、打 tag 一步完成(patch / minor / major)
144
- npm version patch -m "chore: release %s"
151
+ # 1. 把这版的更新说明写在 CHANGELOG.md 的 "## Unreleased" 下面,并提交
152
+ # (npm version 遇到已跟踪文件有未提交改动会直接拒绝)
153
+ # 2. 升版本号(patch / minor / major)
154
+ npm version patch
145
155
  # 3. 提交和 tag 一起推上去,剩下的交给 CI
146
156
  git push --follow-tags
147
157
  ```
148
158
 
159
+ `npm version` 一上来先检查 git 工作区是否干净,不干净就报 `Git working directory not clean.` 退出,所以 `CHANGELOG.md` 在内的所有改动都要先提交(未跟踪的文件不影响)。然后才跑 `package.json` 里声明的钩子:`preversion` 先确认 `CHANGELOG.md` 里有非空的 `## Unreleased` 段落,再跑 `npm run check`,任一不通过就在改动任何文件之前中止;`version` 跑 `scripts/release-changelog.mjs`,把 `## Unreleased` 改成新版本号并 `git add`。然后 npm 把 `package.json`、lockfile 和 `CHANGELOG.md` 一起提交成 `chore: release X.Y.Z`(提交信息定义在 `.npmrc`),并打上 `vX.Y.Z` 的 tag。
160
+
149
161
  ## 📄 许可证
150
162
 
151
163
  MIT,见 [`LICENSE`](./LICENSE)。
package/index.ts CHANGED
@@ -54,7 +54,7 @@ export default function (pi: ExtensionAPI) {
54
54
 
55
55
  // 当前正在用的会话不列出来
56
56
  const currentFile = ctx.sessionManager.getSessionFile();
57
- const all = scanSessions().filter((s) => s.path !== currentFile);
57
+ const all = (await scanSessions()).filter((s) => s.path !== currentFile);
58
58
  if (!all.length) {
59
59
  ctx.ui.notify(msg("noSessions"), "info");
60
60
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-session-peek",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Pi extension: search session history in a two-pane picker with full conversation preview, then resume or fork.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,6 +40,8 @@
40
40
  "test": "node --import tsx --test \"test/**/*.test.ts\"",
41
41
  "check": "npm run typecheck && npm test",
42
42
  "screenshot": "node --import tsx scripts/screenshot.mjs",
43
+ "preversion": "node scripts/release-changelog.mjs --check && npm run check",
44
+ "version": "node scripts/release-changelog.mjs",
43
45
  "prepublishOnly": "npm run check"
44
46
  },
45
47
  "peerDependencies": {
package/src/i18n.ts CHANGED
@@ -14,7 +14,7 @@ const zh = {
14
14
  forked: "已分叉为新会话 {file}",
15
15
  forkFailed: "分叉失败:{error}",
16
16
  switchCancelled: "切换会话已取消",
17
- searchPlaceholder: "关键词过滤(空格分隔=同时命中;@7d 限定近 7 天)",
17
+ searchPlaceholder: "过滤:空格=都要命中 \"短语\" a|b -排除 name:/dir:/user:/ai: /正则/ @7d",
18
18
  renamePlaceholder: "新会话名(Enter 确认 / Esc 取消,留空取消)",
19
19
  title: "🔍 会话搜索预览",
20
20
  scopeLabel: " 范围[Tab]: ",
@@ -54,7 +54,7 @@ const en: Record<keyof typeof zh, string> = {
54
54
  forked: "Forked into new session {file}",
55
55
  forkFailed: "Fork failed: {error}",
56
56
  switchCancelled: "Session switch cancelled",
57
- searchPlaceholder: "Filter (space = all words must match; @7d = last 7 days)",
57
+ searchPlaceholder: "Filter: space=AND \"phrase\" a|b -exclude name:/dir:/user:/ai: /regex/ @7d",
58
58
  renamePlaceholder: "New session name (Enter to confirm, Esc to cancel, empty = cancel)",
59
59
  title: "🔍 Session search",
60
60
  scopeLabel: " Scope[Tab]: ",
@@ -10,7 +10,7 @@ import {
10
10
  type MarkdownTheme,
11
11
  } from "@earendil-works/pi-tui";
12
12
  import { msg } from "./i18n.ts";
13
- import { anyKw, highlight, lineHasKw, parseQuery, snippet, type ParsedQuery } from "./query.ts";
13
+ import { anyMatch, highlight, lineHasMatch, matchesSession, parseQuery, roleTerms, snippet, type ParsedQuery } from "./query.ts";
14
14
  import type { PeekMsg, PeekSession } from "./sessions.ts";
15
15
  import { fmtTime, normPath, padEndVisible } from "./text.ts";
16
16
 
@@ -86,11 +86,11 @@ export class PeekComponent implements Component, Focusable {
86
86
  // keepSelection:尽量保持原来选中的会话,重命名后用
87
87
  private refilter(keepSelection = false): void {
88
88
  const prev = keepSelection ? this.filtered[this.selected] : undefined;
89
- const { kws, since } = this.query();
89
+ const { terms, since } = this.query();
90
90
  let out = this.all;
91
91
  if (this.scope === "current") out = out.filter((s) => this.inCurrentTree(s));
92
92
  if (since) out = out.filter((s) => s.mtime >= since);
93
- if (kws.length) out = out.filter((s) => kws.every((k) => s.searchText.includes(k)));
93
+ if (terms.length) out = out.filter((s) => matchesSession(s, terms));
94
94
  this.filtered = out;
95
95
  const idx = prev ? out.indexOf(prev) : -1;
96
96
  this.selected = idx >= 0 ? idx : keepSelection ? Math.min(this.selected, Math.max(0, out.length - 1)) : 0;
@@ -117,7 +117,6 @@ export class PeekComponent implements Component, Focusable {
117
117
  if (ok) {
118
118
  s.name = name;
119
119
  // 名字参与搜索,改完可能就不再匹配当前关键词了
120
- s.searchText = (s.msgs.map((m) => m.text).join(" ") + " " + name + " " + s.cwd).toLowerCase();
121
120
  this.refilter(true);
122
121
  }
123
122
  this.invalidate();
@@ -272,7 +271,8 @@ export class PeekComponent implements Component, Focusable {
272
271
  // 左栏,每个会话两行
273
272
  private buildList(height: number, lw: number): string[] {
274
273
  const t = this.theme;
275
- const { kws } = this.query();
274
+ const rt = roleTerms(this.query().terms); // 排除词和 name: / cwd: 不在正文里高亮
275
+ const hasBody = rt.user.length > 0 || rt.assistant.length > 0;
276
276
  const visible = Math.max(1, Math.floor(height / 2));
277
277
  if (this.selected < this.listOffset) this.listOffset = this.selected;
278
278
  if (this.selected >= this.listOffset + visible) {
@@ -290,15 +290,15 @@ export class PeekComponent implements Component, Focusable {
290
290
  const sel = idx === this.selected;
291
291
  const time = fmtTime(s.time);
292
292
  const cwdTail = s.cwd.replace(/\\/g, "/").split("/").slice(-2).join("/");
293
- // 有关键词时显示命中的消息数
294
- const hitBadge = kws.length
295
- ? ` ·${s.msgs.reduce((n, m) => n + (anyKw(m.text.toLowerCase(), kws) ? 1 : 0), 0)}`
293
+ // 有正文关键词时显示命中的消息数
294
+ const hitBadge = hasBody
295
+ ? ` ·${s.msgs.reduce((n, m) => n + (anyMatch(m.text, rt[m.role]) ? 1 : 0), 0)}`
296
296
  : "";
297
297
  const l1 = `${sel ? "›" : " "} ${time} ${cwdTail}${hitBadge}`;
298
- // 第二行:有关键词时显示命中片段,否则显示首条消息
299
- const snip = snippet(s.msgs, kws, lw);
298
+ // 第二行:有正文关键词时显示命中片段,否则显示首条消息
299
+ const snip = hasBody ? snippet(s.msgs, rt, lw) : undefined;
300
300
  const l2 = snip !== undefined
301
- ? ` ${highlight(snip, kws, t)}`
301
+ ? ` ${highlight(snip.text, rt[snip.role], t)}`
302
302
  : ` ${s.first}${s.name ? ` [${s.name}]` : ""}`;
303
303
  if (sel) {
304
304
  rows.push(t.bg("selectedBg", padEndVisible(t.fg("accent", truncateToWidth(l1, lw)), lw)));
@@ -359,7 +359,8 @@ export class PeekComponent implements Component, Focusable {
359
359
  );
360
360
  lines.push("");
361
361
 
362
- const { kws } = this.query();
362
+ const rt = roleTerms(this.query().terms);
363
+ const hasBody = rt.user.length > 0 || rt.assistant.length > 0;
363
364
  const MAX_MSGS = 500;
364
365
  const truncated = s.msgs.length > MAX_MSGS;
365
366
  const msgs = truncated ? s.msgs.slice(-MAX_MSGS) : s.msgs;
@@ -367,8 +368,8 @@ export class PeekComponent implements Component, Focusable {
367
368
  lines.push(t.fg("dim", msg("truncated", { n: MAX_MSGS })));
368
369
  lines.push("");
369
370
  }
370
- if (kws.length && !msgs.some((m) => anyKw(m.text.toLowerCase(), kws))) {
371
- const inTruncated = truncated && s.msgs.some((m) => anyKw(m.text.toLowerCase(), kws));
371
+ if (hasBody && !msgs.some((m) => anyMatch(m.text, rt[m.role]))) {
372
+ const inTruncated = truncated && s.msgs.some((m) => anyMatch(m.text, rt[m.role]));
372
373
  lines.push(
373
374
  t.fg(
374
375
  "warning",
@@ -385,7 +386,8 @@ export class PeekComponent implements Component, Focusable {
385
386
  };
386
387
 
387
388
  for (const m of msgs) {
388
- const isMatch = kws.length > 0 && anyKw(m.text.toLowerCase(), kws);
389
+ const terms = rt[m.role]; // user: 的词只在用户消息里高亮,ai: 的只在 AI 回复里
390
+ const isMatch = terms.length > 0 && anyMatch(m.text, terms);
389
391
  const head = lines.length;
390
392
  if (m.role === "user") {
391
393
  lines.push(
@@ -397,8 +399,8 @@ export class PeekComponent implements Component, Focusable {
397
399
  // 先渲染再高亮:往 markdown 源码里插转义码会把链接、代码块的语法弄坏
398
400
  const before = this.matchLines.length;
399
401
  for (const l of this.renderMsg(m, rw)) {
400
- if (isMatch && lineHasKw(l, kws)) this.matchLines.push(lines.length);
401
- lines.push(isMatch ? highlight(l, kws, t) : l);
402
+ if (isMatch && lineHasMatch(l, terms)) this.matchLines.push(lines.length);
403
+ lines.push(isMatch ? highlight(l, terms, t) : l);
402
404
  }
403
405
  // 关键词被折行拆开时哪一行都找不到,退回到消息标题行,别把这条消息漏掉
404
406
  if (isMatch && this.matchLines.length === before) this.matchLines.push(head);
package/src/query.ts CHANGED
@@ -1,53 +1,165 @@
1
1
  import { msg, type MsgKey } from "./i18n.ts";
2
- import type { PeekMsg } from "./sessions.ts";
2
+ import type { PeekMsg, PeekSession } from "./sessions.ts";
3
3
 
4
- // 搜索框语法:空格分隔多个词,都要命中;@7d / @24h / @2w / @1m 限定最近活动时间
4
+ // 搜索框语法。空白分隔多个词,全部满足才算(AND)。每个词可以是:
5
+ // foo 子串,大小写不敏感
6
+ // "foo bar" 短语,引号里的一段空白匹配正文里任意一段空白(含换行)
7
+ // a|b 任一命中(OR);要搜字面的 | 就加引号
8
+ // /re/ 正则(JS 语法,自动带 i 和 m 标志,不能含空白,用 \s 代替);写错了按普通文字搜
9
+ // -foo 排除:命中的会话不显示。--foo 还是普通词,要搜以 - 开头的词就加引号
10
+ // name:foo 只在会话名里找;cwd: / dir: 只看工作目录;user: / ai:(assistant:)只看对应角色的消息
11
+ // @7d 只看最近 7 天活动过的会话,单位 h / d / w / m
12
+ // 前缀可以叠:-user:"foo bar"。引号是万能转义:"-foo"、"a|b"、"name:x"、"/x/" 都按字面搜
13
+
14
+ export type Field = "any" | "name" | "cwd" | "user" | "assistant";
15
+
16
+ export interface Term {
17
+ re: RegExp; // 带 g 和 i,直接在原文上匹配(不再把正文转小写:个别字符小写后长度会变,高亮位置就对不上);用之前先把 lastIndex 归零
18
+ negate: boolean;
19
+ field: Field;
20
+ }
5
21
 
6
22
  export interface ParsedQuery {
7
- kws: string[];
23
+ terms: Term[];
8
24
  since: number; // 毫秒时间戳,0 表示不限
9
25
  sinceLabel: string;
10
26
  }
11
27
 
12
28
  const TIME_UNIT_MS: Record<string, number> = { h: 3600e3, d: 86400e3, w: 7 * 86400e3, m: 30 * 86400e3 };
13
29
  const TIME_UNIT_LABEL: Record<string, MsgKey> = { h: "unitH", d: "unitD", w: "unitW", m: "unitM" };
30
+ const FIELD_ALIAS: Record<string, Field> = { name: "name", cwd: "cwd", dir: "cwd", user: "user", ai: "assistant", assistant: "assistant" };
31
+
32
+ // 按空白切分;带引号的词(前面可以有 - 和 name: 之类的前缀)里的空白不切,引号不闭合就一直到结尾。
33
+ // 引号只在词首算,foo"bar 是普通词
34
+ const TOKEN_RE = /-?(?:(?:name|cwd|dir|user|ai|assistant):)?"[^"]*"?|\S+/gi;
35
+ const FIELD_RE = /^(name|cwd|dir|user|ai|assistant):/i;
36
+
37
+ const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
38
+
39
+ // 单个词 → Term;空词(只剩前缀、空引号)返回 undefined。单个 - 是普通词
40
+ function parseTerm(raw: string): Term | undefined {
41
+ let s = raw;
42
+ let negate = false;
43
+ if (s.length > 1 && s[0] === "-" && s[1] !== "-") {
44
+ negate = true;
45
+ s = s.slice(1);
46
+ }
47
+ let field: Field = "any";
48
+ const f = FIELD_RE.exec(s);
49
+ if (f) {
50
+ field = FIELD_ALIAS[f[1].toLowerCase()];
51
+ s = s.slice(f[0].length);
52
+ }
53
+ let re: RegExp;
54
+ if (s.startsWith('"')) {
55
+ const body = (s.length > 1 && s.endsWith('"') ? s.slice(1, -1) : s.slice(1)).trim();
56
+ if (!body) return undefined;
57
+ re = new RegExp(escapeRe(body.toLowerCase()).replace(/\s+/g, "\\s+"), "gi");
58
+ } else if (s.length >= 3 && s.startsWith("/") && s.endsWith("/")) {
59
+ try {
60
+ re = new RegExp(s.slice(1, -1), "gim");
61
+ } catch {
62
+ re = new RegExp(escapeRe(s.toLowerCase()), "gi");
63
+ }
64
+ } else {
65
+ // 长的放前面:a|ab 在同一位置时高亮取长的那个,和多个词的行为一致
66
+ const parts = s.toLowerCase().split("|").filter(Boolean).sort((a, b) => b.length - a.length);
67
+ if (!parts.length) return undefined;
68
+ re = new RegExp(parts.map(escapeRe).join("|"), "gi");
69
+ }
70
+ return { re, negate, field };
71
+ }
14
72
 
15
- // "foo bar @7d" → kws = [foo, bar],since = 7 天前
73
+ // "foo bar @7d" → terms = [foo, bar],since = 7 天前
16
74
  export function parseQuery(q: string): ParsedQuery {
17
- const kws: string[] = [];
75
+ const terms: Term[] = [];
76
+ const seen = new Set<string>();
18
77
  let since = 0;
19
78
  let sinceLabel = "";
20
- for (const tok of q.toLowerCase().split(/\s+/)) {
21
- if (!tok) continue;
22
- const m = /^@(\d+)([hdwm])$/.exec(tok);
79
+ for (const tok of q.match(TOKEN_RE) ?? []) {
80
+ const m = /^@(\d+)([hdwm])$/i.exec(tok);
23
81
  if (m) {
24
82
  const n = Number(m[1]);
83
+ const unit = m[2].toLowerCase();
25
84
  if (n > 0) {
26
- since = Date.now() - n * TIME_UNIT_MS[m[2]];
27
- sinceLabel = msg("since", { n, unit: msg(TIME_UNIT_LABEL[m[2]]) });
85
+ since = Date.now() - n * TIME_UNIT_MS[unit];
86
+ sinceLabel = msg("since", { n, unit: msg(TIME_UNIT_LABEL[unit]) });
28
87
  }
29
88
  continue;
30
89
  }
31
- if (!kws.includes(tok)) kws.push(tok);
90
+ const t = parseTerm(tok);
91
+ if (!t) continue;
92
+ const key = `${t.negate ? "-" : "+"}${t.field}:${t.re.source}`; // 同一个词打两遍只算一次(普通词已转小写,正则原样)
93
+ if (seen.has(key)) continue;
94
+ seen.add(key);
95
+ terms.push(t);
96
+ }
97
+ return { terms, since, sinceLabel };
98
+ }
99
+
100
+ // 从 from 起找第一个非空命中。g 标志的正则复用前要设 lastIndex,否则从上次命中的位置接着找;
101
+ // 空匹配(如 /a*/ 对上空串)跳过:既不算命中,也免得高亮循环原地打转
102
+ function execFrom(re: RegExp, s: string, from: number): RegExpExecArray | null {
103
+ re.lastIndex = from;
104
+ let m = re.exec(s);
105
+ while (m && !m[0].length) {
106
+ if (m.index >= s.length) return null;
107
+ re.lastIndex = m.index + 1;
108
+ m = re.exec(s);
32
109
  }
33
- return { kws, since, sinceLabel };
110
+ return m;
34
111
  }
35
112
 
36
- // 单条消息用:命中任意一个关键词就算
37
- export function anyKw(lower: string, kws: string[]): boolean {
38
- for (const k of kws) if (lower.includes(k)) return true;
39
- return false;
113
+ function hit(re: RegExp, s: string): boolean {
114
+ return execFrom(re, s, 0) !== null;
40
115
  }
41
116
 
42
- // 最早出现的关键词;同一位置取最长的那个
43
- function nextMatch(lower: string, kws: string[], i: number): [number, number] {
117
+ function termHits(s: PeekSession, t: Term): boolean {
118
+ switch (t.field) {
119
+ case "name":
120
+ return hit(t.re, s.name);
121
+ case "cwd":
122
+ return hit(t.re, s.cwd);
123
+ case "user":
124
+ case "assistant":
125
+ return s.msgs.some((m) => m.role === t.field && hit(t.re, m.text));
126
+ default:
127
+ return hit(t.re, s.name) || hit(t.re, s.cwd) || s.msgs.some((m) => hit(t.re, m.text));
128
+ }
129
+ }
130
+
131
+ // 每个词都要满足:普通词在会话名、cwd 或某条消息里出现,排除词则哪里都不出现;带前缀的只看对应的地方。
132
+ // 正文不预存小写副本,直接在原文上用不区分大小写的正则匹配
133
+ export function matchesSession(s: PeekSession, terms: Term[]): boolean {
134
+ return terms.every((t) => termHits(s, t) !== t.negate);
135
+ }
136
+
137
+ // 单段文字用:命中任意一个词就算
138
+ export function anyMatch(text: string, terms: Term[]): boolean {
139
+ return terms.some((t) => hit(t.re, text));
140
+ }
141
+
142
+ export interface RoleTerms {
143
+ user: Term[];
144
+ assistant: Term[];
145
+ }
146
+
147
+ // 正文里要高亮、计命中的词,按消息角色分开:排除词不算,name: / cwd: 不算,user: / ai: 只给对应角色
148
+ export function roleTerms(terms: Term[]): RoleTerms {
149
+ const pick = (role: PeekMsg["role"]) => terms.filter((t) => !t.negate && (t.field === "any" || t.field === role));
150
+ return { user: pick("user"), assistant: pick("assistant") };
151
+ }
152
+
153
+ // 从 from 起最早的命中 [位置, 长度];同一位置取最长的
154
+ function nextMatch(text: string, terms: Term[], from: number): [number, number] {
44
155
  let best = -1;
45
156
  let len = 0;
46
- for (const k of kws) {
47
- const j = lower.indexOf(k, i);
48
- if (j !== -1 && (best === -1 || j < best || (j === best && k.length > len))) {
49
- best = j;
50
- len = k.length;
157
+ for (const t of terms) {
158
+ const m = execFrom(t.re, text, from);
159
+ if (!m) continue;
160
+ if (best === -1 || m.index < best || (m.index === best && m[0].length > len)) {
161
+ best = m.index;
162
+ len = m[0].length;
51
163
  }
52
164
  }
53
165
  return [best, len];
@@ -96,17 +208,17 @@ function applySgr(st: Sgr, seq: string): void {
96
208
  }
97
209
  }
98
210
 
99
- // 渲染后的一行(可带 ANSI)里有没有关键词,预览按行记命中用
100
- export function lineHasKw(line: string, kws: string[]): boolean {
101
- return kws.length > 0 && anyKw(line.replace(ESC_RE, "").toLowerCase(), kws);
211
+ // 渲染后的一行(可带 ANSI)里有没有命中,预览按行记命中用
212
+ export function lineHasMatch(line: string, terms: Term[]): boolean {
213
+ return terms.length > 0 && anyMatch(line.replace(ESC_RE, ""), terms);
102
214
  }
103
215
 
104
- // 在一行文字里高亮关键词,返回带 ANSI 的字符串。
216
+ // 在一行文字里高亮命中,返回带 ANSI 的字符串。
105
217
  // 输入可以是已经渲染过、带样式的行:转义序列不参与匹配也不会被切断;高亮结束时把原来的
106
218
  // 前景色 / 粗体 / 下划线恢复回去,所以放在标题、链接等样式里面也不会把后面的文字弄丢样式。
107
219
  // 不用主题自带的 searchMatchBg:dark/light 主题里它和 selectedBg 同色,看不出来
108
- export function highlight(line: string, kws: string[], theme: any): string {
109
- if (!kws.length || !line) return line;
220
+ export function highlight(line: string, terms: Term[], theme: any): string {
221
+ if (!terms.length || !line) return line;
110
222
 
111
223
  // 拆成可见文本和转义序列两类片段
112
224
  const segs: { text: string; esc: boolean }[] = [];
@@ -120,12 +232,10 @@ export function highlight(line: string, kws: string[], theme: any): string {
120
232
 
121
233
  let visible = "";
122
234
  for (const s of segs) if (!s.esc) visible += s.text;
123
- const lower = visible.toLowerCase();
124
- if (lower.length !== visible.length) return line; // 个别字符小写后长度会变,位置对不上就不高亮
125
235
 
126
236
  const ranges: [number, number][] = [];
127
237
  for (let i = 0; ; ) {
128
- const [j, len] = nextMatch(lower, kws, i);
238
+ const [j, len] = nextMatch(visible, terms, i);
129
239
  if (j === -1) break;
130
240
  ranges.push([j, j + len]);
131
241
  i = j + len;
@@ -178,15 +288,22 @@ export function highlight(line: string, kws: string[], theme: any): string {
178
288
  return out;
179
289
  }
180
290
 
291
+ export interface Snippet {
292
+ text: string;
293
+ role: PeekMsg["role"]; // 片段来自哪个角色的消息,高亮时用该角色的词
294
+ }
295
+
181
296
  // 左栏用:第一个命中处前后截一段。没有消息命中时返回 undefined,调用方退回首条消息
182
- export function snippet(msgs: PeekMsg[], kws: string[], width: number): string | undefined {
183
- if (!kws.length) return undefined;
297
+ export function snippet(msgs: PeekMsg[], rt: RoleTerms, width: number): Snippet | undefined {
184
298
  for (const m of msgs) {
185
- const flat = m.text.replace(/\s+/g, " ");
186
- const [j] = nextMatch(flat.toLowerCase(), kws, 0);
299
+ const terms = rt[m.role];
300
+ if (!terms.length) continue;
301
+ // 在原文上找命中,正则的 ^ / $ 才能和列表过滤时对得上;截出来的那段再把换行和连续空白压成一个空格
302
+ const [j] = nextMatch(m.text, terms, 0);
187
303
  if (j === -1) continue;
188
304
  const start = Math.max(0, j - Math.floor(width / 3));
189
- return (start > 0 ? "…" : "") + flat.slice(start, start + width);
305
+ const flat = m.text.slice(start, j + width).replace(/\s+/g, " ");
306
+ return { text: (start > 0 ? "…" : "") + flat.slice(0, width), role: m.role };
190
307
  }
191
308
  return undefined;
192
309
  }
package/src/sessions.ts CHANGED
@@ -1,9 +1,11 @@
1
- import { appendFileSync, existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
1
+ import { appendFileSync, existsSync, readFileSync, rmSync } from "node:fs";
2
+ import { readdir, readFile, stat } from "node:fs/promises";
2
3
  import { randomBytes } from "node:crypto";
3
4
  import { homedir } from "node:os";
4
5
  import { join } from "node:path";
5
6
 
6
- // 读 ~/.pi/agent/sessions 下的会话 JSONL,按 mtime 缓存;重命名和删除也在这里
7
+ // 读 ~/.pi/agent/sessions 下的会话 JSONL,按 mtime 缓存;重命名和删除也在这里。
8
+ // 搜索不预存小写全文:会话正文只在 msgs 里放一份,匹配时用不区分大小写的正则直接扫(见 query.ts 的 matchesSession)
7
9
 
8
10
  export interface PeekMsg {
9
11
  role: "user" | "assistant";
@@ -17,11 +19,11 @@ export interface PeekSession {
17
19
  name: string; // 最后一条 session_info 里的名字,没有则为空
18
20
  first: string; // 首条消息,列表里显示用
19
21
  msgs: PeekMsg[];
20
- searchText: string; // 正文 + 会话名 + cwd,已小写
21
22
  mtime: number;
22
23
  }
23
24
 
24
25
  const sessionCache = new Map<string, PeekSession>();
26
+ const READ_CONCURRENCY = 16; // 同时读的文件数,太高会把 libuv 线程池排满
25
27
 
26
28
  // 和 pi 一样认 PI_CODING_AGENT_DIR
27
29
  function sessionsDir(): string {
@@ -30,17 +32,17 @@ function sessionsDir(): string {
30
32
  return join(agent, "sessions");
31
33
  }
32
34
 
33
- function* walkJsonl(dir: string): Generator<string> {
35
+ async function walkJsonl(dir: string, out: string[]): Promise<void> {
34
36
  let entries;
35
37
  try {
36
- entries = readdirSync(dir, { withFileTypes: true });
38
+ entries = await readdir(dir, { withFileTypes: true });
37
39
  } catch {
38
40
  return;
39
41
  }
40
42
  for (const e of entries) {
41
43
  const p = join(dir, e.name);
42
- if (e.isDirectory()) yield* walkJsonl(p);
43
- else if (e.name.endsWith(".jsonl")) yield p;
44
+ if (e.isDirectory()) await walkJsonl(p, out);
45
+ else if (e.name.endsWith(".jsonl")) out.push(p);
44
46
  }
45
47
  }
46
48
 
@@ -53,13 +55,7 @@ function extractText(content: unknown): string {
53
55
  .join("\n");
54
56
  }
55
57
 
56
- function parseSession(path: string, mtime: number): PeekSession | null {
57
- let raw: string;
58
- try {
59
- raw = readFileSync(path, "utf8");
60
- } catch {
61
- return null;
62
- }
58
+ function parseSession(path: string, raw: string, mtime: number): PeekSession | null {
63
59
  let cwd = "";
64
60
  let time = "";
65
61
  let name = "";
@@ -101,36 +97,48 @@ function parseSession(path: string, mtime: number): PeekSession | null {
101
97
  msgs,
102
98
  mtime,
103
99
  first: msgs[0].text.replace(/\s+/g, " ").slice(0, 80),
104
- searchText: (msgs.map((m) => m.text).join(" ") + " " + name + " " + cwd).toLowerCase(),
105
100
  };
106
101
  }
107
102
 
108
- /** 全部会话,按最后修改时间倒序;文件没变的直接用缓存 */
109
- export function scanSessions(): PeekSession[] {
110
- const seen = new Set<string>();
111
- const out: PeekSession[] = [];
103
+ // 单个文件:mtime 没变直接用缓存,否则重新读和解析
104
+ async function loadSession(file: string): Promise<PeekSession | null> {
105
+ let mtime: number;
106
+ try {
107
+ mtime = (await stat(file)).mtimeMs;
108
+ } catch {
109
+ return null;
110
+ }
111
+ const hit = sessionCache.get(file);
112
+ if (hit && hit.mtime === mtime) return hit;
113
+ let raw: string;
114
+ try {
115
+ raw = await readFile(file, "utf8");
116
+ } catch {
117
+ return null;
118
+ }
119
+ const parsed = parseSession(file, raw, mtime);
120
+ if (parsed) sessionCache.set(file, parsed);
121
+ return parsed;
122
+ }
112
123
 
113
- for (const file of walkJsonl(sessionsDir())) {
114
- seen.add(file);
115
- let mtime = 0;
116
- try {
117
- mtime = statSync(file).mtimeMs;
118
- } catch {
119
- continue;
120
- }
121
- const hit = sessionCache.get(file);
122
- if (hit && hit.mtime === mtime) {
123
- out.push(hit);
124
- continue;
125
- }
126
- const parsed = parseSession(file, mtime);
127
- if (parsed) {
128
- sessionCache.set(file, parsed);
129
- out.push(parsed);
124
+ /** 全部会话,按最后修改时间倒序;文件没变的直接用缓存。
125
+ * 目录遍历和文件读取都走异步 I/O,几百个会话也不会把 TUI 卡住 */
126
+ export async function scanSessions(): Promise<PeekSession[]> {
127
+ const files: string[] = [];
128
+ await walkJsonl(sessionsDir(), files);
129
+
130
+ const out: PeekSession[] = [];
131
+ let next = 0;
132
+ const worker = async () => {
133
+ while (next < files.length) {
134
+ const s = await loadSession(files[next++]);
135
+ if (s) out.push(s);
130
136
  }
131
- }
137
+ };
138
+ await Promise.all(Array.from({ length: Math.min(READ_CONCURRENCY, files.length) }, worker));
132
139
 
133
140
  // 文件已经不在了的,从缓存里去掉
141
+ const seen = new Set(files);
134
142
  for (const key of [...sessionCache.keys()]) {
135
143
  if (!seen.has(key)) sessionCache.delete(key);
136
144
  }