dsh-prompt-pocket 1.0.3 → 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
@@ -19,7 +19,8 @@ Prompt libraries ask for a title, tags, a folder and a panel before they will ke
19
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
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
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
- - **Export and import as one JSON file.** The panel exports every prompt and merges an import by id, keeping the newer copy; nothing local is deleted by an import. It is the first step toward syncing two machines through a private git repository.
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.
23
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.
24
25
 
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)
package/README.zh.md CHANGED
@@ -19,7 +19,8 @@
19
19
  - **✦ 写的是 DSH 提示词,不是同义改写。** `{{变量}}`、路径、URL、代码块原样保留,没说过的东西不编,套话在被禁之列。失败或空结果绝不覆盖原文;接受新版本时旧文本留在 `prior` 里,一键退回。
20
20
  - **AI 回复一键存原文。** 从会话日志里只取 text 块,工具调用不会漏进提示词。
21
21
  - **模型共用同一个口袋。** `prompt_stash` 工具读写同一份文件,且守分档,一个项目的提示词不会出现在另一个项目的回答里。
22
- - **导出与导入就是一个 JSON 文件。** 面板能导出全部提示词;导入按 id 合并、保留较新的一份,且导入不会删掉本地任何东西。这是跨机器同步(私有 git 仓库)的第一步。
22
+ - **用你自己的私有 git 仓库同步。** 每次改动自动提交推送,启动时合并远端;一条提示词一个文件,所以合并会让两边都留下,而不是把一份文档写坏。**公开仓库会被直接拒绝**——开启前插件会问一次 GitHub,这个仓库是不是公开的。
23
+ - **导出与导入就是一个 JSON 文件。** 给没有 git 的机器用,或者在信任同步之前先做一次备份。
23
24
  - **最多 500 条,满了淘汰最久没用的那条;一个 JSON 文件、原子写、没有运行时依赖、不需要账号。** 除了你主动点的那一次模型调用,什么都不出这台机器。
24
25
 
25
26
  ![口袋收起时就是输入框角落一枚很淡的圆点](https://raw.githubusercontent.com/FindSomeSkills/dsh-prompt-pocket/main/docs/images/zh-pill.png)
package/client.js CHANGED
@@ -46,6 +46,12 @@ window.__ModuleLoader__.load({
46
46
  importAll: '导入',
47
47
  importDone: '已合并:新增 {a},更新 {u}',
48
48
  importFail: '导入失败,文件格式不对',
49
+ syncOff: '同步未开启',
50
+ syncOn: '同步',
51
+ syncBusy: '同步中…',
52
+ syncFail: '同步失败',
53
+ syncHint: '私有仓库地址(留空关闭同步)',
54
+ syncDone: '同步完成',
49
55
  polishOriginal: '原文',
50
56
  polishResult: 'DSH 提示词',
51
57
  accept: '用这版',
@@ -88,6 +94,12 @@ window.__ModuleLoader__.load({
88
94
  importAll: 'Import',
89
95
  importDone: 'Merged: {a} new, {u} updated',
90
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',
91
103
  polishOriginal: 'Original',
92
104
  polishResult: 'DSH prompt',
93
105
  accept: 'Use this',
@@ -213,6 +225,8 @@ window.__ModuleLoader__.load({
213
225
  const searchRef = useRef(null);
214
226
  const panelRef = useRef(null);
215
227
  const fileRef = useRef(null);
228
+ const [sync, setSync] = useState(null);
229
+ const [syncing, setSyncing] = useState(false);
216
230
  const [lastId, setLastId] = useState(null);
217
231
  const spanRef = useRef(null);
218
232
  const dragRef = useRef(null);
@@ -227,6 +241,8 @@ window.__ModuleLoader__.load({
227
241
  const load = useCallback(async () => {
228
242
  const r = await api('/state' + (workspaceId ? '?workspace=' + encodeURIComponent(workspaceId) : ''));
229
243
  if (r.ok && r.json) setData(r.json);
244
+ const s = await api('/sync');
245
+ if (s.ok && s.json) setSync(s.json);
230
246
  }, [workspaceId]);
231
247
 
232
248
  useEffect(() => {
@@ -370,6 +386,33 @@ window.__ModuleLoader__.load({
370
386
  [workspaceId, t]
371
387
  );
372
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
+
373
416
  const remove = useCallback(
374
417
  async (id) => {
375
418
  const r = await api('/mutate', {
@@ -912,7 +955,25 @@ window.__ModuleLoader__.load({
912
955
  if (file) doImport(file);
913
956
  ev.target.value = '';
914
957
  },
915
- })
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
+ )
916
977
  ),
917
978
  h(
918
979
  'div',
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)));
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;
58
103
  }
59
104
  }
60
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));
127
+ }
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,32 +238,212 @@ 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
+
174
431
  // Merge an exported file into the local store. Same id + newer usedAt wins;
175
432
  // everything else is kept, so an import never deletes a local prompt.
176
433
  async function importEntries(rawEntries) {
177
434
  const store = await readStore();
178
435
  const byId = new Map(store.entries.map((e) => [e.id, e]));
436
+ const tombById = new Map((store.tombstones || []).map((t) => [t.id, t]));
179
437
  const incoming = normalize({ entries: Array.isArray(rawEntries) ? rawEntries : [] }).entries;
180
438
  let added = 0;
181
439
  let updated = 0;
182
440
  let skipped = 0;
183
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
+ }
184
447
  const current = byId.get(entry.id);
185
448
  if (!current) {
186
449
  byId.set(entry.id, entry);
@@ -193,7 +456,7 @@ async function importEntries(rawEntries) {
193
456
  }
194
457
  }
195
458
  const entries = evict([...byId.values()]);
196
- await writeStore({ version: 1, entries });
459
+ await writeStore({ version: 1, entries, tombstones: [...tombById.values()] });
197
460
  return {
198
461
  ok: true,
199
462
  merge: {
@@ -349,6 +612,41 @@ export function apply(ctx) {
349
612
  return sendNode(res, 200, await snapshot(url.searchParams.get('workspace') || undefined));
350
613
  }
351
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
+
352
650
  if (url.pathname === '/dsh-prompt-stash/export') {
353
651
  if (req.method !== 'GET') return sendNode(res, 405, { error: 'method not allowed' });
354
652
  const store = await readStore();
@@ -378,6 +676,7 @@ export function apply(ctx) {
378
676
  }
379
677
  const result = await mutate(body);
380
678
  if (!result.ok) return sendNode(res, 400, result);
679
+ scheduleSync();
381
680
  return sendNode(res, 200, { ...result, ...(await snapshot(body.workspaceId)) });
382
681
  }
383
682
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-prompt-pocket",
3
- "version": "1.0.3",
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
@@ -313,6 +317,38 @@ const pass = (n) => ok.push(n);
313
317
  pass('导入缺数组时 400');
314
318
  }
315
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
+
316
352
  await fs.rm(tmp, { recursive: true, force: true });
317
353
  if (process.env.DSH_HOME === tmp) delete process.env.DSH_HOME;
318
354