dsh-ide-window 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -68,6 +68,7 @@ locale/{zh,en}.json UI 文案(165 个键);插件管理器也从这里
68
68
  | `66-callchain.js` | 调用链(Alt+单击):沿 `findReferences` 向上递归,思维导图式浮层 |
69
69
  | `68-grep.js` | 工作区搜索 + jar 源码查询客户端 |
70
70
  | `70-palette.js` | Search Everywhere(所有/类/符号/文件/文本/操作,默认所有) |
71
+ | `72-screenshot.js` | **截图**:宿主抓屏、预览弹层、「跳转会话(粘贴图片)/ 只截图」、macOS 授权引导 |
71
72
  | `90-apply.js` | 全部注册(槽位、快捷键、命令、设置项)+ `enter()/openPanel()` |
72
73
 
73
74
  ### 3.2 平台层(`platform/`,只支持 macOS + Windows)
@@ -81,7 +82,7 @@ locale/{zh,en}.json UI 文案(165 个键);插件管理器也从这里
81
82
  | `platform/windows.js` | `\` ↔ `/` 互转、`cmd /c start` 打开 URL、`rg.exe`、`intellij-server.bat`、`.bat/.cmd` 需要 shell |
82
83
  | `platform/index.js` | `createPlatform(os)`:**只有 macOS(`darwin`/`macos`/`mac`)用 macOS 实现,其他一律 Windows** |
83
84
 
84
- 接口:`name`、`toPosix()`、`toNative()`、`isAbsolutePath()`、`expandUserPath()`、`ripgrepSuffixes`、`serverLauncherNames`、`needsShell()`、`openUrlCommand()`。
85
+ 接口:`name`、`toPosix()`、`toNative()`、`isAbsolutePath()`、`expandUserPath()`、`ripgrepSuffixes`、`serverLauncherNames`、`needsShell()`、`openUrlCommand()`、`screenshotCommand()`、`clipboardImageCommand()`。
85
86
 
86
87
  根路径不是平台差异:需要时用 `node:path` 的 `parse(path).root`。
87
88
 
@@ -118,6 +119,8 @@ locale/{zh,en}.json UI 文案(165 个键);插件管理器也从这里
118
119
  | `/dsh-ide/text` | 复制文件内容 | 读整个文件(≤512 KB),返回 `{text, truncated}` |
119
120
  | `/dsh-ide/diagnostics` | 诊断日志 | `{action:'read'}` 返回本机最近 100 条事件 + 日志文件路径;`{action:'report', entries}` 接收浏览器缓冲的事件并写入同一文件(`level:'client'`) |
120
121
  | `/dsh-ide/theme` | 主题样式表 | `GET ?id=<主题>` 返回 `themes/<id>.css`(唯一非 JSON 路由,浏览器用 `<link>` 取);id 只允许 `[a-z0-9-]`,未知 404、非法 400 |
122
+ | `/dsh-ide/screenshot` | 截屏 | `{copy:true}` 抓屏并复制;`{copyOf:path}` 只把已有文件复制到剪贴板;返回 `{path, bytes, quality, dataUrl}`(1080p JPEG,质量阶梯保证 ≤1 MB)。失败时 `403 no-screen-permission`(macOS 未授权)或 `500 capture-failed` |
123
+ | `/dsh-ide/screen-permission` | 打开授权面板 | 只 macOS 有效:`open x-apple.systempreferences:…Privacy_ScreenCapture`;其他系统回 `{opened:false}` |
121
124
  | `/dsh-ide/license` | JetBrains 授权 | `{action:'status'}` 跑 `intellij-server license status`;`{action:'open'}` 后台跑 `license login --browser` 并回传授权 URL(6 秒内没出现 URL 就回传工具输出)。给这两个 JVM 动词加 `-Didea.log.path=<tmp>`,避免受限环境下写 `~/Library/Logs` 失败 |
122
125
 
123
126
  ### 3.3.1 跨插件主题约定(和 dsh-git-window)
@@ -211,6 +214,15 @@ tail -f /tmp/dsh-ide-test/logs/dsh-ide-window.log # 自测实例
211
214
  - **源码里的符号右键菜单**:在方法名、字段、类名等任意符号上右键 →「复制名称」/「复制引用」/「复制引用回对话」。引用统一是 DSH 的 `@相对路径` 形式(目录带尾斜杠、含空格时加引号,规则与 DSH 的 reference codec 一致);jar 源码标签页只有「复制名称」,因为 jar 内的路径不是工作区路径
212
215
  - **复制引用回对话**:直接回到对话,并把 `@引用` **追加**到草稿末尾——已有文本和附件一律不动,插入的是真正的引用芯片(不是纯文本)。实现方式:对话输入框是 Lexical 编辑器,`@` 触发菜单,只有从菜单里选中候选才会变成芯片,所以按「人打字」的顺序逐段输入(Tab 进入目录、最后一段回车确认),每一步都核对菜单候选;任何一步对不上就退化成纯文本 `@相对路径`,绝不选错文件。目录无法用芯片表达,直接插入 `@目录/` 文本
213
216
 
217
+ ### 4.2.1 截图
218
+
219
+ - 快捷键 `⌘⇧S`(Windows `Ctrl+Shift+S`),设置里可改;Search Everywhere 的「操作」里也有
220
+ - 宿主用系统自带工具抓全屏:macOS `screencapture -x -t png`、Windows PowerShell + `System.Drawing`(`CopyFromScreen` 抓虚拟屏幕,多显示器也覆盖);**不装任何第三方程序**
221
+ - 抓完统一**压成 1920×1080 JPEG**:macOS `sips -Z 1920 -s format jpeg -s formatOptions <质量>`、Windows PowerShell 双三次缩放 + `EncoderParameters` 质量;质量阶梯 `80/70/60/50`,第一个 ≤1 MB 的就用,原 PNG 随后删除。实测 2560×1440 的 Retina 截图 = 1.2 MB → **270 KB / q80**
222
+ - 抓完弹预览,两个出口:**截图并跳转会话**(回到对话,把图片作为 `File` 通过合成 `ClipboardEvent('paste')` 粘进 Lexical 输入框——只派发 paste,不碰 editor 内容,所以已有文字/引用/附件原样保留);**只截图**(`{copyOf}` 让宿主把该文件写进系统剪贴板,通知给出路径)
223
+ - **macOS 屏幕录制权限**:没授权时 `screencapture` 报 `could not create image from display`,宿主归类为 `403 no-screen-permission`,弹层给系统化指引 + 「打开系统设置」按钮(`x-apple.systempreferences:…Privacy_ScreenCapture`),授权后必须**完全退出应用重开**。Windows 无此权限
224
+ - 合成 paste 已验证可用(输入框里出现 `blob:` 图片、原有文字不变);若某天 DSH 忽略合成事件,代码退化成「已复制到剪贴板,按 ⌘V」
225
+
214
226
  ### 4.3 搜索
215
227
  - **Search Everywhere**:双击 Shift、工具栏放大镜、或快捷键(桌面 `⌘I` 类默认由设置里的绑定决定;Web 默认 `⌥⌘I`)打开,六分类(所有 / 类 / 符号 / 文件 / 文本 / 操作),**默认「所有」**——`类` = 文件即类(`ideFqnOf` 出全限定名);`符号` = 声明形状的 ripgrep 前缀搜索(`ideSymbolPattern`:类/接口/枚举/record、字段、方法、常量、`function/const/def`),**是文本启发式不是符号索引**,局部变量可能混入;`所有` = 类 → 符号 → 文件(非源码)→ 文本(**含源码文件**,仅去掉与符号行完全相同的行)→ 操作;**结果按匹配度排序**(符号 `ideSymbolRank`、文件 `ideFileRank`、文本 `ideMatchRank`、命令 `ideActionRank`)
216
228
  - 样式用 DSH 菜单 token;`⌘P` 聚焦文件树筛选框
@@ -230,6 +242,7 @@ tail -f /tmp/dsh-ide-test/logs/dsh-ide-window.log # 自测实例
230
242
  | `dsh-ide-window.back-to-chat` | key | 桌面 `⌘1` / Web `⌥⌘U` |
231
243
  | `code-workspace.search-everywhere` | sequence | 双击 `Shift`(窗口 400ms) |
232
244
  | `code-workspace.file-search` | key | `⌘P` |
245
+ | `code-workspace.screenshot` | key | `⌘⇧S`(Windows `Ctrl+Shift+S`) |
233
246
  | `code-workspace.gesture-definition` | gesture | 双击 / ⌘+单击 / Ctrl+单击(仅 macOS)/ ⌥+单击 |
234
247
  | `code-workspace.gesture-usages` | gesture | 同上(互斥) |
235
248
  | `code-workspace.gesture-chain` | gesture | ⌥+单击(三个动作互斥) |
@@ -321,6 +334,9 @@ dsh plugin --profile desktop add link:~/dev/dsh-ide-window
321
334
  | 「复制诊断信息」点了没反应、页面像卡住 | `await navigator.clipboard.writeText()` 在无权限/嵌入式环境下可能永不 resolve | 剪贴板用 `Promise.race` 加 1.5 秒超时,上报日志优先,超时退化为「已写入宿主日志」提示 |
322
335
  | 主题弹层里点某一项没反应(真鼠标点不动,代码里 `.click()` 却正常) | 关闭弹层用的是 `document` 上的 **capture** `pointerdown`:真实鼠标先派发 pointerdown,监听器先把弹层卸载,行的 click 永远到不了 | 关闭监听要放过落在弹层/触发按钮内部的按压(`target.closest('.iw-theme-pop, .iw-theme-button')`);**交互必须用真实指针事件验证**,程序化 `.click()` 会绕过 pointerdown |
323
336
  | 切到浅色主题后代码看不清(深色语法色仍在用) | 语法高亮是写死的深色配色,没有跟着主题走 | 语法色走 `--iw-syn-*` 变量,每套主题各给一组并按对比度校验(正文类 ≥4.5:1,注释 ≥3.5:1);`test/theme.mjs` 断言每套主题都有这 8 个变量 |
337
+ | 截图点了没反应,或只给一句「失败」 | `screencapture` 在 macOS 未授权时报 `could not create image from display`;浏览器侧也拿不到屏幕(DSH 把 `setDisplayMediaRequestHandler` 设成 `callback({})` 直接拒绝) | 截图只能由宿主用系统工具做;失败按文案归类成 `no-screen-permission`,弹层给「打开系统设置」深链 + 系统化指引 |
338
+ | 截图附件太大(1 MB 以上) | 直接塞原图:Retina 全屏 5120×2880、PNG 1.2 MB | 压缩是**必做步骤**不是可选项:统一 1920 长边 JPEG,质量阶梯 80→50 直到 ≤1 MB;原 PNG 用完就删,只留小文件 |
339
+ | 想只加一张图却把草稿弄乱 | 直接改输入框内容会动到用户已有的文字/引用/附件 | 合成 `ClipboardEvent('paste')` + `DataTransfer` + `File` 派发给 Lexical 输入框,让 DSH 自己处理粘贴;**不要**写 editor 的 `innerHTML`/`textContent`(`test/screenshot.mjs` 会断言这一点) |
324
340
  | 两个插件(代码工作区 + git 窗口)配色不一致 | 各自注入 CSS、各自用 DSH token,主题是本插件私有的 | 把主题做成跨插件约定:`localStorage['dsh-theme']` + `dsh-theme` 事件 + `[data-dsh-theme]` 选择器;对方只读这三样。只在 `.iw-root` 上作用域的选择器无法共享,必须用通用属性 |
325
341
 
326
342
  ---
@@ -335,6 +351,7 @@ dsh plugin --profile desktop add link:~/dev/dsh-ide-window
335
351
  - ~~加 `engines.dsh` 版本约束~~(已加,锁 `0.2.2-rc.3`)
336
352
  4. **每次改 `src/` 都要重新构建并提交 `client.js`**,否则别人装上跑的是旧代码。主题的调色板不在 bundle 里(`themes/*.css`),改颜色不需要重建。
337
353
  5. 插件需要 `webServer` 服务:在没有 web 服务的 profile 里会显示 `pending (waiting for service: webServer)`,属正常。
354
+ 6. **截图的临时文件不主动删除**:每次截图压在系统临时目录(`os.tmpdir()/dsh-ide-shot-<ts>.jpg`,中间生成的 PNG 用完即删),由操作系统按自己的节奏清理;「只截图」时那个路径就是交给用户的产物,所以不删。
338
355
 
339
356
  ---
340
357
 
@@ -353,6 +370,7 @@ src/client/12-theme.js 配色主题:注册表 + <link> 切换 + 状态
353
370
  themes/*.css 10 套调色板(5 深 5 浅),只覆盖 alias token
354
371
  src/client/30-code.js 代码视图 + 跳转 + 右键菜单挂载
355
372
  src/client/59-gesture-settings.js 设置分区 + 标签页菜单组件
373
+ src/client/72-screenshot.js 截图:宿主抓屏 + 预览弹层 + 授权引导
356
374
  src/client/90-apply.js 全部注册 + 入口
357
375
  platform/{contract,macos,windows,index}.js 平台层(macOS / Windows 的差异都在这里)
358
376
  test/platform.mjs 平台层测试:两个实现满足同一契约
@@ -361,6 +379,7 @@ test/harness.mjs VM 夹具测试(含客户端平台层)
361
379
  test/inference.mjs 归属推断(bean 字段)
362
380
  test/maven.mjs 真实 ~/.m2 jar 端到端
363
381
  test/theme.mjs 主题:注册表/清单/文件一致、token 集合一致、读取器 400/404
382
+ test/screenshot.mjs 截图:两平台命令行、授权错误归类、客户端接法
364
383
  check-dsh-untouched.sh 本体完整性自检(macOS/Linux)
365
384
  restore-profile.sh 恢复 profile 到可用状态(macOS/Linux)
366
385
  start-test-instance.sh 起独立自测实例(固定端口 + 复用本机账号,不再弹登录框)
package/CHANGELOG.md CHANGED
@@ -6,6 +6,20 @@
6
6
  升级方式:DSH →「插件」→ 打开插件的「版本」区 →「检查更新」,或直接卸载后重新安装。
7
7
  (`link:` 本地安装不参与版本检查,拉取仓库即可。)
8
8
 
9
+ ## [0.3.2] — 2026-11-19
10
+
11
+ ### 新增
12
+
13
+ - **截图并跳转会话**:快捷键 `⌘⇧S`(Windows `Ctrl+Shift+S`,设置里可改,Search Everywhere 的「操作」里也有),截完弹出预览,可选「截图并跳转会话」或「只截图」。
14
+ - 截图由宿主调用系统自带工具完成(macOS `screencapture`、Windows PowerShell + `System.Drawing`),**不需要安装任何额外程序**。
15
+ - 「截图并跳转会话」把图片以合成粘贴的方式放进对话输入框:**已有文字、引用、附件一律不动**,只多一张图。
16
+ - 「只截图」把图片复制到系统剪贴板,并在通知里给出文件路径。
17
+ - 图片统一压成 **1920×1080 JPEG**(质量阶梯 80/70/60/50,保证 ≤1 MB),实测一张 Retina 全屏从 1.2 MB 降到约 270 KB;中间生成的 PNG 用完即删。
18
+
19
+ ### 说明
20
+
21
+ - **macOS 首次使用需要「屏幕录制」权限**:没有权限时插件会弹窗说明,并提供「打开系统设置」按钮直达该面板;授权后需要完全退出应用重开。Windows 不需要授权。
22
+
9
23
  ## [0.3.1] — 2026-11-19
10
24
 
11
25
  ### 修复
package/README.md CHANGED
@@ -236,6 +236,19 @@ dsh plugin --profile desktop add "git+https://github.com/simons-jiang/dsh-ide-wi
236
236
  - 改调色板**不需要重新构建** `client.js`,刷新页面即可看到
237
237
  - 新增一套主题 = 放一个 `themes/<id>.css` + 在 `src/client/12-theme.js` 的注册表加一行(`themes/index.json`、`test/theme.mjs` 会校验三处一致:10 套、5 深 5 浅、变量集合完全相同)
238
238
 
239
+ ### 截图
240
+
241
+ 按 `⌘⇧S`(Windows `Ctrl+Shift+S`,可在设置里改)抓一张全屏,随后可以:
242
+
243
+ - **截图并跳转会话** — 回到对话,把图片贴在输入框里。已有的文字、引用、附件一个都不动,只是多一张图
244
+ - **只截图** — 图片复制到剪贴板,通知里给出文件路径
245
+
246
+ 抓屏用的是系统自带工具(macOS `screencapture`、Windows .NET),**不装任何额外程序**。
247
+
248
+ 截图会压到 **1920×1080 的 JPEG、约 250–400 KB**(超过 1 MB 会自动降一档质量重压),粘进对话不会撑大附件:Retina 全屏原图有 1 MB 以上,聊天里没必要。
249
+
250
+ **macOS 第一次用会需要授权**:系统设置 → 隐私与安全性 → 屏幕录制 → 勾选 DeepSeek Harness,然后**完全退出应用重开**。没授权时插件会直接弹窗说明,点「打开系统设置」就能跳到那个面板;Windows 不需要授权。
251
+
239
252
  ---
240
253
 
241
254
  ## 四、快捷键与手势
@@ -246,6 +259,7 @@ dsh plugin --profile desktop add "git+https://github.com/simons-jiang/dsh-ide-wi
246
259
  | 返回对话 | `⌘1` | `Ctrl+1` |
247
260
  | 搜索无处不在 | 双击 `Shift` | 双击 `Shift` |
248
261
  | 定位文件搜索框 | `⌘P` | `Ctrl+P` |
262
+ | 截图(可跳转会话) | `⌘⇧S` | `Ctrl+Shift+S` |
249
263
  | 转到定义 / 查看实现 / 查看调用链 | 下拉选择:双击 / `⌘+单击` / `Ctrl+单击` / `⌥+单击`(默认:双击 / `⌘+单击` / `⌥+单击`) | 双击 / `Ctrl+单击` / `Alt+单击` |
250
264
 
251
265
  键位全部在 设置 → 通用设置 → 代码工作区快捷键 里改;改完立即生效,存于插件偏好(不写 DSH 的快捷键目录)。
package/client.js CHANGED
@@ -235,6 +235,23 @@ window.__ModuleLoader__.load({
235
235
  "theme_atom_one_light": "Atom One Light",
236
236
  "theme_solarized_light": "Solarized Light",
237
237
  "theme_intellij_light": "IntelliJ Light",
238
+ "shortcutScreenshot": "Screenshot (can jump to chat)",
239
+ "shotTitle": "Screenshot taken",
240
+ "shotBusy": "Capturing…",
241
+ "shotPreview": "Screenshot preview",
242
+ "shotJump": "Screenshot and jump to chat",
243
+ "shotKeep": "Screenshot only (copy to clipboard)",
244
+ "shotRetry": "Retry",
245
+ "shotFailed": "Screenshot failed",
246
+ "shotNoPermissionTitle": "Cannot capture: Screen Recording permission is missing",
247
+ "shotNoPermissionMac": "Enable DeepSeek Harness under System Settings → Privacy & Security → Screen Recording, then quit and reopen the app (the grant only applies after a relaunch).",
248
+ "shotNoPermissionWindows": "Windows needs no permission for this. Check that the screen is unlocked and no remote-desktop session or policy blocks capture, then retry.",
249
+ "shotOpenSettings": "Open System Settings",
250
+ "shotAttached": "Screenshot inserted into the conversation",
251
+ "shotCopied": "Screenshot copied to the clipboard",
252
+ "shotNoEditor": "Composer not found: the screenshot is on the clipboard, press ⌘V",
253
+ "shotOpenFailed": "Could not open System Settings. Open it manually: Privacy & Security → Screen Recording",
254
+ "paletteActionScreenshot": "Take a screenshot",
238
255
  }
239
256
  const IDE_TEXT_ZH = {
240
257
  "title": "代码工作区",
@@ -463,6 +480,23 @@ window.__ModuleLoader__.load({
463
480
  "theme_atom_one_light": "Atom One 浅色",
464
481
  "theme_solarized_light": "Solarized 浅色",
465
482
  "theme_intellij_light": "IntelliJ 浅色",
483
+ "shortcutScreenshot": "截图(可跳转会话)",
484
+ "shotTitle": "截图完成",
485
+ "shotBusy": "正在截图…",
486
+ "shotPreview": "截图预览",
487
+ "shotJump": "截图并跳转会话",
488
+ "shotKeep": "只截图(复制到剪贴板)",
489
+ "shotRetry": "重试",
490
+ "shotFailed": "截图失败",
491
+ "shotNoPermissionTitle": "无法截图:缺少屏幕录制权限",
492
+ "shotNoPermissionMac": "请在「系统设置 → 隐私与安全性 → 屏幕录制」里勾选 DeepSeek Harness,然后完全退出并重新打开应用(授权后必须重启才生效)。",
493
+ "shotNoPermissionWindows": "Windows 截图不需要授权。请确认没有锁屏、远程桌面占用或企业策略拦截,然后重试。",
494
+ "shotOpenSettings": "打开系统设置",
495
+ "shotAttached": "已把截图插入对话",
496
+ "shotCopied": "截图已复制到剪贴板",
497
+ "shotNoEditor": "没找到对话框:截图已复制到剪贴板,按 ⌘V 粘贴",
498
+ "shotOpenFailed": "打不开系统设置,请手动打开:系统设置 → 隐私与安全性 → 屏幕录制",
499
+ "paletteActionScreenshot": "截图",
466
500
  }
467
501
 
468
502
  // ---- 00-css.js -----------------------------------------------------------
@@ -1948,6 +1982,74 @@ html.iw-select-code .iw-code .iw-vision {
1948
1982
  .iw-theme-dot--solarized-light { background: #fdf6e3; }
1949
1983
  .iw-theme-dot--intellij-light { background: #f7f8fa; }
1950
1984
 
1985
+ /* ---- screenshot dialog (panel level, above the editor) ---- */
1986
+ .iw-shot {
1987
+ position: absolute;
1988
+ right: 16px;
1989
+ bottom: 40px;
1990
+ width: 420px;
1991
+ max-width: calc(100% - 32px);
1992
+ padding: 14px;
1993
+ box-sizing: border-box;
1994
+ border: 1px solid var(--dsw-alias-border-l1, #2c3038);
1995
+ border-radius: var(--dsw-radius-lg, 10px);
1996
+ background: var(--dsw-alias-bg-layer-2, #23262c);
1997
+ box-shadow: var(--dsw-elevation-prominent, 0 12px 32px rgba(0, 0, 0, 0.4));
1998
+ z-index: 45;
1999
+ }
2000
+ .iw-shot-title {
2001
+ font-size: 13px;
2002
+ font-weight: 500;
2003
+ color: var(--dsw-alias-label-primary, #e6e8ec);
2004
+ }
2005
+ .iw-shot-guide {
2006
+ margin-top: 8px;
2007
+ color: var(--dsw-alias-label-secondary, #98a0ad);
2008
+ font-size: 12px;
2009
+ line-height: 1.6;
2010
+ }
2011
+ .iw-shot-preview {
2012
+ display: block;
2013
+ width: 100%;
2014
+ max-height: 240px;
2015
+ margin-top: 10px;
2016
+ object-fit: contain;
2017
+ border: 1px solid var(--dsw-alias-border-l1, #2c3038);
2018
+ border-radius: var(--dsw-radius-sm, 4px);
2019
+ background: var(--dsw-alias-bg-base, #16181c);
2020
+ }
2021
+ .iw-shot-actions {
2022
+ display: flex;
2023
+ align-items: center;
2024
+ justify-content: flex-end;
2025
+ gap: 8px;
2026
+ margin-top: 12px;
2027
+ }
2028
+ .iw-shot-busy {
2029
+ color: var(--dsw-alias-label-secondary, #98a0ad);
2030
+ font-size: 12px;
2031
+ }
2032
+ .iw-shot-button,
2033
+ .iw-shot-primary {
2034
+ height: 28px;
2035
+ padding: 0 12px;
2036
+ border-radius: var(--dsw-radius-sm, 4px);
2037
+ border: 1px solid var(--dsw-alias-border-l1, #2c3038);
2038
+ background: transparent;
2039
+ color: var(--dsw-alias-label-primary, #e6e8ec);
2040
+ font: inherit;
2041
+ font-size: 12px;
2042
+ cursor: pointer;
2043
+ }
2044
+ .iw-shot-primary {
2045
+ border-color: transparent;
2046
+ background: var(--dsw-alias-brand-primary, #4f8cff);
2047
+ color: #fff;
2048
+ }
2049
+ .iw-shot-button:hover {
2050
+ background: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, 0.16));
2051
+ }
2052
+
1951
2053
  `
1952
2054
 
1953
2055
  /** Render the stylesheet as a React element so unmounting removes it. */
@@ -2425,6 +2527,18 @@ const IDE_SHORTCUTS = [
2425
2527
  },
2426
2528
  action: 'focus-filter',
2427
2529
  },
2530
+ {
2531
+ id: 'code-workspace.screenshot',
2532
+ kind: 'key',
2533
+ labelKey: 'shortcutScreenshot',
2534
+ aliases: ['screenshot', 'capture', 'shot', '截图', '截屏'],
2535
+ // ⌘⇧4 belongs to macOS itself, so the workspace uses its own combination.
2536
+ defaults: {
2537
+ desktop: { code: 'KeyS', modifiers: ['primary', 'shift'] },
2538
+ web: { code: 'KeyS', modifiers: ['primary', 'shift'] },
2539
+ },
2540
+ action: 'screenshot',
2541
+ },
2428
2542
  {
2429
2543
  id: 'code-workspace.gesture-definition',
2430
2544
  kind: 'gesture',
@@ -3122,6 +3236,11 @@ function ideCreateStore(refs) {
3122
3236
  theme: typeof prefs.theme === 'string' ? prefs.theme : '',
3123
3237
  /** Whether the palette popup is open (rendered at panel level, not in the bar). */
3124
3238
  themeMenu: false,
3239
+ /**
3240
+ * Screenshot dialog: `null` when closed, otherwise
3241
+ * `{ phase: 'running' | 'ready' | 'error', dataUrl?, path?, code?, message? }`.
3242
+ */
3243
+ screenshot: null,
3125
3244
  /** Editor and tree font sizes, in px, shared by the whole workspace. */
3126
3245
  codeFontSize: Number.isFinite(prefs.codeFontSize) ? prefs.codeFontSize : 12.5,
3127
3246
  treeFontSize: Number.isFinite(prefs.treeFontSize) ? prefs.treeFontSize : 14.5,
@@ -4174,6 +4293,8 @@ function ideCreateStore(refs) {
4174
4293
  /** Turn reference interception on or off (persisted). */
4175
4294
  /** Open or close the palette popup. */
4176
4295
  setThemeMenu: (themeMenu) => patch({ themeMenu }),
4296
+ /** Show, replace or clear the screenshot dialog. */
4297
+ setScreenshot: (screenshot) => patch({ screenshot }),
4177
4298
  /** Switch the panel palette; an empty id goes back to the DSH colours. */
4178
4299
  setTheme: (theme) => {
4179
4300
  ideWritePrefs({ theme })
@@ -6862,7 +6983,7 @@ function IdeSetupDialog({ tr, open, busy, still, onCheck, onClose, store }) {
6862
6983
  /** How many times the panel body has rendered; a probe can read it. */
6863
6984
  let idePanelRenders = 0
6864
6985
 
6865
- function IdePanel({ store, translate, onBackToChat, onToggleSidebar, onEnter, useSessions, useWorkspaces, navigate, paletteActions, onReferenceToChat }) {
6986
+ function IdePanel({ store, translate, onBackToChat, onToggleSidebar, onEnter, useSessions, useWorkspaces, navigate, paletteActions, onReferenceToChat, onScreenshotJump, onScreenshotKeep, onScreenshotRetry, onScreenshotOpenSettings, onScreenshotClose }) {
6866
6987
  const tr = typeof translate === 'function' ? translate : (key) => key
6867
6988
  const actions = paletteActions ?? []
6868
6989
 
@@ -7122,6 +7243,18 @@ function IdePanel({ store, translate, onBackToChat, onToggleSidebar, onEnter, us
7122
7243
  state.themeMenu === true
7123
7244
  ? h(IdeThemePopup, { key: 'themepopup', store, themeId: ideIsThemeId(state.theme) ? state.theme : '', tr })
7124
7245
  : null,
7246
+ state.screenshot === null || state.screenshot === undefined
7247
+ ? null
7248
+ : h(IdeScreenshotPopup, {
7249
+ key: 'shotpopup',
7250
+ state,
7251
+ tr,
7252
+ onJump: onScreenshotJump,
7253
+ onKeep: onScreenshotKeep,
7254
+ onRetry: onScreenshotRetry,
7255
+ onOpenSettings: onScreenshotOpenSettings,
7256
+ onClose: onScreenshotClose,
7257
+ }),
7125
7258
  h(IdeTreeMenu, {
7126
7259
  key: 'treemenu',
7127
7260
  store,
@@ -10221,6 +10354,153 @@ function IdePalette({ store, tr, actions, onClose }) {
10221
10354
  ])
10222
10355
  }
10223
10356
 
10357
+ // ---- 72-screenshot.js ----------------------------------------------------
10358
+ /**
10359
+ * Screenshots: the Host captures, the panel decides what to do with it.
10360
+ *
10361
+ * The Web page cannot read the screen (the shell answers `getDisplayMedia` with
10362
+ * a refusal), so the capture happens in the Host with an OS built-in tool and
10363
+ * comes back as a data URL. Two outcomes are offered:
10364
+ *
10365
+ * - **截图并跳转会话** — go back to the conversation and paste the image into the
10366
+ * composer. The paste is a synthetic `ClipboardEvent` carrying a `File`: the
10367
+ * shell treats it as a normal paste, so the draft's text, references and
10368
+ * pending attachments are left exactly as they were.
10369
+ * - **只截图** — copy it to the system clipboard and keep the file around; the
10370
+ * notice shows the path.
10371
+ *
10372
+ * macOS gates screen capture behind Screen Recording permission. A refusal is
10373
+ * classified by the Host (`no-screen-permission`) and answered with a guide that
10374
+ * opens the right settings pane in one click (Windows needs no such grant).
10375
+ */
10376
+
10377
+ const IDE_SHOT_ROUTE = '/dsh-ide/screenshot'
10378
+ const IDE_SHOT_PERMISSION_ROUTE = '/dsh-ide/screen-permission'
10379
+
10380
+ /** POST one screenshot request; never throws, returns `{ ok }` shapes. */
10381
+ async function ideShotRequest(body) {
10382
+ let response
10383
+ try {
10384
+ response = await fetch(IDE_SHOT_ROUTE, {
10385
+ method: 'POST',
10386
+ headers: { 'content-type': 'application/json' },
10387
+ body: JSON.stringify(body ?? {}),
10388
+ })
10389
+ } catch (error) {
10390
+ return { ok: false, code: 'network', message: String(error?.message ?? error) }
10391
+ }
10392
+ const parsed = await response.json().catch(() => null)
10393
+ if (parsed === null) return { ok: false, code: `http-${response.status}`, message: '' }
10394
+ if (parsed.ok !== true) {
10395
+ return {
10396
+ ok: false,
10397
+ code: parsed.error?.code ?? 'capture-failed',
10398
+ message: parsed.error?.message ?? '',
10399
+ }
10400
+ }
10401
+ return { ok: true, value: parsed.value }
10402
+ }
10403
+
10404
+ /** Ask the OS to open the place where screen recording is granted. */
10405
+ async function ideOpenScreenPermission() {
10406
+ let response
10407
+ try {
10408
+ response = await fetch(IDE_SHOT_PERMISSION_ROUTE, {
10409
+ method: 'POST',
10410
+ headers: { 'content-type': 'application/json' },
10411
+ body: '{}',
10412
+ })
10413
+ } catch {
10414
+ return { opened: false }
10415
+ }
10416
+ const parsed = await response.json().catch(() => null)
10417
+ return parsed?.ok === true ? parsed.value : { opened: false }
10418
+ }
10419
+
10420
+ /** The image inside a `data:image/png;base64,…` URL as a `File`. */
10421
+ function ideShotFile(dataUrl, name = 'screenshot.png') {
10422
+ const comma = dataUrl.indexOf(',')
10423
+ const head = dataUrl.slice(0, comma)
10424
+ const type = /^data:(image\/[a-z+]+)/.exec(head)?.[1] ?? 'image/png'
10425
+ const binary = atob(dataUrl.slice(comma + 1))
10426
+ const bytes = new Uint8Array(binary.length)
10427
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
10428
+ return new File([bytes], name, { type })
10429
+ }
10430
+
10431
+ /**
10432
+ * Paste the image into the conversation composer.
10433
+ *
10434
+ * Only a paste is dispatched — no editor mutation, no `@` mention flow — so the
10435
+ * draft keeps whatever the user already typed or attached. Returns `false` when
10436
+ * no composer is on screen, which the caller degrades to "copy it and paste
10437
+ * yourself".
10438
+ */
10439
+ async function idePasteScreenshot(dataUrl) {
10440
+ const findEditor = () => (typeof document === 'undefined' ? null : document.querySelector('[data-lexical-editor="true"]'))
10441
+ const deadline = Date.now() + 2000
10442
+ let editor = findEditor()
10443
+ while (editor === null && Date.now() < deadline) {
10444
+ await new Promise((resolve) => setTimeout(resolve, 40))
10445
+ editor = findEditor()
10446
+ }
10447
+ if (editor === null) return false
10448
+ const file = ideShotFile(dataUrl)
10449
+ const transfer = new DataTransfer()
10450
+ transfer.items.add(file)
10451
+ editor.focus()
10452
+ const event = new ClipboardEvent('paste', { clipboardData: transfer, bubbles: true, cancelable: true })
10453
+ editor.dispatchEvent(event)
10454
+ return true
10455
+ }
10456
+
10457
+ /**
10458
+ * The screenshot dialog: a preview with the two choices, or the permission guide
10459
+ * when the capture was refused. Rendered at panel level so it is not clipped.
10460
+ */
10461
+ function IdeScreenshotPopup({ state, tr, onJump, onKeep, onRetry, onOpenSettings, onClose }) {
10462
+ const shot = state.screenshot ?? null
10463
+ if (shot === null) return null
10464
+ const busy = shot.phase === 'running'
10465
+ const failed = shot.phase === 'error'
10466
+ const needsPermission = failed && shot.code === 'no-screen-permission'
10467
+ // The guide depends on the machine running the Host, which is the same machine
10468
+ // as the browser: `ideHostIsMacos()` reads the runtime platform, then the UA.
10469
+ const isMac = ideHostIsMacos()
10470
+
10471
+ const actions = []
10472
+ if (busy) {
10473
+ actions.push(h('span', { key: 'busy', className: 'iw-shot-busy' }, tr('shotBusy')))
10474
+ } else if (needsPermission) {
10475
+ if (isMac) actions.push(h('button', { key: 'settings', type: 'button', className: 'iw-shot-primary', onClick: onOpenSettings }, tr('shotOpenSettings')))
10476
+ actions.push(h('button', { key: 'retry', type: 'button', className: 'iw-shot-button', onClick: onRetry }, tr('shotRetry')))
10477
+ actions.push(h('button', { key: 'close', type: 'button', className: 'iw-shot-button', onClick: onClose }, tr('setupClose')))
10478
+ } else if (failed) {
10479
+ actions.push(h('button', { key: 'retry', type: 'button', className: 'iw-shot-primary', onClick: onRetry }, tr('shotRetry')))
10480
+ actions.push(h('button', { key: 'close', type: 'button', className: 'iw-shot-button', onClick: onClose }, tr('setupClose')))
10481
+ } else {
10482
+ actions.push(h('button', { key: 'jump', type: 'button', className: 'iw-shot-primary', onClick: onJump }, tr('shotJump')))
10483
+ actions.push(h('button', { key: 'keep', type: 'button', className: 'iw-shot-button', onClick: onKeep }, tr('shotKeep')))
10484
+ actions.push(h('button', { key: 'close', type: 'button', className: 'iw-shot-button', onClick: onClose }, tr('setupClose')))
10485
+ }
10486
+
10487
+ const guide = needsPermission
10488
+ ? (isMac ? tr('shotNoPermissionMac') : tr('shotNoPermissionWindows'))
10489
+ : failed ? (shot.message === '' ? tr('shotFailed') : `${tr('shotFailed')}:${shot.message}`) : ''
10490
+
10491
+ return h('div', {
10492
+ className: 'iw-shot',
10493
+ onPointerDown: (event) => event.stopPropagation(),
10494
+ }, [
10495
+ h('div', { key: 'title', className: 'iw-shot-title' }, needsPermission ? tr('shotNoPermissionTitle') : tr('shotTitle')),
10496
+ guide === '' ? null : h('div', { key: 'guide', className: 'iw-shot-guide' }, guide),
10497
+ shot.dataUrl === undefined || shot.dataUrl === ''
10498
+ ? null
10499
+ : h('img', { key: 'preview', className: 'iw-shot-preview', src: shot.dataUrl, alt: tr('shotPreview') }),
10500
+ h('div', { key: 'actions', className: 'iw-shot-actions' }, actions),
10501
+ ])
10502
+ }
10503
+
10224
10504
  // ---- 90-apply.js ---------------------------------------------------------
10225
10505
  /**
10226
10506
  * Client activation.
@@ -10518,6 +10798,52 @@ function apply(ctx) {
10518
10798
  return chipped === true ? 'chip' : 'plain'
10519
10799
  }
10520
10800
 
10801
+ /**
10802
+ * Screenshot flow.
10803
+ *
10804
+ * 1. capture in the Host (OS built-in tool, no permission on Windows, Screen
10805
+ * Recording on macOS);
10806
+ * 2. show the preview with the two choices;
10807
+ * 3. "截图并跳转会话" returns to the conversation and *pastes* the image, so the
10808
+ * draft's text and attachments are untouched; "只截图" puts it on the system
10809
+ * clipboard and keeps the file.
10810
+ */
10811
+ async function startScreenshot() {
10812
+ store.setScreenshot({ phase: 'running' })
10813
+ openPanel()
10814
+ const result = await ideShotRequest({})
10815
+ if (!result.ok) {
10816
+ store.setScreenshot({ phase: 'error', code: result.code, message: result.message })
10817
+ return
10818
+ }
10819
+ store.setScreenshot({ phase: 'ready', ...result.value })
10820
+ }
10821
+
10822
+ async function screenshotJump() {
10823
+ const shot = store.getState().screenshot
10824
+ store.setScreenshot(null)
10825
+ backToChat()
10826
+ if (shot?.dataUrl === undefined || shot.dataUrl === '') return
10827
+ const pasted = await idePasteScreenshot(shot.dataUrl)
10828
+ store.setNotice(pasted ? translate('shotAttached') : translate('shotNoEditor'))
10829
+ }
10830
+
10831
+ async function screenshotKeep() {
10832
+ const shot = store.getState().screenshot
10833
+ store.setScreenshot(null)
10834
+ if (shot?.path === undefined) return
10835
+ const copied = await ideShotRequest({ copyOf: shot.path })
10836
+ store.setNotice(copied.ok ? `${translate('shotCopied')}: ${shot.path}` : translate('shotFailed'))
10837
+ }
10838
+
10839
+ async function screenshotOpenSettings() {
10840
+ const result = await ideOpenScreenPermission()
10841
+ if (result.opened !== true) store.setNotice(translate('shotOpenFailed'))
10842
+ }
10843
+
10844
+ const screenshotClose = () => store.setScreenshot(null)
10845
+ const screenshotRetry = () => { void startScreenshot() }
10846
+
10521
10847
  /**
10522
10848
  * Back to the conversation with the reference appended to the draft.
10523
10849
  *
@@ -10590,6 +10916,7 @@ function apply(ctx) {
10590
10916
  { id: 'jump', labelKey: 'paletteActionJump', run: () => store.setJumpEnabled(!store.getState().jumpEnabled) },
10591
10917
  { id: 'closeTabs', labelKey: 'paletteActionCloseTabs', run: () => store.closeAllTabs() },
10592
10918
  { id: 'back', labelKey: 'paletteActionBack', run: () => backToChat() },
10919
+ { id: 'screenshot', labelKey: 'paletteActionScreenshot', run: () => { void startScreenshot() } },
10593
10920
  { id: 'licenseRelogin', labelKey: 'paletteActionLicenseRelogin', run: () => { void reloginLicense() } },
10594
10921
  { id: 'diagnostics', labelKey: 'paletteActionDiagnostics', run: () => { void exportDiagnostics() } },
10595
10922
  ]
@@ -10916,6 +11243,11 @@ function apply(ctx) {
10916
11243
  navigate,
10917
11244
  paletteActions,
10918
11245
  onReferenceToChat: referenceToChat,
11246
+ onScreenshotJump: screenshotJump,
11247
+ onScreenshotKeep: screenshotKeep,
11248
+ onScreenshotRetry: screenshotRetry,
11249
+ onScreenshotOpenSettings: screenshotOpenSettings,
11250
+ onScreenshotClose: screenshotClose,
10919
11251
  }),
10920
11252
  }, IdePanel))
10921
11253
  ctx.effect(() => {
@@ -10933,6 +11265,11 @@ function apply(ctx) {
10933
11265
  navigate,
10934
11266
  paletteActions,
10935
11267
  onReferenceToChat: referenceToChat,
11268
+ onScreenshotJump: screenshotJump,
11269
+ onScreenshotKeep: screenshotKeep,
11270
+ onScreenshotRetry: screenshotRetry,
11271
+ onScreenshotOpenSettings: screenshotOpenSettings,
11272
+ onScreenshotClose: screenshotClose,
10936
11273
  }),
10937
11274
  }, IdePanel))
10938
11275
  mainRegistered = true
@@ -11097,6 +11434,7 @@ function apply(ctx) {
11097
11434
  event.preventDefault()
11098
11435
  if (command.action === 'toggle') openPanel()
11099
11436
  else if (command.action === 'back') selectPanel(null)
11437
+ else if (command.action === 'screenshot') void startScreenshot()
11100
11438
  return
11101
11439
  }
11102
11440
  }, true)
package/index.js CHANGED
@@ -45,6 +45,8 @@ const ROUTE_TEXT = '/dsh-ide/text'
45
45
  const ROUTE_LICENSE = '/dsh-ide/license'
46
46
  const ROUTE_DIAG = '/dsh-ide/diagnostics'
47
47
  const ROUTE_THEME = '/dsh-ide/theme'
48
+ const ROUTE_SCREENSHOT = '/dsh-ide/screenshot'
49
+ const ROUTE_SCREEN_PERMISSION = '/dsh-ide/screen-permission'
48
50
 
49
51
  /** Where this file lives: the themes sit next to it, not in the profile. */
50
52
  const PLUGIN_ROOT = fileURLToPath(new URL('.', import.meta.url))
@@ -796,6 +798,168 @@ export function themeCss(id) {
796
798
  }
797
799
  }
798
800
 
801
+ /**
802
+ * Run a one-shot command and collect its output.
803
+ *
804
+ * Screenshot and clipboard helpers are short-lived OS tools; the same shell
805
+ * rule as the licence verbs applies on Windows (a `.bat`/`.cmd` needs a shell).
806
+ */
807
+ function runProcess(command, args, timeoutMs) {
808
+ return new Promise((resolve) => {
809
+ let child
810
+ try {
811
+ child = spawn(command, args, {
812
+ stdio: ['ignore', 'pipe', 'pipe'],
813
+ shell: platform.needsShell(command),
814
+ })
815
+ } catch (error) {
816
+ resolve({ code: -1, output: String(error?.message ?? error) })
817
+ return
818
+ }
819
+ let output = ''
820
+ const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs)
821
+ const collect = (chunk) => {
822
+ output += String(chunk)
823
+ if (output.length > 20000) output = output.slice(-20000)
824
+ }
825
+ child.stdout.on('data', collect)
826
+ child.stderr.on('data', collect)
827
+ child.on('error', (error) => {
828
+ clearTimeout(timer)
829
+ resolve({ code: -1, output: String(error?.message ?? error) })
830
+ })
831
+ child.on('close', (code) => {
832
+ clearTimeout(timer)
833
+ resolve({ code: code ?? -1, output })
834
+ })
835
+ })
836
+ }
837
+
838
+ /**
839
+ * Whether a failed capture looks like a missing screen-recording grant.
840
+ *
841
+ * `screencapture` says "could not create image from display" when macOS denied
842
+ * the permission; the wording is the only signal available, so it is pinned by
843
+ * a test rather than being an inline regex.
844
+ */
845
+ export function screenshotLooksPermissionDenied(output) {
846
+ return /could not create image|not permitt|permission|denied|屏幕录制|隐私/i.test(String(output ?? ''))
847
+ }
848
+
849
+ /**
850
+ * Capture the screen into a temp PNG.
851
+ *
852
+ * `copy` also puts it on the system clipboard, which is what "只截图" hands the
853
+ * user. The data URL is what the panel previews and what gets pasted into the
854
+ * conversation, so the client never needs a file:// URL.
855
+ */
856
+ /** The capture is shrunk to a 1080p-class JPEG (the platform sets the long edge). */
857
+ const IDE_SCREENSHOT_MAX_BYTES = 1024 * 1024
858
+ /** JPEG quality ladder: the first result under the budget wins. */
859
+ const IDE_SCREENSHOT_QUALITIES = [80, 70, 60, 50]
860
+
861
+ /**
862
+ * Shrink a capture to a 1080p-class JPEG under 1 MB.
863
+ *
864
+ * A Retina full-screen capture is several megabytes and no chat needs that. The
865
+ * ladder stops at the first size that fits, so a mostly-flat screen keeps its
866
+ * quality while a text-heavy one steps down. Returns the file that was written,
867
+ * or the PNG when no quality produced a file (the caller still has an image).
868
+ */
869
+ async function optimizeScreenshot(pngPath) {
870
+ const jpegPath = pngPath.replace(/\.png$/i, '') + '.jpg'
871
+ let best = null
872
+ for (const quality of IDE_SCREENSHOT_QUALITIES) {
873
+ const { command, args } = platform.imageOptimizeCommand(pngPath, jpegPath, quality)
874
+ const { code, output } = await runProcess(command, args, 20000)
875
+ let bytes = 0
876
+ try {
877
+ bytes = statSync(jpegPath).size
878
+ } catch {
879
+ bytes = 0
880
+ }
881
+ if (code !== 0 || bytes === 0) {
882
+ logEvent('warn', 'screenshot', `optimise failed at quality ${quality}`, output.trim())
883
+ continue
884
+ }
885
+ best = { path: jpegPath, bytes, quality }
886
+ if (bytes <= IDE_SCREENSHOT_MAX_BYTES) break
887
+ }
888
+ return best
889
+ }
890
+
891
+ export async function captureScreen(payload) {
892
+ // "只截图" after a capture only needs the existing file on the clipboard.
893
+ if (typeof payload?.copyOf === 'string' && payload.copyOf !== '') {
894
+ const existing = payload.copyOf
895
+ const clipboard = platform.clipboardImageCommand(existing)
896
+ const copied = await runProcess(clipboard.command, clipboard.args, 20000)
897
+ if (copied.code !== 0) {
898
+ logEvent('warn', 'screenshot', 'clipboard copy failed', copied.output)
899
+ throw new RouteError(500, 'clipboard-failed', copied.output.trim() || 'clipboard copy failed')
900
+ }
901
+ return { path: existing, copied: true, bytes: 0, dataUrl: '' }
902
+ }
903
+ const target = join(tmpdir(), `dsh-ide-shot-${Date.now()}.png`)
904
+ const { command, args } = platform.screenshotCommand(target)
905
+ const { code, output } = await runProcess(command, args, 20000)
906
+ let bytes = 0
907
+ try {
908
+ bytes = statSync(target).size
909
+ } catch {
910
+ bytes = 0
911
+ }
912
+ if (code !== 0 || bytes === 0) {
913
+ if (screenshotLooksPermissionDenied(output)) {
914
+ throw new RouteError(403, 'no-screen-permission', output.trim() || 'screen recording is not permitted')
915
+ }
916
+ throw new RouteError(500, 'capture-failed', output.trim() || `screenshot exited ${code}`)
917
+ }
918
+ if (payload?.copy === true) {
919
+ const clipboard = platform.clipboardImageCommand(target)
920
+ const copied = await runProcess(clipboard.command, clipboard.args, 20000)
921
+ if (copied.code !== 0) {
922
+ logEvent('warn', 'screenshot', 'clipboard copy failed', copied.output)
923
+ }
924
+ }
925
+ // A raw screen is far too big for a chat attachment: shrink it before it is
926
+ // ever shown or pasted, and keep only the small file on disk.
927
+ const optimized = await optimizeScreenshot(target)
928
+ try {
929
+ rmSync(target, { force: true })
930
+ } catch {
931
+ /* the OS will clean the temp dir anyway */
932
+ }
933
+ if (optimized === null) {
934
+ throw new RouteError(500, 'capture-failed', 'the capture could not be optimised')
935
+ }
936
+ const mime = /\.jpe?g$/i.test(optimized.path) ? 'image/jpeg' : 'image/png'
937
+ const dataUrl = `data:${mime};base64,${readFileSync(optimized.path).toString('base64')}`
938
+ logEvent('info', 'screenshot', 'captured', {
939
+ bytes: optimized.bytes,
940
+ quality: optimized.quality,
941
+ path: optimized.path,
942
+ })
943
+ // The temp file stays for "只截图" (the notice shows the path).
944
+ return { path: optimized.path, bytes: optimized.bytes, quality: optimized.quality, dataUrl }
945
+ }
946
+
947
+ /**
948
+ * Open the OS place where screen recording is granted.
949
+ *
950
+ * Only macOS gates capture behind a permission; on Windows the answer says so
951
+ * instead of opening a settings window that does not exist.
952
+ */
953
+ export async function openScreenPermission() {
954
+ if (platform.name !== 'mac') {
955
+ return { opened: false, hint: platform.name === 'windows' ? 'windows-no-permission' : 'unsupported' }
956
+ }
957
+ const url = 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'
958
+ const opened = platform.openUrlCommand(url)
959
+ const { code } = await runProcess(opened.command, opened.args, 10000)
960
+ return { opened: code === 0, hint: 'macos-screen-recording' }
961
+ }
962
+
799
963
  /** Serve one palette as CSS; the ETag keeps a reopened panel from refetching. */
800
964
  function createThemeHandler() {
801
965
  return async (request, response) => {
@@ -1287,7 +1451,7 @@ function createHandler(ctx) {
1287
1451
  return
1288
1452
  }
1289
1453
  pathname = new URL(request.url ?? '/', 'http://dsh-ide.internal').pathname
1290
- if (pathname !== ROUTE_LSP && pathname !== ROUTE_GREP && pathname !== ROUTE_DIFF && pathname !== ROUTE_JAR && pathname !== ROUTE_STATUS && pathname !== ROUTE_BLAME && pathname !== ROUTE_DOCTOR && pathname !== ROUTE_KINDS && pathname !== ROUTE_LOG && pathname !== ROUTE_REFS && pathname !== ROUTE_PATCH && pathname !== ROUTE_TEXT && pathname !== ROUTE_LICENSE && pathname !== ROUTE_DIAG) {
1454
+ if (pathname !== ROUTE_LSP && pathname !== ROUTE_GREP && pathname !== ROUTE_DIFF && pathname !== ROUTE_JAR && pathname !== ROUTE_STATUS && pathname !== ROUTE_BLAME && pathname !== ROUTE_DOCTOR && pathname !== ROUTE_KINDS && pathname !== ROUTE_LOG && pathname !== ROUTE_REFS && pathname !== ROUTE_PATCH && pathname !== ROUTE_TEXT && pathname !== ROUTE_LICENSE && pathname !== ROUTE_DIAG && pathname !== ROUTE_SCREENSHOT && pathname !== ROUTE_SCREEN_PERMISSION) {
1291
1455
  writeJson(response, 404, { ok: false, error: { code: 'not-found', message: 'unknown route' } })
1292
1456
  return
1293
1457
  }
@@ -1318,6 +1482,10 @@ function createHandler(ctx) {
1318
1482
  ? await licenseCommand(payload)
1319
1483
  : pathname === ROUTE_DIAG
1320
1484
  ? diagnosticsReport(payload)
1485
+ : pathname === ROUTE_SCREENSHOT
1486
+ ? await captureScreen(payload)
1487
+ : pathname === ROUTE_SCREEN_PERMISSION
1488
+ ? await openScreenPermission()
1321
1489
  : await query(ctx, payload)
1322
1490
  writeJson(response, 200, { ok: true, value })
1323
1491
  } catch (error) {
@@ -1409,4 +1577,14 @@ export function apply(ctx) {
1409
1577
  path: ROUTE_THEME,
1410
1578
  handler: createThemeHandler(),
1411
1579
  }), 'dsh-ide-window: theme route')
1580
+ ctx.effect(() => ctx.webServer.register({
1581
+ kind: 'prefix',
1582
+ path: ROUTE_SCREENSHOT,
1583
+ handler,
1584
+ }), 'dsh-ide-window: screenshot route')
1585
+ ctx.effect(() => ctx.webServer.register({
1586
+ kind: 'prefix',
1587
+ path: ROUTE_SCREEN_PERMISSION,
1588
+ handler,
1589
+ }), 'dsh-ide-window: screen permission route')
1412
1590
  }
package/locale/en.json CHANGED
@@ -228,5 +228,22 @@
228
228
  "theme_github_light": "GitHub Light",
229
229
  "theme_atom_one_light": "Atom One Light",
230
230
  "theme_solarized_light": "Solarized Light",
231
- "theme_intellij_light": "IntelliJ Light"
231
+ "theme_intellij_light": "IntelliJ Light",
232
+ "shortcutScreenshot": "Screenshot (can jump to chat)",
233
+ "shotTitle": "Screenshot taken",
234
+ "shotBusy": "Capturing…",
235
+ "shotPreview": "Screenshot preview",
236
+ "shotJump": "Screenshot and jump to chat",
237
+ "shotKeep": "Screenshot only (copy to clipboard)",
238
+ "shotRetry": "Retry",
239
+ "shotFailed": "Screenshot failed",
240
+ "shotNoPermissionTitle": "Cannot capture: Screen Recording permission is missing",
241
+ "shotNoPermissionMac": "Enable DeepSeek Harness under System Settings → Privacy & Security → Screen Recording, then quit and reopen the app (the grant only applies after a relaunch).",
242
+ "shotNoPermissionWindows": "Windows needs no permission for this. Check that the screen is unlocked and no remote-desktop session or policy blocks capture, then retry.",
243
+ "shotOpenSettings": "Open System Settings",
244
+ "shotAttached": "Screenshot inserted into the conversation",
245
+ "shotCopied": "Screenshot copied to the clipboard",
246
+ "shotNoEditor": "Composer not found: the screenshot is on the clipboard, press ⌘V",
247
+ "shotOpenFailed": "Could not open System Settings. Open it manually: Privacy & Security → Screen Recording",
248
+ "paletteActionScreenshot": "Take a screenshot"
232
249
  }
package/locale/zh.json CHANGED
@@ -228,5 +228,22 @@
228
228
  "theme_github_light": "GitHub 浅色",
229
229
  "theme_atom_one_light": "Atom One 浅色",
230
230
  "theme_solarized_light": "Solarized 浅色",
231
- "theme_intellij_light": "IntelliJ 浅色"
231
+ "theme_intellij_light": "IntelliJ 浅色",
232
+ "shortcutScreenshot": "截图(可跳转会话)",
233
+ "shotTitle": "截图完成",
234
+ "shotBusy": "正在截图…",
235
+ "shotPreview": "截图预览",
236
+ "shotJump": "截图并跳转会话",
237
+ "shotKeep": "只截图(复制到剪贴板)",
238
+ "shotRetry": "重试",
239
+ "shotFailed": "截图失败",
240
+ "shotNoPermissionTitle": "无法截图:缺少屏幕录制权限",
241
+ "shotNoPermissionMac": "请在「系统设置 → 隐私与安全性 → 屏幕录制」里勾选 DeepSeek Harness,然后完全退出并重新打开应用(授权后必须重启才生效)。",
242
+ "shotNoPermissionWindows": "Windows 截图不需要授权。请确认没有锁屏、远程桌面占用或企业策略拦截,然后重试。",
243
+ "shotOpenSettings": "打开系统设置",
244
+ "shotAttached": "已把截图插入对话",
245
+ "shotCopied": "截图已复制到剪贴板",
246
+ "shotNoEditor": "没找到对话框:截图已复制到剪贴板,按 ⌘V 粘贴",
247
+ "shotOpenFailed": "打不开系统设置,请手动打开:系统设置 → 隐私与安全性 → 屏幕录制",
248
+ "paletteActionScreenshot": "截图"
232
249
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ide-window",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "IDEA-style code workspace for DeepSeek Harness: a centre panel with a workspace file tree, editor tabs and live-updating source, while the left navigation column hides.",
5
5
  "type": "module",
6
6
  "icon": "icon.svg",
@@ -30,7 +30,7 @@
30
30
  "scripts": {
31
31
  "build": "node build.mjs",
32
32
  "check": "node --check index.js && node --check client.js",
33
- "test": "node test/platform.mjs && node test/diagnostics.mjs && node test/status.mjs && node test/harness.mjs && node test/inference.mjs && node test/maven.mjs && node test/theme.mjs"
33
+ "test": "node test/platform.mjs && node test/diagnostics.mjs && node test/status.mjs && node test/harness.mjs && node test/inference.mjs && node test/maven.mjs && node test/theme.mjs && node test/screenshot.mjs"
34
34
  },
35
35
  "dsh": {
36
36
  "bundle": {
@@ -28,6 +28,12 @@
28
28
  * @property {string[]} ripgrepSuffixes Binary paths inside the bundled packages.
29
29
  * @property {string[]} serverLauncherNames Launcher file names, in try order.
30
30
  * @property {(path: string) => boolean} needsShell `spawn` needs `shell: true`
31
+ * @property {(path: string) => {command: string, args: string[]}} screenshotCommand
32
+ * Capture the whole screen into that PNG with an OS built-in tool.
33
+ * @property {(input: string, output: string, quality: number) => {command: string, args: string[]}} imageOptimizeCommand
34
+ * Shrink that PNG to a 1080p-class JPEG (long edge 1920) at `quality`.
35
+ * @property {(path: string) => {command: string, args: string[]}} clipboardImageCommand
36
+ * Put that image file on the system clipboard.
31
37
  * for this path (Windows blocks `.bat`/`.cmd` without it since CVE-2024-27980).
32
38
  * @property {(url: string) => { command: string, args: string[] }} openUrlCommand
33
39
  */
@@ -43,4 +49,7 @@ export const PLATFORM_METHODS = [
43
49
  'serverLauncherNames',
44
50
  'needsShell',
45
51
  'openUrlCommand',
52
+ 'screenshotCommand',
53
+ 'imageOptimizeCommand',
54
+ 'clipboardImageCommand',
46
55
  ]
package/platform/macos.js CHANGED
@@ -27,4 +27,23 @@ export const macPlatform = {
27
27
  serverLauncherNames: ['intellij-server'],
28
28
  needsShell: () => false,
29
29
  openUrlCommand: (url) => ({ command: 'open', args: [url] }),
30
+ // Both tools ship with macOS: `screencapture` writes the PNG and AppleScript
31
+ // puts it on the pasteboard, so nothing has to be installed.
32
+ screenshotCommand: (path) => ({ command: 'screencapture', args: ['-x', '-t', 'png', String(path ?? '')] }),
33
+ // `sips` ships with macOS: `-Z` fits the long edge and `-s formatOptions` is
34
+ // the JPEG quality. A Retina capture is 5120×2880; 1080p is plenty for chat.
35
+ imageOptimizeCommand: (input, output, quality) => ({
36
+ command: 'sips',
37
+ args: [
38
+ '-Z', '1920',
39
+ '-s', 'format', 'jpeg',
40
+ '-s', 'formatOptions', String(quality),
41
+ String(input ?? ''),
42
+ '--out', String(output ?? ''),
43
+ ],
44
+ }),
45
+ clipboardImageCommand: (path) => ({
46
+ command: 'osascript',
47
+ args: ['-e', `set the clipboard to (read (POSIX file "${String(path ?? '')}") as «class PNGf»)`],
48
+ }),
30
49
  }
@@ -38,4 +38,70 @@ export const windowsPlatform = {
38
38
  // goes through a shell layer; `cmd /c start ""` is the documented form and
39
39
  // keeps the empty title argument that `start` needs for a quoted URL.
40
40
  openUrlCommand: (url) => ({ command: 'cmd', args: ['/c', 'start', '', url] }),
41
+ // .NET (part of Windows) captures the virtual screen and fills the clipboard,
42
+ // so no third-party tool is needed. The script writes a real PNG file.
43
+ screenshotCommand: (path) => ({
44
+ command: 'powershell.exe',
45
+ args: ['-NoProfile', '-NonInteractive', '-Command', windowsScreenshotScript(path)],
46
+ }),
47
+ imageOptimizeCommand: (input, output, quality) => ({
48
+ command: 'powershell.exe',
49
+ args: ['-NoProfile', '-NonInteractive', '-Command', windowsOptimizeScript(input, output, quality)],
50
+ }),
51
+ clipboardImageCommand: (path) => ({
52
+ command: 'powershell.exe',
53
+ args: ['-NoProfile', '-NonInteractive', '-STA', '-Command', windowsClipboardScript(path)],
54
+ }),
55
+ }
56
+
57
+ /** The PowerShell that grabs every monitor into one PNG. */
58
+ function windowsScreenshotScript(path) {
59
+ const target = String(path ?? '').replace(/'/g, "''")
60
+ return [
61
+ 'Add-Type -AssemblyName System.Windows.Forms,System.Drawing',
62
+ '$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen',
63
+ '$bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height',
64
+ '$graphics = [System.Drawing.Graphics]::FromImage($bitmap)',
65
+ '$graphics.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bitmap.Size)',
66
+ `$bitmap.Save('${target}', [System.Drawing.Imaging.ImageFormat]::Png)`,
67
+ '$graphics.Dispose()',
68
+ '$bitmap.Dispose()',
69
+ ].join('; ')
70
+ }
71
+
72
+ /** The PowerShell that shrinks a capture to a 1080p-class JPEG. */
73
+ function windowsOptimizeScript(input, output, quality) {
74
+ const source = String(input ?? '').replace(/'/g, "''")
75
+ const target = String(output ?? '').replace(/'/g, "''")
76
+ const level = Math.min(100, Math.max(10, Number.isFinite(quality) ? quality : 80))
77
+ return [
78
+ 'Add-Type -AssemblyName System.Drawing',
79
+ `$source = [System.Drawing.Image]::FromFile('${source}')`,
80
+ '$long = [Math]::Max($source.Width, $source.Height)',
81
+ '$scale = [Math]::Min(1.0, 1920 / $long)',
82
+ '$width = [int][Math]::Round($source.Width * $scale)',
83
+ '$height = [int][Math]::Round($source.Height * $scale)',
84
+ '$bitmap = New-Object System.Drawing.Bitmap $width, $height',
85
+ '$graphics = [System.Drawing.Graphics]::FromImage($bitmap)',
86
+ '$graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic',
87
+ '$graphics.DrawImage($source, 0, 0, $width, $height)',
88
+ '$codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq "image/jpeg" }',
89
+ '$parameters = New-Object System.Drawing.Imaging.EncoderParameters(1)',
90
+ `$parameters.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, [long]${level})`,
91
+ `$bitmap.Save('${target}', $codec, $parameters)`,
92
+ '$graphics.Dispose()',
93
+ '$bitmap.Dispose()',
94
+ '$source.Dispose()',
95
+ ].join('; ')
96
+ }
97
+
98
+ /** The PowerShell that puts an existing PNG on the clipboard. */
99
+ function windowsClipboardScript(path) {
100
+ const target = String(path ?? '').replace(/'/g, "''")
101
+ return [
102
+ 'Add-Type -AssemblyName System.Windows.Forms,System.Drawing',
103
+ `$image = [System.Drawing.Image]::FromFile('${target}')`,
104
+ '[System.Windows.Forms.Clipboard]::SetImage($image)',
105
+ '$image.Dispose()',
106
+ ].join('; ')
41
107
  }