dsh-mobile-plugin 0.5.33 → 0.5.35

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.
Files changed (142) hide show
  1. package/README.md +17 -2
  2. package/dsh-mobile-credentials/lib/credentials.js +49 -2
  3. package/extensions/README.md +25 -21
  4. package/host.js +16 -1
  5. package/lib/git/pr.js +375 -0
  6. package/lib/git/read.js +1 -0
  7. package/lib/host-capabilities.cjs +67 -0
  8. package/lib/http/routing.js +25 -0
  9. package/lib/impl.js +34 -26
  10. package/lib/mirror/history-blob.cjs +184 -0
  11. package/lib/mirror/pusher.cjs +276 -1
  12. package/lib/mobile/approval-facts.js +439 -0
  13. package/lib/mobile/approval-memory.js +199 -0
  14. package/lib/mobile/approvals.js +596 -30
  15. package/lib/mobile/auto-review-log.js +160 -0
  16. package/lib/mobile/auto-review.js +172 -0
  17. package/lib/mobile/credential-upgrade.js +14 -0
  18. package/lib/mobile/device-permissions.js +86 -0
  19. package/lib/mobile/directory-browse.js +23 -8
  20. package/lib/mobile/events.js +9 -1
  21. package/lib/mobile/extension-catalog.js +106 -44
  22. package/lib/mobile/extension-data.js +6 -0
  23. package/lib/mobile/file-ops.js +89 -76
  24. package/lib/mobile/git.js +108 -2
  25. package/lib/mobile/live-steps.js +107 -4
  26. package/lib/mobile/mail.js +621 -0
  27. package/lib/mobile/monitor.js +6 -0
  28. package/lib/mobile/notification-prefs.js +205 -0
  29. package/lib/mobile/pairing.js +15 -2
  30. package/lib/mobile/permissions.js +433 -0
  31. package/lib/mobile/project-write-queue.js +115 -0
  32. package/lib/mobile/project-writes.js +61 -0
  33. package/lib/mobile/push-notify.js +293 -13
  34. package/lib/mobile/questions.js +20 -3
  35. package/lib/mobile/recent-failures.js +48 -0
  36. package/lib/mobile/relay-control.js +5 -0
  37. package/lib/mobile/session-cache.js +50 -0
  38. package/lib/mobile/session-last-turn.js +24 -22
  39. package/lib/mobile/session-new.js +205 -0
  40. package/lib/mobile/session-send.js +0 -1
  41. package/lib/mobile/sessions.js +12 -84
  42. package/lib/mobile/skill-write.js +549 -0
  43. package/lib/mobile/stats-collect.cjs +33 -3
  44. package/lib/mobile/stats-ledger.cjs +39 -2
  45. package/lib/mobile/stream.js +24 -3
  46. package/lib/mobile/supervisor-broadcast.js +58 -11
  47. package/lib/mobile/supervisor-tools.js +1 -1
  48. package/lib/mobile/third-party-extensions.js +158 -0
  49. package/lib/mobile/uploads.js +30 -14
  50. package/lib/mobile/worktree-isolation.js +479 -0
  51. package/lib/mobile/worktree-lifecycle.js +79 -0
  52. package/lib/p2p/wiring.cjs +41 -16
  53. package/lib/panel/index.html +15 -15
  54. package/lib/read-receipt.cjs +89 -5
  55. package/lib/relay/core.js +25 -1
  56. package/lib/relay/lan-proxy.js +6 -1
  57. package/lib/relay/preview.js +21 -1
  58. package/lib/relay/protocol.js +1 -0
  59. package/lib/relay/status.js +6 -0
  60. package/lib/relay/tunnel-forwarder.cjs +178 -0
  61. package/lib/routes/control-plane.js +35 -1
  62. package/lib/routes/mobile-api.js +105 -52
  63. package/lib/shared/via-header.js +15 -2
  64. package/lib/sidecar-facade-worker.cjs +15 -2
  65. package/lib/sidecar-facade.cjs +5 -0
  66. package/lib/tailcat/host-process.cjs +1 -1
  67. package/lib/tailcat/ingress.cjs +2 -2
  68. package/lib/tailcat/wiring.cjs +34 -13
  69. package/package.json +11 -3
  70. package/assets/pets/README.md +0 -9
  71. package/assets/pets/deepy-whale/attention.gif +0 -0
  72. package/assets/pets/deepy-whale/done.gif +0 -0
  73. package/assets/pets/deepy-whale/error.gif +0 -0
  74. package/assets/pets/deepy-whale/idle.gif +0 -0
  75. package/assets/pets/deepy-whale/pack.json +0 -54
  76. package/assets/pets/deepy-whale/sleeping.gif +0 -0
  77. package/assets/pets/deepy-whale/working-3.gif +0 -0
  78. package/assets/pets/deepy-whale/working.gif +0 -0
  79. package/knowledge/apps/alipay.md +0 -30
  80. package/knowledge/apps/android-settings.md +0 -30
  81. package/knowledge/apps/baijiahao.md +0 -30
  82. package/knowledge/apps/bilibili.md +0 -31
  83. package/knowledge/apps/boss-zhipin.md +0 -32
  84. package/knowledge/apps/dedao.md +0 -33
  85. package/knowledge/apps/douyin.md +0 -32
  86. package/knowledge/apps/feishu.md +0 -35
  87. package/knowledge/apps/gmail.md +0 -33
  88. package/knowledge/apps/jike.md +0 -31
  89. package/knowledge/apps/kuaishou.md +0 -34
  90. package/knowledge/apps/linkedin.md +0 -33
  91. package/knowledge/apps/qqmail.md +0 -30
  92. package/knowledge/apps/taobao.md +0 -33
  93. package/knowledge/apps/telegram.md +0 -27
  94. package/knowledge/apps/toutiao.md +0 -32
  95. package/knowledge/apps/uber-eats.md +0 -26
  96. package/knowledge/apps/uber.md +0 -27
  97. package/knowledge/apps/wechat.md +0 -33
  98. package/knowledge/apps/weibo.md +0 -31
  99. package/knowledge/apps/whatsapp.md +0 -27
  100. package/knowledge/apps/x.md +0 -32
  101. package/knowledge/apps/xiaohongshu.md +0 -30
  102. package/knowledge/apps/zhihu.md +0 -31
  103. package/knowledge/sites/bilibili.com/SITE.md +0 -50
  104. package/knowledge/sites/bilibili.com/references/view-fields.md +0 -17
  105. package/knowledge/sites/github.com/SITE.md +0 -51
  106. package/knowledge/sites/github.com/references/repo-fields.md +0 -13
  107. package/knowledge/sites/x.com/SITE.md +0 -47
  108. package/knowledge/sites/xiaohongshu.com/SITE.md +0 -48
  109. package/knowledge/sites/xiaohongshu.com/references/note-fields.md +0 -18
  110. package/knowledge/sites/youtube.com/SITE.md +0 -49
  111. package/knowledge/sites/youtube.com/references/innertube-fields.md +0 -14
  112. package/knowledge/sites/zhihu.com/SITE.md +0 -47
  113. package/knowledge/sites/zhihu.com/references/api-fields.md +0 -21
  114. package/lib/mobile/pet-tools.js +0 -261
  115. package/lib/mobile/pets.js +0 -755
  116. package/lib/mobile/phone/access.js +0 -85
  117. package/lib/mobile/phone/binding.js +0 -247
  118. package/lib/mobile/phone/confirm.js +0 -189
  119. package/lib/mobile/phone/evidence.js +0 -228
  120. package/lib/mobile/phone/gate.js +0 -290
  121. package/lib/mobile/phone/grounding.js +0 -314
  122. package/lib/mobile/phone/guard.js +0 -465
  123. package/lib/mobile/phone/index.js +0 -83
  124. package/lib/mobile/phone/irreversible.js +0 -226
  125. package/lib/mobile/phone/knowledge-tools.js +0 -665
  126. package/lib/mobile/phone/learn.js +0 -329
  127. package/lib/mobile/phone/pacing.js +0 -173
  128. package/lib/mobile/phone/redact.js +0 -237
  129. package/lib/mobile/phone/risk.js +0 -95
  130. package/lib/mobile/phone/route-hint.js +0 -164
  131. package/lib/mobile/phone/routes-memory.js +0 -133
  132. package/lib/mobile/phone/routes.js +0 -279
  133. package/lib/mobile/phone/service.js +0 -500
  134. package/lib/mobile/phone/site-commands.js +0 -271
  135. package/lib/mobile/phone/step-summary.js +0 -201
  136. package/lib/mobile/phone/stop-summary.js +0 -235
  137. package/lib/mobile/phone/tool-groups.js +0 -125
  138. package/lib/mobile/phone/tools.js +0 -2282
  139. package/lib/mobile/phone/untrusted.js +0 -65
  140. package/lib/mobile/phone-knowledge.js +0 -317
  141. package/lib/mobile/wechat-tools.js +0 -257
  142. package/lib/mobile/wechat.js +0 -514
