dsh-composer-screenshot 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tizuld486-netizen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,108 @@
1
- # Temporary Holding Version
1
+ # dsh-composer-screenshot
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A camera button in the [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) composer.
4
+ Click it, drag a box over any part of your desktop, and the picture is attached to the current
5
+ Session as a normal image — right next to the text you are about to send.
6
+
7
+ ![camera button in the composer](docs/composer.png)
8
+
9
+ ## Features
10
+
11
+ - **📷 button in the composer**, top-right corner of the input card, next to the send area.
12
+ - **Select any area** of any screen: the capture helper dims the desktop and lets you drag a
13
+ rectangle; press `Esc` to cancel.
14
+ - **Right-click** the button to grab every display at once.
15
+ - **The image becomes a real attachment**, so the model sees it exactly like a pasted screenshot,
16
+ and you can still type or add files before sending.
17
+ - **Slash command** `/screenshot [region|full]` for the same thing from the keyboard.
18
+ - Captures are written as PNG into `%TEMP%\dsh-screenshots\` (or `$TMPDIR/dsh-screenshots`),
19
+ and files older than 7 days are removed automatically.
20
+
21
+ ## Requirements
22
+
23
+ | Platform | Capture backend | Notes |
24
+ | --- | --- | --- |
25
+ | Windows | `capture.ps1` (PowerShell 5.1+ / `pwsh`) | Draws its own selection overlay; DPI aware, multi-monitor |
26
+ | macOS | `screencapture` | Built into macOS; selection is the system UI |
27
+ | Linux | `maim`, `gnome-screenshot`, `spectacle` or `scrot` | First one found on `PATH` wins |
28
+
29
+ Requires DeepSeek Harness **0.2.2-rc.5** or newer (`engines.dsh`).
30
+
31
+ ## Install
32
+
33
+ From a local clone:
34
+
35
+ ```bash
36
+ git clone https://github.com/tizuld486-netizen/dsh-screenshot.git
37
+ ```
38
+
39
+ Then ask DSH to install the folder as a bundle (Plugin manager → install from folder, or):
40
+
41
+ ```text
42
+ plugin_manager install_bundle target: <absolute path to the cloned folder>
43
+ ```
44
+
45
+ Pinned to a commit, straight from GitHub:
46
+
47
+ ```text
48
+ plugin_manager install_bundle target: git+https://github.com/tizuld486-netizen/dsh-screenshot.git#<commit>
49
+ ```
50
+
51
+ Restart the DeepSeek Harness desktop app afterwards — the Host half registers the
52
+ `/screenshot` command at startup. Open a Session and the camera button is already there.
53
+
54
+ ## Usage
55
+
56
+ | Action | Result |
57
+ | --- | --- |
58
+ | Click 📷 | Dim the desktop, drag a rectangle, release |
59
+ | `Esc` while selecting | Cancel, nothing is attached |
60
+ | Right-click 📷 | Capture every display |
61
+ | `/screenshot` | Same as clicking the button |
62
+ | `/screenshot full` | Same as right-clicking |
63
+
64
+ While a capture is in flight the button spins and ignores further clicks.
65
+
66
+ ## How it works
67
+
68
+ The browser half cannot read the desktop, and the Electron shell ships no `desktopCapturer`,
69
+ so the pixels come from the Host process:
70
+
71
+ 1. Client calls the Host command `/screenshot region` through the remote command channel.
72
+ 2. Host runs the platform capture helper and saves a PNG.
73
+ 3. Host answers with the absolute path of that PNG.
74
+ 4. Client reads the bytes with `workspaceFiles.readBytes` and creates a composer draft with
75
+ `conversation.createDrafts`, then `input.addAttachments` puts it in the input box.
76
+
77
+ Nothing leaves the machine; the helper only writes a local file.
78
+
79
+ ## Security notes
80
+
81
+ - Windows runs PowerShell with `-ExecutionPolicy Bypass`, scoped to that one child process —
82
+ it does **not** change your machine policy.
83
+ - The helper has no network code; it captures the screen, writes one PNG and exits.
84
+ - Captures live in your temp directory and are pruned after 7 days. Delete the folder any time.
85
+
86
+ ## Uninstall
87
+
88
+ ```text
89
+ plugin_manager remove_bundle target: dsh-composer-screenshot
90
+ ```
91
+
92
+ Then restart the app. Nothing else is touched; the temp folder can be removed by hand.
93
+
94
+ ## 中文说明
95
+
96
+ 在输入框右上角加一个 📷 按钮:点一下,桌面变暗,拖动框选任意区域,图片直接进入当前会话的
97
+ 输入框;右键按钮 = 整屏截取;也可以在会话里用 `/screenshot` 或 `/screenshot full`。
98
+
99
+ 安装:把本仓库克隆到本地,用 `plugin_manager install_bundle` 指定这个文件夹,然后重启 DSH;
100
+ 客户端部分改完刷新页面即可生效,宿主部分(命令注册)必须重启。
101
+
102
+ 支持 Windows(自带 PowerShell 助手,含框选界面)、macOS(系统 `screencapture`)、Linux
103
+ (`maim` / `gnome-screenshot` / `spectacle` / `scrot` 任一)。截图落在系统临时目录的
104
+ `dsh-screenshots/` 下,7 天后自动清理。除写入本地 PNG 外没有任何网络行为。
105
+
106
+ ## License
107
+
108
+ MIT © tizuld486-netizen
package/capture.ps1 ADDED
@@ -0,0 +1,159 @@
1
+ # DSH screenshot helper: grab a screen region (or the whole virtual desktop)
2
+ # and save it as a PNG. The last stdout line is a compact JSON result:
3
+ # {"ok":true,"path":"...","width":1280,"height":720}
4
+ # {"ok":false,"cancelled":true}
5
+ param(
6
+ [ValidateSet('region', 'full', 'window')][string]$Mode = 'region',
7
+ [string]$Out
8
+ )
9
+
10
+ $ErrorActionPreference = 'Stop'
11
+
12
+ Add-Type -AssemblyName System.Windows.Forms
13
+ Add-Type -AssemblyName System.Drawing
14
+ Add-Type -Namespace DshShot -Name Native -MemberDefinition '[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();'
15
+
16
+ # A Form subclass: DoubleBuffered is protected on Control, so the overlay has to
17
+ # ask for double buffering from inside the type instead of from the script.
18
+ Add-Type -ReferencedAssemblies System.Windows.Forms, System.Drawing -TypeDefinition @'
19
+ using System.Windows.Forms;
20
+
21
+ public class DshOverlayForm : Form
22
+ {
23
+ public DshOverlayForm()
24
+ {
25
+ SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
26
+ }
27
+ }
28
+ '@
29
+ [DshShot.Native]::SetProcessDPIAware() | Out-Null
30
+ [System.Windows.Forms.Application]::EnableVisualStyles()
31
+
32
+ function Emit([bool]$ok, [bool]$cancelled, [int]$width, [int]$height) {
33
+ $payload = [ordered]@{ ok = $ok; cancelled = $cancelled; width = $width; height = $height }
34
+ if ($ok) { $payload.path = $Out }
35
+ [Console]::Out.WriteLine(([pscustomobject]$payload | ConvertTo-Json -Compress))
36
+ }
37
+
38
+ if ([string]::IsNullOrWhiteSpace($Out)) {
39
+ [Console]::Out.WriteLine('{"ok":false,"cancelled":false,"error":"missing -Out"}')
40
+ exit 1
41
+ }
42
+
43
+ try {
44
+ $bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen
45
+ if ($bounds.Width -le 0 -or $bounds.Height -le 0) { throw 'no screen bounds reported' }
46
+
47
+ $full = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height, ([System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
48
+ $graphics = [System.Drawing.Graphics]::FromImage($full)
49
+ $graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $full.Size)
50
+ $graphics.Dispose()
51
+
52
+ if ($Mode -ne 'region') {
53
+ $full.Save($Out, [System.Drawing.Imaging.ImageFormat]::Png)
54
+ $full.Dispose()
55
+ Emit $true $false $bounds.Width $bounds.Height
56
+ exit 0
57
+ }
58
+
59
+ $script:origin = $null
60
+ $script:current = $null
61
+ $script:accepted = $false
62
+ $script:cancelled = $false
63
+
64
+ $form = New-Object DshOverlayForm
65
+ $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
66
+ $form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
67
+ $form.Bounds = New-Object System.Drawing.Rectangle($bounds.Left, $bounds.Top, $bounds.Width, $bounds.Height)
68
+ $form.TopMost = $true
69
+ $form.ShowInTaskbar = $false
70
+ $form.BackColor = [System.Drawing.Color]::Black
71
+ $form.Opacity = 0.3
72
+ $form.Cursor = [System.Windows.Forms.Cursors]::Cross
73
+ $form.KeyPreview = $true
74
+
75
+ $form.add_MouseDown({
76
+ param($sender, $event)
77
+ if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
78
+ $script:origin = $event.Location
79
+ $script:current = $event.Location
80
+ $sender.Invalidate()
81
+ }
82
+ })
83
+
84
+ $form.add_MouseMove({
85
+ param($sender, $event)
86
+ if ($null -ne $script:origin) {
87
+ $script:current = $event.Location
88
+ $sender.Invalidate()
89
+ }
90
+ })
91
+
92
+ $form.add_MouseUp({
93
+ param($sender, $event)
94
+ if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left -and $null -ne $script:origin) {
95
+ $script:current = $event.Location
96
+ $script:accepted = $true
97
+ $sender.Close()
98
+ }
99
+ })
100
+
101
+ $form.add_KeyDown({
102
+ param($sender, $event)
103
+ if ($event.KeyCode -eq [System.Windows.Forms.Keys]::Escape) {
104
+ $script:cancelled = $true
105
+ $sender.Close()
106
+ }
107
+ })
108
+
109
+ $form.add_Paint({
110
+ param($sender, $event)
111
+ if ($null -eq $script:origin -or $null -eq $script:current) { return }
112
+ $rect = New-Object System.Drawing.Rectangle(
113
+ [Math]::Min($script:origin.X, $script:current.X),
114
+ [Math]::Min($script:origin.Y, $script:current.Y),
115
+ [Math]::Abs($script:origin.X - $script:current.X),
116
+ [Math]::Abs($script:origin.Y - $script:current.Y))
117
+ if ($rect.Width -le 0 -or $rect.Height -le 0) { return }
118
+ $pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::FromArgb(255, 90, 150, 255)), 2
119
+ $event.Graphics.DrawRectangle($pen, $rect)
120
+ $pen.Dispose()
121
+ $font = New-Object System.Drawing.Font 'Segoe UI', 10
122
+ $label = '{0} x {1}' -f $rect.Width, $rect.Height
123
+ $labelY = if ($rect.Y -ge 26) { $rect.Y - 24 } else { $rect.Y + 6 }
124
+ $event.Graphics.DrawString($label, $font, [System.Drawing.Brushes]::White, ($rect.X + 4), $labelY)
125
+ $font.Dispose()
126
+ })
127
+
128
+ [void]$form.ShowDialog()
129
+ $form.Dispose()
130
+
131
+ if (-not $script:accepted) {
132
+ $full.Dispose()
133
+ Emit $false $true 0 0
134
+ exit 3
135
+ }
136
+
137
+ $x = [Math]::Min($script:origin.X, $script:current.X)
138
+ $y = [Math]::Min($script:origin.Y, $script:current.Y)
139
+ $w = [Math]::Abs($script:origin.X - $script:current.X)
140
+ $h = [Math]::Abs($script:origin.Y - $script:current.Y)
141
+
142
+ if ($w -lt 2 -or $h -lt 2) {
143
+ $full.Dispose()
144
+ Emit $false $true 0 0
145
+ exit 3
146
+ }
147
+
148
+ $crop = $full.Clone((New-Object System.Drawing.Rectangle($x, $y, $w, $h)), $full.PixelFormat)
149
+ $crop.Save($Out, [System.Drawing.Imaging.ImageFormat]::Png)
150
+ $crop.Dispose()
151
+ $full.Dispose()
152
+
153
+ Emit $true $false $w $h
154
+ exit 0
155
+ }
156
+ catch {
157
+ [Console]::Out.WriteLine(([pscustomobject]@{ ok = $false; cancelled = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress))
158
+ exit 1
159
+ }
package/client.js ADDED
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Client half of the screenshot bundle: a camera button floating in the
3
+ * composer card's top-right corner and the host round trip that turns the
4
+ * captured PNG into a composer attachment.
5
+ */
6
+ window.__ModuleLoader__.load({
7
+ id: 'dsh-composer-screenshot',
8
+ factory(require) {
9
+ const React = require('react')
10
+ const h = React.createElement
11
+
12
+ /** Locale namespace shared with the `locale` slot option. */
13
+ const NS = 'dsh-composer-screenshot'
14
+ const STYLE_ID = 'dsh-screenshot-style'
15
+
16
+ const DICTIONARIES = {
17
+ en: {
18
+ 'button.title': 'Screenshot: click to select an area, right-click for the whole screen',
19
+ 'button.label': 'Screenshot',
20
+ 'error.notReady': 'Screenshot plugin is not ready: the Session service is unavailable',
21
+ 'error.noChannel': 'The command channel is unavailable',
22
+ 'error.commandFailed': 'The screenshot command failed',
23
+ 'error.noCommand': '/screenshot is not registered on the Host',
24
+ 'error.incomplete': 'The screenshot did not finish',
25
+ 'error.noPath': 'The screenshot returned no file path',
26
+ 'error.readFailed': 'Could not read the screenshot file: {reason}',
27
+ 'error.readNoBytes': 'Could not read the screenshot file: the Host returned no bytes',
28
+ 'error.busy': 'The composer is busy, so the screenshot was not inserted',
29
+ },
30
+ zh: {
31
+ 'button.title': '截图:点击框选区域,右键截取全屏',
32
+ 'button.label': '截图',
33
+ 'error.notReady': '截图插件未就绪:会话服务不可用',
34
+ 'error.noChannel': '远程命令通道不可用',
35
+ 'error.commandFailed': '截图命令调用失败',
36
+ 'error.noCommand': 'Host 端未注册 /screenshot 命令',
37
+ 'error.incomplete': '截图未完成',
38
+ 'error.noPath': '截图没有返回文件路径',
39
+ 'error.readFailed': '读取截图文件失败:{reason}',
40
+ 'error.readNoBytes': '读取截图文件失败:Host 没有返回字节',
41
+ 'error.busy': '输入框正忙,截图未插入',
42
+ },
43
+ }
44
+
45
+ const CSS = `
46
+ .dsh-shot-slot {
47
+ position: absolute;
48
+ top: 6px;
49
+ right: 8px;
50
+ z-index: 2;
51
+ display: flex;
52
+ align-items: center;
53
+ justify-content: flex-end;
54
+ }
55
+ .dsh-shot {
56
+ display: grid;
57
+ flex: none;
58
+ place-items: center;
59
+ width: 26px;
60
+ height: 26px;
61
+ padding: 0;
62
+ border: none;
63
+ border-radius: 999px;
64
+ background: transparent;
65
+ color: var(--dsw-alias-label-tertiary, inherit);
66
+ opacity: 0.85;
67
+ cursor: pointer;
68
+ transition: background 120ms ease, color 120ms ease, opacity 120ms ease;
69
+ }
70
+ .dsh-shot:hover:not(:disabled) {
71
+ background: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, 0.16));
72
+ color: var(--dsw-alias-label-secondary, inherit);
73
+ opacity: 1;
74
+ }
75
+ .dsh-shot:focus-visible {
76
+ outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
77
+ outline-offset: -2px;
78
+ }
79
+ .dsh-shot:disabled {
80
+ cursor: default;
81
+ opacity: 0.45;
82
+ }
83
+ .dsh-shot svg {
84
+ display: block;
85
+ width: 15px;
86
+ height: 15px;
87
+ }
88
+ @keyframes dsh-shot-spin {
89
+ to { transform: rotate(360deg); }
90
+ }
91
+ .dsh-shot[data-busy='true'] svg {
92
+ animation: dsh-shot-spin 900ms linear infinite;
93
+ }
94
+ `
95
+
96
+ /** Install the small stylesheet once per page. */
97
+ function ensureStyle() {
98
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID) !== null) return
99
+ const style = document.createElement('style')
100
+ style.id = STYLE_ID
101
+ style.textContent = CSS
102
+ document.head.appendChild(style)
103
+ }
104
+
105
+ /** The outline camera the composer row already visually rhymes with. */
106
+ const CameraIcon = React.memo(function CameraIcon() {
107
+ return h('svg', {
108
+ viewBox: '0 0 24 24',
109
+ fill: 'none',
110
+ stroke: 'currentColor',
111
+ strokeWidth: 1.7,
112
+ strokeLinecap: 'round',
113
+ strokeLinejoin: 'round',
114
+ 'aria-hidden': true,
115
+ },
116
+ h('path', { d: 'M4 8.5h2.6l1.3-2h8.2l1.3 2H20a1.5 1.5 0 0 1 1.5 1.5v7A1.5 1.5 0 0 1 20 18.5H4A1.5 1.5 0 0 1 2.5 17v-7A1.5 1.5 0 0 1 4 8.5Z' }),
117
+ h('circle', { cx: 12, cy: 13.2, r: 3.2 }))
118
+ })
119
+
120
+ /** A quiet spinner: one arc that turns while the selection overlay is up. */
121
+ const SpinnerIcon = React.memo(function SpinnerIcon() {
122
+ return h('svg', { viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': true },
123
+ h('circle', { cx: 12, cy: 12, r: 8, stroke: 'currentColor', strokeWidth: 1.7, opacity: 0.25 }),
124
+ h('path', { d: 'M20 12a8 8 0 0 0-8-8', stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round' }))
125
+ })
126
+
127
+ /**
128
+ * Translate one key, falling back to the English source text.
129
+ * @param t - translator handed to slot components, when present.
130
+ * @param key - dictionary key.
131
+ * @param fallback - English text used when no translator is available.
132
+ * @returns the localized string.
133
+ */
134
+ function translate(t, key, fallback) {
135
+ try {
136
+ const text = typeof t === 'function' ? t(key) : undefined
137
+ return typeof text === 'string' && text.length > 0 && text !== key ? text : fallback
138
+ } catch {
139
+ return fallback
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Ask the Host for one capture, read the PNG it saved, and attach it.
145
+ * @param ctx - Client plugin context.
146
+ * @param sessionId - Session whose composer receives the image.
147
+ * @param conversation - Session-scoped conversation service.
148
+ * @param input - Session input facade.
149
+ * @param mode - `region` for a selection overlay, `full` for every display.
150
+ * @param t - translator for user-facing failures.
151
+ */
152
+ async function captureIntoSession(ctx, sessionId, conversation, input, mode, t) {
153
+ const remote = ctx.remote
154
+ const commands = remote?.commands
155
+ if (typeof commands?.execute !== 'function') throw new Error(translate(t, 'error.noChannel', DICTIONARIES.en['error.noChannel']))
156
+ const executed = await commands.execute(sessionId, `/screenshot ${mode}`, [])
157
+ if (!executed?.ok) throw new Error(executed?.error?.message ?? translate(t, 'error.commandFailed', DICTIONARIES.en['error.commandFailed']))
158
+ if (executed.value === undefined) throw new Error(translate(t, 'error.noCommand', DICTIONARIES.en['error.noCommand']))
159
+ const result = executed.value.result ?? {}
160
+ if (result.kind !== 'success') {
161
+ const text = typeof result.text === 'string' && result.text.length > 0
162
+ ? result.text
163
+ : translate(t, 'error.incomplete', DICTIONARIES.en['error.incomplete'])
164
+ // A cancelled selection is not a failure: say so and leave the draft alone.
165
+ if (/cancel/i.test(text)) {
166
+ input.notify('info', text)
167
+ return
168
+ }
169
+ throw new Error(text)
170
+ }
171
+ const filePath = String(result.text ?? '').trim()
172
+ if (!/\.png$/i.test(filePath)) throw new Error(translate(t, 'error.noPath', DICTIONARIES.en['error.noPath']))
173
+ const read = await remote.workspaceFiles.readBytes(sessionId, filePath, {})
174
+ if (!read?.ok) {
175
+ const why = read?.error?.message ?? read?.error?.code ?? 'unknown error'
176
+ throw new Error(translate(t, 'error.readFailed', DICTIONARIES.en['error.readFailed']).replace('{reason}', String(why)))
177
+ }
178
+ const raw = read.value?.data
179
+ if (raw === undefined) throw new Error(translate(t, 'error.readNoBytes', DICTIONARIES.en['error.readNoBytes']))
180
+ const data = new Uint8Array(raw)
181
+ const name = filePath.split(/[\\/]/).pop() ?? 'screenshot.png'
182
+ const file = new File([data], name, { type: 'image/png' })
183
+ const drafts = conversation.createDrafts(sessionId, [file], true)
184
+ const ids = drafts.map(draft => draft.id)
185
+ if (input.addAttachments(ids) === false) {
186
+ conversation.releaseDraftAttachments?.(drafts)
187
+ throw new Error(translate(t, 'error.busy', DICTIONARIES.en['error.busy']))
188
+ }
189
+ input.focus()
190
+ }
191
+
192
+ /**
193
+ * The camera button that floats in the composer's top-right corner.
194
+ * @param props - slot props plus the injected binding.
195
+ */
196
+ function ScreenshotButton(props) {
197
+ const [busy, setBusy] = React.useState(false)
198
+ const busyRef = React.useRef(false)
199
+ const t = props.t
200
+
201
+ const shoot = React.useCallback((mode) => {
202
+ if (busyRef.current) return
203
+ busyRef.current = true
204
+ setBusy(true)
205
+ Promise.resolve()
206
+ .then(() => props.captureScreen(mode, t))
207
+ .catch((error) => {
208
+ props.notify('error', error instanceof Error ? error.message : String(error))
209
+ })
210
+ .finally(() => {
211
+ busyRef.current = false
212
+ setBusy(false)
213
+ })
214
+ }, [props, t])
215
+
216
+ return h('div', { className: 'dsh-shot-slot' },
217
+ h('button', {
218
+ type: 'button',
219
+ className: 'dsh-shot',
220
+ 'data-busy': busy ? 'true' : 'false',
221
+ disabled: busy,
222
+ title: translate(t, 'button.title', DICTIONARIES.en['button.title']),
223
+ 'aria-label': translate(t, 'button.label', DICTIONARIES.en['button.label']),
224
+ onMouseDown: event => event.stopPropagation(),
225
+ onClick: (event) => {
226
+ event.preventDefault()
227
+ event.stopPropagation()
228
+ shoot('region')
229
+ },
230
+ onContextMenu: (event) => {
231
+ event.preventDefault()
232
+ event.stopPropagation()
233
+ shoot('full')
234
+ },
235
+ },
236
+ h(busy ? SpinnerIcon : CameraIcon)))
237
+ }
238
+
239
+ return {
240
+ inject: ['slots', 'remote', 'remote.commands', 'remote.workspaceFiles', 'sessions', 'locale'],
241
+ apply(ctx) {
242
+ ensureStyle()
243
+ ctx.effect(() => ctx.locale.register(NS, DICTIONARIES), 'dsh-screenshot: dictionaries')
244
+ ctx.slots.inject('conversation.input.overlay', () => ctx.slots.register({
245
+ name: 'conversation.input.overlay',
246
+ id: 'screenshot',
247
+ order: 15,
248
+ locale: NS,
249
+ inject: (sessionId) => {
250
+ const actx = ctx.sessions?.scope(sessionId)
251
+ const conversation = actx?.get('conversation')
252
+ if (conversation === undefined) {
253
+ return {
254
+ captureScreen: () => Promise.reject(new Error(DICTIONARIES.en['error.notReady'])),
255
+ notify: () => {},
256
+ }
257
+ }
258
+ const input = conversation.input.for(actx)
259
+ return {
260
+ captureScreen: (mode, translator) => captureIntoSession(ctx, sessionId, conversation, input, mode, translator),
261
+ notify: (level, text) => input.notify(level, text),
262
+ }
263
+ },
264
+ }, ScreenshotButton))
265
+ },
266
+ }
267
+ },
268
+ })
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: screenshot
3
+ name: 'dsh-composer-screenshot'
package/docs/DETAIL.md ADDED
@@ -0,0 +1,64 @@
1
+ # dsh-composer-screenshot — details
2
+
3
+ ## Where the button lives
4
+
5
+ The Client half registers into the slot `conversation.input.overlay` (a `list` slot declared by
6
+ `@deepseek-ai/dsh-client-ui-conversation`, anchored on the composer card's top edge) and paints a
7
+ single 26×26 camera button in its top-right corner. The button is `position: absolute; top: 6px;
8
+ right: 8px` inside that zero-height anchor, so it never changes the composer's height and never
9
+ competes with the attachment rail for layout.
10
+
11
+ ## Round trip
12
+
13
+ ```
14
+ click ──▶ ctx.remote.commands.execute(sessionId, '/screenshot region', [])
15
+ │
16
+ ▼ Host
17
+ capture() ──▶ platform helper ──▶ %TEMP%/dsh-screenshots/shot-<ms>.png
18
+ │
19
+ ▼ command result: { kind: 'success', text: '<absolute png path>' }
20
+ client ──▶ ctx.remote.workspaceFiles.readBytes(sessionId, path, {})
21
+ ──▶ new File([bytes], 'shot-….png', { type: 'image/png' })
22
+ ──▶ conversation.createDrafts(sessionId, [file], true)
23
+ ──▶ input.addAttachments(ids) // and input.focus()
24
+ ```
25
+
26
+ Cancelling is a normal outcome: the helper exits with code `3` (Windows) or writes no file
27
+ (macOS/Linux), the Host answers `Screenshot cancelled.`, and the Client shows an info notice
28
+ instead of an error. The button re-enables either way, because the busy flag is cleared in
29
+ `.finally()`.
30
+
31
+ ## Platform helpers
32
+
33
+ - **Windows** — `capture.ps1`. `SetProcessDPIAware()` keeps the selection overlay in physical
34
+ pixels; `SystemInformation.VirtualScreen` covers every monitor; the dimmed overlay is a
35
+ borderless `Form` subclassed in C# so `DoubleBuffered` can be set (it is a protected member and
36
+ cannot be assigned from PowerShell directly). The full screen is grabbed first, then cropped to
37
+ the dragged rectangle and saved as PNG.
38
+ - **macOS** — `screencapture -i -x <file>` (interactive selection) or `-x <file>` for every
39
+ display.
40
+ - **Linux** — first available of `maim -s`, `gnome-screenshot -a`, `spectacle -r -b -n -o`,
41
+ `scrot -s`.
42
+
43
+ Every helper is spawned with `windowsHide: true`, a five-minute timeout and the invocation's
44
+ `AbortSignal`; aborting kills the child, which also closes an open selection overlay.
45
+
46
+ ## Failure modes worth knowing
47
+
48
+ | Symptom | Cause |
49
+ | --- | --- |
50
+ | Button missing | Client half not loaded — check the app was restarted after install, and that the profile lists the bundle |
51
+ | `cannot get property "remote.commands" without inject` | A Client plugin that calls a dotted remote namespace must list every level in `inject` |
52
+ | `找不到属性"DoubleBuffered"` / selection never appears | The overlay form crashed on creation — `DoubleBuffered` must be set inside a C# subclass |
53
+ | `Aborted` / nothing inserted | The command was cancelled, or `addAttachments` returned `false` because the composer was busy |
54
+ | Old captures piling up | Pruning runs on every capture and drops PNGs older than 7 days |
55
+
56
+ ## Files
57
+
58
+ | Path | Role |
59
+ | --- | --- |
60
+ | `index.js` | Host half: `/screenshot` command, capture orchestration, temp-file pruning |
61
+ | `client.js` | Client half: slot registration, the button, the attachment round trip |
62
+ | `capture.ps1` | Windows capture + selection overlay |
63
+ | `cordis.patch.yml` | Bundle descriptor inserted into the profile's plugin graph |
64
+ | `locale/*.json` | Plugin-list metadata (title/description/detail) |
Binary file
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Screenshot">
2
+ <rect x="2" y="2" width="60" height="60" rx="14" fill="#12233a"/>
3
+ <rect x="10" y="21" width="8" height="6" rx="2" fill="#5aa0ff"/>
4
+ <path d="M22 19h6l3-4h10l3 4h8a4 4 0 0 1 4 4v18a4 4 0 0 1-4 4H22a4 4 0 0 1-4-4V23a4 4 0 0 1 4-4Z" fill="none" stroke="#e8f2ff" stroke-width="3.2" stroke-linejoin="round"/>
5
+ <circle cx="35" cy="32" r="7.5" fill="none" stroke="#5aa0ff" stroke-width="3.2"/>
6
+ <path d="M44 13v6M41 16h6" stroke="#e8f2ff" stroke-width="2.6" stroke-linecap="round" opacity="0.85"/>
7
+ </svg>
package/index.js ADDED
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Host half of the screenshot bundle.
3
+ *
4
+ * It owns the only part of the feature a browser cannot do: grabbing pixels of
5
+ * the real desktop. The Client half asks for a capture through the `/screenshot`
6
+ * command and receives the absolute path of the saved PNG, which it then turns
7
+ * into a composer attachment.
8
+ *
9
+ * `/screenshot [region|full]`
10
+ *
11
+ * @module dsh-screenshot
12
+ */
13
+
14
+ import { spawn } from 'node:child_process'
15
+ import { mkdir, readdir, stat, unlink } from 'node:fs/promises'
16
+ import { tmpdir } from 'node:os'
17
+ import path from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+
20
+ /** Plugin name used by the cordis patch descriptor. */
21
+ export const name = 'screenshot'
22
+
23
+ /** The command registry is the only host service this plugin needs. */
24
+ export const inject = ['commands']
25
+
26
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
27
+ const MODES = new Set(['region', 'full'])
28
+ const SHOT_DIR = path.join(tmpdir(), 'dsh-screenshots')
29
+ const KEEP_MS = 7 * 24 * 60 * 60 * 1000
30
+ const CAPTURE_TIMEOUT_MS = 5 * 60 * 1000
31
+
32
+ /**
33
+ * Delete captures nothing is likely to reference any more.
34
+ * @returns once the stale files are gone; failures stay silent.
35
+ */
36
+ async function pruneCaptures() {
37
+ try {
38
+ const now = Date.now()
39
+ for (const entry of await readdir(SHOT_DIR)) {
40
+ if (!entry.endsWith('.png')) continue
41
+ const file = path.join(SHOT_DIR, entry)
42
+ const info = await stat(file).catch(() => undefined)
43
+ if (info !== undefined && now - info.mtimeMs > KEEP_MS) await unlink(file).catch(() => {})
44
+ }
45
+ } catch {
46
+ // A missing capture directory simply means nothing to prune.
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Run one helper process and collect its output.
52
+ * @param executable - helper executable.
53
+ * @param args - helper arguments.
54
+ * @param signal - aborts the capture, which also closes any selection overlay.
55
+ * @returns stdout, stderr and the exit code of the helper.
56
+ */
57
+ function runHelper(executable, args, signal) {
58
+ return new Promise((resolve, reject) => {
59
+ const child = spawn(executable, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
60
+ let stdout = ''
61
+ let stderr = ''
62
+ const timer = setTimeout(() => {
63
+ child.kill()
64
+ reject(new Error('Screenshot timed out after 5 minutes'))
65
+ }, CAPTURE_TIMEOUT_MS)
66
+ const onAbort = () => { child.kill() }
67
+ signal.addEventListener('abort', onAbort, { once: true })
68
+
69
+ child.stdout.setEncoding('utf8')
70
+ child.stderr.setEncoding('utf8')
71
+ child.stdout.on('data', chunk => { stdout += chunk })
72
+ child.stderr.on('data', chunk => { stderr += chunk })
73
+ child.on('error', (error) => {
74
+ clearTimeout(timer)
75
+ signal.removeEventListener('abort', onAbort)
76
+ reject(error)
77
+ })
78
+ child.on('close', (code) => {
79
+ clearTimeout(timer)
80
+ signal.removeEventListener('abort', onAbort)
81
+ resolve({ stdout, stderr, code })
82
+ })
83
+ })
84
+ }
85
+
86
+ /**
87
+ * Pick the last JSON object the Windows helper printed.
88
+ * @param stdout - helper output.
89
+ * @returns the parsed verdict, or undefined when the helper printed none.
90
+ */
91
+ function readVerdict(stdout) {
92
+ const lines = stdout.split(/\r?\n/).map(line => line.trim()).filter(line => line.startsWith('{'))
93
+ const last = lines.at(-1)
94
+ if (last === undefined) return undefined
95
+ try {
96
+ return JSON.parse(last)
97
+ } catch {
98
+ return undefined
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Command-line tools are judged by the file they leave behind: a cancelled
104
+ * selection exits non-zero without writing one.
105
+ * @param file - destination path.
106
+ * @returns true when the PNG exists and holds bytes.
107
+ */
108
+ async function wroteCapture(file) {
109
+ const info = await stat(file).catch(() => undefined)
110
+ return info !== undefined && info.size > 0
111
+ }
112
+
113
+ /**
114
+ * Capture with the Windows PowerShell helper that draws its own selection UI.
115
+ * @param file - destination PNG path.
116
+ * @param mode - `region` or `full`.
117
+ * @param signal - cancellation.
118
+ * @returns true when the file was written, false when the user cancelled.
119
+ */
120
+ async function captureWindows(file, mode, signal) {
121
+ const script = path.join(HERE, 'capture.ps1')
122
+ const args = [
123
+ '-NoProfile',
124
+ '-NonInteractive',
125
+ '-STA',
126
+ '-ExecutionPolicy', 'Bypass',
127
+ '-WindowStyle', 'Hidden',
128
+ '-File', script,
129
+ '-Mode', mode,
130
+ '-Out', file,
131
+ ]
132
+
133
+ let outcome
134
+ try {
135
+ outcome = await runHelper('powershell.exe', args, signal)
136
+ } catch (error) {
137
+ if (error?.code !== 'ENOENT') throw error
138
+ outcome = await runHelper('pwsh', args, signal)
139
+ }
140
+
141
+ const verdict = readVerdict(outcome.stdout)
142
+ if (verdict?.cancelled === true) return false
143
+ if (verdict?.ok !== true) {
144
+ const detail = String(verdict?.error ?? '').trim() || outcome.stderr.trim() || `exit code ${outcome.code}`
145
+ throw new Error(detail)
146
+ }
147
+ return true
148
+ }
149
+
150
+ /**
151
+ * Try one command-line capture tool; a missing executable is not an error.
152
+ * @param executable - tool to launch.
153
+ * @param args - tool arguments.
154
+ * @param file - destination PNG path.
155
+ * @param signal - cancellation.
156
+ * @returns `'missing'` when the tool is not installed, otherwise whether it wrote a file.
157
+ */
158
+ async function tryTool(executable, args, file, signal) {
159
+ let outcome
160
+ try {
161
+ outcome = await runHelper(executable, args, signal)
162
+ } catch (error) {
163
+ if (error?.code === 'ENOENT') return 'missing'
164
+ throw error
165
+ }
166
+ void outcome
167
+ return wroteCapture(file)
168
+ }
169
+
170
+ /**
171
+ * Capture with the tools the platform ships or commonly has installed.
172
+ * @param file - destination PNG path.
173
+ * @param mode - `region` or `full`.
174
+ * @param signal - cancellation.
175
+ * @returns true when a file was written, false when the user cancelled.
176
+ */
177
+ async function captureTools(file, mode, signal) {
178
+ const region = mode === 'region'
179
+ const candidates = process.platform === 'darwin'
180
+ ? [['screencapture', region ? ['-i', '-x', file] : ['-x', file]]]
181
+ : [
182
+ ['maim', region ? ['-s', file] : [file]],
183
+ ['gnome-screenshot', region ? ['-a', '-f', file] : ['-f', file]],
184
+ ['spectacle', [...(region ? ['-r'] : ['-f']), '-b', '-n', '-o', file]],
185
+ ['scrot', region ? ['-s', file] : [file]],
186
+ ]
187
+
188
+ for (const [executable, args] of candidates) {
189
+ const result = await tryTool(executable, args, file, signal)
190
+ if (result !== 'missing') return result
191
+ }
192
+ throw new Error('No capture tool found: macOS ships screencapture; on Linux install one of maim, gnome-screenshot, spectacle or scrot')
193
+ }
194
+
195
+ /**
196
+ * Capture the desktop into a PNG and report where it landed.
197
+ * @param mode - `region` selects an area, `full` takes every display.
198
+ * @param signal - cancellation owned by the dispatching UI request.
199
+ * @returns the saved file, or undefined when the user cancelled.
200
+ */
201
+ async function capture(mode, signal) {
202
+ await mkdir(SHOT_DIR, { recursive: true })
203
+ void pruneCaptures()
204
+
205
+ const file = path.join(SHOT_DIR, `shot-${Date.now()}.png`)
206
+ const saved = process.platform === 'win32'
207
+ ? await captureWindows(file, mode, signal)
208
+ : await captureTools(file, mode, signal)
209
+ if (!saved) {
210
+ await unlink(file).catch(() => {})
211
+ return undefined
212
+ }
213
+ return { path: file }
214
+ }
215
+
216
+ /**
217
+ * Execute one `/screenshot` invocation.
218
+ * @param invocation - the command invocation carrying raw input and cancellation.
219
+ * @returns the saved PNG path on success, a human-readable failure otherwise.
220
+ */
221
+ async function captureCommand(invocation) {
222
+ const tokens = invocation.rawInput.trim().toLowerCase().split(/\s+/).filter(Boolean)
223
+ const mode = tokens.find(token => MODES.has(token)) ?? 'region'
224
+ try {
225
+ const shot = await capture(mode, invocation.signal)
226
+ if (shot === undefined) return { kind: 'error', text: 'Screenshot cancelled.' }
227
+ return { kind: 'success', text: shot.path }
228
+ } catch (error) {
229
+ if (invocation.signal.aborted) return { kind: 'error', text: 'Screenshot cancelled.' }
230
+ const message = error instanceof Error ? error.message : String(error)
231
+ return { kind: 'error', text: `Screenshot failed: ${message}` }
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Register the capture command for every composited client.
237
+ * @param ctx - context carrying the command registry.
238
+ */
239
+ export function apply(ctx) {
240
+ ctx.effect(() => ctx.commands.register({
241
+ name: 'screenshot',
242
+ description: 'Capture a region of the desktop into this Session',
243
+ input: { hint: '[region|full]' },
244
+ handler: captureCommand,
245
+ }), 'screenshot command')
246
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Screenshot",
4
+ "description": "Puts a camera button beside the composer: select any part of the desktop and the picture lands in the current Session.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "截屏",
4
+ "description": "在输入框旁加一个相机按钮:框选桌面任意区域,图片直接进入当前会话。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/market.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "format": 1,
3
+ "title": { "en": "DSH plugins by tizuld486-netizen", "zh": "tizuld486-netizen 的 DSH 插件" },
4
+ "description": {
5
+ "en": "Small plugins that add one missing convenience to DeepSeek Harness.",
6
+ "zh": "给 DeepSeek Harness 补上一个小便利的插件集。"
7
+ },
8
+ "metadata": {
9
+ "categories": {},
10
+ "labels": {},
11
+ "sortKeys": {}
12
+ },
13
+ "plugins": [
14
+ {
15
+ "name": "dsh-composer-screenshot",
16
+ "title": { "en": "Screenshot", "zh": "截屏" },
17
+ "description": {
18
+ "en": "Camera button in the composer: select any part of the desktop and the picture lands in the current Session.",
19
+ "zh": "输入框旁的相机按钮:框选桌面任意区域,图片直接进入当前会话。"
20
+ },
21
+ "author": "tizuld486-netizen",
22
+ "homepage": "https://github.com/tizuld486-netizen/dsh-screenshot#readme",
23
+ "repository": {
24
+ "url": "https://github.com/tizuld486-netizen/dsh-screenshot"
25
+ },
26
+ "metadata": {
27
+ "keywords": ["screenshot", "capture", "image", "composer"],
28
+ "labels": [],
29
+ "sortKeys": {}
30
+ },
31
+ "versions": [
32
+ {
33
+ "version": "0.1.0",
34
+ "publishTimestamp": 1796536929,
35
+ "source": {
36
+ "type": "git",
37
+ "url": "https://github.com/tizuld486-netizen/dsh-screenshot",
38
+ "commit": "8bf72d22718478823ca20dc34e00480a3c466bf7"
39
+ },
40
+ "engines": { "dsh": ">=0.2.2-rc.5" }
41
+ }
42
+ ]
43
+ }
44
+ ]
45
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "dsh-composer-screenshot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "A camera button in the DSH composer: select any part of the desktop and the picture lands in the current Session",
5
+ "keywords": [
6
+ "dsh",
7
+ "dsh-plugin",
8
+ "deepseek-harness",
9
+ "screenshot",
10
+ "capture"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "tizuld486-netizen",
14
+ "homepage": "https://github.com/tizuld486-netizen/dsh-screenshot#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/tizuld486-netizen/dsh-screenshot.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/tizuld486-netizen/dsh-screenshot/issues"
21
+ },
22
+ "engines": {
23
+ "dsh": ">=0.2.2-rc.5"
24
+ },
25
+ "type": "module",
26
+ "exports": {
27
+ ".": "./index.js",
28
+ "./client": "./client.js",
29
+ "./locale/*.json": "./locale/*.json",
30
+ "./icon": "./icon.svg"
31
+ },
32
+ "files": [
33
+ "index.js",
34
+ "client.js",
35
+ "capture.ps1",
36
+ "cordis.patch.yml",
37
+ "locale/*.json",
38
+ "docs",
39
+ "icon.svg",
40
+ "README.md",
41
+ "LICENSE",
42
+ "market.json"
43
+ ],
44
+ "dsh": {
45
+ "bundle": {
46
+ "patch": "./cordis.patch.yml"
47
+ },
48
+ "client": {
49
+ "platform": "web",
50
+ "immediately": true,
51
+ "inject": [
52
+ "@deepseek-ai/dsh-client-ui-conversation"
53
+ ]
54
+ }
55
+ }
6
56
  }