dsh-prompt-pocket 1.0.2 → 1.0.4

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/README.md CHANGED
@@ -1,70 +1,72 @@
1
- # dsh-prompt-pocket
2
-
3
- **A prompt pocket for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness): one keystroke saves what you were typing, one click puts it back at the caret.** It lives as a 24px dot in the corner, so the layout never grows a sidebar, a chip row, or a panel that shifts the conversation.
4
-
5
- ![The prompt pocket open over a session: a search box, two drawers, three saved prompts and the dot in the corner](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/en-panel.png)
6
-
7
- Site: **[dshtoolbox.com/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/)** · 中文页: [dshtoolbox.com/zh/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/) · npm: [dsh-prompt-pocket](https://www.npmjs.com/package/dsh-prompt-pocket)
8
-
9
- ## Why it exists
10
-
11
- Prompt libraries ask for a title, tags, a folder and a panel before they will keep a sentence. By then you have forgotten the sentence. This one keeps the sentence.
12
-
13
- ## What it does that others do not
14
-
15
- - **`Ctrl+Shift+S` saves without a dialog.** The selection if there is one, the whole draft otherwise. No title, no tags, no “where should this go”.
16
- - **The confirmation appears beside the dot even when the panel is closed** — with a one-click move to the other drawer and a button to rewrite the prompt.
17
- - **Insert is revision-guarded, not string concatenation.** A quote chip or attachment you already had stays where it is, the insert is one undo step, and focus returns to the composer.
18
- - **Two drawers split by workspace, not by session.** Sessions get archived and forked; a prompt pinned to one session loses its home. A bare session falls back to General instead of showing an empty drawer.
19
- - **✦ writes a DSH prompt, it does not paraphrase.** Variables, paths, URLs and code blocks are kept byte-for-byte, nothing is invented, and filler is forbidden by the instruction. A failed or empty result never replaces your text; accepting a rewrite keeps the old one in `prior`.
20
- - **One click on an assistant reply keeps it verbatim** as source material, read from the session log — text blocks only, tool calls never leak in.
21
- - **The agent shares the same pocket** through the `prompt_stash` tool, scoped to the drawers so one project's prompts do not show up in another's answer.
22
- - **500 prompts, least recently used dropped, one JSON file, atomic writes, no runtime dependencies, no account.** Nothing leaves the machine except the one model call you explicitly ask for.
23
-
24
- ![The pocket collapsed to a faint dot in the corner of the composer](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/en-pill.png)
25
-
26
- ## Install
27
-
28
- ```bash
29
- dsh plugin --profile web add dsh-prompt-pocket
30
- ```
31
-
32
- Restart the host once so the route, the tool and the client bundle register, then force-reload the page with `Ctrl+Shift+R`. From a checkout instead:
33
-
34
- ```bash
35
- git clone https://github.com/FindSomeSkills/dsh-prompt-pocket
36
- cd dsh-prompt-pocket
37
- dsh plugin --profile web add .
38
- ```
39
-
40
- ## Use
41
-
42
- | Action | How |
43
- | --- | --- |
44
- | Save the selection or the draft | `Ctrl+Shift+S` |
45
- | Open or close the pocket | `Ctrl+Shift+P`, or click the dot |
46
- | Move the dot | Drag it; the position is remembered per browser |
47
- | Insert a prompt at the caret | `Enter`, or click the row |
48
- | Replace the whole draft | `Alt+Enter` while a row is selected |
49
- | Walk the list | `↑` `↓` (wraps around), `Esc` closes |
50
- | Move a prompt between drawers | `⇄` on the row |
51
- | Delete | `×` on the row |
52
- | Rewrite the prompt for DSH | `✦`, or the button on the save confirmation |
53
- | Save an assistant reply | `⤓` in the reply action row |
54
-
55
- ## Where the data lives
56
-
57
- `$DSH_HOME/dsh-prompt-stash/store.json`, by default `~/.dsh/dsh-prompt-stash/store.json`. One file for every profile and every browser pointed at this host; writes go through a temporary file and a rename, and a damaged file is renamed to `.corrupt-<timestamp>.bak` instead of blocking the panel.
58
-
59
- ## Requirements
60
-
61
- DeepSeek Harness `>= 0.2.0-rc.1` and a Web profile — the pocket renders inside the composer. Windows, macOS and Linux run the same code; the interface language follows the DSH setting. The desktop client is untested.
62
-
63
- ## Links
64
-
65
- - Product page: https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/
66
- - Chinese page: https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/
67
- - npm: https://www.npmjs.com/package/dsh-prompt-pocket
68
- - Manual: [docs/DETAIL.md](docs/DETAIL.md) (English) · [docs/DETAIL.zh.md](docs/DETAIL.zh.md) (中文)
69
-
70
- MIT.
1
+ # dsh-prompt-pocket
2
+
3
+ **A prompt pocket for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness): one keystroke saves what you were typing, one click puts it back at the caret.** It lives as a 24px dot in the corner, so the layout never grows a sidebar, a chip row, or a panel that shifts the conversation.
4
+
5
+ ![The prompt pocket open over a session: a search box, two drawers, three saved prompts and the dot in the corner](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/en-panel.png)
6
+
7
+ Site: **[dshtoolbox.com/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/)** · 中文页: [dshtoolbox.com/zh/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/) · npm: [dsh-prompt-pocket](https://www.npmjs.com/package/dsh-prompt-pocket)
8
+
9
+ ## Why it exists
10
+
11
+ Prompt libraries ask for a title, tags, a folder and a panel before they will keep a sentence. By then you have forgotten the sentence. This one keeps the sentence.
12
+
13
+ ## What it does that others do not
14
+
15
+ - **`Ctrl+Shift+S` saves without a dialog.** The selection if there is one, the whole draft otherwise. No title, no tags, no “where should this go”.
16
+ - **The confirmation appears beside the dot even when the panel is closed** — with a one-click move to the other drawer and a button to rewrite the prompt.
17
+ - **Insert is revision-guarded, not string concatenation.** A quote chip or attachment you already had stays where it is, the insert is one undo step, and focus returns to the composer.
18
+ - **Two drawers split by workspace, not by session.** Sessions get archived and forked; a prompt pinned to one session loses its home. A bare session falls back to General instead of showing an empty drawer.
19
+ - **✦ writes a DSH prompt, it does not paraphrase.** Variables, paths, URLs and code blocks are kept byte-for-byte, nothing is invented, and filler is forbidden by the instruction. A failed or empty result never replaces your text; accepting a rewrite keeps the old one in `prior`.
20
+ - **One click on an assistant reply keeps it verbatim** as source material, read from the session log — text blocks only, tool calls never leak in.
21
+ - **The agent shares the same pocket** through the `prompt_stash` tool, scoped to the drawers so one project's prompts do not show up in another's answer.
22
+ - **Sync through your own private git repository.** The panel pushes each change and merges the remote on launch; prompts are one file each, so a merge keeps both sides instead of corrupting one document. **A public repository is refused** — the plugin asks GitHub whether the repo is visible before it enables sync.
23
+ - **Export and import as one JSON file.** For machines without git, or for a backup before you trust a sync.
24
+ - **500 prompts, least recently used dropped, one JSON file, atomic writes, no runtime dependencies, no account.** Nothing leaves the machine except the one model call you explicitly ask for.
25
+
26
+ ![The pocket collapsed to a faint dot in the corner of the composer](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/en-pill.png)
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ dsh plugin --profile web add dsh-prompt-pocket
32
+ ```
33
+
34
+ Restart the host once so the route, the tool and the client bundle register, then force-reload the page with `Ctrl+Shift+R`. From a checkout instead:
35
+
36
+ ```bash
37
+ git clone https://github.com/FindSomeSkills/dsh-prompt-pocket
38
+ cd dsh-prompt-pocket
39
+ dsh plugin --profile web add .
40
+ ```
41
+
42
+ ## Use
43
+
44
+ | Action | How |
45
+ | --- | --- |
46
+ | Save the selection or the draft | `Ctrl+Shift+S` |
47
+ | Open or close the pocket | `Ctrl+Shift+P`, or click the dot |
48
+ | Move the dot | Drag it; the position is remembered per browser |
49
+ | Insert a prompt at the caret | `Enter`, or click the row |
50
+ | Replace the whole draft | `Alt+Enter` while a row is selected |
51
+ | Walk the list | `↑` `↓` (wraps around), `Esc` closes |
52
+ | Move a prompt between drawers | `⇄` on the row |
53
+ | Delete | `×` on the row |
54
+ | Rewrite the prompt for DSH | `✦`, or the button on the save confirmation |
55
+ | Save an assistant reply | `⤓` in the reply action row |
56
+
57
+ ## Where the data lives
58
+
59
+ `$DSH_HOME/dsh-prompt-stash/store.json`, by default `~/.dsh/dsh-prompt-stash/store.json`. One file for every profile and every browser pointed at this host; writes go through a temporary file and a rename, and a damaged file is renamed to `.corrupt-<timestamp>.bak` instead of blocking the panel.
60
+
61
+ ## Requirements
62
+
63
+ DeepSeek Harness `>= 0.2.0-rc.1` and a Web profile — the pocket renders inside the composer. Windows, macOS and Linux run the same code; the interface language follows the DSH setting. The desktop client is untested.
64
+
65
+ ## Links
66
+
67
+ - Product page: https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/
68
+ - Chinese page: https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/
69
+ - npm: https://www.npmjs.com/package/dsh-prompt-pocket
70
+ - Manual: [docs/DETAIL.md](docs/DETAIL.md) (English) · [docs/DETAIL.zh.md](docs/DETAIL.zh.md) (中文)
71
+
72
+ MIT.
package/README.zh.md CHANGED
@@ -1,70 +1,72 @@
1
- # dsh-prompt-pocket
2
-
3
- **给 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 用的提示词口袋:一个快捷键存下你正在打的字,一次点击把它插回光标处。** 它就是角落里一枚 24px 的圆点,界面不会因此长出一条侧栏、一排胶囊,或者一个挤压对话的面板。
4
-
5
- ![提示词口袋展开在会话上方:搜索框、两个抽屉、三条已存提示词,右下角是那颗圆点](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/zh-panel.png)
6
-
7
- 站点:**[dshtoolbox.com/zh/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/)** · English: [dshtoolbox.com/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/) · npm: [dsh-prompt-pocket](https://www.npmjs.com/package/dsh-prompt-pocket)
8
-
9
- ## 为什么做这个
10
-
11
- 提示词库要先让你起标题、打标签、建文件夹、开面板,然后才肯收下一句话。等你填完,那句话已经忘了。这个不填,直接收。
12
-
13
- ## 别处没有的几件事
14
-
15
- - **`Ctrl+Shift+S` 存,不弹窗。** 有选中存选中,没选中存整段草稿。不起标题、不选标签、不问放哪。
16
- - **面板关着也能看见存到哪了。** 圆点旁边出一条两秒的提示,带「改存另一档」和「写成 DSH 提示词」两个按钮。
17
- - **插入走输入框的修订号保护,不是拼字符串。** 你已经插的引用 chip、挂的附件都留在原地,插入是一步撤销,插完焦点回到输入框。
18
- - **两个抽屉按 workspace 分,不按会话分。** 会话会归档、会 fork,绑在会话上的提示词那天就没了家;没有 workspace 的裸会话退成通用,而不是给你一个空标签页。
19
- - **✦ 写的是 DSH 提示词,不是同义改写。** `{{变量}}`、路径、URL、代码块原样保留,没说过的东西不编,套话在被禁之列。失败或空结果绝不覆盖原文;接受新版本时旧文本留在 `prior` 里,一键退回。
20
- - **AI 回复一键存原文。** 从会话日志里只取 text 块,工具调用不会漏进提示词。
21
- - **模型共用同一个口袋。** `prompt_stash` 工具读写同一份文件,且守分档,一个项目的提示词不会出现在另一个项目的回答里。
22
- - **最多 500 条,满了淘汰最久没用的那条;一个 JSON 文件、原子写、没有运行时依赖、不需要账号。** 除了你主动点的那一次模型调用,什么都不出这台机器。
23
-
24
- ![口袋收起时就是输入框角落一枚很淡的圆点](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/zh-pill.png)
25
-
26
- ## 安装
27
-
28
- ```bash
29
- dsh plugin --profile web add dsh-prompt-pocket
30
- ```
31
-
32
- 装完重启一次宿主,让路由、工具和客户端 bundle 注册;然后 `Ctrl+Shift+R` 强刷页面。要从源码装:
33
-
34
- ```bash
35
- git clone https://github.com/FindSomeSkills/dsh-prompt-pocket
36
- cd dsh-prompt-pocket
37
- dsh plugin --profile web add .
38
- ```
39
-
40
- ## 用法
41
-
42
- | 要做什么 | 怎么做 |
43
- | --- | --- |
44
- | 存选中内容或整段草稿 | `Ctrl+Shift+S` |
45
- | 开 / 关面板 | `Ctrl+Shift+P`,或点圆点 |
46
- | 挪圆点 | 按住拖;位置按浏览器记住 |
47
- | 插到光标处 | `Enter`,或直接点那一行 |
48
- | 整段替换 | 选中行后 `Alt+Enter` |
49
- | 上下选 | `↑` `↓`(循环),`Esc` 关 |
50
- | 在两个档之间挪 | 行尾 `⇄` |
51
- | 删除 | 行尾 `×` |
52
- | 写成 DSH 提示词 | 行尾 `✦`,或存完提示里的按钮 |
53
- | 存一条 AI 回复 | 回复动作行的 `⤓` |
54
-
55
- ## 数据在哪
56
-
57
- `$DSH_HOME/dsh-prompt-stash/store.json`,默认 `~/.dsh/dsh-prompt-stash/store.json`。一个文件,所有 profile、所有连到这台机器的浏览器共用;写入走临时文件 + rename,文件坏了会改名成 `.corrupt-<时间戳>.bak`,不会挡住面板。
58
-
59
- ## 运行要求
60
-
61
- DeepSeek Harness `>= 0.2.0-rc.1`,Web profile——口袋渲染在输入框里。Windows、macOS、Linux 跑同一份代码;界面语言跟随 DSH 的设置。桌面客户端没验证过。
62
-
63
- ## 链接
64
-
65
- - 产品页:https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/
66
- - 英文页:https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/
67
- - npm:https://www.npmjs.com/package/dsh-prompt-pocket
68
- - 使用手册:[docs/DETAIL.zh.md](docs/DETAIL.zh.md) · [docs/DETAIL.md](docs/DETAIL.md)
69
-
70
- MIT。
1
+ # dsh-prompt-pocket
2
+
3
+ **给 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 用的提示词口袋:一个快捷键存下你正在打的字,一次点击把它插回光标处。** 它就是角落里一枚 24px 的圆点,界面不会因此长出一条侧栏、一排胶囊,或者一个挤压对话的面板。
4
+
5
+ ![提示词口袋展开在会话上方:搜索框、两个抽屉、三条已存提示词,右下角是那颗圆点](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/zh-panel.png)
6
+
7
+ 站点:**[dshtoolbox.com/zh/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/)** · English: [dshtoolbox.com/plugins/dsh-prompt-pocket](https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/) · npm: [dsh-prompt-pocket](https://www.npmjs.com/package/dsh-prompt-pocket)
8
+
9
+ ## 为什么做这个
10
+
11
+ 提示词库要先让你起标题、打标签、建文件夹、开面板,然后才肯收下一句话。等你填完,那句话已经忘了。这个不填,直接收。
12
+
13
+ ## 别处没有的几件事
14
+
15
+ - **`Ctrl+Shift+S` 存,不弹窗。** 有选中存选中,没选中存整段草稿。不起标题、不选标签、不问放哪。
16
+ - **面板关着也能看见存到哪了。** 圆点旁边出一条两秒的提示,带「改存另一档」和「写成 DSH 提示词」两个按钮。
17
+ - **插入走输入框的修订号保护,不是拼字符串。** 你已经插的引用 chip、挂的附件都留在原地,插入是一步撤销,插完焦点回到输入框。
18
+ - **两个抽屉按 workspace 分,不按会话分。** 会话会归档、会 fork,绑在会话上的提示词那天就没了家;没有 workspace 的裸会话退成通用,而不是给你一个空标签页。
19
+ - **✦ 写的是 DSH 提示词,不是同义改写。** `{{变量}}`、路径、URL、代码块原样保留,没说过的东西不编,套话在被禁之列。失败或空结果绝不覆盖原文;接受新版本时旧文本留在 `prior` 里,一键退回。
20
+ - **AI 回复一键存原文。** 从会话日志里只取 text 块,工具调用不会漏进提示词。
21
+ - **模型共用同一个口袋。** `prompt_stash` 工具读写同一份文件,且守分档,一个项目的提示词不会出现在另一个项目的回答里。
22
+ - **用你自己的私有 git 仓库同步。** 每次改动自动提交推送,启动时合并远端;一条提示词一个文件,所以合并会让两边都留下,而不是把一份文档写坏。**公开仓库会被直接拒绝**——开启前插件会问一次 GitHub,这个仓库是不是公开的。
23
+ - **导出与导入就是一个 JSON 文件。** 给没有 git 的机器用,或者在信任同步之前先做一次备份。
24
+ - **最多 500 条,满了淘汰最久没用的那条;一个 JSON 文件、原子写、没有运行时依赖、不需要账号。** 除了你主动点的那一次模型调用,什么都不出这台机器。
25
+
26
+ ![口袋收起时就是输入框角落一枚很淡的圆点](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/zh-pill.png)
27
+
28
+ ## 安装
29
+
30
+ ```bash
31
+ dsh plugin --profile web add dsh-prompt-pocket
32
+ ```
33
+
34
+ 装完重启一次宿主,让路由、工具和客户端 bundle 注册;然后 `Ctrl+Shift+R` 强刷页面。要从源码装:
35
+
36
+ ```bash
37
+ git clone https://github.com/FindSomeSkills/dsh-prompt-pocket
38
+ cd dsh-prompt-pocket
39
+ dsh plugin --profile web add .
40
+ ```
41
+
42
+ ## 用法
43
+
44
+ | 要做什么 | 怎么做 |
45
+ | --- | --- |
46
+ | 存选中内容或整段草稿 | `Ctrl+Shift+S` |
47
+ | 开 / 关面板 | `Ctrl+Shift+P`,或点圆点 |
48
+ | 挪圆点 | 按住拖;位置按浏览器记住 |
49
+ | 插到光标处 | `Enter`,或直接点那一行 |
50
+ | 整段替换 | 选中行后 `Alt+Enter` |
51
+ | 上下选 | `↑` `↓`(循环),`Esc` 关 |
52
+ | 在两个档之间挪 | 行尾 `⇄` |
53
+ | 删除 | 行尾 `×` |
54
+ | 写成 DSH 提示词 | 行尾 `✦`,或存完提示里的按钮 |
55
+ | 存一条 AI 回复 | 回复动作行的 `⤓` |
56
+
57
+ ## 数据在哪
58
+
59
+ `$DSH_HOME/dsh-prompt-stash/store.json`,默认 `~/.dsh/dsh-prompt-stash/store.json`。一个文件,所有 profile、所有连到这台机器的浏览器共用;写入走临时文件 + rename,文件坏了会改名成 `.corrupt-<时间戳>.bak`,不会挡住面板。
60
+
61
+ ## 运行要求
62
+
63
+ DeepSeek Harness `>= 0.2.0-rc.1`,Web profile——口袋渲染在输入框里。Windows、macOS、Linux 跑同一份代码;界面语言跟随 DSH 的设置。桌面客户端没验证过。
64
+
65
+ ## 链接
66
+
67
+ - 产品页:https://www.dshtoolbox.com/zh/plugins/dsh-prompt-pocket/
68
+ - 英文页:https://www.dshtoolbox.com/plugins/dsh-prompt-pocket/
69
+ - npm:https://www.npmjs.com/package/dsh-prompt-pocket
70
+ - 使用手册:[docs/DETAIL.zh.md](docs/DETAIL.zh.md) · [docs/DETAIL.md](docs/DETAIL.md)
71
+
72
+ MIT。
package/client.js CHANGED
@@ -42,6 +42,16 @@ window.__ModuleLoader__.load({
42
42
  polishNoModel: '没有可用的模型,去设置里选一个',
43
43
  polishSame: '原文已经是完整可执行的提示词,没有改',
44
44
  countTotal: '共 {n} 条',
45
+ exportAll: '导出',
46
+ importAll: '导入',
47
+ importDone: '已合并:新增 {a},更新 {u}',
48
+ importFail: '导入失败,文件格式不对',
49
+ syncOff: '同步未开启',
50
+ syncOn: '同步',
51
+ syncBusy: '同步中…',
52
+ syncFail: '同步失败',
53
+ syncHint: '私有仓库地址(留空关闭同步)',
54
+ syncDone: '同步完成',
45
55
  polishOriginal: '原文',
46
56
  polishResult: 'DSH 提示词',
47
57
  accept: '用这版',
@@ -80,6 +90,16 @@ window.__ModuleLoader__.load({
80
90
  polishNoModel: 'No model is available; pick one in settings',
81
91
  polishSame: 'The input is already an executable prompt; nothing changed',
82
92
  countTotal: '{n} in total',
93
+ exportAll: 'Export',
94
+ importAll: 'Import',
95
+ importDone: 'Merged: {a} new, {u} updated',
96
+ importFail: 'Import failed: not a pocket file',
97
+ syncOff: 'Sync off',
98
+ syncOn: 'Sync',
99
+ syncBusy: 'Syncing…',
100
+ syncFail: 'Sync failed',
101
+ syncHint: 'Private repo URL (leave empty to turn sync off)',
102
+ syncDone: 'Synced',
83
103
  polishOriginal: 'Original',
84
104
  polishResult: 'DSH prompt',
85
105
  accept: 'Use this',
@@ -204,6 +224,9 @@ window.__ModuleLoader__.load({
204
224
  const [active, setActive] = useState(0);
205
225
  const searchRef = useRef(null);
206
226
  const panelRef = useRef(null);
227
+ const fileRef = useRef(null);
228
+ const [sync, setSync] = useState(null);
229
+ const [syncing, setSyncing] = useState(false);
207
230
  const [lastId, setLastId] = useState(null);
208
231
  const spanRef = useRef(null);
209
232
  const dragRef = useRef(null);
@@ -218,6 +241,8 @@ window.__ModuleLoader__.load({
218
241
  const load = useCallback(async () => {
219
242
  const r = await api('/state' + (workspaceId ? '?workspace=' + encodeURIComponent(workspaceId) : ''));
220
243
  if (r.ok && r.json) setData(r.json);
244
+ const s = await api('/sync');
245
+ if (s.ok && s.json) setSync(s.json);
221
246
  }, [workspaceId]);
222
247
 
223
248
  useEffect(() => {
@@ -325,6 +350,69 @@ window.__ModuleLoader__.load({
325
350
  [workspaceId]
326
351
  );
327
352
 
353
+ const doExport = useCallback(async () => {
354
+ const r = await fetch('/dsh-prompt-stash/export');
355
+ if (!r.ok) return;
356
+ const blob = await r.blob();
357
+ const a = document.createElement('a');
358
+ a.href = URL.createObjectURL(blob);
359
+ a.download = `dsh-prompt-pocket-${new Date().toISOString().slice(0, 10)}.json`;
360
+ a.click();
361
+ setTimeout(() => URL.revokeObjectURL(a.href), 2000);
362
+ }, []);
363
+
364
+ const doImport = useCallback(
365
+ async (file) => {
366
+ try {
367
+ const parsed = JSON.parse(await file.text());
368
+ const entries = Array.isArray(parsed) ? parsed : parsed.entries;
369
+ if (!Array.isArray(entries)) throw new Error('entries');
370
+ const r = await fetch('/dsh-prompt-stash/import', {
371
+ method: 'POST',
372
+ headers: { 'content-type': 'application/json' },
373
+ body: JSON.stringify({ entries, workspaceId }),
374
+ });
375
+ const json = await r.json();
376
+ if (!r.ok) throw new Error(json && json.error);
377
+ if (json.entries) setData(json);
378
+ setFlash({
379
+ text: t('importDone').replace('{a}', String(json.merge ? json.merge.added : 0)).replace('{u}', String(json.merge ? json.merge.updated : 0)),
380
+ until: Date.now() + 6000,
381
+ });
382
+ } catch {
383
+ setFlash({ text: t('importFail'), until: Date.now() + 5000 });
384
+ }
385
+ },
386
+ [workspaceId, t]
387
+ );
388
+
389
+ const runSync = useCallback(async (payload) => {
390
+ setSyncing(true);
391
+ try {
392
+ const r = await api(payload ? '/sync' : '/sync/now', payload ? { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) } : { method: 'POST' });
393
+ if (r.ok && r.json) {
394
+ setSync(r.json);
395
+ if (r.json.entries) setData(r.json);
396
+ setFlash({ text: r.json.result && r.json.result.ok ? t('syncDone') : t('syncFail'), until: Date.now() + 5000 });
397
+ } else {
398
+ setFlash({ text: t('syncFail'), until: Date.now() + 5000 });
399
+ }
400
+ } finally {
401
+ setSyncing(false);
402
+ }
403
+ }, [t]);
404
+
405
+ const onSyncClick = useCallback(() => {
406
+ if (syncing) return;
407
+ if (sync && sync.enabled) {
408
+ runSync(null);
409
+ return;
410
+ }
411
+ const remote = window.prompt(t('syncHint'), (sync && sync.remote) || '');
412
+ if (remote === null) return;
413
+ runSync({ enabled: remote.trim().length > 0, remote: remote.trim(), branch: (sync && sync.branch) || 'main' });
414
+ }, [sync, syncing, runSync, t]);
415
+
328
416
  const remove = useCallback(
329
417
  async (id) => {
330
418
  const r = await api('/mutate', {
@@ -836,6 +924,57 @@ window.__ModuleLoader__.load({
836
924
  )
837
925
  )
838
926
  ),
927
+ h(
928
+ 'div',
929
+ { style: { display: 'flex', gap: 12, padding: '2px 10px 6px', fontSize: 11 } },
930
+ h(
931
+ 'button',
932
+ {
933
+ type: 'button',
934
+ onClick: doExport,
935
+ style: { background: 'transparent', border: 'none', padding: 0, color: 'var(--dsw-alias-brand-primary, #4aa3ff)', cursor: 'pointer', font: 'inherit' },
936
+ },
937
+ t('exportAll')
938
+ ),
939
+ h(
940
+ 'button',
941
+ {
942
+ type: 'button',
943
+ onClick: () => fileRef.current && fileRef.current.click(),
944
+ style: { background: 'transparent', border: 'none', padding: 0, color: 'var(--dsw-alias-brand-primary, #4aa3ff)', cursor: 'pointer', font: 'inherit' },
945
+ },
946
+ t('importAll')
947
+ ),
948
+ h('input', {
949
+ ref: fileRef,
950
+ type: 'file',
951
+ accept: '.json,application/json',
952
+ style: { display: 'none' },
953
+ onChange: (ev) => {
954
+ const file = ev.target.files && ev.target.files[0];
955
+ if (file) doImport(file);
956
+ ev.target.value = '';
957
+ },
958
+ }),
959
+ h(
960
+ 'button',
961
+ {
962
+ type: 'button',
963
+ onClick: onSyncClick,
964
+ title: sync && sync.lastError ? sync.lastError : '',
965
+ style: {
966
+ background: 'transparent',
967
+ border: 'none',
968
+ padding: 0,
969
+ color: sync && sync.enabled ? 'var(--dsw-alias-brand-primary, #4aa3ff)' : 'var(--dsw-alias-label-secondary, #888)',
970
+ cursor: 'pointer',
971
+ font: 'inherit',
972
+ marginLeft: 'auto',
973
+ },
974
+ },
975
+ syncing ? t('syncBusy') : sync && sync.enabled ? `${t('syncOn')}${sync.lastSyncAt ? ' · ' + new Date(sync.lastSyncAt).toLocaleTimeString() : ''}` : t('syncOff')
976
+ )
977
+ ),
839
978
  h(
840
979
  'div',
841
980
  {
package/docs/DETAIL.md CHANGED
@@ -57,4 +57,12 @@ The agent can read and write the same pocket through the `prompt_stash` tool, so
57
57
 
58
58
  ## What it does not do
59
59
 
60
- **No tags, no folders, no import wizard, no recycle bin.** Each of those needs a panel, and a panel needs a decision every time you save. This one is built so there is nothing to decide.
60
+ **No tags, no folders, no import wizard, no recycle bin.** Each of those needs a panel, and a panel needs a decision every time you save. This one is built so there is nothing to decide.## Moving prompts between machines
61
+
62
+ Two ways, one file format.
63
+
64
+ **Through a private git repository.** Set the remote in the panel; the host initialises the repository inside `$DSH_HOME/dsh-prompt-stash`, commits after each change and pushes, then merges the remote branch on launch. Prompts are stored as **one file per entry**, so a merge keeps both sides rather than corrupting a single JSON document. Identity is the repository credential — the plugin never stores a token, and it asks GitHub whether the repository is public before enabling sync, refusing if it is.
65
+
66
+ **By hand.** Export writes one JSON file with every entry; import reads it and merges by id — a newer `updatedAt` replaces the local copy, an older one is skipped, invalid entries are counted and ignored, and neither path deletes a local prompt.
67
+
68
+
package/docs/DETAIL.zh.md CHANGED
@@ -57,4 +57,12 @@
57
57
 
58
58
  ## 它不做什么
59
59
 
60
- **没有标签、没有文件夹、没有导入向导、没有回收站。** 这些每一样都要求一个面板,而面板要求你每次保存都做一次决定。这个工具就是为了让你没有决定可做。
60
+ **没有标签、没有文件夹、没有导入向导、没有回收站。** 这些每一样都要求一个面板,而面板要求你每次保存都做一次决定。这个工具就是为了让你没有决定可做。## 怎么把提示词搬到另一台机器
61
+
62
+ 两条路,同一种文件格式。
63
+
64
+ **走你自己的私有 git 仓库。** 在面板里填远端地址,宿主会在 `$DSH_HOME/dsh-prompt-stash` 里初始化仓库,每次改动后提交并推送,启动时合并远端分支。提示词是**一条一个文件**,所以合并会让两边都留下,而不是把一份 JSON 写坏。身份就是仓库的凭据,插件不存 token;开启前它会问一次 GitHub 这个仓库是不是公开的,公开就拒绝。
65
+
66
+ **手动搬。** 导出把全部条目写成一个 JSON 文件;导入按 id 合并——`updatedAt` 更新的覆盖本地、更旧的跳过、无效条目单独计数忽略,两条路都不会删掉本地已有的提示词。
67
+
68
+
package/index.js CHANGED
@@ -6,11 +6,17 @@
6
6
  import { promises as fs } from 'node:fs';
7
7
  import os from 'node:os';
8
8
  import path from 'node:path';
9
+ import { spawn } from 'node:child_process';
10
+ import { promises as fsp } from 'node:fs';
9
11
 
10
12
  const CAP = 500;
11
13
  const HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
12
14
  const DIR = path.join(HOME, 'dsh-prompt-stash');
13
- const FILE = path.join(DIR, 'store.json');
15
+ const STORE = path.join(DIR, 'store.d');
16
+ const LEGACY = path.join(DIR, 'store.json');
17
+ const SYNC = path.join(DIR, 'sync.json');
18
+ const TOMB_DAYS = 90;
19
+ const FILE = LEGACY;
14
20
 
15
21
  function newId() {
16
22
  return 'p' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
@@ -21,48 +27,119 @@ function clipTitle(text) {
21
27
  return first.replace(/\s+/g, ' ').trim().slice(0, 40);
22
28
  }
23
29
 
24
- const empty = () => ({ version: 1, entries: [] });
30
+ const empty = () => ({ version: 1, entries: [], tombstones: [] });
31
+
32
+ function normalizeEntry(raw, fallbackId) {
33
+ const text = String(raw.text).slice(0, 20000);
34
+ const createdAt = typeof raw.createdAt === 'number' ? raw.createdAt : Date.now();
35
+ const usedAt = typeof raw.usedAt === 'number' ? raw.usedAt : createdAt;
36
+ const updatedAt = typeof raw.updatedAt === 'number' ? raw.updatedAt : usedAt;
37
+ return {
38
+ id: typeof raw.id === 'string' && raw.id ? raw.id : fallbackId || newId(),
39
+ text,
40
+ title: typeof raw.title === 'string' && raw.title ? raw.title.slice(0, 60) : clipTitle(text),
41
+ scope: raw.scope === 'workspace' ? 'workspace' : 'global',
42
+ ...(typeof raw.workspaceId === 'string' && raw.workspaceId ? { workspaceId: raw.workspaceId } : {}),
43
+ source: ['draft', 'selection', 'reply', 'manual'].includes(raw.source) ? raw.source : 'manual',
44
+ createdAt,
45
+ usedAt,
46
+ updatedAt,
47
+ useCount: typeof raw.useCount === 'number' ? raw.useCount : 0,
48
+ ...(typeof raw.prior === 'string' && raw.prior.trim() ? { prior: raw.prior.slice(0, 20000) } : {}),
49
+ };
50
+ }
25
51
 
26
52
  function normalize(raw) {
27
53
  if (!raw || typeof raw !== 'object') return empty();
28
54
  const list = Array.isArray(raw.entries) ? raw.entries : [];
29
55
  const entries = list
30
56
  .filter((e) => e && typeof e.text === 'string' && e.text.trim())
31
- .map((e) => ({
32
- id: typeof e.id === 'string' && e.id ? e.id : newId(),
33
- text: String(e.text).slice(0, 20000),
34
- title: typeof e.title === 'string' && e.title ? e.title.slice(0, 60) : clipTitle(e.text),
35
- scope: e.scope === 'workspace' ? 'workspace' : 'global',
36
- ...(typeof e.workspaceId === 'string' && e.workspaceId ? { workspaceId: e.workspaceId } : {}),
37
- source: ['draft', 'selection', 'reply', 'manual'].includes(e.source) ? e.source : 'manual',
38
- createdAt: typeof e.createdAt === 'number' ? e.createdAt : Date.now(),
39
- usedAt: typeof e.usedAt === 'number' ? e.usedAt : typeof e.createdAt === 'number' ? e.createdAt : Date.now(),
40
- useCount: typeof e.useCount === 'number' ? e.useCount : 0,
41
- ...(typeof e.prior === 'string' && e.prior.trim() ? { prior: e.prior.slice(0, 20000) } : {}),
42
- }))
57
+ .map((e) => normalizeEntry(e))
43
58
  .slice(-CAP);
44
- return { version: 1, entries };
59
+ return { version: 1, entries, tombstones: [] };
45
60
  }
46
61
 
47
- async function readStore() {
48
- try {
49
- return normalize(JSON.parse(await fs.readFile(FILE, 'utf8')));
50
- } catch (e) {
51
- if (e && e.code === 'ENOENT') return empty();
62
+ function normalizeTombstone(raw) {
63
+ if (!raw || typeof raw.id !== 'string' || !raw.id) return null;
64
+ if (typeof raw.deletedAt !== 'number') return null;
65
+ return { id: raw.id, deletedAt: raw.deletedAt };
66
+ }
67
+
68
+ // One file per prompt: a git merge can then keep both sides instead of fighting
69
+ // over one JSON document. Tombstones live in the same directory and win when
70
+ // they are newer than the entry they delete.
71
+ async function readEntryFiles() {
72
+ const entries = [];
73
+ const tombstones = [];
74
+ const names = (await fs.readdir(STORE)).filter((n) => n.endsWith('.json'));
75
+ for (const name of names) {
76
+ let raw;
52
77
  try {
53
- await fs.rename(FILE, FILE + '.corrupt-' + Date.now() + '.bak');
78
+ raw = JSON.parse(await fs.readFile(path.join(STORE, name), 'utf8'));
54
79
  } catch {
55
- /* nothing else to do */
80
+ await fs.rename(path.join(STORE, name), path.join(STORE, `${name}.corrupt-${Date.now()}.bak`)).catch(() => {});
81
+ continue;
56
82
  }
57
- return empty();
83
+ if (typeof raw.deletedAt === 'number') {
84
+ const tomb = normalizeTombstone(raw);
85
+ if (tomb) tombstones.push(tomb);
86
+ continue;
87
+ }
88
+ if (typeof raw.text === 'string' && raw.text.trim()) entries.push(normalizeEntry(raw, name.slice(0, -5)));
58
89
  }
90
+ return { entries, tombstones };
91
+ }
92
+
93
+ async function migrateLegacy() {
94
+ try {
95
+ const raw = JSON.parse(await fs.readFile(LEGACY, 'utf8'));
96
+ const legacy = normalize(raw);
97
+ if (!legacy.entries.length) return 0;
98
+ await writeStore(legacy);
99
+ await fs.rename(LEGACY, `${LEGACY}.migrated-${Date.now()}`);
100
+ return legacy.entries.length;
101
+ } catch {
102
+ return 0;
103
+ }
104
+ }
105
+
106
+ async function readStore() {
107
+ await fs.mkdir(STORE, { recursive: true });
108
+ const names = (await fs.readdir(STORE)).filter((n) => n.endsWith('.json'));
109
+ if (!names.length) await migrateLegacy();
110
+ const { entries, tombstones } = await readEntryFiles();
111
+ const cutoff = Date.now() - TOMB_DAYS * 24 * 60 * 60 * 1000;
112
+ return { version: 1, entries, tombstones: tombstones.filter((t) => t.deletedAt >= cutoff) };
113
+ }
114
+
115
+ async function writeFileAtomic(file, body) {
116
+ const tmp = `${file}.${process.pid}.tmp`;
117
+ await fs.writeFile(tmp, body, 'utf8');
118
+ await fs.rename(tmp, file);
119
+ }
120
+
121
+ async function writeEntryFile(entry) {
122
+ await writeFileAtomic(path.join(STORE, `${entry.id}.json`), JSON.stringify(entry));
123
+ }
124
+
125
+ async function writeTombstoneFile(tomb) {
126
+ await writeFileAtomic(path.join(STORE, `${tomb.id}.json`), JSON.stringify(tomb));
59
127
  }
60
128
 
61
129
  async function writeStore(store) {
62
- await fs.mkdir(DIR, { recursive: true });
63
- const tmp = FILE + '.' + process.pid + '.tmp';
64
- await fs.writeFile(tmp, JSON.stringify(store, null, 2), 'utf8');
65
- await fs.rename(tmp, FILE);
130
+ await fs.mkdir(STORE, { recursive: true });
131
+ const entries = store.entries || [];
132
+ const tombstones = store.tombstones || [];
133
+ const keep = new Set(entries.map((e) => e.id));
134
+ const buried = new Set(tombstones.map((t) => t.id));
135
+ for (const entry of entries) await writeEntryFile(entry);
136
+ for (const tomb of tombstones) await writeTombstoneFile(tomb);
137
+ for (const name of await fs.readdir(STORE)) {
138
+ if (!name.endsWith('.json')) continue;
139
+ const id = name.slice(0, -5);
140
+ if (keep.has(id) || buried.has(id)) continue;
141
+ await fs.unlink(path.join(STORE, name)).catch(() => {});
142
+ }
66
143
  }
67
144
 
68
145
  // Least-recently-used first: the entry evicted is the one untouched the longest.
@@ -118,7 +195,12 @@ async function mutate(body) {
118
195
  };
119
196
  entries.push(entry);
120
197
  const next = evict(entries);
121
- await writeStore({ version: 1, entries: next });
198
+ await writeEntryFile(entry);
199
+ for (const dropped of entries) {
200
+ if (!next.some((e) => e.id === dropped.id)) {
201
+ await fs.unlink(path.join(STORE, `${dropped.id}.json`)).catch(() => {});
202
+ }
203
+ }
122
204
  return { ok: true, entry };
123
205
  }
124
206
 
@@ -133,7 +215,7 @@ async function mutate(body) {
133
215
  title: (typeof body.title === 'string' && body.title.trim()) || clipTitle(text),
134
216
  ...(typeof body.prior === 'string' && body.prior.trim() ? { prior: body.prior.slice(0, 20000) } : {}),
135
217
  };
136
- await writeStore({ version: 1, entries });
218
+ await writeEntryFile(entries[i]);
137
219
  return { ok: true, entry: entries[i] };
138
220
  }
139
221
 
@@ -141,7 +223,8 @@ async function mutate(body) {
141
223
  const i = at(body.id);
142
224
  if (i < 0) return { ok: false, code: 'not-found' };
143
225
  entries.splice(i, 1);
144
- await writeStore({ version: 1, entries });
226
+ await writeTombstoneFile({ id: body.id, deletedAt: Date.now() });
227
+ await fs.unlink(path.join(STORE, `${body.id}.json`)).catch(() => {});
145
228
  return { ok: true };
146
229
  }
147
230
 
@@ -155,22 +238,237 @@ async function mutate(body) {
155
238
  ...entries[i],
156
239
  scope,
157
240
  ...(scope === 'workspace' ? { workspaceId } : {}),
241
+ updatedAt: Date.now(),
158
242
  };
159
- await writeStore({ version: 1, entries });
243
+ await writeEntryFile(entries[i]);
160
244
  return { ok: true, entry: entries[i] };
161
245
  }
162
246
 
163
247
  if (op === 'touch') {
164
248
  const i = at(body.id);
165
249
  if (i < 0) return { ok: false, code: 'not-found' };
166
- entries[i] = { ...entries[i], usedAt: Date.now(), useCount: (entries[i].useCount || 0) + 1 };
167
- await writeStore({ version: 1, entries });
250
+ entries[i] = { ...entries[i], usedAt: Date.now(), updatedAt: Date.now(), useCount: (entries[i].useCount || 0) + 1 };
251
+ await writeEntryFile(entries[i]);
168
252
  return { ok: true };
169
253
  }
170
254
 
171
255
  return { ok: false, code: 'unknown-op' };
172
256
  }
173
257
 
258
+ // ---------- git sync ----------
259
+ // The transport is a private git repository the user owns. Identity is the
260
+ // repository credential; the plugin never stores a token. Prompts are one file
261
+ // each, so a merge keeps both sides instead of fighting over one document.
262
+
263
+ function git(args) {
264
+ return new Promise((resolve) => {
265
+ const child = spawn('git', ['-C', DIR, ...args], { windowsHide: true });
266
+ let out = '';
267
+ let err = '';
268
+ const timer = setTimeout(() => child.kill(), 20000);
269
+ child.stdout.on('data', (c) => (out += c));
270
+ child.stderr.on('data', (c) => (err += c));
271
+ child.on('error', () => {
272
+ clearTimeout(timer);
273
+ resolve({ ok: false, code: -1, stdout: '', stderr: 'git not available' });
274
+ });
275
+ child.on('close', (code) => {
276
+ clearTimeout(timer);
277
+ resolve({ ok: code === 0, code, stdout: out.trim(), stderr: err.trim() });
278
+ });
279
+ });
280
+ }
281
+
282
+ async function readSyncConfig() {
283
+ try {
284
+ const raw = JSON.parse(await fsp.readFile(SYNC, 'utf8'));
285
+ return {
286
+ enabled: raw.enabled === true,
287
+ remote: typeof raw.remote === 'string' ? raw.remote : '',
288
+ branch: typeof raw.branch === 'string' && raw.branch ? raw.branch : 'main',
289
+ syncId: typeof raw.syncId === 'string' ? raw.syncId : '',
290
+ lastSyncAt: typeof raw.lastSyncAt === 'number' ? raw.lastSyncAt : 0,
291
+ lastError: typeof raw.lastError === 'string' ? raw.lastError : '',
292
+ };
293
+ } catch {
294
+ return { enabled: false, remote: '', branch: 'main', syncId: '', lastSyncAt: 0, lastError: '' };
295
+ }
296
+ }
297
+
298
+ async function writeSyncConfig(cfg) {
299
+ await fs.mkdir(DIR, { recursive: true });
300
+ await writeFileAtomic(SYNC, JSON.stringify(cfg, null, 2));
301
+ }
302
+
303
+ async function ensureRepo(cfg) {
304
+ await fs.mkdir(DIR, { recursive: true });
305
+ if (!(await fsp.stat(path.join(DIR, '.git')).catch(() => null))) await git(['init']);
306
+ const remote = await git(['remote', 'get-url', 'origin']);
307
+ if (!remote.ok) await git(['remote', 'add', 'origin', cfg.remote]);
308
+ else if (remote.stdout !== cfg.remote) await git(['remote', 'set-url', 'origin', cfg.remote]);
309
+ const name = await git(['config', 'user.name']);
310
+ if (!name.ok || !name.stdout) await git(['config', 'user.name', 'dsh-prompt-pocket']);
311
+ const mail = await git(['config', 'user.email']);
312
+ if (!mail.ok || !mail.stdout) await git(['config', 'user.email', 'pocket@localhost']);
313
+ const ignore = path.join(DIR, '.gitignore');
314
+ if (!(await fsp.stat(ignore).catch(() => null))) await fsp.writeFile(ignore, '*.tmp\n', 'utf8');
315
+ }
316
+
317
+ async function readRemoteEntries(cfg) {
318
+ const fetched = await git(['fetch', 'origin', cfg.branch]);
319
+ if (!fetched.ok) return null; // nothing on the remote yet
320
+ const tmp = path.join(os.tmpdir(), `pocket-sync-${process.pid}-${Date.now()}`);
321
+ const added = await git(['worktree', 'add', '--force', '--detach', tmp, `origin/${cfg.branch}`]);
322
+ if (!added.ok) return null;
323
+ try {
324
+ const dir = path.join(tmp, 'store.d');
325
+ const entries = [];
326
+ const tombstones = [];
327
+ for (const name of (await fsp.readdir(dir).catch(() => [])).filter((n) => n.endsWith('.json'))) {
328
+ try {
329
+ const raw = JSON.parse(await fsp.readFile(path.join(dir, name), 'utf8'));
330
+ if (typeof raw.deletedAt === 'number') tombstones.push(normalizeTombstone(raw));
331
+ else if (raw && typeof raw.text === 'string' && raw.text.trim()) entries.push(normalizeEntry(raw, name.slice(0, -5)));
332
+ } catch {
333
+ /* a bad remote file is skipped, not merged */
334
+ }
335
+ }
336
+ return { entries: entries.filter(Boolean), tombstones: tombstones.filter(Boolean) };
337
+ } finally {
338
+ await git(['worktree', 'remove', '--force', tmp]);
339
+ }
340
+ }
341
+
342
+ function mergeStores(local, remote) {
343
+ const byId = new Map(local.entries.map((e) => [e.id, e]));
344
+ const tombs = new Map();
345
+ for (const tomb of [...(local.tombstones || []), ...(remote.tombstones || [])]) {
346
+ const current = tombs.get(tomb.id);
347
+ if (!current || tomb.deletedAt > current.deletedAt) tombs.set(tomb.id, tomb);
348
+ }
349
+ let added = 0;
350
+ let updated = 0;
351
+ let skipped = 0;
352
+ let deleted = 0;
353
+ for (const incoming of remote.entries) {
354
+ const tomb = tombs.get(incoming.id);
355
+ if (tomb && tomb.deletedAt >= incoming.updatedAt) continue;
356
+ const current = byId.get(incoming.id);
357
+ if (!current) {
358
+ byId.set(incoming.id, incoming);
359
+ added += 1;
360
+ } else if (incoming.updatedAt > current.updatedAt) {
361
+ byId.set(incoming.id, incoming);
362
+ updated += 1;
363
+ } else {
364
+ skipped += 1;
365
+ }
366
+ }
367
+ for (const [id, tomb] of tombs) {
368
+ const current = byId.get(id);
369
+ if (current && tomb.deletedAt > current.updatedAt) {
370
+ byId.delete(id);
371
+ deleted += 1;
372
+ }
373
+ }
374
+ return { entries: [...byId.values()], tombstones: [...tombs.values()].filter(Boolean), added, updated, skipped, deleted };
375
+ }
376
+
377
+ // A public repository would publish every prompt. GitHub answers 404 to an
378
+ // unauthenticated API call for a private repo, 200 for a public one.
379
+ async function publicGitHubRepo(remote) {
380
+ const m = /github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(remote || '');
381
+ if (!m) return false;
382
+ try {
383
+ const res = await fetch(`https://api.github.com/repos/${m[1]}/${m[2]}`, { headers: { 'user-agent': 'dsh-prompt-pocket' } });
384
+ return res.status === 200;
385
+ } catch {
386
+ return false;
387
+ }
388
+ }
389
+
390
+ async function syncNow(cfg) {
391
+ if (!cfg.enabled || !cfg.remote) return { ok: false, code: 'disabled' };
392
+ const hasGit = await git(['--version']);
393
+ if (!hasGit.ok) {
394
+ await writeSyncConfig({ ...cfg, lastError: 'git is not installed' });
395
+ return { ok: false, code: 'no-git' };
396
+ }
397
+ await ensureRepo(cfg);
398
+ const local = await readStore();
399
+ const remote = await readRemoteEntries(cfg);
400
+ const merged = remote ? mergeStores(local, remote) : { entries: local.entries, tombstones: local.tombstones, added: 0, updated: 0, skipped: 0, deleted: 0 };
401
+ await writeStore({ version: 1, entries: merged.entries, tombstones: merged.tombstones });
402
+ await git(['add', '-A']);
403
+ const status = await git(['status', '--porcelain']);
404
+ if (status.ok && status.stdout.trim()) await git(['commit', '-m', `pocket sync ${new Date().toISOString()}`]);
405
+ let pushed = await git(['push', 'origin', `HEAD:${cfg.branch}`]);
406
+ if (!pushed.ok) {
407
+ await git(['pull', '--rebase', 'origin', cfg.branch]);
408
+ pushed = await git(['push', 'origin', `HEAD:${cfg.branch}`]);
409
+ }
410
+ const next = {
411
+ ...cfg,
412
+ lastSyncAt: Date.now(),
413
+ lastError: pushed.ok ? '' : (pushed.stderr || 'push failed').slice(0, 300),
414
+ };
415
+ await writeSyncConfig(next);
416
+ return { ok: pushed.ok, code: pushed.ok ? 'ok' : 'push-failed', merge: merged };
417
+ }
418
+
419
+ let syncTimer = null;
420
+ function scheduleSync() {
421
+ readSyncConfig().then((cfg) => {
422
+ if (!cfg.enabled || !cfg.remote) return;
423
+ clearTimeout(syncTimer);
424
+ syncTimer = setTimeout(() => {
425
+ syncNow(cfg).catch(() => {});
426
+ }, 3000);
427
+ if (syncTimer.unref) syncTimer.unref();
428
+ });
429
+ }
430
+
431
+ // Merge an exported file into the local store. Same id + newer usedAt wins;
432
+ // everything else is kept, so an import never deletes a local prompt.
433
+ async function importEntries(rawEntries) {
434
+ const store = await readStore();
435
+ const byId = new Map(store.entries.map((e) => [e.id, e]));
436
+ const tombById = new Map((store.tombstones || []).map((t) => [t.id, t]));
437
+ const incoming = normalize({ entries: Array.isArray(rawEntries) ? rawEntries : [] }).entries;
438
+ let added = 0;
439
+ let updated = 0;
440
+ let skipped = 0;
441
+ for (const entry of incoming) {
442
+ const tomb = tombById.get(entry.id);
443
+ if (tomb && tomb.deletedAt >= (entry.updatedAt || entry.usedAt || 0)) {
444
+ skipped += 1;
445
+ continue;
446
+ }
447
+ const current = byId.get(entry.id);
448
+ if (!current) {
449
+ byId.set(entry.id, entry);
450
+ added += 1;
451
+ } else if ((entry.usedAt || 0) > (current.usedAt || 0)) {
452
+ byId.set(entry.id, entry);
453
+ updated += 1;
454
+ } else {
455
+ skipped += 1;
456
+ }
457
+ }
458
+ const entries = evict([...byId.values()]);
459
+ await writeStore({ version: 1, entries, tombstones: [...tombById.values()] });
460
+ return {
461
+ ok: true,
462
+ merge: {
463
+ received: Array.isArray(rawEntries) ? rawEntries.length : 0,
464
+ added,
465
+ updated,
466
+ skipped,
467
+ invalid: (Array.isArray(rawEntries) ? rawEntries.length : 0) - incoming.length,
468
+ },
469
+ };
470
+ }
471
+
174
472
  // The client action row only receives a message id; the text lives in the session log.