@@ -20,6 +20,7 @@ const fs = require('node:fs');
20
20
  const path = require('node:path');
21
21
 
22
22
  const { sendJson } = require('../shared/http-util');
23
+ const thirdParty = require('./third-party-extensions');
23
24
 
24
25
  /** 审核清单文件名。只有列进来的 slug 才下发。 */
25
26
  const CATALOG_FILE = 'catalog.json';
@@ -128,48 +129,87 @@ function collectFiles(directory, acc) {
128
129
  }
129
130
 
130
131
  /**
131
- * 扫审核清单,把每个登记过、且目录与 manifest 都在的包读成一份 Package。
132
+ * 把一个已经定位好的包目录读成一份 Package;不合规(没 manifest、没入口页、超限)回 null。
133
+ *
134
+ * 两条来源(随本插件发布的 `catalog.json`、第三方插件自己声明的目录)共用这一份判据:
135
+ * 判的是「这个包能不能装到手机上」,与它从哪来无关。`meta` 里那几格文案由来源各给各的。
132
136
  *
133
137
  * 入口页固定是包目录下那层 `index.html`:App 侧 `extensionEntryPath` 找的就是这个名字,
134
- * `manifest.json` 里写 `main` 不生效。所以这里在列包时先确认 `index.html` 真的在文件清单里,
138
+ * `manifest.json` 里写 `main` 不生效。所以这里先确认 `index.html` 真的在文件清单里,
135
139
  * 缺了就把整包跳过 —— 装到手机上再报「需要重新安装」,比根本不出现在清单里难查得多。
140
+ */
141
+ function readPackage(directory, slug, meta = {}) {
142
+ let stats;
143
+ try { stats = fs.statSync(directory); } catch { return null; }
144
+ if (!stats.isDirectory()) return null;
145
+ let manifest;
146
+ try {
147
+ manifest = JSON.parse(fs.readFileSync(path.join(directory, 'manifest.json'), 'utf8'));
148
+ } catch { return null; }
149
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) return null;
150
+ const acc = { root: directory, files: [], bytes: 0 };
151
+ if (!collectFiles(directory, acc) || acc.files.length === 0) return null;
152
+ if (!acc.files.some((file) => file.path === 'index.html')) return null;
153
+ return {
154
+ slug,
155
+ name: textField(manifest.name, slug),
156
+ description: meta.description ?? null,
157
+ author: meta.author ?? null,
158
+ versionName: textField(manifest.versionName, textField(manifest.version, '0.0.0')),
159
+ apiVersion: textField(manifest.apiVersion, textField(manifest.api_version, '1')),
160
+ releaseNotes: meta.releaseNotes ?? null,
161
+ capabilities: capabilitiesOf(manifest.capabilities),
162
+ // 取数声明一起下发:手机上「已装记录」里若缺这一项(早期版本装下的包),App 用当前电脑上
163
+ // 这一份清单把老记录补上,页面才不会把 /api/… 解析成 file://… 而永远转圈。只下发声明,
164
+ // 不在这里做任何放行判断(真正的边界在 extension-data.js 的服务登记表里)。
165
+ hostData: manifest.hostData && typeof manifest.hostData === 'object' && !Array.isArray(manifest.hostData)
166
+ ? manifest.hostData
167
+ : null,
168
+ size: acc.bytes,
169
+ fileCount: acc.files.length,
170
+ files: acc.files,
171
+ };
172
+ }
173
+
174
+ /**
175
+ * 扫审核清单,把每个登记过、且目录与 manifest 都在的包读成一份 Package。
136
176
  *
137
177
  * 纯函数、root 由调用方给:守卫拿假目录跑,线上 handler 给包内那个固定目录。
138
178
  */
