@inkbite/shotink 0.0.0-stage → 1.4.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/client.js ADDED
@@ -0,0 +1,791 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@local/dsh-screenshot',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const CAPTURE_ROUTE = '/api/dsh-screenshot/capture'
7
+ // The host kills its PowerShell at 130s; failing here first keeps the button
8
+ // from sitting disabled through a dead request.
9
+ const CAPTURE_TIMEOUT_MS = 140000
10
+
11
+ // Where the entry lives: 'menu' = only in the composer "+" menu,
12
+ // 'toolbar' = only the inline button, 'both' = both places.
13
+ const PLACEMENT_KEY = 'dsh-screenshot:placement'
14
+ const PLACEMENTS = ['menu', 'toolbar', 'both']
15
+ const PLACEMENT_FALLBACK = 'both'
16
+ const placementListeners = new Set()
17
+ const shortcutListeners = new Set()
18
+ // sessionId -> capture callback, published by the mounted composer button so
19
+ // the menu row can drive the exact same flow (attachments need the slot's
20
+ // inputActions and the session-bound conversation).
21
+ const captureHandlers = new Map()
22
+
23
+ function readPlacement() {
24
+ try {
25
+ const stored = window.localStorage.getItem(PLACEMENT_KEY)
26
+ return PLACEMENTS.indexOf(stored) === -1 ? PLACEMENT_FALLBACK : stored
27
+ } catch (error) {
28
+ return PLACEMENT_FALLBACK
29
+ }
30
+ }
31
+
32
+ let placement = readPlacement()
33
+
34
+ // In-window shortcut: pressing it starts the same flow as the button or the
35
+ // menu row. Window-scoped on purpose - the overlay is a local process, so a
36
+ // system-wide hotkey would fire with no DSH window to drop the shot into.
37
+ const SHORTCUT_KEY = 'dsh-screenshot:shortcut'
38
+ const SHORTCUTS = ['ctrl+shift+x', 'ctrl+shift+a', 'alt+shift+s']
39
+ const SHORTCUT_FALLBACK = 'ctrl+shift+x'
40
+
41
+ function readShortcut() {
42
+ try {
43
+ const stored = window.localStorage.getItem(SHORTCUT_KEY)
44
+ if (stored === 'off') return 'off'
45
+ return SHORTCUTS.indexOf(stored) === -1 ? SHORTCUT_FALLBACK : stored
46
+ } catch (error) {
47
+ return SHORTCUT_FALLBACK
48
+ }
49
+ }
50
+
51
+ let shortcut = readShortcut()
52
+
53
+ function setShortcut(next) {
54
+ if (next !== 'off' && SHORTCUTS.indexOf(next) === -1) return
55
+ if (next === shortcut) return
56
+ shortcut = next
57
+ try {
58
+ window.localStorage.setItem(SHORTCUT_KEY, next)
59
+ } catch (error) {
60
+ /* storage disabled: still applies for this session */
61
+ }
62
+ for (const listener of shortcutListeners) listener(next)
63
+ }
64
+
65
+ function subscribeShortcut(listener) {
66
+ shortcutListeners.add(listener)
67
+ listener(shortcut)
68
+ return () => { shortcutListeners.delete(listener) }
69
+ }
70
+
71
+ function shortcutMatches(event) {
72
+ if (shortcut === 'off') return false
73
+ const key = String(event.key || '').toLowerCase()
74
+ if (!key) return false
75
+ if (shortcut === 'ctrl+shift+x') {
76
+ return event.ctrlKey && event.shiftKey && !event.altKey && key === 'x'
77
+ }
78
+ if (shortcut === 'ctrl+shift+a') {
79
+ return event.ctrlKey && event.shiftKey && !event.altKey && key === 'a'
80
+ }
81
+ return event.altKey && event.shiftKey && !event.ctrlKey && key === 's'
82
+ }
83
+
84
+ // System-wide hotkey: the resident helper registers it with RegisterHotKey,
85
+ // so a press works while another app has focus. This half owns the value and
86
+ // pushes it to the host on load and on every change.
87
+ const HOTKEY_KEY = 'dsh-screenshot:hotkey'
88
+ const HOTKEYS = ['alt+shift+s', 'ctrl+alt+shift+x']
89
+ const HOTKEY_FALLBACK = 'alt+shift+s'
90
+ const hotkeyListeners = new Set()
91
+ const INBOX_ROUTE = '/api/dsh-screenshot/inbox'
92
+
93
+ function readHotkey() {
94
+ try {
95
+ const stored = window.localStorage.getItem(HOTKEY_KEY)
96
+ if (stored === 'off') return 'off'
97
+ return HOTKEYS.indexOf(stored) === -1 ? HOTKEY_FALLBACK : stored
98
+ } catch (error) {
99
+ return HOTKEY_FALLBACK
100
+ }
101
+ }
102
+
103
+ let hotkey = readHotkey()
104
+
105
+ function syncHotkey() {
106
+ try {
107
+ fetch('/api/dsh-screenshot/hotkey', {
108
+ method: 'POST',
109
+ headers: { 'content-type': 'application/json' },
110
+ body: JSON.stringify({ hotkey }),
111
+ }).catch(() => {})
112
+ } catch (error) { /* the host keeps its own last value */ }
113
+ }
114
+
115
+ function setHotkey(next) {
116
+ if (next !== 'off' && HOTKEYS.indexOf(next) === -1) return
117
+ if (next === hotkey) return
118
+ hotkey = next
119
+ try {
120
+ window.localStorage.setItem(HOTKEY_KEY, next)
121
+ } catch (error) {
122
+ /* storage disabled: still applies for this session */
123
+ }
124
+ syncHotkey()
125
+ for (const listener of hotkeyListeners) listener(next)
126
+ }
127
+
128
+ function subscribeHotkey(listener) {
129
+ hotkeyListeners.add(listener)
130
+ listener(hotkey)
131
+ return () => { hotkeyListeners.delete(listener) }
132
+ }
133
+
134
+ // Floating ball: the resident helper owns the always-on-top window, and this
135
+ // half only stores the user's choice and pushes it, so a restart comes back
136
+ // looking the way it was left.
137
+ const FLOAT_KEY = 'dsh-screenshot:float'
138
+ const floatListeners = new Set()
139
+
140
+ function readFloat() {
141
+ try {
142
+ return window.localStorage.getItem(FLOAT_KEY) === 'off' ? 'off' : 'on'
143
+ } catch (error) {
144
+ return 'on'
145
+ }
146
+ }
147
+
148
+ let floatVisible = readFloat()
149
+
150
+ function syncFloat() {
151
+ try {
152
+ fetch('/api/dsh-screenshot/float', {
153
+ method: 'POST',
154
+ headers: { 'content-type': 'application/json' },
155
+ body: JSON.stringify({ on: floatVisible === 'on' }),
156
+ }).catch(() => {})
157
+ } catch (error) { /* the host keeps its own last value */ }
158
+ }
159
+
160
+ // The host is the truth: the ball can be hidden from its own context menu,
161
+ // which the settings page never sees otherwise. Adopt, do not push back.
162
+ function adoptFloatState(value) {
163
+ if (value !== 'on' && value !== 'off') return
164
+ if (value === floatVisible) return
165
+ floatVisible = value
166
+ try {
167
+ window.localStorage.setItem(FLOAT_KEY, value)
168
+ } catch (error) { }
169
+ for (const listener of floatListeners) listener(value)
170
+ diag({ stage: 'float-adopt', value })
171
+ }
172
+
173
+ function setFloat(next) {
174
+ if (next !== 'on' && next !== 'off') return
175
+ // No early return: if the ball drifted out of sync with this value (hidden
176
+ // from its menu), picking the same option has to push it back anyway.
177
+ floatVisible = next
178
+ try {
179
+ window.localStorage.setItem(FLOAT_KEY, next)
180
+ } catch (error) {
181
+ /* storage disabled: still applies for this session */
182
+ }
183
+ syncFloat()
184
+ for (const listener of floatListeners) listener(next)
185
+ }
186
+
187
+ function subscribeFloat(listener) {
188
+ floatListeners.add(listener)
189
+ listener(floatVisible)
190
+ return () => { floatListeners.delete(listener) }
191
+ }
192
+
193
+ function setPlacement(next) {
194
+ if (PLACEMENTS.indexOf(next) === -1 || next === placement) return
195
+ placement = next
196
+ try {
197
+ window.localStorage.setItem(PLACEMENT_KEY, next)
198
+ } catch (error) {
199
+ /* storage disabled: the choice still applies for this session */
200
+ }
201
+ for (const listener of placementListeners) listener(next)
202
+ }
203
+
204
+ function subscribePlacement(listener) {
205
+ placementListeners.add(listener)
206
+ listener(placement)
207
+ return () => { placementListeners.delete(listener) }
208
+ }
209
+
210
+ function base64ToFile(base64, name) {
211
+ const binary = atob(base64)
212
+ const bytes = new Uint8Array(binary.length)
213
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
214
+ return new File([bytes], name, { type: 'image/png' })
215
+ }
216
+
217
+ // One capture at a time, shared by the button, the "+" menu row and the
218
+ // shortcut: a double press must not open two overlays.
219
+ let capturing = false
220
+ // Latest mounted composer, so the shortcut knows which draft to attach to.
221
+ let activeContext = null
222
+
223
+ async function startCapture(context, onBusy) {
224
+ if (capturing || !context) return
225
+ capturing = true
226
+ if (typeof onBusy === 'function') onBusy(true)
227
+ try {
228
+ const response = await fetch(CAPTURE_ROUTE, {
229
+ method: 'POST',
230
+ headers: { 'content-type': 'application/json' },
231
+ body: '{}',
232
+ signal: typeof AbortSignal.timeout === 'function'
233
+ ? AbortSignal.timeout(CAPTURE_TIMEOUT_MS)
234
+ : undefined,
235
+ })
236
+ const result = await response.json().catch(() => null)
237
+ if (!response.ok || !result || !result.ok) {
238
+ throw new Error(result && result.error ? result.error : `HTTP ${response.status}`)
239
+ }
240
+ // Cancelling is a normal end: the overlay closed on Esc, nothing to report.
241
+ if (result.cancelled) return
242
+ const file = base64ToFile(result.data, result.name || 'screenshot.png')
243
+ const drafts = context.conversation.createDrafts(context.sessionId, [file], true)
244
+ if (!context.inputActions.addAttachments(drafts.map((draft) => draft.id))) {
245
+ context.conversation.releaseDraftAttachments(drafts)
246
+ throw new Error('could not attach screenshot')
247
+ }
248
+ } catch (error) {
249
+ // No toast on screen; failures stay diagnosable in the console.
250
+ console.error('[dsh-screenshot]', error && error.message ? error.message : String(error))
251
+ } finally {
252
+ capturing = false
253
+ if (typeof onBusy === 'function') onBusy(false)
254
+ }
255
+ }
256
+
257
+ // Screenshots taken with the global hotkey arrive through the inbox instead
258
+ // of a request; the open draft is wherever the composer was last mounted,
259
+ // even if the window is in the background.
260
+ const queuedFiles = []
261
+
262
+ function attachFiles(files) {
263
+ const context = activeContext
264
+ if (!context) return false
265
+ const drafts = context.conversation.createDrafts(context.sessionId, files, true)
266
+ if (!context.inputActions.addAttachments(drafts.map((draft) => draft.id))) {
267
+ context.conversation.releaseDraftAttachments(drafts)
268
+ return false
269
+ }
270
+ return true
271
+ }
272
+
273
+ function flushQueuedFiles() {
274
+ if (queuedFiles.length === 0 || !activeContext) return
275
+ const files = queuedFiles.splice(0, queuedFiles.length)
276
+ if (!attachFiles(files)) queuedFiles.unshift(...files)
277
+ }
278
+
279
+ let polling = false
280
+ let waitedForComposer = false
281
+
282
+ const STATE_ROUTE = '/api/dsh-screenshot/state'
283
+
284
+ async function pollFloatState() {
285
+ try {
286
+ const response = await fetch(STATE_ROUTE, { method: 'POST', body: '{}' })
287
+ if (!response.ok) return
288
+ const result = await response.json().catch(() => null)
289
+ if (result && result.ok) adoptFloatState(result.float)
290
+ } catch (error) {
291
+ /* the poll simply retries */
292
+ }
293
+ }
294
+
295
+ async function pollInbox() {
296
+ // Nothing to attach to yet; the file waits in the host inbox.
297
+ if (polling) return
298
+ if (!activeContext) {
299
+ if (!waitedForComposer) {
300
+ waitedForComposer = true
301
+ diag({ stage: 'inbox-wait', reason: 'no-composer' })
302
+ }
303
+ return
304
+ }
305
+ polling = true
306
+ try {
307
+ // Long poll: the host answers as soon as a capture is parked, so the
308
+ // image shows up right after the confirm key instead of on the next tick.
309
+ const response = await fetch(INBOX_ROUTE, {
310
+ method: 'POST',
311
+ headers: { 'content-type': 'application/json' },
312
+ body: JSON.stringify({ waitMs: 25000 }),
313
+ })
314
+ if (!response.ok) {
315
+ const text = await response.text().catch(() => '')
316
+ diag({ stage: 'inbox-http', status: response.status, body: text.slice(0, 120) })
317
+ return
318
+ }
319
+ const result = await response.json().catch(() => null)
320
+ if (!result || !result.ok) return
321
+ adoptFloatState(result.float)
322
+ if (!Array.isArray(result.items) || result.items.length === 0) return
323
+ const files = result.items.map((item) => base64ToFile(item.data, item.name || 'screenshot.png'))
324
+ const attached = attachFiles(files)
325
+ if (!attached) queuedFiles.push(...files)
326
+ diag({ stage: 'inbox', count: files.length, attached })
327
+ } catch (error) {
328
+ /* the poll simply retries */
329
+ } finally {
330
+ polling = false
331
+ }
332
+ }
333
+
334
+ // The host appends these to %TEMP%\dsh-screenshot-client.log: a menu entry
335
+ // that fails to register is invisible on screen, so it needs a paper trail.
336
+ function diag(payload) {
337
+ try {
338
+ fetch('/api/dsh-screenshot/diag', {
339
+ method: 'POST',
340
+ headers: { 'content-type': 'application/json' },
341
+ body: JSON.stringify(payload),
342
+ }).catch(() => {})
343
+ } catch (error) { /* diagnostics never break the plugin */ }
344
+ }
345
+
346
+ // The "+" menu's two sections are a hard-coded roster inside
347
+ // @deepseek-ai/dsh-client-ui-commands (Add = file/goal/plan/feedback,
348
+ // Commands = compact/permission/model/export); a contribution outside both
349
+ // rosters is appended to the end of Commands and there is no public way to
350
+ // ask for the Add group. So the runtime's candidate builder is wrapped: for
351
+ // the empty-query menu only - the one place sections exist - the screenshot
352
+ // row is lifted out and re-inserted directly below "file", carrying the
353
+ // Add group's own section label. A typed query keeps the shared ranking
354
+ // untouched, and if a future build renames the method nothing matches and
355
+ // the row simply stays where it was.
356
+ const PIN_MARK = '__dshScreenshotMenuPin'
357
+
358
+ function liftRow(rows) {
359
+ if (!Array.isArray(rows) || rows.length < 2) return rows
360
+ const moving = []
361
+ const rest = []
362
+ for (const row of rows) {
363
+ if (row && row.name === 'screenshot') moving.push(row)
364
+ else rest.push(row)
365
+ }
366
+ if (moving.length === 0) return rows
367
+ const anchor = rest.findIndex((row) => row && row.name === 'file')
368
+ if (anchor === -1) return rows
369
+ const section = rest[anchor].section
370
+ const lifted = moving.map((row) => (section === undefined ? row : Object.assign({}, row, { section })))
371
+ return rest.slice(0, anchor + 1).concat(lifted, rest.slice(anchor + 1))
372
+ }
373
+
374
+ function pinScreenshotRow(commandUi) {
375
+ try {
376
+ const carrier = typeof commandUi.candidates === 'function' ? commandUi : Object.getPrototypeOf(commandUi)
377
+ const original = carrier && carrier.candidates
378
+ if (typeof original !== 'function') {
379
+ diag({ stage: 'pin-missing' })
380
+ return
381
+ }
382
+ if (carrier[PIN_MARK] === true) return
383
+ const wrapped = function (...args) {
384
+ const result = original.apply(this, args)
385
+ if (result === null || typeof result !== 'object' || typeof result.then !== 'function') return result
386
+ return result.then((rows) => liftRow(rows))
387
+ }
388
+ carrier[PIN_MARK] = true
389
+ carrier.candidates = wrapped
390
+ let applied = carrier.candidates === wrapped
391
+ if (!applied) {
392
+ const proto = Object.getPrototypeOf(carrier)
393
+ if (proto && typeof proto.candidates === 'function' && proto[PIN_MARK] !== true) {
394
+ proto[PIN_MARK] = true
395
+ proto.candidates = wrapped
396
+ applied = proto.candidates === wrapped
397
+ }
398
+ }
399
+ diag({ stage: 'pin', applied })
400
+ } catch (error) {
401
+ diag({ stage: 'pin-failed', error: String((error && error.stack) || error) })
402
+ }
403
+ }
404
+
405
+ // Camera glyph: rounded body, a viewfinder hump on the top edge, thick lens
406
+ // ring - one path so the hump merges into the outline. Shared by the
407
+ // composer button and the two menu rows.
408
+ function CameraIcon(props) {
409
+ const size = (props && props.size) || 16
410
+ return h('svg', {
411
+ viewBox: '0 0 24 24', width: size, height: size,
412
+ fill: 'none', stroke: '#3b7dd8', 'stroke-width': 2,
413
+ 'stroke-linecap': 'round', 'stroke-linejoin': 'round',
414
+ 'aria-hidden': true,
415
+ },
416
+ h('path', { d: 'M6.1 8.5H9Q12 5.1 15 8.5H17.9A2.5 2.5 0 0 1 20.4 11V17.9A2.5 2.5 0 0 1 17.9 20.4H6.1A2.5 2.5 0 0 1 3.6 17.9V11A2.5 2.5 0 0 1 6.1 8.5Z' }),
417
+ h('circle', { cx: 12, cy: 14.3, r: 3.5 }),
418
+ )
419
+ }
420
+
421
+ function ScreenshotButton({ inputActions, sessionId, conversation, t }) {
422
+ const [busy, setBusy] = React.useState(false)
423
+ const [mode, setMode] = React.useState(placement)
424
+
425
+ React.useEffect(() => subscribePlacement(setMode), [])
426
+
427
+ const onClick = React.useCallback(() => {
428
+ startCapture({ conversation, inputActions, sessionId }, setBusy)
429
+ }, [conversation, inputActions, sessionId])
430
+
431
+ // Published while mounted - also while hidden in "menu" mode - so the
432
+ // menu row and the shortcut never depend on this button being visible.
433
+ React.useEffect(() => {
434
+ captureHandlers.set(sessionId, onClick)
435
+ activeContext = { conversation, inputActions, sessionId }
436
+ // A hotkey shot taken while this composer was unmounted waits here.
437
+ flushQueuedFiles()
438
+ return () => {
439
+ if (captureHandlers.get(sessionId) === onClick) captureHandlers.delete(sessionId)
440
+ if (activeContext && activeContext.sessionId === sessionId) activeContext = null
441
+ }
442
+ }, [onClick, conversation, inputActions, sessionId])
443
+
444
+ return h('span', {
445
+ style: {
446
+ position: 'relative',
447
+ display: mode === 'menu' ? 'none' : 'inline-flex',
448
+ alignItems: 'center',
449
+ },
450
+ title: t('button'),
451
+ },
452
+ h('button', {
453
+ type: 'button',
454
+ onClick,
455
+ 'data-dsh-screenshot': '',
456
+ // Button presses steal focus from the draft editor; suppressing the
457
+ // default at mousedown keeps the caret where the user left it, which
458
+ // is what every native composer control does.
459
+ onMouseDown: (event) => { event.preventDefault() },
460
+ disabled: busy,
461
+ 'aria-label': t('button'),
462
+ style: {
463
+ display: 'inline-flex',
464
+ alignItems: 'center',
465
+ justifyContent: 'center',
466
+ width: 30,
467
+ height: 30,
468
+ padding: 0,
469
+ border: '1px solid transparent',
470
+ borderRadius: 6,
471
+ background: 'transparent',
472
+ color: 'var(--dsw-alias-label-secondary, currentColor)',
473
+ cursor: busy ? 'default' : 'pointer',
474
+ opacity: busy ? 0.5 : 1,
475
+ },
476
+ }, h(CameraIcon, { size: 18 }))
477
+ )
478
+ }
479
+
480
+ // Settings → Screenshot. Both preferences used to live only in the "+" menu,
481
+ // which is a command palette, not a place to configure things; the same two
482
+ // values get a real page here and the menu rows stay as a shortcut.
483
+ const SETTINGS_BORDER = 'var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.1))'
484
+ const SETTINGS_BORDER_ON = 'var(--dsw-alias-border-selected, rgba(0, 0, 0, 0.24))'
485
+ const SETTINGS_BG_ON = 'var(--dsw-alias-bg-layer-2, rgba(0, 0, 0, 0.04))'
486
+ const SETTINGS_TEXT = 'var(--dsw-alias-label-primary, currentColor)'
487
+ const SETTINGS_TEXT_SUB = 'var(--dsw-alias-label-secondary, inherit)'
488
+ const SETTINGS_TICK = 'var(--dsw-alias-state-success-primary, #0a8f4c)'
489
+
490
+ function SettingsChoice(props) {
491
+ return h('button', {
492
+ type: 'button',
493
+ role: 'radio',
494
+ 'aria-checked': props.active,
495
+ onClick: props.onSelect,
496
+ style: {
497
+ display: 'flex',
498
+ alignItems: 'flex-start',
499
+ gap: 10,
500
+ width: '100%',
501
+ padding: '10px 12px',
502
+ textAlign: 'left',
503
+ font: 'inherit',
504
+ color: SETTINGS_TEXT,
505
+ background: props.active ? SETTINGS_BG_ON : 'transparent',
506
+ border: `1px solid ${props.active ? SETTINGS_BORDER_ON : SETTINGS_BORDER}`,
507
+ borderRadius: 8,
508
+ cursor: 'pointer',
509
+ },
510
+ },
511
+ h('span', {
512
+ 'aria-hidden': true,
513
+ style: { flex: '0 0 auto', width: 14, marginTop: 1, color: props.active ? SETTINGS_TICK : 'transparent' },
514
+ }, '✓'),
515
+ h('span', { style: { display: 'flex', flexDirection: 'column', gap: 2 } },
516
+ h('span', { style: { fontSize: 13, fontWeight: 500, lineHeight: 1.4 } }, props.label),
517
+ props.desc
518
+ ? h('span', { style: { fontSize: 12, lineHeight: 1.4, color: SETTINGS_TEXT_SUB } }, props.desc)
519
+ : null
520
+ )
521
+ )
522
+ }
523
+
524
+ function ScreenshotSettings(props) {
525
+ const t = props.t
526
+ const [state, setState] = React.useState(() => ({
527
+ placement: props.getPlacement(),
528
+ shortcut: props.getShortcut(),
529
+ hotkey: props.getHotkey(),
530
+ float: props.getFloat(),
531
+ }))
532
+ React.useEffect(() => {
533
+ // The "+" menu rows write the same values, so the page has to follow
534
+ // them rather than keep whichever value it mounted with.
535
+ const offPlacement = props.subscribePlacement((value) => setState((prev) => Object.assign({}, prev, { placement: value })))
536
+ const offShortcut = props.subscribeShortcut((value) => setState((prev) => Object.assign({}, prev, { shortcut: value })))
537
+ const offHotkey = props.subscribeHotkey((value) => setState((prev) => Object.assign({}, prev, { hotkey: value })))
538
+ const offFloat = props.subscribeFloat((value) => setState((prev) => Object.assign({}, prev, { float: value })))
539
+ return () => { offPlacement(); offShortcut(); offHotkey(); offFloat() }
540
+ }, [])
541
+ const headings = (title, desc) => h('div', null,
542
+ h('div', { style: { fontSize: 14, fontWeight: 600, lineHeight: 1.5 } }, title),
543
+ h('div', { style: { fontSize: 12, marginTop: 2, lineHeight: 1.5, color: SETTINGS_TEXT_SUB } }, desc)
544
+ )
545
+ const group = (rows) => h('div', { role: 'radiogroup', style: { display: 'grid', gap: 8 } }, rows)
546
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 28, padding: '4px 0 16px', color: SETTINGS_TEXT } },
547
+ h('section', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
548
+ headings(t('placement'), t('placementDesc')),
549
+ group([
550
+ { id: 'both', label: t('both'), desc: t('bothDesc') },
551
+ { id: 'menu', label: t('menu'), desc: t('menuDesc') },
552
+ { id: 'toolbar', label: t('toolbar'), desc: t('toolbarDesc') },
553
+ ].map((option) => h(SettingsChoice, {
554
+ key: option.id,
555
+ label: option.label,
556
+ desc: option.desc,
557
+ active: state.placement === option.id,
558
+ onSelect: () => props.setPlacement(option.id),
559
+ })))
560
+ ),
561
+ h('section', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
562
+ headings(t('shortcutTitle'), t('shortcutDesc')),
563
+ group([
564
+ { id: 'ctrl+shift+x', label: t('cutX') },
565
+ { id: 'ctrl+shift+a', label: t('cutA') },
566
+ { id: 'alt+shift+s', label: t('cutS') },
567
+ { id: 'off', label: t('off') },
568
+ ].map((option) => h(SettingsChoice, {
569
+ key: option.id,
570
+ label: option.label,
571
+ active: state.shortcut === option.id,
572
+ onSelect: () => props.setShortcut(option.id),
573
+ })))
574
+ ),
575
+ h('section', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
576
+ headings(t('hotkeyTitle'), t('hotkeyDesc')),
577
+ group([
578
+ { id: 'alt+shift+s', label: t('hkS') },
579
+ { id: 'ctrl+alt+shift+x', label: t('hkX') },
580
+ { id: 'off', label: t('off') },
581
+ ].map((option) => h(SettingsChoice, {
582
+ key: option.id,
583
+ label: option.label,
584
+ active: state.hotkey === option.id,
585
+ onSelect: () => props.setHotkey(option.id),
586
+ })))
587
+ ),
588
+ h('section', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
589
+ headings(t('floatTitle'), t('floatDesc')),
590
+ group([
591
+ { id: 'on', label: t('floatOn') },
592
+ { id: 'off', label: t('off') },
593
+ ].map((option) => h(SettingsChoice, {
594
+ key: option.id,
595
+ label: option.label,
596
+ active: state.float === option.id,
597
+ onSelect: () => props.setFloat(option.id),
598
+ })))
599
+ )
600
+ )
601
+ }
602
+
603
+ return {
604
+ inject: ['slots', 'conversation', 'commandUi'],
605
+ apply(ctx) {
606
+ const conversation = ctx.get('conversation')
607
+ const commandUi = ctx.get('commandUi')
608
+ const zh = typeof navigator !== 'undefined' && /^zh\b/i.test(navigator.language || '')
609
+ const dicts = {
610
+ en: {
611
+ button: 'Screenshot',
612
+ settingsNav: 'Screenshot',
613
+ row: 'Screenshot',
614
+ rowDesc: 'Select a screen region and attach it as an image',
615
+ placement: 'Screenshot entry',
616
+ placementDesc: 'Choose where the screenshot entry lives',
617
+ menu: '“+” menu only',
618
+ menuDesc: 'One row inside the composer + menu, no toolbar button',
619
+ toolbar: 'Toolbar button only',
620
+ toolbarDesc: 'The camera button left of the composer',
621
+ both: 'Both places',
622
+ bothDesc: 'Button plus the + menu row',
623
+ shortcutTitle: 'Screenshot shortcut',
624
+ shortcutDesc: 'Press a key combo in this window to start a capture',
625
+ off: 'Off',
626
+ cutX: 'Ctrl + Shift + X',
627
+ cutA: 'Ctrl + Shift + A',
628
+ cutS: 'Alt + Shift + S',
629
+ hotkeyTitle: 'Global hotkey',
630
+ hotkeyDesc: 'Press it with any app in front; the shot lands in the open draft',
631
+ hkS: 'Alt + Shift + S',
632
+ hkX: 'Ctrl + Alt + Shift + X',
633
+ floatTitle: 'Floating ball',
634
+ floatDesc: 'A small ball stays on the desktop; one click starts a capture. Drag it wherever you like, the spot is remembered, right-click to tuck it away.',
635
+ floatOn: 'Show the ball',
636
+ },
637
+ zh: {
638
+ button: '截屏',
639
+ settingsNav: '截图',
640
+ row: '截图',
641
+ rowDesc: '框选屏幕区域,作为图片附件插入',
642
+ placement: '截图入口',
643
+ placementDesc: '选择截图入口放在哪里',
644
+ menu: '仅“+”菜单',
645
+ menuDesc: '收进输入框「+」菜单里,工具栏不再占按钮',
646
+ toolbar: '仅工具栏按钮',
647
+ toolbarDesc: '输入框左侧的相机按钮',
648
+ both: '两处都放',
649
+ bothDesc: '按钮 + “+”菜单里各一个',
650
+ shortcutTitle: '截屏快捷键',
651
+ shortcutDesc: '在本窗口内按组合键直接开始截图',
652
+ off: '关闭',
653
+ cutX: 'Ctrl + Shift + X',
654
+ cutA: 'Ctrl + Shift + A',
655
+ cutS: 'Alt + Shift + S',
656
+ hotkeyTitle: '全局热键',
657
+ hotkeyDesc: '任何应用在前台都能按,截完直接进当前草稿',
658
+ hkS: 'Alt + Shift + S',
659
+ hkX: 'Ctrl + Alt + Shift + X',
660
+ floatTitle: '悬浮窗',
661
+ floatDesc: '桌面上常驻一个小圆球,点一下直接开始截图。可以拖到任意位置,位置会记住;右键可收起。',
662
+ floatOn: '显示悬浮球',
663
+ },
664
+ }
665
+ const tr = (key) => (zh ? dicts.zh : dicts.en)[key] || key
666
+
667
+ ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
668
+ name: 'conversation.input.left',
669
+ id: 'dsh-screenshot',
670
+ order: 10,
671
+ inject: (sessionId) => ({ sessionId }),
672
+ }, (props) => h(ScreenshotButton, {
673
+ inputActions: props.inputActions,
674
+ sessionId: props.sessionId,
675
+ conversation,
676
+ t: tr,
677
+ })))
678
+
679
+ // A real settings page: the settings shell is a list slot, so any feature
680
+ // can own one section and its nav entry.
681
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
682
+ name: 'settings.section',
683
+ id: 'screenshot',
684
+ order: 60,
685
+ label: () => tr('settingsNav'),
686
+ inject: () => ({
687
+ getPlacement: () => placement,
688
+ getShortcut: () => shortcut,
689
+ getHotkey: () => hotkey,
690
+ subscribePlacement,
691
+ subscribeShortcut,
692
+ subscribeHotkey,
693
+ setPlacement,
694
+ setShortcut,
695
+ setHotkey,
696
+ getFloat: () => floatVisible,
697
+ subscribeFloat,
698
+ setFloat,
699
+ }),
700
+ }, (props) => h(ScreenshotSettings, Object.assign({}, props, { t: tr }))))
701
+
702
+ diag({ stage: 'settings-section', registered: true })
703
+
704
+ diag({
705
+ stage: 'apply',
706
+ hasCommandUi: commandUi !== undefined,
707
+ hasSlots: ctx.get('slots') !== undefined,
708
+ language: zh ? 'zh' : 'en',
709
+ })
710
+
711
+ if (commandUi === undefined) {
712
+ console.error('[dsh-screenshot] commandUi unavailable: the + menu entry is off')
713
+ return
714
+ }
715
+
716
+ pinScreenshotRow(commandUi)
717
+
718
+ // Registered outside the menu so it works with the menu closed; capture
719
+ // phase runs first so a host binding the same combo wins through
720
+ // defaultPrevented.
721
+ ctx.effect(() => {
722
+ const onKeyDown = (event) => {
723
+ if (event.defaultPrevented || event.repeat) return
724
+ if (!activeContext) return
725
+ if (!shortcutMatches(event)) return
726
+ event.preventDefault()
727
+ startCapture(activeContext)
728
+ }
729
+ window.addEventListener('keydown', onKeyDown, true)
730
+ return () => window.removeEventListener('keydown', onKeyDown, true)
731
+ })
732
+
733
+ // Tell the host which combo it should hold down system-wide, then poll
734
+ // for shots that arrived while another app had focus.
735
+ ctx.effect(() => {
736
+ syncHotkey()
737
+ syncFloat()
738
+ let stopped = false
739
+ // One request stays parked at the host, so a shot that lands is attached
740
+ // immediately; the loop only re-arms after an answer or a timeout.
741
+ const loop = async () => {
742
+ while (!stopped) {
743
+ await pollInbox()
744
+ await new Promise((resolve) => window.setTimeout(resolve, activeContext ? 30 : 400))
745
+ }
746
+ }
747
+ void loop()
748
+ const timer = window.setInterval(() => { void pollFloatState() }, 3000)
749
+ return () => { stopped = true; window.clearInterval(timer) }
750
+ })
751
+
752
+ try {
753
+ ctx.effect(() => commandUi.register({
754
+ name: 'screenshot',
755
+ label: () => tr('row'),
756
+ description: () => tr('rowDesc'),
757
+ icon: CameraIcon,
758
+ // Re-read on every menu build, so switching to "toolbar only" drops
759
+ // the row from the menu on the next open instead of leaving it behind.
760
+ available: () => placement !== 'toolbar',
761
+ ui: {
762
+ kind: 'action',
763
+ run(session) {
764
+ const key = session === undefined || session === null ? '' : String(session.sessionId)
765
+ const exact = captureHandlers.get(key)
766
+ if (exact !== undefined) {
767
+ exact()
768
+ return
769
+ }
770
+ // The mounted composer button owns the flow for the active session.
771
+ const element = document.querySelector('[data-dsh-screenshot]')
772
+ if (element) {
773
+ element.click()
774
+ return
775
+ }
776
+ const any = captureHandlers.values().next().value
777
+ if (any !== undefined) any()
778
+ },
779
+ },
780
+ }))
781
+ } catch (error) {
782
+ diag({
783
+ stage: 'register-failed',
784
+ error: String((error && error.stack) || error),
785
+ })
786
+ console.error('[dsh-screenshot] could not register the menu entries', error)
787
+ }
788
+ },
789
+ }
790
+ },
791
+ })