dsh-watch-together 0.1.1 → 0.2.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +1221 -1090
  2. package/LICENSE +201 -201
  3. package/README.md +10 -2
  4. package/bin/lines.mjs +202 -202
  5. package/bin/tts.mjs +232 -232
  6. package/bin/watch.mjs +31 -3
  7. package/docs/INTERFACES.zh.md +73 -0
  8. package/dsh.plugin.json +12 -12
  9. package/examples/floating-chat/glass_window.py +7 -0
  10. package/examples/floating-chat/glass_window_gpu.py +502 -0
  11. package/examples/floating-chat/launch.cmd +5 -5
  12. package/examples/floating-chat/mic-dsh.png +0 -0
  13. package/examples/floating-chat/requirements-glass.txt +16 -0
  14. package/examples/floating-chat/run-glass-60fps.cmd +7 -0
  15. package/examples/floating-chat/run-glass-acrylic.cmd +8 -0
  16. package/examples/floating-chat/run-glass-nochroma.cmd +7 -0
  17. package/examples/floating-chat/run-glass.cmd +12 -0
  18. package/examples/floating-chat/window.py +1245 -2286
  19. package/examples/floating-chat/window_protocol.py +167 -0
  20. package/lib/client.js +306 -0
  21. package/package.json +13 -2
  22. package/scripts/start-edge-debug.cmd +41 -41
  23. package/src/chat-server.js +13 -10
  24. package/src/chat-store.js +10 -0
  25. package/src/floating-window.js +198 -198
  26. package/src/handler.js +12 -7
  27. package/src/index.js +26 -0
  28. package/src/input-surface.js +8 -6
  29. package/src/interfaces.js +43 -0
  30. package/src/latency.js +76 -76
  31. package/src/lines-util.js +458 -379
  32. package/src/position.js +160 -160
  33. package/src/public-api.js +24 -0
  34. package/src/recognition-interface.js +43 -0
  35. package/src/register.js +7 -2
  36. package/src/settings/config.js +146 -0
  37. package/src/settings/deps.js +163 -0
  38. package/src/settings/page.html +233 -0
  39. package/src/settings/page.js +11 -0
  40. package/src/settings/server.js +195 -0
  41. package/src/tool-spec.js +6 -1
  42. package/src/tts-interface.js +59 -0
  43. package/src/wake-failure.js +67 -0
  44. package/src/watch-actions.js +173 -170
  45. package/src/watch-lines.js +459 -459
  46. package/src/watch-loop.js +37 -11
  47. package/src/watch-material.js +101 -101
  48. package/src/watch-run.js +79 -8
  49. package/src/watch-source.js +201 -201
  50. package/src/watch-state.js +194 -194
  51. package/src/watch.js +43 -43
  52. package/src/window-interface.js +81 -0
  53. package/src/window-protocol.js +122 -0