175
473
  function replyText(sessions, sessionId, messageId) {
176
474
  if (!sessions || !sessionId || !messageId) return null;
@@ -314,6 +612,60 @@ export function apply(ctx) {
314
612
  return sendNode(res, 200, await snapshot(url.searchParams.get('workspace') || undefined));
315
613
  }
316
614
 
615
+ if (url.pathname === '/dsh-prompt-stash/sync') {
616
+ const cfg = await readSyncConfig();
617
+ if (req.method === 'GET') {
618
+ const hasGit = await git(['--version']);
619
+ return sendNode(res, 200, { ...cfg, gitAvailable: hasGit.ok });
620
+ }
621
+ if (req.method !== 'POST') return sendNode(res, 405, { error: 'method not allowed' });
622
+ let body;
623
+ try {
624
+ body = JSON.parse(await readBody(req));
625
+ } catch {
626
+ return sendNode(res, 400, { error: 'malformed body' });
627
+ }
628
+ const next = {
629
+ ...cfg,
630
+ enabled: body.enabled === true,
631
+ remote: typeof body.remote === 'string' ? body.remote.trim() : cfg.remote,
632
+ branch: typeof body.branch === 'string' && body.branch.trim() ? body.branch.trim() : cfg.branch,
633
+ syncId: cfg.syncId || newId(),
634
+ };
635
+ if (next.enabled && await publicGitHubRepo(next.remote)) {
636
+ return sendNode(res, 400, { error: 'public-repo', code: 'public-repo' });
637
+ }
638
+ await writeSyncConfig(next);
639
+ const result = next.enabled && next.remote ? await syncNow(next) : { ok: true, code: 'saved' };
640
+ return sendNode(res, 200, { ...await readSyncConfig(), result, ...(await snapshot()) });
641
+ }
642
+
643
+ if (url.pathname === '/dsh-prompt-stash/sync/now') {
644
+ if (req.method !== 'POST') return sendNode(res, 405, { error: 'method not allowed' });
645
+ const cfg = await readSyncConfig();
646
+ const result = await syncNow(cfg);
647
+ return sendNode(res, result.ok ? 200 : 400, { ...await readSyncConfig(), result, ...(await snapshot()) });
648
+ }
649
+
650
+ if (url.pathname === '/dsh-prompt-stash/export') {
651
+ if (req.method !== 'GET') return sendNode(res, 405, { error: 'method not allowed' });
652
+ const store = await readStore();
653
+ return sendNode(res, 200, { version: 1, exportedAt: new Date().toISOString(), entries: store.entries });
654
+ }
655
+
656
+ if (url.pathname === '/dsh-prompt-stash/import') {
657
+ if (req.method !== 'POST') return sendNode(res, 405, { error: 'method not allowed' });
658
+ let body;
659
+ try {
660
+ body = JSON.parse(await readBody(req));
661
+ } catch {
662
+ return sendNode(res, 400, { error: 'malformed body' });
663
+ }
664
+ if (!Array.isArray(body && body.entries)) return sendNode(res, 400, { error: 'entries required' });
665
+ const result = await importEntries(body.entries);
666
+ return sendNode(res, 200, { ...result, ...(await snapshot(body.workspaceId)) });
667
+ }
668
+
317
669
  if (url.pathname === '/dsh-prompt-stash/mutate') {
318
670
  if (req.method !== 'POST') return sendNode(res, 405, { error: 'method not allowed' });
319
671
  let body;
@@ -324,6 +676,7 @@ export function apply(ctx) {
324
676
  }
325
677
  const result = await mutate(body);
326
678
  if (!result.ok) return sendNode(res, 400, result);
679
+ scheduleSync();
327
680
  return sendNode(res, 200, { ...result, ...(await snapshot(body.workspaceId)) });
328
681
  }
329
682
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-prompt-pocket",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "A prompt pocket that floats in the corner: save the draft or the selected text with Ctrl+Shift+S, click a saved prompt to drop it back at the caret.",
package/scripts/smoke.mjs CHANGED
@@ -4,6 +4,7 @@ import { promises as fs } from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import assert from 'node:assert/strict';
7
+ import { execFileSync } from 'node:child_process';
7
8
 
8
9
  const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'prompt-stash-'));
