dsh-watch-together 0.1.1 → 0.2.0

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