package/CHANGELOG.md CHANGED
@@ -1,1090 +1,1221 @@
1
- # Changelog
2
-
3
- All notable changes to **dsh-watch-together** are documented here.
4
- This package starts its own version line at `0.0.7` — it is not a continuation of `dsh-video-storyboard`.
5
-
6
- ## [0.1.0] - 2026-11-01
7
-
8
- 首个发布版本。要求 `dsh-video-storyboard@^0.5.11`(字幕轨用到它的 `./transcript-pass` 子路径)。
9
-
10
- ## [0.1.1] - 2026-11-01
11
-
12
- **依赖升到 `dsh-video-storyboard@^0.6.0`。** 分镜从"固定宫格"改成"档位排布"——
13
- 一格 = 一个镜头、格子大小跟切点密度走,`boardOptions()` 返回的参数从
14
- `cells / sheets / minGap` 换成 `maxFrames / maxSheets / minFrames`。旧的参数名在 0.6.0 里已经不存在,
15
- 所以这一版**必须**配 0.6.0 及以上,不能和 0.5.x 混装。
16
-
17
- ### 台词写完之后不再递整段清单(防剧透)
18
-
19
- 用户反馈"老是剧透后面的"。根因不是提示词不够狠:写台词时必须把整段 5 分钟的清单交出去,
20
- 写完它仍然留在上下文里,模型就会把它当成"我知道后面"的凭据 —— 光说"不许提"压不住真实内容。
21
- 现在台词一就绪就换成一句简报("台词已就绪,清单不再提供"),模型手里真的没有后面的信息。
22
-
23
- 顺带在提示词里加了一句自问:「这句话是不是只有已经看过 xx 秒之后的人才写得出来?」
24
- 不确定的事用"现在"而不是"接下来"。
25
-
26
- ### Liquid glass, second pass — the window was still ugly (2026-11-01, later)
27
-
28
- Verbatim feedback: "看一下 watch-together 的悬浮窗设计,太丑了现在" — the first liquid-glass pass
29
- had the vocabulary right and the physics wrong. Five defects, all of them visible in a screenshot:
30
-
31
- **The corners were not round.** `round_rect` and `squircle_mask` both used a superellipse with
32
- `n = 5`, and at `n = 5` the curve is within 0.6% of the straight edge until the last few pixels —
33
- a 22px radius rendered as a near-square corner with a tiny fillet. `squircle_mask` had a second,
34
- independent bug: the row-solve was inverted (`x` grew from 0 instead of `r`), which cut the corners
35
- out as *squares*. Both now use `n ≈ 2.2` and solve each row's span directly (O(h) instead of O(w·h),
36
- and it buys 2× supersampling for free).
37
-
38
- **The chrome was opaque.** The header was a `tk.Frame` and the composer a second one; Tk widgets
39
- must have an opaque background, so the top and bottom strips of a "glass" window were dead black.
40
- Both are now drawn on the canvas (status dot, title, count, `▾`/`✕` as hit-tested canvas items,
41
- the input well as a rounded polygon). Only the `Entry` stays a real widget — it has to be opaque, so
42
- it lives inside a deliberate *inset* well.
43
-
44
- **Bubbles were paper.** Each one was filled with a flat `#3a4459`. They are now cut from the same
45
- blurred backdrop as the panel (`plate()`), with only a white/blue wash on top — they transmit what
46
- is behind them.
47
-
48
- **Tint was global and blue.** One tint for the whole window, and a blue-grey `#171a21`, which fights
49
- every colourful frame it sits on. Tint is now per-plate and *neutral*: measure that plate's mean
50
- luminance and solve for "how opaque does the ink need to be to land under 84" (`a = (L-84)/(L-12)`).
51
- Over a white page it darkens itself; over a dark scene it stays transparent.
52
-
53
- **The sheen was made of lines.** Diagonals stacked with a 3px step left a visible weave across the
54
- panel. Every gradient is now computed on a 16×16 canvas and upscaled bicubically.
55
-
56
- Also added: **dispersion** (warm outside, cool inside, full strength around the whole chamfer and
57
- stronger at the four corners, because a fillet has curvature everywhere but compound curvature at
58
- the corners), **edge fading** in the message list (rows fade in/out across a 30px band instead of
59
- popping at the clip boundary — suppressed on the side that has no more content, otherwise the newest
60
- message is permanently the faintest), a **200ms entrance** per new bubble (8 frames: 10px rise +
61
- alpha ramp + text colour lerp), and **smooth scrolling** (5 frames × 16ms) so the fade band has
62
- something to fade across. The scrollbar moved out into the margin beside the panel.
63
-
64
- Two long-standing bugs fell out of this: `Meta.paint` ended with a leftover `self.cv.tag_lower("bg")`
65
- from the pre-canvas version — `Meta` has no `cv`, so the exception aborted `_reflow` mid-list and only
66
- the newest message was ever visible; and the backdrop image was created after the messages without
67
- `tag_lower`, so any repaint buried them.
68
-
69
- ### Performance — the glass was re-baked on every frame (2026-11-01, same session)
70
-
71
- "背景的模糊还是很卡" — measured, not guessed. One panel plate cost **520ms**, a slab 90ms,
72
- a bubble 28ms. The culprit was `_ring`: it built **two full-size fill masks and subtracted them**,
73
- and every plate needs five or six rings (rim, soft rim, bottom shade, warm, cool, edge weight), so
74
- a 665×594 panel spent ~100ms in that one function plus ~15ms per `squircle_mask`.
75
-
76
- Three fixes, in order of payoff:
77
-
78
- - **Ring solved per row, no intermediate images.** A ring's row is just two short segments — left
79
- and right — so the inner and outer x are solved directly (`_ring`), and middle rows are skipped
80
- entirely. O(h) instead of O(w·h), and no subtraction allocations. 100ms → 3.7ms.
81
- - **Everything smooth is computed at ¼ scale.** `_corner_weight`, `_edge_weight` and `refract`'s
82
- bevel weight are soft blobs, not features: build them at 665/4 and upscale bilinearly. Gaussian
83
- blur cost drops 16×, and the bevel mask (14 rectangle outlines over the full image) went from
84
- ~20ms to ~1ms.
85
- - **Supersampled masks now downsample with `Image.BOX`** instead of LANCZOS. For an exact 2×
86
- reduction BOX *is* the 2×2 average — same result, ~4× faster. `squircle_mask` 15ms → 4.9ms.
87
-
88
- Result: panel 520 → **50ms**, slab 90 → **6.8ms**, bubble 28 → **8ms**; `_paint` with a warm cache
89
- **1.3ms**, `_reflow` **0.5ms**, cold repaint (backdrop changed) **76ms**, window open **387ms**.
90
-
91
- Also: the R/B channel-scaled displacement (`chroma_edge`) is now **off by default**
92
- (`DSH_WATCH_CHROMA_EDGE=1` turns it back on). It cost two full-size channel resizes per plate
93
- (+18ms) and was invisible — the backdrop is already blurred and inked, so there is no contrast left
94
- at the rim to disperse. The visible dispersion is the warm-outside/cool-inside tint pair, which stays.
95
-
96
- Finally, resizing no longer re-bakes: while the resize grip is held the panel is a bilinear scale of
97
- the last baked plate (1.2ms instead of 50ms), and a precise re-bake happens 300ms after release.
98
-
99
- ### Performance, second pass — the backdrop was recomputed on every mouse release (2026-11-01)
100
-
101
- "超级卡,绝对不止一两百毫秒" … "拖动根本不会刷新" … "碰到屏幕边缘松手百分百闪一下".
102
-
103
- Measured, the picture was different from the first pass: `_paint` was already fast (1.3ms warm),
104
- but **every time a drag or resize settled**, `_refresh_backdrop` cost **165ms** — and during the drag
105
- the backdrop never updated at all, because refresh was debounced to 420ms after release.
106
-
107
- What was actually slow, in order of payoff:
108
-
109
- - **`_ring` built two full-size fill masks and subtracted them**, and every plate needs five or six
110
- rings. Rewritten to solve each row's inner and outer x directly and draw two short segments —
111
- O(h), no intermediate allocations. 100ms → 3.7ms per plate. (While rewriting it I dropped the
112
- `width` argument on the floor: the band came out as "from the edge to `inset`", which made a
113
- 1px highlight vanish entirely and pushed the inner shade line onto the rim, darkening it. The
114
- tell was "the glass has no edge and looks grey". Fixed by solving both boundaries properly.)
115
- - **Everything smooth is now built at ¼ scale and upscaled**: curvature weight, dispersion weight,
116
- and the bevel weight in `refract`. They are blobs, not detail. Gaussian cost drops 16×.
117
- - **The "light" layers are pure geometry** — sheen, rim, inner shade, warm/cool fringes do not
118
- depend on the backdrop at all. They are composed once per size into `_light_overlay` and cached;
119
- a re-bake now pays one `alpha_composite` instead of six.
120
- - Tint and wash are both flat colours over flat colours, so they are blended into a single colour
121
- and applied once. Mean luminance is measured on a 48×48 copy (the mean does not care about
122
- resolution). 2× supersampled masks downsample with `Image.BOX` instead of LANCZOS.
123
- - **The stage is now one full-screen capture at ¼ resolution**, taken at open while the window is
124
- still withdrawn. Any later position is a *crop*, never a re-grab — the old "window + margin"
125
- stage ran out of bounds whenever the widget was near a screen edge, and falling out of bounds
126
- is exactly the "release → hitch → flash" the user was seeing.
127
- - **Dragging refreshes live**: `_live_backdrop()` crops from the stage and `_paint_glass_only()`
128
- swaps only the panel and the two slabs — the header, bubbles and composer do not move relative
129
- to the window and are not redrawn. Throttled to 30ms (the mouse is 120Hz). Two hidden costs fell
130
- out of this: `_window_rect()` calls `update_idletasks()`, which silently ran a *full* repaint on
131
- every frame (+17ms), and position-only `<Configure>` events repainted the entire window.
132
- - Bubble plates are invalidated by their own counter (`chat_glass_ver`), so a small drag no longer
133
- re-bakes six bubbles per frame; only panel/slab caches are dropped.
134
- - Edge-of-screen windows now only need to *overlap* the stage, not sit inside it; the off-screen
135
- part is cropped short and padded. And a settle within 8s of the last capture does not re-capture
136
- at all — the stage is refreshed for free while the window is hidden.
137
-
138
- Numbers (665×594 panel, 150% DPI): a panel plate 520ms → **7.7ms**, slab 90 → **0.9ms**, bubble
139
- 28 → **0.9ms**; `_paint` warm 1.3ms, `_reflow` 0.5ms; **dragging costs 24–28ms per frame (~38fps)
140
- where it used to be frozen**; window open 510ms including the full-screen stage.
141
-
142
- ### Fixed — optional services must go through `ctx.get()`
143
-
144
- `ctx?.attachments?.saveImage` looks like a runtime probe but throws in a real host: cordis's `ctx`
145
- is a Proxy whose `get` trap **throws** `cannot get property "xxx" without inject` when a service was
146
- not declared in `inject`. `?.` only guards `null`/`undefined`, not exceptions.
147
-
148
- All optional-service lookups now go through `serviceOf(ctx, name)` (in `src/timer.js`): it prefers
149
- `ctx.get(name)` — cordis's documented way to ask for an optional dependency, returning `undefined`
150
- when absent — and only falls back to property access inside a `try`.
151
-
152
- ### Liquid-glass window, one stream, and a name you can change (2026-11-01)
153
-
154
- Reported as: the scripted lines (warm amber, with a "台词" label) and the assistant's replies (cool
155
- grey, labelled "陪看") read like two different people talking in one stream — and the window itself
156
- looked like a plain dark panel.
157
-
158
- **One stream, one look.** `ROLE` now maps `line` and `assistant` to the *same* colours, and the head
159
- line shows **only the timestamp** — no "台词", no "陪看". Only the user's own messages keep a tint
160
- (so you can still tell which side you are on).
161
-
162
- **Timestamps are wall-clock now** (`HH:MM:SS`), for every role. Scripted lines used to show their
163
- playback position (`01:26.0`) while everything else showed local time — two time bases in one
164
- stream, so reading it meant converting in your head. Seconds are included because a segment runs
165
- 2–5 minutes and several messages share the same minute; `HH:MM` alone would make the stamps useless
166
- for telling them apart. A message with no `at` gets no head line at all (an empty label still eats
167
- a full line of height).
168
-
169
- **Liquid glass.** Three things carry the effect, because tkinter cannot blur what is behind it:
170
-
171
- - **24px+ radius** — and `round_rect` no longer uses `smooth=True`, which renders a 22px radius as
172
- roughly 14px (it smooths a polygon rather than following an arc). It now samples each corner arc
173
- directly.
174
- - **A refractive edge**: a 1px inner highlight along the top, plus an outer border split into a lit
175
- upper half and a shadowed lower half — what a real piece of glass does.
176
- - **Slight window transparency** (`-alpha 0.975`, `DSH_WATCH_GLASS_ALPHA` to tune, ≥1 disables).
177
- The desktop shows through just enough to read as glass without competing with the text.
178
-
179
- Buttons and the input field are **pills** now (`Pill` class + a Canvas-backed field): a square
180
- "发送" button next to a 24px-rounded panel was the most obviously un-Apple thing left.
181
-
182
- **The title is editable.** Click the name in the header, type, press Enter — saved as `name` in
183
- `~/.dsh/watch-window.json` and restored next launch. Committing uses an explicit `_editing` flag
184
- rather than `winfo_ismapped()`, which is still `False` on the frame right after `pack()` and would
185
- silently swallow a fast Enter.
186
-
187
- **Fixed:** `meta` entries (wake failures, mic status) were falling through to the assistant bubble
188
- style — a screenful of `[一起看] 叫醒失败` rendered as full-size cards. They now use the grey
189
- one-line `Meta` row that already existed for exactly this.
190
-
191
- **Fixed:** the saved geometry was clamped against `sw - 120` instead of the window's own width, so a
192
- 700px-wide window could be restored 580px off the right edge.
193
-
194
- ### No more self-made "queued messages", one reminder per interjection, and a hideable window (2026-11-01)
195
-
196
- Reported as three things that turned out to be one root cause plus two design gaps.
197
-
198
- **The queue strip.** `wakeSession` delivers through `agent.followup()`, which lands in the host
199
- inbox's `next-turn`. DSH's `QueueDock` renders **every** row of `next-turn` and does not filter by
200
- `source.kind` — so the plugin's own instructions showed up in the input box as pending messages the
201
- user never typed ("插话栏自动出现"). Two consequences fixed here:
202
-
203
- - **The hangup note no longer goes through `followup`.** Closing the window is still a hangup (clock
204
- stops, nothing is rebuilt, no lines are spoken), but the explanation is now written into
205
- `watch.json` and handed to the model on its next tool result (`takeHangupNote`). The watch loop
206
- already has the model blocked inside an interrupted tool call, so nothing is lost — and the queue
207
- strip stays empty. `markHungUp(input, env, note)` carries the text; taking it clears it.
208
- - **`[未回应]` is emitted once per interjection.** It used to be appended to *every* tool result
209
- until the model answered with `say`, so one message from the user could be read as three separate
210
- events ("大肥鱼已经重复了"). `noteInterjected` also no longer restarts the clock when the same
211
- sentence arrives twice inside the 3-minute TTL.
212
- - **The interjection prompt is two sentences, not a wall of ⚠️.** Same requirements
213
- (`say` first, `speakNow`, lines in the same call), a fifth of the length — it is rendered in the
214
- queue strip, so its size is user-visible.
215
-
216
- ### `window: "hide" | "show"` — put the window away without ending the watch
217
-
218
- Closing the window means "I am done watching". Hiding it does not: the process stays alive, the
219
- clock keeps running, lines keep being spoken, nothing is marked as hung up. Reported as
220
- "如果有其他功能隐藏悬浮窗会更好".
221
-
222
- - `watch_together({ window: "hide" })` writes `hidden: true` into `~/.dsh/watch-window.json`;
223
- `window.py` polls its config every 200 ms (`_sync_visible`) and does `withdraw()` / `deiconify()`.
224
- `withdraw` rather than `iconify`: an always-on-top floating window should leave no taskbar entry
225
- behind.
226
- - `openFloatingWindow` clears `hidden` **before any early return**, so a window that was hidden when
227
- the process died does not come back invisible.
228
-
229
- ### Two-track prefetch (2026-11-01) — subtitles no longer wait for the pictures
230
-
231
- The picture side is the slow one: a segment costs a download plus a scan (10–20 s, 20–90 s for the
232
- first), while the text for the same window arrives in a few seconds (site CC: instant; local ASR
233
- RTF 0.019 ≈ 6 s per 5-minute segment). They used to be produced and delivered as one package, so
234
- the text sat in the slow batch's shadow. Now they are two independent tracks over the **same**
235
- batch table and the **same** look-ahead window.
236
-
237
- - **New subtitle track** (`transcribe` → `dsh-video-storyboard/transcript-pass`). Mirrors the picture
238
- track line for line: same `plan.indexAt` / `windowAt`, its own `transcribed` set. "Whoever's window
239
- is full stops first" falls out of `find()` returning `undefined` — no extra rule.
240
- - **Two-part delivery.** When the text lands before its pictures, it is sent on its own
241
- (`[一起来看·台词] 03:00–06:00` + one timestamped sentence per line). When the picture batch
242
- arrives later it is built with `omitTranscript`, so the cells carry only times and the sentences are
243
- not repeated (measured: 17k vs 26k tokens per 2 hours, +50% when repeated).
244
- - **`feedTranscriptLeadMs`** (default 0 = send as soon as it lands). Raise it to ~20000 if the
245
- two-part delivery feels chatty and you would rather wait for one combined message.
246
- - **`transcriptTrack: false`** turns the whole track off.
247
- - **Failures don't sink the loop.** A failed transcription is not marked as done, so the next tick
248
- retries; three failures in a row blacklist that segment for 10 minutes (a missing ASR service
249
- should not be hit every 2 seconds). The picture track is never blocked by it.
250
- - **Cross-track timestamps now share one clock.** `transcribedAt` / blacklist times were stamped with
251
- `Date.now()` while the tick compares against the injectable `deps.now()`; the difference was
252
- negative by a trillion milliseconds, so the "skip for 10 minutes" and "wait N ms before feeding"
253
- gates were both permanently bypassed (feeding never fired at all).
254
-
255
- ### Experience pass (2026-11-01) — the minutes spent staring at nothing
256
-
257
- Same code, same contract; what changes is what the user sees (or hears) while waiting.
258
-
259
- - **A slow build now says something.** The first batch of a film needs a download plus a scan
260
- (20–90 s) and a tool call cannot speak — so the window stayed empty and the only signal was
261
- silence. After 4 s of building (`DSH_WATCH_SLOW_BUILD_MS`) one `meta` line is appended to the
262
- stream: 「正在取 03:00–06:00 这一段…」. Fast segments write nothing.
263
- - **The measured latency is finally used on the main path.** `latency.js` has been calibrating
264
- "read position → result ready" for a while, but only the background clock (`shouldSpeak`) spent it;
265
- the blocking call still waited until `segment end - lead`, so on the same machine the clock spoke
266
- early and the tool call spoke late. `deliveryState` now uses `lead + aheadSeconds`, while the text
267
- still reports `lead` (what is pulled earlier is the work, not the sentence).
268
- - **Calibration only counts deliveries.** Not-yet calls take tens of milliseconds and are not samples;
269
- recording them dragged the EWMA towards zero (and wrote `latency.json` on every poll).
270
- - **The last batch is delivered at the tail.** The final segment's due point is `end - lead`, which for
271
- the last batch sits past the end of the film — the position never reaches it, so the user watched
272
- the ending and got nothing. Reaching/passing `dur - 1` now counts as due.
273
- - **`speech` only lists lines that are still ahead.** It used to echo the whole draft, including the
274
- lines the same call had just pruned as past — the model read them as "still going to be spoken".
275
- - **Delivery guidance trimmed ~45%** (≈1150 → ≈640 chars). It is resent every batch; the loop/pacing
276
- rules already live in the tool description, so only the hard rules stay here: write the lines,
277
- no spoilers, one sentence, `say` is the only visible channel.
278
-
279
- ### Reading pass over the loop (2026-11-01) — six real bugs, one hot path
280
-
281
- No new features. Everything below was found by reading the code against its own comments and then
282
- reproducing it; each fix carries a regression test that fails on the old code.
283
-
284
- - **`lastDelivered: null` was read as batch 0.** A delivery blocked by the "no lines yet" gate writes
285
- `lastDelivered: null`, and `Number(null)` is `0` — exactly the first batch's start. That batch then
286
- counted as already delivered forever: `wait: true` woke up and answered "already delivered", image
287
- and manifest never handed over. Empty now stays `NaN`.
288
- - **Same film, two URL forms → the loop restarted.** `samePlan` compared the raw `input` string, but the
289
- extension reports `…/BV1g3xN6hEuw/?trackid=…&spm_id_from=…` while the model usually holds the clean
290
- link. Every second call therefore looked like a new source, wiping `spoken` and re-waking segments
291
- that had already been delivered. It now compares `sessionKey()`.
292
- - **`dur: null` became `0 s` on the bridge path.** `Number.isFinite(Number(s.dur))` passes for `null`,
293
- so a report without a duration set the baseline to 0; the next real reading (600 s) then differed by
294
- more than a second and was judged "video changed" — the clock stopped mid-film. `num()` in
295
- `position-bridge.js` and the baseline update now treat empty as empty.
296
- - **`waitForVideo` lost the hangup.** The input surface is prepared once (`prepared ??=`), and the
297
- early pre-warm for `waitForVideo` passed no arguments — so `input`/`open` never reached it. Without
298
- `input` the recorded hangup could not be matched, the window was re-opened, and the call went off to
299
- wait for a video instead of returning `[hangup]`.
300
- - **`dueLine` rewrote `watch.json` on every tick.** Its `dirty` flag was shared across segments: once one
301
- batch had pinned its un-timed lines, every later batch was written back unchanged — a full state write
302
- every 2 s for the rest of the film. The flag is per segment now.
303
- - **`waitUntil` / `waitForRefill` lied about why they stopped.** Breaking out because the user paused (or
304
- the film ended) still produced "waited to the cap". The text now names the real reason.
305
-
306
- Hot path, same area:
307
-
308
- - `cachedCues()` re-read and re-parsed the whole subtitle file on every tick (`dueLine` asks several
309
- times per tick). It is memoised on `path + size + mtime` now, and returns the **same array** so that
310
- `makeLagFn`'s memo can be keyed on array identity. `makeLagFn` additionally sorts once and looks up
311
- by binary search instead of a linear scan of every cue. 2000 cues × 5400 lookups: **66.7 ms → 0.8 ms**
312
- (×83), and the disk read/parse per tick is gone.
313
- - `lines-util.js` had its own `cacheDir()` that fell back to `~/AppData/Local` on every platform, so on
314
- Linux/macOS the subtitle cache landed in a directory that does not exist; it now uses the storyboard's
315
- `cacheDir()`. `findCachedMedia()` likewise uses `tmpdir()` instead of `LOCALAPPDATA/Temp`.
316
- - Dead exports removed: `plan.starts` (a 513-element array allocated on every `makePlan`),
317
- `legacySessionKey`, `wasWritten`, `MATERIAL_PARTS`. The input surface failing to start no longer fails
318
- the whole call — it is reported in the result instead.
319
-
320
- Three rounds on 2026-10-31. The through-line: the plugin knew something, and the model (or the user)
321
- never found out — plus one window that needed to look like something people want to keep on screen.
322
-
323
- ### Long-video recap — merged, but opt-in
324
-
325
- PR #2, after one round of review. Its first shape prepended a 420-character `[前情]` to **every**
326
- delivery, partly built from the model's own scripted lines: second-hand context in a package whose
327
- contract is "raw material only — never retell what the user just watched", at ~200 tokens per
328
- segment, with no evidence it helped.
329
-
330
- What shipped instead: off unless `recap: true` or `DSH_WATCH_RECAP=1` (`recap: false` beats the env
331
- var); only **cached subtitle sentences**, never the model's lines; `recapSegments` 1–3 (default 2),
332
- `recapMaxChars` 80–1200 (default 420); never reads past the current segment, never trims the live
333
- transcript, no ASR, no network. Whether it actually reduces retelling is still **unmeasured** — it
334
- stays opt-in until somebody measures it.
335
-
336
- ### Observability: `statusOnly` can now answer "why is it slow"
337
-
338
- Promised in issue #4. `pos + reason` says *what* the clock thinks, not *where it is stuck*.
339
-
340
- - `segment { index, from, to, delivered, total }` — which batch, its bounds, how many were delivered
341
- this session, how many the film has (`total` is `null` when the duration is unknown). The last batch
342
- index is taken at `dur - 1 ms`, because a duration that lands exactly on a boundary would otherwise
343
- report one batch too many.
344
- - `speech { queued, lastLateSec, busyUntil }` — lines still waiting, how late the previous line was
345
- (from `dueLine`'s new `meta: true`, which also keeps the plain-string return for old callers), and
346
- when the serial voice engine frees up.
347
- - `build { inflight, cached, lastMs }` — which batch is being built, how many are cached, how long the
348
- last build took. The cache is passed into the loop for reporting only; it never influences a decision.
349
- - `queued` needs a disk read, so it is filled in `statusOnly` only, and a failure there is reported as
350
- `speech.queueError` instead of being swallowed (the first version of this swallowed a `ReferenceError`
351
- from a missing import and looked exactly like "there are no lines").
352
-
353
- ### The floating window, rebuilt
354
-
355
- "这个悬浮窗太丑了" — fair. The old one was a borderless frame with a `Text` widget that painted
356
- role-coloured **full-width stripes**, on a window Windows stretched from 96 dpi, reading the whole
357
- `chat.jsonl` every 200 ms.
358
-
359
- - **Real bubbles.** Each message is its own rounded card (Canvas background + wrapped Label), sized
360
- to its content: script lines in amber with a left rule, the model in slate, the user's own words
361
- right-aligned in blue. Above each one, a muted line saying who and when (`台词 04:12.3` for a
362
- scripted line, `我 21:16` for chat).
363
- - **Per-monitor DPI awareness** before the window exists, and every size/font derived from the real
364
- scale factor. Unaware Tk windows are bitmap-stretched at 125/150%, which reads as "blurry and wrong".
365
- - **Rounded window** via `-transparentcolor` (Windows only; falls back to square corners), a 1 px
366
- border, and a hand-drawn 6 px scrollbar that only appears when the list actually scrolls.
367
- - **Does not steal focus.** `focus_force()` at startup meant pressing space to pause the video landed
368
- in the chat box; now the entry only takes focus inside the window.
369
- - **Does not fight your scrolling.** New lines auto-scroll only if you were already at the bottom.
370
- - **Incremental read.** Only the bytes appended since the last tick are parsed, and the first paint
371
- replays just the last 60 entries.
372
- - Resizable from the bottom-right grip; position and size persist in `~/.dsh/watch-window.json`.
373
-
374
- ### Stop when the signal says stop: hangup, dead source, switched video
375
-
376
- Reported as "换片或者我都关浏览器了还在念台词" and "关了悬浮窗 AI 还是会自动调出来,根本不会自动结束".
377
- Both were the same shape: the plugin knew the source was gone, and kept talking anyway.
378
-
379
- - **Speech now requires a believable position.** The line queue only fired when the position was
380
- `fresh`, or `extrapolated` within `SAFETY_AFTER_MS` (20 s — the normal gap between probes).
381
- Before, the only thing excluded was `paused`; `estimate()` happily extrapolates a dead source
382
- forward and `pos` stays finite, so closing the browser kept reading lines out for minutes.
383
- Nothing is spoken on an `unknown` position, and the position-unknown give-up dropped from
384
- 10 min to 5 min (the watch should not sit there pretending).
385
- - **Closing the floating window is a hangup, treated like an interjection.** The window is the only
386
- way to talk mid-watch, so closing it means "I'm done":
387
- - the clock stops and **really wakes the model** — `wake:false` (the default) used to silence this
388
- too, because it shared the `wake` path with the segment-end reminder. User actions (hangup,
389
- video changed, video ended, seek, unreadable position, high-frequency mode) now use a separate
390
- always-real channel (`wakeSignal`), and the message says **do not call watch_together again and
391
- do not read out any more lines**;
392
- - the guard is stored on the loop and can be turned on later (`resumed` path used to freeze it,
393
- so a window opened by an earlier call was never guarded);
394
- - the next tool call **does nothing at all**: no frame, no clock, no window (`[hangup]` result).
395
- `sameWatch` previously required `args.input`, which the model never sends — so every call looked
396
- like "a new watch" and re-opened the window the user had just closed.
397
- - `wakeWithRetry` called an undefined `note()` in its failure branch (a `ReferenceError` swallowed by
398
- the ticker). Real wakes can fail, so it was reachable; now it records into `loop.logs`.
399
-
400
- Tests: 247 pass, +4 in `test/hangup-guard.test.mjs` (dead source sends nothing, live source still
401
- speaks, hangup wakes with the right wording, post-hangup call is inert).
402
-
403
- ### Interjections: speak first, then look
404
-
405
- Reported as "它一声不吭先去 zoom,回来才说话". The root cause was not the model: a normal reply
406
- never reaches the floating window — only `say` does and only `say` is spoken. So "think, then look,
407
- then answer" was, from the user's side, complete silence for tens of seconds.
408
-
409
- - One wording, one place (`src/interject.js`) for all five entry points (during a build, during the
410
- lookahead fill, during a blocking wait, `waitUntil`, `nextLine`). It now says exactly what to do:
411
- `watch_together({ say: "我看一眼", speakNow: true })` — one call, words written before any frame
412
- is built. `lines` and `say` can ride in the same call, so "台词优先" no longer means "stay silent".
413
- - Unanswered interjections are **tracked**: the next tool result ends with `[未回应] …你还没回`,
414
- until a call actually carries `say` (expires after 3 min). Previously the reminder existed only
415
- inside the message that woke the model, which it had already scrolled past.
416
- - `waitUntil` / `nextLine` called a function that **did not exist** (`chatResult`) — an interjection
417
- during either wait threw `ReferenceError` and the tool failed. Defined, and it reuses the same wording.
418
- - Waiting for a video to appear returned a result **without `text`**, which the host's `output.schema`
419
- requires. That path now returns a proper result.
420
-
421
- ### Reply vs. scripted line: 12-second guard
422
-
423
- Reported as "说话和插话的回复离太近,把后面那句改一下". Two lines spoken back to back on a serial
424
- TTS chain means the second one either drifts or is dropped by the adapter (queue > 3.5 s → `skipped`).
425
-
426
- - `say` now marks the voice engine busy for its full spoken length (`src/reply-guard.js`), so the
427
- loop stops feeding scripted lines while a reply is still playing. Previously only the loop's own
428
- lines updated that clock — a reply was invisible to it.
429
- - Lines scheduled within 12 s of a reply are **withdrawn from the batch and handed back** to the
430
- model (`[lines·太近]`) with instructions to rewrite them around what was just said, or drop them.
431
- Withdrawn, not silently deleted: the user asked for "改一下", not "少一句".
432
-
433
- ### Switching videos is noticed in ~2 s, not ~15 s
434
-
435
- - The per-tick bridge read (every 2 s) now does the switch / end-of-video / big-jump checks, and
436
- keeps the `dur`/`url` baseline up to date. Before, all three lived in the 15-second CDP probe
437
- branch only, so a switch could go unnoticed for a quarter of a minute — while the clock kept
438
- computing segment boundaries against the old film.
439
- - The blocking wait in `watch-run` now compares each read against the film it started with and
440
- returns `[video-changed]` immediately. **This was the only reliable path**: the loop's wake goes
441
- through `followup()`, which is delivered *after* the current tool call returns — and that call was
442
- busy waiting.
443
- - `sourceSwitched()` centralises the test, and `Number(null) === 0` is explicitly guarded: a
444
- not-yet-known duration used to look like a "0-second film" and stop the watch instantly.
445
-
446
- ### Cold start: don't wait a full minute for a video we can already identify
447
-
448
- - The extension only reports while the tab is **visible** — and "一起看" is usually typed in another
449
- window. The position went stale after 5 s, the plugin concluded "no video", and sat in the 60 s
450
- wait. It now falls back to a **stale** sample (up to 2 min) to identify the film, marks the
451
- position `stale`, and lets the next fresh reading correct it.
452
- - Automatic waiting (no `waitForVideo`) dropped from 60 s to **20 s**; explicit `waitForVideo: true`
453
- stays at 120 s.
454
- - `probeBrowser()` is skipped when the extension already reports: one probe is `listTargets`
455
- (1.2 s) plus up to 8×1.5 s of CDP round-trips — pure overhead for a `browser:` line the extension
456
- just answered. The line now reads `browser: extension reporting <title> playing 03:20`.
457
-
458
- Tests: 243 pass (`node --test`), 6 of them new in `test/interject-reply.test.mjs`.
459
-
460
- ## [0.0.7] — 2026-10-31 (first release)
461
-
462
- The first published version. One tool, `watch_together`: it follows the user's real playback
463
- position, hands the model one storyboard + transcript per segment just before that segment ends,
464
- and speaks the scripted lines at the second they belong to.
465
-
466
- **Licence: Apache-2.0** (the package was developed under MIT and switched before the first
467
- public release, to match `dsh-video-storyboard`). `LICENSE` is the full text, `NOTICE` states
468
- what the project deliberately does **not** do — no hosted video, no uploaded position, no DRM or
469
- paywall bypass, no bundled TTS engine.
470
-
471
- ### Repo hygiene — the extension's manifest and icons were never committed
472
-
473
- `.gitignore` carried `manifest*.json` and `*.png` (meant for CLI artifacts). Those two rules also
474
- swallowed `extension/manifest.json` and `extension/icons/*.png`, so a clone would have shipped an
475
- extension **with no manifest** — completely broken, and nothing would have failed until someone tried
476
- to load it. Both are now force-added, and the ignore rules are anchored (`/*.png`, `/*.meta.json`) so
477
- they can only ever catch files at the repo root. Also: `* cookies*.txt` (a pattern with a space, which
478
- never matched anything) is gone, `__pycache__` is out of the npm tarball via a new `.npmignore`, and
479
- `npm test` no longer requires the sibling `dsh-video-storyboard` checkout — it falls back to the
480
- installed copy, so a clone can run the suite.
481
-
482
- ### Docs — one page per service, and the stale one is gone
483
-
484
- `docs/WATCH.zh.md` still explained how to configure things around the **OS media session (SMTC)**,
485
- which was deleted a while ago: wrong rationale, wrong `confidence` values, wrong defaults. Deleted.
486
- Replaced by [`docs/CONFIG.zh.md`](docs/CONFIG.zh.md): ffmpeg → yt-dlp + cookies → subtitles/ASR →
487
- browser extension (9377) → debug port (9333) → voice (`voice.json` + `tts.json`) → floating window →
488
- cache locations → a one-page troubleshooting table. Every entry says **what breaks if you skip it**.
489
-
490
- `README.md` got a 30-second start, a "what to configure" table, a corrected parameter table
491
- (`depth` is auto-by-time now, `lookahead` was missing), a CLI table that matches the 15 real
492
- subcommands, a privacy note for the extension, and a dev section. `docs/VOICE.zh.md` gained
493
- `state: 'skipped'` and a correction: `at` is a **playback second**, not a wall-clock timestamp.
494
-
495
- ### `doctor` — three levels, because "not configured" is not "broken"
496
-
497
- `FAIL` used to be printed for things that are merely "not set up yet": a missing cookie file (only
498
- needed for Bilibili), a closed debug port (the extension is the recommended channel), an extension
499
- that is loaded but has no video playing. First-run users read that as "something is broken" and went
500
- to reinstall the extension. Now: **OK / WAIT / FAIL**, only `plugin` and `ffmpeg` are fatal, and when
501
- the extension has checked in but nothing is playing, `doctor` says `READY — 播个视频就能读到位置`
502
- instead of "both position channels are down".
503
-
504
- ### Performance — the chat watcher no longer re-reads the whole log every 150 ms
505
-
506
- The blocking-wait loop polls `chat.jsonl` every 150 ms. Each poll re-read `readChat()` and parsed
507
- every line, so a two-hour session (thousands of entries) was decoding hundreds of KB several times a
508
- second, and getting slower the longer the session ran. `makeChatWatcher()` now keeps a byte offset
509
- and reads **only what was appended since last time** (falling back to a full re-read if the file
510
- shrank, i.e. it was cleared). Measured on a 5000-line log: **0.061 ms per poll, independent of file
511
- size**. `appendChat()` also stopped parsing the whole log to keep `at` monotonic — it reads the last
512
- 4 KB instead.
513
-
514
- ### Tool description — pacing is now a rule the model can follow
515
-
516
- `watch_together`'s description tells the model to keep lines **≥ 6 s apart** and why: speech is
517
- serialized, so a denser draft is thinned at runtime (engine busy → next line held; past the late
518
- grace → dropped). The three previous rounds of "台词太早 / 太密" all came from the model not knowing
519
- this budget.
520
-
521
- ### Fixed — speech piled up in the engine queue, and an interjection could no longer break a blocked wait
522
-
523
- Two reports in one message: "吐字太快,台词会挤到一起,只有上一句念完才到下一句,话太密会导致语音越来越
524
- 滞后" and "悬浮窗插话不能让他从等待中出来 —— 这个功能之前是好的".
525
-
526
- **The voice queue.** `examples/voice-edge-tts` chains every `due` event onto an unbounded serial promise
527
- ("two lines never overlap"). Lines are now scheduled at the right second, so when they arrive faster
528
- than the engine can speak them the chain simply grows: speech drifts further from the picture with
529
- every line, and the caption (written on `spoken`) drifts with it.
530
-
531
- - `src/watch-loop.js` — the clock now keeps a **voice budget**: after handing out a line it records
532
- `voiceBusyUntil = now + speechSeconds(len)` and will not hand out the next one while the engine is
533
- still talking. A line that misses its window by more than the late grace is dropped by `dueLine`
534
- as usual: **speak one line less rather than one line later**.
535
- - `src/speech.js` — `speechSeconds(chars)`: full spoken duration (`0.35 + chars/5`, 0.8–30 s).
536
- `speechLag()` stays as it was — that one answers "when may I start talking", this one answers
537
- "how long is the engine busy".
538
- - `examples/voice-edge-tts` — safety net: if a queued line has been waiting more than 3.5 s it is
539
- **abandoned** (logged) instead of spoken, and the queue empties immediately.
540
- - `src/speech-bus.js` / `src/chat-store.js` — a fourth state, `skipped`: the adapter reports that it
541
- gave up on a line, and `attachSpeechToChat` cancels the pending fallback timer for it. Without this
542
- the 2.5 s fallback would paint a caption for a line that was never spoken.
543
-
544
- **The interjection.** `chat.jsonl` is a **consuming** channel: `poll()` marks a message read. The
545
- blocking wait and the watch loop share one watcher, and the loop's handler is `followup()` — which
546
- cannot interrupt a session that is sitting inside a tool call (the message is only processed when
547
- the turn ends). So whichever polled first decided the outcome, and the loop (every 2 s) sometimes
548
- won: the interjection was swallowed, the wait's `poll()` never saw it, and the user's "stop, I have a
549
- question" did nothing until the segment ended.
550
-
551
- - `src/interrupt.js` — `enterChatWait()` / `chatWaiterCount()`: whoever is blocking on purpose
552
- **owns** the channel. `raceChat()` (storyboard build, prefetch) registers too.
553
- - `src/watch-loop.js` — `wakeOnChat` is skipped entirely while `chatWaiterCount() > 0`. The wake path
554
- still works when the model is idle (no waiter), which is its whole purpose.
555
- - `src/watch-run.js` (the `wait: true` loop), `src/watch-modes.js` (`waitUntil` / `waitForRefill` /
556
- `nextLine`), `src/watch-source.js` (`waitForVideo`) — all register as waiters for the duration of
557
- their loop.
558
-
559
- Tests: `test/lines-timing.test.mjs` (engine busy → next line is not handed out; the overdue one is
560
- dropped), `test/chat.test.mjs` (`skipped` writes nothing, not even the fallback),
561
- `test/interject-anywhere.test.mjs` (the loop must not consume while a waiter is active; counter
562
- cannot go negative).
563
-
564
- ### Fixed — scripted lines came out like a machine gun, and minutes before the picture
565
-
566
- Reported as: "台词出现时间早了很多,而且和机关枪一样突突突一下出来一大堆,时间点都比视频早了".
567
-
568
- The line queue is ordered by `at` (the second of the video this line is *for*) and fired by playback
569
- position, so the pacing is only as good as the `at` values. When a line was written **without** `at`
570
- (the model wrote prose only), `pinTimes()` decided when it would be said — and it took *the first N
571
- subtitle sentence starts of the segment*. Sixteen lines written for a 3-minute segment were therefore
572
- all packed into its first 62 seconds (181.6 → 244.2, measured on the live queue), i.e. one every
573
- 2–3 seconds: the clock ticks every 2 s and hands out at most one line per tick, which is exactly the
574
- "machine gun". The last 14 of them ran one to two minutes ahead of the picture they describe.
575
-
576
- - `src/watch-lines.js` `pinTimes()` — each line now aims at its **even share of the segment**
577
- (`from + i*size/n`) and snaps to the nearest subtitle start within half a slot, so the queue is
578
- spread over the whole segment instead of stacked at its head. Falls back to the even share when no
579
- start is close enough, and **never goes backwards** (the old tail fallback could emit 152.8 → 150).
580
- - `src/watch-lines.js` `dueLine()` — pinning uses **the segment that line belongs to** (`sizeOf`),
581
- not the segment the user happens to be in. With the 1/2/3/4/5-minute ramp, a 60-second slot pinned
582
- with a 300-second size put its last lines outside the segment entirely.
583
- - `src/watch-lines.js` `saveLines()` — `at` given as **subtitle text** was resolved only against
584
- `recallSegments()`, which is a 4-entry in-process cache (empty in a fresh process, and lines are
585
- usually written in a different turn). A miss silently became "no `at`", i.e. the head of the
586
- segment — the other half of "the line is way too early". Now it reads the on-disk
587
- `subs-<key>.json` cache first, then falls back to memory, then to a fuzzy match (≥60 % of the
588
- characters), and only then warns.
589
- - `src/watch-run.js` — the delivery note pruned "past" lines with `Number(l.at)`, and
590
- `Number(null) === 0`: **every line without `at` was judged as second 0 and deleted** at delivery.
591
- The note now previews the same pinning the clock will use, so the reported "earliest …" time is the
592
- real one, and only lines whose *actual* time has passed are dropped (by text).
593
- - `src/watch-run.js` — the note now lists the landing times it will use (`[lines] 落点:…`) and warns
594
- when the average gap is under 6 s, instead of leaving the model to guess its own pacing.
595
- - `src/watch-loop.js` — with the extension as the position source, the anchor is now re-read **every
596
- tick** (a small local JSON, not CDP). Between the 15-second probes the clock extrapolated blindly,
597
- so after a pause the lines up to 15 s ahead were spoken **early** — extrapolation is bounded for
598
- lateness but nothing guarded earliness.
599
- - `src/latency.js` `aheadSeconds()` — returns 0 instead of `NaN` when `ms` is missing. `NaN` made
600
- `pos` `NaN`, every comparison false, and `shouldSpeak()` reported "due" for the first unspoken
601
- segment at every tick.
602
-
603
- Tests: `test/pin-times.test.mjs` (the 16-line packing regression, monotonic fallback, cues bunched at
604
- the head), `test/watch-lines.test.mjs` (per-segment size, `at` from the on-disk subtitle cache),
605
- `test/lines-timing.test.mjs` (a stuck video must not speak the next line early).
606
-
607
- ### Fixed — the caption appeared before the voice, because it waited on `due` instead of "actually speaking"
608
-
609
- `attachSpeechToChat` wrote a line into `chat.jsonl` the moment `due` fired. But `due` only means
610
- "it is time to say this": synthesis still has to happen (edge-tts does a network round trip, then a
611
- fresh `ffplay` process — 0.6–2 s even for a short sentence). The floating window polls that file, so
612
- the text was already on screen a beat before anything was heard.
613
-
614
- Delaying the voice instead (`speechLag`) would align the two, but push the voice further from the
615
- picture, which is the one thing this plugin cannot trade away. So the **caption** moves:
616
-
617
- - `src/speech-bus.js` — a third state, `spoken`, plus `emitSpoken(event)` for engines to report
618
- "audio is starting now". The adapter API gains `emitSpoken`.
619
- - `src/chat-store.js` — writes on `spoken` when a `voice: true` subscriber exists; still writes on
620
- `due` when nobody will speak (the zero-dependency path must not go mute); falls back after
621
- `fallbackMs` (2.5 s, `DSH_WATCH_CAPTION_FALLBACK_MS`) for adapters that never report.
622
- Pairing is by `at|text`, not by `seq` — `spoken` is a **new** event, so `emitSpeech` gives it a
623
- new sequence number.
624
- - `examples/voice-edge-tts` — reports `spoken` right before playback starts (i.e. after synthesis).
625
- - `examples/floating-chat/window.py` — polls every 200 ms instead of 400 ms; the poll interval is
626
- the residual "text lags the voice" gap.
627
-
628
- `test/chat.test.mjs` covers both new paths (waits for `spoken`; falls back when nobody reports, and
629
- does not write twice if `spoken` arrives afterwards).
630
-
631
- ### Fixed — scripted lines never reached the chat window without a voice engine
632
-
633
- `watch-loop.js` consumed the due line inside `if (speechSubscribers() > 0)`. That helper counts only
634
- `voice: true` subscribers (real engines), while `attachSpeechToChat` — the one that writes lines into
635
- `chat.jsonl`, which is exactly what the floating window reads — subscribes with `voice: false`.
636
- So with no voice adapter, or one that failed to load, a scripted line was **never taken from the
637
- queue at all**: not spoken, not displayed, and the queue silently accumulated.
638
-
639
- Display and speaking are two separate things. The line is now handed out at its due moment
640
- regardless: `emitSpeech` delivers it to every subscriber, and only a real `voice: true` subscriber
641
- counts as "said" (`if (speechSubscribers() > 0) return;` still stops the wake, so nothing changes
642
- when a voice engine *is* attached).
643
-
644
- `test/lines-to-chat.test.mjs` covers both sides. The test was checked against the bug: restoring the
645
- old condition makes the no-voice case fail while the with-voice case still passes.
646
-
647
- ### Changed — `say` no longer reads as "only to answer an interjection"
648
-
649
- It always worked at any moment: it writes the sentence into the shared stream and hands it to
650
- whoever listens for speech, exactly like a scripted line. But the description ended with
651
- "use it to answer an interjection", which reads as "only after the user speaks". A model follows
652
- that literally, so the one path for saying something **unprompted** went unused.
653
-
654
- The description now says any time, and says it explicitly: something in the picture strikes you,
655
- the user asks something, a thought lands while waiting for the next batch — plus
656
- "do not wait for the user to speak first". It also states the cost, because that is what makes it
657
- usable mid-wait: no position read, no frame built, no batch advanced, one round trip.
658
-
659
- `test/say.test.mjs` pins the wiring — parameter → stream (one `assistant` row with `say: true`) →
660
- speech event with `origin: 'chat'`, no image, no state advanced. The store layer was already covered
661
- by `test/chat.test.mjs`; the uncovered part was the parameter entry itself.
662
-
663
- ### Added — an end-to-end test for "talk while the frame is building"
664
-
665
- The mechanism already existed (`raceChat(buildSegment(...))` in `runWatchPass`), and
666
- `test/interrupt.test.mjs` covered `raceChat` itself — but the `built.kind === 'interrupted'`
667
- branch had **no** coverage. If a refactor ever dropped the wrapper, or `chatWatcherShared()` got
668
- replaced with a fresh watcher per call, every existing test would still pass.
669
-
670
- `test/interject-build.test.mjs` builds a segment that takes 1.2 s, writes a user message at 0.2 s,
671
- and asserts all four things at once: the call returns before the build finishes, it carries that
672
- exact message, it carries no image, and the build still completes into the cache afterwards.
673
-
674
- ### Changed — three implicit couplings now have exactly one source each
675
-
676
- A pass over the module boundaries. Same behaviour except the `lead` fix at the end, which was a
677
- real bug: the parameter only worked on one of the three paths that used it.
678
-
679
- - **`handler.js` stopped preparing UI.** The floating window, the chat service and the "where do I
680
- type" note moved to `input-surface.js` (`createInputSurface()`). `handler` is a router again —
681
- three exits: quick action, one pass, start the loop. The `widgetNote` variable no longer travels
682
- from the top of the function to the bottom.
683
- - **`watch-run.js` has one return shape.** Eleven exits each used to build their own ten-field
684
- object; now they all call one `pass()` closure. Adding a field is one edit instead of eleven, and
685
- a branch can no longer quietly forget one.
686
- - **One segment length.** `watch-state.js` exported `WATCH_SEGMENT = 120` while `batches.js`
687
- declared `DEFAULT_SEGMENT = 300`; whichever fallback fired first decided how long a segment was.
688
- `batches.js` is now the only source, and `WATCH_SEGMENT` is gone.
689
- - **One lead.** The delivery lead was hardcoded in three places: `batches.from()` produced
690
- `sayAt = to - 15`, `watch-loop.js` passed `lead: 15` to `shouldSpeak`, and only `watch-run.js`
691
- actually read `args.lead`. Segments no longer carry `sayAt`; `shouldSpeak` computes `to - lead`,
692
- and `startWatchLoop` takes `lead` from the caller. `lead: 60` now really moves the trigger point
693
- (checked against a 300 s segment: at 241 s, `lead=15` stays quiet, `lead=60` fires).
694
-
695
- ### Removed — no more auto-launched browsers, no more browser widget
696
-
697
- Both were early paths from before the browser extension existed. Neither could produce a position
698
- for the tab the user is actually watching, so both are gone rather than kept as fallbacks.
699
-
700
- - **Auto-launching a browser**: `ensureWatchBrowser()` (`launchBrowser` + `waitForPort`), the
701
- `autoLaunch` flag on `runWatchPass`, the `attachOnly` parameter, and the `launchBrowser: true`
702
- branch in `~/.dsh/video.json`. The extension already reports `currentTime` every second from the
703
- page the user is on; opening a second Edge with its own profile never helped that page. When no
704
- position can be read the tool now asks "how far are you" instead of starting a program.
705
- - **The browser widget page**: `GET /widget`, `WIDGET_PAGE`, `openWidgetInBrowser()`, `widgetUrl()`,
706
- and the `documentPictureInPicture` button in the chat page. The input box is the native tkinter
707
- window (`examples/floating-chat/window.py`); the HTML page stays as a read-only fallback at `/`
708
- (`chatPageUrl()`), and is never opened automatically.
709
- - **Dead parameters**: `wakeOnLinesEmpty` (the handler never passed it, so its 30-line branch in
710
- `watch-loop.js` could never run), `title` (nothing in `src/` or in storyboard read it), and
711
- `segmentStart()` (every caller uses `plan.segmentAt()`). Parameter count 36 → 34.
712
-
713
- ### Fixed — interjections used to get swallowed (four different ways)
714
-
715
- The interjection path was the one place where losing user input was silent: nothing crashed, nothing
716
- logged, the words just never arrived. All four ways of losing them are now closed, and each one has
717
- a regression test (`test/cli-interrupt.test.mjs` — the CLI had **no** test coverage before this).
718
-
719
- - **Between two `cue` runs.** Every `cue` is a fresh process, and the watcher took "however many
720
- lines exist right now" as its baseline — so anything the user typed while the model was thinking,
721
- building a segment or replying was never read by anyone. The read position now lives in
722
- `<watch>/chat-cursor.json`: a `cue` starts from where the last one stopped, and delivers what it
723
- finds the moment it enters the wait. Baseline is persisted as soon as it is established, because a
724
- `cue` that hears nothing (the common case) otherwise leaves no cursor for the next one.
725
- - **Two messages arriving in the same poll.** Both watchers (chat box and host session file) marked
726
- the whole batch as read and reported only the first, so the second was gone. They now consume up
727
- to the message they hand over and no further — "reply first, then take the next one".
728
- - **Wrong conversation.** `findActiveSessionFile()` took the most recently modified session jsonl
729
- across *all* projects, so a chat in another window could interrupt the watch session. It now
730
- prefers the project matching the current directory and only falls back to global when that one has
731
- no active session.
732
- - **The host writing old messages late.** WorkBuddy flushes a user's message into the session file
733
- *after* the reply to it. The watcher saw new bytes and treated them as a fresh interjection —
734
- interrupting the current turn with the message that started it. Messages whose `timestamp`
735
- predates the watcher are now ignored.
736
-
737
- Also in this path: interjections heard via the host input box are appended to the chat stream too
738
- (they used to appear only in `cue`'s stdout, so the page showed a stream with a hole in it); the
739
- chat page puts the words back in the input box when a send fails instead of losing them; and
740
- `POST /api/say` answers `ok:false` for requests it did not write, which is what makes that recovery
741
- possible.
742
-
743
- ### Fixed — `cue` and `say`
744
-
745
- - `cue` no longer waits forever when the video changes underneath it. It compared against the
746
- segment delivery point of the *old* video, and if the new one was shorter, `deliverAt` was a
747
- position that would never be reached. It now detects a changed URL or duration and exits with
748
- `VIDEO-CHANGED` (pending lines are saved under the old source), and exits with `REWIND` when the
749
- user drags the progress bar back more than a minute — the model should hear about that instead of
750
- sitting on lines written for a position the user left.
751
- - Two `cue` processes can no longer run at once: a state file saying `blocking` with a **live** pid
752
- is refused with `BUSY` (exit 1). A dead pid is taken for what it is — the residue of a killed run —
753
- and does not block anything. `check` mode is read-only and never takes the lock.
754
- - `check` mode no longer leaves `cue-state.json` at `blocking`, which used to make the next run
755
- report "last wait was killed externally" for a run that was never waiting.
756
- - `say` called edge-tts once by hand and then again inside `speak()` (twice the synthesis, and the
757
- manual attempt passed the raw configured voice, so a SAPI-style name like `Huihui` never matched
758
- and silently fell back). It now calls `speak()` once, which does the mapping and the fallback.
759
- - `voices` was advertised in `help` and crashed with `cmdVoices is not defined` when called. It now
760
- lists the SAPI voices plus whether edge-tts is present and which voice is configured — the first
761
- place to look when "why am I still hearing the navigation lady" comes up.
762
-
763
- ### Added — talk instead of type: a microphone button in the floating window
764
-
765
- `examples/floating-chat/mic.py` is a separate process the window starts from its `麦` button. It
766
- listens, cuts what you say into utterances with the Silero VAD already sitting in `models-sherpa/`,
767
- transcribes each one, and writes it into the **same** `chat.jsonl` the typing path uses — so a
768
- running `cue` picks it up through the interjection cursor and the model answers without anyone
769
- typing a character. Measured end to end on this machine (i9-12900HX, int8 paraformer):
770
-
771
- - one model instance ≈ **284 MB** working set, loads in ~2 s
772
- - a 3 s utterance transcribes in **0.15 s**; a 45 s one in ~1.2–3.3 s (RTF ≈ 0.05, 20× realtime)
773
- - concurrent transcription barely queues: a 3 s short request takes 0.14 s even while a 45 s
774
- transcription is running
775
-
776
- **It runs its own model by default** (`--engine local`), which is the answer to "can ASR run twice":
777
- yes, and it is cheap. It also means the microphone never waits behind a video transcription. The
778
- existing service cannot offer that yet — see the note below. `--engine http` shares port 8000
779
- instead, saving 284 MB at the cost of queuing behind long audio.
780
-
781
- **It refuses to hear itself.** The agent speaks through speakers; the microphone hears it; without a
782
- guard that gets transcribed as if the user had said it, and the model answers its own line forever.
783
- Every utterance is checked against `quiet-until.json` (the same window `say` and `cue` already take
784
- before speaking) and dropped if the agent is talking.
785
-
786
- ### Added — acoustic echo cancellation, so the microphone hears you and not the computer
787
-
788
- `examples/floating-chat/aec.py`: the microphone picks up whatever the speakers are playing, which
789
- means the video's narration gets transcribed as if you had said it. Since neither `speexdsp` nor
790
- `webrtc-audio-processing` builds on this machine (no C compiler, no wheels), this is a frequency-domain
791
- adaptive filter (overlap-save FDAF, power-normalised NLMS) in numpy — one FFT per 32 ms frame.
792
-
793
- It captures the **loopback** channel (what the computer is playing, auto-detected as the
794
- speaker/loopback device, never "stereo mix" — that one can contain the microphone too) and subtracts
795
- the estimated echo from the microphone. On top of that, an utterance whose energy drops below
796
- `--echo-gate` (default 30 %) after cancellation is discarded outright: that is the hard guarantee
797
- that pure-echo segments are never transcribed, whatever the filter is doing.
798
-
799
- Two things that mattered more than the filter itself:
800
-
801
- - **Double-talk detection cannot compare against the echo estimate.** At startup the filter is zero,
802
- so the estimate is zero, so "mic > 2 × estimate" is always true, so the filter freezes and never
803
- converges (first version: 498 frames frozen, 0 dB). It now compares against the **reference**
804
- signal (Geigel-style), which does not depend on the filter's state.
805
- - **Measured on a synthetic but honest mixture** (real speech as the video, a different real speech
806
- segment as you, through a 150 ms-delayed reverberant echo path):
807
- ERLE **13.6 dB** during echo-only passage; the video's words in the transcript went from **25 % →
808
- 0 %**, and an 8 s passage with nothing but video audio produced **no transcription at all**.
809
-
810
- Tunables: `--dt-ratio` (1.4 — mic peak vs reference peak before the filter freezes), `--taps`
811
- (8192 ≈ 512 ms of reverb tail), `--echo-gate`, `--no-aec`, `--loopback`.
812
-
813
- Honest limits: it is a software AEC, not magic. The first second or two of your speech, right as the
814
- filter re-converges after you start talking, is where the damage shows (a few characters in the test
815
- above). Speaker loudness and room reverb both make it harder. **Headphones remove the problem
816
- entirely** — with headphones there is no echo to cancel, and everything above is unnecessary.
817
-
818
- ### Added — a browser extension, so you never open a special window again
819
-
820
- Position used to require a browser started with `--remote-debugging-port`, and Chromium 136+ refuses
821
- that flag on the default profile — so users had to keep a second, separate browser window open just
822
- for watching. That was the whole reason this package felt like it needed a "special browser".
823
-
824
- `extension/` is an MV3 extension that reads `<video>.currentTime` from the page you are actually
825
- watching and POSTs it to the plugin's own localhost server (`127.0.0.1:9377/api/position`). After a
826
- one-time install it works in **your normal browser**, with your bookmarks and your logins.
827
-
828
- - `src/position-bridge.js` — the receiving end: writes each report to
829
- `<cache>/position.json` (temp file + atomic rename) and treats anything older than 5 s as absent.
830
- It goes through a file rather than memory because the CLI is a **different process** and has to
831
- be able to read it too.
832
- - `POST /api/position` and `GET /api/position` on the existing chat server, with CORS and a
833
- Private-Network-Access opt-in (a page on https://bilibili.com talking to 127.0.0.1 needs both).
834
- - `readPositionOrNull()` now tries the extension report when CDP is not configured or returns
835
- nothing, so every existing call site gets the new channel for free.
836
- - `doctor` grew an `extension` row and now treats "either channel works" as ready instead of
837
- insisting on the debug port.
838
- - `docs/BRIDGE.zh.md` — step-by-step install guide written for someone who has never heard of a
839
- manifest file, including the eight failure modes people actually hit.
840
- - `node watch.mjs install-extension` (and `scripts/install-extension.cmd`) does everything that
841
- *can* be automated: copies the extension to `%LOCALAPPDATA%\\dsh-watch-together\\extension` so it
842
- survives moving the repo, puts that path on the clipboard, and opens `edge://extensions`.
843
- The last three clicks cannot be automated — Chrome 137 removed `--load-extension` from branded
844
- builds and extension installs are HMAC-protected, deliberately, because silent install is the
845
- malware channel. The guide says so plainly instead of pretending otherwise.
846
- - **The extension now says hello on load** (`POST /api/hello`, persisted as `extension.json`).
847
- Without it, "extension not installed" and "installed but no video playing" look identical from the
848
- outside — both are silence. `doctor` and `bridge` can now tell them apart.
849
- - `extension/welcome.html` opens on install/update: the three verification steps, plus what each
850
- popup state means. Install is the one moment the user has no idea what to expect.
851
- - `install-extension` no longer just prints and quits: it keeps the window open and **watches until
852
- the extension proves it is loaded** (`✓ 扩展装上了`), then until a real position arrives
853
- (`✅ 全部完成`). One double-click now covers install *and* verification, and the window cannot
854
- vanish mid-instruction because it is still polling.
855
- - `node watch.mjs install-extension --steps` re-prints just the three clicks without touching any
856
- file — for when the window scrolled past or was closed.
857
- - `install-extension` now waits for Enter when it has a TTY, so the instructions cannot vanish
858
- before being read (running it from an IDE "Run" button has no TTY, which is the common way this
859
- happened).
860
- - `ensureWatchBrowser(port, url)` now passes the film through: with `launchBrowser: true`, saying
861
- "陪我看这个 <link>" opens the dedicated window **at that link** instead of the Bilibili homepage.
862
- That is the zero-install path — no extension, no port config, at the cost of watching in that
863
- window. Both paths coexist; neither requires the other.
864
- - `node watch.mjs bridge` (and `scripts/bridge.cmd`) starts just the position receiver and says
865
- "✓ 收到上报" on the first report. Without it, a user who installs the extension and immediately
866
- looks at the popup sees "not connected" — because the server only runs during `watch_together`
867
- or `watch.mjs chat`, and concludes the install failed.
868
-
869
- ### Added — closing the remaining "no one is listening" dead ends
870
-
871
- - **Idle stop now wakes the model too.** Video-ended and video-changed already did; idle ("no movement
872
- for two segments") did not — and since the loop is stopped, nothing polls the chat box afterwards,
873
- so anything the user said next went nowhere. Now it wakes and says where it stopped.
874
- - **Waiting is polled, not slept through.** The 500 ms tick in the blocking wait now uses
875
- `sleepWithChat`, so a message is noticed within ~150 ms instead of up to 500 ms later.
876
- - **The tool description now tells the model what an interruption is:** a result carrying `chat` means
877
- "answer them first, then call again with the same arguments — the wait resumes, nothing is lost, and
878
- the image is already in the cache". Without this the model had no way to know.
879
- - **`doctor` distinguishes "nobody is receiving" from "extension not connected".** Both look like
880
- silence, and the old wording told the user to reinstall the extension — but if no server is running
881
- on 9377 the extension cannot report at all, and reinstalling would have changed nothing.
882
- - Stale SMTC-era wording removed from the strings the *model* reads (`input`/`cursor`/`title`
883
- descriptions, and the `browser:` line), which still talked about the OS media session.
884
-
885
- ### Added — you can interrupt almost any wait, and it picks up where it left off
886
-
887
- Every blocking wait in `watch_together` can now be interrupted by a message in the chat box, and in
888
- all cases the answer is "reply to them, then call again with the same arguments" — the tool resumes:
889
-
890
- - **Building a segment** (8–10 s, longer with ASR) and **filling the lookahead buffer** (up to 4
891
- segments serially, 30 s+) — the most pointless kind of waiting, now interruptible.
892
- - **Waiting for the video to appear** (`waitForVideo`, up to 2 min).
893
- - **Waiting for a condition** (`waitUntil`) and **waiting for the next line** (`nextLine`).
894
- - Waiting to the delivery point and `cue` already listened; they now share one watcher (below).
895
-
896
- The interrupted work is **not cancelled**: the storyboard keeps building in the background and lands
897
- in the cache, so the follow-up call returns it immediately instead of rebuilding it.
898
-
899
- New `src/interrupt.js`:
900
- - `raceChat(promise)` — polls the chat while a slow promise runs; returns `interrupted` with the
901
- message, or `done`. Wakes on whichever happens first (the promise settling, or the next poll tick).
902
- The first version slept a fixed 500 ms per tick, which added half a second to *every* build —
903
- enough that playback passed the delivery point and the blocking wait returned instantly.
904
- - `sleepWithChat(ms)` — sleep that can be cut short by a message.
905
- - `chatWatcherShared()` — **one watcher for the whole process.** `makeChatWatcher()` baselines at
906
- creation time, so a fresh one per wait silently dropped anything the user said while the model was
907
- thinking, in the gap between two waits.
908
-
909
- ### Added — it now reacts to what you do mid-video
910
-
911
- Auditing the whole flow against the user's checklist surfaced three gaps where the plugin behaved
912
- correctly but **never told the model**, leaving it silent until the user poked it:
913
-
914
- - **Video ended / video changed now wake the model once.** Previously they only stopped the loop, so
915
- the model sat blocked on the previous segment with no idea the film was over or had been replaced.
916
- - **Large seeks (>60 s, forward or backward) wake the model once** with where the user jumped to and
917
- from, with a 3-minute cooldown. Position tracking was already correct — it was the model that had
918
- no idea. Rewatching does not re-speak already-spoken segments (no immediate-repeat chatter).
919
- - **Only the visible tab reports** (`document.visibilityState`), plus a report on `visibilitychange`.
920
- Every tab with a `<video>` reports once per second; with two such tabs open the server received
921
- alternating positions and the plugin interpreted it as the user scrubbing wildly.
922
- - The simulator can now jump the playhead (`seeks: [{at, to}]`), and there are four new scenario
923
- tests covering: video changed wakes once, video ended wakes once, seek forward wakes once, rewatch
924
- wakes once and does not re-speak.
925
-
926
- Note the jump check must run **before** the anchor is refreshed — comparing the new reading against
927
- the already-updated anchor measures zero. That was the first (failed) version.
928
-
929
- ### Fixed
930
-
931
- - **`bin/watch.mjs chat` ran its own copy of the chat server** — an inline `http.createServer` plus
932
- duplicated copies of both HTML templates (92 lines). The copies had drifted: it served `/`,
933
- `/widget`, `/api/messages`, `/api/say` but **not `/api/position` or `/api/hello`**. So running
934
- only `watch.mjs chat` (instead of `bridge`) meant extension reports hit 404 and the CLI path could
935
- never read a position. It also never called `attachSpeechToChat()`, so that chat box showed user
936
- messages but no script lines. It now uses `startChatServer()` + `attachSpeechToChat()` like the
937
- plugin and `bridge` do, and the duplicated templates are deleted.
938
- - **`watch.mjs reply` wrote straight to the stream** with `appendChat('assistant', …)`, so the text
939
- appeared in the chat box but was never handed to speech subscribers — a TTS adapter stayed silent
940
- while the page showed the words. It now uses `appendAssistantSay()`, which writes the stream *and*
941
- emits the speech event, matching what `watch_together({say})` does.
942
-
943
- ### Fixed
944
-
945
- - **The plugin passed the browser's debug port to `ensureChatSession()`**, so the chat server tried
946
- to bind 9333 — the port the browser is already using. The bind failed, the error was swallowed,
947
- and the chat box silently never came up in DSH. It now uses the chat port (9377) as intended.
948
- This also mattered for the extension: that server is where reports land.
949
-
950
- ### Removed — the OS media session (SMTC) backend is gone
951
-
952
- Position used to have two sources: the browser's DevTools port, and Windows' system media controls
953
- (read by a bundled `watch_smtc.py`). **SMTC is deleted**, along with everything that only existed
954
- because of it:
955
-
956
- - `src/watch-probe.js` (121 lines) and `src/watch_smtc.py` (62 lines)
957
- - `src/resolve-playing.js` (153 lines) — it reversed a *title* into a source by searching filenames
958
- and then Bilibili. With CDP the page URL is the source, so this whole "guess the film" path is
959
- gone (it was also the thing most likely to pick the wrong video)
960
- - the `winrt` Python dependency (three packages) and the interpreter search
961
- - most of the extrapolation policy in `position.js`: the cap drops 180 s → 60 s, `FRESH_MS`
962
- becomes 5 s, and the safety margin now only applies after a *missed* read
963
- - `pickSession` / `probePlayback` / `describeStatus` and the `probe` injection point
964
-
965
- Rationale: SMTC's `Position` only refreshes on player events (measured gaps of 143 s and 216 s), so
966
- treating it as a live position required extrapolating, and extrapolating over a wrong pause means
967
- every later segment is built on a wrong cursor. The benefit — "watch in whatever player you like" —
968
- did not survive contact with how it actually behaved.
969
-
970
- What you give up: you now watch inside the dedicated browser window
971
- (`scripts/start-edge-debug.cmd`). Chromium 136+ refuses to open a DevTools port on the default
972
- profile, so that window necessarily has its own profile and needs a one-time login.
973
-
974
- ### Fixed
975
-
976
- - **`loop.built` / `loop.dur` / `loop.sourceUrl` leaked across films.** Starting a second watch
977
- session reused the previous film's duration, so the first read of the new film looked like a
978
- "video changed" event and stopped the loop immediately; `built` made prefetch skip segments it had
979
- built for the old film. Both are now reset when the source changes.
980
- - **`startWatchLoop` used `Date.now()` for the anchor while pricing time off its injected clock**,
981
- which made every simulated read look minutes old. It now uses the injected clock.
982
- - **The CLI's `pos()` never read SMTC at all**, so the CLI was browser-only even while the plugin
983
- had a fallback. Moot now that SMTC is gone, but it is why the tool seemed to demand a special
984
- browser.
985
-
986
- ### Removed — dead code trimmed so there is one decision path
987
-
988
- Two functions that duplicated live logic and were never called in production are gone:
989
-
990
- - `dueDecision` (in `src/timer.js`) — a pure "should I speak now" decision that shadowed
991
- `position.shouldSpeak`. Nothing in the loop ever called it; only a test exercised the abandoned
992
- design. The "pause too long → stop" intent it carried is now not implemented (see note below).
993
- - `depthForBuffer` (in `src/batches.js`) — a count-based lookahead that duplicated `windowFor`,
994
- which the loop actually uses (position-based, so the invariant holds at every position, not just
995
- at segment starts). Its tests were redundant guards of that same invariant.
996
-
997
- Net: 13 tests removed (8 for `dueDecision`, 5 for `depthForBuffer`); `windowFor`'s existing tests
998
- already cover "lookahead ≥ N seconds at every position", so no coverage was lost.
999
-
1000
- ### Changed — idle auto-stop now also covers a paused-and-abandoned video
1001
-
1002
- The loop used to only stop itself on "no movement" when the last reading was a *playing* sample
1003
- (`why === 'recent-refresh'`). A paused video reports a frozen position forever — `estimate` returns
1004
- `why: 'paused'`, never stale — so pausing and walking away left the loop polling indefinitely. The
1005
- idle check now also fires on a frozen *paused* position, after the same `2 × segment` grace period,
1006
- and wakes you with "停了一会儿" so you can resume by calling `watch_together` again.
1007
-
1008
- ### Fixed — voice adapter no longer hard-codes a voice
1009
-
1010
- `examples/voice-edge-tts/index.mjs` used to fall back to `zh-CN-XiaoxuanNeural` when
1011
- `~/.dsh/tts.json` had no `voice`. That baked one person's voice into the example, so shipping it
1012
- would have dragged that choice into everyone's install. It now falls back to the neutral
1013
- `zh-CN-YunxiNeural` and prints a one-line hint telling you to set `voice` in `~/.dsh/tts.json`
1014
- (e.g. `"voice": "zh-CN-XiaoxuanNeural"`). Nothing about the voice ships in the package — you mount
1015
- the adapter via `~/.dsh/voice.json` (or `DSH_VOICE_ADAPTER`) and pick the voice yourself.
1016
-
1017
- ## Earlier — 0.1.0 draft, never published (2026-10-30)
1018
-
1019
- The first cut as a standalone plugin. It was not published under this number; the version line now
1020
- starts at 0.0.7, so this section is kept purely as a record of how the feature set got here. The feature existed inside `dsh-video-storyboard` 0.4.x as
1021
- `src/watch/`; it is now its own package with its own entry point, its own version, and a one-way
1022
- dependency on `dsh-video-storyboard`.
1023
-
1024
- ### Added
1025
-
1026
- - **`watch_together`** — watch a video together with a text-only agent. Instead of one whole-film
1027
- storyboard, it follows the user's **real playback position** and hands over one segment at a time,
1028
- `lead` seconds before the segment ends. The next segment is built while the user is still watching
1029
- the current one, so delivery is perceived as instant (4/4 measured deliveries at 0.0 s).
1030
- - **Ramp-up start.** Segment lengths grow `[60, 120, 180, 240]` → `segment`, so the first line lands
1031
- around 45 s instead of after a full 5-minute batch. `ramp: []` disables the ladder.
1032
- - **Double buffering.** `depth: 2` keeps the current batch plus the next one built, and starts the
1033
- one after that while the user watches.
1034
- - **Playback position straight from the page.** It reads `<video>.currentTime` over the DevTools
1035
- protocol, so the value is exact, and the page URL becomes the source (`file:///D:/x.mp4` → local
1036
- path) — no searching, no downloading, no asking. Never released with the OS media session (SMTC)
1037
- backend documented below: SMTC's `Position` only refreshes on events, so using it as a live
1038
- position meant extrapolating, and a wrong position poisons every later segment.
1039
- - **Honest confidence levels.** The plugin reads every 15 s and extrapolates in between, which is
1040
- normal and self-correcting. What it refuses to do is keep extrapolating after it has *missed* a
1041
- read: past 20 s it demands an extra 5 s of margin before speaking, and past 60 s it stops
1042
- guessing and asks for `cursor` instead.
1043
- - **The speech seam, with no engine.** `src/speech-bus.js` exposes `onSpeech(handler, { voice })`,
1044
- `emitSpeech()`, `speechEvents()` and `lastSpeech()`. The plugin ships no engine, no default
1045
- adapter and no voice parameters; `watch_together` results carry `speech: [{ at, text, state }]`
1046
- and the loop emits `state: 'due'` when a line is actually due.
1047
- - **Adapters loaded by path.** `~/.dsh/voice.json` `{ "adapter": "<path or module>" }` (or
1048
- `DSH_VOICE_ADAPTER`) is `import()`ed once at startup; the module exports `attach(api)` and returns
1049
- a detach. Nothing is bundled, and a failure only logs a warning.
1050
- - **`examples/voice-edge-tts/`** — a working adapter (edge-tts → `ffplay` → system-voice fallback).
1051
- It prints `[voice 03:11.4] <line>` to stderr for every line that comes due; that log, not the
1052
- audio, is what you want when checking *when* text fires.
1053
- - **One text stream for the chat box.** `chat.jsonl` carries `line` (scripted), `assistant`
1054
- (interjection) and `user`, with `say: true` marking the speakable ones.
1055
- `watch_together({ say: "…" })` is how the model gets its interjection in — the plugin cannot read a
1056
- normal reply. `attachSpeechToChat()` subscribes with `voice: false`, so a display-only consumer can
1057
- never silence the loop.
1058
- - **A localhost chat page** (`/` full view, `/widget` capsule) with an `/api/messages` long-poll and
1059
- an `/api/say` callback. This is the only channel that actually reaches a blocked `watch_together`
1060
- call — messages typed into the host's own input box are appended to the session log *after* the
1061
- blocking call returns (measured: 42 s of polling, 0 bytes written).
1062
- - **`examples/floating-chat/window.py`** — a real floating window without a browser: frameless,
1063
- always-on-top, translucent, stdlib tkinter only. Reads the same `chat.jsonl`.
1064
- - **`bin/watch.mjs`** — a CLI shell for sessions that have no `watch_together` tool. It imports the
1065
- same `src/`, so behaviour cannot drift from the plugin.
1066
-
1067
- ### Fixed
1068
-
1069
- - **The CLI imported pre-refactor paths** (`src/browser-time.js`, `src/pipeline.js`, …) that no
1070
- longer exist, so `bin/watch.mjs` could not even start. All imports now resolve through the
1071
- `dsh-video-storyboard` package name.
1072
-
1073
- ### Changed
1074
-
1075
- - `detachAdapters()` no longer reaches into the bus's private subscriber map; it calls
1076
- `__resetSpeech()` from `speech-bus.js`.
1077
- - `watch-run.js` imported `./watch.js` twice; merged into one import.
1078
-
1079
- ### Known limits
1080
-
1081
- - **Speaker separation is not attempted.** Measured on the reference machine: per-sentence cam++
1082
- embeddings split single-speaker material into 6 speakers; demucs pre-separation made no difference
1083
- (median similarity 0.62 → 0.61); FunASR's `ClusterBackend` returns "one speaker" outright below 20
1084
- speech segments — short clips are outside its operating range by design.
1085
- - **Interjection audio can collide with a line already being spoken.** Windows mixes both SAPI
1086
- instances, so `say` occupies `quiet-until.json` before speaking and `cue` skips lines inside that
1087
- window (it skips rather than defers — deferring desynchronises from the picture). The remaining
1088
- gap is the 3–8 s while a line is mid-speech, which cannot be cut short.
1089
- - **CRLF-less assumption.** The chat page replaces `__PORT__` in the templates per start; changing
1090
- the port while a browser tab is already open requires a reload.
1
+ # Changelog
2
+
3
+ All notable changes to **dsh-watch-together** are documented here.
4
+ This package starts its own version line at `0.0.7` — it is not a continuation of `dsh-video-storyboard`.
5
+
6
+ ## [0.2.1] - 2026-11-01
7
+
8
+ 两项都是从社区审计(#18 / #16)来的,各配了回归用例。
9
+
10
+ ### Added — 插件设置页(合 PR #11, closes #10)
11
+
12
+ 设置直接渲染在 DSH 插件详情页(`plugins.bundle.config`),不再用 iframe / 内嵌滚动窗口;
13
+ 「设置 → 内置插件」的 tab 也还在。
14
+
15
+ - 表单:`browserPort`(共享 `video.json`)、`chatPort`(`watch.json`)、语音适配器(`voice.json`)。
16
+ - **依赖自检**:ffmpeg/ffprobe、Python、`dsh-video-storyboard`、浏览器扩展、悬浮窗脚本;
17
+ 缺什么就直接给官方下载入口,已装的显示「已安装」。插件**不会**静默安装或替你执行下载。
18
+ - 修核心包误报:`dsh-video-storyboard/package.json` 不在 `exports` 里,改成解析 `dist` 信息。
19
+
20
+ ### Changed — 悬浮窗换成实时捕获管线,模块拆成接口(合 PR #20)
21
+
22
+ - **窗口实现换代**:`examples/floating-chat/window.py` 以 PR #15 的实时捕获管线为底稿重写
23
+ (1454 行,原 3372 行)。每帧抓屏 → 1/4 尺度模糊 → SDF 边缘折射 → 透镜采样 → 合成,
24
+ 静帧时整条管线跳过。**依赖变化**:`mss` 和 `numpy` 从可选变必需,缺了窗口起不来。
25
+ - **保留并补齐交互**:双击标题改名、▾ 折叠/展开、系统行(meta)、发送回写、位置保存、
26
+ 麦克风图标、滑入动画。输入框仍是"画布上画字 + 2×2 的 Entry 只收 IME/键盘"。
27
+ - **模块解耦**:`src/interfaces.js` 组合识别 / TTS / 悬浮窗三个接口,`handler.js` 与
28
+ `watch-loop.js` 只调接口、不再直接 import 实现(`docs/INTERFACES.zh.md`)。
29
+ - **窗口线协议**:插件写 `window-events.jsonl`、窗口写 `window-outbox.jsonl`,
30
+ Python 侧 `window_protocol.py` 只共享线格式;旧版只写 `chat.jsonl` 时窗口继续兼容。
31
+
32
+ ### Fixed — 无音轨视频不再卡在"缺台词"门槛(fixes #18)
33
+
34
+ `noListen` 之前只改了文案,**没有参与 `hasLines`** —— 无可等台词时 `segLines` 为空,
35
+ `hasLines` 恒为 false,于是 `spoken` / `lastDelivered` 都不写,每次调用都落回同一段、
36
+ 永远带 `[DELIVERY INCOMPLETE]`。这不是"模型不肯写台词",是状态机不推进。
37
+
38
+ - `noLinesNeeded = Boolean(noListen)` 参与 `hasLines`:没音轨 / 没配 ASR / 连不上 / 这段真静音时,
39
+ 画面这一半就算交付完成。
40
+ - 没有台词可等时**不再提示"先取字幕"**(取了也不会有),也不说"本段台词已就绪"。
41
+ - `[听音]` 段补一句"这一段也没有台词可等,用你看见的画面说一句即可,别编对白"。
42
+ - **普通视频的台词门槛保持原样**:有声有字幕但没写台词,仍然 `complete=false`。
43
+
44
+ ### Fixed — 叫醒失败不再刷屏,确定性失败不再空等(fixes #16)
45
+
46
+ `no-session-controller`(当前进程没有 DSH 会话控制器)和 `no-session-id` 是**确定性**失败,
47
+ 以前每次都要等 800ms 再重试,并且每次都往 `chat.jsonl` 写一条 `[一起看] 叫醒失败`;
48
+ 持续故障时悬浮窗会被几十条一样的 meta 刷满。
49
+
50
+ - 这两类失败**不重试**;其他偶发失败仍重试一次。
51
+ - 失败提示按 `(sessionId, reason)` 节流:**60 秒内只显示第一条**,静默期里折叠掉的次数
52
+ 在下一次显示时带上("同类失败另有 19 次已折叠")。
53
+ - `no-session-controller` 的提示补一句可行动的说明(从 DSH 里启动,或先关掉陪看循环)。
54
+
55
+ ## [0.2.0] - 2026-11-01
56
+
57
+ 这一版把悬浮窗的玻璃重做了。三块独立玻璃、底色真正跟着背景走、静帧不空转、
58
+ 边缘不再是"放大贴纸"而是把框外画面折进来;同时把「听不到声音」这件事从
59
+ "模型答不上来"变成"能直接说清原因"。
60
+
61
+ ### 听不到声音,不再只有一个答案
62
+
63
+ 用户反馈(2026-11-01,B 站评论区):「能看视频,但是听不了」「没有音轨」。
64
+ 文档里写清楚了要装 ASR,但**运行时没有任何地方告诉用户这件事** —— 模型只能回一句"我听不到",
65
+ 用户于是以为插件坏了(同一个问题在评论区被问了十几遍)。
66
+
67
+ - `explainCuesFailure()`:把每种原因翻成**一句能直接说给用户听的话**(没配 ASR / 装了连不上 /
68
+ 这份副本没音轨 / 听了但没说话 / 字幕要登录)。`transcriptOnly` 的返回和陪看交付共用这一份文案,
69
+ 不再各写一遍。
70
+ - `asrCues` **不再把"没配 key"和"服务连不上"糊成 `asr-empty`**(那是"这片子没人说话",
71
+ 一个会误导人的结论)。没配 key 时连请求都不发 —— 以前会照发,401 被吞掉。
72
+ - 陪看交付新增 `[听音]` 段(同一部片子只详说一次,之后一句短的):用户问"你怎么听不到声音"时,
73
+ 模型手里终于有依据。**没句子时门槛改成"用画面说一句、别编对白"**,而不是硬逼出一段台词。
74
+ - 修 `findCachedMedia`:拿不到 BV 号时原来会 `return video` —— 返回媒体目录里碰到的**第一个**
75
+ `video.mp4`,于是拿**另一部片子**的音轨去转写。台词全错,而且一句都不报。
76
+
77
+ ### 玻璃底色跟着背景走
78
+
79
+ 用户原话:「太卡顿,而且刷新很慢……经常是背景换了,液态玻璃还没动,还没变颜色。」
80
+
81
+ 根因不在渲染算法,在**缓存永不过期**:整屏截图只在开窗那一刻做一次(`_stage` 的注释还写着
82
+ "之后无论拖到哪儿都是裁一刀"),所以对面视频换场景、桌面换壁纸,这块玻璃永远是开窗时的颜色。
83
+ 拖动结束后那个"8 秒才值得重截"的判定也救不了**静止**的窗口 —— 而陪看时窗口恰恰是静止的。
84
+
85
+ 现在:
86
+
87
+ - **按 TTL 定时重截**(`DSH_WATCH_GLASS_TTL`,默认 **600ms**,0 = 关掉回到旧行为)。
88
+ - **截屏在子线程**(抓屏 + 1/4 缩放 + 模糊 + 色散 + 提饱和),主线程只做裁片 + 贴图(1~2ms)。
89
+ Tk 对象一个都不在子线程碰 —— 屏幕尺寸、缩放系数都在主线程读好再传。
90
+ - **优先用 `mss` 抓屏**(可选依赖,见 `examples/floating-chat/requirements-glass.txt`):
91
+ 整屏 38ms vs ImageGrab 71ms,全管线从 ~200ms 降到 ~98ms,所以 TTL 才敢压到 600ms。
92
+ 没装就自动退回 ImageGrab。
93
+ - **新增 `_repaint_glass()`:只换玻璃不动内容**。`_paint()` 末尾会 `_reflow()` 重排所有气泡,
94
+ 为了换一层底色付这个代价不值得;现在只 `delete("panel")` 再贴一张。
95
+ - `_glass_busy` 防重入:上一发没回来就跳过这一拍;窗口隐藏/折叠时根本不截。
96
+
97
+ 实测(本机 2560×1600 / 150% 缩放,TTL=500ms):3 秒内 6 次截屏,底板时间戳推进 3.3 秒,稳定。
98
+ 抓屏基准:mss 38.3ms / ImageGrab 71.0ms;mss 全管线(抓 + 1/4 缩 + 模糊)98.6ms。
99
+
100
+ **依赖**:Pillow + 可选 `mss`(**0.1MB**、纯 Python 无编译)。numpy 不需要。
101
+
102
+ **踩到的坑**:第一版把 `_glass_ttl_start()` 插进了 `poll()` 末尾(那个方法每 200ms 自己再排一次),
103
+ 于是每拍都重启一条定时链 —— 实测 3.2 秒触发 16 次、截屏频率飙到 9Hz。加了 `_glass_started` 锁。
104
+
105
+ ### 液态玻璃重做(本轮)
106
+
107
+ 三块**分离**的玻璃(标题栏 / 主体 / 输入栏,中间 10px 真缝,缝里透出桌面),
108
+ 滚动条移到主体右侧外面,不占消息区。
109
+
110
+ - **`WDA_EXCLUDEFROMCAPTURE`**:让窗口从屏幕捕获里消失,于是抓"自己背后"时
111
+ **不用把 `-alpha` 设 0 再恢复** —— 那个来回会逼 DWM 把整个桌面重排两次,
112
+ 视频在播时最贵,肉眼就是"松手闪一下"。`DSH_GLASS_WDA=0` 可关(录屏要用)。
113
+ - **静帧跳帧**:用未模糊的原图缩到 48×30 比灰度差,`mean>0.8` 才算动了;
114
+ 没动且运动已停 0.3 秒就直接复用上一帧,整条管线(抓屏 17ms + 糊 + 色散)全跳过。
115
+ 慢速滚动不会先停一两帧 —— 阈值比"定时到点就重算"灵敏。
116
+ - **边缘折射换成 SDF 法线向外采样**:老做法是"整图放大一点、再按边缘权重把放大版盖回",
117
+ 边缘看到的是**自己被放大的内容**,像贴了层凸透镜贴纸。现在沿圆角矩形 signed distance
118
+ field 的梯度法线**向外**取样本,边上一窄条里塞的是**框外**的画面,被压扁折进来。
119
+ - **底板 1/8 → 1/4**:1/8 放大 8 倍时边缘和背景细节都发虚。
120
+ - **文字可读性**:新增 `text_on_glass()`(整段文字 + 右下 1px 深色影子)和
121
+ `on_glass_fill()`(按那个点的背景亮度决定用浅字还是深字)。影子用在气泡正文、
122
+ 标题栏名字、系统行、输入槽;翻色用在标题栏名字。
123
+ **没有逐字建 item** —— 玻璃上几十像素内明暗本来就不变,整段取一次样就够,
124
+ 长列表滚动时 item 数不翻倍。
125
+
126
+ **依赖**:Pillow + 可选 `mss`;**numpy 也是可选**(只给 SDF 折射用,没装自动退回老折射)。
127
+
128
+ ### 参考并移植了上游的 PR
129
+
130
+ - **#13 `feat/liquid-glass-speed`**:O(n²) → O(n) 的追加优化(只 layout 新气泡、resize debounce 70ms、
131
+ Configure 合并到 16ms、after_idle 批量、mtime 缓存、玻璃尺寸没变不重画、拖动只画边框)。
132
+ 它的数据是 210 条消息从 14.22s 降到 605ms(23×)。**这次没合**:那个 PR 基于 1314 行的旧
133
+ `window.py`,我们这边已经 2632 行(液态玻璃二版 + 本轮改动),冲突面太大;但思路(尤其
134
+ "玻璃尺寸没变不重画")以后可以逐条移植。
135
+ - **#15 `feat/live-glass-window`**:独立一套 `glass_window.py` / `glass_window_gpu.py`。
136
+ **没有整包拿过来**(它是第二套 UI,切过去会丢掉气泡、meta、入场动画、折叠、改名这些交互),
137
+ 而是逐项移植了它的机制:`WDA_EXCLUDEFROMCAPTURE`、静帧跳帧、SDF 法线折射、1/4 底板、
138
+ 文字影子与按背景翻色。GPU 合成(moderngl)没有采用 —— 需要额外依赖且仅限 Windows/OpenGL 3.3+。
139
+
140
+ ## [0.1.1] - 2026-11-01
141
+ **依赖升到 `dsh-video-storyboard@^0.6.0`。** 分镜从"固定宫格"改成"档位排布"——
142
+ 一格 = 一个镜头、格子大小跟切点密度走,`boardOptions()` 返回的参数从
143
+ `cells / sheets / minGap` 换成 `maxFrames / maxSheets / minFrames`。旧的参数名在 0.6.0 里已经不存在,
144
+ 所以这一版**必须**配 0.6.0 及以上,不能和 0.5.x 混装。
145
+
146
+ ### 台词写完之后不再递整段清单(防剧透)
147
+
148
+ 用户反馈"老是剧透后面的"。根因不是提示词不够狠:写台词时必须把整段 5 分钟的清单交出去,
149
+ 写完它仍然留在上下文里,模型就会把它当成"我知道后面"的凭据 —— 光说"不许提"压不住真实内容。
150
+ 现在台词一就绪就换成一句简报("台词已就绪,清单不再提供"),模型手里真的没有后面的信息。
151
+
152
+ 顺带在提示词里加了一句自问:「这句话是不是只有已经看过 xx 秒之后的人才写得出来?」
153
+ 不确定的事用"现在"而不是"接下来"。
154
+
155
+ ### Liquid glass, second pass — the window was still ugly (2026-11-01, later)
156
+
157
+ Verbatim feedback: "看一下 watch-together 的悬浮窗设计,太丑了现在" — the first liquid-glass pass
158
+ had the vocabulary right and the physics wrong. Five defects, all of them visible in a screenshot:
159
+
160
+ **The corners were not round.** `round_rect` and `squircle_mask` both used a superellipse with
161
+ `n = 5`, and at `n = 5` the curve is within 0.6% of the straight edge until the last few pixels —
162
+ a 22px radius rendered as a near-square corner with a tiny fillet. `squircle_mask` had a second,
163
+ independent bug: the row-solve was inverted (`x` grew from 0 instead of `r`), which cut the corners
164
+ out as *squares*. Both now use `n ≈ 2.2` and solve each row's span directly (O(h) instead of O(w·h),
165
+ and it buys 2× supersampling for free).
166
+
167
+ **The chrome was opaque.** The header was a `tk.Frame` and the composer a second one; Tk widgets
168
+ must have an opaque background, so the top and bottom strips of a "glass" window were dead black.
169
+ Both are now drawn on the canvas (status dot, title, count, `▾`/`✕` as hit-tested canvas items,
170
+ the input well as a rounded polygon). Only the `Entry` stays a real widget — it has to be opaque, so
171
+ it lives inside a deliberate *inset* well.
172
+
173
+ **Bubbles were paper.** Each one was filled with a flat `#3a4459`. They are now cut from the same
174
+ blurred backdrop as the panel (`plate()`), with only a white/blue wash on top — they transmit what
175
+ is behind them.
176
+
177
+ **Tint was global and blue.** One tint for the whole window, and a blue-grey `#171a21`, which fights
178
+ every colourful frame it sits on. Tint is now per-plate and *neutral*: measure that plate's mean
179
+ luminance and solve for "how opaque does the ink need to be to land under 84" (`a = (L-84)/(L-12)`).
180
+ Over a white page it darkens itself; over a dark scene it stays transparent.
181
+
182
+ **The sheen was made of lines.** Diagonals stacked with a 3px step left a visible weave across the
183
+ panel. Every gradient is now computed on a 16×16 canvas and upscaled bicubically.
184
+
185
+ Also added: **dispersion** (warm outside, cool inside, full strength around the whole chamfer and
186
+ stronger at the four corners, because a fillet has curvature everywhere but compound curvature at
187
+ the corners), **edge fading** in the message list (rows fade in/out across a 30px band instead of
188
+ popping at the clip boundary — suppressed on the side that has no more content, otherwise the newest
189
+ message is permanently the faintest), a **200ms entrance** per new bubble (8 frames: 10px rise +
190
+ alpha ramp + text colour lerp), and **smooth scrolling** (5 frames × 16ms) so the fade band has
191
+ something to fade across. The scrollbar moved out into the margin beside the panel.
192
+
193
+ Two long-standing bugs fell out of this: `Meta.paint` ended with a leftover `self.cv.tag_lower("bg")`
194
+ from the pre-canvas version — `Meta` has no `cv`, so the exception aborted `_reflow` mid-list and only
195
+ the newest message was ever visible; and the backdrop image was created after the messages without
196
+ `tag_lower`, so any repaint buried them.
197
+
198
+ ### Performance — the glass was re-baked on every frame (2026-11-01, same session)
199
+
200
+ "背景的模糊还是很卡" — measured, not guessed. One panel plate cost **520ms**, a slab 90ms,
201
+ a bubble 28ms. The culprit was `_ring`: it built **two full-size fill masks and subtracted them**,
202
+ and every plate needs five or six rings (rim, soft rim, bottom shade, warm, cool, edge weight), so
203
+ a 665×594 panel spent ~100ms in that one function plus ~15ms per `squircle_mask`.
204
+
205
+ Three fixes, in order of payoff:
206
+
207
+ - **Ring solved per row, no intermediate images.** A ring's row is just two short segments — left
208
+ and right — so the inner and outer x are solved directly (`_ring`), and middle rows are skipped
209
+ entirely. O(h) instead of O(w·h), and no subtraction allocations. 100ms → 3.7ms.
210
+ - **Everything smooth is computed at ¼ scale.** `_corner_weight`, `_edge_weight` and `refract`'s
211
+ bevel weight are soft blobs, not features: build them at 665/4 and upscale bilinearly. Gaussian
212
+ blur cost drops 16×, and the bevel mask (14 rectangle outlines over the full image) went from
213
+ ~20ms to ~1ms.
214
+ - **Supersampled masks now downsample with `Image.BOX`** instead of LANCZOS. For an exact 2×
215
+ reduction BOX *is* the 2×2 average — same result, ~4× faster. `squircle_mask` 15ms → 4.9ms.
216
+
217
+ Result: panel 520 → **50ms**, slab 90 → **6.8ms**, bubble 28 → **8ms**; `_paint` with a warm cache
218
+ **1.3ms**, `_reflow` **0.5ms**, cold repaint (backdrop changed) **76ms**, window open **387ms**.
219
+
220
+ Also: the R/B channel-scaled displacement (`chroma_edge`) is now **off by default**
221
+ (`DSH_WATCH_CHROMA_EDGE=1` turns it back on). It cost two full-size channel resizes per plate
222
+ (+18ms) and was invisible — the backdrop is already blurred and inked, so there is no contrast left
223
+ at the rim to disperse. The visible dispersion is the warm-outside/cool-inside tint pair, which stays.
224
+
225
+ Finally, resizing no longer re-bakes: while the resize grip is held the panel is a bilinear scale of
226
+ the last baked plate (1.2ms instead of 50ms), and a precise re-bake happens 300ms after release.
227
+
228
+ ### Performance, second pass — the backdrop was recomputed on every mouse release (2026-11-01)
229
+
230
+ "超级卡,绝对不止一两百毫秒" … "拖动根本不会刷新" … "碰到屏幕边缘松手百分百闪一下".
231
+
232
+ Measured, the picture was different from the first pass: `_paint` was already fast (1.3ms warm),
233
+ but **every time a drag or resize settled**, `_refresh_backdrop` cost **165ms** — and during the drag
234
+ the backdrop never updated at all, because refresh was debounced to 420ms after release.
235
+
236
+ What was actually slow, in order of payoff:
237
+
238
+ - **`_ring` built two full-size fill masks and subtracted them**, and every plate needs five or six
239
+ rings. Rewritten to solve each row's inner and outer x directly and draw two short segments —
240
+ O(h), no intermediate allocations. 100ms → 3.7ms per plate. (While rewriting it I dropped the
241
+ `width` argument on the floor: the band came out as "from the edge to `inset`", which made a
242
+ 1px highlight vanish entirely and pushed the inner shade line onto the rim, darkening it. The
243
+ tell was "the glass has no edge and looks grey". Fixed by solving both boundaries properly.)
244
+ - **Everything smooth is now built at ¼ scale and upscaled**: curvature weight, dispersion weight,
245
+ and the bevel weight in `refract`. They are blobs, not detail. Gaussian cost drops 16×.
246
+ - **The "light" layers are pure geometry** — sheen, rim, inner shade, warm/cool fringes do not
247
+ depend on the backdrop at all. They are composed once per size into `_light_overlay` and cached;
248
+ a re-bake now pays one `alpha_composite` instead of six.
249
+ - Tint and wash are both flat colours over flat colours, so they are blended into a single colour
250
+ and applied once. Mean luminance is measured on a 48×48 copy (the mean does not care about
251
+ resolution). 2× supersampled masks downsample with `Image.BOX` instead of LANCZOS.
252
+ - **The stage is now one full-screen capture at ¼ resolution**, taken at open while the window is
253
+ still withdrawn. Any later position is a *crop*, never a re-grab — the old "window + margin"
254
+ stage ran out of bounds whenever the widget was near a screen edge, and falling out of bounds
255
+ is exactly the "release → hitch → flash" the user was seeing.
256
+ - **Dragging refreshes live**: `_live_backdrop()` crops from the stage and `_paint_glass_only()`
257
+ swaps only the panel and the two slabs — the header, bubbles and composer do not move relative
258
+ to the window and are not redrawn. Throttled to 30ms (the mouse is 120Hz). Two hidden costs fell
259
+ out of this: `_window_rect()` calls `update_idletasks()`, which silently ran a *full* repaint on
260
+ every frame (+17ms), and position-only `<Configure>` events repainted the entire window.
261
+ - Bubble plates are invalidated by their own counter (`chat_glass_ver`), so a small drag no longer
262
+ re-bakes six bubbles per frame; only panel/slab caches are dropped.
263
+ - Edge-of-screen windows now only need to *overlap* the stage, not sit inside it; the off-screen
264
+ part is cropped short and padded. And a settle within 8s of the last capture does not re-capture
265
+ at all — the stage is refreshed for free while the window is hidden.
266
+
267
+ Numbers (665×594 panel, 150% DPI): a panel plate 520ms → **7.7ms**, slab 90 → **0.9ms**, bubble
268
+ 28 → **0.9ms**; `_paint` warm 1.3ms, `_reflow` 0.5ms; **dragging costs 24–28ms per frame (~38fps)
269
+ where it used to be frozen**; window open 510ms including the full-screen stage.
270
+
271
+ ### Fixed — optional services must go through `ctx.get()`
272
+
273
+ `ctx?.attachments?.saveImage` looks like a runtime probe but throws in a real host: cordis's `ctx`
274
+ is a Proxy whose `get` trap **throws** `cannot get property "xxx" without inject` when a service was
275
+ not declared in `inject`. `?.` only guards `null`/`undefined`, not exceptions.
276
+
277
+ All optional-service lookups now go through `serviceOf(ctx, name)` (in `src/timer.js`): it prefers
278
+ `ctx.get(name)` — cordis's documented way to ask for an optional dependency, returning `undefined`
279
+ when absent — and only falls back to property access inside a `try`.
280
+
281
+ ### Liquid-glass window, one stream, and a name you can change (2026-11-01)
282
+
283
+ Reported as: the scripted lines (warm amber, with a "台词" label) and the assistant's replies (cool
284
+ grey, labelled "陪看") read like two different people talking in one stream — and the window itself
285
+ looked like a plain dark panel.
286
+
287
+ **One stream, one look.** `ROLE` now maps `line` and `assistant` to the *same* colours, and the head
288
+ line shows **only the timestamp** — no "台词", no "陪看". Only the user's own messages keep a tint
289
+ (so you can still tell which side you are on).
290
+
291
+ **Timestamps are wall-clock now** (`HH:MM:SS`), for every role. Scripted lines used to show their
292
+ playback position (`01:26.0`) while everything else showed local time — two time bases in one
293
+ stream, so reading it meant converting in your head. Seconds are included because a segment runs
294
+ 2–5 minutes and several messages share the same minute; `HH:MM` alone would make the stamps useless
295
+ for telling them apart. A message with no `at` gets no head line at all (an empty label still eats
296
+ a full line of height).
297
+
298
+ **Liquid glass.** Three things carry the effect, because tkinter cannot blur what is behind it:
299
+
300
+ - **24px+ radius** — and `round_rect` no longer uses `smooth=True`, which renders a 22px radius as
301
+ roughly 14px (it smooths a polygon rather than following an arc). It now samples each corner arc
302
+ directly.
303
+ - **A refractive edge**: a 1px inner highlight along the top, plus an outer border split into a lit
304
+ upper half and a shadowed lower half — what a real piece of glass does.
305
+ - **Slight window transparency** (`-alpha 0.975`, `DSH_WATCH_GLASS_ALPHA` to tune, ≥1 disables).
306
+ The desktop shows through just enough to read as glass without competing with the text.
307
+
308
+ Buttons and the input field are **pills** now (`Pill` class + a Canvas-backed field): a square
309
+ "发送" button next to a 24px-rounded panel was the most obviously un-Apple thing left.
310
+
311
+ **The title is editable.** Click the name in the header, type, press Enter — saved as `name` in
312
+ `~/.dsh/watch-window.json` and restored next launch. Committing uses an explicit `_editing` flag
313
+ rather than `winfo_ismapped()`, which is still `False` on the frame right after `pack()` and would
314
+ silently swallow a fast Enter.
315
+
316
+ **Fixed:** `meta` entries (wake failures, mic status) were falling through to the assistant bubble
317
+ style — a screenful of `[一起看] 叫醒失败` rendered as full-size cards. They now use the grey
318
+ one-line `Meta` row that already existed for exactly this.
319
+
320
+ **Fixed:** the saved geometry was clamped against `sw - 120` instead of the window's own width, so a
321
+ 700px-wide window could be restored 580px off the right edge.
322
+
323
+ ### No more self-made "queued messages", one reminder per interjection, and a hideable window (2026-11-01)
324
+
325
+ Reported as three things that turned out to be one root cause plus two design gaps.
326
+
327
+ **The queue strip.** `wakeSession` delivers through `agent.followup()`, which lands in the host
328
+ inbox's `next-turn`. DSH's `QueueDock` renders **every** row of `next-turn` and does not filter by
329
+ `source.kind` — so the plugin's own instructions showed up in the input box as pending messages the
330
+ user never typed ("插话栏自动出现"). Two consequences fixed here:
331
+
332
+ - **The hangup note no longer goes through `followup`.** Closing the window is still a hangup (clock
333
+ stops, nothing is rebuilt, no lines are spoken), but the explanation is now written into
334
+ `watch.json` and handed to the model on its next tool result (`takeHangupNote`). The watch loop
335
+ already has the model blocked inside an interrupted tool call, so nothing is lost — and the queue
336
+ strip stays empty. `markHungUp(input, env, note)` carries the text; taking it clears it.
337
+ - **`[未回应]` is emitted once per interjection.** It used to be appended to *every* tool result
338
+ until the model answered with `say`, so one message from the user could be read as three separate
339
+ events ("大肥鱼已经重复了"). `noteInterjected` also no longer restarts the clock when the same
340
+ sentence arrives twice inside the 3-minute TTL.
341
+ - **The interjection prompt is two sentences, not a wall of ⚠️.** Same requirements
342
+ (`say` first, `speakNow`, lines in the same call), a fifth of the length — it is rendered in the
343
+ queue strip, so its size is user-visible.
344
+
345
+ ### `window: "hide" | "show"` — put the window away without ending the watch
346
+
347
+ Closing the window means "I am done watching". Hiding it does not: the process stays alive, the
348
+ clock keeps running, lines keep being spoken, nothing is marked as hung up. Reported as
349
+ "如果有其他功能隐藏悬浮窗会更好".
350
+
351
+ - `watch_together({ window: "hide" })` writes `hidden: true` into `~/.dsh/watch-window.json`;
352
+ `window.py` polls its config every 200 ms (`_sync_visible`) and does `withdraw()` / `deiconify()`.
353
+ `withdraw` rather than `iconify`: an always-on-top floating window should leave no taskbar entry
354
+ behind.
355
+ - `openFloatingWindow` clears `hidden` **before any early return**, so a window that was hidden when
356
+ the process died does not come back invisible.
357
+
358
+ ### Two-track prefetch (2026-11-01) — subtitles no longer wait for the pictures
359
+
360
+ The picture side is the slow one: a segment costs a download plus a scan (10–20 s, 20–90 s for the
361
+ first), while the text for the same window arrives in a few seconds (site CC: instant; local ASR
362
+ RTF 0.019 ≈ 6 s per 5-minute segment). They used to be produced and delivered as one package, so
363
+ the text sat in the slow batch's shadow. Now they are two independent tracks over the **same**
364
+ batch table and the **same** look-ahead window.
365
+
366
+ - **New subtitle track** (`transcribe` → `dsh-video-storyboard/transcript-pass`). Mirrors the picture
367
+ track line for line: same `plan.indexAt` / `windowAt`, its own `transcribed` set. "Whoever's window
368
+ is full stops first" falls out of `find()` returning `undefined` — no extra rule.
369
+ - **Two-part delivery.** When the text lands before its pictures, it is sent on its own
370
+ (`[一起来看·台词] 03:00–06:00` + one timestamped sentence per line). When the picture batch
371
+ arrives later it is built with `omitTranscript`, so the cells carry only times and the sentences are
372
+ not repeated (measured: 17k vs 26k tokens per 2 hours, +50% when repeated).
373
+ - **`feedTranscriptLeadMs`** (default 0 = send as soon as it lands). Raise it to ~20000 if the
374
+ two-part delivery feels chatty and you would rather wait for one combined message.
375
+ - **`transcriptTrack: false`** turns the whole track off.
376
+ - **Failures don't sink the loop.** A failed transcription is not marked as done, so the next tick
377
+ retries; three failures in a row blacklist that segment for 10 minutes (a missing ASR service
378
+ should not be hit every 2 seconds). The picture track is never blocked by it.
379
+ - **Cross-track timestamps now share one clock.** `transcribedAt` / blacklist times were stamped with
380
+ `Date.now()` while the tick compares against the injectable `deps.now()`; the difference was
381
+ negative by a trillion milliseconds, so the "skip for 10 minutes" and "wait N ms before feeding"
382
+ gates were both permanently bypassed (feeding never fired at all).
383
+
384
+ ### Experience pass (2026-11-01) — the minutes spent staring at nothing
385
+
386
+ Same code, same contract; what changes is what the user sees (or hears) while waiting.
387
+
388
+ - **A slow build now says something.** The first batch of a film needs a download plus a scan
389
+ (20–90 s) and a tool call cannot speak — so the window stayed empty and the only signal was
390
+ silence. After 4 s of building (`DSH_WATCH_SLOW_BUILD_MS`) one `meta` line is appended to the
391
+ stream: 「正在取 03:00–06:00 这一段…」. Fast segments write nothing.
392
+ - **The measured latency is finally used on the main path.** `latency.js` has been calibrating
393
+ "read position → result ready" for a while, but only the background clock (`shouldSpeak`) spent it;
394
+ the blocking call still waited until `segment end - lead`, so on the same machine the clock spoke
395
+ early and the tool call spoke late. `deliveryState` now uses `lead + aheadSeconds`, while the text
396
+ still reports `lead` (what is pulled earlier is the work, not the sentence).
397
+ - **Calibration only counts deliveries.** Not-yet calls take tens of milliseconds and are not samples;
398
+ recording them dragged the EWMA towards zero (and wrote `latency.json` on every poll).
399
+ - **The last batch is delivered at the tail.** The final segment's due point is `end - lead`, which for
400
+ the last batch sits past the end of the film — the position never reaches it, so the user watched
401
+ the ending and got nothing. Reaching/passing `dur - 1` now counts as due.
402
+ - **`speech` only lists lines that are still ahead.** It used to echo the whole draft, including the
403
+ lines the same call had just pruned as past — the model read them as "still going to be spoken".
404
+ - **Delivery guidance trimmed ~45%** (≈1150 → ≈640 chars). It is resent every batch; the loop/pacing
405
+ rules already live in the tool description, so only the hard rules stay here: write the lines,
406
+ no spoilers, one sentence, `say` is the only visible channel.
407
+
408
+ ### Reading pass over the loop (2026-11-01) — six real bugs, one hot path
409
+
410
+ No new features. Everything below was found by reading the code against its own comments and then
411
+ reproducing it; each fix carries a regression test that fails on the old code.
412
+
413
+ - **`lastDelivered: null` was read as batch 0.** A delivery blocked by the "no lines yet" gate writes
414
+ `lastDelivered: null`, and `Number(null)` is `0` — exactly the first batch's start. That batch then
415
+ counted as already delivered forever: `wait: true` woke up and answered "already delivered", image
416
+ and manifest never handed over. Empty now stays `NaN`.
417
+ - **Same film, two URL forms → the loop restarted.** `samePlan` compared the raw `input` string, but the
418
+ extension reports `…/BV1g3xN6hEuw/?trackid=…&spm_id_from=…` while the model usually holds the clean
419
+ link. Every second call therefore looked like a new source, wiping `spoken` and re-waking segments
420
+ that had already been delivered. It now compares `sessionKey()`.
421
+ - **`dur: null` became `0 s` on the bridge path.** `Number.isFinite(Number(s.dur))` passes for `null`,
422
+ so a report without a duration set the baseline to 0; the next real reading (600 s) then differed by
423
+ more than a second and was judged "video changed" — the clock stopped mid-film. `num()` in
424
+ `position-bridge.js` and the baseline update now treat empty as empty.
425
+ - **`waitForVideo` lost the hangup.** The input surface is prepared once (`prepared ??=`), and the
426
+ early pre-warm for `waitForVideo` passed no arguments — so `input`/`open` never reached it. Without
427
+ `input` the recorded hangup could not be matched, the window was re-opened, and the call went off to
428
+ wait for a video instead of returning `[hangup]`.
429
+ - **`dueLine` rewrote `watch.json` on every tick.** Its `dirty` flag was shared across segments: once one
430
+ batch had pinned its un-timed lines, every later batch was written back unchanged — a full state write
431
+ every 2 s for the rest of the film. The flag is per segment now.
432
+ - **`waitUntil` / `waitForRefill` lied about why they stopped.** Breaking out because the user paused (or
433
+ the film ended) still produced "waited to the cap". The text now names the real reason.
434
+
435
+ Hot path, same area:
436
+
437
+ - `cachedCues()` re-read and re-parsed the whole subtitle file on every tick (`dueLine` asks several
438
+ times per tick). It is memoised on `path + size + mtime` now, and returns the **same array** so that
439
+ `makeLagFn`'s memo can be keyed on array identity. `makeLagFn` additionally sorts once and looks up
440
+ by binary search instead of a linear scan of every cue. 2000 cues × 5400 lookups: **66.7 ms → 0.8 ms**
441
+ (×83), and the disk read/parse per tick is gone.
442
+ - `lines-util.js` had its own `cacheDir()` that fell back to `~/AppData/Local` on every platform, so on
443
+ Linux/macOS the subtitle cache landed in a directory that does not exist; it now uses the storyboard's
444
+ `cacheDir()`. `findCachedMedia()` likewise uses `tmpdir()` instead of `LOCALAPPDATA/Temp`.
445
+ - Dead exports removed: `plan.starts` (a 513-element array allocated on every `makePlan`),
446
+ `legacySessionKey`, `wasWritten`, `MATERIAL_PARTS`. The input surface failing to start no longer fails
447
+ the whole call — it is reported in the result instead.
448
+
449
+ Three rounds on 2026-10-31. The through-line: the plugin knew something, and the model (or the user)
450
+ never found out — plus one window that needed to look like something people want to keep on screen.
451
+
452
+ ### Long-video recap — merged, but opt-in
453
+
454
+ PR #2, after one round of review. Its first shape prepended a 420-character `[前情]` to **every**
455
+ delivery, partly built from the model's own scripted lines: second-hand context in a package whose
456
+ contract is "raw material only — never retell what the user just watched", at ~200 tokens per
457
+ segment, with no evidence it helped.
458
+
459
+ What shipped instead: off unless `recap: true` or `DSH_WATCH_RECAP=1` (`recap: false` beats the env
460
+ var); only **cached subtitle sentences**, never the model's lines; `recapSegments` 1–3 (default 2),
461
+ `recapMaxChars` 80–1200 (default 420); never reads past the current segment, never trims the live
462
+ transcript, no ASR, no network. Whether it actually reduces retelling is still **unmeasured** — it
463
+ stays opt-in until somebody measures it.
464
+
465
+ ### Observability: `statusOnly` can now answer "why is it slow"
466
+
467
+ Promised in issue #4. `pos + reason` says *what* the clock thinks, not *where it is stuck*.
468
+
469
+ - `segment { index, from, to, delivered, total }` — which batch, its bounds, how many were delivered
470
+ this session, how many the film has (`total` is `null` when the duration is unknown). The last batch
471
+ index is taken at `dur - 1 ms`, because a duration that lands exactly on a boundary would otherwise
472
+ report one batch too many.
473
+ - `speech { queued, lastLateSec, busyUntil }` — lines still waiting, how late the previous line was
474
+ (from `dueLine`'s new `meta: true`, which also keeps the plain-string return for old callers), and
475
+ when the serial voice engine frees up.
476
+ - `build { inflight, cached, lastMs }` — which batch is being built, how many are cached, how long the
477
+ last build took. The cache is passed into the loop for reporting only; it never influences a decision.
478
+ - `queued` needs a disk read, so it is filled in `statusOnly` only, and a failure there is reported as
479
+ `speech.queueError` instead of being swallowed (the first version of this swallowed a `ReferenceError`
480
+ from a missing import and looked exactly like "there are no lines").
481
+
482
+ ### The floating window, rebuilt
483
+
484
+ "这个悬浮窗太丑了" — fair. The old one was a borderless frame with a `Text` widget that painted
485
+ role-coloured **full-width stripes**, on a window Windows stretched from 96 dpi, reading the whole
486
+ `chat.jsonl` every 200 ms.
487
+
488
+ - **Real bubbles.** Each message is its own rounded card (Canvas background + wrapped Label), sized
489
+ to its content: script lines in amber with a left rule, the model in slate, the user's own words
490
+ right-aligned in blue. Above each one, a muted line saying who and when (`台词 04:12.3` for a
491
+ scripted line, `我 21:16` for chat).
492
+ - **Per-monitor DPI awareness** before the window exists, and every size/font derived from the real
493
+ scale factor. Unaware Tk windows are bitmap-stretched at 125/150%, which reads as "blurry and wrong".
494
+ - **Rounded window** via `-transparentcolor` (Windows only; falls back to square corners), a 1 px
495
+ border, and a hand-drawn 6 px scrollbar that only appears when the list actually scrolls.
496
+ - **Does not steal focus.** `focus_force()` at startup meant pressing space to pause the video landed
497
+ in the chat box; now the entry only takes focus inside the window.
498
+ - **Does not fight your scrolling.** New lines auto-scroll only if you were already at the bottom.
499
+ - **Incremental read.** Only the bytes appended since the last tick are parsed, and the first paint
500
+ replays just the last 60 entries.
501
+ - Resizable from the bottom-right grip; position and size persist in `~/.dsh/watch-window.json`.
502
+
503
+ ### Stop when the signal says stop: hangup, dead source, switched video
504
+
505
+ Reported as "换片或者我都关浏览器了还在念台词" and "关了悬浮窗 AI 还是会自动调出来,根本不会自动结束".
506
+ Both were the same shape: the plugin knew the source was gone, and kept talking anyway.
507
+
508
+ - **Speech now requires a believable position.** The line queue only fired when the position was
509
+ `fresh`, or `extrapolated` within `SAFETY_AFTER_MS` (20 s — the normal gap between probes).
510
+ Before, the only thing excluded was `paused`; `estimate()` happily extrapolates a dead source
511
+ forward and `pos` stays finite, so closing the browser kept reading lines out for minutes.
512
+ Nothing is spoken on an `unknown` position, and the position-unknown give-up dropped from
513
+ 10 min to 5 min (the watch should not sit there pretending).
514
+ - **Closing the floating window is a hangup, treated like an interjection.** The window is the only
515
+ way to talk mid-watch, so closing it means "I'm done":
516
+ - the clock stops and **really wakes the model** — `wake:false` (the default) used to silence this
517
+ too, because it shared the `wake` path with the segment-end reminder. User actions (hangup,
518
+ video changed, video ended, seek, unreadable position, high-frequency mode) now use a separate
519
+ always-real channel (`wakeSignal`), and the message says **do not call watch_together again and
520
+ do not read out any more lines**;
521
+ - the guard is stored on the loop and can be turned on later (`resumed` path used to freeze it,
522
+ so a window opened by an earlier call was never guarded);
523
+ - the next tool call **does nothing at all**: no frame, no clock, no window (`[hangup]` result).
524
+ `sameWatch` previously required `args.input`, which the model never sends — so every call looked
525
+ like "a new watch" and re-opened the window the user had just closed.
526
+ - `wakeWithRetry` called an undefined `note()` in its failure branch (a `ReferenceError` swallowed by
527
+ the ticker). Real wakes can fail, so it was reachable; now it records into `loop.logs`.
528
+
529
+ Tests: 247 pass, +4 in `test/hangup-guard.test.mjs` (dead source sends nothing, live source still
530
+ speaks, hangup wakes with the right wording, post-hangup call is inert).
531
+
532
+ ### Interjections: speak first, then look
533
+
534
+ Reported as "它一声不吭先去 zoom,回来才说话". The root cause was not the model: a normal reply
535
+ never reaches the floating window — only `say` does and only `say` is spoken. So "think, then look,
536
+ then answer" was, from the user's side, complete silence for tens of seconds.
537
+
538
+ - One wording, one place (`src/interject.js`) for all five entry points (during a build, during the
539
+ lookahead fill, during a blocking wait, `waitUntil`, `nextLine`). It now says exactly what to do:
540
+ `watch_together({ say: "我看一眼", speakNow: true })` — one call, words written before any frame
541
+ is built. `lines` and `say` can ride in the same call, so "台词优先" no longer means "stay silent".
542
+ - Unanswered interjections are **tracked**: the next tool result ends with `[未回应] …你还没回`,
543
+ until a call actually carries `say` (expires after 3 min). Previously the reminder existed only
544
+ inside the message that woke the model, which it had already scrolled past.
545
+ - `waitUntil` / `nextLine` called a function that **did not exist** (`chatResult`) — an interjection
546
+ during either wait threw `ReferenceError` and the tool failed. Defined, and it reuses the same wording.
547
+ - Waiting for a video to appear returned a result **without `text`**, which the host's `output.schema`
548
+ requires. That path now returns a proper result.
549
+
550
+ ### Reply vs. scripted line: 12-second guard
551
+
552
+ Reported as "说话和插话的回复离太近,把后面那句改一下". Two lines spoken back to back on a serial
553
+ TTS chain means the second one either drifts or is dropped by the adapter (queue > 3.5 s → `skipped`).
554
+
555
+ - `say` now marks the voice engine busy for its full spoken length (`src/reply-guard.js`), so the
556
+ loop stops feeding scripted lines while a reply is still playing. Previously only the loop's own
557
+ lines updated that clock — a reply was invisible to it.
558
+ - Lines scheduled within 12 s of a reply are **withdrawn from the batch and handed back** to the
559
+ model (`[lines·太近]`) with instructions to rewrite them around what was just said, or drop them.
560
+ Withdrawn, not silently deleted: the user asked for "改一下", not "少一句".
561
+
562
+ ### Switching videos is noticed in ~2 s, not ~15 s
563
+
564
+ - The per-tick bridge read (every 2 s) now does the switch / end-of-video / big-jump checks, and
565
+ keeps the `dur`/`url` baseline up to date. Before, all three lived in the 15-second CDP probe
566
+ branch only, so a switch could go unnoticed for a quarter of a minute — while the clock kept
567
+ computing segment boundaries against the old film.
568
+ - The blocking wait in `watch-run` now compares each read against the film it started with and
569
+ returns `[video-changed]` immediately. **This was the only reliable path**: the loop's wake goes
570
+ through `followup()`, which is delivered *after* the current tool call returns — and that call was
571
+ busy waiting.
572
+ - `sourceSwitched()` centralises the test, and `Number(null) === 0` is explicitly guarded: a
573
+ not-yet-known duration used to look like a "0-second film" and stop the watch instantly.
574
+
575
+ ### Cold start: don't wait a full minute for a video we can already identify
576
+
577
+ - The extension only reports while the tab is **visible** — and "一起看" is usually typed in another
578
+ window. The position went stale after 5 s, the plugin concluded "no video", and sat in the 60 s
579
+ wait. It now falls back to a **stale** sample (up to 2 min) to identify the film, marks the
580
+ position `stale`, and lets the next fresh reading correct it.
581
+ - Automatic waiting (no `waitForVideo`) dropped from 60 s to **20 s**; explicit `waitForVideo: true`
582
+ stays at 120 s.
583
+ - `probeBrowser()` is skipped when the extension already reports: one probe is `listTargets`
584
+ (1.2 s) plus up to 8×1.5 s of CDP round-trips — pure overhead for a `browser:` line the extension
585
+ just answered. The line now reads `browser: extension reporting <title> playing 03:20`.
586
+
587
+ Tests: 243 pass (`node --test`), 6 of them new in `test/interject-reply.test.mjs`.
588
+
589
+ ## [0.1.0] - 2026-11-01
590
+ 首个发布版本。要求 `dsh-video-storyboard@^0.5.11`(字幕轨用到它的 `./transcript-pass` 子路径)。
591
+
592
+ ## [0.0.7] — 2026-10-31 (first release)
593
+ The first published version. One tool, `watch_together`: it follows the user's real playback
594
+ position, hands the model one storyboard + transcript per segment just before that segment ends,
595
+ and speaks the scripted lines at the second they belong to.
596
+
597
+ **Licence: Apache-2.0** (the package was developed under MIT and switched before the first
598
+ public release, to match `dsh-video-storyboard`). `LICENSE` is the full text, `NOTICE` states
599
+ what the project deliberately does **not** do — no hosted video, no uploaded position, no DRM or
600
+ paywall bypass, no bundled TTS engine.
601
+
602
+ ### Repo hygiene — the extension's manifest and icons were never committed
603
+
604
+ `.gitignore` carried `manifest*.json` and `*.png` (meant for CLI artifacts). Those two rules also
605
+ swallowed `extension/manifest.json` and `extension/icons/*.png`, so a clone would have shipped an
606
+ extension **with no manifest** — completely broken, and nothing would have failed until someone tried
607
+ to load it. Both are now force-added, and the ignore rules are anchored (`/*.png`, `/*.meta.json`) so
608
+ they can only ever catch files at the repo root. Also: `* cookies*.txt` (a pattern with a space, which
609
+ never matched anything) is gone, `__pycache__` is out of the npm tarball via a new `.npmignore`, and
610
+ `npm test` no longer requires the sibling `dsh-video-storyboard` checkout — it falls back to the
611
+ installed copy, so a clone can run the suite.
612
+
613
+ ### Docs — one page per service, and the stale one is gone
614
+
615
+ `docs/WATCH.zh.md` still explained how to configure things around the **OS media session (SMTC)**,
616
+ which was deleted a while ago: wrong rationale, wrong `confidence` values, wrong defaults. Deleted.
617
+ Replaced by [`docs/CONFIG.zh.md`](docs/CONFIG.zh.md): ffmpeg → yt-dlp + cookies → subtitles/ASR →
618
+ browser extension (9377) → debug port (9333) → voice (`voice.json` + `tts.json`) → floating window →
619
+ cache locations → a one-page troubleshooting table. Every entry says **what breaks if you skip it**.
620
+
621
+ `README.md` got a 30-second start, a "what to configure" table, a corrected parameter table
622
+ (`depth` is auto-by-time now, `lookahead` was missing), a CLI table that matches the 15 real
623
+ subcommands, a privacy note for the extension, and a dev section. `docs/VOICE.zh.md` gained
624
+ `state: 'skipped'` and a correction: `at` is a **playback second**, not a wall-clock timestamp.
625
+
626
+ ### `doctor` — three levels, because "not configured" is not "broken"
627
+
628
+ `FAIL` used to be printed for things that are merely "not set up yet": a missing cookie file (only
629
+ needed for Bilibili), a closed debug port (the extension is the recommended channel), an extension
630
+ that is loaded but has no video playing. First-run users read that as "something is broken" and went
631
+ to reinstall the extension. Now: **OK / WAIT / FAIL**, only `plugin` and `ffmpeg` are fatal, and when
632
+ the extension has checked in but nothing is playing, `doctor` says `READY — 播个视频就能读到位置`
633
+ instead of "both position channels are down".
634
+
635
+ ### Performance — the chat watcher no longer re-reads the whole log every 150 ms
636
+
637
+ The blocking-wait loop polls `chat.jsonl` every 150 ms. Each poll re-read `readChat()` and parsed
638
+ every line, so a two-hour session (thousands of entries) was decoding hundreds of KB several times a
639
+ second, and getting slower the longer the session ran. `makeChatWatcher()` now keeps a byte offset
640
+ and reads **only what was appended since last time** (falling back to a full re-read if the file
641
+ shrank, i.e. it was cleared). Measured on a 5000-line log: **0.061 ms per poll, independent of file
642
+ size**. `appendChat()` also stopped parsing the whole log to keep `at` monotonic — it reads the last
643
+ 4 KB instead.
644
+
645
+ ### Tool description — pacing is now a rule the model can follow
646
+
647
+ `watch_together`'s description tells the model to keep lines **≥ 6 s apart** and why: speech is
648
+ serialized, so a denser draft is thinned at runtime (engine busy → next line held; past the late
649
+ grace → dropped). The three previous rounds of "台词太早 / 太密" all came from the model not knowing
650
+ this budget.
651
+
652
+ ### Fixed — speech piled up in the engine queue, and an interjection could no longer break a blocked wait
653
+
654
+ Two reports in one message: "吐字太快,台词会挤到一起,只有上一句念完才到下一句,话太密会导致语音越来越
655
+ 滞后" and "悬浮窗插话不能让他从等待中出来 —— 这个功能之前是好的".
656
+
657
+ **The voice queue.** `examples/voice-edge-tts` chains every `due` event onto an unbounded serial promise
658
+ ("two lines never overlap"). Lines are now scheduled at the right second, so when they arrive faster
659
+ than the engine can speak them the chain simply grows: speech drifts further from the picture with
660
+ every line, and the caption (written on `spoken`) drifts with it.
661
+
662
+ - `src/watch-loop.js` — the clock now keeps a **voice budget**: after handing out a line it records
663
+ `voiceBusyUntil = now + speechSeconds(len)` and will not hand out the next one while the engine is
664
+ still talking. A line that misses its window by more than the late grace is dropped by `dueLine`
665
+ as usual: **speak one line less rather than one line later**.
666
+ - `src/speech.js` — `speechSeconds(chars)`: full spoken duration (`0.35 + chars/5`, 0.8–30 s).
667
+ `speechLag()` stays as it was — that one answers "when may I start talking", this one answers
668
+ "how long is the engine busy".
669
+ - `examples/voice-edge-tts` — safety net: if a queued line has been waiting more than 3.5 s it is
670
+ **abandoned** (logged) instead of spoken, and the queue empties immediately.
671
+ - `src/speech-bus.js` / `src/chat-store.js` — a fourth state, `skipped`: the adapter reports that it
672
+ gave up on a line, and `attachSpeechToChat` cancels the pending fallback timer for it. Without this
673
+ the 2.5 s fallback would paint a caption for a line that was never spoken.
674
+
675
+ **The interjection.** `chat.jsonl` is a **consuming** channel: `poll()` marks a message read. The
676
+ blocking wait and the watch loop share one watcher, and the loop's handler is `followup()` — which
677
+ cannot interrupt a session that is sitting inside a tool call (the message is only processed when
678
+ the turn ends). So whichever polled first decided the outcome, and the loop (every 2 s) sometimes
679
+ won: the interjection was swallowed, the wait's `poll()` never saw it, and the user's "stop, I have a
680
+ question" did nothing until the segment ended.
681
+
682
+ - `src/interrupt.js` — `enterChatWait()` / `chatWaiterCount()`: whoever is blocking on purpose
683
+ **owns** the channel. `raceChat()` (storyboard build, prefetch) registers too.
684
+ - `src/watch-loop.js` — `wakeOnChat` is skipped entirely while `chatWaiterCount() > 0`. The wake path
685
+ still works when the model is idle (no waiter), which is its whole purpose.
686
+ - `src/watch-run.js` (the `wait: true` loop), `src/watch-modes.js` (`waitUntil` / `waitForRefill` /
687
+ `nextLine`), `src/watch-source.js` (`waitForVideo`) — all register as waiters for the duration of
688
+ their loop.
689
+
690
+ Tests: `test/lines-timing.test.mjs` (engine busy → next line is not handed out; the overdue one is
691
+ dropped), `test/chat.test.mjs` (`skipped` writes nothing, not even the fallback),
692
+ `test/interject-anywhere.test.mjs` (the loop must not consume while a waiter is active; counter
693
+ cannot go negative).
694
+
695
+ ### Fixed — scripted lines came out like a machine gun, and minutes before the picture
696
+
697
+ Reported as: "台词出现时间早了很多,而且和机关枪一样突突突一下出来一大堆,时间点都比视频早了".
698
+
699
+ The line queue is ordered by `at` (the second of the video this line is *for*) and fired by playback
700
+ position, so the pacing is only as good as the `at` values. When a line was written **without** `at`
701
+ (the model wrote prose only), `pinTimes()` decided when it would be said — and it took *the first N
702
+ subtitle sentence starts of the segment*. Sixteen lines written for a 3-minute segment were therefore
703
+ all packed into its first 62 seconds (181.6 → 244.2, measured on the live queue), i.e. one every
704
+ 2–3 seconds: the clock ticks every 2 s and hands out at most one line per tick, which is exactly the
705
+ "machine gun". The last 14 of them ran one to two minutes ahead of the picture they describe.
706
+
707
+ - `src/watch-lines.js` `pinTimes()` — each line now aims at its **even share of the segment**
708
+ (`from + i*size/n`) and snaps to the nearest subtitle start within half a slot, so the queue is
709
+ spread over the whole segment instead of stacked at its head. Falls back to the even share when no
710
+ start is close enough, and **never goes backwards** (the old tail fallback could emit 152.8 → 150).
711
+ - `src/watch-lines.js` `dueLine()` — pinning uses **the segment that line belongs to** (`sizeOf`),
712
+ not the segment the user happens to be in. With the 1/2/3/4/5-minute ramp, a 60-second slot pinned
713
+ with a 300-second size put its last lines outside the segment entirely.
714
+ - `src/watch-lines.js` `saveLines()` — `at` given as **subtitle text** was resolved only against
715
+ `recallSegments()`, which is a 4-entry in-process cache (empty in a fresh process, and lines are
716
+ usually written in a different turn). A miss silently became "no `at`", i.e. the head of the
717
+ segment — the other half of "the line is way too early". Now it reads the on-disk
718
+ `subs-<key>.json` cache first, then falls back to memory, then to a fuzzy match (≥60 % of the
719
+ characters), and only then warns.
720
+ - `src/watch-run.js` — the delivery note pruned "past" lines with `Number(l.at)`, and
721
+ `Number(null) === 0`: **every line without `at` was judged as second 0 and deleted** at delivery.
722
+ The note now previews the same pinning the clock will use, so the reported "earliest …" time is the
723
+ real one, and only lines whose *actual* time has passed are dropped (by text).
724
+ - `src/watch-run.js` — the note now lists the landing times it will use (`[lines] 落点:…`) and warns
725
+ when the average gap is under 6 s, instead of leaving the model to guess its own pacing.
726
+ - `src/watch-loop.js` — with the extension as the position source, the anchor is now re-read **every
727
+ tick** (a small local JSON, not CDP). Between the 15-second probes the clock extrapolated blindly,
728
+ so after a pause the lines up to 15 s ahead were spoken **early** — extrapolation is bounded for
729
+ lateness but nothing guarded earliness.
730
+ - `src/latency.js` `aheadSeconds()` — returns 0 instead of `NaN` when `ms` is missing. `NaN` made
731
+ `pos` `NaN`, every comparison false, and `shouldSpeak()` reported "due" for the first unspoken
732
+ segment at every tick.
733
+
734
+ Tests: `test/pin-times.test.mjs` (the 16-line packing regression, monotonic fallback, cues bunched at
735
+ the head), `test/watch-lines.test.mjs` (per-segment size, `at` from the on-disk subtitle cache),
736
+ `test/lines-timing.test.mjs` (a stuck video must not speak the next line early).
737
+
738
+ ### Fixed — the caption appeared before the voice, because it waited on `due` instead of "actually speaking"
739
+
740
+ `attachSpeechToChat` wrote a line into `chat.jsonl` the moment `due` fired. But `due` only means
741
+ "it is time to say this": synthesis still has to happen (edge-tts does a network round trip, then a
742
+ fresh `ffplay` process — 0.6–2 s even for a short sentence). The floating window polls that file, so
743
+ the text was already on screen a beat before anything was heard.
744
+
745
+ Delaying the voice instead (`speechLag`) would align the two, but push the voice further from the
746
+ picture, which is the one thing this plugin cannot trade away. So the **caption** moves:
747
+
748
+ - `src/speech-bus.js` — a third state, `spoken`, plus `emitSpoken(event)` for engines to report
749
+ "audio is starting now". The adapter API gains `emitSpoken`.
750
+ - `src/chat-store.js` — writes on `spoken` when a `voice: true` subscriber exists; still writes on
751
+ `due` when nobody will speak (the zero-dependency path must not go mute); falls back after
752
+ `fallbackMs` (2.5 s, `DSH_WATCH_CAPTION_FALLBACK_MS`) for adapters that never report.
753
+ Pairing is by `at|text`, not by `seq` — `spoken` is a **new** event, so `emitSpeech` gives it a
754
+ new sequence number.
755
+ - `examples/voice-edge-tts` — reports `spoken` right before playback starts (i.e. after synthesis).
756
+ - `examples/floating-chat/window.py` — polls every 200 ms instead of 400 ms; the poll interval is
757
+ the residual "text lags the voice" gap.
758
+
759
+ `test/chat.test.mjs` covers both new paths (waits for `spoken`; falls back when nobody reports, and
760
+ does not write twice if `spoken` arrives afterwards).
761
+
762
+ ### Fixed — scripted lines never reached the chat window without a voice engine
763
+
764
+ `watch-loop.js` consumed the due line inside `if (speechSubscribers() > 0)`. That helper counts only
765
+ `voice: true` subscribers (real engines), while `attachSpeechToChat` — the one that writes lines into
766
+ `chat.jsonl`, which is exactly what the floating window reads — subscribes with `voice: false`.
767
+ So with no voice adapter, or one that failed to load, a scripted line was **never taken from the
768
+ queue at all**: not spoken, not displayed, and the queue silently accumulated.
769
+
770
+ Display and speaking are two separate things. The line is now handed out at its due moment
771
+ regardless: `emitSpeech` delivers it to every subscriber, and only a real `voice: true` subscriber
772
+ counts as "said" (`if (speechSubscribers() > 0) return;` still stops the wake, so nothing changes
773
+ when a voice engine *is* attached).
774
+
775
+ `test/lines-to-chat.test.mjs` covers both sides. The test was checked against the bug: restoring the
776
+ old condition makes the no-voice case fail while the with-voice case still passes.
777
+
778
+ ### Changed — `say` no longer reads as "only to answer an interjection"
779
+
780
+ It always worked at any moment: it writes the sentence into the shared stream and hands it to
781
+ whoever listens for speech, exactly like a scripted line. But the description ended with
782
+ "use it to answer an interjection", which reads as "only after the user speaks". A model follows
783
+ that literally, so the one path for saying something **unprompted** went unused.
784
+
785
+ The description now says any time, and says it explicitly: something in the picture strikes you,
786
+ the user asks something, a thought lands while waiting for the next batch — plus
787
+ "do not wait for the user to speak first". It also states the cost, because that is what makes it
788
+ usable mid-wait: no position read, no frame built, no batch advanced, one round trip.
789
+
790
+ `test/say.test.mjs` pins the wiring — parameter → stream (one `assistant` row with `say: true`) →
791
+ speech event with `origin: 'chat'`, no image, no state advanced. The store layer was already covered
792
+ by `test/chat.test.mjs`; the uncovered part was the parameter entry itself.
793
+
794
+ ### Added — an end-to-end test for "talk while the frame is building"
795
+
796
+ The mechanism already existed (`raceChat(buildSegment(...))` in `runWatchPass`), and
797
+ `test/interrupt.test.mjs` covered `raceChat` itself — but the `built.kind === 'interrupted'`
798
+ branch had **no** coverage. If a refactor ever dropped the wrapper, or `chatWatcherShared()` got
799
+ replaced with a fresh watcher per call, every existing test would still pass.
800
+
801
+ `test/interject-build.test.mjs` builds a segment that takes 1.2 s, writes a user message at 0.2 s,
802
+ and asserts all four things at once: the call returns before the build finishes, it carries that
803
+ exact message, it carries no image, and the build still completes into the cache afterwards.
804
+
805
+ ### Changed — three implicit couplings now have exactly one source each
806
+
807
+ A pass over the module boundaries. Same behaviour except the `lead` fix at the end, which was a
808
+ real bug: the parameter only worked on one of the three paths that used it.
809
+
810
+ - **`handler.js` stopped preparing UI.** The floating window, the chat service and the "where do I
811
+ type" note moved to `input-surface.js` (`createInputSurface()`). `handler` is a router again —
812
+ three exits: quick action, one pass, start the loop. The `widgetNote` variable no longer travels
813
+ from the top of the function to the bottom.
814
+ - **`watch-run.js` has one return shape.** Eleven exits each used to build their own ten-field
815
+ object; now they all call one `pass()` closure. Adding a field is one edit instead of eleven, and
816
+ a branch can no longer quietly forget one.
817
+ - **One segment length.** `watch-state.js` exported `WATCH_SEGMENT = 120` while `batches.js`
818
+ declared `DEFAULT_SEGMENT = 300`; whichever fallback fired first decided how long a segment was.
819
+ `batches.js` is now the only source, and `WATCH_SEGMENT` is gone.
820
+ - **One lead.** The delivery lead was hardcoded in three places: `batches.from()` produced
821
+ `sayAt = to - 15`, `watch-loop.js` passed `lead: 15` to `shouldSpeak`, and only `watch-run.js`
822
+ actually read `args.lead`. Segments no longer carry `sayAt`; `shouldSpeak` computes `to - lead`,
823
+ and `startWatchLoop` takes `lead` from the caller. `lead: 60` now really moves the trigger point
824
+ (checked against a 300 s segment: at 241 s, `lead=15` stays quiet, `lead=60` fires).
825
+
826
+ ### Removed — no more auto-launched browsers, no more browser widget
827
+
828
+ Both were early paths from before the browser extension existed. Neither could produce a position
829
+ for the tab the user is actually watching, so both are gone rather than kept as fallbacks.
830
+
831
+ - **Auto-launching a browser**: `ensureWatchBrowser()` (`launchBrowser` + `waitForPort`), the
832
+ `autoLaunch` flag on `runWatchPass`, the `attachOnly` parameter, and the `launchBrowser: true`
833
+ branch in `~/.dsh/video.json`. The extension already reports `currentTime` every second from the
834
+ page the user is on; opening a second Edge with its own profile never helped that page. When no
835
+ position can be read the tool now asks "how far are you" instead of starting a program.
836
+ - **The browser widget page**: `GET /widget`, `WIDGET_PAGE`, `openWidgetInBrowser()`, `widgetUrl()`,
837
+ and the `documentPictureInPicture` button in the chat page. The input box is the native tkinter
838
+ window (`examples/floating-chat/window.py`); the HTML page stays as a read-only fallback at `/`
839
+ (`chatPageUrl()`), and is never opened automatically.
840
+ - **Dead parameters**: `wakeOnLinesEmpty` (the handler never passed it, so its 30-line branch in
841
+ `watch-loop.js` could never run), `title` (nothing in `src/` or in storyboard read it), and
842
+ `segmentStart()` (every caller uses `plan.segmentAt()`). Parameter count 36 → 34.
843
+
844
+ ### Fixed — interjections used to get swallowed (four different ways)
845
+
846
+ The interjection path was the one place where losing user input was silent: nothing crashed, nothing
847
+ logged, the words just never arrived. All four ways of losing them are now closed, and each one has
848
+ a regression test (`test/cli-interrupt.test.mjs` — the CLI had **no** test coverage before this).
849
+
850
+ - **Between two `cue` runs.** Every `cue` is a fresh process, and the watcher took "however many
851
+ lines exist right now" as its baseline — so anything the user typed while the model was thinking,
852
+ building a segment or replying was never read by anyone. The read position now lives in
853
+ `<watch>/chat-cursor.json`: a `cue` starts from where the last one stopped, and delivers what it
854
+ finds the moment it enters the wait. Baseline is persisted as soon as it is established, because a
855
+ `cue` that hears nothing (the common case) otherwise leaves no cursor for the next one.
856
+ - **Two messages arriving in the same poll.** Both watchers (chat box and host session file) marked
857
+ the whole batch as read and reported only the first, so the second was gone. They now consume up
858
+ to the message they hand over and no further — "reply first, then take the next one".
859
+ - **Wrong conversation.** `findActiveSessionFile()` took the most recently modified session jsonl
860
+ across *all* projects, so a chat in another window could interrupt the watch session. It now
861
+ prefers the project matching the current directory and only falls back to global when that one has
862
+ no active session.
863
+ - **The host writing old messages late.** WorkBuddy flushes a user's message into the session file
864
+ *after* the reply to it. The watcher saw new bytes and treated them as a fresh interjection —
865
+ interrupting the current turn with the message that started it. Messages whose `timestamp`
866
+ predates the watcher are now ignored.
867
+
868
+ Also in this path: interjections heard via the host input box are appended to the chat stream too
869
+ (they used to appear only in `cue`'s stdout, so the page showed a stream with a hole in it); the
870
+ chat page puts the words back in the input box when a send fails instead of losing them; and
871
+ `POST /api/say` answers `ok:false` for requests it did not write, which is what makes that recovery
872
+ possible.
873
+
874
+ ### Fixed — `cue` and `say`
875
+
876
+ - `cue` no longer waits forever when the video changes underneath it. It compared against the
877
+ segment delivery point of the *old* video, and if the new one was shorter, `deliverAt` was a
878
+ position that would never be reached. It now detects a changed URL or duration and exits with
879
+ `VIDEO-CHANGED` (pending lines are saved under the old source), and exits with `REWIND` when the
880
+ user drags the progress bar back more than a minute — the model should hear about that instead of
881
+ sitting on lines written for a position the user left.
882
+ - Two `cue` processes can no longer run at once: a state file saying `blocking` with a **live** pid
883
+ is refused with `BUSY` (exit 1). A dead pid is taken for what it is — the residue of a killed run —
884
+ and does not block anything. `check` mode is read-only and never takes the lock.
885
+ - `check` mode no longer leaves `cue-state.json` at `blocking`, which used to make the next run
886
+ report "last wait was killed externally" for a run that was never waiting.
887
+ - `say` called edge-tts once by hand and then again inside `speak()` (twice the synthesis, and the
888
+ manual attempt passed the raw configured voice, so a SAPI-style name like `Huihui` never matched
889
+ and silently fell back). It now calls `speak()` once, which does the mapping and the fallback.
890
+ - `voices` was advertised in `help` and crashed with `cmdVoices is not defined` when called. It now
891
+ lists the SAPI voices plus whether edge-tts is present and which voice is configured — the first
892
+ place to look when "why am I still hearing the navigation lady" comes up.
893
+
894
+ ### Added — talk instead of type: a microphone button in the floating window
895
+
896
+ `examples/floating-chat/mic.py` is a separate process the window starts from its `麦` button. It
897
+ listens, cuts what you say into utterances with the Silero VAD already sitting in `models-sherpa/`,
898
+ transcribes each one, and writes it into the **same** `chat.jsonl` the typing path uses — so a
899
+ running `cue` picks it up through the interjection cursor and the model answers without anyone
900
+ typing a character. Measured end to end on this machine (i9-12900HX, int8 paraformer):
901
+
902
+ - one model instance ≈ **284 MB** working set, loads in ~2 s
903
+ - a 3 s utterance transcribes in **0.15 s**; a 45 s one in ~1.2–3.3 s (RTF ≈ 0.05, 20× realtime)
904
+ - concurrent transcription barely queues: a 3 s short request takes 0.14 s even while a 45 s
905
+ transcription is running
906
+
907
+ **It runs its own model by default** (`--engine local`), which is the answer to "can ASR run twice":
908
+ yes, and it is cheap. It also means the microphone never waits behind a video transcription. The
909
+ existing service cannot offer that yet — see the note below. `--engine http` shares port 8000
910
+ instead, saving 284 MB at the cost of queuing behind long audio.
911
+
912
+ **It refuses to hear itself.** The agent speaks through speakers; the microphone hears it; without a
913
+ guard that gets transcribed as if the user had said it, and the model answers its own line forever.
914
+ Every utterance is checked against `quiet-until.json` (the same window `say` and `cue` already take
915
+ before speaking) and dropped if the agent is talking.
916
+
917
+ ### Added — acoustic echo cancellation, so the microphone hears you and not the computer
918
+
919
+ `examples/floating-chat/aec.py`: the microphone picks up whatever the speakers are playing, which
920
+ means the video's narration gets transcribed as if you had said it. Since neither `speexdsp` nor
921
+ `webrtc-audio-processing` builds on this machine (no C compiler, no wheels), this is a frequency-domain
922
+ adaptive filter (overlap-save FDAF, power-normalised NLMS) in numpy — one FFT per 32 ms frame.
923
+
924
+ It captures the **loopback** channel (what the computer is playing, auto-detected as the
925
+ speaker/loopback device, never "stereo mix" — that one can contain the microphone too) and subtracts
926
+ the estimated echo from the microphone. On top of that, an utterance whose energy drops below
927
+ `--echo-gate` (default 30 %) after cancellation is discarded outright: that is the hard guarantee
928
+ that pure-echo segments are never transcribed, whatever the filter is doing.
929
+
930
+ Two things that mattered more than the filter itself:
931
+
932
+ - **Double-talk detection cannot compare against the echo estimate.** At startup the filter is zero,
933
+ so the estimate is zero, so "mic > 2 × estimate" is always true, so the filter freezes and never
934
+ converges (first version: 498 frames frozen, 0 dB). It now compares against the **reference**
935
+ signal (Geigel-style), which does not depend on the filter's state.
936
+ - **Measured on a synthetic but honest mixture** (real speech as the video, a different real speech
937
+ segment as you, through a 150 ms-delayed reverberant echo path):
938
+ ERLE **13.6 dB** during echo-only passage; the video's words in the transcript went from **25 % →
939
+ 0 %**, and an 8 s passage with nothing but video audio produced **no transcription at all**.
940
+
941
+ Tunables: `--dt-ratio` (1.4 — mic peak vs reference peak before the filter freezes), `--taps`
942
+ (8192 ≈ 512 ms of reverb tail), `--echo-gate`, `--no-aec`, `--loopback`.
943
+
944
+ Honest limits: it is a software AEC, not magic. The first second or two of your speech, right as the
945
+ filter re-converges after you start talking, is where the damage shows (a few characters in the test
946
+ above). Speaker loudness and room reverb both make it harder. **Headphones remove the problem
947
+ entirely** — with headphones there is no echo to cancel, and everything above is unnecessary.
948
+
949
+ ### Added — a browser extension, so you never open a special window again
950
+
951
+ Position used to require a browser started with `--remote-debugging-port`, and Chromium 136+ refuses
952
+ that flag on the default profile — so users had to keep a second, separate browser window open just
953
+ for watching. That was the whole reason this package felt like it needed a "special browser".
954
+
955
+ `extension/` is an MV3 extension that reads `<video>.currentTime` from the page you are actually
956
+ watching and POSTs it to the plugin's own localhost server (`127.0.0.1:9377/api/position`). After a
957
+ one-time install it works in **your normal browser**, with your bookmarks and your logins.
958
+
959
+ - `src/position-bridge.js` — the receiving end: writes each report to
960
+ `<cache>/position.json` (temp file + atomic rename) and treats anything older than 5 s as absent.
961
+ It goes through a file rather than memory because the CLI is a **different process** and has to
962
+ be able to read it too.
963
+ - `POST /api/position` and `GET /api/position` on the existing chat server, with CORS and a
964
+ Private-Network-Access opt-in (a page on https://bilibili.com talking to 127.0.0.1 needs both).
965
+ - `readPositionOrNull()` now tries the extension report when CDP is not configured or returns
966
+ nothing, so every existing call site gets the new channel for free.
967
+ - `doctor` grew an `extension` row and now treats "either channel works" as ready instead of
968
+ insisting on the debug port.
969
+ - `docs/BRIDGE.zh.md` — step-by-step install guide written for someone who has never heard of a
970
+ manifest file, including the eight failure modes people actually hit.
971
+ - `node watch.mjs install-extension` (and `scripts/install-extension.cmd`) does everything that
972
+ *can* be automated: copies the extension to `%LOCALAPPDATA%\\dsh-watch-together\\extension` so it
973
+ survives moving the repo, puts that path on the clipboard, and opens `edge://extensions`.
974
+ The last three clicks cannot be automated — Chrome 137 removed `--load-extension` from branded
975
+ builds and extension installs are HMAC-protected, deliberately, because silent install is the
976
+ malware channel. The guide says so plainly instead of pretending otherwise.
977
+ - **The extension now says hello on load** (`POST /api/hello`, persisted as `extension.json`).
978
+ Without it, "extension not installed" and "installed but no video playing" look identical from the
979
+ outside — both are silence. `doctor` and `bridge` can now tell them apart.
980
+ - `extension/welcome.html` opens on install/update: the three verification steps, plus what each
981
+ popup state means. Install is the one moment the user has no idea what to expect.
982
+ - `install-extension` no longer just prints and quits: it keeps the window open and **watches until
983
+ the extension proves it is loaded** (`✓ 扩展装上了`), then until a real position arrives
984
+ (`✅ 全部完成`). One double-click now covers install *and* verification, and the window cannot
985
+ vanish mid-instruction because it is still polling.
986
+ - `node watch.mjs install-extension --steps` re-prints just the three clicks without touching any
987
+ file — for when the window scrolled past or was closed.
988
+ - `install-extension` now waits for Enter when it has a TTY, so the instructions cannot vanish
989
+ before being read (running it from an IDE "Run" button has no TTY, which is the common way this
990
+ happened).
991
+ - `ensureWatchBrowser(port, url)` now passes the film through: with `launchBrowser: true`, saying
992
+ "陪我看这个 <link>" opens the dedicated window **at that link** instead of the Bilibili homepage.
993
+ That is the zero-install path — no extension, no port config, at the cost of watching in that
994
+ window. Both paths coexist; neither requires the other.
995
+ - `node watch.mjs bridge` (and `scripts/bridge.cmd`) starts just the position receiver and says
996
+ "✓ 收到上报" on the first report. Without it, a user who installs the extension and immediately
997
+ looks at the popup sees "not connected" — because the server only runs during `watch_together`
998
+ or `watch.mjs chat`, and concludes the install failed.
999
+
1000
+ ### Added — closing the remaining "no one is listening" dead ends
1001
+
1002
+ - **Idle stop now wakes the model too.** Video-ended and video-changed already did; idle ("no movement
1003
+ for two segments") did not — and since the loop is stopped, nothing polls the chat box afterwards,
1004
+ so anything the user said next went nowhere. Now it wakes and says where it stopped.
1005
+ - **Waiting is polled, not slept through.** The 500 ms tick in the blocking wait now uses
1006
+ `sleepWithChat`, so a message is noticed within ~150 ms instead of up to 500 ms later.
1007
+ - **The tool description now tells the model what an interruption is:** a result carrying `chat` means
1008
+ "answer them first, then call again with the same arguments — the wait resumes, nothing is lost, and
1009
+ the image is already in the cache". Without this the model had no way to know.
1010
+ - **`doctor` distinguishes "nobody is receiving" from "extension not connected".** Both look like
1011
+ silence, and the old wording told the user to reinstall the extension — but if no server is running
1012
+ on 9377 the extension cannot report at all, and reinstalling would have changed nothing.
1013
+ - Stale SMTC-era wording removed from the strings the *model* reads (`input`/`cursor`/`title`
1014
+ descriptions, and the `browser:` line), which still talked about the OS media session.
1015
+
1016
+ ### Added — you can interrupt almost any wait, and it picks up where it left off
1017
+
1018
+ Every blocking wait in `watch_together` can now be interrupted by a message in the chat box, and in
1019
+ all cases the answer is "reply to them, then call again with the same arguments" — the tool resumes:
1020
+
1021
+ - **Building a segment** (8–10 s, longer with ASR) and **filling the lookahead buffer** (up to 4
1022
+ segments serially, 30 s+) — the most pointless kind of waiting, now interruptible.
1023
+ - **Waiting for the video to appear** (`waitForVideo`, up to 2 min).
1024
+ - **Waiting for a condition** (`waitUntil`) and **waiting for the next line** (`nextLine`).
1025
+ - Waiting to the delivery point and `cue` already listened; they now share one watcher (below).
1026
+
1027
+ The interrupted work is **not cancelled**: the storyboard keeps building in the background and lands
1028
+ in the cache, so the follow-up call returns it immediately instead of rebuilding it.
1029
+
1030
+ New `src/interrupt.js`:
1031
+ - `raceChat(promise)` — polls the chat while a slow promise runs; returns `interrupted` with the
1032
+ message, or `done`. Wakes on whichever happens first (the promise settling, or the next poll tick).
1033
+ The first version slept a fixed 500 ms per tick, which added half a second to *every* build —
1034
+ enough that playback passed the delivery point and the blocking wait returned instantly.
1035
+ - `sleepWithChat(ms)` — sleep that can be cut short by a message.
1036
+ - `chatWatcherShared()` — **one watcher for the whole process.** `makeChatWatcher()` baselines at
1037
+ creation time, so a fresh one per wait silently dropped anything the user said while the model was
1038
+ thinking, in the gap between two waits.
1039
+
1040
+ ### Added — it now reacts to what you do mid-video
1041
+
1042
+ Auditing the whole flow against the user's checklist surfaced three gaps where the plugin behaved
1043
+ correctly but **never told the model**, leaving it silent until the user poked it:
1044
+
1045
+ - **Video ended / video changed now wake the model once.** Previously they only stopped the loop, so
1046
+ the model sat blocked on the previous segment with no idea the film was over or had been replaced.
1047
+ - **Large seeks (>60 s, forward or backward) wake the model once** with where the user jumped to and
1048
+ from, with a 3-minute cooldown. Position tracking was already correct — it was the model that had
1049
+ no idea. Rewatching does not re-speak already-spoken segments (no immediate-repeat chatter).
1050
+ - **Only the visible tab reports** (`document.visibilityState`), plus a report on `visibilitychange`.
1051
+ Every tab with a `<video>` reports once per second; with two such tabs open the server received
1052
+ alternating positions and the plugin interpreted it as the user scrubbing wildly.
1053
+ - The simulator can now jump the playhead (`seeks: [{at, to}]`), and there are four new scenario
1054
+ tests covering: video changed wakes once, video ended wakes once, seek forward wakes once, rewatch
1055
+ wakes once and does not re-speak.
1056
+
1057
+ Note the jump check must run **before** the anchor is refreshed — comparing the new reading against
1058
+ the already-updated anchor measures zero. That was the first (failed) version.
1059
+
1060
+ ### Fixed
1061
+
1062
+ - **`bin/watch.mjs chat` ran its own copy of the chat server** — an inline `http.createServer` plus
1063
+ duplicated copies of both HTML templates (92 lines). The copies had drifted: it served `/`,
1064
+ `/widget`, `/api/messages`, `/api/say` but **not `/api/position` or `/api/hello`**. So running
1065
+ only `watch.mjs chat` (instead of `bridge`) meant extension reports hit 404 and the CLI path could
1066
+ never read a position. It also never called `attachSpeechToChat()`, so that chat box showed user
1067
+ messages but no script lines. It now uses `startChatServer()` + `attachSpeechToChat()` like the
1068
+ plugin and `bridge` do, and the duplicated templates are deleted.
1069
+ - **`watch.mjs reply` wrote straight to the stream** with `appendChat('assistant', …)`, so the text
1070
+ appeared in the chat box but was never handed to speech subscribers — a TTS adapter stayed silent
1071
+ while the page showed the words. It now uses `appendAssistantSay()`, which writes the stream *and*
1072
+ emits the speech event, matching what `watch_together({say})` does.
1073
+
1074
+ ### Fixed
1075
+
1076
+ - **The plugin passed the browser's debug port to `ensureChatSession()`**, so the chat server tried
1077
+ to bind 9333 — the port the browser is already using. The bind failed, the error was swallowed,
1078
+ and the chat box silently never came up in DSH. It now uses the chat port (9377) as intended.
1079
+ This also mattered for the extension: that server is where reports land.
1080
+
1081
+ ### Removed — the OS media session (SMTC) backend is gone
1082
+
1083
+ Position used to have two sources: the browser's DevTools port, and Windows' system media controls
1084
+ (read by a bundled `watch_smtc.py`). **SMTC is deleted**, along with everything that only existed
1085
+ because of it:
1086
+
1087
+ - `src/watch-probe.js` (121 lines) and `src/watch_smtc.py` (62 lines)
1088
+ - `src/resolve-playing.js` (153 lines) — it reversed a *title* into a source by searching filenames
1089
+ and then Bilibili. With CDP the page URL is the source, so this whole "guess the film" path is
1090
+ gone (it was also the thing most likely to pick the wrong video)
1091
+ - the `winrt` Python dependency (three packages) and the interpreter search
1092
+ - most of the extrapolation policy in `position.js`: the cap drops 180 s → 60 s, `FRESH_MS`
1093
+ becomes 5 s, and the safety margin now only applies after a *missed* read
1094
+ - `pickSession` / `probePlayback` / `describeStatus` and the `probe` injection point
1095
+
1096
+ Rationale: SMTC's `Position` only refreshes on player events (measured gaps of 143 s and 216 s), so
1097
+ treating it as a live position required extrapolating, and extrapolating over a wrong pause means
1098
+ every later segment is built on a wrong cursor. The benefit — "watch in whatever player you like" —
1099
+ did not survive contact with how it actually behaved.
1100
+
1101
+ What you give up: you now watch inside the dedicated browser window
1102
+ (`scripts/start-edge-debug.cmd`). Chromium 136+ refuses to open a DevTools port on the default
1103
+ profile, so that window necessarily has its own profile and needs a one-time login.
1104
+
1105
+ ### Fixed
1106
+
1107
+ - **`loop.built` / `loop.dur` / `loop.sourceUrl` leaked across films.** Starting a second watch
1108
+ session reused the previous film's duration, so the first read of the new film looked like a
1109
+ "video changed" event and stopped the loop immediately; `built` made prefetch skip segments it had
1110
+ built for the old film. Both are now reset when the source changes.
1111
+ - **`startWatchLoop` used `Date.now()` for the anchor while pricing time off its injected clock**,
1112
+ which made every simulated read look minutes old. It now uses the injected clock.
1113
+ - **The CLI's `pos()` never read SMTC at all**, so the CLI was browser-only even while the plugin
1114
+ had a fallback. Moot now that SMTC is gone, but it is why the tool seemed to demand a special
1115
+ browser.
1116
+
1117
+ ### Removed — dead code trimmed so there is one decision path
1118
+
1119
+ Two functions that duplicated live logic and were never called in production are gone:
1120
+
1121
+ - `dueDecision` (in `src/timer.js`) — a pure "should I speak now" decision that shadowed
1122
+ `position.shouldSpeak`. Nothing in the loop ever called it; only a test exercised the abandoned
1123
+ design. The "pause too long → stop" intent it carried is now not implemented (see note below).
1124
+ - `depthForBuffer` (in `src/batches.js`) — a count-based lookahead that duplicated `windowFor`,
1125
+ which the loop actually uses (position-based, so the invariant holds at every position, not just
1126
+ at segment starts). Its tests were redundant guards of that same invariant.
1127
+
1128
+ Net: 13 tests removed (8 for `dueDecision`, 5 for `depthForBuffer`); `windowFor`'s existing tests
1129
+ already cover "lookahead ≥ N seconds at every position", so no coverage was lost.
1130
+
1131
+ ### Changed — idle auto-stop now also covers a paused-and-abandoned video
1132
+
1133
+ The loop used to only stop itself on "no movement" when the last reading was a *playing* sample
1134
+ (`why === 'recent-refresh'`). A paused video reports a frozen position forever — `estimate` returns
1135
+ `why: 'paused'`, never stale — so pausing and walking away left the loop polling indefinitely. The
1136
+ idle check now also fires on a frozen *paused* position, after the same `2 × segment` grace period,
1137
+ and wakes you with "停了一会儿" so you can resume by calling `watch_together` again.
1138
+
1139
+ ### Fixed — voice adapter no longer hard-codes a voice
1140
+
1141
+ `examples/voice-edge-tts/index.mjs` used to fall back to `zh-CN-XiaoxuanNeural` when
1142
+ `~/.dsh/tts.json` had no `voice`. That baked one person's voice into the example, so shipping it
1143
+ would have dragged that choice into everyone's install. It now falls back to the neutral
1144
+ `zh-CN-YunxiNeural` and prints a one-line hint telling you to set `voice` in `~/.dsh/tts.json`
1145
+ (e.g. `"voice": "zh-CN-XiaoxuanNeural"`). Nothing about the voice ships in the package — you mount
1146
+ the adapter via `~/.dsh/voice.json` (or `DSH_VOICE_ADAPTER`) and pick the voice yourself.
1147
+
1148
+ ## Earlier — 0.1.0 draft, never published (2026-10-30)
1149
+
1150
+ The first cut as a standalone plugin. It was not published under this number; the version line now
1151
+ starts at 0.0.7, so this section is kept purely as a record of how the feature set got here. The feature existed inside `dsh-video-storyboard` 0.4.x as
1152
+ `src/watch/`; it is now its own package with its own entry point, its own version, and a one-way
1153
+ dependency on `dsh-video-storyboard`.
1154
+
1155
+ ### Added
1156
+
1157
+ - **`watch_together`** — watch a video together with a text-only agent. Instead of one whole-film
1158
+ storyboard, it follows the user's **real playback position** and hands over one segment at a time,
1159
+ `lead` seconds before the segment ends. The next segment is built while the user is still watching
1160
+ the current one, so delivery is perceived as instant (4/4 measured deliveries at 0.0 s).
1161
+ - **Ramp-up start.** Segment lengths grow `[60, 120, 180, 240]` → `segment`, so the first line lands
1162
+ around 45 s instead of after a full 5-minute batch. `ramp: []` disables the ladder.
1163
+ - **Double buffering.** `depth: 2` keeps the current batch plus the next one built, and starts the
1164
+ one after that while the user watches.
1165
+ - **Playback position straight from the page.** It reads `<video>.currentTime` over the DevTools
1166
+ protocol, so the value is exact, and the page URL becomes the source (`file:///D:/x.mp4` → local
1167
+ path) — no searching, no downloading, no asking. Never released with the OS media session (SMTC)
1168
+ backend documented below: SMTC's `Position` only refreshes on events, so using it as a live
1169
+ position meant extrapolating, and a wrong position poisons every later segment.
1170
+ - **Honest confidence levels.** The plugin reads every 15 s and extrapolates in between, which is
1171
+ normal and self-correcting. What it refuses to do is keep extrapolating after it has *missed* a
1172
+ read: past 20 s it demands an extra 5 s of margin before speaking, and past 60 s it stops
1173
+ guessing and asks for `cursor` instead.
1174
+ - **The speech seam, with no engine.** `src/speech-bus.js` exposes `onSpeech(handler, { voice })`,
1175
+ `emitSpeech()`, `speechEvents()` and `lastSpeech()`. The plugin ships no engine, no default
1176
+ adapter and no voice parameters; `watch_together` results carry `speech: [{ at, text, state }]`
1177
+ and the loop emits `state: 'due'` when a line is actually due.
1178
+ - **Adapters loaded by path.** `~/.dsh/voice.json` `{ "adapter": "<path or module>" }` (or
1179
+ `DSH_VOICE_ADAPTER`) is `import()`ed once at startup; the module exports `attach(api)` and returns
1180
+ a detach. Nothing is bundled, and a failure only logs a warning.
1181
+ - **`examples/voice-edge-tts/`** — a working adapter (edge-tts → `ffplay` → system-voice fallback).
1182
+ It prints `[voice 03:11.4] <line>` to stderr for every line that comes due; that log, not the
1183
+ audio, is what you want when checking *when* text fires.
1184
+ - **One text stream for the chat box.** `chat.jsonl` carries `line` (scripted), `assistant`
1185
+ (interjection) and `user`, with `say: true` marking the speakable ones.
1186
+ `watch_together({ say: "…" })` is how the model gets its interjection in — the plugin cannot read a
1187
+ normal reply. `attachSpeechToChat()` subscribes with `voice: false`, so a display-only consumer can
1188
+ never silence the loop.
1189
+ - **A localhost chat page** (`/` full view, `/widget` capsule) with an `/api/messages` long-poll and
1190
+ an `/api/say` callback. This is the only channel that actually reaches a blocked `watch_together`
1191
+ call — messages typed into the host's own input box are appended to the session log *after* the
1192
+ blocking call returns (measured: 42 s of polling, 0 bytes written).
1193
+ - **`examples/floating-chat/window.py`** — a real floating window without a browser: frameless,
1194
+ always-on-top, translucent, stdlib tkinter only. Reads the same `chat.jsonl`.
1195
+ - **`bin/watch.mjs`** — a CLI shell for sessions that have no `watch_together` tool. It imports the
1196
+ same `src/`, so behaviour cannot drift from the plugin.
1197
+
1198
+ ### Fixed
1199
+
1200
+ - **The CLI imported pre-refactor paths** (`src/browser-time.js`, `src/pipeline.js`, …) that no
1201
+ longer exist, so `bin/watch.mjs` could not even start. All imports now resolve through the
1202
+ `dsh-video-storyboard` package name.
1203
+
1204
+ ### Changed
1205
+
1206
+ - `detachAdapters()` no longer reaches into the bus's private subscriber map; it calls
1207
+ `__resetSpeech()` from `speech-bus.js`.
1208
+ - `watch-run.js` imported `./watch.js` twice; merged into one import.
1209
+
1210
+ ### Known limits
1211
+
1212
+ - **Speaker separation is not attempted.** Measured on the reference machine: per-sentence cam++
1213
+ embeddings split single-speaker material into 6 speakers; demucs pre-separation made no difference
1214
+ (median similarity 0.62 → 0.61); FunASR's `ClusterBackend` returns "one speaker" outright below 20
1215
+ speech segments — short clips are outside its operating range by design.
1216
+ - **Interjection audio can collide with a line already being spoken.** Windows mixes both SAPI
1217
+ instances, so `say` occupies `quiet-until.json` before speaking and `cue` skips lines inside that
1218
+ window (it skips rather than defers — deferring desynchronises from the picture). The remaining
1219
+ gap is the 3–8 s while a line is mid-speech, which cannot be cut short.
1220
+ - **CRLF-less assumption.** The chat page replaces `__PORT__` in the templates per start; changing
1221
+ the port while a browser tab is already open requires a reload.