9
10
  process.env.DSH_HOME = tmp;
@@ -207,16 +208,19 @@ const pass = (n) => ok.push(n);
207
208
  pass('超过 500 条按最久未用淘汰,新条留下');
208
209
  }
209
210
 
210
- // 13. a corrupt file is renamed and the store starts clean
211
+ // 13. one corrupt entry file is quarantined, the rest of the pocket survives
211
212
  {
212
- const file = path.join(tmp, 'dsh-prompt-stash', 'store.json');
213
- await fs.writeFile(file, '{ this is not json', 'utf8');
213
+ const dir = path.join(tmp, 'dsh-prompt-stash', 'store.d');
214
+ const files = (await fs.readdir(dir)).filter((f) => f.endsWith('.json'));
215
+ assert.ok(files.length > 0, '应当已经有条目文件');
216
+ const before = (await call('/dsh-prompt-stash/state')).json.total;
217
+ await fs.writeFile(path.join(dir, files[0]), '{ this is not json', 'utf8');
214
218
  const r = await call('/dsh-prompt-stash/state');
215
219
  assert.equal(r.status, 200);
216
- assert.deepEqual(r.json.entries, []);
217
- const files = await fs.readdir(path.dirname(file));
218
- assert.ok(files.some((f) => f.includes('.corrupt-')), '坏文件要留底');
219
- pass('坏文件留底后从空库继续');
220
+ const after = await fs.readdir(dir);
221
+ assert.ok(after.some((f) => f.includes('.corrupt-')), '坏文件要留底');
222
+ assert.equal(r.json.total, before - 1, '只损失坏掉的那一条,其余照常');
223
+ pass('单条坏文件留底,其余条目照常读取');
220
224
  }
