dsh-yazi 0.2.1 → 0.2.2
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/DECISIONS.md +63 -0
- package/README.md +29 -4
- package/README.zh.md +20 -1
- package/client.js +46 -57
- package/cordis.patch.yml +3 -0
- package/index.js +67 -4
- package/package.json +1 -1
- package/src/client/assets.js +20 -43
- package/src/client/main.js +26 -14
- package/src/host/cwd.js +29 -12
- package/src/host/route.js +8 -0
- package/src/host/telemetry.js +321 -0
- package/src/host/workspace.js +30 -0
package/DECISIONS.md
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
# DECISIONS
|
|
2
2
|
|
|
3
3
|
<!-- APPEND-ONLY LOG: 新条目插入到此行之后 -->
|
|
4
|
+
## DEC-027 2026-11-27 ⛔️ 进入 worktree 后 yazi 仍打开工作区路径(取代: DEC-004 的解析顺序)
|
|
5
|
+
|
|
6
|
+
用户报告:会话当场处于 worktree 时,yazi 打开的是 worktree 目录,这是错的,应该打开工作区自身的路径。
|
|
7
|
+
|
|
8
|
+
- **根因**:DEC-004 的阶梯把 `workingDirectory.get(session)` 放在最前。`enter_worktree` 正是通过
|
|
9
|
+
`workingDirectory.set` 发布 `workspace-root/change` 来移动会话目录的(见 worktrees 子系统文档:
|
|
10
|
+
"the Session's directory is moved ... through ctx.workingDirectory.set"),所以实时投影天然等于
|
|
11
|
+
`<checkout>/.agents/worktrees/<name>`,结果 yazi 的根目录跟着落进了 checkout。
|
|
12
|
+
- **为什么"工作区路径"能代表项目**:worktree 文档明确写着进入 checkout "does not change the Session's
|
|
13
|
+
original project",而 `SessionHeader.cwd` 与 `Workspace.sessionIds` 都锚定在这个原始项目上。因此
|
|
14
|
+
工作区路径不是猜出来的——它就是 header 语义的直接读法。
|
|
15
|
+
- **新阶梯**:`workspaceRegistry` 中把该 session 记在 `sessionIds` 里的工作区 `path` → `header.cwd`
|
|
16
|
+
→ 实时 `workingDirectory` → 客户端 hint → 首个已注册工作区 → `defaultDirectory`,逐级仍校验目录存在且是目录。
|
|
17
|
+
前两级都指向项目;实时投影降级为"两者都没有"时的兜底,这正是 worktree 不再成为根目录的原因。
|
|
18
|
+
- **归属用 `sessionIds`,不按路径形状猜**:先写的版本用 `path.startsWith(<ws> + '/.agents/worktrees/')`
|
|
19
|
+
识别 checkout,但那把 `directory` 配置、名字前缀等实现细节硬编码进插件。`Workspace.sessionIds`
|
|
20
|
+
是注册表的正式记账,且 `list()` 返回时已按规范化的 header 索引过滤过,直接用它更准也更稳。
|
|
21
|
+
`sessionId` 还必须在**没有活动 Session** 时也参与判断:`ctx.sessions.get()` 只回答 live 会话,
|
|
22
|
+
冷会话重新打开时若只依赖它就会退回实时投影、又落回 worktree。
|
|
23
|
+
- **客户端不再上报实时目录**:面板原来把 `cwd: <workingDirectory 投影>` 当 hint 发过去,并在工具栏
|
|
24
|
+
把这个投影当根目录显示。Host 已能自己解析,hint 现在是多余且误导的信息源,删除;工具栏只显示
|
|
25
|
+
Host 实际打开的目录(`hello.cwd`),避免"显示 worktree、实际打开工作区"这种自相矛盾的画面。
|
|
26
|
+
投影仍保留在 effect 依赖里,仅作为"目录移动了,重新解析一次"的触发信号。
|
|
27
|
+
- **兜底行为**:工作区目录被删、会话没有登记工作区时,仍逐级回退到 header、实时目录,不会出现
|
|
28
|
+
"因为找不到工作区就不开面板"。原有 10 条阶梯用例全部保留并通过。
|
|
29
|
+
- 测试:新增 `test/workspace.test.js`(6 条,归属判定)、`test/cwd.test.js` 5 条阶梯用例、
|
|
30
|
+
`test/route.test.js` 3 条用真实临时目录跑 `makeDirectoryResolver` 的集成用例、client 1 条
|
|
31
|
+
"工具栏不得把 worktree 当根目录"。全部 184 条通过;红→绿已逐条确认(先红后改)。
|
|
32
|
+
|
|
33
|
+
## DEC-026 2026-11-27 增加匿名安装 + DAU 统计,详情页默认开启的同意开关
|
|
34
|
+
|
|
35
|
+
用户要求:增加插件安装和 DAU 统计;详情页增加统计选项,默认打开,由用户选择是否同意匿名统计;上报服务端地址与 ../dsh-decision-engine 相同。
|
|
36
|
+
|
|
37
|
+
- **复用协议而非另起炉灶**:采集端就是 decision-engine 的 `https://dsh.zuos.us/api/e`,上报体用同一套短键(`v/p/id/k/ver/os/arch/host/day`),`p` 固定为 `dsh-yazi`。服务端按 `p` 分插件统计,因此不新建表、不改协议版本。上报内容只有随机 UUIDv4 安装 id、版本、平台、架构、事件种类(install / heartbeat);**不含**路径、文件名、会话内容、API key。
|
|
38
|
+
- **为什么用 `telemetryLevel` 三档而不是一个布尔**:直接照搬 decision-engine 的 `off/install/daily` 模型。`install` 档会让 DAU 恒为 0(已装用户第二天起不再上报),所以**默认 `daily`**——它同时覆盖首次安装事件和每当地日一次的活跃心跳。详情页只暴露一个勾选框:`daily` = 同意(默认勾选),`off` = 拒绝;`install` 仍是合法档位但不在 UI 暴露,避免用户选到让 DAU 失效的档。
|
|
39
|
+
- **默认开 ≠ 强制开**:`cordis.patch.yml` 与 Schemastery `Config` 都写 `daily` 默认值;用户显式写 `off` 时压过默认。`off` 是硬承诺:不读状态文件、不建目录、不发任何请求(`startTelemetry` 在构造 reporter 之前就短路)。
|
|
40
|
+
- **状态文件与节流**:`<DSH_HOME>/plugins/dsh-yazi/analytics.json`,与 decision-engine / pocket-kit 同目录约定。按 `Asia/Shanghai` 固定 +8 算日(中国无夏令时),`lastAttemptDay` 保证每当地日最多一次;损坏状态退化为全新安装而不是永远不报;连续 30 次失败后 `degraded` 彻底降级;先落盘状态再发请求,避免同日重复发。
|
|
41
|
+
- **绝不阻塞插件**:`apply()` 里 `void startTelemetry(...)`;`TelemetryReporter.start()` 吞掉所有异常(最多一条 warn),超时 5 秒,统计故障不会变成终端故障。
|
|
42
|
+
- **客户端不擅自默认**:`readPanelOptions()` 在没有服务端下发的 level 时读成 `off`,"默认开"由 Host 的 Config 决定——浏览器端不能替用户假设同意。
|
|
43
|
+
- **纯函数与副作用分离**:`src/host/telemetry.js` 把日期、状态、是否该发、上报体做成纯函数,副作用集中在 `TelemetryReporter`,注入 `dir/fetchImpl/clock`。测试完全不碰真实网络;新增 20 条用例(15 纯模块 + 5 startTelemetry),连同 config/client 共 169 条全绿。
|
|
44
|
+
- 版本 0.2.1 → 0.3.0(新功能)。
|
|
45
|
+
|
|
46
|
+
## DEC-025 2026-11-27 快捷键由 ⌘P 改为 ⌘Y,并删掉快捷键冲突的提示
|
|
47
|
+
|
|
48
|
+
用户要求把插件快捷键从 ⌘P 换成 ⌘Y,同时删除所有与快捷键冲突相关的文字。
|
|
49
|
+
|
|
50
|
+
- 判定键:`installPanelShortcut` 与已删除的旧 helper 都只认 `event.key` 的
|
|
51
|
+
`p`/`P`,现在改为 `y`/`Y`;仍同时接受 meta 与 ctrl,保持 macOS/iPad 与 Windows
|
|
52
|
+
的 primary 语义。捕获阶段安装、按键时读开关、以及「再按一次回到原标签」的开关式
|
|
53
|
+
行为都不变。
|
|
54
|
+
- 删除的冲突文案:`settings.takeoverShortcutNote`(中英双语,要求用户先去
|
|
55
|
+
「设置 → 快捷键」清除「工作区文件」的绑定)连同设置卡片里的 note 节点与
|
|
56
|
+
`.dshyz-cfg-note` 样式一起移除;开关副文案里「而不是打开『文件』面板」的措辞
|
|
57
|
+
也改掉,因为它描述的正是同一件抢占关系。
|
|
58
|
+
- 字段名 `takeoverShortcut` 保留:改名会让已安装 profile 里 `true` 的配置回落到
|
|
59
|
+
默认 `false`,用户得重新开一次开关。名字里的 takeover 现在只表示「接管这个键」,
|
|
60
|
+
不再暗示与 DSH 自己的绑定冲突。
|
|
61
|
+
- 顺手删掉 `installShortcutTakeover`:它自 DEC-024 起就没有调用方,仅被旧测试引用,
|
|
62
|
+
两份按键判断逻辑并存只会让下一次改键漏改一处。
|
|
63
|
+
- 测试同步:用例里的 `key: 'p'` 改为 `'y'`,设置卡片新增三条断言,确认渲染结果里
|
|
64
|
+
不再出现「快捷键 / Shortcuts / 清除 / 工作区文件 / Workspace Files」等字样。
|
|
65
|
+
|
|
66
|
+
|
|
4
67
|
## DEC-024 2026-11-27 ⌘P 改为开关式:再按一次回到原来的标签
|
|
5
68
|
|
|
6
69
|
用户希望「快捷键进 Yazi 后,再按一次回到原标签」。实现:第一次按键记录当前选中
|
package/README.md
CHANGED
|
@@ -6,8 +6,13 @@
|
|
|
6
6
|
|
|
7
7
|
Adds a **Yazi** tab to the session's view tab row — beside `对话` and `轨迹` —
|
|
8
8
|
via the `conversation.view` slot. Selecting it renders the real local `yazi`
|
|
9
|
-
file manager in a genuine PTY, rooted at the
|
|
10
|
-
|
|
9
|
+
file manager in a genuine PTY, rooted at the workspace the session belongs to.
|
|
10
|
+
|
|
11
|
+
That is deliberately **not** the session's live working directory: entering a
|
|
12
|
+
worktree moves that directory into `<checkout>/.agents/worktrees/<name>`, while
|
|
13
|
+
the project itself stays the workspace path. The panel is a view of the
|
|
14
|
+
project, so it opens the workspace; the live directory is only a fallback for a
|
|
15
|
+
session with no workspace record.
|
|
11
16
|
|
|
12
17
|
## How it works
|
|
13
18
|
|
|
@@ -58,6 +63,25 @@ browser / desktop page Host (this package)
|
|
|
58
63
|
| `idleMinutes` | `30` | Reclaim an unattached PTY after this long; `0` disables |
|
|
59
64
|
| `maxSessions` | `8` | Cap on live PTYs; the least recently used unattached one is evicted |
|
|
60
65
|
| `editor` | unset | Value exported as `EDITOR` inside yazi |
|
|
66
|
+
| `telemetryLevel` | `daily` | Anonymous install + DAU statistics: `daily` (on, default), `install` (first run only), `off` (never) |
|
|
67
|
+
|
|
68
|
+
## Anonymous statistics (install + DAU)
|
|
69
|
+
|
|
70
|
+
The detail page's **Yazi panel** section has an **Allow anonymous usage statistics**
|
|
71
|
+
switch, **on by default**. Turning it off writes `telemetryLevel: off` and stops
|
|
72
|
+
all reporting: no state file is read or created and no request is made.
|
|
73
|
+
|
|
74
|
+
When on, the Host fires one anonymous report per local day (`Asia/Shanghai`)
|
|
75
|
+
to the same collector `dsh-decision-engine` uses (`https://dsh.zuos.us/api/e`):
|
|
76
|
+
|
|
77
|
+
- the first run sends an `install` event; later days send a `heartbeat` event
|
|
78
|
+
that counts as one daily active user;
|
|
79
|
+
- payload contains only a random UUIDv4 install id, plugin version, OS, CPU
|
|
80
|
+
architecture and the event kind. **No paths, file names, session content or
|
|
81
|
+
API keys** are sent;
|
|
82
|
+
- the state file is `<DSH_HOME>/plugins/dsh-yazi/analytics.json` (delete it to
|
|
83
|
+
start with a fresh anonymous id). A day is counted at most once; failures
|
|
84
|
+
never block the plugin.
|
|
61
85
|
|
|
62
86
|
## Requirements and limits
|
|
63
87
|
|
|
@@ -76,8 +100,9 @@ browser / desktop page Host (this package)
|
|
|
76
100
|
- yazi reads your own `~/.config/yazi`. If that configuration has an error,
|
|
77
101
|
yazi's own error dialog appears inside the panel — that text comes from yazi,
|
|
78
102
|
not from this plugin.
|
|
79
|
-
- The panel shows the directory it actually opened, so a silently
|
|
80
|
-
directory is visible rather than assumed.
|
|
103
|
+
- The panel toolbar shows the directory it actually opened, so a silently
|
|
104
|
+
substituted directory is visible rather than assumed. It never shows the
|
|
105
|
+
live working directory, which can differ when a worktree is checked out.
|
|
81
106
|
|
|
82
107
|
## Development
|
|
83
108
|
|
package/README.zh.md
CHANGED
|
@@ -4,7 +4,11 @@
|
|
|
4
4
|
|
|
5
5
|
在会话顶部的视图 tab 行(`对话` 和 `轨迹` 旁边)新增一个 **Yazi** 标签,通过
|
|
6
6
|
`conversation.view` 插槽注入。选中后会打开一个真正的 PTY,在里头运行本机的
|
|
7
|
-
`yazi`
|
|
7
|
+
`yazi` 文件管理器,工作目录为**该会话所属的工作区路径**。
|
|
8
|
+
|
|
9
|
+
这里刻意不用会话的实时 workingDirectory:进入 worktree 会把那个目录移动成
|
|
10
|
+
`<checkout>/.agents/worktrees/<name>`,而项目本身仍是工作区路径。面板是项目的
|
|
11
|
+
视图,所以打开工作区;实时目录只在会话没有工作区记录时兜底。
|
|
8
12
|
|
|
9
13
|
## 工作原理
|
|
10
14
|
|
|
@@ -53,6 +57,21 @@
|
|
|
53
57
|
| `idleMinutes` | `30` | 无附着连接的 PTY 闲置多久后回收;`0` 表示禁用 |
|
|
54
58
|
| `maxSessions` | `8` | 存活 PTY 数量上限;淘汰最久未使用的未附着会话 |
|
|
55
59
|
| `editor` | 未设置 | 在 yazi 内导出为 `EDITOR` 的值 |
|
|
60
|
+
| `telemetryLevel` | `daily` | 匿名安装 + DAU 统计:`daily`(开,默认)、`install`(仅首次)、`off`(永不) |
|
|
61
|
+
|
|
62
|
+
## 匿名统计(安装量 + DAU)
|
|
63
|
+
|
|
64
|
+
插件详情页的 **Yazi 面板** 区域有一个 **允许匿名统计** 开关,**默认开启**。
|
|
65
|
+
关闭会写入 `telemetryLevel: off`,并彻底停止上报:不读、不建状态文件,也不发任何请求。
|
|
66
|
+
|
|
67
|
+
开启时,Host 每当地日(`Asia/Shanghai`)向 dsh-decision-engine 相同的采集端
|
|
68
|
+
`https://dsh.zuos.us/api/e` 上报一次:
|
|
69
|
+
|
|
70
|
+
- 首次运行发送 `install` 事件;之后每天发送一次 `heartbeat`,即一个日活;
|
|
71
|
+
- 上报内容只有随机 UUIDv4 安装 id、插件版本、系统与 CPU 架构以及事件种类。
|
|
72
|
+
**不包含**任何路径、文件名、会话内容或 API key;
|
|
73
|
+
- 状态文件为 `<DSH_HOME>/plugins/dsh-yazi/analytics.json`(删除它即可换一个新的匿名 id)。
|
|
74
|
+
每个当地日最多计一次;任何失败都不会影响插件运行。
|
|
56
75
|
|
|
57
76
|
## 要求与限制
|
|
58
77
|
|
package/client.js
CHANGED
|
@@ -146,9 +146,6 @@ const CSS = [
|
|
|
146
146
|
'.dshyz-cfg-row input{margin:2px 0 0;flex:none}',
|
|
147
147
|
'.dshyz-cfg-label{font-size:13px;line-height:1.4;cursor:pointer}',
|
|
148
148
|
'.dshyz-cfg-hint{font-size:11px;line-height:1.6;opacity:.65;margin-top:2px;padding-bottom:2px}',
|
|
149
|
-
'.dshyz-cfg-note{font-size:11px;line-height:1.6;margin-top:4px;padding:6px 8px;border-radius:6px;',
|
|
150
|
-
'color:var(--dsw-alias-label-secondary,#555);background:var(--dsw-alias-bg-layer-1,rgba(0,0,0,.03));',
|
|
151
|
-
'border-left:2px solid var(--dsw-alias-state-warn-primary,#e67700)}',
|
|
152
149
|
].join('')
|
|
153
150
|
|
|
154
151
|
// The locale service registers dictionaries grouped by locale id, each with
|
|
@@ -171,11 +168,12 @@ const EN = {
|
|
|
171
168
|
'panel.restart': 'Reopen',
|
|
172
169
|
'panel.kill': 'Quit yazi',
|
|
173
170
|
'settings.title': 'Yazi panel',
|
|
174
|
-
'settings.takeoverShortcut': 'Use ⌘
|
|
175
|
-
'settings.takeoverShortcutHint': '
|
|
176
|
-
'settings.takeoverShortcutNote': 'If DSH binds the same key, DSH wins: clear the binding for Workspace Files in Settings → Shortcuts first, otherwise this switch has no effect.',
|
|
171
|
+
'settings.takeoverShortcut': 'Use ⌘Y / Ctrl+Y for yazi',
|
|
172
|
+
'settings.takeoverShortcutHint': 'Opens yazi from any tab. Once yazi is showing, the same key returns focus to the file manager.',
|
|
177
173
|
'settings.fullScreen': 'Let yazi fill the session area',
|
|
178
174
|
'settings.fullScreenHint': 'Hides the composer and other editing elements. The tab row stays so you can switch back.',
|
|
175
|
+
'settings.telemetry': 'Allow anonymous usage statistics',
|
|
176
|
+
'settings.telemetryHint': 'On by default. Sends one anonymous install event and at most one daily active event per day (random install id, plugin version, OS and CPU architecture only). No paths, file names or session content. Turn off to stop all reporting.',
|
|
179
177
|
'settings.unavailable': 'These options are unavailable in this profile.',
|
|
180
178
|
}
|
|
181
179
|
|
|
@@ -195,11 +193,12 @@ const ZH = {
|
|
|
195
193
|
'panel.restart': '重新打开',
|
|
196
194
|
'panel.kill': '退出 yazi',
|
|
197
195
|
'settings.title': 'Yazi 面板',
|
|
198
|
-
'settings.takeoverShortcut': '用 ⌘
|
|
199
|
-
'settings.takeoverShortcutHint': '在任意标签下按该快捷键都会切到 yazi
|
|
200
|
-
'settings.takeoverShortcutNote': '如果 DSH 也绑定了同一个键,DSH 优先:请先在「设置 → 快捷键」里清除「工作区文件」的绑定,否则这个开关不会生效。',
|
|
196
|
+
'settings.takeoverShortcut': '用 ⌘Y / Ctrl+Y 打开 yazi',
|
|
197
|
+
'settings.takeoverShortcutHint': '在任意标签下按该快捷键都会切到 yazi;已在 yazi 时则把焦点交回文件管理器。',
|
|
201
198
|
'settings.fullScreen': '让 yazi 占满会话区域',
|
|
202
199
|
'settings.fullScreenHint': '隐藏输入框等编辑元素;标签栏保留,方便切回对话。',
|
|
200
|
+
'settings.telemetry': '允许匿名统计',
|
|
201
|
+
'settings.telemetryHint': '默认开启。仅上报一次匿名安装事件和每天至多一次的活跃事件(只有随机安装 id、插件版本、系统与 CPU 架构),不包含任何路径、文件名或会话内容。关闭后不再进行任何上报。',
|
|
203
202
|
'settings.unavailable': '当前配置不支持修改这些选项。',
|
|
204
203
|
}
|
|
205
204
|
|
|
@@ -311,7 +310,7 @@ const FULLSCREEN_ATTR = 'dshYaziFullscreen'
|
|
|
311
310
|
* DSH's own shortcuts and layout.
|
|
312
311
|
*
|
|
313
312
|
* @param form configForms handle, or undefined.
|
|
314
|
-
* @returns {{ takeoverShortcut: boolean, fullScreen: boolean }}
|
|
313
|
+
* @returns {{ takeoverShortcut: boolean, fullScreen: boolean, telemetryLevel: string }}
|
|
315
314
|
*/
|
|
316
315
|
function readPanelOptions(form) {
|
|
317
316
|
let value = {}
|
|
@@ -322,19 +321,24 @@ function readPanelOptions(form) {
|
|
|
322
321
|
}
|
|
323
322
|
// A served document normally carries plain literals, but a volatile field
|
|
324
323
|
// can arrive wrapped; accept both shapes so a switch never reads as off.
|
|
325
|
-
const
|
|
324
|
+
const unwrap = (raw) => {
|
|
326
325
|
if (raw !== null && typeof raw === 'object' && typeof raw.get === 'function') {
|
|
327
326
|
try {
|
|
328
|
-
return raw.get()
|
|
327
|
+
return raw.get()
|
|
329
328
|
} catch {
|
|
330
|
-
return
|
|
329
|
+
return undefined
|
|
331
330
|
}
|
|
332
331
|
}
|
|
333
|
-
return raw
|
|
332
|
+
return raw
|
|
334
333
|
}
|
|
334
|
+
const on = (raw) => unwrap(raw) === true
|
|
335
|
+
const level = unwrap(value?.telemetryLevel)
|
|
335
336
|
return {
|
|
336
337
|
takeoverShortcut: on(value?.takeoverShortcut),
|
|
337
338
|
fullScreen: on(value?.fullScreen),
|
|
339
|
+
// Without a served level, treat consent as absent. The Host owns the
|
|
340
|
+
// default-on decision; the client must never assume it in the UI.
|
|
341
|
+
telemetryLevel: level === 'off' || level === 'install' || level === 'daily' ? level : 'off',
|
|
338
342
|
}
|
|
339
343
|
}
|
|
340
344
|
|
|
@@ -352,34 +356,7 @@ function applyFullScreen(doc, enabled) {
|
|
|
352
356
|
}
|
|
353
357
|
|
|
354
358
|
/**
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
* DSH's shortcut registry refuses a second command bound to a reserved
|
|
358
|
-
* combination, so the takeover is a capture-phase listener: it runs before the
|
|
359
|
-
* registry's own handler and stops the event there. Only the plain primary+P
|
|
360
|
-
* combination is taken; anything else stays with DSH or reaches yazi.
|
|
361
|
-
*
|
|
362
|
-
* @param win Window-like owner of the gesture.
|
|
363
|
-
* @param onTaken Called when the gesture is claimed.
|
|
364
|
-
* @returns Disposer removing the listener.
|
|
365
|
-
*/
|
|
366
|
-
function installShortcutTakeover(win, onTaken) {
|
|
367
|
-
const handler = (event) => {
|
|
368
|
-
if (event === null || typeof event !== 'object') return
|
|
369
|
-
const key = event.key
|
|
370
|
-
if (key !== 'p' && key !== 'P') return
|
|
371
|
-
if (event.metaKey !== true && event.ctrlKey !== true) return
|
|
372
|
-
if (event.altKey === true || event.shiftKey === true) return
|
|
373
|
-
event.preventDefault?.()
|
|
374
|
-
event.stopPropagation?.()
|
|
375
|
-
onTaken?.()
|
|
376
|
-
}
|
|
377
|
-
win.addEventListener('keydown', handler, true)
|
|
378
|
-
return () => win.removeEventListener('keydown', handler, true)
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/**
|
|
382
|
-
* Claim primary+P for the panel while its switch is on and its tab is mounted.
|
|
359
|
+
* Claim primary+Y for the panel while its switch is on and its tab is mounted.
|
|
383
360
|
*
|
|
384
361
|
* The switch and the visibility are read on every keypress through `live`
|
|
385
362
|
* rather than captured at install time: a React effect that re-installs the
|
|
@@ -405,7 +382,7 @@ function installPanelShortcut(win, live) {
|
|
|
405
382
|
|
|
406
383
|
const handler = (event) => {
|
|
407
384
|
if (event === null || typeof event !== 'object') return
|
|
408
|
-
if (event.key !== '
|
|
385
|
+
if (event.key !== 'y' && event.key !== 'Y') return
|
|
409
386
|
if (event.metaKey !== true && event.ctrlKey !== true) return
|
|
410
387
|
if (event.altKey === true || event.shiftKey === true) return
|
|
411
388
|
if (live?.isEnabled?.() !== true) return
|
|
@@ -804,10 +781,12 @@ window.__ModuleLoader__.load({
|
|
|
804
781
|
const t = props.t
|
|
805
782
|
const form = props.form
|
|
806
783
|
|
|
807
|
-
//
|
|
808
|
-
//
|
|
784
|
+
// The live workingDirectory projection moves into a worktree checkout,
|
|
785
|
+
// which is not what this panel shows: it is a file manager for the
|
|
786
|
+
// project. The Host resolves that from the workspace registry, so the
|
|
787
|
+
// projection is not used as a path — only as a re-open trigger, because a
|
|
788
|
+
// directory move is when the resolved project may need re-checking.
|
|
809
789
|
const projected = useProjection('workingDirectory')
|
|
810
|
-
const directory = typeof projected === 'string' && projected !== '' ? projected : undefined
|
|
811
790
|
|
|
812
791
|
const stageRef = React.useRef(null)
|
|
813
792
|
const [phase, setPhase] = React.useState('connecting')
|
|
@@ -886,7 +865,9 @@ window.__ModuleLoader__.load({
|
|
|
886
865
|
bundle,
|
|
887
866
|
// No cols/rows here: the terminal fits itself to the container and
|
|
888
867
|
// reports the real size on socket open and on every resize.
|
|
889
|
-
|
|
868
|
+
// No cwd hint: the Host reads the session's workspace itself. A
|
|
869
|
+
// hint from here would be the live directory, i.e. the worktree.
|
|
870
|
+
query: { sid: sessionId },
|
|
890
871
|
notify(event) {
|
|
891
872
|
if (event.type === 'connecting') return
|
|
892
873
|
if (event.type === 'ready') {
|
|
@@ -918,7 +899,7 @@ window.__ModuleLoader__.load({
|
|
|
918
899
|
focusRef.current = null
|
|
919
900
|
terminal.dispose()
|
|
920
901
|
}
|
|
921
|
-
}, [generation, sessionId,
|
|
902
|
+
}, [generation, sessionId, projected, serverEpoch])
|
|
922
903
|
|
|
923
904
|
return h('div', { className: 'dshyz-root' }, [
|
|
924
905
|
h('div', { key: 'bar', className: 'dshyz-bar' }, [
|
|
@@ -932,8 +913,9 @@ window.__ModuleLoader__.load({
|
|
|
932
913
|
phase === 'live' ? t('panel.stateReady')
|
|
933
914
|
: phase === 'error' ? t('panel.stateError')
|
|
934
915
|
: t('panel.stateConnecting')),
|
|
935
|
-
|
|
936
|
-
|
|
916
|
+
// Only the directory the Host actually opened: showing the phrased
|
|
917
|
+
// projection would claim a root the panel never used.
|
|
918
|
+
h('span', { key: 'cwd', className: 'dshyz-cwd', title: cwd }, cwd),
|
|
937
919
|
h('button', {
|
|
938
920
|
key: 'restart',
|
|
939
921
|
type: 'button',
|
|
@@ -1004,18 +986,18 @@ window.__ModuleLoader__.load({
|
|
|
1004
986
|
const writable = state.status !== 'unavailable' && state.writable !== false
|
|
1005
987
|
const options = readPanelOptions(form)
|
|
1006
988
|
|
|
1007
|
-
const switchRow = (field, labelKey, hintKey) => h('div', { key: field, className: 'dshyz-cfg-row' }, [
|
|
989
|
+
const switchRow = (field, labelKey, hintKey, read, write) => h('div', { key: field, className: 'dshyz-cfg-row' }, [
|
|
1008
990
|
h('input', {
|
|
1009
991
|
key: 'input',
|
|
1010
992
|
id: 'dshyz-cfg-' + field,
|
|
1011
993
|
type: 'checkbox',
|
|
1012
|
-
checked: options[field] === true,
|
|
994
|
+
checked: (read ? read(options[field]) : options[field]) === true,
|
|
1013
995
|
disabled: !writable,
|
|
1014
996
|
onChange: (event) => {
|
|
1015
997
|
const next = event?.target?.checked === true
|
|
1016
998
|
// Optimistic local echo: the Host mirror confirms shortly after.
|
|
1017
999
|
setState((previous) => ({ ...previous }))
|
|
1018
|
-
void form?.set?.(field, next)
|
|
1000
|
+
void form?.set?.(field, write ? write(next) : next)
|
|
1019
1001
|
},
|
|
1020
1002
|
}),
|
|
1021
1003
|
h('label', { key: 'label', className: 'dshyz-cfg-label', htmlFor: 'dshyz-cfg-' + field }, [
|
|
@@ -1028,10 +1010,17 @@ window.__ModuleLoader__.load({
|
|
|
1028
1010
|
h('div', { key: 'title', className: 'dshyz-cfg-label' }, t('settings.title')),
|
|
1029
1011
|
writable ? null : h('div', { key: 'off', className: 'dshyz-cfg-hint' }, t('settings.unavailable')),
|
|
1030
1012
|
switchRow('takeoverShortcut', 'settings.takeoverShortcut', 'settings.takeoverShortcutHint'),
|
|
1031
|
-
// Outside the switch label: this is a precondition the user must satisfy
|
|
1032
|
-
// in another settings page, not part of toggling the switch.
|
|
1033
|
-
h('div', { key: 'shortcut-note', className: 'dshyz-cfg-note' }, t('settings.takeoverShortcutNote')),
|
|
1034
1013
|
switchRow('fullScreen', 'settings.fullScreen', 'settings.fullScreenHint'),
|
|
1014
|
+
// Anonymous statistics is a level, not a boolean: the checkbox maps
|
|
1015
|
+
// daily(consented) <-> off. `install` remains a supported level but is
|
|
1016
|
+
// intentionally not offered in the detail-page UI.
|
|
1017
|
+
switchRow(
|
|
1018
|
+
'telemetryLevel',
|
|
1019
|
+
'settings.telemetry',
|
|
1020
|
+
'settings.telemetryHint',
|
|
1021
|
+
(level) => level !== 'off',
|
|
1022
|
+
(checked) => (checked ? 'daily' : 'off'),
|
|
1023
|
+
),
|
|
1035
1024
|
])
|
|
1036
1025
|
}
|
|
1037
1026
|
|
|
@@ -1062,7 +1051,7 @@ window.__ModuleLoader__.load({
|
|
|
1062
1051
|
select: (doc, label) => activatePanel(doc, label),
|
|
1063
1052
|
focus: () => panelFocus.current?.(),
|
|
1064
1053
|
document: typeof document === 'undefined' ? undefined : document,
|
|
1065
|
-
}), 'yazi: primary+
|
|
1054
|
+
}), 'yazi: primary+Y takeover')
|
|
1066
1055
|
}
|
|
1067
1056
|
|
|
1068
1057
|
ctx.effect(() => {
|
package/cordis.patch.yml
CHANGED
|
@@ -12,3 +12,6 @@
|
|
|
12
12
|
# Panel behaviour, surfaced on this plugin's settings page.
|
|
13
13
|
takeoverShortcut: false
|
|
14
14
|
fullScreen: false
|
|
15
|
+
# Anonymous install + DAU statistics. Default on; detail-page switch
|
|
16
|
+
# can set this to off for a complete no-op (no state file, no request).
|
|
17
|
+
telemetryLevel: daily
|
package/index.js
CHANGED
|
@@ -15,11 +15,12 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import z from '@deepseek-ai/schemastery'
|
|
17
17
|
import { stat } from 'node:fs/promises'
|
|
18
|
-
import { appendFileSync } from 'node:fs'
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
18
|
+
import { appendFileSync, readFileSync } from 'node:fs'
|
|
19
|
+
import { homedir, tmpdir } from 'node:os'
|
|
20
|
+
import { join, resolve } from 'node:path'
|
|
21
21
|
import { YaziSessions } from './src/host/pty.js'
|
|
22
22
|
import { registerYaziRoute, makeDirectoryResolver, registerYaziDiagnosticRoute } from './src/host/route.js'
|
|
23
|
+
import { TelemetryReporter, resolveLevel } from './src/host/telemetry.js'
|
|
23
24
|
|
|
24
25
|
export const inject = ['subprocess', 'webServer', 'sessions', 'workingDirectory', 'workspaceRegistry']
|
|
25
26
|
|
|
@@ -34,6 +35,9 @@ const DEFAULTS = {
|
|
|
34
35
|
// Panel behaviour, read by the browser half through `configForms`.
|
|
35
36
|
takeoverShortcut: false,
|
|
36
37
|
fullScreen: false,
|
|
38
|
+
// Anonymous usage statistics. Default on: the user opts out on this plugin's
|
|
39
|
+
// detail page. `daily` covers both the install event and the DAU heartbeat.
|
|
40
|
+
telemetryLevel: 'daily',
|
|
37
41
|
}
|
|
38
42
|
|
|
39
43
|
function positive(value, fallback) {
|
|
@@ -63,9 +67,15 @@ export const Config = z.object({
|
|
|
63
67
|
maxSessions: z.number().step(1).min(1).max(32).default(DEFAULTS.maxSessions).description('同时保留的 yazi 进程上限'),
|
|
64
68
|
editor: z.string().default('').description('传给 yazi 的 EDITOR(留空 = 沿用环境变量)'),
|
|
65
69
|
takeoverShortcut: z.boolean().default(DEFAULTS.takeoverShortcut).volatile()
|
|
66
|
-
.description('
|
|
70
|
+
.description('用 ⌘Y / Ctrl+Y 在任意标签下切到 yazi'),
|
|
67
71
|
fullScreen: z.boolean().default(DEFAULTS.fullScreen).volatile()
|
|
68
72
|
.description('让 yazi 占满整个会话区域(隐藏输入框等编辑元素,标签栏保留以便切回)'),
|
|
73
|
+
// Anonymous install + DAU statistics, default ON. `off` means no request and
|
|
74
|
+
// no state file at all. Volatile so the consent switch takes effect without
|
|
75
|
+
// restarting the plugin. Endpoint/config lives in code, not in this document.
|
|
76
|
+
telemetryLevel: z.union([z.const('off'), z.const('install'), z.const('daily')])
|
|
77
|
+
.default(DEFAULTS.telemetryLevel).volatile()
|
|
78
|
+
.description('匿名统计:daily=每天一次(含安装),install=仅首次,off=完全不联网(默认 daily)'),
|
|
69
79
|
})
|
|
70
80
|
|
|
71
81
|
/**
|
|
@@ -101,6 +111,7 @@ export function normalizeConfig(raw = {}) {
|
|
|
101
111
|
editor: editor.length > 0 ? editor : undefined,
|
|
102
112
|
takeoverShortcut: boolOf(raw.takeoverShortcut),
|
|
103
113
|
fullScreen: boolOf(raw.fullScreen),
|
|
114
|
+
telemetryLevel: resolveLevel(raw.telemetryLevel, DEFAULTS.telemetryLevel),
|
|
104
115
|
}
|
|
105
116
|
}
|
|
106
117
|
|
|
@@ -155,6 +166,55 @@ export function makeDiagnosticLog(file = join(tmpdir(), 'dsh-yazi.log')) {
|
|
|
155
166
|
}
|
|
156
167
|
}
|
|
157
168
|
|
|
169
|
+
/** Plugin identity used in the anonymous report (`p` field). */
|
|
170
|
+
const PLUGIN_ID = 'dsh-yazi'
|
|
171
|
+
|
|
172
|
+
/** Resolve `<DSH_HOME>/plugins/dsh-yazi`, the state file's home. */
|
|
173
|
+
export function resolvePluginDir(options = {}) {
|
|
174
|
+
const env = options.env ?? process.env
|
|
175
|
+
const raw = env?.DSH_HOME
|
|
176
|
+
const fromEnv = typeof raw === 'string' && raw.trim().length > 0 ? raw : undefined
|
|
177
|
+
const chosen = fromEnv ?? join(homedir(), '.dsh')
|
|
178
|
+
return resolve(chosen, 'plugins', PLUGIN_ID)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Read this plugin's own version from its shipped package.json. */
|
|
182
|
+
function readOwnVersion() {
|
|
183
|
+
try {
|
|
184
|
+
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
|
|
185
|
+
return typeof pkg?.version === 'string' ? pkg.version : ''
|
|
186
|
+
} catch {
|
|
187
|
+
return ''
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Fire one anonymous report. Kept separate from `apply` so tests can inject
|
|
193
|
+
* `dir` / `fetchImpl` / `clock` and assert what would be sent without a network.
|
|
194
|
+
* The caller must `void` the returned promise: statistics must never block
|
|
195
|
+
* plugin startup or the terminal.
|
|
196
|
+
*/
|
|
197
|
+
export function startTelemetry(options = {}) {
|
|
198
|
+
const level = resolveLevel(options.level ?? DEFAULTS.telemetryLevel)
|
|
199
|
+
if (level === 'off') return Promise.resolve({ sent: false, kind: null, reason: 'off' })
|
|
200
|
+
const reporter = new TelemetryReporter({
|
|
201
|
+
dir: options.dir ?? resolvePluginDir({ env: options.env }),
|
|
202
|
+
logger: options.logger,
|
|
203
|
+
pluginId: options.pluginId ?? PLUGIN_ID,
|
|
204
|
+
level,
|
|
205
|
+
endpoint: options.endpoint,
|
|
206
|
+
fetchImpl: options.fetchImpl,
|
|
207
|
+
clock: options.clock,
|
|
208
|
+
})
|
|
209
|
+
return reporter.start({
|
|
210
|
+
version: options.version ?? readOwnVersion(),
|
|
211
|
+
platform: options.platform ?? process.platform,
|
|
212
|
+
arch: options.arch ?? process.arch,
|
|
213
|
+
hostVersion: options.hostVersion ?? '',
|
|
214
|
+
count: options.count,
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
158
218
|
/**
|
|
159
219
|
* Attach the upgrade route and the PTY registry to the plugin context.
|
|
160
220
|
* @param {import('@deepseek-ai/cordis').Context} ctx The Host plugin context.
|
|
@@ -167,6 +227,9 @@ export function apply(ctx, config) {
|
|
|
167
227
|
const diagnostic = makeDiagnosticLog()
|
|
168
228
|
// Proves from the Host process that the log is writable and where it lands.
|
|
169
229
|
diagnostic('plugin', `activated yaziPath=${options.yaziPath}`)
|
|
230
|
+
// Anonymous install + DAU report. Fire-and-forget: off means no request and
|
|
231
|
+
// no state file at all; a failure only warns once and never breaks the panel.
|
|
232
|
+
void startTelemetry({ level: options.telemetryLevel, logger: ctx.logger })
|
|
170
233
|
const resolveExecutable = makeExecutableResolver({
|
|
171
234
|
resolveExecutable: (name) => ctx.subprocess.resolveExecutable(name),
|
|
172
235
|
stat,
|
package/package.json
CHANGED
package/src/client/assets.js
CHANGED
|
@@ -82,9 +82,6 @@ const CSS = [
|
|
|
82
82
|
'.dshyz-cfg-row input{margin:2px 0 0;flex:none}',
|
|
83
83
|
'.dshyz-cfg-label{font-size:13px;line-height:1.4;cursor:pointer}',
|
|
84
84
|
'.dshyz-cfg-hint{font-size:11px;line-height:1.6;opacity:.65;margin-top:2px;padding-bottom:2px}',
|
|
85
|
-
'.dshyz-cfg-note{font-size:11px;line-height:1.6;margin-top:4px;padding:6px 8px;border-radius:6px;',
|
|
86
|
-
'color:var(--dsw-alias-label-secondary,#555);background:var(--dsw-alias-bg-layer-1,rgba(0,0,0,.03));',
|
|
87
|
-
'border-left:2px solid var(--dsw-alias-state-warn-primary,#e67700)}',
|
|
88
85
|
].join('')
|
|
89
86
|
|
|
90
87
|
// The locale service registers dictionaries grouped by locale id, each with
|
|
@@ -107,11 +104,12 @@ const EN = {
|
|
|
107
104
|
'panel.restart': 'Reopen',
|
|
108
105
|
'panel.kill': 'Quit yazi',
|
|
109
106
|
'settings.title': 'Yazi panel',
|
|
110
|
-
'settings.takeoverShortcut': 'Use ⌘
|
|
111
|
-
'settings.takeoverShortcutHint': '
|
|
112
|
-
'settings.takeoverShortcutNote': 'If DSH binds the same key, DSH wins: clear the binding for Workspace Files in Settings → Shortcuts first, otherwise this switch has no effect.',
|
|
107
|
+
'settings.takeoverShortcut': 'Use ⌘Y / Ctrl+Y for yazi',
|
|
108
|
+
'settings.takeoverShortcutHint': 'Opens yazi from any tab. Once yazi is showing, the same key returns focus to the file manager.',
|
|
113
109
|
'settings.fullScreen': 'Let yazi fill the session area',
|
|
114
110
|
'settings.fullScreenHint': 'Hides the composer and other editing elements. The tab row stays so you can switch back.',
|
|
111
|
+
'settings.telemetry': 'Allow anonymous usage statistics',
|
|
112
|
+
'settings.telemetryHint': 'On by default. Sends one anonymous install event and at most one daily active event per day (random install id, plugin version, OS and CPU architecture only). No paths, file names or session content. Turn off to stop all reporting.',
|
|
115
113
|
'settings.unavailable': 'These options are unavailable in this profile.',
|
|
116
114
|
}
|
|
117
115
|
|
|
@@ -131,11 +129,12 @@ const ZH = {
|
|
|
131
129
|
'panel.restart': '重新打开',
|
|
132
130
|
'panel.kill': '退出 yazi',
|
|
133
131
|
'settings.title': 'Yazi 面板',
|
|
134
|
-
'settings.takeoverShortcut': '用 ⌘
|
|
135
|
-
'settings.takeoverShortcutHint': '在任意标签下按该快捷键都会切到 yazi
|
|
136
|
-
'settings.takeoverShortcutNote': '如果 DSH 也绑定了同一个键,DSH 优先:请先在「设置 → 快捷键」里清除「工作区文件」的绑定,否则这个开关不会生效。',
|
|
132
|
+
'settings.takeoverShortcut': '用 ⌘Y / Ctrl+Y 打开 yazi',
|
|
133
|
+
'settings.takeoverShortcutHint': '在任意标签下按该快捷键都会切到 yazi;已在 yazi 时则把焦点交回文件管理器。',
|
|
137
134
|
'settings.fullScreen': '让 yazi 占满会话区域',
|
|
138
135
|
'settings.fullScreenHint': '隐藏输入框等编辑元素;标签栏保留,方便切回对话。',
|
|
136
|
+
'settings.telemetry': '允许匿名统计',
|
|
137
|
+
'settings.telemetryHint': '默认开启。仅上报一次匿名安装事件和每天至多一次的活跃事件(只有随机安装 id、插件版本、系统与 CPU 架构),不包含任何路径、文件名或会话内容。关闭后不再进行任何上报。',
|
|
139
138
|
'settings.unavailable': '当前配置不支持修改这些选项。',
|
|
140
139
|
}
|
|
141
140
|
|
|
@@ -247,7 +246,7 @@ const FULLSCREEN_ATTR = 'dshYaziFullscreen'
|
|
|
247
246
|
* DSH's own shortcuts and layout.
|
|
248
247
|
*
|
|
249
248
|
* @param form configForms handle, or undefined.
|
|
250
|
-
* @returns {{ takeoverShortcut: boolean, fullScreen: boolean }}
|
|
249
|
+
* @returns {{ takeoverShortcut: boolean, fullScreen: boolean, telemetryLevel: string }}
|
|
251
250
|
*/
|
|
252
251
|
function readPanelOptions(form) {
|
|
253
252
|
let value = {}
|
|
@@ -258,19 +257,24 @@ function readPanelOptions(form) {
|
|
|
258
257
|
}
|
|
259
258
|
// A served document normally carries plain literals, but a volatile field
|
|
260
259
|
// can arrive wrapped; accept both shapes so a switch never reads as off.
|
|
261
|
-
const
|
|
260
|
+
const unwrap = (raw) => {
|
|
262
261
|
if (raw !== null && typeof raw === 'object' && typeof raw.get === 'function') {
|
|
263
262
|
try {
|
|
264
|
-
return raw.get()
|
|
263
|
+
return raw.get()
|
|
265
264
|
} catch {
|
|
266
|
-
return
|
|
265
|
+
return undefined
|
|
267
266
|
}
|
|
268
267
|
}
|
|
269
|
-
return raw
|
|
268
|
+
return raw
|
|
270
269
|
}
|
|
270
|
+
const on = (raw) => unwrap(raw) === true
|
|
271
|
+
const level = unwrap(value?.telemetryLevel)
|
|
271
272
|
return {
|
|
272
273
|
takeoverShortcut: on(value?.takeoverShortcut),
|
|
273
274
|
fullScreen: on(value?.fullScreen),
|
|
275
|
+
// Without a served level, treat consent as absent. The Host owns the
|
|
276
|
+
// default-on decision; the client must never assume it in the UI.
|
|
277
|
+
telemetryLevel: level === 'off' || level === 'install' || level === 'daily' ? level : 'off',
|
|
274
278
|
}
|
|
275
279
|
}
|
|
276
280
|
|
|
@@ -288,34 +292,7 @@ function applyFullScreen(doc, enabled) {
|
|
|
288
292
|
}
|
|
289
293
|
|
|
290
294
|
/**
|
|
291
|
-
*
|
|
292
|
-
*
|
|
293
|
-
* DSH's shortcut registry refuses a second command bound to a reserved
|
|
294
|
-
* combination, so the takeover is a capture-phase listener: it runs before the
|
|
295
|
-
* registry's own handler and stops the event there. Only the plain primary+P
|
|
296
|
-
* combination is taken; anything else stays with DSH or reaches yazi.
|
|
297
|
-
*
|
|
298
|
-
* @param win Window-like owner of the gesture.
|
|
299
|
-
* @param onTaken Called when the gesture is claimed.
|
|
300
|
-
* @returns Disposer removing the listener.
|
|
301
|
-
*/
|
|
302
|
-
function installShortcutTakeover(win, onTaken) {
|
|
303
|
-
const handler = (event) => {
|
|
304
|
-
if (event === null || typeof event !== 'object') return
|
|
305
|
-
const key = event.key
|
|
306
|
-
if (key !== 'p' && key !== 'P') return
|
|
307
|
-
if (event.metaKey !== true && event.ctrlKey !== true) return
|
|
308
|
-
if (event.altKey === true || event.shiftKey === true) return
|
|
309
|
-
event.preventDefault?.()
|
|
310
|
-
event.stopPropagation?.()
|
|
311
|
-
onTaken?.()
|
|
312
|
-
}
|
|
313
|
-
win.addEventListener('keydown', handler, true)
|
|
314
|
-
return () => win.removeEventListener('keydown', handler, true)
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* Claim primary+P for the panel while its switch is on and its tab is mounted.
|
|
295
|
+
* Claim primary+Y for the panel while its switch is on and its tab is mounted.
|
|
319
296
|
*
|
|
320
297
|
* The switch and the visibility are read on every keypress through `live`
|
|
321
298
|
* rather than captured at install time: a React effect that re-installs the
|
|
@@ -341,7 +318,7 @@ function installPanelShortcut(win, live) {
|
|
|
341
318
|
|
|
342
319
|
const handler = (event) => {
|
|
343
320
|
if (event === null || typeof event !== 'object') return
|
|
344
|
-
if (event.key !== '
|
|
321
|
+
if (event.key !== 'y' && event.key !== 'Y') return
|
|
345
322
|
if (event.metaKey !== true && event.ctrlKey !== true) return
|
|
346
323
|
if (event.altKey === true || event.shiftKey === true) return
|
|
347
324
|
if (live?.isEnabled?.() !== true) return
|
package/src/client/main.js
CHANGED
|
@@ -27,10 +27,12 @@ window.__ModuleLoader__.load({
|
|
|
27
27
|
const t = props.t
|
|
28
28
|
const form = props.form
|
|
29
29
|
|
|
30
|
-
//
|
|
31
|
-
//
|
|
30
|
+
// The live workingDirectory projection moves into a worktree checkout,
|
|
31
|
+
// which is not what this panel shows: it is a file manager for the
|
|
32
|
+
// project. The Host resolves that from the workspace registry, so the
|
|
33
|
+
// projection is not used as a path — only as a re-open trigger, because a
|
|
34
|
+
// directory move is when the resolved project may need re-checking.
|
|
32
35
|
const projected = useProjection('workingDirectory')
|
|
33
|
-
const directory = typeof projected === 'string' && projected !== '' ? projected : undefined
|
|
34
36
|
|
|
35
37
|
const stageRef = React.useRef(null)
|
|
36
38
|
const [phase, setPhase] = React.useState('connecting')
|
|
@@ -109,7 +111,9 @@ window.__ModuleLoader__.load({
|
|
|
109
111
|
bundle,
|
|
110
112
|
// No cols/rows here: the terminal fits itself to the container and
|
|
111
113
|
// reports the real size on socket open and on every resize.
|
|
112
|
-
|
|
114
|
+
// No cwd hint: the Host reads the session's workspace itself. A
|
|
115
|
+
// hint from here would be the live directory, i.e. the worktree.
|
|
116
|
+
query: { sid: sessionId },
|
|
113
117
|
notify(event) {
|
|
114
118
|
if (event.type === 'connecting') return
|
|
115
119
|
if (event.type === 'ready') {
|
|
@@ -141,7 +145,7 @@ window.__ModuleLoader__.load({
|
|
|
141
145
|
focusRef.current = null
|
|
142
146
|
terminal.dispose()
|
|
143
147
|
}
|
|
144
|
-
}, [generation, sessionId,
|
|
148
|
+
}, [generation, sessionId, projected, serverEpoch])
|
|
145
149
|
|
|
146
150
|
return h('div', { className: 'dshyz-root' }, [
|
|
147
151
|
h('div', { key: 'bar', className: 'dshyz-bar' }, [
|
|
@@ -155,8 +159,9 @@ window.__ModuleLoader__.load({
|
|
|
155
159
|
phase === 'live' ? t('panel.stateReady')
|
|
156
160
|
: phase === 'error' ? t('panel.stateError')
|
|
157
161
|
: t('panel.stateConnecting')),
|
|
158
|
-
|
|
159
|
-
|
|
162
|
+
// Only the directory the Host actually opened: showing the phrased
|
|
163
|
+
// projection would claim a root the panel never used.
|
|
164
|
+
h('span', { key: 'cwd', className: 'dshyz-cwd', title: cwd }, cwd),
|
|
160
165
|
h('button', {
|
|
161
166
|
key: 'restart',
|
|
162
167
|
type: 'button',
|
|
@@ -227,18 +232,18 @@ window.__ModuleLoader__.load({
|
|
|
227
232
|
const writable = state.status !== 'unavailable' && state.writable !== false
|
|
228
233
|
const options = readPanelOptions(form)
|
|
229
234
|
|
|
230
|
-
const switchRow = (field, labelKey, hintKey) => h('div', { key: field, className: 'dshyz-cfg-row' }, [
|
|
235
|
+
const switchRow = (field, labelKey, hintKey, read, write) => h('div', { key: field, className: 'dshyz-cfg-row' }, [
|
|
231
236
|
h('input', {
|
|
232
237
|
key: 'input',
|
|
233
238
|
id: 'dshyz-cfg-' + field,
|
|
234
239
|
type: 'checkbox',
|
|
235
|
-
checked: options[field] === true,
|
|
240
|
+
checked: (read ? read(options[field]) : options[field]) === true,
|
|
236
241
|
disabled: !writable,
|
|
237
242
|
onChange: (event) => {
|
|
238
243
|
const next = event?.target?.checked === true
|
|
239
244
|
// Optimistic local echo: the Host mirror confirms shortly after.
|
|
240
245
|
setState((previous) => ({ ...previous }))
|
|
241
|
-
void form?.set?.(field, next)
|
|
246
|
+
void form?.set?.(field, write ? write(next) : next)
|
|
242
247
|
},
|
|
243
248
|
}),
|
|
244
249
|
h('label', { key: 'label', className: 'dshyz-cfg-label', htmlFor: 'dshyz-cfg-' + field }, [
|
|
@@ -251,10 +256,17 @@ window.__ModuleLoader__.load({
|
|
|
251
256
|
h('div', { key: 'title', className: 'dshyz-cfg-label' }, t('settings.title')),
|
|
252
257
|
writable ? null : h('div', { key: 'off', className: 'dshyz-cfg-hint' }, t('settings.unavailable')),
|
|
253
258
|
switchRow('takeoverShortcut', 'settings.takeoverShortcut', 'settings.takeoverShortcutHint'),
|
|
254
|
-
// Outside the switch label: this is a precondition the user must satisfy
|
|
255
|
-
// in another settings page, not part of toggling the switch.
|
|
256
|
-
h('div', { key: 'shortcut-note', className: 'dshyz-cfg-note' }, t('settings.takeoverShortcutNote')),
|
|
257
259
|
switchRow('fullScreen', 'settings.fullScreen', 'settings.fullScreenHint'),
|
|
260
|
+
// Anonymous statistics is a level, not a boolean: the checkbox maps
|
|
261
|
+
// daily(consented) <-> off. `install` remains a supported level but is
|
|
262
|
+
// intentionally not offered in the detail-page UI.
|
|
263
|
+
switchRow(
|
|
264
|
+
'telemetryLevel',
|
|
265
|
+
'settings.telemetry',
|
|
266
|
+
'settings.telemetryHint',
|
|
267
|
+
(level) => level !== 'off',
|
|
268
|
+
(checked) => (checked ? 'daily' : 'off'),
|
|
269
|
+
),
|
|
258
270
|
])
|
|
259
271
|
}
|
|
260
272
|
|
|
@@ -285,7 +297,7 @@ window.__ModuleLoader__.load({
|
|
|
285
297
|
select: (doc, label) => activatePanel(doc, label),
|
|
286
298
|
focus: () => panelFocus.current?.(),
|
|
287
299
|
document: typeof document === 'undefined' ? undefined : document,
|
|
288
|
-
}), 'yazi: primary+
|
|
300
|
+
}), 'yazi: primary+Y takeover')
|
|
289
301
|
}
|
|
290
302
|
|
|
291
303
|
ctx.effect(() => {
|
package/src/host/cwd.js
CHANGED
|
@@ -11,34 +11,51 @@ export class CwdError extends Error {
|
|
|
11
11
|
/**
|
|
12
12
|
* Find a directory for yazi to open in.
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
14
|
+
* The panel is a file manager for the *project*, so a session that entered a
|
|
15
|
+
* worktree must not drag the panel into the checkout. Precedence:
|
|
16
|
+
*
|
|
17
|
+
* 1. the workspace that owns this session (registry `sessionIds`)
|
|
18
|
+
* 2. the session's immutable `header.cwd` (the original project)
|
|
19
|
+
* 3. the session's live `workingDirectory` projection (moves with the UI)
|
|
20
|
+
* 4. a client-provided hint (e.g. the path the panel already renders)
|
|
21
|
+
* 5. the first registered workspace whose path still exists
|
|
22
|
+
* 6. the configured default directory
|
|
23
|
+
*
|
|
24
|
+
* Rules 1 and 2 both name the project. The live projection is only a fallback
|
|
25
|
+
* for sessions that have neither, which is what keeps a worktree entry from
|
|
26
|
+
* becoming the panel's root.
|
|
20
27
|
*
|
|
21
28
|
* Every candidate is stat'ed and must still be a directory; vanished
|
|
22
29
|
* directories fall through to the next candidate.
|
|
23
30
|
*
|
|
24
|
-
* @param deps { getSession, getWorkingDirectory, listWorkspaces, stat, defaultDirectory }
|
|
31
|
+
* @param deps { getSession, getWorkingDirectory, findWorkspace, listWorkspaces, stat, defaultDirectory }
|
|
25
32
|
* stat: (path) => Promise<'dir' | 'file' | 'missing'>
|
|
33
|
+
* findWorkspace: (session, sessionId) => Workspace | undefined
|
|
26
34
|
* @param request { sessionId?, hintPath? }
|
|
27
|
-
* @returns Promise<{ path: string, source: '
|
|
35
|
+
* @returns Promise<{ path: string, source: 'ownership'|'header'|'session'|'hint'|'workspace'|'default' }>
|
|
28
36
|
* @throws {CwdError} when no candidate survives.
|
|
29
37
|
*/
|
|
30
38
|
export async function resolveYaziDirectory(deps, request = {}) {
|
|
31
39
|
const candidates = []
|
|
32
40
|
const session = request.sessionId ? deps.getSession(request.sessionId) : undefined
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
41
|
+
// Ownership is asked for even without a live session: `ctx.sessions.get()`
|
|
42
|
+
// only answers for live ones, while the registry's account still names the
|
|
43
|
+
// project a cold session belongs to.
|
|
44
|
+
if (request.sessionId !== undefined) {
|
|
45
|
+
const owned = deps.findWorkspace?.(session, request.sessionId)
|
|
46
|
+
if (owned && typeof owned.path === 'string' && owned.path.length > 0) {
|
|
47
|
+
candidates.push({ path: owned.path, source: 'ownership' })
|
|
37
48
|
}
|
|
49
|
+
}
|
|
50
|
+
if (session !== undefined) {
|
|
38
51
|
const header = session.header && session.header.cwd
|
|
39
52
|
if (typeof header === 'string' && header.length > 0) {
|
|
40
53
|
candidates.push({ path: header, source: 'header' })
|
|
41
54
|
}
|
|
55
|
+
const live = deps.getWorkingDirectory(session)
|
|
56
|
+
if (typeof live === 'string' && live.length > 0) {
|
|
57
|
+
candidates.push({ path: live, source: 'session' })
|
|
58
|
+
}
|
|
42
59
|
}
|
|
43
60
|
if (typeof request.hintPath === 'string' && request.hintPath.length > 0) {
|
|
44
61
|
candidates.push({ path: request.hintPath, source: 'hint' })
|
package/src/host/route.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { stat } from 'node:fs/promises'
|
|
6
6
|
import { createHandshakeResponse, encodeFrame, OPCODES } from './websocket.js'
|
|
7
7
|
import { resolveYaziDirectory } from './cwd.js'
|
|
8
|
+
import { makeWorkspaceFinder } from './workspace.js'
|
|
8
9
|
|
|
9
10
|
export const UPGRADE_PATH = '/dsh-yazi/pty'
|
|
10
11
|
|
|
@@ -22,9 +23,15 @@ function httpError(socket, status, reason) {
|
|
|
22
23
|
|
|
23
24
|
/**
|
|
24
25
|
* Build the Host-side cwd resolver from plugin context services.
|
|
26
|
+
*
|
|
27
|
+
* The workspace lookup comes first so a session that entered a worktree still
|
|
28
|
+
* gets the project it belongs to: `workingDirectory` moves with that entry and
|
|
29
|
+
* would otherwise root the panel inside `.agents/worktrees/<name>`.
|
|
30
|
+
*
|
|
25
31
|
* @param ctx Host plugin context (sessions/workingDirectory/workspaceRegistry).
|
|
26
32
|
*/
|
|
27
33
|
export function makeDirectoryResolver(ctx) {
|
|
34
|
+
const findWorkspace = makeWorkspaceFinder(ctx.workspaceRegistry)
|
|
28
35
|
return async function resolve(request) {
|
|
29
36
|
const check = async (path) => {
|
|
30
37
|
try {
|
|
@@ -37,6 +44,7 @@ export function makeDirectoryResolver(ctx) {
|
|
|
37
44
|
return resolveYaziDirectory({
|
|
38
45
|
getSession: (id) => ctx.sessions?.get?.(id),
|
|
39
46
|
getWorkingDirectory: (session) => ctx.workingDirectory?.get(session),
|
|
47
|
+
findWorkspace,
|
|
40
48
|
listWorkspaces: () => ctx.workspaceRegistry?.list?.() ?? [],
|
|
41
49
|
stat: check,
|
|
42
50
|
defaultDirectory: ctx.workingDirectory?.defaultDirectory ?? process.cwd(),
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 匿名使用统计的上报端(Host 侧)。
|
|
3
|
+
*
|
|
4
|
+
* 复用 dsh-decision-engine 的采集协议:`https://dsh.zuos.us/api/e`,上报体用
|
|
5
|
+
* 同样的短键(v/p/id/k/ver/os/arch/host/day),服务端按 `p`(插件 id)分插件
|
|
6
|
+
* 统计。这里只上报匿名安装 id、版本、平台、架构与事件种类;**绝不**发送路径、
|
|
7
|
+
* 会话内容、API key 或任何用户标识。
|
|
8
|
+
*
|
|
9
|
+
* 三条硬承诺(与参考插件一致):
|
|
10
|
+
* 1. `level === "off"` 时连状态文件都不读,更不发请求;
|
|
11
|
+
* 2. 每当地日(`Asia/Shanghai`,固定 +8,中国无夏令时)最多一次;
|
|
12
|
+
* 3. 绝不阻塞插件:所有失败都吞成一条警告,调用方 `void` 掉 `start()`。
|
|
13
|
+
*
|
|
14
|
+
* 纯计算(日期、状态、是否该发、上报体)与副作用(读写文件、HTTP)分开,
|
|
15
|
+
* 前者可被 test/telemetry.test.js 直接断言,后者用注入的 fetch / 时钟 / 目录
|
|
16
|
+
* 测试,完全不碰真实网络。
|
|
17
|
+
*/
|
|
18
|
+
import { randomUUID } from 'node:crypto'
|
|
19
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
20
|
+
import { join } from 'node:path'
|
|
21
|
+
|
|
22
|
+
/** 默认上报端点,与 dsh-decision-engine 相同。 */
|
|
23
|
+
export const DEFAULT_ENDPOINT = 'https://dsh.zuos.us/api/e'
|
|
24
|
+
|
|
25
|
+
/** 统计档位:off 完全不联网;install 仅首次;daily 每天一次(默认)。 */
|
|
26
|
+
export const TELEMETRY_LEVELS = ['off', 'install', 'daily']
|
|
27
|
+
|
|
28
|
+
/** 状态文件名,与 decision-engine 同目录约定(放在插件数据目录)。 */
|
|
29
|
+
export const STATE_FILE = 'analytics.json'
|
|
30
|
+
|
|
31
|
+
/** 北京时间固定偏移(毫秒)。中国自 1991 年起无夏令时。 */
|
|
32
|
+
const TZ_OFFSET_MS = 8 * 60 * 60 * 1000
|
|
33
|
+
|
|
34
|
+
/** 单次上报超时,避免拖住进程退出。 */
|
|
35
|
+
const REQUEST_TIMEOUT_MS = 5000
|
|
36
|
+
|
|
37
|
+
/** 连续失败多少次后彻底降级。 */
|
|
38
|
+
const DEGRADE_AFTER_FAILURES = 30
|
|
39
|
+
|
|
40
|
+
/** 把毫秒时间戳格式化成 Asia/Shanghai 的日历日 `YYYY-MM-DD`。 */
|
|
41
|
+
export function shanghaiDay(ms) {
|
|
42
|
+
const value = Number(ms)
|
|
43
|
+
if (!Number.isFinite(value)) return ''
|
|
44
|
+
return new Date(value + TZ_OFFSET_MS).toISOString().slice(0, 10)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 安装 id 合法性:UUIDv4(服务端按同一规则校验)。 */
|
|
48
|
+
export function isValidInstallId(value) {
|
|
49
|
+
return typeof value === 'string'
|
|
50
|
+
&& /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 生成一个新的匿名安装 id(随机 UUIDv4,与账号无关)。 */
|
|
54
|
+
export function newInstallId() {
|
|
55
|
+
return randomUUID()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 解析状态文件;任何损坏都退化为「全新安装」而不是抛错。 */
|
|
59
|
+
export function parseState(text) {
|
|
60
|
+
let raw = null
|
|
61
|
+
try {
|
|
62
|
+
raw = JSON.parse(String(text ?? ''))
|
|
63
|
+
} catch {
|
|
64
|
+
raw = null
|
|
65
|
+
}
|
|
66
|
+
const source = raw !== null && typeof raw === 'object' ? raw : {}
|
|
67
|
+
const firstRunAt = Number(source.firstRunAt)
|
|
68
|
+
const failures = Number(source.failures)
|
|
69
|
+
return {
|
|
70
|
+
installId: isValidInstallId(source.installId) ? source.installId : null,
|
|
71
|
+
firstRunAt: Number.isFinite(firstRunAt) && firstRunAt > 0 ? firstRunAt : null,
|
|
72
|
+
firstVersion: typeof source.firstVersion === 'string' ? source.firstVersion : '',
|
|
73
|
+
lastSentDay: typeof source.lastSentDay === 'string' ? source.lastSentDay : '',
|
|
74
|
+
lastAttemptDay: typeof source.lastAttemptDay === 'string' ? source.lastAttemptDay : '',
|
|
75
|
+
lastOkDay: typeof source.lastOkDay === 'string' ? source.lastOkDay : '',
|
|
76
|
+
failures: Number.isFinite(failures) ? Math.max(0, failures) : 0,
|
|
77
|
+
degraded: source.degraded === true,
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 序列化状态,字段顺序固定,便于人直接读。 */
|
|
82
|
+
export function serializeState(state) {
|
|
83
|
+
return `${JSON.stringify({
|
|
84
|
+
installId: state?.installId ?? null,
|
|
85
|
+
firstRunAt: state?.firstRunAt ?? null,
|
|
86
|
+
firstVersion: state?.firstVersion ?? '',
|
|
87
|
+
lastSentDay: state?.lastSentDay ?? '',
|
|
88
|
+
lastAttemptDay: state?.lastAttemptDay ?? '',
|
|
89
|
+
lastOkDay: state?.lastOkDay ?? '',
|
|
90
|
+
failures: state?.failures ?? 0,
|
|
91
|
+
degraded: state?.degraded === true,
|
|
92
|
+
}, null, 2)}\n`
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 决定本次要不要上报。纯函数,测试主入口。
|
|
97
|
+
* @returns `"install"` / `"heartbeat"` / null(本次不发)。
|
|
98
|
+
*/
|
|
99
|
+
export function decideKind(state, { today, level } = {}) {
|
|
100
|
+
if (level === 'off') return null
|
|
101
|
+
if (typeof today !== 'string' || today.length === 0) return null
|
|
102
|
+
if (state?.degraded === true) return null
|
|
103
|
+
// 同一当地日重复启动不重发:这是「每天最多一次」的唯一执行点。
|
|
104
|
+
if (state?.lastAttemptDay === today) return null
|
|
105
|
+
const fresh = !isValidInstallId(state?.installId) || !Number.isFinite(Number(state?.firstRunAt))
|
|
106
|
+
if (fresh) return 'install'
|
|
107
|
+
if (level === 'install') return null
|
|
108
|
+
return 'heartbeat'
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 版本号清洗:只保留可打印版本字符,防注入与超长。 */
|
|
112
|
+
export function normalizeVersion(value) {
|
|
113
|
+
return String(value ?? '').trim().replace(/[^0-9A-Za-z._+-]/g, '').slice(0, 32)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function shortField(value, max = 24) {
|
|
117
|
+
return String(value ?? '').trim().replace(/[^0-9A-Za-z._+-]/g, '').slice(0, max)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function normalizeDay(value) {
|
|
121
|
+
const text = String(value ?? '').trim()
|
|
122
|
+
return /^\d{4}-\d{2}-\d{2}$/.test(text) ? text : ''
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 插件标识(npm 包名形态):小写,字母数字与 - . _,最长 48。 */
|
|
126
|
+
export function normalizePluginId(value) {
|
|
127
|
+
const text = String(value ?? '').trim().toLowerCase()
|
|
128
|
+
return /^[a-z0-9][a-z0-9._-]{0,47}$/.test(text) ? text : ''
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 构造上报体,键名刻意短:**没有地方放 prompt / 路径 / 会话内容**。
|
|
133
|
+
* 字段名与 decision-engine 完全一致,服务端共用同一采集协议。
|
|
134
|
+
*/
|
|
135
|
+
export function buildPayload(input = {}) {
|
|
136
|
+
const payload = {
|
|
137
|
+
v: 1,
|
|
138
|
+
p: normalizePluginId(input.pluginId),
|
|
139
|
+
id: input.installId,
|
|
140
|
+
k: input.kind,
|
|
141
|
+
ver: normalizeVersion(input.version) || 'unknown',
|
|
142
|
+
os: shortField(input.platform),
|
|
143
|
+
arch: shortField(input.arch),
|
|
144
|
+
}
|
|
145
|
+
const host = normalizeVersion(input.hostVersion)
|
|
146
|
+
if (host.length > 0) payload.host = host
|
|
147
|
+
const day = normalizeDay(input.day)
|
|
148
|
+
if (day.length > 0) payload.day = day
|
|
149
|
+
const count = Number(input.count)
|
|
150
|
+
if (Number.isFinite(count) && count > 0) payload.d = Math.min(Math.trunc(count), 100000)
|
|
151
|
+
return payload
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 校验上报端点;非法或空时回落默认值。 */
|
|
155
|
+
export function resolveEndpoint(raw) {
|
|
156
|
+
const text = String(raw ?? '').trim()
|
|
157
|
+
if (text.length === 0) return DEFAULT_ENDPOINT
|
|
158
|
+
try {
|
|
159
|
+
const url = new URL(text)
|
|
160
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') return DEFAULT_ENDPOINT
|
|
161
|
+
return url.href
|
|
162
|
+
} catch {
|
|
163
|
+
return DEFAULT_ENDPOINT
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** 档位规范化;未知值回落默认档。接受 cordis Volatile 包装。 */
|
|
168
|
+
export function resolveLevel(raw, fallback = 'daily') {
|
|
169
|
+
let value = raw
|
|
170
|
+
if (value !== null && typeof value === 'object' && typeof value.get === 'function') {
|
|
171
|
+
try {
|
|
172
|
+
value = value.get()
|
|
173
|
+
} catch {
|
|
174
|
+
value = undefined
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const text = String(value ?? '').trim()
|
|
178
|
+
if (TELEMETRY_LEVELS.includes(text)) return text
|
|
179
|
+
return TELEMETRY_LEVELS.includes(fallback) ? fallback : 'daily'
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 上报器。副作用全部集中在 `start()`;注入 dir / logger / fetchImpl / clock,
|
|
184
|
+
* 测试无需真实网络或宿主环境。
|
|
185
|
+
*/
|
|
186
|
+
export class TelemetryReporter {
|
|
187
|
+
#dir
|
|
188
|
+
#logger
|
|
189
|
+
#endpoint
|
|
190
|
+
#pluginId
|
|
191
|
+
#level
|
|
192
|
+
#fetchImpl
|
|
193
|
+
#clock
|
|
194
|
+
#warned = false
|
|
195
|
+
|
|
196
|
+
constructor(options = {}) {
|
|
197
|
+
this.#dir = options.dir ?? '.'
|
|
198
|
+
this.#logger = options.logger
|
|
199
|
+
this.#endpoint = resolveEndpoint(options.endpoint)
|
|
200
|
+
this.#pluginId = normalizePluginId(options.pluginId)
|
|
201
|
+
this.#level = resolveLevel(options.level ?? 'daily')
|
|
202
|
+
this.#fetchImpl = options.fetchImpl ?? globalThis.fetch
|
|
203
|
+
this.#clock = typeof options.clock === 'function' ? options.clock : () => Date.now()
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
get level() { return this.#level }
|
|
207
|
+
get endpoint() { return this.#endpoint }
|
|
208
|
+
get pluginId() { return this.#pluginId }
|
|
209
|
+
get statePath() { return join(this.#dir, STATE_FILE) }
|
|
210
|
+
|
|
211
|
+
/** 只读状态文件;不存在或损坏时返回全新安装状态,不创建文件。 */
|
|
212
|
+
async readState() {
|
|
213
|
+
try {
|
|
214
|
+
return parseState(await readFile(this.statePath, 'utf8'))
|
|
215
|
+
} catch {
|
|
216
|
+
return parseState('')
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 原子写状态:临时文件 + rename,避免半截 JSON。 */
|
|
221
|
+
async writeState(state) {
|
|
222
|
+
await mkdir(this.#dir, { recursive: true })
|
|
223
|
+
const tmp = `${this.statePath}.tmp`
|
|
224
|
+
await writeFile(tmp, serializeState(state), { encoding: 'utf8', mode: 0o600 })
|
|
225
|
+
await rename(tmp, this.statePath)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** 计算本次应发的上报体(不发送、不落盘)。不该发时返回 null。 */
|
|
229
|
+
async prepare(input = {}) {
|
|
230
|
+
if (this.#level === 'off') return null
|
|
231
|
+
if (this.#pluginId.length === 0) return null
|
|
232
|
+
const now = this.#clock()
|
|
233
|
+
const today = shanghaiDay(now)
|
|
234
|
+
if (today.length === 0) return null
|
|
235
|
+
const state = await this.readState()
|
|
236
|
+
const kind = decideKind(state, { today, level: this.#level })
|
|
237
|
+
if (kind === null) return null
|
|
238
|
+
const installId = state.installId ?? newInstallId()
|
|
239
|
+
const next = {
|
|
240
|
+
...state,
|
|
241
|
+
installId,
|
|
242
|
+
firstRunAt: state.firstRunAt ?? now,
|
|
243
|
+
firstVersion: state.firstVersion.length > 0 ? state.firstVersion : normalizeVersion(input.version),
|
|
244
|
+
lastAttemptDay: today,
|
|
245
|
+
}
|
|
246
|
+
const payload = buildPayload({
|
|
247
|
+
pluginId: this.#pluginId,
|
|
248
|
+
installId,
|
|
249
|
+
kind,
|
|
250
|
+
version: input.version,
|
|
251
|
+
platform: input.platform,
|
|
252
|
+
arch: input.arch,
|
|
253
|
+
hostVersion: input.hostVersion,
|
|
254
|
+
day: input.day,
|
|
255
|
+
count: input.count,
|
|
256
|
+
})
|
|
257
|
+
return { state: next, payload, today, kind }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** 执行一次上报。**绝不抛错**:失败只记一条警告并把状态留到下次。 */
|
|
261
|
+
async start(input = {}) {
|
|
262
|
+
if (this.#level === 'off') return { sent: false, kind: null, reason: 'off' }
|
|
263
|
+
if (this.#pluginId.length === 0) return { sent: false, kind: null, reason: 'no-plugin-id' }
|
|
264
|
+
let prepared = null
|
|
265
|
+
try {
|
|
266
|
+
prepared = await this.prepare(input)
|
|
267
|
+
} catch (error) {
|
|
268
|
+
this.#warn(`统计状态读取失败(不影响插件):${String(error?.message ?? error)}`)
|
|
269
|
+
return { sent: false, kind: null, reason: 'state-error' }
|
|
270
|
+
}
|
|
271
|
+
if (prepared === null) return { sent: false, kind: null, reason: 'not-due' }
|
|
272
|
+
const { state, payload, today } = prepared
|
|
273
|
+
// 先落状态再发送:即便发送中被杀,也不会在同一天反复重发。
|
|
274
|
+
try {
|
|
275
|
+
await this.writeState(state)
|
|
276
|
+
} catch (error) {
|
|
277
|
+
this.#warn(`统计状态写入失败(不影响插件):${String(error?.message ?? error)}`)
|
|
278
|
+
}
|
|
279
|
+
const sent = await this.#post(payload)
|
|
280
|
+
try {
|
|
281
|
+
await this.writeState({
|
|
282
|
+
...state,
|
|
283
|
+
lastSentDay: sent ? today : state.lastSentDay,
|
|
284
|
+
lastOkDay: sent ? today : state.lastOkDay,
|
|
285
|
+
failures: sent ? 0 : state.failures + 1,
|
|
286
|
+
degraded: sent ? false : state.failures + 1 >= DEGRADE_AFTER_FAILURES,
|
|
287
|
+
})
|
|
288
|
+
} catch {
|
|
289
|
+
/* 第二次写失败只影响下次重试,不必再警告 */
|
|
290
|
+
}
|
|
291
|
+
if (!sent) this.#warn(`上报未成功(端点 ${this.#endpoint}),下次启动再试;不影响插件`)
|
|
292
|
+
return { sent, kind: payload.k, reason: sent ? 'ok' : 'http-failed' }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** 真正发请求;返回是否 2xx。超时 / 网络错误一律当作没成功。 */
|
|
296
|
+
async #post(payload) {
|
|
297
|
+
const fetchImpl = this.#fetchImpl
|
|
298
|
+
if (typeof fetchImpl !== 'function') return false
|
|
299
|
+
const controller = new AbortController()
|
|
300
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
|
301
|
+
try {
|
|
302
|
+
const response = await fetchImpl(this.#endpoint, {
|
|
303
|
+
method: 'POST',
|
|
304
|
+
headers: { 'content-type': 'application/json' },
|
|
305
|
+
body: JSON.stringify(payload),
|
|
306
|
+
signal: controller.signal,
|
|
307
|
+
})
|
|
308
|
+
return Boolean(response?.ok)
|
|
309
|
+
} catch {
|
|
310
|
+
return false
|
|
311
|
+
} finally {
|
|
312
|
+
clearTimeout(timer)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
#warn(message) {
|
|
317
|
+
if (this.#warned) return
|
|
318
|
+
this.#warned = true
|
|
319
|
+
this.#logger?.warn?.(`dsh-yazi: ${message}`)
|
|
320
|
+
}
|
|
321
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Ownership lookup for the Yazi panel: which registered workspace does a
|
|
2
|
+
// session belong to?
|
|
3
|
+
//
|
|
4
|
+
// The registry records membership in `Workspace.sessionIds`, validated against
|
|
5
|
+
// each session's immutable `header.cwd`. Entering a worktree publishes a
|
|
6
|
+
// `workspace-root/change` and leaves that header alone — the docs put it as
|
|
7
|
+
// "it does not change the Session's original project" — so membership keeps
|
|
8
|
+
// naming the project even while the session works inside `.agents/worktrees/`.
|
|
9
|
+
// That is exactly the split the panel needs.
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Build the ownership finder handed to `resolveYaziDirectory`.
|
|
13
|
+
*
|
|
14
|
+
* @param registry The `ctx.workspaceRegistry` service.
|
|
15
|
+
* @returns (session, sessionId?) => Workspace | undefined
|
|
16
|
+
*/
|
|
17
|
+
export function makeWorkspaceFinder(registry) {
|
|
18
|
+
return function findWorkspace(_session, sessionId) {
|
|
19
|
+
if (sessionId === undefined) return undefined
|
|
20
|
+
// `list()` is a synchronous projection whose `sessionIds` is already
|
|
21
|
+
// filtered through the canonical-cwd header index, so a stale entry cannot
|
|
22
|
+
// claim a session it no longer owns.
|
|
23
|
+
for (const workspace of registry?.list?.() ?? []) {
|
|
24
|
+
if (Array.isArray(workspace?.sessionIds) && workspace.sessionIds.includes(sessionId)) {
|
|
25
|
+
return workspace
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return undefined
|
|
29
|
+
}
|
|
30
|
+
}
|