@renyuluo/dsh-deepsearch 0.0.0-stage → 0.1.13
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/LICENSE +9 -0
- package/README.md +139 -2
- package/client.js +427 -0
- package/cordis.patch.yml +3 -0
- package/host.js +62 -0
- package/icon.svg +1 -0
- package/locale/en.json +6 -0
- package/locale/zh-CN.json +6 -0
- package/package.json +68 -4
- package/runtime-0.1.13.js +1 -0
- package/search-core.js +300 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSearch contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,140 @@
|
|
|
1
|
-
#
|
|
1
|
+
# DeepSearch · 会话全文搜索
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
为 **DeepSeek Harness** 制作的本地全文搜索插件。记得一小段内容,就能找回对应会话,而不必记住标题。
|
|
4
|
+
|
|
5
|
+
- **中文片段也能搜**:不依赖 FTS 分词,支持连续中文子串、英文大小写不敏感和字面符号。
|
|
6
|
+
- **正文搜索**:会话标题、用户输入、助手已完成的最终回复;命中摘要直接高亮,展示消息的本地日期与时间。
|
|
7
|
+
- **当前会话优先**:先从当前会话最新消息往前搜索,再自动逐批扫描其他会话。
|
|
8
|
+
- **原生会话定位**:打开 DSH 原生会话,加载精确消息并尝试滚动、高亮,不替换详情页。
|
|
9
|
+
- **范围与外观**:项目 / 工作区过滤、可选归档;毛玻璃、跟随主题、自定义颜色、不透明度与模糊。
|
|
10
|
+
- **不上传聊天**:复用宿主认证与历史服务,不开额外生产监听端口,不修改会话。
|
|
11
|
+
|
|
12
|
+
## 功能预览
|
|
13
|
+
|
|
14
|
+
以下图片使用**真实插件组件 + 隔离模拟宿主 + 虚构演示数据**生成,并非你的聊天记录或 DSH 原生页面截图。原生消息跳转需在真实宿主中验证,演示页不模拟“定位成功”。
|
|
15
|
+
|
|
16
|
+
### 全文搜索、命中摘要与准确时间
|
|
17
|
+
|
|
18
|
+

|
|
19
|
+
|
|
20
|
+
### 项目与工作区范围
|
|
21
|
+
|
|
22
|
+

|
|
23
|
+
|
|
24
|
+
### 归档会话
|
|
25
|
+
|
|
26
|
+

|
|
27
|
+
|
|
28
|
+
### 三种面板外观
|
|
29
|
+
|
|
30
|
+

|
|
31
|
+
|
|
32
|
+

|
|
33
|
+
|
|
34
|
+

