dsh-duet 0.1.2 → 0.1.4

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.
@@ -1,34 +1,57 @@
1
1
  /** A brief, non-modal invitation after the microphone is actually ready. */
2
- export function mountConnectionHint(controls, { duration = 8000 } = {}) {
2
+ import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.4'
3
+ export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{} } = {}) {
3
4
  const hint = document.createElement('div')
4
5
  hint.dataset.duetConnectionHint = ''
5
6
  hint.setAttribute('role', 'status')
6
7
  hint.setAttribute('aria-live', 'polite')
7
8
  hint.hidden = true
8
- hint.style.cssText = 'position:absolute;bottom:calc(100% + 10px);left:0;z-index:9998;box-sizing:border-box;width:268px;max-width:calc(100vw - 32px);padding:12px 15px;border:1px solid #a5d8f4;border-radius:12px;background:#eff9ff;color:#163c56;font:13px/1.65 system-ui,sans-serif;box-shadow:0 8px 28px #153e6524;pointer-events:none'
9
- hint.textContent = '连接成功,可以试试对我说“你好”。'
9
+ hint.style.cssText = 'position:fixed;z-index:100020;box-sizing:border-box;width:268px;max-width:calc(100vw - 32px);padding:12px 15px;border:1px solid #a5d8f4;border-radius:12px;background:#eff9ff;color:#163c56;font:13px/1.65 system-ui,sans-serif;box-shadow:0 8px 28px #153e6524;pointer-events:none'
10
+ const text=document.createTextNode(normalizeGuidance(null).text)
11
+ hint.append(text)
10
12
  const arrow = document.createElement('span')
11
13
  arrow.setAttribute('aria-hidden', 'true')
12
14
  arrow.style.cssText = 'position:absolute;bottom:-6px;width:10px;height:10px;transform:rotate(45deg);background:#eff9ff;border-right:1px solid #a5d8f4;border-bottom:1px solid #a5d8f4'
13
15
  hint.append(arrow)
14
- controls.append(hint)
16
+ // A body-level overlay escapes the sidebar's overflow and stacking context.
17
+ document.body.append(hint)
15
18
  let wasReady = false, timer, disposed = false
19
+ const position = () => {
20
+ if (hint.hidden || disposed) return
21
+ if (!controls.isConnected) { hide(); return }
22
+ const button = controls.querySelector('[data-voice=mic]') || controls
23
+ const rect = button.getBoundingClientRect(), width = hint.offsetWidth, height = hint.offsetHeight
24
+ const left = Math.max(16, Math.min(rect.left, innerWidth - width - 16))
25
+ const above = rect.top >= height + 26
26
+ hint.style.left = `${left}px`
27
+ hint.style.top = `${Math.max(16, Math.min(above ? rect.top - height - 10 : rect.bottom + 10, innerHeight - height - 16))}px`
28
+ arrow.style.left = `${Math.max(16, Math.min(width - 26, rect.left + rect.width / 2 - left - 5))}px`
29
+ arrow.style.bottom = above ? '-6px' : 'auto'
30
+ arrow.style.top = above ? 'auto' : '-6px'
31
+ arrow.style.transform = above ? 'rotate(45deg)' : 'rotate(225deg)'
32
+ }
16
33
  const hide = () => { hint.hidden = true; clearTimeout(timer) }
17
34
  const dismiss = event => { if (event.type !== 'keydown' || event.key === 'Escape') hide() }
18
35
  controls.addEventListener('pointerdown', dismiss)
19
36
  document.addEventListener('keydown', dismiss)
37
+ window.addEventListener('resize', position)
38
+ window.addEventListener('scroll', position, true)
39
+ const observer = new ResizeObserver(position)
40
+ observer.observe(controls)
20
41
  return {
21
42
  dismiss: hide,
22
- update({ mode, ready, teaching = false }) {
43
+ update({ mode, ready, teaching = false, guidance }) {
23
44
  if (disposed) return
24
45
  const active = mode === 'online' && ready
25
46
  if (!active || teaching) hide()
26
47
  if (active && !wasReady && !teaching) {
27
- const button = controls.querySelector('[data-voice=mic]')
28
- arrow.style.left = `${Math.max(16, Math.min(244, (button?.offsetLeft || 32) + (button?.offsetWidth || 30) / 2 - 5))}px`
48
+ const actual=normalizeGuidance(guidance)
49
+ text.textContent=actual.text
29
50
  hint.hidden = false
51
+ position()
30
52
  clearTimeout(timer)
31
53
  timer = setTimeout(hide, duration)
54
+ try{onShown(actual)}catch{ /* Diagnostics must never break the tooltip. */ }
32
55
  }
33
56
  wasReady = active
34
57
  },
@@ -37,6 +60,9 @@ export function mountConnectionHint(controls, { duration = 8000 } = {}) {
37
60
  hide()
38
61
  controls.removeEventListener('pointerdown', dismiss)
39
62
  document.removeEventListener('keydown', dismiss)
63
+ window.removeEventListener('resize', position)
64
+ window.removeEventListener('scroll', position, true)
65
+ observer.disconnect()
40
66
  hint.remove()
41
67
  },
42
68
  }
@@ -0,0 +1,18 @@
1
+ /** Follow the host's available sidebar width, without depending on DSH classes. */
2
+ export function mountControlsLayout(controls) {
3
+ const parent = controls.parentElement
4
+ const update = () => {
5
+ const compact = parent.getBoundingClientRect().width < 160
6
+ if (controls.dataset.compact === String(compact)) return
7
+ controls.dataset.compact = String(compact)
8
+ controls.style.flexDirection = compact ? 'column' : 'row'
9
+ controls.style.margin = compact ? '4px 0' : '4px 8px'
10
+ controls.style.padding = compact ? '6px 0' : '6px 8px'
11
+ const entry = controls.querySelector('#dsh-duet-entry')
12
+ if (entry) entry.style.display = compact ? 'none' : ''
13
+ }
14
+ const observer = new ResizeObserver(update)
15
+ observer.observe(parent)
16
+ update()
17
+ return () => observer.disconnect()
18
+ }
@@ -8,30 +8,10 @@ window.__ModuleLoader__.load({
8
8
  const inject = ["sessions", "conversation", "uiSession", "workspaces"]
9
9
 
10
10
  function apply(ctx) {
11
- const focusedSession = () => {
12
- const snapshot = ctx.sessions.list.getSnapshot()
13
- if ('current' in snapshot) return snapshot.current || null
14
- const selected = Object.entries(snapshot.byId || {}).filter(([, row]) => row.retainedBy?.mainView > 0)
15
- return selected.length === 1 ? selected[0][0] : null
16
- }
17
- const browserClientId = crypto.randomUUID()
18
- // A hung fetch must not permanently hold heartbeatRunning/pollRunning.
19
- const bridgeFetch = async (url, options = {}, timeoutMs = 8000) => {
20
- const request = new AbortController()
21
- const abort = () => request.abort()
22
- options.signal?.addEventListener('abort', abort, { once: true })
23
- if (options.signal?.aborted) abort()
24
- const timer = setTimeout(abort, timeoutMs)
25
- try { return await fetch(url, { ...options, signal: request.signal }) }
26
- finally {
27
- clearTimeout(timer)
28
- options.signal?.removeEventListener('abort', abort)
29
- }
30
- }
31
11
  ctx.effect(() => {
32
12
  let active = true
33
13
  let dispose
34
- import('/duet/assets/client/browser.mjs?v=0.1.2').then(module => {
14
+ import('/duet/assets/client/browser.mjs?v=0.1.4').then(module => {
35
15
  if (active) dispose = module.mountDuet(ctx)
36
16
  }).catch(error => console.warn('duet controls could not load:', error))
37
17
  return () => { active = false; dispose?.() }
@@ -70,393 +50,6 @@ window.__ModuleLoader__.load({
70
50
  }
71
51
  }, "duet-client: mount main page entry")
72
52
 
73
- ctx.effect(() => {
74
- if (typeof BroadcastChannel === "undefined") return () => {}
75
- const channel = new BroadcastChannel("dsh-duplex-control-v1")
76
-
77
- const currentComposer = () => {
78
- const sessionId = focusedSession()
79
- if (typeof sessionId !== "string") throw new Error("Harness currently has no selected session")
80
- const sessionContext = ctx.sessions.scope(sessionId)
81
- if (sessionContext === undefined) throw new Error(`Harness session ${sessionId} is not ready`)
82
- return {
83
- sessionId,
84
- input: ctx.conversation.input.for(sessionContext),
85
- }
86
- }
87
-
88
- const composerState = (sessionId, input) => {
89
- const state = input.state.getSnapshot()
90
- return {
91
- session_id: sessionId,
92
- draft: state.draft,
93
- phase: state.phase,
94
- draft_revision: state.draftRev,
95
- }
96
- }
97
-
98
- channel.onmessage = (event) => {
99
- const message = event.data
100
- if (
101
- message === null
102
- || typeof message !== "object"
103
- || message.source !== "duplex-control-page"
104
- || typeof message.request_id !== "string"
105
- ) return
106
- if (!["composer/get", "composer/set", "composer/clear"].includes(message.type)) return
107
-
108
- const respond = (payload) => channel.postMessage({
109
- source: "harness-main-page",
110
- type: "composer/result",
111
- request_id: message.request_id,
112
- ...payload,
113
- })
114
-
115
- try {
116
- const { sessionId, input } = currentComposer()
117
- if (message.type === "composer/set") {
118
- const text = String(message.text ?? "")
119
- if (text.length > 100_000) throw new Error("Draft is too large")
120
- const before = input.state.getSnapshot()
121
- if (before.phase !== "plain") {
122
- throw new Error(`Harness input is busy (${before.phase})`)
123
- }
124
- input.setDraft(message.mode === "append" ? `${before.draft}${text}` : text)
125
- } else if (message.type === "composer/clear") {
126
- const before = input.state.getSnapshot()
127
- if (before.phase !== "plain") {
128
- throw new Error(`Harness input is busy (${before.phase})`)
129
- }
130
- input.setDraft("")
131
- }
132
- respond({ ok: true, composer: composerState(sessionId, input) })
133
- } catch (error) {
134
- respond({ ok: false, error: error instanceof Error ? error.message : String(error) })
135
- }
136
- }
137
-
138
- return () => channel.close()
139
- }, "duet-client: bridge current composer")
140
-
141
- ctx.effect(() => {
142
- const controller = new AbortController()
143
- const clientId = browserClientId
144
- let pollRunning = false
145
- let retryTimer
146
-
147
- const digest = async (text) => {
148
- const bytes = new TextEncoder().encode(text)
149
- const hash = await crypto.subtle.digest("SHA-256", bytes)
150
- return [...new Uint8Array(hash)].map(value => value.toString(16).padStart(2, "0")).join("")
151
- }
152
-
153
- const composerForSession = async (sessionId) => {
154
- await ctx.sessions.refresh()
155
- const sessionContext = ctx.sessions.scope(sessionId)
156
- if (sessionContext === undefined) {
157
- const error = new Error(`Harness session ${sessionId} is not ready`)
158
- error.code = "session_not_ready"
159
- throw error
160
- }
161
- return ctx.conversation.input.for(sessionContext)
162
- }
163
-
164
- const composerState = async (sessionId, input) => {
165
- const state = input.state.getSnapshot()
166
- return {
167
- session_id: sessionId,
168
- text: state.draft,
169
- phase: state.phase,
170
- revision: state.draftRev,
171
- hash: await digest(state.draft),
172
- }
173
- }
174
-
175
- const execute = async (request) => {
176
- const input = await composerForSession(request.session_id)
177
- const before = await composerState(request.session_id, input)
178
- const checkFocus = () => {
179
- if (request.require_focus && focusedSession() !== request.session_id) {
180
- const error = new Error("Focused session changed; read input_status again")
181
- error.code = "focus_conflict"
182
- throw error
183
- }
184
- }
185
- checkFocus()
186
- if (["set", "clear", "consume"].includes(request.type)) {
187
- const overwrite = request.type === "set" && request.overwrite === true
188
- if (before.phase !== "plain") {
189
- const error = new Error(`Harness input is busy (${before.phase})`)
190
- error.code = "composer_busy"
191
- throw error
192
- }
193
- if (!overwrite && (
194
- before.revision !== request.expected_revision
195
- || before.hash !== request.expected_hash
196
- )) {
197
- const error = new Error("Harness input changed before the requested edit")
198
- error.code = "draft_conflict"
199
- throw error
200
- }
201
- // Hashing yields to the browser. Recheck the live draft immediately before
202
- // the synchronous write so a keystroke during hashing cannot be overwritten.
203
- const live = input.state.getSnapshot()
204
- if (!overwrite && (live.draftRev !== before.revision || live.draft !== before.text || live.phase !== before.phase)) {
205
- const error = new Error("Harness input changed during snapshot")
206
- error.code = "draft_conflict"
207
- throw error
208
- }
209
- if (live.phase !== "plain") {
210
- const error = new Error("Harness input is busy")
211
- error.code = "composer_busy"
212
- throw error
213
- }
214
- checkFocus()
215
- // DSH 0.1.5 adds generic attachments. The host submit RPC below is
216
- // text-only: do not clear/send just the text and silently omit files.
217
- // Older DSH exposes the same browser-owned items as imageIds.
218
- if (request.type === "consume" && (live.attachmentIds ?? live.imageIds ?? []).length > 0) {
219
- const error = new Error("输入框含有附件,请在 Harness 页面发送;语音发送目前只支持纯文本")
220
- error.code = "composer_attachments_unsupported"
221
- throw error
222
- }
223
- const consumed = request.type === "consume" ? before : null
224
- input.setDraft(["clear", "consume"].includes(request.type) ? "" : String(request.text ?? ""))
225
- await new Promise(resolve => setTimeout(resolve, 0))
226
- const after = await composerState(request.session_id, input)
227
- if (consumed !== null) {
228
- return {
229
- ...after,
230
- consumed_text: consumed.text,
231
- consumed_revision: consumed.revision,
232
- consumed_hash: consumed.hash,
233
- }
234
- }
235
- return after
236
- } else if (request.type !== "get") {
237
- const error = new Error(`Unsupported composer request: ${request.type}`)
238
- error.code = "unsupported_composer_operation"
239
- throw error
240
- }
241
- return before
242
- }
243
-
244
- const complete = async (requestId, payload) => {
245
- await bridgeFetch(`/duplex-control/api/composer/requests/${encodeURIComponent(requestId)}/complete`, {
246
- method: "POST",
247
- headers: { "Content-Type": "application/json" },
248
- body: JSON.stringify({ client_id: clientId, ...payload }),
249
- cache: "no-store",
250
- signal: controller.signal,
251
- })
252
- }
253
-
254
- const processRequest = async (candidate) => {
255
- const claimResponse = await bridgeFetch(
256
- `/duplex-control/api/composer/requests/${encodeURIComponent(candidate.id)}/claim`,
257
- {
258
- method: "POST",
259
- headers: { "Content-Type": "application/json" },
260
- body: JSON.stringify({ client_id: clientId }),
261
- cache: "no-store",
262
- signal: controller.signal,
263
- },
264
- )
265
- if (claimResponse.status === 404 || claimResponse.status === 409) return
266
- if (!claimResponse.ok) throw new Error(`Composer claim failed: HTTP ${claimResponse.status}`)
267
- const request = (await claimResponse.json()).request
268
- try {
269
- const composer = await execute(request)
270
- await complete(request.id, { ok: true, composer })
271
- } catch (error) {
272
- await complete(request.id, {
273
- ok: false,
274
- error_code: error?.code || "composer_operation_failed",
275
- error: error instanceof Error ? error.message : String(error),
276
- status: error?.code === "session_not_ready" ? 503 : 409,
277
- })
278
- }
279
- }
280
-
281
- const poll = async () => {
282
- if (pollRunning || controller.signal.aborted) return
283
- clearTimeout(retryTimer)
284
- pollRunning = true
285
- let succeeded = false
286
- try {
287
- const sessionId = focusedSession() || ''
288
- const visibility = typeof document === 'undefined' ? 'unknown' : document.visibilityState
289
- const query = `wait=1&client_id=${encodeURIComponent(clientId)}&session_id=${encodeURIComponent(sessionId)}&visibility=${encodeURIComponent(visibility)}`
290
- const response = await bridgeFetch(`/duplex-control/api/composer/requests?${query}`, {
291
- cache: "no-store",
292
- signal: controller.signal,
293
- }, 30_000)
294
- if (!response.ok) return
295
- const payload = await response.json()
296
- await Promise.all((payload.requests || []).map(processRequest))
297
- // Old hosts return an immediate empty list: retain a retry delay
298
- // rather than spinning if a browser/host upgrade is staggered.
299
- succeeded = payload.long_poll_supported === true
300
- } catch (error) {
301
- if (!controller.signal.aborted) console.warn("duet composer RPC failed:", error)
302
- } finally {
303
- pollRunning = false
304
- if (!controller.signal.aborted) {
305
- // Successful long polls re-arm without a background-tab timer.
306
- if (succeeded) void poll()
307
- else retryTimer = setTimeout(() => { void poll() }, 1000)
308
- }
309
- }
310
- }
311
-
312
- void poll()
313
- const resume = () => { void poll() }
314
- window.addEventListener?.('online', resume)
315
- window.addEventListener?.('pageshow', resume)
316
- if (typeof document !== 'undefined') document.addEventListener('visibilitychange', resume)
317
- return () => {
318
- controller.abort()
319
- clearTimeout(retryTimer)
320
- window.removeEventListener?.('online', resume)
321
- window.removeEventListener?.('pageshow', resume)
322
- if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', resume)
323
- }
324
- }, "duet-client: bridge server composer RPC")
325
-
326
- ctx.effect(() => {
327
- const controller = new AbortController()
328
- const focusClientId = browserClientId
329
- let lastEpoch
330
- let lastRevision = -1
331
- let lastPublishedSession
332
- let pollRunning = false
333
- let heartbeatRunning = false
334
- let publishRunning = false
335
- let publishPending = false
336
- let publishReady = false
337
-
338
- const selectedSession = focusedSession
339
-
340
- const observeEpoch = (epoch) => {
341
- if (typeof epoch !== "string" || epoch === lastEpoch) return
342
- lastEpoch = epoch
343
- lastRevision = -1
344
- lastPublishedSession = undefined
345
- }
346
-
347
- const heartbeat = async () => {
348
- if (heartbeatRunning) return
349
- heartbeatRunning = true
350
- try {
351
- const response = await bridgeFetch("/duplex-control/api/browser-clients/heartbeat", {
352
- method: "POST",
353
- headers: { "Content-Type": "application/json" },
354
- body: JSON.stringify({
355
- client_id: focusClientId,
356
- session_id: selectedSession(),
357
- visibility: document.visibilityState,
358
- }),
359
- cache: "no-store",
360
- signal: controller.signal,
361
- })
362
- if (response.ok) observeEpoch((await response.json()).focus_epoch)
363
- } catch (error) {
364
- if (!controller.signal.aborted) console.warn("duet heartbeat failed:", error)
365
- } finally {
366
- heartbeatRunning = false
367
- }
368
- }
369
-
370
- const publishSelection = async () => {
371
- if (!publishReady) return
372
- if (publishRunning) {
373
- publishPending = true
374
- return
375
- }
376
- publishRunning = true
377
- try {
378
- do {
379
- publishPending = false
380
- const sessionId = selectedSession()
381
- if (sessionId === lastPublishedSession) continue
382
- const response = await bridgeFetch("/duplex-control/api/focus", {
383
- method: "POST",
384
- headers: { "Content-Type": "application/json" },
385
- body: JSON.stringify({ session_id: sessionId }),
386
- cache: "no-store",
387
- signal: controller.signal,
388
- })
389
- if (!response.ok) {
390
- const payload = await response.json().catch(() => ({}))
391
- throw new Error(payload.detail || `HTTP ${response.status}`)
392
- }
393
- lastPublishedSession = sessionId
394
- } while (publishPending)
395
- } catch (error) {
396
- if (!controller.signal.aborted) console.warn("duet selection publish failed:", error)
397
- } finally {
398
- publishRunning = false
399
- }
400
- }
401
-
402
- const poll = async () => {
403
- if (pollRunning) return
404
- pollRunning = true
405
- try {
406
- const response = await bridgeFetch("/duplex-control/api/focus", {
407
- cache: "no-store",
408
- signal: controller.signal,
409
- })
410
- if (!response.ok) return
411
- const focus = await response.json()
412
- observeEpoch(focus.focus_epoch)
413
- if (!Number.isInteger(focus.revision) || focus.revision <= lastRevision) return
414
- if (focus.revision === 0 || typeof focus.session_id !== "string") {
415
- lastRevision = focus.revision
416
- return
417
- }
418
- await ctx.sessions.refresh()
419
- if (ctx.sessions.list.getSnapshot().byId[focus.session_id] === undefined) return
420
- lastPublishedSession = focus.session_id
421
- // New DSH separates controller selection from the visible panel.
422
- // Use the UI navigation API so a selected session is not hidden
423
- // behind the empty-workspace/settings panel while RPC edits it.
424
- const navigation = typeof ctx.get === "function" ? ctx.get("uiWorkspace") : ctx.uiWorkspace
425
- if (navigation?.openSession) navigation.openSession(focus.session_id)
426
- else ctx.sessions.open(focus.session_id)
427
- lastRevision = focus.revision
428
- } catch (error) {
429
- if (!controller.signal.aborted) console.warn("duet focus sync failed:", error)
430
- } finally {
431
- pollRunning = false
432
- }
433
- }
434
-
435
- const unsubscribe = ctx.sessions.list.subscribe(() => { void publishSelection() })
436
- void poll().finally(() => {
437
- publishReady = true
438
- void publishSelection()
439
- })
440
- void heartbeat()
441
- const timer = setInterval(() => {
442
- void poll()
443
- void publishSelection()
444
- }, 500)
445
- const heartbeatTimer = setInterval(() => { void heartbeat() }, 1000)
446
- const onVisibilityChange = () => { void heartbeat(); void poll(); void publishSelection() }
447
- document.addEventListener("visibilitychange", onVisibilityChange)
448
- window.addEventListener?.('online', onVisibilityChange)
449
- window.addEventListener?.('pageshow', onVisibilityChange)
450
- return () => {
451
- controller.abort()
452
- clearInterval(timer)
453
- clearInterval(heartbeatTimer)
454
- document.removeEventListener("visibilitychange", onVisibilityChange)
455
- window.removeEventListener?.('online', onVisibilityChange)
456
- window.removeEventListener?.('pageshow', onVisibilityChange)
457
- unsubscribe()
458
- }
459
- }, "duet-client: synchronize host and browser focus")
460
53
  }
461
54
 
462
55
  exports.apply = apply
@@ -6,7 +6,7 @@ export function mountRating(anchor, sessionTicket) {
6
6
  panel.style.cssText='position:fixed;z-index:100020;width:min(300px,calc(100vw - 24px));box-sizing:border-box;background:#17212f;color:#edf3ff;border:1px solid #52647d;border-radius:16px;padding:16px;box-shadow:0 12px 40px #0006;font:14px/1.6 system-ui'
7
7
  const title=document.createElement('h3');title.textContent='这次语音体验怎么样?';title.style.margin='0 0 10px';panel.append(title)
8
8
  const stars=document.createElement('div');stars.setAttribute('role','group');stars.setAttribute('aria-label','1 到 5 星');panel.append(stars)
9
- let rating=0,busy=false,requestId=crypto.randomUUID()
9
+ let rating=0,busy=false,disposed=false,requestId=crypto.randomUUID(),requestController,requestTimeout
10
10
  const buttons=[]
11
11
  for(let value=1;value<=5;value++){
12
12
  const b=document.createElement('button');b.type='button';b.textContent='☆';b.setAttribute('aria-label',`${value} 星`);b.setAttribute('aria-pressed','false')
@@ -23,21 +23,26 @@ export function mountRating(anchor, sessionTicket) {
23
23
  panel.style.top=(rect.top>=box.height+20?rect.top-box.height-12:rect.bottom+12)+'px'
24
24
  }
25
25
  let countdown,timeout
26
- const dispose=()=>{clearInterval(countdown);clearTimeout(timeout);panel.remove();document.removeEventListener('keydown',onKey);window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true)}
26
+ const dispose=()=>{disposed=true;clearInterval(countdown);clearTimeout(timeout);clearTimeout(requestTimeout);requestController?.abort();panel.remove();document.removeEventListener('keydown',onKey);window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true)}
27
27
  const onKey=e=>{if(e.key==='Escape')dispose()}
28
28
  skip.onclick=dispose
29
29
  submit.onclick=async()=>{
30
- if(busy||!rating)return
30
+ if(disposed||busy||!rating)return
31
31
  busy=true;submit.disabled=true;buttons.forEach(b=>b.disabled=true)
32
+ clearInterval(countdown);clearTimeout(timeout)
33
+ submit.textContent='正在提交…';skip.textContent='关闭'
34
+ requestController=new AbortController()
35
+ requestTimeout=setTimeout(()=>requestController.abort(),15000)
32
36
  try {
33
37
  const r=await fetch('/duplex-control/api/feedback',{method:'POST',credentials:'same-origin',
34
- headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'},signal:AbortSignal.timeout(15000),
38
+ headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'},signal:requestController.signal,
35
39
  body:JSON.stringify({kind:'rating',request_id:requestId,session_ticket:sessionTicket,rating})})
36
40
  const result=await r.json()
41
+ if(disposed)return
37
42
  if(!r.ok||result.persisted!==true)throw Error('not_saved')
38
43
  dispose()
39
- }catch{title.textContent='提交失败,请重试';submit.disabled=false;buttons.forEach(b=>b.disabled=false)}
40
- finally{busy=false}
44
+ }catch{if(!disposed){title.textContent='提交失败,请重试';submit.disabled=false;buttons.forEach(b=>b.disabled=false)}}
45
+ finally{clearTimeout(requestTimeout);busy=false;if(!disposed)submit.textContent='提交评分'}
41
46
  }
42
47
  panel.append(submit,skip);document.body.append(panel);document.addEventListener('keydown',onKey)
43
48
  position();window.addEventListener('resize',position);window.addEventListener('scroll',position,true)
@@ -0,0 +1,47 @@
1
+ /** Page-level notices must not inherit a sidebar's clipping or stacking context. */
2
+ export function mountNotice(anchor) {
3
+ const panel = document.createElement('div')
4
+ panel.dataset.duetNotice = ''
5
+ panel.setAttribute('role', 'status')
6
+ panel.setAttribute('aria-live', 'polite')
7
+ panel.hidden = true
8
+ panel.style.cssText = 'position:fixed;z-index:100021;box-sizing:border-box;width:280px;max-width:calc(100vw - 24px);max-height:calc(100vh - 24px);overflow:auto;background:#252c38;color:white;padding:14px;border:1px solid #52647d;border-radius:12px;font:13px/1.6 system-ui;box-shadow:0 8px 28px #0005;overflow-wrap:anywhere'
9
+ document.body.append(panel)
10
+ let timer, disposed = false
11
+ const hide = () => { panel.hidden = true; clearTimeout(timer) }
12
+ const position = () => {
13
+ if (panel.hidden || disposed) return
14
+ const control = anchor()
15
+ if (!control?.isConnected) { hide(); return }
16
+ const rect = control.getBoundingClientRect(), box = panel.getBoundingClientRect()
17
+ panel.style.left = Math.max(12, Math.min(rect.left, innerWidth - box.width - 12)) + 'px'
18
+ const top = rect.top >= box.height + 24 ? rect.top - box.height - 12 : rect.bottom + 12
19
+ panel.style.top = Math.max(12, Math.min(top, innerHeight - box.height - 12)) + 'px'
20
+ }
21
+ const key = event => { if (event.key === 'Escape') hide() }
22
+ window.addEventListener('resize', position)
23
+ window.addEventListener('scroll', position, true)
24
+ document.addEventListener('keydown', key)
25
+ const observer = new ResizeObserver(position)
26
+ observer.observe(panel)
27
+ return {
28
+ show(text, {upgrade = false} = {}) {
29
+ if (disposed) return
30
+ clearTimeout(timer); panel.textContent = text; panel.hidden = false
31
+ if (upgrade) {
32
+ const help = document.createElement('details'), title = document.createElement('summary')
33
+ title.textContent = '如何升级'; help.append(title)
34
+ const before = document.createElement('p'), command = document.createElement('code'), after = document.createElement('p')
35
+ before.textContent = '通过 npm 安装的用户,可在终端运行:'
36
+ command.textContent = 'dsh plugin --profile web add dsh-duet@latest'
37
+ command.style.cssText = 'display:block;white-space:normal;margin:8px 0'
38
+ after.textContent = '其他安装方式请从原来源更新。完成后重启 DSH 并刷新页面,再手动开启语音。'
39
+ help.append(before, command, after); panel.append(help)
40
+ help.addEventListener('toggle', position)
41
+ const close = document.createElement('button'); close.type = 'button'; close.textContent = '知道了'; close.onclick = hide; panel.append(close)
42
+ } else timer = setTimeout(hide, 8000)
43
+ position()
44
+ },
45
+ dispose() { disposed = true; hide(); observer.disconnect(); panel.remove(); window.removeEventListener('resize', position); window.removeEventListener('scroll', position, true); document.removeEventListener('keydown', key) },
46
+ }
47
+ }
@@ -20,13 +20,14 @@ export function validateRPC(request) {
20
20
  }
21
21
 
22
22
  export class HarnessRPCExecutor {
23
- constructor(send, fetchImpl = fetch, diagnostic = () => {}, localComposer = null, catalogOrder = rows => orderSessionCatalog(rows, readWorkspaceView())) {
23
+ constructor(send, fetchImpl = fetch, diagnostic = () => {}, localComposer = null, catalogOrder = rows => orderSessionCatalog(rows, readWorkspaceView()), binding = {}) {
24
24
  // Native Window.fetch rejects an RPCExecutor receiver (Illegal invocation).
25
25
  // Call the captured function plainly, not as an instance method.
26
26
  this.send = send; this.fetch = (...args) => fetchImpl(...args); this.closed = false
27
27
  this.diagnostic = diagnostic
28
28
  this.localComposer = localComposer
29
29
  this.catalogOrder = catalogOrder
30
+ this.binding = binding
30
31
  this.connectionId = null; this.seen = new Map(); this.retired = new Set(); this.controllers = new Set()
31
32
  }
32
33
 
@@ -75,13 +76,16 @@ export class HarnessRPCExecutor {
75
76
  method: request.method, credentials: 'same-origin', redirect: 'error',
76
77
  cache: 'no-store', signal: controller.signal,
77
78
  headers: { 'Content-Type': 'application/json', 'X-Duplex-Control-Client': 'realtime-client-rpc-v1',
78
- 'X-Duet-Native-Interactions': '1' },
79
+ 'X-Duet-Native-Interactions': '1',
80
+ ...(this.binding.id ? { 'X-Duet-Browser-Client': this.binding.id } : {}) },
79
81
  ...(request.method !== 'GET' ? { body: JSON.stringify(request.payload ?? {}) } : {}),
80
82
  })
81
83
  const text = await response.text()
82
84
  if (new TextEncoder().encode(text).length > MAX_BYTES - 512) throw new Error('harness_rpc_response_too_large')
83
85
  const body = JSON.parse(text)
84
86
  if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('invalid_harness_rpc_body')
87
+ controller.signal.throwIfAborted()
88
+ if (response.ok && this.binding.completed) await this.binding.completed(request, body, controller.signal)
85
89
  if (response.status === 200 && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
86
90
  // Both startup prompt and nth_N resolution read this same browser-local
87
91
  // order, including manual drag order; archived rows cannot consume ranks.