221
225
 
222
226
  // 14. the tool reads and writes the same file the routes serve
@@ -275,6 +279,76 @@ const pass = (n) => ok.push(n);
275
279
  pass('有模型时把流式结果拼成润色文本');
276
280
  }
277
281
 
282
+ // 18. export returns every entry
283
+ {
284
+ await post('/mutate', { op: 'save', text: 'exported prompt', scope: 'global' });
285
+ const r = await call('/dsh-prompt-stash/export');
286
+ assert.equal(r.status, 200);
287
+ assert.ok(Array.isArray(r.json.entries) && r.json.entries.length >= 1);
288
+ assert.equal(typeof r.json.exportedAt, 'string');
289
+ pass('导出的文件带上全部条目和时间');
290
+ }
291
+
292
+ // 19. import merges by id: one new, one newer version, one invalid
293
+ {
294
+ const before = await call('/dsh-prompt-stash/state');
295
+ const local = before.json.entries[0];
296
+ const r = await post('/dsh-prompt-stash/import', {
297
+ entries: [
298
+ { ...local, text: 'updated by import', usedAt: local.usedAt + 10000 },
299
+ { id: 'imported-1', text: 'a prompt from another machine', scope: 'global', usedAt: Date.now() },
300
+ { text: '' },
301
+ ],
302
+ });
303
+ assert.equal(r.status, 200);
304
+ assert.equal(r.json.merge.added, 1);
305
+ assert.equal(r.json.merge.updated, 1);
306
+ assert.equal(r.json.merge.invalid, 1);
307
+ const after = await call('/dsh-prompt-stash/state');
308
+ assert.ok(after.json.entries.some((e) => e.text === 'updated by import'));
309
+ assert.ok(after.json.entries.some((e) => e.id === 'imported-1'));
310
+ pass('导入按 id 合并:新增、更新、无效各计一次');
311
+ }
312
+
313
+ // 20. import without an entries array is refused
314
+ {
315
+ const r = await post('/dsh-prompt-stash/import', { entries: 'nope' });
316
+ assert.equal(r.status, 400);
317
+ pass('导入缺数组时 400');
318
+ }
319
+
320
+ // 21. git sync: first push creates the branch on the remote
321
+ {
322
+ const remote = path.join(tmp, 'remote.git');
323
+ execFileSync('git', ['init', '--bare', remote], { stdio: 'ignore' });
324
+ const r = await post('/dsh-prompt-stash/sync', { enabled: true, remote, branch: 'main' });
325
+ assert.equal(r.status, 200);
326
+ assert.equal(r.json.result.ok, true, '首次同步应当成功');
327
+ const files = execFileSync('git', ['--git-dir', remote, 'ls-tree', '-r', '--name-only', 'main'], { encoding: 'utf8' });
328
+ assert.ok(files.includes('store.d/'), '远端应当有 store.d');
329
+ assert.ok(files.split('\n').filter((f) => f.startsWith('store.d/')).length >= 1, '远端应当有至少一个条目文件');
330
+ pass('git 同步:首次推送把条目推到远端分支');
331
+ }
332
+
333
+ // 22. git sync: a change made on the remote is merged into the local pocket
334
+ {
335
+ const remote = path.join(tmp, 'remote.git');
336
+ const clone = path.join(tmp, 'clone');
337
+ execFileSync('git', ['clone', '-b', 'main', remote, clone], { stdio: 'ignore' });
338
+ execFileSync('git', ['-C', clone, 'config', 'user.name', 'test'], { stdio: 'ignore' });
339
+ execFileSync('git', ['-C', clone, 'config', 'user.email', 'test@local'], { stdio: 'ignore' });
340
+ const entry = { id: 'from-mac', text: 'a prompt saved on the other machine', title: 'from mac', scope: 'global', source: 'manual', createdAt: Date.now(), usedAt: Date.now(), updatedAt: Date.now(), useCount: 0 };
341
+ await fs.writeFile(path.join(clone, 'store.d', 'from-mac.json'), JSON.stringify(entry), 'utf8');
342
+ execFileSync('git', ['-C', clone, 'add', '-A'], { stdio: 'ignore' });
343
+ execFileSync('git', ['-C', clone, 'commit', '-m', 'from mac'], { stdio: 'ignore' });
344
+ execFileSync('git', ['-C', clone, 'push', 'origin', 'main'], { stdio: 'ignore' });
345
+
346
+ const r = await post('/dsh-prompt-stash/sync/now', {});
347
+ assert.equal(r.status, 200);
348
+ assert.ok(r.json.entries.some((e) => e.id === 'from-mac'), '另一台机器的条目应当合并进来');
349
+ pass('git 同步:远端新增的条目合并到本地');
350
+ }
351
+
278
352
  await fs.rm(tmp, { recursive: true, force: true });
279
353
  if (process.env.DSH_HOME === tmp) delete process.env.DSH_HOME;
280
354