139
179
  function listPackages(root) {
140
180
  const packages = [];
141
181
  for (const entry of readCatalog(root)) {
142
- const directory = path.join(root, entry.slug);
143
- let stats;
144
- try { stats = fs.statSync(directory); } catch { continue; }
145
- if (!stats.isDirectory()) continue;
146
- let manifest;
182
+ const pkg = readPackage(path.join(root, entry.slug), entry.slug, entry);
183
+ if (pkg) packages.push(pkg);
184
+ }
185
+ return packages;
186
+ }
187
+
188
+ /**
189
+ * 第三方插件自带的扩展:profile 里任何一个插件的 `package.json` 声明了 `dshMobileExtensions`,
190
+ * 它那份目录里的每个子目录就是一个扩展(见 `third-party-extensions.js`)。
191
+ *
192
+ * 这一档**没有登记清单**:作者装好自己的插件,他的手机就能拉到,我们这边不认识他。
193
+ * 审核不在仓库里做,所以判据只剩「能不能装」—— 与上一条同一个 `readPackage`,判不过就不列。
194
+ *
195
+ * 文案从包里自己的 `manifest.json` 读(`description` / `author` 也认包内的,缺了才退到插件名),
196
+ * 不另立一份清单文件:作者已经在写 manifest 了,再要求一张表就是又一个要同步的东西。
197
+ */
198
+ function listThirdParty(pluginsRoot) {
199
+ const packages = [];
200
+ for (const found of thirdParty.discoverPackages(pluginsRoot)) {
201
+ let manifest = null;
147
202
  try {
148
- manifest = JSON.parse(fs.readFileSync(path.join(directory, 'manifest.json'), 'utf8'));
149
- } catch { continue; }
150
- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) continue;
151
- const acc = { root: directory, files: [], bytes: 0 };
152
- if (!collectFiles(directory, acc) || acc.files.length === 0) continue;
153
- if (!acc.files.some((file) => file.path === 'index.html')) continue;
154
- packages.push({
155
- slug: entry.slug,
156
- name: textField(manifest.name, entry.slug),
157
- description: entry.description,
158
- author: entry.author,
159
- versionName: textField(manifest.versionName, textField(manifest.version, '0.0.0')),
160
- apiVersion: textField(manifest.apiVersion, textField(manifest.api_version, '1')),
161
- releaseNotes: entry.releaseNotes,
162
- capabilities: capabilitiesOf(manifest.capabilities),
163
- // 取数声明一起下发:手机上「已装记录」里若缺这一项(早期版本装下的包),App 用当前电脑上
164
- // 这一份清单把老记录补上,页面才不会把 /api/… 解析成 file://… 而永远转圈。只下发声明,
165
- // 不在这里做任何放行判断(真正的边界在 extension-data.js 的服务登记表里)。
166
- hostData: manifest.hostData && typeof manifest.hostData === 'object' && !Array.isArray(manifest.hostData)
167
- ? manifest.hostData
168
- : null,
169
- size: acc.bytes,
170
- fileCount: acc.files.length,
171
- files: acc.files,
172
- });
203
+ manifest = JSON.parse(fs.readFileSync(path.join(found.directory, 'manifest.json'), 'utf8'));
204
+ } catch { manifest = null; }
205
+ const author = manifest && typeof manifest.author === 'string' && manifest.author.trim()
206
+ ? manifest.author
207
+ : found.packageName;
208
+ const description = manifest && typeof manifest.description === 'string' && manifest.description.trim()
209
+ ? manifest.description
210
+ : null;
211
+ const pkg = readPackage(found.directory, found.slug, { description, author });
212
+ if (pkg) packages.push(pkg);
173
213
  }
