dsh-annotate-upper 0.0.0-stage → 0.1.15-fork.1

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/lib/client.js ADDED
@@ -0,0 +1,1757 @@
1
+ // Generated by build.mjs — edit src/client.js instead.
2
+ window.__ModuleLoader__.load({
3
+ id: "dsh-annotate",
4
+ factory: (require) => {
5
+ const module = { exports: {} };
6
+ const exports = module.exports;
7
+ const React = require("react");
8
+ /**
9
+ * dsh-annotate — UI message catalog.
10
+ *
11
+ * Deliberately not an ES module: build.mjs prepends this file to the client
12
+ * bundle and wraps it around the injected overlay, and neither is loaded through
13
+ * a module system. Both call `dsaI18n(...)` and get back `{ t, lang, set,
14
+ * toggle, detect }`.
15
+ *
16
+ * Two rules when adding a string:
17
+ * 1. Add the key to BOTH languages below.
18
+ * 2. Call `t('key')` at the use site — never inline a literal.
19
+ * `t` falls back to English and then to the key itself, so a missing
20
+ * translation shows up as a visible key rather than an empty element.
21
+ *
22
+ * Placeholders are `{name}` and are substituted by `t(key, { name: value })`.
23
+ */
24
+ function dsaI18n(preferred) {
25
+ var CATALOG = {
26
+ en: {
27
+ // ---- annotation block sent to the model ------------------------------
28
+ 'payload.head': 'Page annotations · {page} ({count})',
29
+ 'payload.locator': ' Element: ',
30
+ 'payload.selectorAmbiguous': ' (matches {count}; verify target)',
31
+ 'payload.selectorNotFound': ' (no match; verify target)',
32
+ 'payload.selectorInvalid': ' (invalid selector; verify target)',
33
+ 'payload.selectorUnknown': ' (match unverified; verify target)',
34
+ 'payload.selectorMissing': '(no selector; verify target)',
35
+ 'payload.viewport': 'viewport {w}×{h}',
36
+ 'payload.verify': ' Verify: ',
37
+ 'payload.attached': '{count} attached',
38
+ 'payload.removeOne': 'Remove this block from the composer',
39
+ 'payload.removeAll': 'Remove all',
40
+ 'zone.topLeft': 'top left',
41
+ 'zone.topCenter': 'top center',
42
+ 'zone.topRight': 'top right',
43
+ 'zone.middleLeft': 'middle left',
44
+ 'zone.middleCenter': 'center',
45
+ 'zone.middleRight': 'middle right',
46
+ 'zone.bottomLeft': 'bottom left',
47
+ 'zone.bottomCenter': 'bottom center',
48
+ 'zone.bottomRight': 'bottom right',
49
+
50
+ // ---- injected overlay ------------------------------------------------
51
+ 'overlay.saveFailed': 'Annotations cannot be saved in this browser. Attach them to the composer before you navigate away.',
52
+ 'overlay.viewPin': 'View annotation {n}: {comment}',
53
+ 'overlay.viewTitle': 'Annotation',
54
+ 'overlay.editTitle': 'Edit annotation',
55
+ 'overlay.commentLabel': 'Annotation comment',
56
+ 'overlay.details': 'Element details',
57
+ 'overlay.editHint': 'Click the comment to edit',
58
+ 'overlay.cancel': 'Cancel',
59
+ 'overlay.finishDraft': 'Save or discard the unfinished annotation before editing another one.',
60
+ 'page.more': 'More tools',
61
+ 'page.sendOptions': 'Submission options',
62
+ 'page.batch': 'Pending annotations',
63
+ 'page.batchCount': '{count} comments',
64
+ 'page.draft': 'Draft',
65
+ 'page.resumeDraft': 'Resume annotation draft',
66
+ 'page.discardDraft': 'Discard annotation draft',
67
+ 'page.view': 'View annotation',
68
+ 'page.pickHint': 'Select an element · Esc to leave',
69
+ 'overlay.close': 'Close',
70
+ 'overlay.placeholder': 'What should change here?',
71
+ 'overlay.hint': 'Enter to save',
72
+ 'overlay.save': 'Save',
73
+
74
+ // ---- panel: entry points --------------------------------------------
75
+ 'panel.tabTitle': 'Annotations',
76
+ 'panel.tabDescription': 'Pick an element, leave a note.',
77
+ 'panel.noSession': 'Choose a workspace and open a conversation first, then use UI annotations.',
78
+ 'panel.language': 'Language',
79
+ 'panel.languageSwitch': 'Switch to {lang}',
80
+
81
+ // ---- panel: list face -----------------------------------------------
82
+ 'list.detecting': 'Scanning for local services…',
83
+ 'list.detected': '{count} local services found',
84
+ 'list.none': 'No local services found',
85
+ 'list.redetect': 'Scan again',
86
+ 'list.open': 'Open →',
87
+ 'list.project': 'This project',
88
+ 'list.declared': 'Configured port',
89
+ 'list.filesHeader': 'Static pages in this project ({count})',
90
+ 'list.emptyHint': 'No local web server is running ({count} ports scanned). Start one, then refresh:',
91
+ 'list.copy': 'Copy',
92
+ 'list.copied': 'Copied: {text}',
93
+ 'list.autoRefresh': 'Checked every 5 seconds. You can also type a port below to open it directly.',
94
+ 'list.placeholder': '5173 or localhost:3000',
95
+ 'list.addressLabel': 'Local service address',
96
+ 'list.openButton': 'Open',
97
+ 'list.recentHeader': 'Recently opened',
98
+ 'list.clearRecent': 'Clear',
99
+ 'list.favorite': 'Pin to top',
100
+ 'list.removeRecent': 'Remove from recent',
101
+ 'list.pickFile': 'Choose file…',
102
+ 'notice.filePathUnavailable': 'This browser cannot read the file path. Paste the absolute path (e.g. D:\\site\\index.html) instead.',
103
+ 'list.helpHeader': 'Annotate inside the preview',
104
+ 'list.helpPicking': 'Press Mark in the toolbar, then click an element in the page and write a note. Enter saves it so you can select the next element.',
105
+ 'list.helpEscape': 'Press Esc or Mark again to leave annotation mode.',
106
+ 'list.helpCmdClick': '⌘/Ctrl+click an element = save it and send immediately.',
107
+ 'list.helpSendHeader': 'The list and sending',
108
+ 'list.helpSendList': 'The comment count opens a compact list. Select a comment to view it, then click its text to edit.',
109
+ 'list.helpSendActions': '“Send annotations” sends only the annotations; “Add to composer” combines them with your draft so you can add context. Annotations survive a failed send.',
110
+
111
+ // ---- panel: page face -----------------------------------------------
112
+ 'page.back': 'Back',
113
+ 'page.forward': 'Forward',
114
+ 'page.reload': 'Reload',
115
+ 'page.addressPlaceholder': 'Address',
116
+ 'page.widthLabel': 'Preview width',
117
+ 'page.widthFit': 'Fit',
118
+ 'page.widthMobile': 'Mobile',
119
+ 'page.listToggleLabel': 'Annotation list, {count}',
120
+ 'page.listToggleEmpty': 'Annotation list, empty',
121
+ 'page.listExpand': 'Expand the annotation list',
122
+ 'page.listCollapse': 'Collapse the annotation list',
123
+ 'page.listEmpty': 'No annotations',
124
+ 'page.listAria': 'Annotation list',
125
+ 'page.backToList': 'Back to the local service list',
126
+ 'page.help': 'How this works',
127
+ 'page.locate': 'Locate in the preview',
128
+ 'page.delete': 'Delete this annotation',
129
+ 'page.previewTitle': 'Preview',
130
+ 'page.loading': 'Opening the preview…',
131
+ 'page.loadingHint': 'Connecting to the local service. Annotations are restored automatically.',
132
+ 'page.unavailable': 'Preview unavailable',
133
+ 'page.retry': 'Retry',
134
+ 'page.markTitle': 'Mark mode: click an element to write a note (Esc to leave)',
135
+ 'page.mark': 'Mark',
136
+ 'page.marking': 'Marking',
137
+ 'page.openExternal': 'Open in the system browser',
138
+ 'page.unit': '{count}',
139
+ 'page.attach': 'Add to composer',
140
+ 'page.send': 'Send annotations',
141
+ 'page.sending': 'Sending…',
142
+ 'page.sendHint': 'Send only these annotations and keep the composer draft',
143
+ 'notice.undo': 'Undo',
144
+ 'notice.dismiss': 'Dismiss',
145
+ 'notice.deleted': 'Annotation deleted. You can undo this.',
146
+ 'notice.badAddress': 'That does not look like an address. Try localhost:5173 or just 5173.',
147
+ 'notice.notLocal': 'Open a local development service; external sites and Harness itself are not supported.',
148
+ 'notice.previewFailed': 'Could not open the preview',
149
+ 'notice.detectFailed': 'Scan failed: {error}',
150
+ 'notice.unknownError': 'unknown error',
151
+ 'notice.autoOpened': 'One local service found, opened it automatically',
152
+ 'notice.autoOpenedFile': 'One static page found, opened it automatically',
153
+ 'notice.storageUnavailable': 'Browser storage is unavailable. Add the annotations to the composer before closing.',
154
+ 'notice.finishEditing': 'Save or discard the annotation changes before sending.',
155
+ 'notice.noComposer': 'Select a conversation with a composer first.',
156
+ 'notice.attachFailed': 'Could not add to the composer. The annotations are kept.',
157
+ 'notice.attached': 'Added to the composer. Add context and send when ready.',
158
+ 'notice.sendUnsupported': 'This Harness build cannot send directly; use “Add to composer”.',
159
+ 'notice.notAccepted': 'The conversation did not accept this message',
160
+ 'notice.accepted': 'Conversation accepted {count} annotations',
161
+ 'notice.sendFailed': 'Send failed, annotations kept: {error}',
162
+ 'notice.pluginUnavailable': 'The plugin service is unavailable. Confirm that Harness restarted and loaded the plugin.',
163
+ 'notice.loadTimeout': 'The page took too long to load. Check the development service and retry.',
164
+ 'notice.draftUnavailable': 'The draft cannot be persisted. Save the annotation first.',
165
+ 'notice.elementGone': 'The original element changed or disappeared. The annotation is kept — delete it and annotate again.',
166
+ 'host.notLocalTarget': 'Only local development services can be previewed; Harness itself cannot.',
167
+ 'host.notAllowedFile': 'Only an HTML file inside this workspace can be previewed as a file.',
168
+ 'host.notHtmlFile': 'Only .html and .htm files can be opened as a static page.',
169
+ 'host.staticUnavailable': 'That file is no longer available in this workspace.',
170
+ 'host.tooManyPreviews': 'Too many previews are active. Close another preview and retry.',
171
+ 'host.noCommand': 'No start command is configured (this is an optional feature).',
172
+ 'host.noRoot': 'The workspace directory is unknown, so no dev server can be started.',
173
+ 'host.starting': 'A service for this workspace is already starting. Please wait.',
174
+ 'host.portBusy': 'That port is already in use and cannot be confirmed as yours. Open it from the local service list, or change the port.',
175
+ 'host.startFailed': 'Failed to start: {error}',
176
+ 'host.exited': 'The dev server exited ({code})',
177
+ 'host.readyTimeout': 'Timed out waiting for the dev server to become ready ({seconds}s)',
178
+ 'host.originNotAllowed': 'origin not allowed',
179
+ 'host.methodNotAllowed': 'method not allowed',
180
+ 'host.upstreamUnreachable': 'The local service is unreachable. Check the service or its HTTPS certificate.',
181
+ 'host.previewConnectFailed': 'Preview connection failed',
182
+ 'host.connectTimeout': 'Connection timed out',
183
+ },
184
+
185
+ zh: {
186
+ // ---- annotation block sent to the model ------------------------------
187
+ 'payload.head': '页面批注 · {page}({count} 条)',
188
+ 'payload.locator': ' 元素:',
189
+ 'payload.selectorAmbiguous': '(匹配 {count} 个,需核对)',
190
+ 'payload.selectorNotFound': '(未命中,需核对)',
191
+ 'payload.selectorInvalid': '(选择器无效,需核对)',
192
+ 'payload.selectorUnknown': '(匹配未确认,需核对)',
193
+ 'payload.selectorMissing': '(无选择器,需核对)',
194
+ 'payload.viewport': '视口 {w}×{h}',
195
+ 'payload.verify': ' 核对:',
196
+ 'payload.attached': '已附 {count} 条标注',
197
+ 'payload.removeOne': '从输入框移除这段标注',
198
+ 'payload.removeAll': '全部移除',
199
+ 'zone.topLeft': '左上',
200
+ 'zone.topCenter': '上中',
201
+ 'zone.topRight': '右上',
202
+ 'zone.middleLeft': '左中',
203
+ 'zone.middleCenter': '正中',
204
+ 'zone.middleRight': '右中',
205
+ 'zone.bottomLeft': '左下',
206
+ 'zone.bottomCenter': '下中',
207
+ 'zone.bottomRight': '右下',
208
+
209
+ // ---- injected overlay ------------------------------------------------
210
+ 'overlay.saveFailed': '批注无法保存到浏览器,请在离开页面前加入输入框。',
211
+ 'overlay.viewPin': '查看批注 {n}:{comment}',
212
+ 'overlay.viewTitle': '查看批注',
213
+ 'overlay.editTitle': '编辑批注',
214
+ 'overlay.commentLabel': '批注内容',
215
+ 'overlay.details': '元素定位信息',
216
+ 'overlay.editHint': '点击正文编辑',
217
+ 'overlay.cancel': '取消',
218
+ 'overlay.finishDraft': '请先保存或取消未完成的批注,再编辑另一条。',
219
+ 'page.more': '更多工具',
220
+ 'page.sendOptions': '提交选项',
221
+ 'page.batch': '待提交批注',
222
+ 'page.batchCount': '{count} 条批注',
223
+ 'page.draft': '草稿',
224
+ 'page.resumeDraft': '继续编辑草稿',
225
+ 'page.discardDraft': '丢弃批注草稿',
226
+ 'page.view': '查看批注',
227
+ 'page.pickHint': '点选页面元素 · Esc 退出',
228
+ 'overlay.close': '关闭',
229
+ 'overlay.placeholder': '这里需要怎么调整?',
230
+ 'overlay.hint': 'Enter 保存',
231
+ 'overlay.save': '保存',
232
+
233
+ // ---- panel: entry points --------------------------------------------
234
+ 'panel.tabTitle': '页面批注',
235
+ 'panel.tabDescription': '圈选页面元素,写下修改意见。',
236
+ 'panel.noSession': '先选择工作区并打开会话,再使用界面标注。',
237
+ 'panel.language': '语言',
238
+ 'panel.languageSwitch': '切换到{lang}',
239
+
240
+ // ---- panel: list face -----------------------------------------------
241
+ 'list.detecting': '正在检测本地服务…',
242
+ 'list.detected': '检测到 {count} 个本地服务',
243
+ 'list.none': '没有检测到本地服务',
244
+ 'list.redetect': '重新检测',
245
+ 'list.open': '打开 →',
246
+ 'list.project': '当前项目',
247
+ 'list.declared': '配置端口',
248
+ 'list.filesHeader': '本项目内的静态页面({count})',
249
+ 'list.emptyHint': '没有正在运行的本地 web(已扫 {count} 个端口)。先把它跑起来,再点刷新:',
250
+ 'list.copy': '复制',
251
+ 'list.copied': '已复制:{text}',
252
+ 'list.autoRefresh': '每 5 秒自动检查一次。也可在下方输入端口直接打开。',
253
+ 'list.placeholder': '5173 或 localhost:3000',
254
+ 'list.addressLabel': '本地服务地址',
255
+ 'list.openButton': '打开',
256
+ 'list.recentHeader': '最近打开',
257
+ 'list.clearRecent': '清空',
258
+ 'list.favorite': '置顶收藏',
259
+ 'list.removeRecent': '从最近打开中移除',
260
+ 'list.pickFile': '选择文件…',
261
+ 'notice.filePathUnavailable': '此浏览器读不到文件路径,请改为粘贴绝对路径(如 D:\\site\\index.html)。',
262
+ 'list.helpHeader': '在预览里标注',
263
+ 'list.helpPicking': '点工具栏的「标注」,然后点页面里的元素写批注,Enter 保存后可直接选择下一个元素继续标注。',
264
+ 'list.helpEscape': '按 Esc 或再次点「标注」退出标注状态。',
265
+ 'list.helpCmdClick': '⌘/Ctrl+点击元素 = 写完立即发送。',
266
+ 'list.helpSendHeader': '批注列表与发送',
267
+ 'list.helpSendList': '点底部批注数量展开列表,点击批注先查看,点击正文后直接编辑。',
268
+ 'list.helpSendActions': '「发送批注」只发送当前批注;「加入输入框」可与草稿一起补充后发送。失败时批注会保留。',
269
+
270
+ // ---- panel: page face -----------------------------------------------
271
+ 'page.back': '后退',
272
+ 'page.forward': '前进',
273
+ 'page.reload': '重新载入',
274
+ 'page.addressPlaceholder': '地址',
275
+ 'page.widthLabel': '预览宽度',
276
+ 'page.widthFit': '自适应',
277
+ 'page.widthMobile': '移动端',
278
+ 'page.listToggleLabel': '批注列表,{count} 条',
279
+ 'page.listToggleEmpty': '批注列表,暂无批注',
280
+ 'page.listExpand': '展开批注列表',
281
+ 'page.listCollapse': '收起批注列表',
282
+ 'page.listEmpty': '暂无批注',
283
+ 'page.listAria': '批注列表',
284
+ 'page.backToList': '回到本地服务列表',
285
+ 'page.help': '怎么用',
286
+ 'page.locate': '在预览里定位',
287
+ 'page.delete': '删除这条标注',
288
+ 'page.previewTitle': '预览',
289
+ 'page.loading': '正在打开预览…',
290
+ 'page.loadingHint': '正在连接本地服务,批注会自动恢复。',
291
+ 'page.unavailable': '预览暂时不可用',
292
+ 'page.retry': '重试',
293
+ 'page.markTitle': '标记模式:点击元素写批注(Esc 退出)',
294
+ 'page.mark': '标注',
295
+ 'page.marking': '标注中',
296
+ 'page.openExternal': '在系统浏览器打开',
297
+ 'page.unit': '{count} 条',
298
+ 'page.attach': '加入输入框',
299
+ 'page.send': '发送批注',
300
+ 'page.sending': '发送中…',
301
+ 'page.sendHint': '只发送这些批注,保留输入框中的草稿',
302
+ 'notice.undo': '撤销',
303
+ 'notice.dismiss': '知道了',
304
+ 'notice.deleted': '已删除批注,可撤销。',
305
+ 'notice.badAddress': '这个地址看不出来是什么,试试 localhost:5173 或直接输 5173',
306
+ 'notice.notLocal': '请打开本地开发服务;不支持外部网站或 Harness 自身。',
307
+ 'notice.previewFailed': '无法打开预览',
308
+ 'notice.detectFailed': '检测失败:{error}',
309
+ 'notice.unknownError': '未知错误',
310
+ 'notice.autoOpened': '检测到 1 个本地服务,已自动打开',
311
+ 'notice.autoOpenedFile': '检测到 1 个静态页面,已自动打开',
312
+ 'notice.storageUnavailable': '浏览器存储不可用,请在关闭前加入输入框。',
313
+ 'notice.finishEditing': '请先保存或取消批注的未保存修改,再发送。',
314
+ 'notice.noComposer': '请先选择一个有输入框的会话。',
315
+ 'notice.attachFailed': '未能加入输入框,批注已保留。',
316
+ 'notice.attached': '已加入输入框,可补充说明后发送。',
317
+ 'notice.sendUnsupported': '当前 Harness 不支持直接发送,请使用「加入输入框」。',
318
+ 'notice.notAccepted': '会话未接受这条消息',
319
+ 'notice.accepted': '会话已接收 {count} 条批注',
320
+ 'notice.sendFailed': '发送失败,批注已保留:{error}',
321
+ 'notice.pluginUnavailable': '插件服务不可用,请确认 Harness 已重启并加载插件。',
322
+ 'notice.loadTimeout': '页面加载超时。请检查开发服务后重试。',
323
+ 'notice.draftUnavailable': '草稿无法持久保存,请先保存批注。',
324
+ 'notice.elementGone': '原元素已变化或消失,批注仍保留,可删除后重新标注。',
325
+ 'host.notLocalTarget': '仅支持本地开发服务,不可预览 Harness 自身。',
326
+ 'host.notAllowedFile': '只能预览当前工作区内、属于本项目的 HTML 文件。',
327
+ 'host.notHtmlFile': '静态预览只支持 .html / .htm 文件。',
328
+ 'host.staticUnavailable': '该文件在当前工作区中已不可用。',
329
+ 'host.tooManyPreviews': '正在使用的预览已达上限,请关闭其他预览后重试。',
330
+ 'host.noCommand': '未配置启动命令(可选功能)',
331
+ 'host.noRoot': '不知道工作区目录,无法启动 dev server',
332
+ 'host.starting': '当前工作区的服务正在启动,请稍候。',
333
+ 'host.portBusy': '该端口已被占用,无法确认属于当前工作区。请从本地服务列表打开,或更换端口。',
334
+ 'host.startFailed': '启动失败: {error}',
335
+ 'host.exited': 'dev server 退出({code})',
336
+ 'host.readyTimeout': '等待 dev server 就绪超时({seconds}s)',
337
+ 'host.originNotAllowed': '来源不被允许',
338
+ 'host.methodNotAllowed': '请求方法不被允许',
339
+ 'host.upstreamUnreachable': '本地服务无法连接,请检查服务或 HTTPS 证书。',
340
+ 'host.previewConnectFailed': '预览连接失败',
341
+ 'host.connectTimeout': '连接超时',
342
+ },
343
+ }
344
+
345
+ var LABELS = { en: 'EN', zh: '中' }
346
+
347
+ /** `zh-Hans-CN` and `zh` both mean Chinese; anything else falls through. */
348
+ function normalize(value) {
349
+ var text = String(value || '').toLowerCase()
350
+ if (text.indexOf('zh') === 0) return 'zh'
351
+ if (text.indexOf('en') === 0) return 'en'
352
+ return ''
353
+ }
354
+
355
+ function detect() {
356
+ if (typeof navigator === 'undefined') return 'en'
357
+ var tags = navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language]
358
+ for (var i = 0; i < tags.length; i += 1) {
359
+ var match = normalize(tags[i])
360
+ if (match) return match
361
+ }
362
+ return 'en'
363
+ }
364
+
365
+ function format(template, vars) {
366
+ return String(template).replace(/\{(\w+)\}/g, function (match, key) {
367
+ return vars && Object.prototype.hasOwnProperty.call(vars, key) ? String(vars[key]) : match
368
+ })
369
+ }
370
+
371
+ var lang = normalize(preferred) || detect()
372
+
373
+ return {
374
+ get lang() {
375
+ return lang
376
+ },
377
+ label: function () {
378
+ return LABELS[lang] || lang
379
+ },
380
+ /** Name of the language `toggle()` would switch to, for the button title. */
381
+ nextLabel: function () {
382
+ return LABELS[lang === 'en' ? 'zh' : 'en']
383
+ },
384
+ set: function (next) {
385
+ var match = normalize(next)
386
+ if (match) lang = match
387
+ return lang
388
+ },
389
+ toggle: function () {
390
+ lang = lang === 'zh' ? 'en' : 'zh'
391
+ return lang
392
+ },
393
+ detect: detect,
394
+ /** The raw table for one language. `scripts/check.mjs` uses this to assert
395
+ * that both languages define exactly the same keys. */
396
+ catalog: function (which) {
397
+ return CATALOG[which] || CATALOG.en
398
+ },
399
+ t: function (key, vars) {
400
+ var table = CATALOG[lang] || CATALOG.en
401
+ var value = table[key] === undefined ? CATALOG.en[key] : table[key]
402
+ if (value === undefined) return key
403
+ return vars ? format(value, vars) : value
404
+ },
405
+ }
406
+ }
407
+
408
+ /** Shared visual primitives; build.mjs embeds this in both isolated surfaces. */
409
+ function dsaTheme() {
410
+ return {
411
+ marker: '#f0a05a',
412
+ markerInk: '#8b5529',
413
+ focus: '#438bbf',
414
+ toolbarHeight: 48,
415
+ cardWidth: 294,
416
+ sans: 'ui-sans-serif,system-ui,-apple-system,"Segoe UI","PingFang SC",sans-serif',
417
+ mono: 'ui-monospace,SFMono-Regular,Menlo,Consolas,monospace',
418
+ light: { ink: '#252525', muted: '#747474', surface: '#ffffff', field: '#f5f5f5', line: '#e3e3e3', action: '#292929', onAction: '#ffffff' },
419
+ dark: { ink: '#ededed', muted: '#a4a4a4', surface: '#242424', field: '#303030', line: '#444444', action: '#ededed', onAction: '#242424' },
420
+ }
421
+ }
422
+
423
+ /**
424
+ * dsh-annotate — Client half.
425
+ *
426
+ * The right-sidebar tab has two faces:
427
+ *
428
+ * - **list** — the local web servers that are actually running, discovered by
429
+ * the host half; one click opens one (a lone find opens itself). Nothing to
430
+ * configure, nothing to type. If nothing is up, it says what to run.
431
+ * - **page** — the opened page, served from its own isolated loopback preview
432
+ * origin so its DOM is readable, with element picking, comments and one
433
+ * structured block into the composer.
434
+ *
435
+ * Bundled by build.mjs into the ModuleLoader format. The overlay is a separate
436
+ * script the host half injects into the previewed document.
437
+ */
438
+ const inject = ['timer', 'sessions', 'slots', 'sidebarRight', 'sidebarRightTabs']
439
+
440
+ const CHANNEL_IN = 'dsh-annotate-overlay'
441
+ const CHANNEL_OUT = 'dsh-annotate-panel'
442
+ const PAGE_CHANNEL = 'dsh-annotate-page'
443
+ const KIND = 'annotate'
444
+ const TAB_ID = 'dsh-annotate'
445
+ const THEME = dsaTheme()
446
+ const MARKER = THEME.marker
447
+
448
+ // The panel's language is a user preference, kept on the harness origin; the
449
+ // injected overlay is told about a change over postMessage.
450
+ const LANG_KEY = 'dsh-annotate:lang'
451
+ const i18n = dsaI18n((() => {
452
+ try { return localStorage.getItem(LANG_KEY) || '' } catch (error) { void error; return '' }
453
+ })())
454
+ const t = (key, vars) => i18n.t(key, vars)
455
+
456
+ /** Host replies carry a stable `code` plus any template values in `detail`;
457
+ * render that in the panel's language and fall back to the host's own wording. */
458
+ const hostMessage = (reply, fallbackKey) => {
459
+ const code = reply && reply.code
460
+ if (code) {
461
+ const text = i18n.t('host.' + code, reply.detail || {})
462
+ if (text !== 'host.' + code) return text
463
+ }
464
+ return (reply && reply.error) || t(fallbackKey)
465
+ }
466
+
467
+ const PANEL_CSS = `
468
+ .dsa-col { --dsa-ink:var(--dsw-alias-label-primary,${THEME.light.ink}); --dsa-muted:var(--dsw-alias-label-secondary,${THEME.light.muted});
469
+ --dsa-surface:var(--dsw-alias-bg-layer-1,${THEME.light.surface}); --dsa-base:var(--dsw-alias-bg-base,${THEME.light.field});
470
+ --dsa-line:color-mix(in srgb,var(--dsa-ink) 12%,transparent); --dsa-hover:color-mix(in srgb,var(--dsa-ink) 5%,transparent);
471
+ display:flex; flex-direction:column; height:100%; min-height:0; min-width:0; position:relative; z-index:2; container-type:inline-size;
472
+ color:var(--dsa-ink); background:var(--dsa-base); font:13px/1.5 ${THEME.sans}; }
473
+ .dsa-col-page { background:transparent; pointer-events:none }
474
+ .dsa-passthrough { pointer-events:none!important }
475
+ .dsa-passthrough-bg { background:transparent!important }
476
+ .dsa-col-page .dsa-stage { background:transparent; pointer-events:none }
477
+ .dsa-col-page .dsa-stage > * { pointer-events:auto }
478
+ .dsa-col-page .dsa-bar, .dsa-col-page .dsa-foot, .dsa-col-page .dsa-popover, .dsa-col-page .dsa-toast { pointer-events:auto }
479
+ .dsa-col { scrollbar-color:color-mix(in srgb,var(--dsa-ink) 25%,transparent) transparent; scrollbar-width:thin }
480
+ .dsa-col * { scrollbar-color:inherit; scrollbar-width:thin }
481
+ .dsa-col *, .dsa-col *::before, .dsa-col *::after { box-sizing:border-box }
482
+ .dsa-col button { font:inherit; cursor:pointer; touch-action:manipulation }
483
+ .dsa-col button:disabled { opacity:.35; cursor:default }
484
+ .dsa-col button:focus-visible, .dsa-col select:focus-visible, .dsa-col input:focus-visible { outline:2px solid ${THEME.focus}; outline-offset:2px }
485
+ .dsa-bar { position:relative; z-index:4; display:flex; align-items:center; gap:6px; min-height:${THEME.toolbarHeight}px; padding:7px 9px; flex:none;
486
+ background:var(--dsa-surface); border-bottom:1px solid var(--dsa-line) }
487
+ .dsa-ico { display:inline-flex; align-items:center; justify-content:center; gap:5px; width:32px; height:32px; padding:0; flex:none;
488
+ border:0; border-radius:7px; background:transparent; color:var(--dsa-muted) }
489
+ .dsa-ico svg { width:15px; height:15px; flex:none }
490
+ .dsa-ico:hover:not(:disabled), .dsa-menu button:hover:not(:disabled), .dsa-mini:hover { background:var(--dsa-hover); color:var(--dsa-ink) }
491
+ .dsa-ico[data-on="true"] { background:var(--dsa-hover); color:var(--dsa-ink) }
492
+ .dsa-mark { width:auto; padding:0 8px; font-size:12px!important; white-space:nowrap }
493
+ .dsa-address { flex:1; min-width:0; display:flex; align-items:center; height:32px; border:1px solid transparent; border-radius:8px;
494
+ background:color-mix(in srgb,var(--dsa-ink) 4%,var(--dsa-surface)); padding-left:9px }
495
+ .dsa-address:focus-within { border-color:var(--dsa-line); background:var(--dsa-surface) }
496
+ .dsa-url { width:100%; min-width:0; border:0; outline:none!important; background:transparent; color:var(--dsa-muted);
497
+ font:11px ${THEME.mono}; text-overflow:ellipsis; padding:0 }
498
+ .dsa-url:focus { color:var(--dsa-ink) }
499
+ .dsa-address .dsa-ico { width:30px; height:30px }
500
+ .dsa-popover { position:absolute; z-index:30; max-width:calc(100% - 16px); padding:5px; border:1px solid var(--dsa-line); border-radius:12px;
501
+ color:var(--dsa-ink); background:var(--dsa-surface); box-shadow:0 8px 26px #0002; pointer-events:auto }
502
+ .dsa-menu { top:43px; right:8px; width:220px; max-height:min(520px,calc(100vh - 80px)); overflow:auto }
503
+ .dsa-menu button { display:flex; align-items:center; gap:8px; width:100%; padding:6px 9px; min-height:34px; border:0; border-radius:6px;
504
+ background:transparent; color:inherit; text-align:left; font-size:12px }
505
+ .dsa-menu button svg { width:14px; height:14px; color:var(--dsa-muted) }
506
+ .dsa-menu button .dsa-menu-value { margin-left:auto; color:var(--dsa-muted); font-size:11px }
507
+ .dsa-menu-row { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:6px 9px; min-height:38px; font-size:12px }
508
+ .dsa-width { width:100px; min-width:0; height:30px; border:1px solid var(--dsa-line); border-radius:6px; color:inherit;
509
+ background:var(--dsa-surface); font:11px ${THEME.sans}; padding:0 5px }
510
+ .dsa-menu-sep { border-top:1px solid var(--dsa-line); margin:5px 4px }
511
+ .dsa-help { padding:8px 9px; font-size:11px; line-height:1.7; color:var(--dsa-muted) }
512
+ .dsa-help b { display:block; margin:8px 0 3px; color:var(--dsa-ink); font-size:11px }
513
+ .dsa-help b:first-child { margin-top:0 }
514
+ .dsa-help p { margin:0 0 5px }
515
+ .dsa-stage { position:relative; flex:1; min-height:0; overflow:hidden; background:var(--dsa-base) }
516
+ .dsa-frame { width:100%; height:100%; border:0; display:block; background:white }
517
+ .dsa-foot { position:absolute; z-index:30; left:50%; bottom:14px; transform:translateX(-50%); display:flex; align-items:center; gap:4px;
518
+ height:44px; max-width:calc(100% - 24px); padding:5px 6px 5px 10px; border:1px solid var(--dsa-line); border-radius:24px;
519
+ background:var(--dsa-surface); box-shadow:0 4px 18px #0002 }
520
+ .dsa-review-toggle { display:flex; gap:7px; align-items:center; min-width:0; height:32px; padding:0 5px; border:0; border-radius:6px;
521
+ background:transparent; color:var(--dsa-muted); white-space:nowrap; font-size:12px!important }
522
+ .dsa-review-toggle svg { width:14px; height:14px; flex:none }
523
+ .dsa-review-toggle:hover { background:var(--dsa-hover); color:var(--dsa-ink) }
524
+ .dsa-foot .dsa-ico { width:28px; height:30px }
525
+ .dsa-divider { height:15px; border-left:1px solid var(--dsa-line); margin:0 3px }
526
+ .dsa-send { display:inline-flex; align-items:center; justify-content:center; flex:none; min-height:32px; padding:0 12px;
527
+ border:0; border-radius:7px; background:var(--dsa-ink); color:var(--dsa-surface); font-size:12px!important }
528
+ .dsa-foot .dsa-send { width:32px; height:32px; padding:0; border-radius:50% }
529
+ .dsa-send svg { width:15px; height:15px }
530
+ .dsa-send:hover:not(:disabled) { opacity:.85 }
531
+ .dsa-busy { animation:dsa-pulse 1s ease-in-out infinite; font:700 16px ${THEME.mono} }
532
+ @keyframes dsa-pulse { 50% { opacity:.4 } }
533
+ .dsa-submit-menu { left:50%; bottom:66px; transform:translateX(-50%); top:auto; width:190px }
534
+ .dsa-review-panel { left:50%; bottom:66px; transform:translateX(-50%); width:310px; max-height:min(360px,55%); overflow:auto }
535
+ .dsa-item { display:flex; align-items:flex-start; gap:3px; border-bottom:1px solid var(--dsa-line) }
536
+ .dsa-item:last-child { border-bottom:0 }
537
+ .dsa-note-open { display:flex; align-items:flex-start; flex:1; min-width:0; gap:9px; padding:10px 7px; border:0; border-radius:7px;
538
+ color:inherit; background:transparent; text-align:left; font-size:12px!important; line-height:1.65!important }
539
+ .dsa-note-open:hover { background:var(--dsa-hover) }
540
+ .dsa-idx { flex:none; width:18px; height:18px; margin-top:1px; border-radius:50%; display:grid; place-items:center; background:color-mix(in srgb,${MARKER} 19%,var(--dsa-surface));
541
+ color:var(--dsa-ink); font:600 9px ${THEME.mono} }
542
+ .dsa-body { min-width:0; flex:1; overflow-wrap:anywhere }
543
+ .dsa-comment { display:-webkit-box; -webkit-line-clamp:4; -webkit-box-orient:vertical; overflow:hidden; white-space:pre-wrap }
544
+ .dsa-note-target { display:block; margin-top:3px; color:var(--dsa-muted); font-size:10px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap }
545
+ .dsa-draft-label { display:block; color:var(--dsa-muted); font-size:10px; margin-top:3px }
546
+ .dsa-mini { display:inline-flex; align-items:center; justify-content:center; width:28px; height:30px; margin:6px 2px 0 0; flex:none; padding:0;
547
+ color:var(--dsa-muted); border:0; border-radius:6px; background:transparent; opacity:.55 }
548
+ .dsa-mini svg { width:13px; height:13px }
549
+ .dsa-item:hover .dsa-mini, .dsa-item:focus-within .dsa-mini { opacity:1 }
550
+ .dsa-mini[data-danger="true"]:hover { color:var(--dsw-alias-state-error-primary,#c25151) }
551
+ .dsa-pick-hint { position:absolute; bottom:18px; left:14px; z-index:2; pointer-events:none; color:var(--dsa-muted); font-size:10px }
552
+ .dsa-pick-hint[data-batch="true"] { bottom:68px; left:50%; transform:translateX(-50%); white-space:nowrap }
553
+ .dsa-notice { display:flex; align-items:center; gap:8px; padding:9px 11px; color:var(--dsa-ink); background:var(--dsa-surface); font-size:12px; line-height:1.6 }
554
+ .dsa-toast { position:absolute; left:50%; bottom:68px; transform:translateX(-50%); z-index:30; max-width:calc(100% - 24px); width:max-content;
555
+ border:1px solid var(--dsa-line); border-radius:10px; box-shadow:0 4px 18px #0002 }
556
+ .dsa-toast[data-kind="error"] { border-color:color-mix(in srgb,#c25151 45%,var(--dsa-line)) }
557
+ .dsa-notice button { display:inline-flex; align-items:center; justify-content:center; flex:none; min-width:28px; min-height:28px; border:0; border-radius:5px; padding:2px 5px; color:inherit; background:transparent; font-size:11px }
558
+ .dsa-notice button:hover { background:var(--dsa-hover) }
559
+ .dsa-notice .dsa-dismiss { margin-left:auto; color:var(--dsa-muted) }
560
+ .dsa-empty { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:12px;
561
+ padding:24px; text-align:center; color:var(--dsa-muted); background:var(--dsa-base) }
562
+ .dsa-empty h4 { margin:0; font-size:13px; color:var(--dsa-ink); font-weight:600 }
563
+ .dsa-empty p { margin:0; max-width:330px; font-size:12px; line-height:1.65 }
564
+ .dsa-listwrap { flex:1; min-height:0; overflow:auto }
565
+ .dsa-sechead { display:flex; align-items:center; gap:8px; padding:16px 14px 9px; font-size:12px; color:var(--dsa-muted) }
566
+ .dsa-sechead .dsa-ico { margin-left:auto }
567
+ .dsa-svc { display:flex; align-items:center; gap:10px; width:calc(100% - 20px); margin:0 10px 7px; padding:12px; border:1px solid var(--dsa-line); border-radius:9px;
568
+ background:var(--dsa-surface); color:inherit; text-align:left }
569
+ .dsa-svc:hover { border-color:color-mix(in srgb,var(--dsa-ink) 25%,transparent) }
570
+ .dsa-svc .dot { width:6px; height:6px; border-radius:50%; flex:none; background:#4b9c72 }
571
+ .dsa-svc .copy { flex:1; min-width:0 }
572
+ .dsa-svc .copy b { display:block; font-size:12px; font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap }
573
+ .dsa-svc .copy span { display:block; margin-top:3px; color:var(--dsa-muted); font:10.5px ${THEME.mono}; overflow:hidden; text-overflow:ellipsis; white-space:nowrap }
574
+ .dsa-svc .copy .dsa-tag { display:inline-block; margin:0 0 0 6px; font-family:inherit; font-size:9px; vertical-align:1px }
575
+ .dsa-svc .go { flex:none; font-size:11px; color:var(--dsa-muted) }
576
+ .dsa-tag { display:inline-block; margin-left:6px; padding:1px 5px; border-radius:5px; font-size:9px; vertical-align:1px; color:var(--dsa-muted); background:var(--dsa-hover) }
577
+ .dsa-tag.is-project { color:var(--dsa-ink); background:color-mix(in srgb,${MARKER} 17%,transparent) }
578
+ .dsa-file .dot { background:#9299a2 }
579
+ .dsa-openrow { display:flex; align-items:center; gap:8px; padding:12px; border-top:1px solid var(--dsa-line) }
580
+ .dsa-openrow-top { border-top:0; border-bottom:1px solid var(--dsa-line); padding:10px 12px }
581
+ .dsa-openrow .dsa-pickbtn { background:transparent; color:var(--dsa-muted); border:1px solid var(--dsa-line); white-space:nowrap }
582
+ .dsa-link { border:0; background:transparent; color:var(--dsa-muted); font-size:11px; padding:3px 5px; border-radius:5px }
583
+ .dsa-link:hover { color:var(--dsa-ink); background:var(--dsa-hover) }
584
+ .dsa-sechead .dsa-link { margin-left:auto }
585
+ .dsa-recent { border-bottom:1px solid var(--dsa-line) }
586
+ .dsa-recentrow { display:flex; align-items:center; gap:3px; padding:0 8px 0 0 }
587
+ .dsa-recent-open { display:flex; min-width:0; flex:1; padding:8px 12px; border:0; border-radius:6px; background:transparent; color:inherit; text-align:left }
588
+ .dsa-recent-open:hover { background:var(--dsa-hover) }
589
+ .dsa-recent-open .copy { display:flex; flex-direction:column; gap:2px; min-width:0; width:100% }
590
+ .dsa-recent-open .copy b { font-size:12px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap }
591
+ .dsa-recent-open .copy span { color:var(--dsa-muted); font:10px ${THEME.mono}; overflow:hidden; text-overflow:ellipsis; white-space:nowrap }
592
+ .dsa-fav { opacity:.5 }
593
+ .dsa-fav.is-fav { opacity:1; color:${MARKER} }
594
+ .dsa-openrow input { min-width:0; flex:1; height:34px; padding:0 9px; border:1px solid var(--dsa-line); border-radius:7px; color:inherit; background:var(--dsa-surface); font:11px ${THEME.mono} }
595
+ .dsa-openrow button { height:34px; padding:0 12px; border:0; border-radius:7px; background:var(--dsa-ink); color:var(--dsa-surface); font-size:12px }
596
+ .dsa-hintbox { padding:14px; color:var(--dsa-muted); font-size:12px; line-height:1.75 }
597
+ .dsa-hintbox p { margin:0 0 8px }
598
+ .dsa-cmd { display:flex; align-items:center; gap:8px; padding:7px 9px; margin-bottom:5px; border:1px solid var(--dsa-line); border-radius:7px; background:var(--dsa-surface) }
599
+ .dsa-cmd code { min-width:0; flex:1; overflow-wrap:anywhere; font:11px ${THEME.mono} }
600
+ .dsa-cmd button { flex:none; border:0; background:transparent; color:inherit; font-size:11px }
601
+ .dsa-dock { display:flex; flex-wrap:wrap; gap:6px; align-items:center; padding:0 2px 6px }
602
+ .dsa-chip { display:inline-flex; align-items:center; gap:6px; min-height:26px; padding:0 4px 0 8px; border-radius:20px; font-size:11.5px;
603
+ color:var(--dsw-alias-label-primary,${THEME.light.ink}); background:color-mix(in srgb,${MARKER} 16%,transparent); border:1px solid color-mix(in srgb,${MARKER} 42%,transparent) }
604
+ .dsa-chip .dot { width:6px; height:6px; border-radius:50%; background:${MARKER} }
605
+ .dsa-chip button, .dsa-chip-clear { border:0; background:transparent; color:inherit; cursor:pointer; padding:3px 5px; border-radius:50%; font-size:11px }
606
+ .dsa-global-notice { position:fixed; bottom:24px; left:50%; transform:translateX(-50%); z-index:2147483647; padding:12px 18px; border-radius:10px;
607
+ background:#252525; color:#fff; box-shadow:0 4px 18px #0003; font:13px/1.5 ${THEME.sans}; max-width:calc(100vw - 32px) }
608
+ @container (max-width:380px) { .dsa-bar { padding:7px 6px; gap:4px } .dsa-mark { width:32px; padding:0 } .dsa-mark span { display:none } .dsa-url { font-size:10px } .dsa-address { padding-left:7px } .dsa-mini { opacity:.7 } }
609
+ @media (pointer:coarse) { .dsa-mini { opacity:1 } }
610
+ @media (prefers-reduced-motion:reduce) { .dsa-col * { transition:none!important; animation:none!important } }
611
+ `
612
+
613
+ function injectStyles(text) {
614
+ const el = document.createElement('style')
615
+ el.setAttribute('data-dsh-annotate', '')
616
+ // Claim ownership before other lazy factories inventory untagged styles.
617
+ el.setAttribute('data-plugin', 'dsh-annotate')
618
+ el.setAttribute('data-plugin-css', 'dsh-annotate/panel.css')
619
+ el.textContent = text
620
+ document.head.appendChild(el)
621
+ return () => el.remove()
622
+ }
623
+
624
+ const ICONS = {
625
+ send: 'M12 20V4m-6 6 6-6 6 6',
626
+ more: 'M5 12h.01M12 12h.01M19 12h.01',
627
+ attach: 'm9 14 7-7a3 3 0 0 1 4 4l-9 9a5 5 0 0 1-7-7l9-9M7 16l8-8',
628
+ annotation: 'M8 18H6a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3h-5l-5 3v-3ZM7 8h10M7 12h6',
629
+ marker: 'M3 17.2 14.4 5.8a2 2 0 0 1 2.8 0l1 1a2 2 0 0 1 0 2.8L6.8 21H3z',
630
+ refresh: 'M13.6 4.2a6.8 6.8 0 1 0 6.4 8.5h-2a4.8 4.8 0 1 1-4.4-6.5V9l4-3.4z',
631
+ back: 'M14.5 5 7.5 12l7 7',
632
+ forward: 'M9.5 5l7 7-7 7',
633
+ list: 'M4 6h16v2H4zM4 11h16v2H4zM4 16h16v2H4z',
634
+ locate: 'M12 2v3m0 14v3M2 12h3m14 0h3M12 8.4a3.6 3.6 0 1 0 0 7.2 3.6 3.6 0 0 0 0-7.2z',
635
+ trash: 'M6 7h12l-1 13H7zM9 4h6l1 2H8z',
636
+ external: 'M14 4h6v6h-2V7.4l-7.3 7.3-1.4-1.4L16.6 6H14zM5 6h5v2H7v9h9v-3h2v5H5z',
637
+ review: 'M5 5.5h14v10H10l-5 4z',
638
+ chevron: 'M7.4 10 12 14.6 16.6 10',
639
+ help: 'M12 4a4 4 0 0 1 4 4c0 2-1.3 2.9-2.3 3.6-.7.5-1 .9-1 1.6v.4h-2v-.6c0-1.5.7-2.3 1.8-3.1.8-.5 1.4-1 1.4-1.9A1.9 1.9 0 0 0 12 6a1.9 1.9 0 0 0-2 1.8H8A3.9 3.9 0 0 1 12 4zm0 12.1a1.2 1.2 0 1 1 0 2.4 1.2 1.2 0 0 1 0-2.4z',
640
+ }
641
+
642
+ function Icon(props) {
643
+ return React.createElement(
644
+ 'svg',
645
+ { viewBox: '0 0 24 24', width: 20, height: 20, className: props.className, style: props.style, 'aria-hidden': 'true', fill: 'none', stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round' },
646
+ props.name === 'more'
647
+ ? [5, 12, 19].map((cx) => React.createElement('circle', { key: cx, cx, cy: 12, r: 1.35, fill: 'currentColor', stroke: 'none' }))
648
+ : React.createElement('path', { d: ICONS[props.name] })
649
+ )
650
+ }
651
+
652
+ function compactText(value, max = 64) {
653
+ const text = String(value || '').replace(/\s+/g, ' ').trim()
654
+ return text.length > max ? text.slice(0, max - 1) + '…' : text
655
+ }
656
+
657
+ function payloadOf(ann, index, viewport) {
658
+ // Keep the requested change intact. Technical context is a single locator
659
+ // line unless the captured selector needs disambiguation.
660
+ const comment = String(ann.comment || '').replace(/\n/g, '\n ')
661
+ const lines = [(index + 1) + '. ' + comment]
662
+ const label = compactText(ann.ariaLabel || ann.alt || ann.text || ann.name || ann.component)
663
+ const selector = String(ann.selector || '')
664
+ const unique = !!selector && ann.selectorMatches === 1
665
+ let status = ''
666
+ if (!selector) status = t('payload.selectorMissing')
667
+ else if (ann.selectorMatches > 1) status = t('payload.selectorAmbiguous', { count: ann.selectorMatches })
668
+ else if (ann.selectorMatches === 0) status = t('payload.selectorNotFound')
669
+ else if (ann.selectorMatches === -1) status = t('payload.selectorInvalid')
670
+ else if (!unique) status = t('payload.selectorUnknown')
671
+ lines.push(t('payload.locator') + selector + status + (label ? ' · “' + label + '”' : ''))
672
+ if (!unique) {
673
+ const anchors = [ann.tag || 'element']
674
+ if (ann.role && ann.role !== ann.tag) anchors.push('role=' + ann.role)
675
+ if (ann.testId) anchors.push(ann.testId)
676
+ if (ann.name) anchors.push('name=' + JSON.stringify(compactText(ann.name)))
677
+ if (ann.component) anchors.push('component=' + compactText(ann.component))
678
+ const rect = ann.rect
679
+ if (rect && ['x', 'y', 'w', 'h'].every(key => Number.isFinite(rect[key]))) {
680
+ anchors.push(rect.w + '×' + rect.h + ' @ (' + rect.x + ', ' + rect.y + ')')
681
+ }
682
+ const size = ann.viewport || viewport
683
+ if (size?.w && size?.h) anchors.push(t('payload.viewport', { w: size.w, h: size.h }))
684
+ lines.push(t('payload.verify') + anchors.join(' · '))
685
+ }
686
+ return lines.join('\n')
687
+ }
688
+
689
+ function payloadBlock(annotations, page, viewport) {
690
+ if (!annotations.length) return ''
691
+ const head = t('payload.head', { page, count: annotations.length })
692
+ return head + '\n' + annotations.map((ann, i) => payloadOf(ann, i, viewport)).join('\n\n')
693
+ }
694
+
695
+
696
+ function annotationLabel(ann) {
697
+ return String(ann.ariaLabel || ann.text || ann.component || ann.tag || '').replace(/\s+/g, ' ').trim().slice(0, 70)
698
+ }
699
+
700
+ /** Accept what people actually type: `5173`, `:5173`, `localhost:3000/x`, a URL,
701
+ * or a local file path (`D:\site\index.html`, `\\server\share\a.html`, `/srv/a.html`). */
702
+ function looksLocalPath(text) {
703
+ return /^file:\/\//i.test(text) || /^[a-zA-Z]:[\\/]/.test(text) || /^\\\\/.test(text) || /^\//.test(text)
704
+ }
705
+ function normalizeAddress(text) {
706
+ const raw = String(text || '').trim()
707
+ if (!raw) return null
708
+ let candidate = raw
709
+ if (/^\d+$/.test(candidate)) candidate = `http://127.0.0.1:${candidate}/`
710
+ else if (candidate.startsWith(':')) candidate = `http://127.0.0.1${candidate}`
711
+ else if (looksLocalPath(candidate)) {
712
+ try {
713
+ const url = new URL(fileAddressOf(candidate))
714
+ return url.host ? null : url.href
715
+ } catch (error) {
716
+ void error
717
+ return null
718
+ }
719
+ } else if (!/^[a-z]+:\/\//i.test(candidate)) candidate = `http://${candidate}`
720
+ try {
721
+ const url = new URL(candidate)
722
+ if (url.protocol === 'file:') return url.host ? null : url.href
723
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
724
+ return url.href
725
+ } catch (error) {
726
+ return null
727
+ }
728
+ }
729
+
730
+ /** Turn a filesystem path into a file URL. The browser has no path helper and
731
+ * Windows paths use backslashes and a drive colon, so normalise both — a `#`
732
+ * or `?` in a name still cannot become a fragment or query. */
733
+ function fileAddressOf(input) {
734
+ let text = String(input || '').trim()
735
+ if (/^file:\/\//i.test(text)) return text
736
+ text = text.replace(/\\/g, '/')
737
+ if (/^\/\//.test(text)) {
738
+ // UNC path: \\server\share → file://server/share
739
+ return 'file://' + text.slice(2).split('/').map((part, index) => (index === 0 ? part : encodeURIComponent(part))).join('/')
740
+ }
741
+ if (/^[a-zA-Z]:/.test(text)) text = '/' + text
742
+ else if (!text.startsWith('/')) text = '/' + text
743
+ return 'file://' + text.split('/').map((part, index) => {
744
+ if (index === 0) return ''
745
+ if (index === 1 && /^[a-zA-Z]:$/.test(part)) return part
746
+ return encodeURIComponent(part)
747
+ }).join('/')
748
+ }
749
+
750
+ const isLoopback = (hostname) => /^(127\.0\.0\.1|localhost|\[::1\]|::1)$/.test(hostname)
751
+
752
+
753
+ function apply(ctx) {
754
+ const slots = ctx.get('slots')
755
+ if (slots === undefined) return
756
+ const sidebarRightTabs = ctx.get('sidebarRightTabs')
757
+ const sidebarRight = ctx.get('sidebarRight')
758
+ ctx.effect(() => injectStyles(PANEL_CSS))
759
+
760
+ const makeModel = (initial) => {
761
+ let state = initial
762
+ const subs = new Set()
763
+ return {
764
+ get: () => state,
765
+ set: (patch) => {
766
+ state = Object.assign({}, state, patch)
767
+ subs.forEach((fn) => fn())
768
+ },
769
+ sub: (fn) => {
770
+ subs.add(fn)
771
+ return () => subs.delete(fn)
772
+ },
773
+ }
774
+ }
775
+ const useSub = (model) => {
776
+ const [, force] = React.useReducer((n) => n + 1, 0)
777
+ React.useEffect(() => model.sub(force), [model])
778
+ }
779
+
780
+ const panels = new Map()
781
+ const getPanel = (sid) => {
782
+ const key = sid || '__root__'
783
+ let panel = panels.get(key)
784
+ if (!panel) {
785
+ panel = {
786
+ sid: key,
787
+ model: makeModel({
788
+ view: 'list',
789
+ services: [],
790
+ files: [],
791
+ recent: [],
792
+ detect: 'idle',
793
+ scanned: 0,
794
+ hint: null,
795
+ url: '',
796
+ input: '',
797
+ src: '',
798
+ history: [],
799
+ index: -1,
800
+ annotations: [],
801
+ viewport: { w: 0, h: 0 },
802
+ page: '',
803
+ mode: 'idle',
804
+ helpOpen: false,
805
+ menuOpen: false,
806
+ sendMenuOpen: false,
807
+ draft: null,
808
+ listOpen: false,
809
+ sending: false,
810
+ loading: false,
811
+ error: null,
812
+ previewOrigin: '',
813
+ previewLease: '',
814
+ width: 'fit',
815
+ pending: [],
816
+ notice: null,
817
+ root: '',
818
+ lang: i18n.lang,
819
+ }),
820
+ draftWriter: null,
821
+ noticeTimer: null,
822
+ }
823
+ panels.set(key, panel)
824
+ }
825
+ return panel
826
+ }
827
+
828
+ const api = async (method, args) => {
829
+ try {
830
+ const res = await fetch('/__dsh-annotate/api', {
831
+ method: 'POST',
832
+ headers: { 'Content-Type': 'application/json' },
833
+ signal: AbortSignal.timeout(20000),
834
+ body: JSON.stringify({ method: method, args: args || {} }),
835
+ })
836
+ return await res.json()
837
+ } catch (error) {
838
+ return { ok: false, error: String((error && error.message) || error) }
839
+ }
840
+ }
841
+
842
+ let frameRef = null
843
+ let activePanel = null
844
+
845
+ // Preview iframes live in a fixed pool outside the React tree so switching
846
+ // sessions only changes visibility — the document (and its in-page state) is
847
+ // never rebuilt. They are destroyed by the host on archive, idle reap or an
848
+ // explicit close.
849
+ let poolLayer = null
850
+ const framePool = new Map()
851
+ // The frame layer must outlive session switches, so it lives on <body>. Its
852
+ // z-index stays low: the right sidebar's tab surface has its own stacking
853
+ // context above it (so toolbar/footer/review stay clickable and visible) and
854
+ // DSH dialogs sit above as well. The stage is made transparent in page view so
855
+ // the frame shows through it.
856
+ const ensureLayer = () => {
857
+ if (poolLayer && poolLayer.isConnected) return poolLayer
858
+ poolLayer = document.createElement('div')
859
+ poolLayer.setAttribute('data-dsh-annotate-pool', '')
860
+ Object.assign(poolLayer.style, { position: 'fixed', inset: '0px', zIndex: '1', pointerEvents: 'none', display: 'none' })
861
+ document.body.appendChild(poolLayer)
862
+ return poolLayer
863
+ }
864
+ const poolKey = (panel, origin) => String(panel.sid) + '::' + origin
865
+ const POOL_LIMIT = 8
866
+ const hidePool = () => {
867
+ if (poolLayer) poolLayer.style.display = 'none'
868
+ for (const entry of framePool.values()) entry.frame.style.display = 'none'
869
+ }
870
+ const destroyEntry = (entry) => {
871
+ if (!entry) return
872
+ try { entry.frame.remove() } catch {}
873
+ framePool.delete(entry.key)
874
+ for (const item of framePool.values()) if (item === entry) framePool.delete(item.key)
875
+ }
876
+ // Explicit close from this tab: drop the pooled document and ask the host to
877
+ // stop that preview server, so its cookies are not kept around.
878
+ const disposeFrame = (panel, origin) => {
879
+ if (!origin) return
880
+ const entry = framePool.get(poolKey(panel, origin))
881
+ destroyEntry(entry)
882
+ void api('closePreview', { sid: panel.sid, origin }).catch(() => {})
883
+ }
884
+ const ensureFrame = (panel, preview, requestedUrl) => {
885
+ const key = poolKey(panel, preview.origin)
886
+ let entry = framePool.get(key)
887
+ if (!entry) {
888
+ const frame = document.createElement('iframe')
889
+ frame.className = 'dsa-frame'
890
+ frame.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-downloads allow-modals')
891
+ frame.setAttribute('title', t('page.previewTitle'))
892
+ Object.assign(frame.style, {
893
+ position: 'absolute', border: '0', margin: '0', background: '#fff',
894
+ display: 'none', pointerEvents: 'auto', width: '0px', height: '0px', left: '0px', top: '0px',
895
+ })
896
+ frame.src = 'about:blank'
897
+ entry = { key, sid: panel.sid, origin: preview.origin, frame, requestedUrl, loaded: false, lastUsed: Date.now() }
898
+ frame.addEventListener('load', () => {
899
+ entry.loaded = true
900
+ panel.frame = frame
901
+ frameRef = frame
902
+ if (activePanel === panel) {
903
+ notify('ping', {}, panel)
904
+ notify('lang', { lang: i18n.lang }, panel)
905
+ }
906
+ })
907
+ framePool.set(key, entry)
908
+ ensureLayer().appendChild(frame)
909
+ // Attach the load listener before navigating, so a fast local/cached page
910
+ // cannot finish loading before we are listening for its "ready" message.
911
+ frame.src = preview.url
912
+ } else if (requestedUrl && requestedUrl !== entry.requestedUrl) {
913
+ // A different address on the same preview origin: navigate in place.
914
+ entry.requestedUrl = requestedUrl
915
+ entry.frame.src = preview.url
916
+ }
917
+ entry.lastUsed = Date.now()
918
+ entry.requestedUrl = requestedUrl || entry.requestedUrl
919
+ panel.frame = entry.frame
920
+ if (framePool.size > POOL_LIMIT) {
921
+ let oldest = null
922
+ for (const item of framePool.values()) {
923
+ if (item.key === key) continue
924
+ if (!oldest || item.lastUsed < oldest.lastUsed) oldest = item
925
+ }
926
+ if (oldest) { const gone = oldest.origin; destroyEntry(oldest); void api('closePreview', { sid: panel.sid, origin: gone }).catch(() => {}) }
927
+ }
928
+ return entry
929
+ }
930
+
931
+ const notify = (type, payload, panel = activePanel) => {
932
+ const frame = panel?.frame || frameRef
933
+ if (!frame || !frame.contentWindow) return
934
+ // Messages carry the annotation payload, so they are addressed to the
935
+ // preview origin rather than broadcast to '*'.
936
+ let target = panel?.model?.get?.().previewOrigin || ''
937
+ if (!target) {
938
+ try { target = new URL(frame.src).origin } catch (error) { void error }
939
+ }
940
+ if (!target) return
941
+ try {
942
+ frame.contentWindow.postMessage(Object.assign({ source: CHANNEL_OUT, type: type }, payload || {}), target)
943
+ } catch (error) {
944
+ void error
945
+ }
946
+ }
947
+
948
+ /** Language is a per-user preference, not per-panel: switching it re-renders
949
+ * this panel and tells the injected overlay to follow. */
950
+ const switchLanguage = (panel) => {
951
+ const next = i18n.toggle()
952
+ try { localStorage.setItem(LANG_KEY, next) } catch (error) { void error }
953
+ panel.model.set({ lang: next, helpOpen: false })
954
+ notify('lang', { lang: next }, panel)
955
+ }
956
+
957
+ const openAnnotate = () => {
958
+ try {
959
+ if (sidebarRight && typeof sidebarRight.openTab === 'function') sidebarRight.openTab(KIND)
960
+ } catch (error) {
961
+ console.warn('dsh-annotate: could not open the sidebar tab', error)
962
+ document.querySelector('.dsa-global-notice')?.remove()
963
+ const notice = document.createElement('div')
964
+ notice.className = 'dsa-global-notice'
965
+ notice.setAttribute('role', 'status')
966
+ notice.textContent = t('panel.noSession')
967
+ document.body.appendChild(notice)
968
+ setTimeout(() => notice.remove(), 6000)
969
+ }
970
+ }
971
+
972
+ const flash = (panel, message, options = {}) => {
973
+ // A toast replaces any previous one, so the undo affordance it carried must
974
+ // go with it.
975
+ panel.model.set({ notice: message, noticeKind: options.kind || 'info', undoAvailable: !!options.undo, canRetrySend: !!options.retry })
976
+ if (panel.noticeTimer) clearTimeout(panel.noticeTimer)
977
+ if (!options.retry) panel.noticeTimer = setTimeout(() => panel.model.set({ notice: null }), 6000)
978
+ }
979
+
980
+ /** Open a page: harness-origin URLs load directly, everything else through the
981
+ * loopback proxy (which is what makes its DOM readable). */
982
+ const openUpstream = async (panel, raw, options) => {
983
+ const push = !options || options.push !== false
984
+ const url = normalizeAddress(raw)
985
+ if (!url) {
986
+ flash(panel, t('notice.badAddress'))
987
+ return false
988
+ }
989
+ const parsed = new URL(url)
990
+ const isFile = parsed.protocol === 'file:'
991
+ // A file target is checked by the host against the session workspace.
992
+ if (!isFile && (!isLoopback(parsed.hostname) || parsed.origin === location.origin)) {
993
+ flash(panel, t('notice.notLocal'))
994
+ return false
995
+ }
996
+ const request = (panel.openRequest || 0) + 1
997
+ panel.openRequest = request
998
+ panel.model.set({ loading: true, error: null, view: 'page', input: url })
999
+ const lease = crypto.randomUUID()
1000
+ const preview = await api('preview', { sid: panel.sid, url, root: panel.model.get().root, lease, parentOrigin: location.origin })
1001
+ if (panel.openRequest !== request) {
1002
+ if (preview.ok) void api('releasePreview', { sid: panel.sid, origin: preview.origin, lease })
1003
+ return false
1004
+ }
1005
+ if (!preview.ok) {
1006
+ panel.model.set({ loading: false, error: hostMessage(preview, 'notice.previewFailed') })
1007
+ return false
1008
+ }
1009
+ const state = panel.model.get()
1010
+ const history = state.previewOrigin !== preview.origin ? [url] : push ? state.history.slice(0, state.index + 1).concat([url]) : state.history
1011
+ const entry = ensureFrame(panel, preview, url)
1012
+ const pageTitle = isFile ? decodeURIComponent(parsed.pathname.split('/').pop() || '') : (parsed.host + parsed.pathname)
1013
+ recordRecent(panel, url, pageTitle)
1014
+ panel.model.set({
1015
+ view: 'page',
1016
+ url: url,
1017
+ input: url,
1018
+ src: preview.url,
1019
+ previewOrigin: preview.origin,
1020
+ previewLease: lease,
1021
+ history: history.slice(-40),
1022
+ index: Math.min(history.length - 1, 39),
1023
+ mode: 'idle',
1024
+ annotations: readAnnotations(panel, url),
1025
+ draft: readDraft(panel, url),
1026
+ menuOpen: false, sendMenuOpen: false, listOpen: false,
1027
+ page: isFile ? '/' + decodeURIComponent(parsed.pathname.split('/').pop() || '') : parsed.pathname,
1028
+ notice: null,
1029
+ })
1030
+ panel.frame = entry.frame
1031
+ frameRef = entry.frame
1032
+ if (entry.loaded) {
1033
+ notify('ping', {}, panel)
1034
+ notify('lang', { lang: i18n.lang }, panel)
1035
+ }
1036
+ return true
1037
+ }
1038
+
1039
+ const detectCacheKey = (root) => 'dsh-annotate:detect:v3:' + encodeURIComponent(root || '')
1040
+ const readDetectCache = (root) => {
1041
+ try {
1042
+ const value = JSON.parse(localStorage.getItem(detectCacheKey(root)) || 'null')
1043
+ if (!value || !Array.isArray(value.services)) return null
1044
+ return value
1045
+ } catch (error) {
1046
+ void error
1047
+ return null
1048
+ }
1049
+ }
1050
+ const writeDetectCache = (root, data) => {
1051
+ try { localStorage.setItem(detectCacheKey(root), JSON.stringify(data)) } catch (error) { void error }
1052
+ }
1053
+
1054
+ const runDetect = async (panel, options) => {
1055
+ const auto = !options || options.auto !== false
1056
+ // Check and claim the busy flag in that order: reading it after setting it
1057
+ // would make the re-entrancy guard a no-op.
1058
+ if (panel.model.get().detect === 'busy') return
1059
+ panel.model.set({ detect: 'busy' })
1060
+ const state = panel.model.get()
1061
+ const res = await api('detect', { sid: panel.sid, root: state.root, force: options?.force })
1062
+ if (!res || !res.ok) {
1063
+ panel.model.set({ detect: 'error' })
1064
+ flash(panel, t('notice.detectFailed', { error: hostMessage(res, 'notice.unknownError') }))
1065
+ return
1066
+ }
1067
+ const services = res.services || []
1068
+ panel.model.set({
1069
+ services: services,
1070
+ files: [],
1071
+ hint: res.hint || null,
1072
+ scanned: res.scanned || 0,
1073
+ detect: 'idle',
1074
+ })
1075
+ writeDetectCache(state.root, { at: Date.now(), services, scanned: res.scanned || 0, hint: res.hint || null })
1076
+ const current = panel.model.get()
1077
+ // One candidate and nothing open: the zero-configuration promise.
1078
+ if (auto && current.view === 'list' && !current.url && services.length === 1) {
1079
+ openUpstream(panel, services[0].url, { push: true })
1080
+ flash(panel, t('notice.autoOpened'))
1081
+ }
1082
+ }
1083
+
1084
+ const annotationKey = (panel, url) => 'dsh-review:v2:' + encodeURIComponent(panel.sid) + ':' + encodeURIComponent(url)
1085
+ const readAnnotations = (panel, url) => {
1086
+ try { const value = JSON.parse(localStorage.getItem(annotationKey(panel, url)) || '[]'); return Array.isArray(value) ? value : [] } catch { return [] }
1087
+ }
1088
+ const readDraft = (panel, url) => {
1089
+ try { return JSON.parse(localStorage.getItem(annotationKey(panel, url) + ':draft') || 'null') } catch { return null }
1090
+ }
1091
+ const writeAnnotations = (panel, url, annotations) => {
1092
+ try { localStorage.setItem(annotationKey(panel, url), JSON.stringify(annotations)) }
1093
+ catch { flash(panel, t('notice.storageUnavailable')) }
1094
+ }
1095
+ const recentKey = (root) => 'dsh-annotate:recent:v1:' + encodeURIComponent(root || '')
1096
+ const readRecent = (root) => {
1097
+ try {
1098
+ const value = JSON.parse(localStorage.getItem(recentKey(root)) || '[]')
1099
+ return Array.isArray(value) ? value : []
1100
+ } catch (error) {
1101
+ void error
1102
+ return []
1103
+ }
1104
+ }
1105
+ const saveRecent = (root, list) => {
1106
+ try { localStorage.setItem(recentKey(root), JSON.stringify(list)) } catch (error) { void error }
1107
+ }
1108
+ const recordRecent = (panel, url, title) => {
1109
+ const root = panel.model.get().root
1110
+ const previous = readRecent(root)
1111
+ const existing = previous.find((item) => item.url === url)
1112
+ const next = [{ url, title: title || url, time: Date.now(), fav: existing ? !!existing.fav : false }]
1113
+ .concat(previous.filter((item) => item.url !== url))
1114
+ .slice(0, 20)
1115
+ saveRecent(root, next)
1116
+ panel.model.set({ recent: next })
1117
+ }
1118
+ const removeRecent = (panel, url) => {
1119
+ const root = panel.model.get().root
1120
+ const next = readRecent(root).filter((item) => item.url !== url)
1121
+ saveRecent(root, next)
1122
+ panel.model.set({ recent: next })
1123
+ }
1124
+ const toggleFav = (panel, url) => {
1125
+ const root = panel.model.get().root
1126
+ const next = readRecent(root).map((item) => (item.url === url ? Object.assign({}, item, { fav: !item.fav }) : item))
1127
+ saveRecent(root, next)
1128
+ panel.model.set({ recent: next })
1129
+ }
1130
+ const clearRecent = (panel) => {
1131
+ const root = panel.model.get().root
1132
+ try { localStorage.removeItem(recentKey(root)) } catch (error) { void error }
1133
+ panel.model.set({ recent: [] })
1134
+ }
1135
+ const followNavigation = (panel, url) => {
1136
+ const current = panel.model.get()
1137
+ if (!url || url === current.url) return
1138
+ const expected = panel.historyTarget
1139
+ const isTraversal = expected !== undefined && current.history[expected] === url
1140
+ const history = isTraversal ? current.history : current.history.slice(0, current.index + 1).concat([url])
1141
+ panel.historyTarget = undefined
1142
+ const pooled = framePool.get(poolKey(panel, current.previewOrigin))
1143
+ if (pooled) pooled.requestedUrl = url
1144
+ panel.model.set({ url, input: url, history: history.slice(-40), index: isTraversal ? expected : Math.min(history.length - 1, 39), annotations: readAnnotations(panel, url), draft: readDraft(panel, url), mode: 'idle', listOpen: false, menuOpen: false, sendMenuOpen: false })
1145
+ }
1146
+ const sendAll = async (panel, setDraft, options) => {
1147
+ const state = panel.model.get()
1148
+ if (!state.annotations.length || state.sending) return false
1149
+ if (state.mode === 'writing' || (state.draft?.existing && state.annotations.some((ann) => ann.id === state.draft.id))) { flash(panel, t('notice.finishEditing')); return false }
1150
+ const submit = !options || options.submit !== false
1151
+ const block = payloadBlock(state.annotations, state.url, state.viewport)
1152
+ const ids = state.annotations.map((ann) => ann.id)
1153
+ const clearAccepted = () => {
1154
+ const stored = readAnnotations(panel, state.url)
1155
+ const accepted = stored.filter((ann) => state.annotations.some((sent) => sent.id === ann.id && sent.comment === ann.comment))
1156
+ const acceptedIds = accepted.map((ann) => ann.id)
1157
+ const remaining = stored.filter((ann) => !acceptedIds.includes(ann.id))
1158
+ writeAnnotations(panel, state.url, remaining)
1159
+ if (panel.model.get().url === state.url) {
1160
+ panel.model.set({ annotations: remaining, mode: 'idle', listOpen: remaining.length ? panel.model.get().listOpen : false })
1161
+ if (activePanel === panel) notify('clear', { ids: acceptedIds })
1162
+ }
1163
+ }
1164
+ if (!submit) {
1165
+ const writer = setDraft || panel.draftWriter?.setDraft
1166
+ if (!writer) { flash(panel, t('notice.noComposer')); return false }
1167
+ const current = String(panel.draftWriter?.draft || '')
1168
+ const next = current.includes(block) ? current : (current ? current.trimEnd() + '\n\n' : '') + block
1169
+ try { writer(next) } catch { flash(panel, t('notice.attachFailed')); return false }
1170
+ if (panel.draftWriter) panel.draftWriter.draft = next
1171
+ panel.model.set({ pending: state.pending.concat([{ id: crypto.randomUUID(), count: ids.length, payload: block }]) })
1172
+ clearAccepted()
1173
+ flash(panel, t('notice.attached'))
1174
+ return true
1175
+ }
1176
+ // Use the session-addressed public controller and its admission receipt.
1177
+ // Existing composer drafts and attachments are deliberately untouched.
1178
+ const sessions = ctx.get('sessions')
1179
+ const scope = sessions?.scope?.(panel.sid)
1180
+ const session = scope && sessions.sessionOf(scope)
1181
+ if (!session?.prompt) { flash(panel, t('notice.sendUnsupported')); return false }
1182
+ panel.model.set({ sending: true, notice: null, canRetrySend: false })
1183
+ notify('busy', { value: true }, panel)
1184
+ let submission
1185
+ try {
1186
+ submission = session.beginSubmission({ mode: 'queue', text: block, attachments: [] })
1187
+ const result = await session.prompt([{ type: 'text', text: block }], 'queue', undefined, submission.requestId)
1188
+ if (!result?.ok || !result.value?.accepted) throw new Error(result?.error?.message || t('notice.notAccepted'))
1189
+ clearAccepted()
1190
+ flash(panel, t('notice.accepted', { count: ids.length }))
1191
+ return true
1192
+ } catch (error) {
1193
+ submission?.abandon()
1194
+ flash(panel, t('notice.sendFailed', { error: String(error.message || error) }), { kind: 'error', retry: true })
1195
+ return false
1196
+ } finally { panel.model.set({ sending: false }); if (panel.frame) notify('busy', { value: false }, panel) }
1197
+ }
1198
+
1199
+ // --------------------------------------------------------------- tab body
1200
+
1201
+ const AnnotateTab = (props) => {
1202
+ const panel = getPanel(props.sessionId)
1203
+ activePanel = panel
1204
+ useSub(panel.model)
1205
+ const state = panel.model.get()
1206
+ const stageRef = React.useRef(null)
1207
+ const annotations = state.annotations
1208
+ const draft = props.useInput ? props.useInput((s) => s.draft) : ''
1209
+ const sessionId = props.sessionId
1210
+ const inputActions = props.inputActions
1211
+ const workspaceItems = props.useWorkspaces ? props.useWorkspaces((snapshot) => snapshot.items) : undefined
1212
+
1213
+ React.useEffect(() => {
1214
+ const list = Array.isArray(workspaceItems) ? workspaceItems : []
1215
+ const mine = list.find((item) => item && Array.isArray(item.sessionIds) && item.sessionIds.indexOf(sessionId) !== -1)
1216
+ const root = (mine && mine.path) || (list[0] && list[0].path) || ''
1217
+ if (root && root !== panel.model.get().root) panel.model.set({ root: root, recent: readRecent(root) })
1218
+ }, [sessionId, workspaceItems, panel])
1219
+
1220
+ // First look around: show what we remember instantly, then refresh in the
1221
+ // background (force the first scan so the cache is never the only truth).
1222
+ React.useEffect(() => {
1223
+ let cancelled = false
1224
+ void (async () => {
1225
+ const hostState = await api('state', { sid: sessionId })
1226
+ if (cancelled) return
1227
+ if (!hostState?.ok) { panel.model.set({ detect: 'error' }); flash(panel, t('notice.pluginUnavailable')); return }
1228
+ const current = panel.model.get()
1229
+ if (!current.url) {
1230
+ const cached = readDetectCache(current.root)
1231
+ if (cached) panel.model.set({ services: cached.services || [], scanned: cached.scanned || 0, hint: cached.hint || null, detect: 'idle' })
1232
+ await runDetect(panel, { auto: true, force: !cached })
1233
+ } else if (current.view === 'page') await openUpstream(panel, current.url, { push: false })
1234
+ })()
1235
+ return () => {
1236
+ cancelled = true
1237
+ panel.openRequest = (panel.openRequest || 0) + 1
1238
+ const current = panel.model.get()
1239
+ if (current.previewLease) void api('releasePreview', { sid: panel.sid, origin: current.previewOrigin, lease: current.previewLease })
1240
+ hidePool()
1241
+ }
1242
+ }, [panel, sessionId])
1243
+
1244
+ React.useEffect(() => {
1245
+ if (state.view !== 'page' || !state.previewLease) return undefined
1246
+ const args = { sid: panel.sid, origin: state.previewOrigin, lease: state.previewLease }
1247
+ let cancelled = false
1248
+ const retain = async () => {
1249
+ const result = await api('retainPreview', args)
1250
+ // A suspended tab may outlive its lease; reopening restores annotations
1251
+ // from the Harness origin instead of leaving a dead iframe behind.
1252
+ if (!result.ok && !cancelled) await openUpstream(panel, panel.model.get().url, { push: false })
1253
+ }
1254
+ const timer = setInterval(retain, 30_000)
1255
+ const onVisible = () => { if (!document.hidden) void retain() }
1256
+ document.addEventListener('visibilitychange', onVisible)
1257
+ return () => {
1258
+ cancelled = true
1259
+ clearInterval(timer)
1260
+ document.removeEventListener('visibilitychange', onVisible)
1261
+ void api('releasePreview', args)
1262
+ }
1263
+ }, [panel, state.view, state.previewOrigin, state.previewLease])
1264
+
1265
+ // Keep the pooled iframe aligned with the stage. The frame never moves in the
1266
+ // DOM (that would reload it); only its fixed position and size are updated.
1267
+ React.useEffect(() => {
1268
+ const layer = ensureLayer()
1269
+ // The frame sits on <body> so it survives session switches. To let clicks and
1270
+ // wheel events reach it through the sidebar, the sidebar's wrapper chain is
1271
+ // made transparent to pointer events (the toolbar/footer opt back in), and
1272
+ // the panel backdrop is cleared so the frame is not tinted.
1273
+ const passthroughNodes = () => {
1274
+ const nodes = []
1275
+ let el = document.querySelector('.dsa-col')
1276
+ while (el && el !== document.body) {
1277
+ const cls = typeof el.className === 'string' ? el.className : ''
1278
+ if (/tabBody|paneBody|_tabHost_/.test(cls)) nodes.push(el)
1279
+ el = el.parentElement
1280
+ }
1281
+ return nodes
1282
+ }
1283
+ const applyPassthrough = (on) => {
1284
+ for (const node of passthroughNodes()) {
1285
+ node.classList.toggle('dsa-passthrough', on)
1286
+ node.classList.toggle('dsa-passthrough-bg', on)
1287
+ }
1288
+ }
1289
+ const sync = () => {
1290
+ const stage = stageRef.current
1291
+ const current = panel.model.get()
1292
+ const entry = current.previewOrigin ? framePool.get(poolKey(panel, current.previewOrigin)) : null
1293
+ // Show the frame as soon as it exists, even while loading: a
1294
+ // display:none / 0×0 iframe can be throttled and never run its scripts,
1295
+ // which would leave the ready handshake waiting forever.
1296
+ if (!stage || !entry || current.view !== 'page' || current.error) {
1297
+ applyPassthrough(false)
1298
+ layer.style.display = 'none'
1299
+ for (const item of framePool.values()) item.frame.style.display = 'none'
1300
+ return
1301
+ }
1302
+ applyPassthrough(true)
1303
+ const rect = stage.getBoundingClientRect()
1304
+ const host = layer.parentElement
1305
+ const base = host && host !== document.body ? host.getBoundingClientRect() : { left: 0, top: 0 }
1306
+ const width = current.width && current.width !== 'fit' ? Math.min(Number(current.width) || rect.width, rect.width) : rect.width
1307
+ const left = rect.left - base.left + Math.max(0, (rect.width - width) / 2)
1308
+ const reserve = current.listOpen || current.draft ? 70 : 0
1309
+ layer.style.display = 'block'
1310
+ for (const item of framePool.values()) {
1311
+ if (item === entry) {
1312
+ Object.assign(item.frame.style, {
1313
+ display: 'block', left: left + 'px', top: (rect.top - base.top) + 'px',
1314
+ width: width + 'px', height: Math.max(0, rect.height - reserve) + 'px',
1315
+ })
1316
+ } else {
1317
+ item.frame.style.display = 'none'
1318
+ }
1319
+ }
1320
+ frameRef = entry.frame
1321
+ panel.frame = entry.frame
1322
+ }
1323
+ sync()
1324
+ const timer = setInterval(sync, 200)
1325
+ window.addEventListener('resize', sync)
1326
+ document.addEventListener('scroll', sync, true)
1327
+ return () => {
1328
+ clearInterval(timer)
1329
+ window.removeEventListener('resize', sync)
1330
+ document.removeEventListener('scroll', sync, true)
1331
+ applyPassthrough(false)
1332
+ hidePool()
1333
+ }
1334
+ }, [panel, state.view, state.previewOrigin, state.width, state.listOpen, !!state.draft, state.loading, state.error])
1335
+
1336
+ React.useEffect(() => {
1337
+ panel.draftWriter = {
1338
+ sessionId: sessionId,
1339
+ draft: draft,
1340
+ setDraft: inputActions?.setDraft ? (value) => inputActions.setDraft(value) : null,
1341
+ }
1342
+ }, [panel, sessionId, draft, inputActions])
1343
+
1344
+ React.useEffect(() => {
1345
+ if (state.view !== 'list') return undefined
1346
+ const timer = setInterval(() => { if (!document.hidden) void runDetect(panel, { auto: false }) }, 5000)
1347
+ return () => clearInterval(timer)
1348
+ }, [panel, state.view])
1349
+ React.useEffect(() => {
1350
+ if (!state.loading) return undefined
1351
+ const timer = setTimeout(() => panel.model.set({ loading: false, error: t('notice.loadTimeout') }), 18000)
1352
+ return () => clearTimeout(timer)
1353
+ }, [panel, state.loading, state.src])
1354
+ React.useEffect(() => () => { if (activePanel === panel) activePanel = null }, [panel])
1355
+
1356
+ React.useEffect(() => {
1357
+ if (!state.menuOpen && !state.listOpen && !state.sendMenuOpen) return undefined
1358
+ const close = (event) => {
1359
+ if (event.target.closest?.('.dsa-popover, .dsa-popup-trigger')) return
1360
+ panel.model.set({ menuOpen: false, helpOpen: false, listOpen: false, sendMenuOpen: false })
1361
+ }
1362
+ document.addEventListener('pointerdown', close)
1363
+ return () => document.removeEventListener('pointerdown', close)
1364
+ }, [panel, state.menuOpen, state.listOpen, state.sendMenuOpen])
1365
+
1366
+ React.useEffect(() => {
1367
+ const onMessage = (event) => {
1368
+ const frame = frameRef
1369
+ if (!frame || event.source !== frame.contentWindow || event.origin !== panel.model.get().previewOrigin) return
1370
+ const data = event.data
1371
+ if (!data) return
1372
+ if (data.source === CHANNEL_IN) {
1373
+ if (data.type === 'ready' || data.type === 'changed') {
1374
+ // Reusing an already loaded iframe only sends ping: there is no
1375
+ // new load/navigation event after an HTTP redirect. Follow the
1376
+ // overlay's actual URL before restoring or clearing its notes.
1377
+ followNavigation(panel, data.url)
1378
+ const current = panel.model.get()
1379
+ const pageUrl = data.url || current.url
1380
+ if (data.type === 'ready') {
1381
+ const draft = readDraft(panel, pageUrl)
1382
+ panel.model.set({ draft })
1383
+ notify('restore', { annotations: readAnnotations(panel, pageUrl), draft })
1384
+ }
1385
+ else writeAnnotations(panel, pageUrl, data.annotations || [])
1386
+ const nextAnnotations = data.type === 'ready' ? readAnnotations(panel, pageUrl) : data.annotations || []
1387
+ panel.model.set({
1388
+ loading: false,
1389
+ error: null,
1390
+ mode: data.type === 'ready' ? 'idle' : current.mode,
1391
+ annotations: nextAnnotations,
1392
+ listOpen: nextAnnotations.length ? current.listOpen : false,
1393
+ viewport: data.viewport || current.viewport,
1394
+ // The overlay reports the proxied path; the upstream URL is the
1395
+ // one worth keeping, so only fill in when we have nothing.
1396
+ page: current.url ? current.page : data.path || current.page,
1397
+ })
1398
+ } else if (data.type === 'draft') {
1399
+ panel.model.set({ draft: data.draft || null })
1400
+ try { localStorage.setItem(annotationKey(panel, data.url || panel.model.get().url) + ':draft', JSON.stringify(data.draft)) } catch { flash(panel, t('notice.draftUnavailable')) }
1401
+ } else if (data.type === 'interact') {
1402
+ panel.model.set({ menuOpen: false, sendMenuOpen: false, listOpen: false, helpOpen: false })
1403
+ } else if (data.type === 'warning' || data.type === 'missing') {
1404
+ flash(panel, data.message || t('notice.elementGone'))
1405
+ } else if (data.type === 'mode') {
1406
+ panel.model.set({ mode: data.mode })
1407
+ } else if (data.type === 'send') {
1408
+ sendAll(panel, inputActions && inputActions.setDraft)
1409
+ }
1410
+ return
1411
+ }
1412
+ if (data.source === PAGE_CHANNEL && data.type === 'error') { panel.model.set({ loading: false, error: hostMessage({ code: data.code, error: data.message }, 'notice.previewFailed') }); return }
1413
+ if (data.source === PAGE_CHANNEL && data.type === 'navigated' && data.url) {
1414
+ // SPA route change: follow it in the address bar and remember it.
1415
+ followNavigation(panel, data.url)
1416
+ }
1417
+ }
1418
+ window.addEventListener('message', onMessage)
1419
+ return () => window.removeEventListener('message', onMessage)
1420
+ }, [panel, inputActions, annotations])
1421
+
1422
+ const go = (delta) => {
1423
+ const current = panel.model.get()
1424
+ const index = current.index + delta
1425
+ if (index < 0 || index >= current.history.length) return
1426
+ panel.historyTarget = index
1427
+ notify('navigate', { delta })
1428
+ }
1429
+
1430
+ const reload = () => { panel.model.set({ loading: true, error: null }); notify('reload') }
1431
+
1432
+ const copy = async (text) => {
1433
+ try {
1434
+ await navigator.clipboard.writeText(text)
1435
+ flash(panel, t('list.copied', { text: text }))
1436
+ } catch (error) {
1437
+ void error
1438
+ }
1439
+ }
1440
+
1441
+ const showList = () => {
1442
+ if (panel.model.get().previewOrigin) disposeFrame(panel, panel.model.get().previewOrigin)
1443
+ panel.model.set({ view: 'list', src: '', previewOrigin: '', previewLease: '', mode: 'idle', notice: null, loading: false, error: null, listOpen: false, helpOpen: false, menuOpen: false, sendMenuOpen: false })
1444
+ panel.openRequest = (panel.openRequest || 0) + 1
1445
+ hidePool()
1446
+ notify('set-mode', { mode: 'idle' })
1447
+ void runDetect(panel, { auto: false })
1448
+ }
1449
+
1450
+ /** The overlay owns the mode (it may be mid-card), so ask it to toggle and
1451
+ * let its `mode` message update this button. */
1452
+ const toggleMode = () => {
1453
+ notify('toggle-mode')
1454
+ }
1455
+
1456
+ const notice = state.notice
1457
+ ? React.createElement(
1458
+ 'div',
1459
+ { className: 'dsa-notice' + (state.view === 'page' ? ' dsa-toast' : ''), role: state.noticeKind === 'error' ? 'alert' : 'status', 'aria-live': 'polite', 'data-kind': state.noticeKind || 'info' },
1460
+ state.notice,
1461
+ state.canRetrySend ? React.createElement('button', { type: 'button', disabled: state.sending, onClick: () => sendAll(panel, inputActions?.setDraft) }, t('page.retry')) : null,
1462
+ state.undoAvailable ? React.createElement('button', { type: 'button', onClick: () => { notify('undo'); panel.model.set({ undoAvailable: false, notice: null }) } }, t('notice.undo')) : null,
1463
+ React.createElement('button', { className: 'dsa-dismiss', type: 'button', title: t('notice.dismiss'), 'aria-label': t('notice.dismiss'), onClick: () => panel.model.set({ notice: null }) }, '✕')
1464
+ )
1465
+ : null
1466
+
1467
+ const pickFile = () => {
1468
+ const input = document.createElement('input')
1469
+ input.type = 'file'
1470
+ input.accept = '.html,.htm,text/html'
1471
+ input.style.display = 'none'
1472
+ input.addEventListener('change', () => {
1473
+ const file = input.files && input.files[0]
1474
+ let path = ''
1475
+ if (file) {
1476
+ path = file.path || (window.dsh && window.dsh.webUtils && window.dsh.webUtils.getPathForFile ? window.dsh.webUtils.getPathForFile(file) : '')
1477
+ }
1478
+ input.remove()
1479
+ if (path) openUpstream(panel, fileAddressOf(path))
1480
+ else flash(panel, t('notice.filePathUnavailable'))
1481
+ })
1482
+ document.body.appendChild(input)
1483
+ input.click()
1484
+ }
1485
+
1486
+ if (state.view === 'list') {
1487
+ const services = state.services
1488
+ const recent = (state.recent || []).slice().sort((a, b) => (b.fav ? 1 : 0) - (a.fav ? 1 : 0))
1489
+ const commands =
1490
+ state.hint && state.hint.commands && state.hint.commands.length
1491
+ ? state.hint.commands
1492
+ : [{ script: 'dev', command: 'npm run dev' }]
1493
+ const tag = (key, extra) => React.createElement('span', { className: 'dsa-tag' + (extra ? ' ' + extra : '') }, t(key))
1494
+ return React.createElement(
1495
+ 'div',
1496
+ { className: 'dsa-col' },
1497
+ notice,
1498
+ React.createElement(
1499
+ 'div',
1500
+ { className: 'dsa-listwrap' },
1501
+ React.createElement('div', { className: 'dsa-openrow dsa-openrow-top' },
1502
+ React.createElement('input', {
1503
+ value: state.input, spellCheck: false, placeholder: t('list.placeholder'), 'aria-label': t('list.addressLabel'),
1504
+ onChange: (event) => panel.model.set({ input: event.target.value }),
1505
+ onKeyDown: (event) => { if (event.key === 'Enter' && !event.nativeEvent?.isComposing) openUpstream(panel, event.target.value) },
1506
+ }),
1507
+ React.createElement('button', { type: 'button', onClick: () => openUpstream(panel, state.input) }, t('list.openButton')),
1508
+ React.createElement('button', { type: 'button', className: 'dsa-pickbtn', title: t('list.pickFile'), onClick: pickFile }, t('list.pickFile'))),
1509
+ recent.length ? React.createElement('div', { className: 'dsa-recent' },
1510
+ React.createElement('div', { className: 'dsa-sechead is-sub' }, t('list.recentHeader'),
1511
+ React.createElement('button', { className: 'dsa-link', type: 'button', onClick: () => clearRecent(panel) }, t('list.clearRecent'))),
1512
+ recent.map((item) => React.createElement('div', { className: 'dsa-recentrow', key: item.url },
1513
+ React.createElement('button', { className: 'dsa-recent-open', type: 'button', title: item.url, onClick: () => openUpstream(panel, item.url) },
1514
+ React.createElement('span', { className: 'copy' }, React.createElement('b', null, item.title || item.url), React.createElement('span', null, item.url))),
1515
+ React.createElement('button', { className: 'dsa-mini dsa-fav' + (item.fav ? ' is-fav' : ''), type: 'button', title: t('list.favorite'), 'aria-pressed': !!item.fav, onClick: () => toggleFav(panel, item.url) }, '★'),
1516
+ React.createElement('button', { className: 'dsa-mini', type: 'button', title: t('list.removeRecent'), onClick: () => removeRecent(panel, item.url) }, '✕')))) : null,
1517
+ React.createElement(
1518
+ 'div',
1519
+ { className: 'dsa-sechead' },
1520
+ state.detect === 'busy'
1521
+ ? t('list.detecting')
1522
+ : services.length
1523
+ ? t('list.detected', { count: services.length })
1524
+ : t('list.none'),
1525
+ React.createElement(
1526
+ 'button',
1527
+ { className: 'dsa-ico', type: 'button', title: t('list.redetect'), disabled: state.detect === 'busy', onClick: () => void runDetect(panel, { auto: false }) },
1528
+ React.createElement(Icon, { name: 'refresh' })
1529
+ )
1530
+ ),
1531
+ services.map((service) =>
1532
+ React.createElement(
1533
+ 'button',
1534
+ { className: 'dsa-svc' + (service.project ? ' is-project' : ''), type: 'button', key: service.port, onClick: () => openUpstream(panel, service.url) },
1535
+ React.createElement('span', { className: 'dot' }),
1536
+ React.createElement(
1537
+ 'span',
1538
+ { className: 'copy' },
1539
+ React.createElement(
1540
+ 'b',
1541
+ null,
1542
+ service.title || service.url,
1543
+ service.project ? tag('list.project', 'is-project') : service.declared ? tag('list.declared') : null
1544
+ ),
1545
+ React.createElement('span', null, service.url)
1546
+ ),
1547
+ React.createElement('span', { className: 'go' }, t('list.open'))
1548
+ )
1549
+ ),
1550
+ !services.length && state.detect !== 'busy'
1551
+ ? React.createElement(
1552
+ 'div',
1553
+ { className: 'dsa-hintbox' },
1554
+ React.createElement('p', null, t('list.emptyHint', { count: state.scanned || 0 })),
1555
+ commands.map((entry) =>
1556
+ React.createElement(
1557
+ 'div',
1558
+ { className: 'dsa-cmd', key: entry.command },
1559
+ React.createElement('code', null, entry.command),
1560
+ React.createElement('button', { type: 'button', onClick: () => copy(entry.command) }, t('list.copy'))
1561
+ )
1562
+ ),
1563
+ React.createElement('p', { style: { marginTop: '10px' } }, t('list.autoRefresh'))
1564
+ )
1565
+ : null
1566
+ )
1567
+ )
1568
+ }
1569
+
1570
+ const h = React.createElement
1571
+ const batchVisible = annotations.length > 0 || !!state.draft
1572
+ const closeMenus = () => panel.model.set({ menuOpen: false, helpOpen: false, sendMenuOpen: false, listOpen: false })
1573
+ const iconButton = (label, icon, onClick, props) => h('button', Object.assign({
1574
+ className: 'dsa-ico', type: 'button', title: label, 'aria-label': label, onClick,
1575
+ }, props), h(Icon, { name: icon }))
1576
+ const openComment = (ann) => { closeMenus(); notify('view', { id: ann.id }) }
1577
+ const resumeDraft = () => { closeMenus(); notify('resume-draft') }
1578
+ const draftRow = state.draft ? h('div', { className: 'dsa-item dsa-draft', key: 'draft' },
1579
+ h('button', { className: 'dsa-note-open', type: 'button', onClick: resumeDraft, title: t('page.resumeDraft') },
1580
+ h('span', { className: 'dsa-idx', 'aria-hidden': true }, '✎'),
1581
+ h('span', { className: 'dsa-body' }, h('span', { className: 'dsa-comment' }, state.draft.comment), h('span', { className: 'dsa-draft-label' }, t('page.draft')))),
1582
+ iconButton(t('page.discardDraft'), 'trash', () => notify('discard-draft'), { className: 'dsa-mini', 'data-danger': 'true' })) : null
1583
+
1584
+ return h('div', { className: state.view === 'page' ? 'dsa-col dsa-col-page' : 'dsa-col' },
1585
+ h('div', { className: 'dsa-bar' },
1586
+ iconButton(t('page.backToList'), 'back', showList),
1587
+ h('div', { className: 'dsa-address' },
1588
+ h('input', {
1589
+ className: 'dsa-url', value: state.input, spellCheck: false, placeholder: t('page.addressPlaceholder'), 'aria-label': t('list.addressLabel'),
1590
+ onChange: (event) => panel.model.set({ input: event.target.value }),
1591
+ onKeyDown: (event) => { if (event.key === 'Enter' && !event.nativeEvent?.isComposing) { closeMenus(); openUpstream(panel, event.target.value) } },
1592
+ }), iconButton(t('page.reload'), 'refresh', () => { closeMenus(); reload() })),
1593
+ h('button', {
1594
+ className: 'dsa-ico dsa-mark', type: 'button', title: t('page.markTitle'), 'aria-label': t('page.markTitle'),
1595
+ 'aria-pressed': state.mode !== 'idle', 'data-on': state.mode !== 'idle' ? 'true' : 'false',
1596
+ disabled: state.loading || !!state.error || state.sending, onClick: () => { closeMenus(); toggleMode() },
1597
+ }, h(Icon, { name: 'marker' }), h('span', null, t('page.mark'))),
1598
+ iconButton(t('page.more'), 'more', () => panel.model.set({ menuOpen: !state.menuOpen, listOpen: false, sendMenuOpen: false }), {
1599
+ className: 'dsa-ico dsa-popup-trigger', 'aria-expanded': !!state.menuOpen, 'aria-controls': 'dsa-menu-' + sessionId,
1600
+ }),
1601
+ state.menuOpen ? h('div', { className: 'dsa-popover dsa-menu', id: 'dsa-menu-' + sessionId, role: 'region', 'aria-label': t('page.more') },
1602
+ h('button', { type: 'button', title: t('page.back'), disabled: state.index <= 0, onClick: () => { closeMenus(); go(-1) } }, h(Icon, { name: 'back' }), t('page.back')),
1603
+ h('button', { type: 'button', title: t('page.forward'), disabled: state.index >= state.history.length - 1, onClick: () => { closeMenus(); go(1) } }, h(Icon, { name: 'forward' }), t('page.forward')),
1604
+ h('div', { className: 'dsa-menu-row' }, h('label', { htmlFor: 'dsa-width-' + sessionId }, t('page.widthLabel')),
1605
+ h('select', { id: 'dsa-width-' + sessionId, className: 'dsa-width', value: state.width, onChange: (event) => panel.model.set({ width: event.target.value }) },
1606
+ h('option', { value: 'fit' }, t('page.widthFit')), h('option', { value: '390' }, t('page.widthMobile')))),
1607
+ h('button', { className: 'dsa-lang', type: 'button', title: t('panel.languageSwitch', { lang: i18n.nextLabel() }), 'aria-label': t('panel.languageSwitch', { lang: i18n.nextLabel() }), onClick: () => switchLanguage(panel) },
1608
+ t('panel.language'), h('span', { className: 'dsa-menu-value' }, i18n.nextLabel())),
1609
+ h('button', { type: 'button', onClick: () => { closeMenus(); window.open(state.url, '_blank', 'noopener') } }, h(Icon, { name: 'external' }), t('page.openExternal')),
1610
+ h('div', { className: 'dsa-menu-sep' }),
1611
+ h('button', { type: 'button', 'aria-expanded': state.helpOpen, onClick: () => panel.model.set({ helpOpen: !state.helpOpen }) }, h(Icon, { name: 'help' }), t('page.help')),
1612
+ state.helpOpen ? h('div', { className: 'dsa-help' },
1613
+ h('b', null, t('list.helpHeader')), h('p', null, t('list.helpPicking')), h('p', null, t('list.helpEscape')), h('p', null, t('list.helpCmdClick')),
1614
+ h('b', null, t('list.helpSendHeader')), h('p', null, t('list.helpSendList')), h('p', null, t('list.helpSendActions'))) : null) : null),
1615
+ h('div', { className: 'dsa-stage', ref: stageRef },
1616
+ state.error || state.loading ? h('div', { className: 'dsa-empty' },
1617
+ h('h4', null, t(state.error ? 'page.unavailable' : 'page.loading')), h('p', null, state.error || t('page.loadingHint')),
1618
+ state.error ? h('button', { className: 'dsa-send', type: 'button', onClick: () => openUpstream(panel, state.input) }, t('page.retry')) : null) : null,
1619
+ state.mode === 'picking' ? h('div', { className: 'dsa-pick-hint', 'data-batch': batchVisible ? 'true' : 'false' }, t('page.pickHint')) : null,
1620
+ batchVisible ? h('div', { className: 'dsa-foot', 'aria-label': t('page.batch') },
1621
+ h('button', {
1622
+ className: 'dsa-review-toggle dsa-popup-trigger', type: 'button', 'aria-expanded': state.listOpen,
1623
+ 'aria-controls': 'dsa-review-panel-' + sessionId, 'aria-label': annotations.length ? t('page.listToggleLabel', { count: annotations.length }) : t('page.resumeDraft'),
1624
+ title: state.listOpen ? t('page.listCollapse') : t('page.listExpand'),
1625
+ onClick: () => { if (!annotations.length && state.draft) resumeDraft(); else panel.model.set({ listOpen: !state.listOpen, sendMenuOpen: false, menuOpen: false }) },
1626
+ }, h(Icon, { name: 'review' }), annotations.length ? t('page.batchCount', { count: annotations.length }) : t('page.draft')),
1627
+ h('span', { className: 'dsa-divider', 'aria-hidden': true }),
1628
+ iconButton(t('page.sendOptions'), 'more', () => panel.model.set({ sendMenuOpen: !state.sendMenuOpen, listOpen: false, menuOpen: false }), { className: 'dsa-ico dsa-popup-trigger', 'aria-expanded': !!state.sendMenuOpen, 'aria-controls': 'dsa-submit-menu-' + sessionId }),
1629
+ h('button', { className: 'dsa-send', type: 'button', title: t('page.sendHint'), 'aria-label': t(state.sending ? 'page.sending' : 'page.send'), disabled: !annotations.length || state.sending,
1630
+ onClick: (event) => { closeMenus(); sendAll(panel, inputActions?.setDraft, { submit: !(event.altKey || event.metaKey) }) },
1631
+ }, state.sending ? h('span', { className: 'dsa-busy', 'aria-hidden': true }, '···') : h(Icon, { name: 'send' }))) : null,
1632
+ state.listOpen && batchVisible ? h('div', {
1633
+ className: 'dsa-popover dsa-review-panel', id: 'dsa-review-panel-' + sessionId, role: 'region', 'aria-label': t('page.listAria'),
1634
+ }, draftRow, annotations.map((ann, index) => h('div', { className: 'dsa-item', key: ann.id },
1635
+ h('button', { className: 'dsa-note-open', type: 'button', title: t('page.view'), onClick: () => openComment(ann) },
1636
+ h('span', { className: 'dsa-idx', 'aria-hidden': true }, String(index + 1)), h('span', { className: 'dsa-body' },
1637
+ h('span', { className: 'dsa-comment' }, ann.comment), h('span', { className: 'dsa-note-target' }, annotationLabel(ann)))),
1638
+ iconButton(t('page.delete'), 'trash', () => { notify('remove', { id: ann.id }); flash(panel, t('notice.deleted'), { undo: true }) }, { className: 'dsa-mini', 'data-danger': 'true' })))) : null,
1639
+ state.sendMenuOpen ? h('div', { className: 'dsa-popover dsa-menu dsa-submit-menu', id: 'dsa-submit-menu-' + sessionId, role: 'region', 'aria-label': t('page.sendOptions') },
1640
+ h('button', { className: 'dsa-secondary', type: 'button', disabled: !annotations.length || state.sending, onClick: () => { closeMenus(); sendAll(panel, inputActions?.setDraft, { submit: false }) } }, h(Icon, { name: 'attach' }), t('page.attach'))) : null,
1641
+ notice))
1642
+ }
1643
+
1644
+ // ------------------------------------------------------- smaller entries
1645
+
1646
+ const Dock = (props) => {
1647
+ const panel = getPanel(props.sessionId)
1648
+ useSub(panel.model)
1649
+ const draft = props.useInput((s) => s.draft)
1650
+ const pending = panel.model.get().pending.filter((item) => String(draft || '').includes(item.payload))
1651
+ if (!pending.length) return null
1652
+ return React.createElement(
1653
+ 'div',
1654
+ { className: 'dsa-dock' },
1655
+ pending.map((item) =>
1656
+ React.createElement(
1657
+ 'span',
1658
+ { className: 'dsa-chip', key: item.id },
1659
+ React.createElement('span', { className: 'dot' }),
1660
+ t('payload.attached', { count: item.count }),
1661
+ React.createElement(
1662
+ 'button',
1663
+ {
1664
+ type: 'button',
1665
+ title: t('payload.removeOne'),
1666
+ onClick: () => {
1667
+ const next = String(draft || '').replace(item.payload, '').replace(/\n{3,}/g, '\n\n').trim()
1668
+ props.inputActions.setDraft(next)
1669
+ panel.model.set({ pending: pending.filter((p) => p.id !== item.id) })
1670
+ },
1671
+ },
1672
+ '✕'
1673
+ )
1674
+ )
1675
+ ),
1676
+ React.createElement(
1677
+ 'button',
1678
+ {
1679
+ className: 'dsa-chip-clear',
1680
+ type: 'button',
1681
+ onClick: () => {
1682
+ let next = String(draft || '')
1683
+ pending.forEach((item) => {
1684
+ next = next.replace(item.payload, '')
1685
+ })
1686
+ props.inputActions.setDraft(next.replace(/\n{3,}/g, '\n\n').trim())
1687
+ panel.model.set({ pending: [] })
1688
+ },
1689
+ },
1690
+ t('payload.removeAll')
1691
+ )
1692
+ )
1693
+ }
1694
+
1695
+ // ------------------------------------------------------------ registration
1696
+
1697
+ if (sidebarRightTabs && typeof sidebarRightTabs.register === 'function') {
1698
+ ctx.effect(() =>
1699
+ sidebarRightTabs.register({
1700
+ id: TAB_ID,
1701
+ kind: KIND,
1702
+ priority: 'extension',
1703
+ title: () => t('panel.tabTitle'),
1704
+ guide: [
1705
+ {
1706
+ order: 40,
1707
+ title: () => t('panel.tabTitle'),
1708
+ description: () => t('panel.tabDescription'),
1709
+ icon: (iconProps) => React.createElement(Icon, Object.assign({ name: 'annotation' }, iconProps)),
1710
+ },
1711
+ ],
1712
+ })
1713
+ )
1714
+ } else {
1715
+ console.warn('dsh-annotate: sidebarRightTabs is unavailable; the tab cannot register')
1716
+ }
1717
+
1718
+ const contribute = (key, id, component, label, extra) => {
1719
+ try {
1720
+ slots.inject(key, () => slots.register(Object.assign({ name: key, id: id, label: label, order: 12 }, extra), component))
1721
+ } catch (error) {
1722
+ console.warn('dsh-annotate: slot ' + key + ' unavailable', error)
1723
+ }
1724
+ }
1725
+ contribute('sidebar.right.pane.tab', TAB_ID, AnnotateTab, undefined, { key: TAB_ID })
1726
+ contribute('conversation.input.dock', 'annotate-dock', Dock)
1727
+
1728
+ // ⌘⇧B mirrors Codex's in-app browser; ⌘⇧A stays as an alias.
1729
+ const onKeyDown = (event) => {
1730
+ if (event.key === 'Escape' && activePanel) {
1731
+ const state = activePanel.model.get()
1732
+ if (state.menuOpen || state.listOpen || state.sendMenuOpen) {
1733
+ const surface = event.target.closest?.('.dsa-popover')
1734
+ if (surface?.id) document.querySelector('[aria-controls=' + JSON.stringify(surface.id) + ']')?.focus()
1735
+ event.preventDefault()
1736
+ activePanel.model.set({ menuOpen: false, helpOpen: false, listOpen: false, sendMenuOpen: false })
1737
+ return
1738
+ }
1739
+ activePanel.model.set({ mode: 'idle' })
1740
+ notify('set-mode', { mode: 'idle' })
1741
+ return
1742
+ }
1743
+ if (!(event.metaKey || event.ctrlKey) || !event.shiftKey) return
1744
+ const key = String(event.key).toLowerCase()
1745
+ if (key !== 'b' && key !== 'a') return
1746
+ event.preventDefault()
1747
+ openAnnotate()
1748
+ }
1749
+ window.addEventListener('keydown', onKeyDown)
1750
+ ctx.effect(() => () => window.removeEventListener('keydown', onKeyDown))
1751
+ }
1752
+
1753
+ exports.apply = apply;
1754
+ if (typeof inject !== "undefined") exports.inject = inject;
1755
+ return module.exports;
1756
+ },
1757
+ });