|
|
35
|
+
|
|
36
|
+
## 安装
|
|
37
|
+
|
|
38
|
+
当前验证宿主为 **DSH Desktop 0.2.2-rc.3**;其他版本与平台尚未完成真实桌面回归。包的兼容性范围暂时限定该版本。
|
|
39
|
+
|
|
40
|
+
### 从 npm 安装(推荐)
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
dsh plugin --profile desktop add @renyuluo/dsh-deepsearch
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
公开包名为 **`@renyuluo/dsh-deepsearch`**;产品名和 GitHub 仓库名不变。
|
|
47
|
+
|
|
48
|
+
### 从 GitHub 安装
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
dsh plugin --profile desktop add 'https://github.com/luorenyu/dsh-deepsearch.git#v0.1.13'
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
也可以从 [Releases](https://github.com/luorenyu/dsh-deepsearch/releases) 下载安装包后安装:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
dsh plugin --profile desktop add /path/to/renyuluo-dsh-deepsearch-0.1.13.tgz
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
> **重要:不要运行 `add dsh-deepsearch` 来安装 npm 同名包。** 无作用域的 npm 同名包属于其他作者,与本仓库无关。请使用 `@renyuluo/dsh-deepsearch`,或本仓库 GitHub / Release 地址。
|
|
61
|
+
|
|
62
|
+
从本项目旧版无作用域 GitHub 安装迁移时,请先卸载旧条目,再安装作用域包,避免两份搜索插件同时加载:
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
dsh plugin --profile desktop remove dsh-deepsearch
|
|
66
|
+
dsh plugin --profile desktop add @renyuluo/dsh-deepsearch
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
这是替换本项目旧安装条目,不是建议卸载其他作者的同名插件。外观存储键保持不变;同一宿主页面来源下已有偏好会继续使用。
|
|
70
|
+
|
|
71
|
+
上方功能截图来自 0.1.12 演示组件;0.1.13 仅调整分发身份,不改变搜索功能。
|
|
72
|
+
|
|
73
|
+
### 在 DSH 插件市场中发现
|
|
74
|
+
|
|
75
|
+
已提交 [市场收录申请 #15379](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin/pull/15379),目前为草稿,等待仓库创建满 24 小时后转为正式待审及维护者审核。[Awesome DSH Plugin](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin) 是 `dshmarket` 使用的第三方社区目录;是否收录以 PR 合并和市场同步为准。**GitHub 发布不等于已经在市场上架。**
|
|
76
|
+
|
|
77
|
+
审核通过后,可在相应市场搜索 **DeepSearch** 或 **会话全文搜索**。请确认来源是 `luorenyu/dsh-deepsearch`,不是其他作者的同名插件。DSH 本体也支持自定义索引,各客户端配置的来源可能不同。
|
|
78
|
+
|
|
79
|
+
## 使用
|
|
80
|
+
|
|
81
|
+
| 操作 | 快捷键 / 入口 |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| 打开或关闭搜索 | macOS `⌘⇧K`;Windows / Linux `Ctrl⇧K`(未实机验证) |
|
|
84
|
+
| 选择结果 | `↑` / `↓` |
|
|
85
|
+
| 打开结果 | `Enter` |
|
|
86
|
+
| 关闭浮层 | `Esc` 或点击外部 |
|
|
87
|
+
| 搜索范围 | 全部 / 对话 / 项目,工作区下拉,含归档 |
|
|
88
|
+
| 调整面板 | 右上角「外观」 |
|
|
89
|
+
|
|
90
|
+
不占用 DSH 原生 `⌘K`,也不占用其他搜索插件常用的 `⌘F`。
|
|
91
|
+
|
|
92
|
+
输入中文片段或英文关键词后,搜索自动继续,不需要逐页点击。结果随扫描逐步出现;只有扫描完成且没有命中才显示没有找到。读取失败、超时、未完成与 200 条结果上限会单独提示。切换关键词或关闭面板会取消旧任务。
|
|
93
|
+
|
|
94
|
+
点击正文结果后,插件打开原生会话,使用 `sessionId + seq` 检查精确消息是否存在,随后尝试定位原生行并高亮。提示区可以返回搜索或清除高亮;切换会话或其他功能页时释放定位资源。标题结果仅打开会话,不冒充消息定位成功。
|
|
95
|
+
|
|
96
|
+
## 外观
|
|
97
|
+
|
|
98
|
+
- **毛玻璃**:优先使用宿主输入框玻璃底色,仅对搜索面板覆盖区域模糊。
|
|
99
|
+
- **跟随 DSH**:使用宿主主题的实色底板。
|
|
100
|
+
- **自定义**:颜色、不透明度 55–100%、模糊 0–32px,可恢复默认。
|
|
101
|
+
|
|
102
|
+
不暗化全屏,不模糊整个 DSH 页面。兼容壁纸插件的实色弹窗覆盖规则,修正只作用于 DeepSearch 自己。偏好存于本机 `localStorage`;禁止存储时仍可在本次使用。系统要求降低透明度或不支持模糊时使用实色回退。
|
|
103
|
+
|
|
104
|
+
## 隐私与限制
|
|
105
|
+
|
|
106
|
+
- 通过宿主公开历史服务读取,不直接解析私有聊天文件,不上传聊天、不写入原始消息。搜索 API 使用宿主 `connection.fetch` owner 认证路由。
|
|
107
|
+
- 默认搜索普通会话标题、用户输入及已完成助手最终回复;排除工具输出、推理、子智能体与未完成回复。默认不含归档。
|
|
108
|
+
- 搜索采用有界内存、短期游标和逐批扫描,**不是持久增量索引**。超长历史首次查询可能较慢;最多显示 200 条命中,游标闲置两分钟过期后需重搜。
|
|
109
|
+
- 每个会话首次读取的历史切面构成本次范围;扫描期间新追加内容需要重新搜索才会出现。版本变更或历史截断会明确要求重新搜索。
|
|
110
|
+
- 项目来自宿主已登记工作区,**不搜索磁盘文件内容**,也不提供命令搜索。
|
|
111
|
+
- 消息时间按本机时区显示为 `YYYY/MM/DD HH:mm`,缺失或非法时间不编造。
|
|
112
|
+
- 精确定位使用当前宿主 DOM 兼容适配,并非公开稳定滚动 API。折叠消息、Markdown 文本变形、非 Chat 视图、宿主升级或滚动策略可能导致无法定位或逐字高亮,插件会区分状态,不阻塞原生会话。
|
|
113
|
+
|
|
114
|
+
## 开发与测试
|
|
115
|
+
|
|
116
|
+
无需构建和生产第三方依赖,Node.js 22+:
|
|
117
|
+
|
|
118
|
+
```sh
|
|
119
|
+
git clone https://github.com/luorenyu/dsh-deepsearch.git
|
|
120
|
+
cd dsh-deepsearch
|
|
121
|
+
npm test
|
|
122
|
+
npm run check
|
|
123
|
+
npm pack --ignore-scripts
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
核心测试覆盖字面匹配、中文与 Unicode 范围、历史投影、逆序分页、自动续搜、取消 / 超时 / 游标、原生定位生命周期、摘要渲染、时间和外观。组件截图和模拟服务测试不等于所有宿主版本、主题与平台实机验收。
|
|
127
|
+
|
|
128
|
+
代码分工:
|
|
129
|
+
- [client.js](client.js):搜索浮层、快捷键、摘要、外观和原生定位适配。
|
|
130
|
+
- [host.js](host.js):认证路由和请求限制。
|
|
131
|
+
- [search-core.js](search-core.js):会话目录、最终回复投影、字串匹配和分页。
|
|
132
|
+
- [tests](tests):无宿主单元 / 合约回归测试。
|
|
133
|
+
|
|
134
|
+
卸载:
|
|
135
|
+
|
|
136
|
+
```sh
|
|
137
|
+
dsh plugin --profile desktop remove @renyuluo/dsh-deepsearch
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
[MIT License](LICENSE) · [问题反馈](https://github.com/luorenyu/dsh-deepsearch/issues)
|
package/client.js
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: '@renyuluo/dsh-deepsearch',
|
|
3
|
+
factory(require) {
|
|
4
|
+
const React = require('react'), h = React.createElement;
|
|
5
|
+
const MAX_RESULTS = 200;
|
|
6
|
+
function selectedKeys(chat, seq) {
|
|
7
|
+
if (!Number.isSafeInteger(seq) || !chat?.order || !chat.nodes?.get) return [];
|
|
8
|
+
return chat.order.filter(key => {
|
|
9
|
+
const node = chat.nodes.get(key);
|
|
10
|
+
return node && [node.anchorSeq, node.data?.seq, node.data?.finalNode?.seq, node.data?.root?.seq].includes(seq);
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
async function loadExact(reference, seq, isCurrent, signal) {
|
|
14
|
+
if (signal?.aborted) return false;
|
|
15
|
+
const connected = await new Promise((resolve, reject) => {
|
|
16
|
+
const finish = (value, error) => {clearTimeout(timer); signal?.removeEventListener('abort', cancel); error ? reject(error) : resolve(value);};
|
|
17
|
+
const cancel = () => finish(false);
|
|
18
|
+
const timer = setTimeout(() => finish(false, new Error('会话连接超时,请重试')), 10000);
|
|
19
|
+
signal?.addEventListener('abort', cancel, {once: true});
|
|
20
|
+
reference.ready.then(() => finish(true), error => finish(false, error));
|
|
21
|
+
});
|
|
22
|
+
if (!connected || !isCurrent() || signal?.aborted) return false;
|
|
23
|
+
const binding = reference.binding, session = binding.session;
|
|
24
|
+
const contains = () => binding.eventSource.getSnapshot().entries.some(entry => entry.type === 'event' && entry.event.seq === seq);
|
|
25
|
+
if (contains()) return true;
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
let disposed = false, running = false, attempts = 0, unsubscribe, retryTimer;
|
|
28
|
+
const finish = (error) => {
|
|
29
|
+
if (disposed) return; disposed = true; clearTimeout(timer); clearTimeout(retryTimer); unsubscribe?.(); signal?.removeEventListener('abort', cancel);
|
|
30
|
+
error ? reject(error) : resolve(!signal?.aborted && isCurrent());
|
|
31
|
+
};
|
|
32
|
+
const cancel = () => finish();
|
|
33
|
+
const timer = setTimeout(() => finish(new Error('历史未能加载到命中消息,请重试或手动查看')), 10000);
|
|
34
|
+
signal?.addEventListener('abort', cancel, {once: true});
|
|
35
|
+
async function check() {
|
|
36
|
+
if (disposed) return;
|
|
37
|
+
if (!isCurrent()) {finish(); return;}
|
|
38
|
+
if (contains()) {finish(); return;}
|
|
39
|
+
if (running || session.getSnapshot().loadingOlder || attempts >= 4) return;
|
|
40
|
+
running = true; attempts++;
|
|
41
|
+
try {
|
|
42
|
+
await session.loadThrough(seq);
|
|
43
|
+
if (disposed) return;
|
|
44
|
+
if (contains()) finish();
|
|
45
|
+
else if (!session.getSnapshot().hasMore) finish(new Error('历史中找不到原命中消息;它可能已被撤回或改写'));
|
|
46
|
+
} catch (failure) {finish(failure);}
|
|
47
|
+
finally {running = false; if (!disposed && attempts < 4) retryTimer = setTimeout(check, 150);}
|
|
48
|
+
}
|
|
49
|
+
unsubscribe = session.subscribe(check); check();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function isShortcut(event) {
|
|
53
|
+
return (event.metaKey || event.ctrlKey) && event.shiftKey && !event.altKey &&
|
|
54
|
+
event.key.toLowerCase() === 'k' && !event.isComposing && !event.repeat;
|
|
55
|
+
}
|
|
56
|
+
function joinItems(previous, next) {
|
|
57
|
+
const seen = new Set(previous.map(item => item.id));
|
|
58
|
+
return previous.concat(next.filter(item => !seen.has(item.id) && seen.add(item.id))).slice(0, MAX_RESULTS);
|
|
59
|
+
}
|
|
60
|
+
function currentSessionId(binding, snapshot) {
|
|
61
|
+
return binding?.key ?? Object.values(snapshot?.byId || {}).find(row => (row.retainedBy?.mainView ?? 0) > 0)?.id;
|
|
62
|
+
}
|
|
63
|
+
function pauseScan(signal) {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const cancel = () => {clearTimeout(timer); signal.removeEventListener('abort', cancel); reject(signal.reason);};
|
|
66
|
+
const timer = setTimeout(() => {signal.removeEventListener('abort', cancel); resolve();}, 20);
|
|
67
|
+
signal.addEventListener('abort', cancel, {once: true}); if (signal.aborted) cancel();
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
async function scanPages({requestPage, onPage, isCurrent, signal, cursor, initialItems = [], yieldPage = pauseScan}) {
|
|
71
|
+
let items = initialItems, warnings = [];
|
|
72
|
+
do {
|
|
73
|
+
if (signal.aborted || !isCurrent()) return;
|
|
74
|
+
const page = await requestPage(cursor, signal);
|
|
75
|
+
if (signal.aborted || !isCurrent()) return;
|
|
76
|
+
const incoming = page.items || [], uniqueCount = new Set(items.concat(incoming).map(item => item.id)).size;
|
|
77
|
+
items = joinItems(items, incoming); cursor = page.cursor;
|
|
78
|
+
warnings = [...new Map(warnings.concat(page.warnings || []).map(warning => [JSON.stringify(warning), warning])).values()].slice(0, 32);
|
|
79
|
+
onPage({...page, items, warnings, capped: uniqueCount > MAX_RESULTS || (items.length >= MAX_RESULTS && !!cursor)});
|
|
80
|
+
if (!cursor || items.length >= MAX_RESULTS) return;
|
|
81
|
+
await yieldPage(signal);
|
|
82
|
+
} while (true);
|
|
83
|
+
}
|
|
84
|
+
function searchStatus({busy, error, result, query, projects = false}) {
|
|
85
|
+
if (projects || !query) return {empty: query ? '没有找到匹配项目' : '把记得的那句话交给 DeepSearch', footer: '⌘⇧K / Ctrl⇧K'};
|
|
86
|
+
const progress = (result.items?.length || 0) + ' 条 · 已扫描 ' + result.scanned + '/' + result.totalSessions;
|
|
87
|
+
if (busy) return {empty: '正在查找对话内容', footer: '搜索中 · ' + progress};
|
|
88
|
+
if (error) return {empty: '搜索未完成', footer: '搜索中断 · ' + progress};
|
|
89
|
+
if (result.capped || result.cursor) return {empty: '搜索尚未完成', footer: (result.capped || result.items.length >= MAX_RESULTS ? '已达 200 条上限,请缩小范围 · ' : '等待继续 · ') + progress};
|
|
90
|
+
if (result.warnings?.length) return {empty: '部分历史读取失败,无法确认没有匹配', footer: '部分完成 · ' + progress};
|
|
91
|
+
return {empty: '没有找到匹配内容', footer: '搜索完成 · ' + progress};
|
|
92
|
+
}
|
|
93
|
+
// Transform context separately so the exact UTF-16 match is never lost to clipping.
|
|
94
|
+
function matchPreview(text = '', range) {
|
|
95
|
+
const compact = value => value.replace(/\s+/gu, ' ');
|
|
96
|
+
if (!Array.isArray(range) || range.length !== 2 || !range.every(Number.isInteger) || range[0] < 0 || range[1] <= range[0] || range[1] > text.length) {
|
|
97
|
+
const points = Array.from(compact(text));
|
|
98
|
+
return {text: points.slice(0, 96).join('') + (points.length > 96 ? '…' : ''), range: null};
|
|
99
|
+
}
|
|
100
|
+
const before = Array.from(compact(text.slice(0, range[0]))), after = Array.from(compact(text.slice(range[1])));
|
|
101
|
+
const prefix = (before.length > 32 ? '…' : '') + before.slice(-32).join('');
|
|
102
|
+
const hit = text.slice(...range);
|
|
103
|
+
return {text: prefix + hit + after.slice(0, 64).join('') + (after.length > 64 ? '…' : ''), range: [prefix.length, prefix.length + hit.length]};
|
|
104
|
+
}
|
|
105
|
+
const APPEARANCE_KEY = 'dsh-deepsearch.appearance.v1';
|
|
106
|
+
function formatMessageTime(value) {
|
|
107
|
+
if (typeof value !== 'string' && typeof value !== 'number') return null;
|
|
108
|
+
if (typeof value === 'string') {
|
|
109
|
+
const parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/.exec(value);
|
|
110
|
+
if (!parts) return null;
|
|
111
|
+
const [,year,month,day,hour,minute,second,offsetHour = 0,offsetMinute = 0] = parts.map(Number);
|
|
112
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0), days = [31,leap ? 29 : 28,31,30,31,30,31,31,30,31,30,31];
|
|
113
|
+
if (month < 1 || month > 12 || day < 1 || day > days[month - 1] || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) return null;
|
|
114
|
+
}
|
|
115
|
+
const date = new Date(value); if (!Number.isFinite(date.getTime())) return null;
|
|
116
|
+
const pad = n => String(n).padStart(2, '0');
|
|
117
|
+
return date.getFullYear() + '/' + pad(date.getMonth() + 1) + '/' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes());
|
|
118
|
+
}
|
|
119
|
+
function appearancePrefs(value) {
|
|
120
|
+
const number = (value, fallback, min, max) => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
|
|
121
|
+
return {mode: ['glass','theme','custom'].includes(value?.mode) ? value.mode : 'glass',
|
|
122
|
+
color: typeof value?.color === 'string' && /^#[a-f0-9]{6}$/i.test(value.color) ? value.color : '#edf2f7',
|
|
123
|
+
opacity: number(value?.opacity, 88, 55, 100), blur: number(value?.blur, 18, 0, 32)};
|
|
124
|
+
}
|
|
125
|
+
function readAppearance(storage) {
|
|
126
|
+
try {const raw = storage.getItem(APPEARANCE_KEY); return appearancePrefs(raw?.length > 2048 ? null : JSON.parse(raw));} catch {return appearancePrefs(null);}
|
|
127
|
+
}
|
|
128
|
+
function saveAppearance(storage, value) {
|
|
129
|
+
try {storage.setItem(APPEARANCE_KEY, JSON.stringify(appearancePrefs(value))); return true;} catch {return false;}
|
|
130
|
+
}
|
|
131
|
+
function appearanceStyle(value) {
|
|
132
|
+
const prefs = appearancePrefs(value);
|
|
133
|
+
if (prefs.mode === 'theme') return {'--ds-surface':'var(--ds-bg)', '--ds-blur':'0px', '--ds-filter':'none'};
|
|
134
|
+
// Reuse the native composer material when available, not the transparent canvas token.
|
|
135
|
+
const style = {'--ds-surface':'var(--dsw-specific-input-major, color-mix(in srgb, var(--ds-bg) 65%, transparent))', '--ds-blur':prefs.blur + 'px',
|
|
136
|
+
'--ds-filter':'blur(var(--ds-blur)) saturate(var(--we-saturate,1.3)) brightness(var(--we-glass-brightness,1.04)) contrast(1.01)'};
|
|
137
|
+
if (prefs.mode === 'custom') {
|
|
138
|
+
const rgb = [1,3,5].map(i => parseInt(prefs.color.slice(i,i+2),16));
|
|
139
|
+
const light = rgb[0]*.299 + rgb[1]*.587 + rgb[2]*.114 > 150;
|
|
140
|
+
Object.assign(style, {'--ds-bg':prefs.color, '--ds-surface':'rgba(' + rgb.join(',') + ',' + prefs.opacity/100 + ')',
|
|
141
|
+
'--ds-text':light ? '#14202f' : '#f4f7fc', '--ds-muted':light ? '#455368' : '#c5d0df',
|
|
142
|
+
'--ds-hover':light ? '#0000000b' : '#ffffff17', '--ds-line':light ? '#00000022' : '#ffffff30'});
|
|
143
|
+
}
|
|
144
|
+
return style;
|
|
145
|
+
}
|
|
146
|
+
function Icon({folder = false}) {
|
|
147
|
+
return h('svg', {width: 19, height: 19, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true},
|
|
148
|
+
folder ? h('path', {d: 'M3 6h6l2 3h10v11H3z'}) : h(React.Fragment, null, h('circle', {cx: 10.5, cy: 10.5, r: 6.7}), h('path', {d: 'm16 16 5 5'})));
|
|
149
|
+
}
|
|
150
|
+
function Mark({text = '', range}) {
|
|
151
|
+
const preview = matchPreview(text, range);
|
|
152
|
+
if (!preview.range) return preview.text;
|
|
153
|
+
return h(React.Fragment, null, preview.text.slice(0, preview.range[0]), h('mark', null, preview.text.slice(...preview.range)), preview.text.slice(preview.range[1]));
|
|
154
|
+
}
|
|
155
|
+
const css = "\n.deepsearch-panel{--ds-bg:var(--we-panel-color,var(--dsw-alias-bg-base,#fff));--ds-line:var(--dsw-alias-border-l1,#e5e7eb);--ds-text:var(--dsw-alias-label-primary,#18212f);--ds-muted:var(--dsw-alias-label-secondary,#657080);--ds-hover:var(--dsw-alias-bg-layer-2,#f3f5f7);position:fixed;pointer-events:auto;z-index:10000;top:clamp(26px,12vh,128px);left:50%;transform:translateX(-50%);width:min(700px,calc(100vw - 32px));max-height:calc(100vh - clamp(26px,12vh,128px) - 24px);display:flex;flex-direction:column;color:var(--ds-text);background:var(--ds-bg);background:var(--ds-effective-surface,var(--ds-surface,var(--ds-bg)));backdrop-filter:var(--ds-effective-filter,var(--ds-filter,none));-webkit-backdrop-filter:var(--ds-effective-filter,var(--ds-filter,none));border:1px solid var(--ds-line);border-radius:16px;box-shadow:0 16px 60px #0002,0 2px 8px #0001;font-family:inherit;overflow:hidden;text-align:left;isolation:isolate}\n.deepsearch-panel *{box-sizing:border-box}.deepsearch-panel button,.deepsearch-panel input,.deepsearch-panel select,.deepsearch-jump button{font:inherit;color:inherit}.deepsearch-panel button{cursor:pointer}.deepsearch-panel button:disabled{cursor:default;opacity:.6}.deepsearch-panel button:focus-visible,.deepsearch-panel select:focus-visible,.deepsearch-jump button:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#3478f6);outline-offset:-2px}.deepsearch-search{display:flex;align-items:center;gap:14px;padding:19px 20px 17px;color:var(--ds-muted)}.deepsearch-search>input{min-width:0;flex:1;border:0;outline:none;background:transparent;font-size:18px;line-height:28px;color:var(--ds-text)}.deepsearch-search>input::placeholder{color:var(--ds-muted);opacity:.8}.deepsearch-escape{border:1px solid var(--ds-line);border-radius:5px;padding:2px 6px;background:none;font-size:11px!important;color:var(--ds-muted)!important}.deepsearch-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 16px 11px;border-bottom:1px solid var(--ds-line)}.deepsearch-tabs{display:flex;gap:4px}.deepsearch-tabs button{border:0;border-radius:6px;background:none;font-size:12px;padding:6px 12px;color:var(--ds-muted)}.deepsearch-tabs button[aria-selected=true]{background:var(--ds-hover);color:var(--ds-text);font-weight:600}.deepsearch-toolbar select{max-width:190px;min-width:0;border:0;outline:none;background:var(--ds-bg);font-size:11px;color:var(--ds-muted);padding:5px}.deepsearch-caption{display:flex;justify-content:space-between;gap:12px;padding:13px 20px 7px;font-size:11px;color:var(--ds-muted)}.deepsearch-caption label{display:flex;align-items:center;gap:4px;cursor:pointer}.deepsearch-caption input{margin:0;width:12px;height:12px;accent-color:var(--dsw-alias-brand-primary,#3478f6)}.deepsearch-results{overflow-y:auto;overscroll-behavior:contain;max-height:min(440px,50vh);padding:0 8px 8px;scroll-padding:8px;min-height:80px}.deepsearch-result{display:flex;width:100%;gap:12px;align-items:flex-start;border:0;border-radius:8px;background:transparent;padding:12px;text-align:left}.deepsearch-result[aria-selected=true]{background:var(--ds-hover)}.deepsearch-result-icon{color:var(--ds-muted);padding-top:2px;flex:none}.deepsearch-result-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:5px}.deepsearch-result-title{font-size:13px;line-height:20px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.deepsearch-snippet{font-size:12px;line-height:1.7;color:var(--ds-muted);white-space:pre-wrap;overflow-wrap:anywhere;display:block}.deepsearch-snippet mark{background:#ffe293;color:#382a09;border-radius:2px;padding:0 1px}.deepsearch-meta{font-size:10px;line-height:17px;color:var(--ds-muted);opacity:.85}.deepsearch-return{font-size:14px;align-self:center;color:var(--ds-muted);opacity:0}.deepsearch-result[aria-selected=true] .deepsearch-return{opacity:1}.deepsearch-footer{display:flex;justify-content:space-between;align-items:center;gap:8px;border-top:1px solid var(--ds-line);padding:12px 20px;color:var(--ds-muted);font-size:10px}.deepsearch-footer strong{font-weight:600;color:var(--ds-text)}.deepsearch-empty{display:flex;align-items:center;flex-direction:column;gap:12px;padding:37px 18px 32px;color:var(--ds-muted)}.deepsearch-empty>svg{width:27px;height:27px;opacity:.5}.deepsearch-empty strong{font-size:13px;font-weight:500;color:var(--ds-text)}.deepsearch-empty p{font-size:11px;margin:0;text-align:center}.deepsearch-error,.deepsearch-warning{padding:8px 20px;font-size:11px;color:var(--ds-text);background:var(--ds-hover)}.deepsearch-error button{margin-left:8px;border:0;background:none;text-decoration:underline}.deepsearch-more{background:transparent;border:0;border-top:1px solid var(--ds-line);padding:10px;font-size:11px;color:var(--ds-muted)}.deepsearch-jump{display:flex;flex-direction:column;flex:1;min-height:0;height:100%;position:relative}.deepsearch-jump-bar{display:flex;align-items:center;gap:12px;padding:9px 18px;flex-shrink:0;border-bottom:1px solid var(--dsw-alias-border-l1,#ddd);font-size:11px;color:var(--dsw-alias-label-secondary,#667);background:var(--dsw-alias-bg-base,#fff)}.deepsearch-jump-bar>span{flex:1}.deepsearch-jump button,.deepsearch-jump-loading button{border:1px solid var(--dsw-alias-border-l1,#ddd);border-radius:5px;background:var(--dsw-alias-bg-base,#fff);font:inherit;color:inherit;padding:3px 7px;cursor:pointer}.deepsearch-jump-loading{padding:24px;font:inherit;color:var(--dsw-alias-label-primary,#18212f)}.deepsearch-jump *::highlight(deepsearch-hit){background:#ffe293;color:#382a09}\n@media(max-width:520px){.deepsearch-panel{top:18px;width:calc(100vw - 20px);border-radius:12px}.deepsearch-search{padding:14px;gap:10px}.deepsearch-search>input{font-size:16px}.deepsearch-toolbar{padding:0 10px 10px}.deepsearch-toolbar select{max-width:130px}.deepsearch-caption{padding-left:14px;padding-right:14px}.deepsearch-footer{padding:11px 14px}.deepsearch-key-hint{display:none}.deepsearch-jump-bar{flex-wrap:wrap}}\n";
|
|
156
|
+
const appearanceCss = '.deepsearch-appearance{display:flex;flex-wrap:wrap;gap:12px;padding:12px 20px 16px;border-top:1px solid var(--ds-line);font-size:12px}.deepsearch-appearance label{display:flex;align-items:center;gap:8px}.deepsearch-appearance select,.deepsearch-appearance button{background:var(--ds-hover);border:1px solid var(--ds-line);border-radius:6px;padding:5px}.deepsearch-appearance input[type=range]{width:100px;accent-color:var(--dsw-alias-brand-primary,#3478f6)}.deepsearch-appearance input[type=color]{width:30px;height:24px;padding:0;border:0;background:none}.deepsearch-appearance p{width:100%;margin:0;color:var(--ds-muted)}/* Wallpaper Engine intentionally solidifies ordinary ARIA dialogs. Only this owned panel opts back into its selected material; never forge its runtime markers or change global settings. */body[data-we-glass-page][data-we-floater-solid] .deepsearch-panel[role=dialog][data-appearance]{background-color:var(--ds-effective-surface,var(--ds-surface,var(--ds-bg)))!important;backdrop-filter:var(--ds-effective-filter,var(--ds-filter,none))!important;-webkit-backdrop-filter:var(--ds-effective-filter,var(--ds-filter,none))!important}@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){.deepsearch-panel{--ds-effective-surface:var(--ds-bg);--ds-effective-filter:none}}@media(prefers-reduced-transparency:reduce){.deepsearch-panel{--ds-effective-surface:var(--ds-bg);--ds-effective-filter:none}}';
|
|
157
|
+
return {
|
|
158
|
+
inject: ['slots', 'layout', 'uiWorkspace', 'uiSession', 'sessions'],
|
|
159
|
+
apply(ctx) {
|
|
160
|
+
let opened = false, intent = null, releaseShell, previousFocus, preferredSessionId;
|
|
161
|
+
const listeners = new Set();
|
|
162
|
+
const notify = () => { for (const listener of listeners) listener(); };
|
|
163
|
+
const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener); };
|
|
164
|
+
const setOpen = value => {
|
|
165
|
+
if (value && !opened) {previousFocus = document.activeElement; preferredSessionId = currentSessionId(ctx.uiSession.adapter.current.getSnapshot(), ctx.sessions.list.getSnapshot());}
|
|
166
|
+
opened = value; notify();
|
|
167
|
+
if (!value && previousFocus?.isConnected) previousFocus.focus?.({preventScroll: true});
|
|
168
|
+
};
|
|
169
|
+
function clearIntent() {
|
|
170
|
+
const current = intent; intent = null;
|
|
171
|
+
const release = releaseShell; releaseShell = undefined;
|
|
172
|
+
current?.cancelDOM?.(); release?.(); window.CSS?.highlights?.delete('deepsearch-hit'); notify();
|
|
173
|
+
}
|
|
174
|
+
async function api(path, body, signal) {
|
|
175
|
+
const deadline = AbortSignal.timeout(20000);
|
|
176
|
+
const boundedSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
177
|
+
try {
|
|
178
|
+
const response = await fetch(new URL('api/deepsearch/' + path, document.baseURI), {
|
|
179
|
+
method: body ? 'POST' : 'GET', credentials: 'same-origin', cache: 'no-store', signal: boundedSignal,
|
|
180
|
+
headers: body ? {'Content-Type': 'application/json'} : undefined,
|
|
181
|
+
body: body ? JSON.stringify(body) : undefined
|
|
182
|
+
});
|
|
183
|
+
const raw = await response.text();
|
|
184
|
+
let value; try {value = JSON.parse(raw);} catch {throw new Error('搜索接口返回异常(HTTP ' + response.status + '),请重试');}
|
|
185
|
+
if (!response.ok) throw new Error(value.error || '搜索服务返回 HTTP ' + response.status);
|
|
186
|
+
return value;
|
|
187
|
+
} catch (failure) {
|
|
188
|
+
if (deadline.aborted || signal?.reason?.name === 'TimeoutError') throw new Error('搜索超时,请缩小工作区或重试');
|
|
189
|
+
throw failure;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function beginJump(item, query) {
|
|
193
|
+
clearIntent();
|
|
194
|
+
ctx.uiWorkspace.openSession(item.sessionId); ctx.layout.selectPanel(null);
|
|
195
|
+
if (!Number.isSafeInteger(item.seq)) {setOpen(false); return;}
|
|
196
|
+
const current = intent = {...item, query, loaded: false, status: '正在加载命中消息的历史…'};
|
|
197
|
+
const cancellation = new AbortController(), disposers = [];
|
|
198
|
+
let reference, released = false, observedBinding;
|
|
199
|
+
const isCurrent = () => intent === current && !cancellation.signal.aborted;
|
|
200
|
+
releaseShell = () => {
|
|
201
|
+
if (released) return; released = true; cancellation.abort();
|
|
202
|
+
current.cancelDOM?.(); for (const dispose of disposers.splice(0)) dispose(); reference?.release();
|
|
203
|
+
};
|
|
204
|
+
const watch = () => {
|
|
205
|
+
if (!isCurrent()) return;
|
|
206
|
+
const binding = ctx.uiSession.adapter.current.getSnapshot();
|
|
207
|
+
if (ctx.layout.panelInfo.getSnapshot().activePanelId !== null) {clearIntent(); return;}
|
|
208
|
+
if (observedBinding && binding !== observedBinding) {clearIntent(); return;}
|
|
209
|
+
if (binding.key === current.sessionId) observedBinding = binding;
|
|
210
|
+
else if (binding.key && binding.key !== initialBinding.key) clearIntent();
|
|
211
|
+
};
|
|
212
|
+
const initialBinding = ctx.uiSession.adapter.current.getSnapshot();
|
|
213
|
+
try {
|
|
214
|
+
disposers.push(ctx.uiSession.adapter.current.subscribe(watch), ctx.layout.panelInfo.subscribe(watch));
|
|
215
|
+
watch(); if (!isCurrent()) return;
|
|
216
|
+
disposers.push(ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({
|
|
217
|
+
name: 'conversation.session.header.utilities', id: 'deepsearch-location', order: 20,
|
|
218
|
+
}, JumpBody)));
|
|
219
|
+
reference = ctx.sessions.retain(current.sessionId, {source: 'gateway'});
|
|
220
|
+
loadExact(reference, current.seq, isCurrent, cancellation.signal).then(loaded => {
|
|
221
|
+
if (!loaded || !isCurrent()) return;
|
|
222
|
+
current.loaded = true; current.status = '历史已加载 · #' + current.seq + ';正在定位精确消息…'; notify();
|
|
223
|
+
}).catch(failure => {
|
|
224
|
+
if (!isCurrent()) return;
|
|
225
|
+
current.status = '历史加载失败:' + failure.message; notify();
|
|
226
|
+
});
|
|
227
|
+
setOpen(false); notify();
|
|
228
|
+
} catch (failure) {clearIntent(); throw failure;}
|
|
229
|
+
}
|
|
230
|
+
function JumpBody({sessionId, useChat, useSession}) {
|
|
231
|
+
const current = React.useSyncExternalStore(subscribe, () => intent);
|
|
232
|
+
const message = React.useSyncExternalStore(subscribe, () => intent?.status);
|
|
233
|
+
const chat = useChat(snapshot => snapshot), session = useSession(snapshot => snapshot), root = React.useRef(null);
|
|
234
|
+
const keys = selectedKeys(chat, current?.seq), keySignature = JSON.stringify(keys);
|
|
235
|
+
React.useEffect(() => {
|
|
236
|
+
if (!current || sessionId !== current.sessionId) return;
|
|
237
|
+
return () => {if (intent === current) clearIntent();};
|
|
238
|
+
}, [current, sessionId]);
|
|
239
|
+
React.useEffect(() => {
|
|
240
|
+
if (!current?.loaded || !root.current || sessionId !== current.sessionId) return;
|
|
241
|
+
const frame = root.current.closest('header[data-window-drag]')?.closest('[data-phase]');
|
|
242
|
+
const watchRoot = frame || root.current;
|
|
243
|
+
let container, cancelled = false, finished = false, scrolled = false, observer, timer, markedRow;
|
|
244
|
+
const alive = () => !cancelled && intent === current && ctx.uiSession.adapter.current.getSnapshot().key === sessionId && ctx.layout.panelInfo.getSnapshot().activePanelId === null;
|
|
245
|
+
const status = value => {if (alive() && current.status !== value) {current.status = value; notify();}};
|
|
246
|
+
const stopWatching = () => {clearTimeout(timer); observer?.disconnect(); watchRoot.removeEventListener('wheel', stop); watchRoot.removeEventListener('touchstart', stop);};
|
|
247
|
+
const cleanup = () => {
|
|
248
|
+
if (cancelled) return; cancelled = true; stopWatching();
|
|
249
|
+
markedRow?.removeAttribute('data-deepsearch-hit'); window.CSS?.highlights?.delete('deepsearch-hit');
|
|
250
|
+
if (current.cancelDOM === cleanup) current.cancelDOM = undefined;
|
|
251
|
+
};
|
|
252
|
+
const stop = () => {status('已停止自动定位;可继续手动阅读。'); finished = true; stopWatching();};
|
|
253
|
+
function locate() {
|
|
254
|
+
if (!alive() || finished) return;
|
|
255
|
+
const candidate = [...(frame?.querySelectorAll('[data-conversation-content][data-conversation-session]') || [])].find(content => content.closest('[data-phase]') === frame && content.dataset.conversationSession === sessionId);
|
|
256
|
+
container = candidate?.dataset.conversationSession === sessionId ? candidate : undefined;
|
|
257
|
+
if (!container) return;
|
|
258
|
+
const rows = [...container.querySelectorAll('[data-chat-flow] [data-chat-node-key]')].filter(row => row.closest('[data-conversation-content]') === container && keys.includes(row.getAttribute('data-chat-node-key')));
|
|
259
|
+
const row = rows.find(row => row.getClientRects().length);
|
|
260
|
+
if (!row) return;
|
|
261
|
+
if (!scrolled) {row.scrollIntoView({block: 'center', behavior: 'instant'}); scrolled = true;}
|
|
262
|
+
const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT, {acceptNode(node) {
|
|
263
|
+
return node.parentElement?.closest('script,style,button,input,textarea,[contenteditable="true"]') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
|
|
264
|
+
}});
|
|
265
|
+
let text = '', nodes = [], node;
|
|
266
|
+
while ((node = walker.nextNode()) && text.length < 200000) {nodes.push({node, start: text.length}); text += node.textContent;}
|
|
267
|
+
const escaped = current.query.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&');
|
|
268
|
+
const match = escaped && new RegExp(escaped, 'iu').exec(text);
|
|
269
|
+
if (match && window.CSS?.highlights && window.Highlight) {
|
|
270
|
+
const index = match.index, end = index + match[0].length;
|
|
271
|
+
const first = nodes.find(part => part.start + part.node.textContent.length > index), last = nodes.find(part => part.start + part.node.textContent.length >= end);
|
|
272
|
+
if (first && last) {
|
|
273
|
+
const range = document.createRange(); range.setStart(first.node, index - first.start); range.setEnd(last.node, end - last.start);
|
|
274
|
+
if (range.getClientRects().length) {
|
|
275
|
+
markedRow = row; row.setAttribute('data-deepsearch-hit', '');
|
|
276
|
+
window.CSS.highlights.set('deepsearch-hit', new window.Highlight(range));
|
|
277
|
+
status('已定位并高亮命中消息 · #' + current.seq); finished = true; stopWatching(); return;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
status('已定位对应消息 · #' + current.seq + ';该内容暂不能高亮。');
|
|
282
|
+
}
|
|
283
|
+
current.cancelDOM?.(); current.cancelDOM = cleanup;
|
|
284
|
+
watchRoot.addEventListener('wheel', stop, {passive: true}); watchRoot.addEventListener('touchstart', stop, {passive: true});
|
|
285
|
+
observer = new MutationObserver(locate); observer.observe(watchRoot, {childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['data-conversation-session']});
|
|
286
|
+
timer = setTimeout(() => {
|
|
287
|
+
if (!alive() || finished) return;
|
|
288
|
+
status(!container ? '历史已加载,但当前原生会话区域不可用;精确定位未完成。' : scrolled ? '已定位对应消息 · #' + current.seq + ';格式化内容可能无法逐字高亮。' : '历史已加载,但宿主未呈现对应消息;精确定位未完成。可返回搜索或手动查看。');
|
|
289
|
+
finished = true; stopWatching();
|
|
290
|
+
}, 8000);
|
|
291
|
+
locate(); return cleanup;
|
|
292
|
+
}, [current, current?.loaded, sessionId, keySignature, session?.openState]);
|
|
293
|
+
if (!current || sessionId !== current.sessionId) return null;
|
|
294
|
+
return h('div', {className: 'deepsearch-native-location', ref: root, style: {display: 'flex', alignItems: 'center', gap: 6, maxWidth: 'min(520px,50vw)', fontSize: 12}},
|
|
295
|
+
h('style', null, '[data-deepsearch-hit]::highlight(deepsearch-hit),[data-deepsearch-hit] *::highlight(deepsearch-hit){background:#ffe69a;color:#302600}'),
|
|
296
|
+
h('span', {role: 'status', style: {overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}, title: message}, message),
|
|
297
|
+
h('button', {onClick: () => {clearIntent(); setOpen(true);}, style: {whiteSpace: 'nowrap'}}, '返回搜索'),
|
|
298
|
+
h('button', {onClick: clearIntent, style: {whiteSpace: 'nowrap'}}, '退出定位'));
|
|
299
|
+
}
|
|
300
|
+
function Overlay() {
|
|
301
|
+
const visible = React.useSyncExternalStore(subscribe, () => opened);
|
|
302
|
+
const [query, setQuery] = React.useState(''), [tab, setTab] = React.useState('all');
|
|
303
|
+
const [workspace, setWorkspace] = React.useState(''), [archived, setArchived] = React.useState(false);
|
|
304
|
+
const [catalog, setCatalog] = React.useState({sessions: [], workspaces: []}), [catalogError, setCatalogError] = React.useState('');
|
|
305
|
+
const [result, setResult] = React.useState({items: [], cursor: null, scanned: 0, totalSessions: 0, warnings: []});
|
|
306
|
+
const [busy, setBusy] = React.useState(false), [error, setError] = React.useState(''), [index, setIndex] = React.useState(0), [retry, setRetry] = React.useState(0);
|
|
307
|
+
const panel = React.useRef(null), input = React.useRef(null), list = React.useRef(null), control = React.useRef(null), generation = React.useRef(0), requestRef = React.useRef(null);
|
|
308
|
+
const [composing, setComposing] = React.useState(false);
|
|
309
|
+
const [appearance, setAppearance] = React.useState(() => {try {return readAppearance(window.localStorage);} catch {return appearancePrefs(null);}});
|
|
310
|
+
const [settings, setSettings] = React.useState(false), [appearanceError, setAppearanceError] = React.useState('');
|
|
311
|
+
const updateAppearance = value => {
|
|
312
|
+
const next = appearancePrefs(value); setAppearance(next);
|
|
313
|
+
let saved = false; try {saved = saveAppearance(window.localStorage, next);} catch {}
|
|
314
|
+
setAppearanceError(saved ? '' : '本次外观已应用,但浏览器禁止保存;重新打开后可能恢复默认。');
|
|
315
|
+
};
|
|
316
|
+
React.useEffect(() => {if (!visible) setComposing(false);}, [visible]);
|
|
317
|
+
const request = {query: query.trim(), ...(workspace ? {workspaceId: workspace} : {}), ...(preferredSessionId ? {preferredSessionId} : {}), includeArchived: archived};
|
|
318
|
+
requestRef.current = request;
|
|
319
|
+
const key = JSON.stringify(request);
|
|
320
|
+
const renderKey = JSON.stringify([key, tab, visible, composing, retry]);
|
|
321
|
+
const activeRender = React.useRef(renderKey); activeRender.current = renderKey;
|
|
322
|
+
React.useEffect(() => {
|
|
323
|
+
if (!visible) return;
|
|
324
|
+
input.current?.focus();
|
|
325
|
+
const controller = new AbortController();
|
|
326
|
+
setCatalogError('');
|
|
327
|
+
api('catalog', null, controller.signal).then(setCatalog).catch(failure => {if (!controller.signal.aborted) setCatalogError(failure.message);});
|
|
328
|
+
const outside = event => {if (panel.current && !panel.current.contains(event.target)) {event.preventDefault(); event.stopPropagation(); setOpen(false);}};
|
|
329
|
+
document.addEventListener('pointerdown', outside, true);
|
|
330
|
+
return () => {controller.abort(); document.removeEventListener('pointerdown', outside, true);};
|
|
331
|
+
}, [visible, retry]);
|
|
332
|
+
async function fetchPage(cursor, append, owner, requestValue, controller, renderOwner) {
|
|
333
|
+
try {
|
|
334
|
+
await scanPages({cursor, initialItems: append ? result.items : [], signal: controller.signal,
|
|
335
|
+
isCurrent: () => generation.current === owner && activeRender.current === renderOwner,
|
|
336
|
+
requestPage: (next, signal) => api('search', {...requestValue, ...(next ? {cursor: next} : {})}, signal),
|
|
337
|
+
onPage: page => setResult({...page, renderOwner})});
|
|
338
|
+
} catch (failure) {if (!controller.signal.aborted && generation.current === owner && activeRender.current === renderOwner) setError(failure.message);}
|
|
339
|
+
finally {if (!controller.signal.aborted && generation.current === owner && activeRender.current === renderOwner) setBusy(false);}
|
|
340
|
+
}
|
|
341
|
+
React.useEffect(() => {
|
|
342
|
+
control.current?.abort(); const controller = new AbortController(); control.current = controller;
|
|
343
|
+
const owner = ++generation.current;
|
|
344
|
+
setResult({items: [], cursor: null, scanned: 0, totalSessions: 0, warnings: []}); setIndex(0); setError(''); setBusy(false);
|
|
345
|
+
if (!visible || !request.query || tab === 'projects' || composing) return () => controller.abort();
|
|
346
|
+
setBusy(true);
|
|
347
|
+
const timer = setTimeout(() => fetchPage(null, false, owner, requestRef.current, controller, renderKey), 220);
|
|
348
|
+
return () => {clearTimeout(timer); controller.abort(); control.current?.abort();};
|
|
349
|
+
}, [key, visible, tab, composing, retry]);
|
|
350
|
+
const projects = (catalog.workspaces || []).filter(project => (!workspace || project.id === workspace) &&
|
|
351
|
+
(!request.query || (project.title || '').toLocaleLowerCase().includes(request.query.toLocaleLowerCase()))).map(project => ({...project, kind: 'project'}));
|
|
352
|
+
const recent = (catalog.sessions || []).filter(session => !workspace || session.workspaceId === workspace).slice(0, 7).map(session => ({...session, kind: 'title', sessionId: session.id}));
|
|
353
|
+
const visibleHits = result.renderOwner === renderKey ? result.items : [];
|
|
354
|
+
const items = tab === 'projects' ? projects : request.query ? (tab === 'all' ? projects.slice(0, 3).concat(visibleHits) : visibleHits) : recent;
|
|
355
|
+
React.useEffect(() => {setIndex(old => Math.min(old, Math.max(0, items.length - 1)));}, [items.length]);
|
|
356
|
+
React.useEffect(() => {list.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({block: 'nearest'});}, [index]);
|
|
357
|
+
function choose(item) {
|
|
358
|
+
if (!item) return;
|
|
359
|
+
if (item.kind === 'project') {setWorkspace(item.id); setTab('conversations'); setQuery(''); input.current?.focus(); return;}
|
|
360
|
+
try {beginJump(item, request.query);} catch (failure) {setError('打开失败:' + failure.message);}
|
|
361
|
+
}
|
|
362
|
+
if (!visible) return null;
|
|
363
|
+
const more = () => {
|
|
364
|
+
if (busy || !result.cursor || result.items.length >= MAX_RESULTS) return;
|
|
365
|
+
control.current?.abort(); const controller = new AbortController(); control.current = controller;
|
|
366
|
+
const owner = ++generation.current; setBusy(true); setError('');
|
|
367
|
+
fetchPage(result.cursor, true, owner, request, controller, renderKey);
|
|
368
|
+
};
|
|
369
|
+
const displayResult = result.renderOwner === renderKey ? result : {items: [], scanned: 0, totalSessions: 0, warnings: [], cursor: null};
|
|
370
|
+
const status = searchStatus({busy: busy || (request.query && tab !== 'projects' && !composing && result.renderOwner !== renderKey && !error), error, result: displayResult, query: request.query, projects: tab === 'projects'});
|
|
371
|
+
function onKey(event) {
|
|
372
|
+
if (event.isComposing || event.nativeEvent?.isComposing || event.keyCode === 229 || composing) return;
|
|
373
|
+
if (event.key === 'Escape') {event.preventDefault(); event.stopPropagation(); setOpen(false);}
|
|
374
|
+
if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && event.target === input.current) {event.preventDefault(); setIndex(old => items.length ? (old + (event.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length : 0);}
|
|
375
|
+
if (event.key === 'Enter' && event.target === input.current) {event.preventDefault(); choose(items[index]);}
|
|
376
|
+
if (event.key === 'Tab') {
|
|
377
|
+
const focusable = [...panel.current.querySelectorAll('button:not(:disabled),input,select,[tabindex="0"]')].filter(node => node.tabIndex >= 0 && !node.closest('[hidden],[inert]') && node.getClientRects().length > 0);
|
|
378
|
+
const first = focusable[0], last = focusable[focusable.length - 1];
|
|
379
|
+
if (event.shiftKey && document.activeElement === first) {event.preventDefault(); last?.focus();}
|
|
380
|
+
else if (!event.shiftKey && document.activeElement === last) {event.preventDefault(); first?.focus();}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return h('section', {className: 'deepsearch-panel', style: appearanceStyle(appearance), 'data-appearance': appearance.mode, role: 'dialog', 'aria-label': 'DeepSearch 全文搜索', 'aria-modal': false, ref: panel, onKeyDown: onKey},
|
|
384
|
+
h('style', null, css + appearanceCss),
|
|
385
|
+
h('header', {className: 'deepsearch-search'}, h(Icon),
|
|
386
|
+
h('input', {ref: input, value: query, maxLength: 256, placeholder: '搜索对话里的任何一句话…', 'aria-label': '搜索会话正文', role: 'combobox', 'aria-expanded': true, 'aria-controls': 'deepsearch-results', 'aria-activedescendant': items[index] ? 'deepsearch-result-' + index : undefined, autoComplete: 'off', spellCheck: false, onChange: event => setQuery(event.target.value), onCompositionStart: () => setComposing(true), onCompositionEnd: () => setComposing(false)}),
|
|
387
|
+
h('button', {className: 'deepsearch-escape', 'aria-expanded': settings, 'aria-controls': 'deepsearch-appearance', onClick: () => setSettings(value => !value)}, '外观'),
|
|
388
|
+
h('button', {className: 'deepsearch-escape', onClick: () => setOpen(false), 'aria-label': '关闭 DeepSearch'}, 'esc')),
|
|
389
|
+
settings && h('div', {className: 'deepsearch-appearance', id: 'deepsearch-appearance', role: 'group', 'aria-label': '面板外观'},
|
|
390
|
+
h('label', null, '背景模式', h('select', {value: appearance.mode, onChange: e => updateAppearance({...appearance, mode:e.target.value})},
|
|
391
|
+
...[['glass','毛玻璃'],['theme','跟随 DSH'],['custom','自定义']].map(([value,label]) => h('option',{key:value,value},label)))),
|
|
392
|
+
appearance.mode === 'custom' && h('label', null, '底色', h('input', {type:'color', value:appearance.color, onChange:e=>updateAppearance({...appearance,color:e.target.value})})),
|
|
393
|
+
appearance.mode === 'custom' && h('label', null, '不透明度 ' + appearance.opacity + '%', h('input', {type:'range', min:55, max:100, value:appearance.opacity, onChange:e=>updateAppearance({...appearance,opacity:Number(e.target.value)})})),
|
|
394
|
+
appearance.mode !== 'theme' && h('label', null, '模糊 ' + appearance.blur + 'px', h('input', {type:'range', min:0, max:32, value:appearance.blur, onChange:e=>updateAppearance({...appearance,blur:Number(e.target.value)})})),
|
|
395
|
+
h('button', {onClick:()=>updateAppearance(null)}, '恢复默认'),
|
|
396
|
+
appearanceError && h('p', {role:'status'}, appearanceError)),
|
|
397
|
+
h('div', {className: 'deepsearch-toolbar'}, h('div', {className: 'deepsearch-tabs', role: 'tablist', 'aria-label': '结果类型'},
|
|
398
|
+
...[['all', '全部'], ['conversations', '对话'], ['projects', '项目']].map(([value, label]) => h('button', {key: value, role: 'tab', 'aria-selected': tab === value, onClick: () => setTab(value)}, label))),
|
|
399
|
+
h('select', {'aria-label': '工作区范围', value: workspace, onChange: event => setWorkspace(event.target.value)}, h('option', {value: ''}, '所有工作区'), ...(catalog.workspaces || []).map(project => h('option', {key: project.id, value: project.id}, project.title)))),
|
|
400
|
+
h('div', {className: 'deepsearch-caption'}, h('span', null, request.query ? (tab === 'projects' ? '匹配项目' : '标题 · 你的输入 · 助手回复') : '最近对话'),
|
|
401
|
+
tab !== 'projects' && h('label', null, h('input', {type: 'checkbox', checked: archived, onChange: event => setArchived(event.target.checked)}), '含归档')),
|
|
402
|
+
h('div', {className: 'deepsearch-results', ref: list, role: 'listbox', id: 'deepsearch-results', 'aria-label': '搜索结果', 'aria-busy': busy},
|
|
403
|
+
...items.map((item, i) => h('button', {key: item.id, id: 'deepsearch-result-' + i, className: 'deepsearch-result', tabIndex: -1, role: 'option', 'aria-selected': index === i, onMouseEnter: () => setIndex(i), onClick: () => choose(item)},
|
|
404
|
+
h('span', {className: 'deepsearch-result-icon'}, h(Icon, {folder: item.kind === 'project'})),
|
|
405
|
+
h('span', {className: 'deepsearch-result-text'}, h('span', {className: 'deepsearch-result-title'}, item.title || '未命名会话'),
|
|
406
|
+
item.snippet && h('span', {className: 'deepsearch-snippet'}, h(Mark, {text: item.snippet, range: item.range})),
|
|
407
|
+
h('span', {className: 'deepsearch-meta'}, item.kind === 'project' ? '工作区 · 点击限定搜索范围' :
|
|
408
|
+
[item.role === 'user' ? '你' : item.role === 'assistant' ? '助手' : '会话标题', item.workspaceTitle, formatMessageTime(item.time)].filter(Boolean).join(' · '))), h('span', {className: 'deepsearch-return', 'aria-hidden': true}, '↵'))),
|
|
409
|
+
!items.length && h('div', {className: 'deepsearch-empty', role: 'status'}, h(Icon), h('strong', null, status.empty),
|
|
410
|
+
h('p', null, busy ? '逐批读取本地历史,不上传你的对话。' : request.query ? '支持连续中文片段,不需要输入整句话。' : '中文片段、英文关键词,都可以。'))),
|
|
411
|
+
(error || catalogError) && h('div', {className: 'deepsearch-error', role: 'alert'}, error || '目录读取失败:' + catalogError, h('button', {onClick: () => error && displayResult.cursor ? more() : setRetry(value => value + 1)}, '重试')),
|
|
412
|
+
displayResult.warnings?.length > 0 && h('div', {className: 'deepsearch-warning', role: 'status'}, '部分历史读取失败(' + displayResult.warnings.length + ');当前结果可能不完整。'),
|
|
413
|
+
tab !== 'projects' && displayResult.cursor && h('button', {className: 'deepsearch-more', onClick: more, disabled: busy || result.items.length >= MAX_RESULTS}, result.items.length >= MAX_RESULTS ? '已显示 200 条,请缩小搜索范围' : busy ? '正在继续扫描…' : '继续搜索剩余历史'),
|
|
414
|
+
h('footer', {className: 'deepsearch-footer'}, h('span', null, h('strong', null, 'DeepSearch'), ' 0.1.13 / 本地全文'),
|
|
415
|
+
h('span', {role: 'status'}, status.footer),
|
|
416
|
+
h('span', {className: 'deepsearch-key-hint'}, '↑↓ 选择 ↵ 打开')));
|
|
417
|
+
}
|
|
418
|
+
ctx.effect(() => {
|
|
419
|
+
const onKey = event => {if (!isShortcut(event)) return; event.preventDefault(); event.stopPropagation(); setOpen(!opened);};
|
|
420
|
+
window.addEventListener('keydown', onKey, true);
|
|
421
|
+
return () => {window.removeEventListener('keydown', onKey, true); setOpen(false); clearIntent();};
|
|
422
|
+
});
|
|
423
|
+
ctx.slots.inject('shell.overlay', () => ctx.slots.register({name: 'shell.overlay', id: 'deepsearch'}, Overlay));
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
});
|
package/cordis.patch.yml
ADDED
package/host.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {createSearchService, SearchError} from './search-core.js?deepsearch=0.1.13';
|
|
2
|
+
|
|
3
|
+
export const inject = ['sessionQuery', 'sessionController', 'workspaceController', 'connection'];
|
|
4
|
+
export const MAX_BODY_BYTES = 16 * 1024;
|
|
5
|
+
|
|
6
|
+
function json(value, status = 200, extraHeaders = {}) {
|
|
7
|
+
return new Response(JSON.stringify(value), {status, headers: {
|
|
8
|
+
'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
|
|
9
|
+
'X-Content-Type-Options': 'nosniff', ...extraHeaders,
|
|
10
|
+
}});
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function readJson(request) {
|
|
14
|
+
request.signal.throwIfAborted();
|
|
15
|
+
if (!/^application\/json(?:\s*;|$)/iu.test(request.headers.get('content-type') ?? ''))
|
|
16
|
+
throw new SearchError('application/json content type required', 415, 'UNSUPPORTED_MEDIA_TYPE');
|
|
17
|
+
const declared = request.headers.get('content-length');
|
|
18
|
+
if (declared !== null && (!/^\d+$/u.test(declared) || Number(declared) > MAX_BODY_BYTES))
|
|
19
|
+
throw new SearchError('JSON body exceeds 16 KiB or has invalid Content-Length', 413, 'BODY_TOO_LARGE');
|
|
20
|
+
const reader = request.body?.getReader();
|
|
21
|
+
if (!reader) throw new SearchError('JSON body required');
|
|
22
|
+
const chunks = []; let length = 0;
|
|
23
|
+
try {
|
|
24
|
+
while (true) {
|
|
25
|
+
request.signal.throwIfAborted();
|
|
26
|
+
const {done, value} = await reader.read();
|
|
27
|
+
if (done) break;
|
|
28
|
+
length += value.byteLength;
|
|
29
|
+
if (length > MAX_BODY_BYTES) {
|
|
30
|
+
await reader.cancel();
|
|
31
|
+
throw new SearchError('JSON body exceeds 16 KiB', 413, 'BODY_TOO_LARGE');
|
|
32
|
+
}
|
|
33
|
+
chunks.push(value);
|
|
34
|
+
}
|
|
35
|
+
} finally {reader.releaseLock();}
|
|
36
|
+
request.signal.throwIfAborted();
|
|
37
|
+
const bytes = new Uint8Array(length); let offset = 0;
|
|
38
|
+
for (const chunk of chunks) {bytes.set(chunk, offset); offset += chunk.byteLength;}
|
|
39
|
+
try {return JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes));}
|
|
40
|
+
catch {throw new SearchError('Invalid JSON body');}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function apply(ctx) {
|
|
44
|
+
const service = createSearchService(ctx);
|
|
45
|
+
// Host performs Host/Origin, authentication and owner checks before fetch,
|
|
46
|
+
// and binds route registration cleanup to the plugin owner effect.
|
|
47
|
+
const handler = (method, operation) => async request => {
|
|
48
|
+
if (request.method !== method) return json({error: method + ' required', code: 'METHOD_NOT_ALLOWED'}, 405, {Allow: method});
|
|
49
|
+
try {return json(await operation(request));}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (request.signal.aborted || error?.name === 'AbortError') return json({error: 'Search cancelled', code: 'CANCELLED'}, 499);
|
|
52
|
+
if (error instanceof SearchError) return json({error: error.message, code: error.code}, error.status);
|
|
53
|
+
return json({error: 'History service unavailable', code: 'SERVICE_UNAVAILABLE'}, 503);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
ctx.connection.fetch.register({path: '/api/deepsearch/search', methods: ['POST'], requestBody: 'buffered',
|
|
57
|
+
fetch: handler('POST', async request => service.search(await readJson(request), request.signal))});
|
|
58
|
+
ctx.connection.fetch.register({path: '/api/deepsearch/catalog', methods: ['GET'], requestBody: 'buffered',
|
|
59
|
+
fetch: handler('GET', request => service.catalog(request.signal))});
|
|
60
|
+
// Abort in-flight operations and discard cursor metadata on plugin unload.
|
|
61
|
+
ctx.effect(() => () => service.dispose());
|
|
62
|
+
}
|
package/icon.svg
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#0f2735"/><circle cx="28" cy="27" r="14" fill="none" stroke="#8ee2d0" stroke-width="5"/><path d="m39 38 12 12" stroke="#8ee2d0" stroke-width="5" stroke-linecap="round"/><path d="M21 23h14M21 30h10" stroke="#eefbf7" stroke-width="3" stroke-linecap="round"/></svg>
|
package/locale/en.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@renyuluo/dsh-deepsearch",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.13",
|
|
4
|
+
"description": "Local-first conversation full-text search for DeepSeek Harness, with Chinese substring matching and native message navigation.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"publishConfig": {"access": "public", "registry": "https://registry.npmjs.org/"},
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "RonnyLuo",
|
|
9
|
+
"homepage": "https://github.com/luorenyu/dsh-deepsearch",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/luorenyu/dsh-deepsearch.git"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/luorenyu/dsh-deepsearch/issues"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"dsh",
|
|
19
|
+
"deepseek-harness",
|
|
20
|
+
"deepsearch",
|
|
21
|
+
"search",
|
|
22
|
+
"full-text",
|
|
23
|
+
"session",
|
|
24
|
+
"conversation",
|
|
25
|
+
"中文",
|
|
26
|
+
"全文搜索",
|
|
27
|
+
"会话搜索"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22",
|
|
31
|
+
"dsh": "0.2.2-rc.3"
|
|
32
|
+
},
|
|
33
|
+
"exports": {
|
|
34
|
+
".": "./runtime-0.1.13.js",
|
|
35
|
+
"./client": "./client.js",
|
|
36
|
+
"./package.json": "./package.json",
|
|
37
|
+
"./locale/en.json": "./locale/en.json",
|
|
38
|
+
"./locale/zh-CN.json": "./locale/zh-CN.json",
|
|
39
|
+
"./icon": "./icon.svg"
|
|
40
|
+
},
|
|
41
|
+
"icon": "./icon.svg",
|
|
42
|
+
"files": [
|
|
43
|
+
"runtime-0.1.13.js",
|
|
44
|
+
"host.js",
|
|
45
|
+
"search-core.js",
|
|
46
|
+
"client.js",
|
|
47
|
+
"cordis.patch.yml",
|
|
48
|
+
"locale",
|
|
49
|
+
"icon.svg",
|
|
50
|
+
"README.md",
|
|
51
|
+
"LICENSE"
|
|
52
|
+
],
|
|
53
|
+
"dsh": {
|
|
54
|
+
"bundle": {
|
|
55
|
+
"patch": "./cordis.patch.yml"
|
|
56
|
+
},
|
|
57
|
+
"client": {
|
|
58
|
+
"platform": "web",
|
|
59
|
+
"immediately": true,
|
|
60
|
+
"inject": [
|
|
61
|
+
"@deepseek-ai/dsh-client-ui-conversation",
|
|
62
|
+
"@deepseek-ai/dsh-client-ui-session"
|
|
63
|
+
]
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
"scripts": {
|
|
67
|
+
"test": "node --test tests/*.test.js",
|
|
68
|
+
"check": "node --check client.js && node --check host.js && node --check search-core.js && node --check runtime-0.1.13.js"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './host.js?deepsearch=0.1.13';
|
package/search-core.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export const LIMITS = Object.freeze({pageSize: 40, sessionsPerPage: 8, eventsPerPage: 2048,
|
|
4
|
+
maxSessions: 10000, maxWorkspaces: 2000, maxConcurrent: 4, maxWarnings: 32, maxCursors: 16, cacheBytes: 8 * 1024 * 1024,
|
|
5
|
+
cursorTtlMs: 120000, operationTimeoutMs: 15000, queryLength: 1024, snippetLength: 1280});
|
|
6
|
+
|
|
7
|
+
export class SearchError extends Error {
|
|
8
|
+
constructor(message, status = 400, code = 'INVALID_REQUEST') {
|
|
9
|
+
super(message); this.name = 'SearchError'; this.status = status; this.code = code;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function validateInput(input) {
|
|
14
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new SearchError('Expected a JSON object');
|
|
15
|
+
const allowed = new Set(['query', 'cursor', 'sessionId', 'preferredSessionId', 'workspaceId', 'includeArchived']);
|
|
16
|
+
if (Object.keys(input).some(key => !allowed.has(key))) throw new SearchError('Unknown search parameter');
|
|
17
|
+
if (typeof input.query !== 'string' || !input.query.trim() || input.query.length > LIMITS.queryLength)
|
|
18
|
+
throw new SearchError('query must contain 1–1024 characters');
|
|
19
|
+
const result = {query: input.query, includeArchived: input.includeArchived === undefined ? false : input.includeArchived};
|
|
20
|
+
if (typeof result.includeArchived !== 'boolean') throw new SearchError('includeArchived must be boolean');
|
|
21
|
+
for (const key of ['cursor', 'sessionId', 'preferredSessionId', 'workspaceId']) {
|
|
22
|
+
if (input[key] === undefined) continue;
|
|
23
|
+
if (typeof input[key] !== 'string' || !input[key].trim() || input[key].length > 512)
|
|
24
|
+
throw new SearchError(key + ' must be nonempty text of at most 512 characters');
|
|
25
|
+
result[key] = input[key];
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const yieldTask = () => new Promise(resolve => setImmediate(resolve));
|
|
31
|
+
const check = signal => signal?.throwIfAborted();
|
|
32
|
+
const keyOf = input => JSON.stringify([input.query, input.sessionId ?? null, input.workspaceId ?? null, input.includeArchived, input.preferredSessionId ?? null]);
|
|
33
|
+
const textOf = content => (Array.isArray(content) ? content : []).filter(block => block.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n');
|
|
34
|
+
const pathKey = value => {
|
|
35
|
+
if (typeof value !== 'string' || !value) return '';
|
|
36
|
+
const path = value.replace(/\\/g, '/').replace(/\/+$/u, '') || '/';
|
|
37
|
+
return /^[a-z]:(?:\/|$)/iu.test(path) || path.startsWith('//') ? path.toLowerCase() : path;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// Escaped literal only. Original UTF-16 match indices survive Unicode casing.
|
|
41
|
+
export async function literalSnippet(text, query, signal) {
|
|
42
|
+
const escaped = query.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&');
|
|
43
|
+
const pattern = new RegExp(escaped, 'iu');
|
|
44
|
+
const chunkSize = 65536;
|
|
45
|
+
for (let offset = 0; offset < text.length; offset += chunkSize) {
|
|
46
|
+
check(signal);
|
|
47
|
+
const start = offset > 0 && /[\uDC00-\uDFFF]/u.test(text[offset]) ? offset - 1 : offset;
|
|
48
|
+
const match = pattern.exec(text.slice(start, offset + chunkSize + query.length + 2));
|
|
49
|
+
if (match) {
|
|
50
|
+
const index = start + match.index;
|
|
51
|
+
let left = Math.max(0, index - 90);
|
|
52
|
+
let right = Math.min(text.length, Math.max(left + 320, index + match[0].length + 90));
|
|
53
|
+
right = Math.min(right, left + LIMITS.snippetLength - 2);
|
|
54
|
+
if (left && /[\uDC00-\uDFFF]/u.test(text[left])) left--;
|
|
55
|
+
if (right < text.length && /[\uDC00-\uDFFF]/u.test(text[right])) right++;
|
|
56
|
+
const prefix = left ? '…' : '';
|
|
57
|
+
return {snippet: prefix + text.slice(left, right) + (right < text.length ? '…' : ''),
|
|
58
|
+
range: [prefix.length + index - left, prefix.length + index - left + match[0].length]};
|
|
59
|
+
}
|
|
60
|
+
await yieldTask();
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Provider cancellation is cooperative; stop waiting even if a provider ignores it.
|
|
66
|
+
// Keep both settlement handlers attached so late rejections are always consumed.
|
|
67
|
+
function awaitProvider(signal, operation, discard) {
|
|
68
|
+
check(signal);
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
let settled = false;
|
|
71
|
+
const abort = () => {
|
|
72
|
+
if (settled) return;
|
|
73
|
+
settled = true; signal.removeEventListener('abort', abort); reject(signal.reason);
|
|
74
|
+
};
|
|
75
|
+
signal.addEventListener('abort', abort, {once: true});
|
|
76
|
+
Promise.resolve().then(() => {check(signal); return operation();}).then(value => {
|
|
77
|
+
if (settled) {
|
|
78
|
+
try {discard?.(value);} catch { /* Late cleanup cannot change the completed request. */ }
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
settled = true; signal.removeEventListener('abort', abort); resolve(value);
|
|
82
|
+
}, error => {
|
|
83
|
+
if (settled) return;
|
|
84
|
+
settled = true; signal.removeEventListener('abort', abort); reject(error);
|
|
85
|
+
});
|
|
86
|
+
if (signal.aborted) abort();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function workspaceSnapshot(controller, signal) {
|
|
91
|
+
const stream = controller.follow(signal);
|
|
92
|
+
try {
|
|
93
|
+
const frame = await awaitProvider(signal, () => stream.next()); check(signal);
|
|
94
|
+
if (frame.done || frame.value.type !== 'baseline') throw new SearchError('Workspace catalog unavailable', 503, 'CATALOG_UNAVAILABLE');
|
|
95
|
+
return frame.value.value;
|
|
96
|
+
} finally {
|
|
97
|
+
// Iterator return may queue behind a pending next(); never let cleanup block cancellation.
|
|
98
|
+
const closing = Promise.resolve().then(() => stream.return());
|
|
99
|
+
closing.catch(() => {});
|
|
100
|
+
if (!signal.aborted) await awaitProvider(signal, () => closing);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function readCatalog(services, includeArchived, signal) {
|
|
105
|
+
check(signal);
|
|
106
|
+
const [records, list, snapshot] = await Promise.all([
|
|
107
|
+
awaitProvider(signal, () => services.sessionQuery.listSessions(signal)),
|
|
108
|
+
awaitProvider(signal, () => services.sessionController.list({}, signal)),
|
|
109
|
+
workspaceSnapshot(services.workspaceController, signal),
|
|
110
|
+
]);
|
|
111
|
+
check(signal);
|
|
112
|
+
if (records.length > LIMITS.maxSessions || list.items.length > LIMITS.maxSessions || snapshot.items.length > LIMITS.maxWorkspaces)
|
|
113
|
+
throw new SearchError('Catalog exceeds the supported 10000-session / 2000-workspace bound', 503, 'CATALOG_LIMIT');
|
|
114
|
+
const metadata = new Map(list.items.map(row => [row.sessionId, row]));
|
|
115
|
+
const membership = new Map(), roots = new Map();
|
|
116
|
+
const assign = (map, id, workspaceId) => map.set(id, map.has(id) && map.get(id) !== workspaceId ? undefined : workspaceId);
|
|
117
|
+
const workspaces = snapshot.items.map(workspace => {
|
|
118
|
+
for (const id of workspace.sessionIds) assign(membership, id, workspace.workspaceId);
|
|
119
|
+
const root = pathKey(workspace.path); if (root) assign(roots, root, workspace.workspaceId);
|
|
120
|
+
return {id: workspace.workspaceId, title: workspace.title.slice(0, 512)};
|
|
121
|
+
});
|
|
122
|
+
const archived = new Set(snapshot.archivedSessionIds);
|
|
123
|
+
const rows = [], seen = new Set();
|
|
124
|
+
for (const {header} of records) {
|
|
125
|
+
check(signal);
|
|
126
|
+
if (seen.has(header.id)) continue;
|
|
127
|
+
seen.add(header.id);
|
|
128
|
+
const row = metadata.get(header.id);
|
|
129
|
+
if (header.origin === 'subagent' || row?.origin === 'subagent' || row?.blank || (!includeArchived && archived.has(header.id))) continue;
|
|
130
|
+
rows.push({id: header.id, title: row?.projections?.values?.title, updatedAt: row?.updatedAt ?? header.createdAt ?? 0,
|
|
131
|
+
workspaceId: membership.has(header.id) ? membership.get(header.id) : roots.get(pathKey(row?.cwd ?? header.cwd))});
|
|
132
|
+
}
|
|
133
|
+
const missing = rows.filter(row => row.title == null);
|
|
134
|
+
for (let offset = 0; offset < missing.length; offset += 128) {
|
|
135
|
+
check(signal);
|
|
136
|
+
const titles = await awaitProvider(signal, () => services.sessionQuery.readTitleSnapshots(missing.slice(offset, offset + 128).map(row => row.id), signal));
|
|
137
|
+
const byId = new Map(titles.filter(result => result.status === 'fulfilled').map(result => [result.sessionId, result.value.title?.title]));
|
|
138
|
+
for (const row of missing.slice(offset, offset + 128)) row.title = byId.get(row.id);
|
|
139
|
+
await yieldTask();
|
|
140
|
+
}
|
|
141
|
+
for (const row of rows) row.title = typeof row.title === 'string' ? row.title : '';
|
|
142
|
+
rows.sort((a, b) => b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
143
|
+
return {workspaces, rows};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Scan the tail directly and persist only an array index and turn eligibility,
|
|
147
|
+
// never a materialized text document list. A completed end makes exactly its
|
|
148
|
+
// last assistant message eligible; even an interrupted/tool-call last message
|
|
149
|
+
// consumes eligibility so earlier commentary cannot become a false final.
|
|
150
|
+
function documentAt(events, index, position) {
|
|
151
|
+
const event = events[index], data = event.data;
|
|
152
|
+
if (event.type === 'turn/start') position.turn = null;
|
|
153
|
+
if (event.type === 'turn/end') position.turn = data.reason?.kind === 'completed' ? data.turn : null;
|
|
154
|
+
if (event.type === 'user/message' && data.source?.kind === 'user')
|
|
155
|
+
return {seq: event.seq, time: event.time, role: 'user', text: textOf(data.content)};
|
|
156
|
+
if (event.type !== 'assistant/message' || position.turn == null || data.turn !== position.turn) return null;
|
|
157
|
+
position.turn = null;
|
|
158
|
+
if (data.interrupted) return null;
|
|
159
|
+
const content = data.message?.content;
|
|
160
|
+
if (!Array.isArray(content) || content.some(block => block.type === 'tool-call')) return null;
|
|
161
|
+
return {seq: event.seq, time: event.time, role: 'assistant', text: textOf(content)};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Domain live logs are append-only and each observation is an immutable cut.
|
|
165
|
+
// Resume the original cut, not new appends: no retained lease or copied event log.
|
|
166
|
+
// Cold revisions/source transitions still fail explicitly; constant-size seq anchors
|
|
167
|
+
// also reject truncation or shifted cut/unread boundaries without a prefix scan.
|
|
168
|
+
function resumeEvents(observation, events, position) {
|
|
169
|
+
const version = {source: observation.source ?? null, cursor: observation.cursor,
|
|
170
|
+
revision: observation.revision ?? null, length: events.length};
|
|
171
|
+
if (position.version !== null) {
|
|
172
|
+
const previous = position.version;
|
|
173
|
+
const sameVersion = JSON.stringify(previous) === JSON.stringify(version);
|
|
174
|
+
const liveAppend = previous.source === 'live' && version.source === 'live'
|
|
175
|
+
&& JSON.stringify(previous.revision) === JSON.stringify(version.revision)
|
|
176
|
+
&& version.length >= previous.length && version.cursor >= previous.cursor;
|
|
177
|
+
if ((!sameVersion && !liveAppend) || events[position.cutoff.index]?.seq !== position.cutoff.seq
|
|
178
|
+
|| (position.event >= 0 && events[position.event]?.seq !== position.nextSeq))
|
|
179
|
+
throw new SearchError('History changed during pagination; search again', 409, 'HISTORY_CHANGED');
|
|
180
|
+
} else {
|
|
181
|
+
position.event = events.length - 1;
|
|
182
|
+
position.cutoff = {index: position.event, seq: events[position.event]?.seq ?? null};
|
|
183
|
+
}
|
|
184
|
+
position.version = version;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const freshPosition = () => ({event: null, titleDone: false, turn: null, version: null, cutoff: null, nextSeq: null});
|
|
188
|
+
|
|
189
|
+
export function createSearchService(services, options = {}) {
|
|
190
|
+
const limits = {...LIMITS, ...options};
|
|
191
|
+
const cursors = new Map(), busy = new Set();
|
|
192
|
+
let bytes = 0, active = 0, disposed = false;
|
|
193
|
+
const lifetime = new AbortController();
|
|
194
|
+
const remove = token => {const entry = cursors.get(token); if (entry) {bytes -= entry.bytes; cursors.delete(token);}};
|
|
195
|
+
const prune = () => {
|
|
196
|
+
for (const [token, entry] of cursors) if (entry.expires <= Date.now()) remove(token);
|
|
197
|
+
while (cursors.size > limits.maxCursors || bytes > limits.cacheBytes) remove(cursors.keys().next().value);
|
|
198
|
+
};
|
|
199
|
+
const save = state => {
|
|
200
|
+
const size = Buffer.byteLength(JSON.stringify(state));
|
|
201
|
+
if (size > limits.cacheBytes) throw new SearchError('Search snapshot exceeds cache bound; narrow the scope', 503, 'CACHE_LIMIT');
|
|
202
|
+
const token = randomUUID();
|
|
203
|
+
cursors.set(token, {state, bytes: size, expires: Date.now() + limits.cursorTtlMs}); bytes += size; prune(); return token;
|
|
204
|
+
};
|
|
205
|
+
const signalFor = signal => signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal;
|
|
206
|
+
const beginOperation = signal => {
|
|
207
|
+
const deadline = new AbortController();
|
|
208
|
+
const timer = setTimeout(() => deadline.abort(new SearchError('搜索批次超时,请缩小工作区或重试', 504, 'SEARCH_TIMEOUT')), limits.operationTimeoutMs);
|
|
209
|
+
return {signal: AbortSignal.any([signal, deadline.signal]), finish() {clearTimeout(timer); deadline.abort();}};
|
|
210
|
+
};
|
|
211
|
+
return {
|
|
212
|
+
async catalog(signal) {
|
|
213
|
+
signal = signalFor(signal); check(signal);
|
|
214
|
+
const operation = beginOperation(signal); signal = operation.signal;
|
|
215
|
+
try {
|
|
216
|
+
const {rows, workspaces} = await readCatalog(services, false, signal);
|
|
217
|
+
check(signal);
|
|
218
|
+
return {workspaces, sessions: rows.map(({id, title, workspaceId}) => ({id, title: title.slice(0, 512), ...(workspaceId ? {workspaceId} : {})}))};
|
|
219
|
+
} finally {operation.finish();}
|
|
220
|
+
},
|
|
221
|
+
async search(raw, signal) {
|
|
222
|
+
const input = validateInput(raw); signal = signalFor(signal); check(signal); prune();
|
|
223
|
+
if (disposed) throw new SearchError('Search service disposed', 503);
|
|
224
|
+
if (active >= limits.maxConcurrent) throw new SearchError('Too many concurrent searches; retry shortly', 429, 'SEARCH_BUSY');
|
|
225
|
+
let state;
|
|
226
|
+
if (input.cursor) {
|
|
227
|
+
const entry = cursors.get(input.cursor);
|
|
228
|
+
if (!entry) throw new SearchError('Search cursor expired; search again', 410, 'CURSOR_EXPIRED');
|
|
229
|
+
if (entry.state.key !== keyOf(input)) throw new SearchError('Cursor does not match query and scope', 400, 'CURSOR_MISMATCH');
|
|
230
|
+
if (busy.has(input.cursor)) throw new SearchError('Cursor is already in use', 409, 'CURSOR_BUSY');
|
|
231
|
+
state = {...entry.state, position: {...entry.state.position}, warnings: [...entry.state.warnings]};
|
|
232
|
+
busy.add(input.cursor);
|
|
233
|
+
}
|
|
234
|
+
const operation = beginOperation(signal); signal = operation.signal;
|
|
235
|
+
active++;
|
|
236
|
+
try {
|
|
237
|
+
if (!state) {
|
|
238
|
+
const {rows, workspaces} = await readCatalog(services, input.includeArchived, signal);
|
|
239
|
+
if (input.workspaceId && !workspaces.some(row => row.id === input.workspaceId)) throw new SearchError('Workspace is unavailable');
|
|
240
|
+
if (input.sessionId && !rows.some(row => row.id === input.sessionId)) throw new SearchError('Session is unavailable or excluded');
|
|
241
|
+
if (input.sessionId && input.workspaceId && rows.find(row => row.id === input.sessionId).workspaceId !== input.workspaceId)
|
|
242
|
+
throw new SearchError('Session does not belong to selected workspace');
|
|
243
|
+
state = {key: keyOf(input), rows: rows.filter(row => (!input.sessionId || row.id === input.sessionId) && (!input.workspaceId || row.workspaceId === input.workspaceId)),
|
|
244
|
+
workspaces, session: 0, scanned: 0, position: freshPosition(), warnings: []};
|
|
245
|
+
const preferred = state.rows.findIndex(row => row.id === input.preferredSessionId);
|
|
246
|
+
if (preferred > 0) state.rows.unshift(...state.rows.splice(preferred, 1));
|
|
247
|
+
}
|
|
248
|
+
const items = [];
|
|
249
|
+
let sessions = 0, visited = 0;
|
|
250
|
+
while (state.session < state.rows.length && items.length < limits.pageSize && sessions < limits.sessionsPerPage && visited < limits.eventsPerPage) {
|
|
251
|
+
check(signal);
|
|
252
|
+
const row = state.rows[state.session], position = state.position;
|
|
253
|
+
const common = {sessionId: row.id, title: row.title.slice(0, 512), ...(row.workspaceId ? {workspaceId: row.workspaceId,
|
|
254
|
+
workspaceTitle: state.workspaces.find(workspace => workspace.id === row.workspaceId)?.title} : {})};
|
|
255
|
+
if (!position.titleDone) {
|
|
256
|
+
const match = await literalSnippet(row.title, input.query, signal); position.titleDone = true;
|
|
257
|
+
if (match) items.push({...common, id: row.id + ':title', kind: 'title', ...match});
|
|
258
|
+
if (items.length >= limits.pageSize) break;
|
|
259
|
+
}
|
|
260
|
+
let finished = false;
|
|
261
|
+
try {
|
|
262
|
+
const observation = await awaitProvider(signal,
|
|
263
|
+
() => services.sessionQuery.observeSession(row.id, {signal, projectionMode: 'none'}),
|
|
264
|
+
late => late[Symbol.dispose]());
|
|
265
|
+
try {
|
|
266
|
+
check(signal);
|
|
267
|
+
const events = observation.events;
|
|
268
|
+
resumeEvents(observation, events, position);
|
|
269
|
+
while (position.event >= 0 && items.length < limits.pageSize && visited < limits.eventsPerPage) {
|
|
270
|
+
check(signal);
|
|
271
|
+
const document = documentAt(events, position.event--, position); visited++;
|
|
272
|
+
if (document?.text) {
|
|
273
|
+
const match = await literalSnippet(document.text, input.query, signal);
|
|
274
|
+
if (match) items.push({...common, id: row.id + ':message:' + document.seq, kind: 'message', seq: document.seq,
|
|
275
|
+
...(document.time !== undefined ? {time: document.time} : {}), role: document.role, ...match});
|
|
276
|
+
}
|
|
277
|
+
if (visited % 64 === 0) {await yieldTask(); check(signal);}
|
|
278
|
+
}
|
|
279
|
+
finished = position.event < 0;
|
|
280
|
+
position.nextSeq = finished ? null : events[position.event].seq;
|
|
281
|
+
} finally {observation[Symbol.dispose]();}
|
|
282
|
+
} catch (error) {
|
|
283
|
+
check(signal);
|
|
284
|
+
if (error instanceof SearchError) throw error;
|
|
285
|
+
if (state.warnings.length < limits.maxWarnings) state.warnings.push({sessionId: row.id, code: 'SESSION_UNAVAILABLE', message: 'Session history could not be read'});
|
|
286
|
+
finished = true;
|
|
287
|
+
}
|
|
288
|
+
if (finished) {state.session++; state.scanned++; sessions++; state.position = freshPosition();}
|
|
289
|
+
else break;
|
|
290
|
+
await yieldTask();
|
|
291
|
+
}
|
|
292
|
+
check(signal);
|
|
293
|
+
const cursor = state.session < state.rows.length ? save(state) : null;
|
|
294
|
+
if (input.cursor) remove(input.cursor);
|
|
295
|
+
return {items, cursor, scanned: state.scanned, totalSessions: state.rows.length, warnings: state.warnings, workspaces: state.workspaces};
|
|
296
|
+
} finally {operation.finish(); active--; if (input.cursor) busy.delete(input.cursor);}
|
|
297
|
+
},
|
|
298
|
+
dispose() {disposed = true; lifetime.abort(); cursors.clear(); bytes = 0;},
|
|
299
|
+
};
|
|
300
|
+
}
|