174
214
  return packages;
175
215
  }
@@ -177,11 +217,21 @@ function listPackages(root) {
177
217
  /**
178
218
  * GET /api/mobile/v1/extension/catalog(token)
179
219
  *
180
- * 回审核过的第三方扩展清单。`root` 只是给守卫传假目录的可选参数,线上由 route() 调用时
181
- * 不传,永远走包内那个固定目录。
220
+ * 回这台电脑能给手机装的全部扩展:随本插件发布的(审核清单)+ 第三方插件自己带的那几条。
221
+ *
222
+ * `root` 只是给守卫传假目录的可选参数,线上由 route() 调用时不传,永远走包内那个固定目录;
223
+ * `pluginsRoot` 同理,是 profile 的 `node_modules`(运行时由外壳报上来)。
182
224
  */
183
- async function handleCatalog(_ctx, _req, res, root = catalogRoot()) {
184
- sendJson(res, 200, { ok: true, packages: listPackages(root) });
225
+ async function handleCatalog(_ctx, _req, res, root = catalogRoot(), pluginsRoot = null) {
226
+ const packages = listPackages(root);
227
+ const seen = new Set(packages.map((entry) => entry.slug));
228
+ for (const pkg of listThirdParty(pluginsRoot)) {
229
+ // 同 slug 以随本插件发布那份为准:那是我们发的包,不该被某个插件里的同名目录顶掉。
230
+ if (seen.has(pkg.slug)) continue;
231
+ seen.add(pkg.slug);
232
+ packages.push(pkg);
233
+ }
234
+ sendJson(res, 200, { ok: true, packages });
185
235
  }
186
236
 
187
237
  /**
@@ -201,8 +251,7 @@ async function handleCatalogArchive(_ctx, req, res, root = catalogRoot()) {
201
251
  }
202
252
  if (!readCatalog(root).some((entry) => entry.slug === slug)) {
203
253
  return fail(res, 404, 'package-missing', `审核清单里没有 ${slug} 这个包`);
204
- }
205
- const zipPath = path.join(root, `${slug}.zip`);
254
+ } const zipPath = path.join(root, `${slug}.zip`);
206
255
  let raw;
207
256
  try {
208
257
  const stat = fs.statSync(zipPath);
@@ -215,16 +264,28 @@ async function handleCatalogArchive(_ctx, req, res, root = catalogRoot()) {
215
264
  sendJson(res, 200, { ok: true, slug, size: raw.length, sha256: sha256Hex(raw), content: raw.toString('base64') });
216
265
  }
217
266
 
267
+ /**
268
+ * 一个 slug 对应的包目录:先查本插件里那批登记过的,再查第三方插件自己声明的。
269
+ *
270
+ * 两档都不认就返回 null —— 取文件那条据此回 404,目录里的字节读不到。
271
+ */
272
+ function packageDirOf(root, pluginsRoot, slug) {
273
+ if (readCatalog(root).some((entry) => entry.slug === slug)) {
274
+ return path.join(root, slug);
275
+ }
276
+ return thirdParty.directoryOf(pluginsRoot, slug);
277
+ }
278
+
218
279
  /**
219
280
  * GET /api/mobile/v1/extension/catalog/file?slug=…&path=…(token)
220
281
  *
221
- * 取一个已审核包里的一个文件,回 base64 与 sha256(与列表里那条同一份算法)。审核闸门对取文件
222
- * 同样生效:没登记进 catalog.json 的 slug 一律 404,免得绕过清单直接把目录里的字节读走。
282
+ * 取一个包里的一个文件,回 base64 与 sha256(与列表里那条同一份算法)。两档来源共用这道闸:
283
+ * 既不在本插件的审核清单里、也不是哪个插件声明过的 slug,一律 404,免得绕过清单直接把字节读走。
223
284
  *
224
285
  * 路径检查两道:先挡明显不该出现的(绝对路径、`..` 段),再 resolve 之后判前缀 —— 后者才是
225
286
  * 判据,前缀比较必须带分隔符,否则 `/x/extensions/foobar` 会被 `/x/extensions/foo` 认成子路径。
226
287
  */
227
- async function handleCatalogFile(_ctx, req, res, root = catalogRoot()) {
288
+ async function handleCatalogFile(_ctx, req, res, root = catalogRoot(), pluginsRoot = null) {
228
289
  const url = new URL(req.url || '/', 'http://x');
229
290
  const slug = (url.searchParams.get('slug') || '').trim();
230
291
  const requested = (url.searchParams.get('path') || '').trim();
@@ -232,10 +293,10 @@ async function handleCatalogFile(_ctx, req, res, root = catalogRoot()) {
232
293
  return fail(res, 400, 'bad-request', '需要合法的 slug 与 path(path 是相对包目录的路径)');
233
294
  }
234
295
 
235
- if (!readCatalog(root).some((entry) => entry.slug === slug)) {
236
- return fail(res, 404, 'package-missing', `审核清单里没有 ${slug} 这个包`);
296
+ const directory = packageDirOf(root, pluginsRoot, slug);
297
+ if (!directory) {
298
+ return fail(res, 404, 'package-missing', `这台电脑上没有 ${slug} 这个扩展`);
237
299
  }
238
- const directory = path.join(root, slug);
239
300
  if (!fs.existsSync(path.join(directory, 'manifest.json'))) {
240
301
  return fail(res, 404, 'package-missing', `${slug} 没有可下发的包(缺 manifest.json)`);
241
302
  }
@@ -275,6 +336,7 @@ async function handleCatalogFile(_ctx, req, res, root = catalogRoot()) {
275
336
  module.exports = {
276
337
  catalogRoot,
277
338
  listPackages,
339
+ listThirdParty,
278
340
  handleCatalog,
279
341
  handleCatalogFile,
280
342
  handleCatalogArchive,
@@ -23,6 +23,7 @@ const http = require('node:http');
23
23
 
24
24
  const { sendJson, readJsonBody } = require('../shared/http-util');
25
25
  const { ensureWeb } = require('./magpie-web.js');
26
+ const { hasPermission } = require('./permissions.js');
26
27
 
27
28
  /** 请求体的上限:扩展页发来的是「一条请求」,几个 KB 的 JSON 足够,2MB 已经很宽松。 */
28
29
  const MAX_REQUEST_BYTES = 2 * 1024 * 1024;
@@ -191,6 +192,11 @@ async function handleExtensionData(_ctx, req, res) {
191
192
 
192
193
  const method = typeof body.method === 'string' ? body.method.trim().toUpperCase() : 'GET';
193
194
  if (!METHODS.has(method)) return failure(res, 400, 'bad-method', `不支持的方法:${method}`);
195
+ // 这条路由在外层永远是 POST(分类表只能按它当读放行),真正的方法藏在 body 里。所以写方法
196
+ // 必须在这里按设备单独判:只读档设备否则能借代发通道对扩展后台发写请求。
197
+ if (method !== 'GET' && !hasPermission(req.__dshRecord, 'files.write')) {
198
+ return failure(res, 403, 'permission-denied', '这台设备没有执行该操作的权限');
199
+ }
194
200
 
195
201
  const path = body.path.trim();
196
202
  if (!path.startsWith('/') || path.startsWith('//')) return failure(res, 400, 'bad-path', '路径必须是本源内的绝对路径');
@@ -19,6 +19,11 @@
19
19
  * 仍然拒绝符号链接与目录。父目录必须已经存在(建目录走 `directory-browse.js` 的
20
20
  * `directory/create`),这条不顺手递归 `mkdir` —— 少一层就少一处能爬出允许区的路径。
21
21
  * 4. 不写 shell,全程 `node:fs/promises`。
22
+ *
23
+ * 5. **按项目串行**:同一个项目目录同一时刻只让一个写落盘(`project-write-queue`)。手机能
24
+ * 一口气派几条会话,落点又在同一个项目里,并发写就是后写的覆盖先写的。只读不进这条队列。
25
+ * 队列键由 `queueKeyOf` 统一给,`uploads.js` 的落盘与 `directory-browse.js` 的建目录算的
26
+ * 是同一份 —— 口径分叉等于没排队。
22
27
  */
23
28
 
24
29
  const { writeFile, unlink, rename, lstat, realpath } = require('node:fs/promises');
@@ -26,6 +31,7 @@ const path = require('node:path');
26
31
 
27
32
  const { sendJson, readJsonBody } = require('../shared/http-util');
28
33
  const { allowedRoots, inAllowedZone } = require('./allowed-zone.js');
34
+ const { withProjectWrite, queueKeyOf } = require('./project-write-queue.js');
29
35
 
30
36
  const FILE_PATH_MAX = 4096; // 绝对路径长度上限
31
37
  const FILE_NAME_MAX = 255; // 单个文件名上限(多数文件系统同值)
@@ -110,7 +116,7 @@ async function handleFileCreate(ctx, req, res) {
110
116
  const body = (await readJsonBody(req)) || {};
111
117
  const prepared = await preparePath(ctx, body, res);
112
118
  if (!prepared) return;
113
- const { target } = prepared;
119
+ const { target, roots } = prepared;
114
120
 
115
121
  const content = typeof body.content === 'string' ? body.content : (body.content == null ? '' : null);
116
122
  if (content === null) return sendError(res, 400, 'invalid-content', 'content 必须是字符串');
@@ -119,31 +125,34 @@ async function handleFileCreate(ctx, req, res) {
119
125
  return sendError(res, 413, 'too-large', '文件太大,手机这边不支持一次性新建这么大的文件');
120
126
  }
121
127
 
122
- let existing = null;
123
- try {
124
- existing = await lstat(target);
125
- } catch {
126
- existing = null;
127
- }
128
- if (existing) {
129
- if (existing.isSymbolicLink()) return sendError(res, 400, 'symlink-refused', '这是一个符号链接,不在这里新建或覆盖');
130
- if (existing.isDirectory()) return sendError(res, 400, 'not-a-file', '这条路径已经是一个目录');
131
- if (!body.overwrite) return sendError(res, 409, 'file-exists', '同名文件已经存在');
132
- }
128
+ // 落盘这一段按项目串行:判重与写入必须在同一个独占窗口里,否则两条并发请求会都判「不存在」。
129
+ await withProjectWrite(queueKeyOf(roots, target), async () => {
130
+ let existing = null;
131
+ try {
132
+ existing = await lstat(target);
133
+ } catch {
134
+ existing = null;
135
+ }
136
+ if (existing) {
137
+ if (existing.isSymbolicLink()) return sendError(res, 400, 'symlink-refused', '这是一个符号链接,不在这里新建或覆盖');
138
+ if (existing.isDirectory()) return sendError(res, 400, 'not-a-file', '这条路径已经是一个目录');
139
+ if (!body.overwrite) return sendError(res, 409, 'file-exists', '同名文件已经存在');
140
+ }
133
141
 
134
- try {
135
- await writeFile(target, content, { encoding: 'utf8', flag: existing ? 'w' : 'wx' });
136
- } catch (error) {
137
- if (error && error.code === 'EEXIST') return sendError(res, 409, 'file-exists', '同名文件已经存在');
138
- return sendError(res, 502, 'write-failed', `写文件失败:${String((error && error.message) || error)}`);
139
- }
142
+ try {
143
+ await writeFile(target, content, { encoding: 'utf8', flag: existing ? 'w' : 'wx' });
144
+ } catch (error) {
145
+ if (error && error.code === 'EEXIST') return sendError(res, 409, 'file-exists', '同名文件已经存在');
146
+ return sendError(res, 502, 'write-failed', `写文件失败:${String((error && error.message) || error)}`);
147
+ }
140
148
 
141
- sendJson(res, 200, {
142
- ok: true,
143
- path: target,
144
- created: !existing,
145
- overwritten: !!existing,
146
- bytes,
149
+ sendJson(res, 200, {
150
+ ok: true,
151
+ path: target,
152
+ created: !existing,
153
+ overwritten: !!existing,
154
+ bytes,
155
+ });
147
156
  });
148
157
  }
149
158
 
@@ -155,28 +164,30 @@ async function handleFileDelete(ctx, req, res) {
155
164
  const body = (await readJsonBody(req)) || {};
156
165
  const prepared = await preparePath(ctx, body, res);
157
166
  if (!prepared) return;
158
- const { target } = prepared;
167
+ const { target, roots } = prepared;
159
168
 
160
- let info;
161
- try {
162
- info = await lstat(target);
163
- } catch {
164
- return sendError(res, 404, 'missing', '这个文件已经不在这台电脑上了');
165
- }
166
- if (info.isSymbolicLink()) {
167
- // 既不移除链接、也绝不顺着链接去删它指向的文件。
168
- return sendError(res, 400, 'symlink-refused', '这是一个符号链接,不删除');
169
- }
170
- if (!info.isFile()) {
171
- return sendError(res, 400, 'not-a-file', '这条路径不是一个文件');
172
- }
169
+ await withProjectWrite(queueKeyOf(roots, target), async () => {
170
+ let info;
171
+ try {
172
+ info = await lstat(target);
173
+ } catch {
174
+ return sendError(res, 404, 'missing', '这个文件已经不在这台电脑上了');
175
+ }
176
+ if (info.isSymbolicLink()) {
177
+ // 既不移除链接、也绝不顺着链接去删它指向的文件。
178
+ return sendError(res, 400, 'symlink-refused', '这是一个符号链接,不删除');
179
+ }
180
+ if (!info.isFile()) {
181
+ return sendError(res, 400, 'not-a-file', '这条路径不是一个文件');
182
+ }
173
183
 
174
- try {
175
- await unlink(target);
176
- } catch (error) {
177
- return sendError(res, 502, 'delete-failed', `删除失败:${String((error && error.message) || error)}`);
178
- }
179
- sendJson(res, 200, { ok: true, path: target, deleted: true });
184
+ try {
185
+ await unlink(target);
186
+ } catch (error) {
187
+ return sendError(res, 502, 'delete-failed', `删除失败:${String((error && error.message) || error)}`);
188
+ }
189
+ sendJson(res, 200, { ok: true, path: target, deleted: true });
190
+ });
180
191
  }
181
192
 
182
193
  /** 单个路径段:非空、不是 . / ..、不含分隔符、不过长。 */
@@ -204,41 +215,43 @@ async function handleFileRename(ctx, req, res) {
204
215
  const name = validSegment(body.name);
205
216
  if (!name) return sendError(res, 400, 'invalid-name', 'name 必须是单个文件名(不含路径分隔符)');
206
217
 
207
- let source;
208
- try {
209
- source = await lstat(target);
210
- } catch {
211
- return sendError(res, 404, 'missing', '这个文件已经不在这台电脑上了');
212
- }
213
- if (source.isDirectory()) return sendError(res, 400, 'not-a-file', '这条路径是一个目录,不在这里改名');
218
+ await withProjectWrite(queueKeyOf(roots, target), async () => {
219
+ let source;
220
+ try {
221
+ source = await lstat(target);
222
+ } catch {
223
+ return sendError(res, 404, 'missing', '这个文件已经不在这台电脑上了');
224
+ }
225
+ if (source.isDirectory()) return sendError(res, 400, 'not-a-file', '这条路径是一个目录,不在这里改名');
214
226
 
215
- const destination = path.join(parent, name);
216
- if (!inAllowedZone(roots, destination)) {
217
- // 正常到不了:name 是单段、parent 已校验。留着是防「以后有人把 name 放宽成相对路径」。
218
- return sendError(res, 403, 'outside-allowed', '改名后的位置不在允许区里');
219
- }
220
- if (destination === target) {
221
- return sendJson(res, 200, { ok: true, path: target, from: target, renamed: false });
222
- }
227
+ const destination = path.join(parent, name);
228
+ if (!inAllowedZone(roots, destination)) {
229
+ // 正常到不了:name 是单段、parent 已校验。留着是防「以后有人把 name 放宽成相对路径」。
230
+ return sendError(res, 403, 'outside-allowed', '改名后的位置不在允许区里');
231
+ }
232
+ if (destination === target) {
233
+ return sendJson(res, 200, { ok: true, path: target, from: target, renamed: false });
234
+ }
223
235
 
224
- let destinationInfo = null;
225
- try {
226
- destinationInfo = await lstat(destination);
227
- } catch {
228
- destinationInfo = null;
229
- }
230
- if (destinationInfo) {
231
- if (!body.overwrite) return sendError(res, 409, 'file-exists', '目标名字已经有文件了');
232
- if (destinationInfo.isSymbolicLink()) return sendError(res, 400, 'symlink-refused', '目标是一个符号链接,不覆盖');
233
- if (destinationInfo.isDirectory()) return sendError(res, 400, 'not-a-file', '目标名字已经是一个目录');
234
- }
236
+ let destinationInfo = null;
237
+ try {
238
+ destinationInfo = await lstat(destination);
239
+ } catch {
240
+ destinationInfo = null;
241
+ }
242
+ if (destinationInfo) {
243
+ if (!body.overwrite) return sendError(res, 409, 'file-exists', '目标名字已经有文件了');
244
+ if (destinationInfo.isSymbolicLink()) return sendError(res, 400, 'symlink-refused', '目标是一个符号链接,不覆盖');
245
+ if (destinationInfo.isDirectory()) return sendError(res, 400, 'not-a-file', '目标名字已经是一个目录');
246
+ }
235
247
 
236
- try {
237
- await rename(target, destination);
238
- } catch (error) {
239
- return sendError(res, 502, 'rename-failed', `改名失败:${String((error && error.message) || error)}`);
240
- }
241
- sendJson(res, 200, { ok: true, path: destination, from: target, renamed: true });
248
+ try {
249
+ await rename(target, destination);
250
+ } catch (error) {
251
+ return sendError(res, 502, 'rename-failed', `改名失败:${String((error && error.message) || error)}`);
252
+ }
253
+ sendJson(res, 200, { ok: true, path: destination, from: target, renamed: true });
254
+ });
242
255
  }
243
256
 
244
257
  module.exports = {
package/lib/mobile/git.js CHANGED
@@ -10,9 +10,12 @@
10
10
  * 项目识别出来的根之一,于是随意传路径、`..`、仓库外目录都进不来。写操作按仓库串行,避免
11
11
  * 并发写撞 `.git/index.lock`,写完顺手回一份新的变更清单。
12
12
  *
13
- * 明确不做合并 / 变基 / 拣选 / 冲突解决 / 强制推送 / 删除远端分支 / 改配置与凭据 / 子模块 /
14
- * fetch、pull;push 只推当前分支到已有上游,远端分叉或没有上游一律拒掉。丢弃改动也没做,
13
+ * 明确不做本地分支的合并 / 变基 / 拣选 / 冲突解决 / 强制推送 / 删除远端分支 / 改配置与凭据 /
14
+ * 子模块 / fetch、pull;push 只推当前分支到已有上游,远端分叉或没有上游一律拒掉。丢弃改动也没做,
15
15
  * 接口留白比一个能被误按的按钮安全。
16
+ *
17
+ * 唯一的「合并」是 GitHub PR 那一层(`lib/git/pr.js` 与文件末尾那五个 handler):合的是 GitHub 上的
18
+ * PR,只认 squash / merge 两档,不碰本地工作树。
16
19
  */
17
20
 
18
21
  const { isAbsolute, resolve } = require('node:path');
@@ -21,6 +24,7 @@ const { readJsonBody, sendJson } = require('../shared/http-util');
21
24
  const { unwrap } = require('./envelope.js');
22
25
  const { describeProjectGit } = require('./git-repos.js');
23
26
  const read = require('../git/read');
27
+ const pr = require('../git/pr');
24
28
  const { runGit, withRepoLock } = require('../git/exec');
25
29
 
26
30
  /** 错误码 → HTTP 状态。前端只认 code,message 只用于排障与兜底文案。 */
@@ -49,6 +53,15 @@ const STATUS_BY_CODE = {
49
53
  GIT_UNAVAILABLE: 503,
50
54
  LLM_UNAVAILABLE: 503,
51
55
  TIMEOUT: 504,
56
+ // GitHub PR 那一层(lib/git/pr.js)。
57
+ PR_NOT_FOUND: 404,
58
+ NO_PR: 404,
59
+ CHECKS_FAILING: 409,
60
+ MERGE_NOT_ALLOWED: 409,
61
+ ALREADY_MERGED: 409,
62
+ GH_AUTH: 403,
63
+ GH_RATE_LIMITED: 429,
64
+ GH_UNAVAILABLE: 502,
52
65
  };
53
66
 
54
67
  class GitRequestError extends Error {
@@ -575,6 +588,94 @@ async function handleGitPush(ctx, req, res) {
575
588
  });
576
589
  }
577
590
 
591
+ // ── GitHub PR ───────────────────────────────────────────────────────────────
592
+ //
593
+ // 这一组仍然是封闭动词:不收 URL / host / method / GraphQL,能做的只有「看本分支的 PR、
594
+ // 看检查、标可评审、合并、读评论」。GitHub 的具体路都写死在 lib/git/pr.js 里,这里只管
595
+ // 归属校验、参数校验与出包。合并只到 GitHub PR,本地分支合并仍留在电脑上。
596
+
597
+ /** PR 号:必须是纯数字的正整数。`01` 也收(转成 1),字符串 `"../x"` 一律拒。 */
598
+ function prNumber(value) {
599
+ const raw = typeof value === 'number' ? String(value) : text(value);
600
+ if (!/^\d+$/.test(raw)) throw fail('BAD_REQUEST', 'PR 号要是正整数');
601
+ const parsed = Number(raw);
602
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) throw fail('BAD_REQUEST', 'PR 号要是正整数');
603
+ return parsed;
604
+ }
605
+
606
+ /** GET git/prs { workspaceId, repo?, state? }:列**当前分支**的 PR(不收分支名)。 */
607
+ async function handleGitPrs(ctx, req, res) {
608
+ const params = query(req);
609
+ const target = await resolveTarget(ctx, {
610
+ workspaceId: params.get('workspaceId'),
611
+ repo: params.get('repo'),
612
+ });
613
+ const repo = await pr.githubRepoOf(target.repoRoot);
614
+ if (!repo) {
615
+ sendJson(res, 200, { ok: true, prs: [], notGithub: true });
616
+ return;
617
+ }
618
+ const state = pr.normalizeState(params.get('state'));
619
+ const summary = await read.repoOf(target.repoRoot);
620
+ if (summary.detached || !text(summary.branch)) throw fail('NO_PR', '现在不在任何分支上,回电脑上切回分支再看 PR');
621
+ const { prs } = await pr.pullsOf(target.repoRoot, { state });
622
+ sendJson(res, 200, { ok: true, prs });
623
+ }
624
+
625
+ /** GET git/pr/checks:先拿 head.sha,再拉那个提交的 check-runs。 */
626
+ async function handleGitPrChecks(ctx, req, res) {
627
+ const params = query(req);
628
+ const target = await resolveTarget(ctx, {
629
+ workspaceId: params.get('workspaceId'),
630
+ repo: params.get('repo'),
631
+ });
632
+ const number = prNumber(params.get('number'));
633
+ const checks = await pr.checksOf(target.repoRoot, number);
634
+ sendJson(res, 200, { ok: true, checks });
635
+ }
636
+
637
+ /** POST git/pr/ready:把草稿 PR 标成可评审。写操作,按仓库串行。 */
638
+ async function handleGitPrReady(ctx, req, res) {
639
+ const body = await bodyJson(req);
640
+ const target = await resolveTarget(ctx, body);
641
+ const number = prNumber(body.number);
642
+ const result = await withRepoLock(target.repoRoot, async () => pr.markReady(target.repoRoot, number));
643
+ sendJson(res, 200, {
644
+ ok: true,
645
+ number: result.number,
646
+ draft: Boolean(result.draft),
647
+ state: result.state || 'open',
648
+ });
649
+ }
650
+
651
+ /**
652
+ * POST git/pr/merge { workspaceId, repo?, number, method }:合并一条 PR。
653
+ *
654
+ * `method` 必填且只有 `squash` / `merge` 两档 —— rebase 与自定义提交信息不收,本地就回 400,
655
+ * 一个请求都不发出去。不预判 checks:那是 GitHub 的事,它拒了再按措辞分成 `CHECKS_FAILING`。
656
+ */
657
+ async function handleGitPrMerge(ctx, req, res) {
658
+ const body = await bodyJson(req);
659
+ const target = await resolveTarget(ctx, body);
660
+ const number = prNumber(body.number);
661
+ const method = text(body.method).toLowerCase();
662
+ if (!pr.MERGE_METHODS.has(method)) throw fail('BAD_REQUEST', '合并方式只支持 squash 或 merge');
663
+ const result = await withRepoLock(target.repoRoot, async () => pr.mergeOf(target.repoRoot, number, method));
664
+ sendJson(res, 200, { ok: true, number, merged: true, sha: result.sha });
665
+ }
666
+
667
+ /** GET git/pr/comments:PR 评论(走 issues/{number}/comments)。 */
668
+ async function handleGitPrComments(ctx, req, res) {
669
+ const params = query(req);
670
+ const target = await resolveTarget(ctx, {
671
+ workspaceId: params.get('workspaceId'),
672
+ repo: params.get('repo'),
673
+ });
674
+ const number = prNumber(params.get('number'));
675
+ const comments = await pr.commentsOf(target.repoRoot, number);
676
+ sendJson(res, 200, { ok: true, comments });
677
+ }
678
+
578
679
  module.exports = {
579
680
  handleGitRepo: handle(handleGitRepo),
580
681
  handleGitStatus: handle(handleGitStatus),
@@ -589,6 +690,11 @@ module.exports = {
589
690
  handleGitCheckout: handle(handleGitCheckout),
590
691
  handleGitPush: handle(handleGitPush),
591
692
  handleGitCommitMessage: handle(handleGitCommitMessage),
693
+ handleGitPrs: handle(handleGitPrs),
694
+ handleGitPrChecks: handle(handleGitPrChecks),
695
+ handleGitPrReady: handle(handleGitPrReady),
696
+ handleGitPrMerge: handle(handleGitPrMerge),
697
+ handleGitPrComments: handle(handleGitPrComments),
592
698
  GitRequestError,
593
699
  repoTargetPath,
594
700
  resolveTarget,