dsh-watch-together 0.0.0-stage → 0.1.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +958 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +52 -0
  4. package/README.md +590 -2
  5. package/bin/lines.mjs +202 -0
  6. package/bin/tts.mjs +232 -0
  7. package/bin/watch.mjs +1722 -0
  8. package/cordis.patch.yml +3 -0
  9. package/docs/BRIDGE.zh.md +436 -0
  10. package/docs/CONFIG.zh.md +298 -0
  11. package/docs/VOICE.zh.md +255 -0
  12. package/dsh.plugin.json +12 -0
  13. package/examples/floating-chat/__pycache__/window.cpython-313.pyc +0 -0
  14. package/examples/floating-chat/aec.py +135 -0
  15. package/examples/floating-chat/launch.cmd +5 -0
  16. package/examples/floating-chat/mic.py +398 -0
  17. package/examples/floating-chat/window.py +1094 -0
  18. package/examples/voice-edge-tts/index.mjs +185 -0
  19. package/extension/background.js +96 -0
  20. package/extension/content.js +74 -0
  21. package/extension/icons/icon128.png +0 -0
  22. package/extension/icons/icon16.png +0 -0
  23. package/extension/icons/icon48.png +0 -0
  24. package/extension/manifest.json +34 -0
  25. package/extension/popup.html +38 -0
  26. package/extension/popup.js +57 -0
  27. package/extension/welcome.html +66 -0
  28. package/package.json +87 -4
  29. package/scripts/bridge.cmd +16 -0
  30. package/scripts/check-syntax.mjs +56 -0
  31. package/scripts/install-dev.mjs +149 -0
  32. package/scripts/install-extension.cmd +29 -0
  33. package/scripts/start-edge-debug.cmd +41 -0
  34. package/scripts/sync-dep.mjs +68 -0
  35. package/scripts/watch-e2e.mjs +128 -0
  36. package/scripts/watch-sim.mjs +92 -0
  37. package/src/batches.js +152 -0
  38. package/src/chat-server.js +198 -0
  39. package/src/chat-store.js +329 -0
  40. package/src/chat-view.js +70 -0
  41. package/src/chat.js +35 -0
  42. package/src/floating-window.js +198 -0
  43. package/src/handler.js +261 -0
  44. package/src/index.js +130 -0
  45. package/src/input-surface.js +154 -0
  46. package/src/interject.js +119 -0
  47. package/src/interrupt.js +154 -0
  48. package/src/latency.js +76 -0
  49. package/src/lines-util.js +379 -0
  50. package/src/position-bridge.js +180 -0
  51. package/src/position.js +160 -0
  52. package/src/recap.js +79 -0
  53. package/src/register.js +34 -0
  54. package/src/reply-guard.js +116 -0
  55. package/src/speech-bus.js +192 -0
  56. package/src/speech.js +142 -0
  57. package/src/time.js +16 -0
  58. package/src/timer.js +137 -0
  59. package/src/tool-spec.js +519 -0
  60. package/src/voice-adapter.js +181 -0
  61. package/src/voice.js +33 -0
  62. package/src/watch-actions.js +170 -0
  63. package/src/watch-browser.js +92 -0
  64. package/src/watch-lines.js +459 -0
  65. package/src/watch-loop.js +1032 -0
  66. package/src/watch-material.js +101 -0
  67. package/src/watch-modes.js +198 -0
  68. package/src/watch-run.js +923 -0
  69. package/src/watch-source.js +201 -0
  70. package/src/watch-state.js +194 -0
  71. package/src/watch.js +43 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,958 @@
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
+ ### Fixed — optional services must go through `ctx.get()`
11
+
12
+ `ctx?.attachments?.saveImage` looks like a runtime probe but throws in a real host: cordis's `ctx`
13
+ is a Proxy whose `get` trap **throws** `cannot get property "xxx" without inject` when a service was
14
+ not declared in `inject`. `?.` only guards `null`/`undefined`, not exceptions.
15
+
16
+ All optional-service lookups now go through `serviceOf(ctx, name)` (in `src/timer.js`): it prefers
17
+ `ctx.get(name)` — cordis's documented way to ask for an optional dependency, returning `undefined`
18
+ when absent — and only falls back to property access inside a `try`.
19
+
20
+ ### Liquid-glass window, one stream, and a name you can change (2026-11-01)
21
+
22
+ Reported as: the scripted lines (warm amber, with a "台词" label) and the assistant's replies (cool
23
+ grey, labelled "陪看") read like two different people talking in one stream — and the window itself
24
+ looked like a plain dark panel.
25
+
26
+ **One stream, one look.** `ROLE` now maps `line` and `assistant` to the *same* colours, and the head
27
+ line shows **only the timestamp** — no "台词", no "陪看". Only the user's own messages keep a tint
28
+ (so you can still tell which side you are on).
29
+
30
+ **Timestamps are wall-clock now** (`HH:MM:SS`), for every role. Scripted lines used to show their
31
+ playback position (`01:26.0`) while everything else showed local time — two time bases in one
32
+ stream, so reading it meant converting in your head. Seconds are included because a segment runs
33
+ 2–5 minutes and several messages share the same minute; `HH:MM` alone would make the stamps useless
34
+ for telling them apart. A message with no `at` gets no head line at all (an empty label still eats
35
+ a full line of height).
36
+
37
+ **Liquid glass.** Three things carry the effect, because tkinter cannot blur what is behind it:
38
+
39
+ - **24px+ radius** — and `round_rect` no longer uses `smooth=True`, which renders a 22px radius as
40
+ roughly 14px (it smooths a polygon rather than following an arc). It now samples each corner arc
41
+ directly.
42
+ - **A refractive edge**: a 1px inner highlight along the top, plus an outer border split into a lit
43
+ upper half and a shadowed lower half — what a real piece of glass does.
44
+ - **Slight window transparency** (`-alpha 0.975`, `DSH_WATCH_GLASS_ALPHA` to tune, ≥1 disables).
45
+ The desktop shows through just enough to read as glass without competing with the text.
46
+
47
+ Buttons and the input field are **pills** now (`Pill` class + a Canvas-backed field): a square
48
+ "发送" button next to a 24px-rounded panel was the most obviously un-Apple thing left.
49
+
50
+ **The title is editable.** Click the name in the header, type, press Enter — saved as `name` in
51
+ `~/.dsh/watch-window.json` and restored next launch. Committing uses an explicit `_editing` flag
52
+ rather than `winfo_ismapped()`, which is still `False` on the frame right after `pack()` and would
53
+ silently swallow a fast Enter.
54
+
55
+ **Fixed:** `meta` entries (wake failures, mic status) were falling through to the assistant bubble
56
+ style — a screenful of `[一起看] 叫醒失败` rendered as full-size cards. They now use the grey
57
+ one-line `Meta` row that already existed for exactly this.
58
+
59
+ **Fixed:** the saved geometry was clamped against `sw - 120` instead of the window's own width, so a
60
+ 700px-wide window could be restored 580px off the right edge.
61
+
62
+ ### No more self-made "queued messages", one reminder per interjection, and a hideable window (2026-11-01)
63
+
64
+ Reported as three things that turned out to be one root cause plus two design gaps.
65
+
66
+ **The queue strip.** `wakeSession` delivers through `agent.followup()`, which lands in the host
67
+ inbox's `next-turn`. DSH's `QueueDock` renders **every** row of `next-turn` and does not filter by
68
+ `source.kind` — so the plugin's own instructions showed up in the input box as pending messages the
69
+ user never typed ("插话栏自动出现"). Two consequences fixed here:
70
+
71
+ - **The hangup note no longer goes through `followup`.** Closing the window is still a hangup (clock
72
+ stops, nothing is rebuilt, no lines are spoken), but the explanation is now written into
73
+ `watch.json` and handed to the model on its next tool result (`takeHangupNote`). The watch loop
74
+ already has the model blocked inside an interrupted tool call, so nothing is lost — and the queue
75
+ strip stays empty. `markHungUp(input, env, note)` carries the text; taking it clears it.
76
+ - **`[未回应]` is emitted once per interjection.** It used to be appended to *every* tool result
77
+ until the model answered with `say`, so one message from the user could be read as three separate
78
+ events ("大肥鱼已经重复了"). `noteInterjected` also no longer restarts the clock when the same
79
+ sentence arrives twice inside the 3-minute TTL.
80
+ - **The interjection prompt is two sentences, not a wall of ⚠️.** Same requirements
81
+ (`say` first, `speakNow`, lines in the same call), a fifth of the length — it is rendered in the
82
+ queue strip, so its size is user-visible.
83
+
84
+ ### `window: "hide" | "show"` — put the window away without ending the watch
85
+
86
+ Closing the window means "I am done watching". Hiding it does not: the process stays alive, the
87
+ clock keeps running, lines keep being spoken, nothing is marked as hung up. Reported as
88
+ "如果有其他功能隐藏悬浮窗会更好".
89
+
90
+ - `watch_together({ window: "hide" })` writes `hidden: true` into `~/.dsh/watch-window.json`;
91
+ `window.py` polls its config every 200 ms (`_sync_visible`) and does `withdraw()` / `deiconify()`.
92
+ `withdraw` rather than `iconify`: an always-on-top floating window should leave no taskbar entry
93
+ behind.
94
+ - `openFloatingWindow` clears `hidden` **before any early return**, so a window that was hidden when
95
+ the process died does not come back invisible.
96
+
97
+ ### Two-track prefetch (2026-11-01) — subtitles no longer wait for the pictures
98
+
99
+ The picture side is the slow one: a segment costs a download plus a scan (10–20 s, 20–90 s for the
100
+ first), while the text for the same window arrives in a few seconds (site CC: instant; local ASR
101
+ RTF 0.019 ≈ 6 s per 5-minute segment). They used to be produced and delivered as one package, so
102
+ the text sat in the slow batch's shadow. Now they are two independent tracks over the **same**
103
+ batch table and the **same** look-ahead window.
104
+
105
+ - **New subtitle track** (`transcribe` → `dsh-video-storyboard/transcript-pass`). Mirrors the picture
106
+ track line for line: same `plan.indexAt` / `windowAt`, its own `transcribed` set. "Whoever's window
107
+ is full stops first" falls out of `find()` returning `undefined` — no extra rule.
108
+ - **Two-part delivery.** When the text lands before its pictures, it is sent on its own
109
+ (`[一起来看·台词] 03:00–06:00` + one timestamped sentence per line). When the picture batch
110
+ arrives later it is built with `omitTranscript`, so the cells carry only times and the sentences are
111
+ not repeated (measured: 17k vs 26k tokens per 2 hours, +50% when repeated).
112
+ - **`feedTranscriptLeadMs`** (default 0 = send as soon as it lands). Raise it to ~20000 if the
113
+ two-part delivery feels chatty and you would rather wait for one combined message.
114
+ - **`transcriptTrack: false`** turns the whole track off.
115
+ - **Failures don't sink the loop.** A failed transcription is not marked as done, so the next tick
116
+ retries; three failures in a row blacklist that segment for 10 minutes (a missing ASR service
117
+ should not be hit every 2 seconds). The picture track is never blocked by it.
118
+ - **Cross-track timestamps now share one clock.** `transcribedAt` / blacklist times were stamped with
119
+ `Date.now()` while the tick compares against the injectable `deps.now()`; the difference was
120
+ negative by a trillion milliseconds, so the "skip for 10 minutes" and "wait N ms before feeding"
121
+ gates were both permanently bypassed (feeding never fired at all).
122
+
123
+ ### Experience pass (2026-11-01) — the minutes spent staring at nothing
124
+
125
+ Same code, same contract; what changes is what the user sees (or hears) while waiting.
126
+
127
+ - **A slow build now says something.** The first batch of a film needs a download plus a scan
128
+ (20–90 s) and a tool call cannot speak — so the window stayed empty and the only signal was
129
+ silence. After 4 s of building (`DSH_WATCH_SLOW_BUILD_MS`) one `meta` line is appended to the
130
+ stream: 「正在取 03:00–06:00 这一段…」. Fast segments write nothing.
131
+ - **The measured latency is finally used on the main path.** `latency.js` has been calibrating
132
+ "read position → result ready" for a while, but only the background clock (`shouldSpeak`) spent it;
133
+ the blocking call still waited until `segment end - lead`, so on the same machine the clock spoke
134
+ early and the tool call spoke late. `deliveryState` now uses `lead + aheadSeconds`, while the text
135
+ still reports `lead` (what is pulled earlier is the work, not the sentence).
136
+ - **Calibration only counts deliveries.** Not-yet calls take tens of milliseconds and are not samples;
137
+ recording them dragged the EWMA towards zero (and wrote `latency.json` on every poll).
138
+ - **The last batch is delivered at the tail.** The final segment's due point is `end - lead`, which for
139
+ the last batch sits past the end of the film — the position never reaches it, so the user watched
140
+ the ending and got nothing. Reaching/passing `dur - 1` now counts as due.
141
+ - **`speech` only lists lines that are still ahead.** It used to echo the whole draft, including the
142
+ lines the same call had just pruned as past — the model read them as "still going to be spoken".
143
+ - **Delivery guidance trimmed ~45%** (≈1150 → ≈640 chars). It is resent every batch; the loop/pacing
144
+ rules already live in the tool description, so only the hard rules stay here: write the lines,
145
+ no spoilers, one sentence, `say` is the only visible channel.
146
+
147
+ ### Reading pass over the loop (2026-11-01) — six real bugs, one hot path
148
+
149
+ No new features. Everything below was found by reading the code against its own comments and then
150
+ reproducing it; each fix carries a regression test that fails on the old code.
151
+
152
+ - **`lastDelivered: null` was read as batch 0.** A delivery blocked by the "no lines yet" gate writes
153
+ `lastDelivered: null`, and `Number(null)` is `0` — exactly the first batch's start. That batch then
154
+ counted as already delivered forever: `wait: true` woke up and answered "already delivered", image
155
+ and manifest never handed over. Empty now stays `NaN`.
156
+ - **Same film, two URL forms → the loop restarted.** `samePlan` compared the raw `input` string, but the
157
+ extension reports `…/BV1g3xN6hEuw/?trackid=…&spm_id_from=…` while the model usually holds the clean
158
+ link. Every second call therefore looked like a new source, wiping `spoken` and re-waking segments
159
+ that had already been delivered. It now compares `sessionKey()`.
160
+ - **`dur: null` became `0 s` on the bridge path.** `Number.isFinite(Number(s.dur))` passes for `null`,
161
+ so a report without a duration set the baseline to 0; the next real reading (600 s) then differed by
162
+ more than a second and was judged "video changed" — the clock stopped mid-film. `num()` in
163
+ `position-bridge.js` and the baseline update now treat empty as empty.
164
+ - **`waitForVideo` lost the hangup.** The input surface is prepared once (`prepared ??=`), and the
165
+ early pre-warm for `waitForVideo` passed no arguments — so `input`/`open` never reached it. Without
166
+ `input` the recorded hangup could not be matched, the window was re-opened, and the call went off to
167
+ wait for a video instead of returning `[hangup]`.
168
+ - **`dueLine` rewrote `watch.json` on every tick.** Its `dirty` flag was shared across segments: once one
169
+ batch had pinned its un-timed lines, every later batch was written back unchanged — a full state write
170
+ every 2 s for the rest of the film. The flag is per segment now.
171
+ - **`waitUntil` / `waitForRefill` lied about why they stopped.** Breaking out because the user paused (or
172
+ the film ended) still produced "waited to the cap". The text now names the real reason.
173
+
174
+ Hot path, same area:
175
+
176
+ - `cachedCues()` re-read and re-parsed the whole subtitle file on every tick (`dueLine` asks several
177
+ times per tick). It is memoised on `path + size + mtime` now, and returns the **same array** so that
178
+ `makeLagFn`'s memo can be keyed on array identity. `makeLagFn` additionally sorts once and looks up
179
+ by binary search instead of a linear scan of every cue. 2000 cues × 5400 lookups: **66.7 ms → 0.8 ms**
180
+ (×83), and the disk read/parse per tick is gone.
181
+ - `lines-util.js` had its own `cacheDir()` that fell back to `~/AppData/Local` on every platform, so on
182
+ Linux/macOS the subtitle cache landed in a directory that does not exist; it now uses the storyboard's
183
+ `cacheDir()`. `findCachedMedia()` likewise uses `tmpdir()` instead of `LOCALAPPDATA/Temp`.
184
+ - Dead exports removed: `plan.starts` (a 513-element array allocated on every `makePlan`),
185
+ `legacySessionKey`, `wasWritten`, `MATERIAL_PARTS`. The input surface failing to start no longer fails
186
+ the whole call — it is reported in the result instead.
187
+
188
+ Three rounds on 2026-10-31. The through-line: the plugin knew something, and the model (or the user)
189
+ never found out — plus one window that needed to look like something people want to keep on screen.
190
+
191
+ ### Long-video recap — merged, but opt-in
192
+
193
+ PR #2, after one round of review. Its first shape prepended a 420-character `[前情]` to **every**
194
+ delivery, partly built from the model's own scripted lines: second-hand context in a package whose
195
+ contract is "raw material only — never retell what the user just watched", at ~200 tokens per
196
+ segment, with no evidence it helped.
197
+
198
+ What shipped instead: off unless `recap: true` or `DSH_WATCH_RECAP=1` (`recap: false` beats the env
199
+ var); only **cached subtitle sentences**, never the model's lines; `recapSegments` 1–3 (default 2),
200
+ `recapMaxChars` 80–1200 (default 420); never reads past the current segment, never trims the live
201
+ transcript, no ASR, no network. Whether it actually reduces retelling is still **unmeasured** — it
202
+ stays opt-in until somebody measures it.
203
+
204
+ ### Observability: `statusOnly` can now answer "why is it slow"
205
+
206
+ Promised in issue #4. `pos + reason` says *what* the clock thinks, not *where it is stuck*.
207
+
208
+ - `segment { index, from, to, delivered, total }` — which batch, its bounds, how many were delivered
209
+ this session, how many the film has (`total` is `null` when the duration is unknown). The last batch
210
+ index is taken at `dur - 1 ms`, because a duration that lands exactly on a boundary would otherwise
211
+ report one batch too many.
212
+ - `speech { queued, lastLateSec, busyUntil }` — lines still waiting, how late the previous line was
213
+ (from `dueLine`'s new `meta: true`, which also keeps the plain-string return for old callers), and
214
+ when the serial voice engine frees up.
215
+ - `build { inflight, cached, lastMs }` — which batch is being built, how many are cached, how long the
216
+ last build took. The cache is passed into the loop for reporting only; it never influences a decision.
217
+ - `queued` needs a disk read, so it is filled in `statusOnly` only, and a failure there is reported as
218
+ `speech.queueError` instead of being swallowed (the first version of this swallowed a `ReferenceError`
219
+ from a missing import and looked exactly like "there are no lines").
220
+
221
+ ### The floating window, rebuilt
222
+
223
+ "这个悬浮窗太丑了" — fair. The old one was a borderless frame with a `Text` widget that painted
224
+ role-coloured **full-width stripes**, on a window Windows stretched from 96 dpi, reading the whole
225
+ `chat.jsonl` every 200 ms.
226
+
227
+ - **Real bubbles.** Each message is its own rounded card (Canvas background + wrapped Label), sized
228
+ to its content: script lines in amber with a left rule, the model in slate, the user's own words
229
+ right-aligned in blue. Above each one, a muted line saying who and when (`台词 04:12.3` for a
230
+ scripted line, `我 21:16` for chat).
231
+ - **Per-monitor DPI awareness** before the window exists, and every size/font derived from the real
232
+ scale factor. Unaware Tk windows are bitmap-stretched at 125/150%, which reads as "blurry and wrong".
233
+ - **Rounded window** via `-transparentcolor` (Windows only; falls back to square corners), a 1 px
234
+ border, and a hand-drawn 6 px scrollbar that only appears when the list actually scrolls.
235
+ - **Does not steal focus.** `focus_force()` at startup meant pressing space to pause the video landed
236
+ in the chat box; now the entry only takes focus inside the window.
237
+ - **Does not fight your scrolling.** New lines auto-scroll only if you were already at the bottom.
238
+ - **Incremental read.** Only the bytes appended since the last tick are parsed, and the first paint
239
+ replays just the last 60 entries.
240
+ - Resizable from the bottom-right grip; position and size persist in `~/.dsh/watch-window.json`.
241
+
242
+ ### Stop when the signal says stop: hangup, dead source, switched video
243
+
244
+ Reported as "换片或者我都关浏览器了还在念台词" and "关了悬浮窗 AI 还是会自动调出来,根本不会自动结束".
245
+ Both were the same shape: the plugin knew the source was gone, and kept talking anyway.
246
+
247
+ - **Speech now requires a believable position.** The line queue only fired when the position was
248
+ `fresh`, or `extrapolated` within `SAFETY_AFTER_MS` (20 s — the normal gap between probes).
249
+ Before, the only thing excluded was `paused`; `estimate()` happily extrapolates a dead source
250
+ forward and `pos` stays finite, so closing the browser kept reading lines out for minutes.
251
+ Nothing is spoken on an `unknown` position, and the position-unknown give-up dropped from
252
+ 10 min to 5 min (the watch should not sit there pretending).
253
+ - **Closing the floating window is a hangup, treated like an interjection.** The window is the only
254
+ way to talk mid-watch, so closing it means "I'm done":
255
+ - the clock stops and **really wakes the model** — `wake:false` (the default) used to silence this
256
+ too, because it shared the `wake` path with the segment-end reminder. User actions (hangup,
257
+ video changed, video ended, seek, unreadable position, high-frequency mode) now use a separate
258
+ always-real channel (`wakeSignal`), and the message says **do not call watch_together again and
259
+ do not read out any more lines**;
260
+ - the guard is stored on the loop and can be turned on later (`resumed` path used to freeze it,
261
+ so a window opened by an earlier call was never guarded);
262
+ - the next tool call **does nothing at all**: no frame, no clock, no window (`[hangup]` result).
263
+ `sameWatch` previously required `args.input`, which the model never sends — so every call looked
264
+ like "a new watch" and re-opened the window the user had just closed.
265
+ - `wakeWithRetry` called an undefined `note()` in its failure branch (a `ReferenceError` swallowed by
266
+ the ticker). Real wakes can fail, so it was reachable; now it records into `loop.logs`.
267
+
268
+ Tests: 247 pass, +4 in `test/hangup-guard.test.mjs` (dead source sends nothing, live source still
269
+ speaks, hangup wakes with the right wording, post-hangup call is inert).
270
+
271
+ ### Interjections: speak first, then look
272
+
273
+ Reported as "它一声不吭先去 zoom,回来才说话". The root cause was not the model: a normal reply
274
+ never reaches the floating window — only `say` does and only `say` is spoken. So "think, then look,
275
+ then answer" was, from the user's side, complete silence for tens of seconds.
276
+
277
+ - One wording, one place (`src/interject.js`) for all five entry points (during a build, during the
278
+ lookahead fill, during a blocking wait, `waitUntil`, `nextLine`). It now says exactly what to do:
279
+ `watch_together({ say: "我看一眼", speakNow: true })` — one call, words written before any frame
280
+ is built. `lines` and `say` can ride in the same call, so "台词优先" no longer means "stay silent".
281
+ - Unanswered interjections are **tracked**: the next tool result ends with `[未回应] …你还没回`,
282
+ until a call actually carries `say` (expires after 3 min). Previously the reminder existed only
283
+ inside the message that woke the model, which it had already scrolled past.
284
+ - `waitUntil` / `nextLine` called a function that **did not exist** (`chatResult`) — an interjection
285
+ during either wait threw `ReferenceError` and the tool failed. Defined, and it reuses the same wording.
286
+ - Waiting for a video to appear returned a result **without `text`**, which the host's `output.schema`
287
+ requires. That path now returns a proper result.
288
+
289
+ ### Reply vs. scripted line: 12-second guard
290
+
291
+ Reported as "说话和插话的回复离太近,把后面那句改一下". Two lines spoken back to back on a serial
292
+ TTS chain means the second one either drifts or is dropped by the adapter (queue > 3.5 s → `skipped`).
293
+
294
+ - `say` now marks the voice engine busy for its full spoken length (`src/reply-guard.js`), so the
295
+ loop stops feeding scripted lines while a reply is still playing. Previously only the loop's own
296
+ lines updated that clock — a reply was invisible to it.
297
+ - Lines scheduled within 12 s of a reply are **withdrawn from the batch and handed back** to the
298
+ model (`[lines·太近]`) with instructions to rewrite them around what was just said, or drop them.
299
+ Withdrawn, not silently deleted: the user asked for "改一下", not "少一句".
300
+
301
+ ### Switching videos is noticed in ~2 s, not ~15 s
302
+
303
+ - The per-tick bridge read (every 2 s) now does the switch / end-of-video / big-jump checks, and
304
+ keeps the `dur`/`url` baseline up to date. Before, all three lived in the 15-second CDP probe
305
+ branch only, so a switch could go unnoticed for a quarter of a minute — while the clock kept
306
+ computing segment boundaries against the old film.
307
+ - The blocking wait in `watch-run` now compares each read against the film it started with and
308
+ returns `[video-changed]` immediately. **This was the only reliable path**: the loop's wake goes
309
+ through `followup()`, which is delivered *after* the current tool call returns — and that call was
310
+ busy waiting.
311
+ - `sourceSwitched()` centralises the test, and `Number(null) === 0` is explicitly guarded: a
312
+ not-yet-known duration used to look like a "0-second film" and stop the watch instantly.
313
+
314
+ ### Cold start: don't wait a full minute for a video we can already identify
315
+
316
+ - The extension only reports while the tab is **visible** — and "一起看" is usually typed in another
317
+ window. The position went stale after 5 s, the plugin concluded "no video", and sat in the 60 s
318
+ wait. It now falls back to a **stale** sample (up to 2 min) to identify the film, marks the
319
+ position `stale`, and lets the next fresh reading correct it.
320
+ - Automatic waiting (no `waitForVideo`) dropped from 60 s to **20 s**; explicit `waitForVideo: true`
321
+ stays at 120 s.
322
+ - `probeBrowser()` is skipped when the extension already reports: one probe is `listTargets`
323
+ (1.2 s) plus up to 8×1.5 s of CDP round-trips — pure overhead for a `browser:` line the extension
324
+ just answered. The line now reads `browser: extension reporting <title> playing 03:20`.
325
+
326
+ Tests: 243 pass (`node --test`), 6 of them new in `test/interject-reply.test.mjs`.
327
+
328
+ ## [0.0.7] — 2026-10-31 (first release)
329
+
330
+ The first published version. One tool, `watch_together`: it follows the user's real playback
331
+ position, hands the model one storyboard + transcript per segment just before that segment ends,
332
+ and speaks the scripted lines at the second they belong to.
333
+
334
+ **Licence: Apache-2.0** (the package was developed under MIT and switched before the first
335
+ public release, to match `dsh-video-storyboard`). `LICENSE` is the full text, `NOTICE` states
336
+ what the project deliberately does **not** do — no hosted video, no uploaded position, no DRM or
337
+ paywall bypass, no bundled TTS engine.
338
+
339
+ ### Repo hygiene — the extension's manifest and icons were never committed
340
+
341
+ `.gitignore` carried `manifest*.json` and `*.png` (meant for CLI artifacts). Those two rules also
342
+ swallowed `extension/manifest.json` and `extension/icons/*.png`, so a clone would have shipped an
343
+ extension **with no manifest** — completely broken, and nothing would have failed until someone tried
344
+ to load it. Both are now force-added, and the ignore rules are anchored (`/*.png`, `/*.meta.json`) so
345
+ they can only ever catch files at the repo root. Also: `* cookies*.txt` (a pattern with a space, which
346
+ never matched anything) is gone, `__pycache__` is out of the npm tarball via a new `.npmignore`, and
347
+ `npm test` no longer requires the sibling `dsh-video-storyboard` checkout — it falls back to the
348
+ installed copy, so a clone can run the suite.
349
+
350
+ ### Docs — one page per service, and the stale one is gone
351
+
352
+ `docs/WATCH.zh.md` still explained how to configure things around the **OS media session (SMTC)**,
353
+ which was deleted a while ago: wrong rationale, wrong `confidence` values, wrong defaults. Deleted.
354
+ Replaced by [`docs/CONFIG.zh.md`](docs/CONFIG.zh.md): ffmpeg → yt-dlp + cookies → subtitles/ASR →
355
+ browser extension (9377) → debug port (9333) → voice (`voice.json` + `tts.json`) → floating window →
356
+ cache locations → a one-page troubleshooting table. Every entry says **what breaks if you skip it**.
357
+
358
+ `README.md` got a 30-second start, a "what to configure" table, a corrected parameter table
359
+ (`depth` is auto-by-time now, `lookahead` was missing), a CLI table that matches the 15 real
360
+ subcommands, a privacy note for the extension, and a dev section. `docs/VOICE.zh.md` gained
361
+ `state: 'skipped'` and a correction: `at` is a **playback second**, not a wall-clock timestamp.
362
+
363
+ ### `doctor` — three levels, because "not configured" is not "broken"
364
+
365
+ `FAIL` used to be printed for things that are merely "not set up yet": a missing cookie file (only
366
+ needed for Bilibili), a closed debug port (the extension is the recommended channel), an extension
367
+ that is loaded but has no video playing. First-run users read that as "something is broken" and went
368
+ to reinstall the extension. Now: **OK / WAIT / FAIL**, only `plugin` and `ffmpeg` are fatal, and when
369
+ the extension has checked in but nothing is playing, `doctor` says `READY — 播个视频就能读到位置`
370
+ instead of "both position channels are down".
371
+
372
+ ### Performance — the chat watcher no longer re-reads the whole log every 150 ms
373
+
374
+ The blocking-wait loop polls `chat.jsonl` every 150 ms. Each poll re-read `readChat()` and parsed
375
+ every line, so a two-hour session (thousands of entries) was decoding hundreds of KB several times a
376
+ second, and getting slower the longer the session ran. `makeChatWatcher()` now keeps a byte offset
377
+ and reads **only what was appended since last time** (falling back to a full re-read if the file
378
+ shrank, i.e. it was cleared). Measured on a 5000-line log: **0.061 ms per poll, independent of file
379
+ size**. `appendChat()` also stopped parsing the whole log to keep `at` monotonic — it reads the last
380
+ 4 KB instead.
381
+
382
+ ### Tool description — pacing is now a rule the model can follow
383
+
384
+ `watch_together`'s description tells the model to keep lines **≥ 6 s apart** and why: speech is
385
+ serialized, so a denser draft is thinned at runtime (engine busy → next line held; past the late
386
+ grace → dropped). The three previous rounds of "台词太早 / 太密" all came from the model not knowing
387
+ this budget.
388
+
389
+ ### Fixed — speech piled up in the engine queue, and an interjection could no longer break a blocked wait
390
+
391
+ Two reports in one message: "吐字太快,台词会挤到一起,只有上一句念完才到下一句,话太密会导致语音越来越
392
+ 滞后" and "悬浮窗插话不能让他从等待中出来 —— 这个功能之前是好的".
393
+
394
+ **The voice queue.** `examples/voice-edge-tts` chains every `due` event onto an unbounded serial promise
395
+ ("two lines never overlap"). Lines are now scheduled at the right second, so when they arrive faster
396
+ than the engine can speak them the chain simply grows: speech drifts further from the picture with
397
+ every line, and the caption (written on `spoken`) drifts with it.
398
+
399
+ - `src/watch-loop.js` — the clock now keeps a **voice budget**: after handing out a line it records
400
+ `voiceBusyUntil = now + speechSeconds(len)` and will not hand out the next one while the engine is
401
+ still talking. A line that misses its window by more than the late grace is dropped by `dueLine`
402
+ as usual: **speak one line less rather than one line later**.
403
+ - `src/speech.js` — `speechSeconds(chars)`: full spoken duration (`0.35 + chars/5`, 0.8–30 s).
404
+ `speechLag()` stays as it was — that one answers "when may I start talking", this one answers
405
+ "how long is the engine busy".
406
+ - `examples/voice-edge-tts` — safety net: if a queued line has been waiting more than 3.5 s it is
407
+ **abandoned** (logged) instead of spoken, and the queue empties immediately.
408
+ - `src/speech-bus.js` / `src/chat-store.js` — a fourth state, `skipped`: the adapter reports that it
409
+ gave up on a line, and `attachSpeechToChat` cancels the pending fallback timer for it. Without this
410
+ the 2.5 s fallback would paint a caption for a line that was never spoken.
411
+
412
+ **The interjection.** `chat.jsonl` is a **consuming** channel: `poll()` marks a message read. The
413
+ blocking wait and the watch loop share one watcher, and the loop's handler is `followup()` — which
414
+ cannot interrupt a session that is sitting inside a tool call (the message is only processed when
415
+ the turn ends). So whichever polled first decided the outcome, and the loop (every 2 s) sometimes
416
+ won: the interjection was swallowed, the wait's `poll()` never saw it, and the user's "stop, I have a
417
+ question" did nothing until the segment ended.
418
+
419
+ - `src/interrupt.js` — `enterChatWait()` / `chatWaiterCount()`: whoever is blocking on purpose
420
+ **owns** the channel. `raceChat()` (storyboard build, prefetch) registers too.
421
+ - `src/watch-loop.js` — `wakeOnChat` is skipped entirely while `chatWaiterCount() > 0`. The wake path
422
+ still works when the model is idle (no waiter), which is its whole purpose.
423
+ - `src/watch-run.js` (the `wait: true` loop), `src/watch-modes.js` (`waitUntil` / `waitForRefill` /
424
+ `nextLine`), `src/watch-source.js` (`waitForVideo`) — all register as waiters for the duration of
425
+ their loop.
426
+
427
+ Tests: `test/lines-timing.test.mjs` (engine busy → next line is not handed out; the overdue one is
428
+ dropped), `test/chat.test.mjs` (`skipped` writes nothing, not even the fallback),
429
+ `test/interject-anywhere.test.mjs` (the loop must not consume while a waiter is active; counter
430
+ cannot go negative).
431
+
432
+ ### Fixed — scripted lines came out like a machine gun, and minutes before the picture
433
+
434
+ Reported as: "台词出现时间早了很多,而且和机关枪一样突突突一下出来一大堆,时间点都比视频早了".
435
+
436
+ The line queue is ordered by `at` (the second of the video this line is *for*) and fired by playback
437
+ position, so the pacing is only as good as the `at` values. When a line was written **without** `at`
438
+ (the model wrote prose only), `pinTimes()` decided when it would be said — and it took *the first N
439
+ subtitle sentence starts of the segment*. Sixteen lines written for a 3-minute segment were therefore
440
+ all packed into its first 62 seconds (181.6 → 244.2, measured on the live queue), i.e. one every
441
+ 2–3 seconds: the clock ticks every 2 s and hands out at most one line per tick, which is exactly the
442
+ "machine gun". The last 14 of them ran one to two minutes ahead of the picture they describe.
443
+
444
+ - `src/watch-lines.js` `pinTimes()` — each line now aims at its **even share of the segment**
445
+ (`from + i*size/n`) and snaps to the nearest subtitle start within half a slot, so the queue is
446
+ spread over the whole segment instead of stacked at its head. Falls back to the even share when no
447
+ start is close enough, and **never goes backwards** (the old tail fallback could emit 152.8 → 150).
448
+ - `src/watch-lines.js` `dueLine()` — pinning uses **the segment that line belongs to** (`sizeOf`),
449
+ not the segment the user happens to be in. With the 1/2/3/4/5-minute ramp, a 60-second slot pinned
450
+ with a 300-second size put its last lines outside the segment entirely.
451
+ - `src/watch-lines.js` `saveLines()` — `at` given as **subtitle text** was resolved only against
452
+ `recallSegments()`, which is a 4-entry in-process cache (empty in a fresh process, and lines are
453
+ usually written in a different turn). A miss silently became "no `at`", i.e. the head of the
454
+ segment — the other half of "the line is way too early". Now it reads the on-disk
455
+ `subs-<key>.json` cache first, then falls back to memory, then to a fuzzy match (≥60 % of the
456
+ characters), and only then warns.
457
+ - `src/watch-run.js` — the delivery note pruned "past" lines with `Number(l.at)`, and
458
+ `Number(null) === 0`: **every line without `at` was judged as second 0 and deleted** at delivery.
459
+ The note now previews the same pinning the clock will use, so the reported "earliest …" time is the
460
+ real one, and only lines whose *actual* time has passed are dropped (by text).
461
+ - `src/watch-run.js` — the note now lists the landing times it will use (`[lines] 落点:…`) and warns
462
+ when the average gap is under 6 s, instead of leaving the model to guess its own pacing.
463
+ - `src/watch-loop.js` — with the extension as the position source, the anchor is now re-read **every
464
+ tick** (a small local JSON, not CDP). Between the 15-second probes the clock extrapolated blindly,
465
+ so after a pause the lines up to 15 s ahead were spoken **early** — extrapolation is bounded for
466
+ lateness but nothing guarded earliness.
467
+ - `src/latency.js` `aheadSeconds()` — returns 0 instead of `NaN` when `ms` is missing. `NaN` made
468
+ `pos` `NaN`, every comparison false, and `shouldSpeak()` reported "due" for the first unspoken
469
+ segment at every tick.
470
+
471
+ Tests: `test/pin-times.test.mjs` (the 16-line packing regression, monotonic fallback, cues bunched at
472
+ the head), `test/watch-lines.test.mjs` (per-segment size, `at` from the on-disk subtitle cache),
473
+ `test/lines-timing.test.mjs` (a stuck video must not speak the next line early).
474
+
475
+ ### Fixed — the caption appeared before the voice, because it waited on `due` instead of "actually speaking"
476
+
477
+ `attachSpeechToChat` wrote a line into `chat.jsonl` the moment `due` fired. But `due` only means
478
+ "it is time to say this": synthesis still has to happen (edge-tts does a network round trip, then a
479
+ fresh `ffplay` process — 0.6–2 s even for a short sentence). The floating window polls that file, so
480
+ the text was already on screen a beat before anything was heard.
481
+
482
+ Delaying the voice instead (`speechLag`) would align the two, but push the voice further from the
483
+ picture, which is the one thing this plugin cannot trade away. So the **caption** moves:
484
+
485
+ - `src/speech-bus.js` — a third state, `spoken`, plus `emitSpoken(event)` for engines to report
486
+ "audio is starting now". The adapter API gains `emitSpoken`.
487
+ - `src/chat-store.js` — writes on `spoken` when a `voice: true` subscriber exists; still writes on
488
+ `due` when nobody will speak (the zero-dependency path must not go mute); falls back after
489
+ `fallbackMs` (2.5 s, `DSH_WATCH_CAPTION_FALLBACK_MS`) for adapters that never report.
490
+ Pairing is by `at|text`, not by `seq` — `spoken` is a **new** event, so `emitSpeech` gives it a
491
+ new sequence number.
492
+ - `examples/voice-edge-tts` — reports `spoken` right before playback starts (i.e. after synthesis).
493
+ - `examples/floating-chat/window.py` — polls every 200 ms instead of 400 ms; the poll interval is
494
+ the residual "text lags the voice" gap.
495
+
496
+ `test/chat.test.mjs` covers both new paths (waits for `spoken`; falls back when nobody reports, and
497
+ does not write twice if `spoken` arrives afterwards).
498
+
499
+ ### Fixed — scripted lines never reached the chat window without a voice engine
500
+
501
+ `watch-loop.js` consumed the due line inside `if (speechSubscribers() > 0)`. That helper counts only
502
+ `voice: true` subscribers (real engines), while `attachSpeechToChat` — the one that writes lines into
503
+ `chat.jsonl`, which is exactly what the floating window reads — subscribes with `voice: false`.
504
+ So with no voice adapter, or one that failed to load, a scripted line was **never taken from the
505
+ queue at all**: not spoken, not displayed, and the queue silently accumulated.
506
+
507
+ Display and speaking are two separate things. The line is now handed out at its due moment
508
+ regardless: `emitSpeech` delivers it to every subscriber, and only a real `voice: true` subscriber
509
+ counts as "said" (`if (speechSubscribers() > 0) return;` still stops the wake, so nothing changes
510
+ when a voice engine *is* attached).
511
+
512
+ `test/lines-to-chat.test.mjs` covers both sides. The test was checked against the bug: restoring the
513
+ old condition makes the no-voice case fail while the with-voice case still passes.
514
+
515
+ ### Changed — `say` no longer reads as "only to answer an interjection"
516
+
517
+ It always worked at any moment: it writes the sentence into the shared stream and hands it to
518
+ whoever listens for speech, exactly like a scripted line. But the description ended with
519
+ "use it to answer an interjection", which reads as "only after the user speaks". A model follows
520
+ that literally, so the one path for saying something **unprompted** went unused.
521
+
522
+ The description now says any time, and says it explicitly: something in the picture strikes you,
523
+ the user asks something, a thought lands while waiting for the next batch — plus
524
+ "do not wait for the user to speak first". It also states the cost, because that is what makes it
525
+ usable mid-wait: no position read, no frame built, no batch advanced, one round trip.
526
+
527
+ `test/say.test.mjs` pins the wiring — parameter → stream (one `assistant` row with `say: true`) →
528
+ speech event with `origin: 'chat'`, no image, no state advanced. The store layer was already covered
529
+ by `test/chat.test.mjs`; the uncovered part was the parameter entry itself.
530
+
531
+ ### Added — an end-to-end test for "talk while the frame is building"
532
+
533
+ The mechanism already existed (`raceChat(buildSegment(...))` in `runWatchPass`), and
534
+ `test/interrupt.test.mjs` covered `raceChat` itself — but the `built.kind === 'interrupted'`
535
+ branch had **no** coverage. If a refactor ever dropped the wrapper, or `chatWatcherShared()` got
536
+ replaced with a fresh watcher per call, every existing test would still pass.
537
+
538
+ `test/interject-build.test.mjs` builds a segment that takes 1.2 s, writes a user message at 0.2 s,
539
+ and asserts all four things at once: the call returns before the build finishes, it carries that
540
+ exact message, it carries no image, and the build still completes into the cache afterwards.
541
+
542
+ ### Changed — three implicit couplings now have exactly one source each
543
+
544
+ A pass over the module boundaries. Same behaviour except the `lead` fix at the end, which was a
545
+ real bug: the parameter only worked on one of the three paths that used it.
546
+
547
+ - **`handler.js` stopped preparing UI.** The floating window, the chat service and the "where do I
548
+ type" note moved to `input-surface.js` (`createInputSurface()`). `handler` is a router again —
549
+ three exits: quick action, one pass, start the loop. The `widgetNote` variable no longer travels
550
+ from the top of the function to the bottom.
551
+ - **`watch-run.js` has one return shape.** Eleven exits each used to build their own ten-field
552
+ object; now they all call one `pass()` closure. Adding a field is one edit instead of eleven, and
553
+ a branch can no longer quietly forget one.
554
+ - **One segment length.** `watch-state.js` exported `WATCH_SEGMENT = 120` while `batches.js`
555
+ declared `DEFAULT_SEGMENT = 300`; whichever fallback fired first decided how long a segment was.
556
+ `batches.js` is now the only source, and `WATCH_SEGMENT` is gone.
557
+ - **One lead.** The delivery lead was hardcoded in three places: `batches.from()` produced
558
+ `sayAt = to - 15`, `watch-loop.js` passed `lead: 15` to `shouldSpeak`, and only `watch-run.js`
559
+ actually read `args.lead`. Segments no longer carry `sayAt`; `shouldSpeak` computes `to - lead`,
560
+ and `startWatchLoop` takes `lead` from the caller. `lead: 60` now really moves the trigger point
561
+ (checked against a 300 s segment: at 241 s, `lead=15` stays quiet, `lead=60` fires).
562
+
563
+ ### Removed — no more auto-launched browsers, no more browser widget
564
+
565
+ Both were early paths from before the browser extension existed. Neither could produce a position
566
+ for the tab the user is actually watching, so both are gone rather than kept as fallbacks.
567
+
568
+ - **Auto-launching a browser**: `ensureWatchBrowser()` (`launchBrowser` + `waitForPort`), the
569
+ `autoLaunch` flag on `runWatchPass`, the `attachOnly` parameter, and the `launchBrowser: true`
570
+ branch in `~/.dsh/video.json`. The extension already reports `currentTime` every second from the
571
+ page the user is on; opening a second Edge with its own profile never helped that page. When no
572
+ position can be read the tool now asks "how far are you" instead of starting a program.
573
+ - **The browser widget page**: `GET /widget`, `WIDGET_PAGE`, `openWidgetInBrowser()`, `widgetUrl()`,
574
+ and the `documentPictureInPicture` button in the chat page. The input box is the native tkinter
575
+ window (`examples/floating-chat/window.py`); the HTML page stays as a read-only fallback at `/`
576
+ (`chatPageUrl()`), and is never opened automatically.
577
+ - **Dead parameters**: `wakeOnLinesEmpty` (the handler never passed it, so its 30-line branch in
578
+ `watch-loop.js` could never run), `title` (nothing in `src/` or in storyboard read it), and
579
+ `segmentStart()` (every caller uses `plan.segmentAt()`). Parameter count 36 → 34.
580
+
581
+ ### Fixed — interjections used to get swallowed (four different ways)
582
+
583
+ The interjection path was the one place where losing user input was silent: nothing crashed, nothing
584
+ logged, the words just never arrived. All four ways of losing them are now closed, and each one has
585
+ a regression test (`test/cli-interrupt.test.mjs` — the CLI had **no** test coverage before this).
586
+
587
+ - **Between two `cue` runs.** Every `cue` is a fresh process, and the watcher took "however many
588
+ lines exist right now" as its baseline — so anything the user typed while the model was thinking,
589
+ building a segment or replying was never read by anyone. The read position now lives in
590
+ `<watch>/chat-cursor.json`: a `cue` starts from where the last one stopped, and delivers what it
591
+ finds the moment it enters the wait. Baseline is persisted as soon as it is established, because a
592
+ `cue` that hears nothing (the common case) otherwise leaves no cursor for the next one.
593
+ - **Two messages arriving in the same poll.** Both watchers (chat box and host session file) marked
594
+ the whole batch as read and reported only the first, so the second was gone. They now consume up
595
+ to the message they hand over and no further — "reply first, then take the next one".
596
+ - **Wrong conversation.** `findActiveSessionFile()` took the most recently modified session jsonl
597
+ across *all* projects, so a chat in another window could interrupt the watch session. It now
598
+ prefers the project matching the current directory and only falls back to global when that one has
599
+ no active session.
600
+ - **The host writing old messages late.** WorkBuddy flushes a user's message into the session file
601
+ *after* the reply to it. The watcher saw new bytes and treated them as a fresh interjection —
602
+ interrupting the current turn with the message that started it. Messages whose `timestamp`
603
+ predates the watcher are now ignored.
604
+
605
+ Also in this path: interjections heard via the host input box are appended to the chat stream too
606
+ (they used to appear only in `cue`'s stdout, so the page showed a stream with a hole in it); the
607
+ chat page puts the words back in the input box when a send fails instead of losing them; and
608
+ `POST /api/say` answers `ok:false` for requests it did not write, which is what makes that recovery
609
+ possible.
610
+
611
+ ### Fixed — `cue` and `say`
612
+
613
+ - `cue` no longer waits forever when the video changes underneath it. It compared against the
614
+ segment delivery point of the *old* video, and if the new one was shorter, `deliverAt` was a
615
+ position that would never be reached. It now detects a changed URL or duration and exits with
616
+ `VIDEO-CHANGED` (pending lines are saved under the old source), and exits with `REWIND` when the
617
+ user drags the progress bar back more than a minute — the model should hear about that instead of
618
+ sitting on lines written for a position the user left.
619
+ - Two `cue` processes can no longer run at once: a state file saying `blocking` with a **live** pid
620
+ is refused with `BUSY` (exit 1). A dead pid is taken for what it is — the residue of a killed run —
621
+ and does not block anything. `check` mode is read-only and never takes the lock.
622
+ - `check` mode no longer leaves `cue-state.json` at `blocking`, which used to make the next run
623
+ report "last wait was killed externally" for a run that was never waiting.
624
+ - `say` called edge-tts once by hand and then again inside `speak()` (twice the synthesis, and the
625
+ manual attempt passed the raw configured voice, so a SAPI-style name like `Huihui` never matched
626
+ and silently fell back). It now calls `speak()` once, which does the mapping and the fallback.
627
+ - `voices` was advertised in `help` and crashed with `cmdVoices is not defined` when called. It now
628
+ lists the SAPI voices plus whether edge-tts is present and which voice is configured — the first
629
+ place to look when "why am I still hearing the navigation lady" comes up.
630
+
631
+ ### Added — talk instead of type: a microphone button in the floating window
632
+
633
+ `examples/floating-chat/mic.py` is a separate process the window starts from its `麦` button. It
634
+ listens, cuts what you say into utterances with the Silero VAD already sitting in `models-sherpa/`,
635
+ transcribes each one, and writes it into the **same** `chat.jsonl` the typing path uses — so a
636
+ running `cue` picks it up through the interjection cursor and the model answers without anyone
637
+ typing a character. Measured end to end on this machine (i9-12900HX, int8 paraformer):
638
+
639
+ - one model instance ≈ **284 MB** working set, loads in ~2 s
640
+ - a 3 s utterance transcribes in **0.15 s**; a 45 s one in ~1.2–3.3 s (RTF ≈ 0.05, 20× realtime)
641
+ - concurrent transcription barely queues: a 3 s short request takes 0.14 s even while a 45 s
642
+ transcription is running
643
+
644
+ **It runs its own model by default** (`--engine local`), which is the answer to "can ASR run twice":
645
+ yes, and it is cheap. It also means the microphone never waits behind a video transcription. The
646
+ existing service cannot offer that yet — see the note below. `--engine http` shares port 8000
647
+ instead, saving 284 MB at the cost of queuing behind long audio.
648
+
649
+ **It refuses to hear itself.** The agent speaks through speakers; the microphone hears it; without a
650
+ guard that gets transcribed as if the user had said it, and the model answers its own line forever.
651
+ Every utterance is checked against `quiet-until.json` (the same window `say` and `cue` already take
652
+ before speaking) and dropped if the agent is talking.
653
+
654
+ ### Added — acoustic echo cancellation, so the microphone hears you and not the computer
655
+
656
+ `examples/floating-chat/aec.py`: the microphone picks up whatever the speakers are playing, which
657
+ means the video's narration gets transcribed as if you had said it. Since neither `speexdsp` nor
658
+ `webrtc-audio-processing` builds on this machine (no C compiler, no wheels), this is a frequency-domain
659
+ adaptive filter (overlap-save FDAF, power-normalised NLMS) in numpy — one FFT per 32 ms frame.
660
+
661
+ It captures the **loopback** channel (what the computer is playing, auto-detected as the
662
+ speaker/loopback device, never "stereo mix" — that one can contain the microphone too) and subtracts
663
+ the estimated echo from the microphone. On top of that, an utterance whose energy drops below
664
+ `--echo-gate` (default 30 %) after cancellation is discarded outright: that is the hard guarantee
665
+ that pure-echo segments are never transcribed, whatever the filter is doing.
666
+
667
+ Two things that mattered more than the filter itself:
668
+
669
+ - **Double-talk detection cannot compare against the echo estimate.** At startup the filter is zero,
670
+ so the estimate is zero, so "mic > 2 × estimate" is always true, so the filter freezes and never
671
+ converges (first version: 498 frames frozen, 0 dB). It now compares against the **reference**
672
+ signal (Geigel-style), which does not depend on the filter's state.
673
+ - **Measured on a synthetic but honest mixture** (real speech as the video, a different real speech
674
+ segment as you, through a 150 ms-delayed reverberant echo path):
675
+ ERLE **13.6 dB** during echo-only passage; the video's words in the transcript went from **25 % →
676
+ 0 %**, and an 8 s passage with nothing but video audio produced **no transcription at all**.
677
+
678
+ Tunables: `--dt-ratio` (1.4 — mic peak vs reference peak before the filter freezes), `--taps`
679
+ (8192 ≈ 512 ms of reverb tail), `--echo-gate`, `--no-aec`, `--loopback`.
680
+
681
+ Honest limits: it is a software AEC, not magic. The first second or two of your speech, right as the
682
+ filter re-converges after you start talking, is where the damage shows (a few characters in the test
683
+ above). Speaker loudness and room reverb both make it harder. **Headphones remove the problem
684
+ entirely** — with headphones there is no echo to cancel, and everything above is unnecessary.
685
+
686
+ ### Added — a browser extension, so you never open a special window again
687
+
688
+ Position used to require a browser started with `--remote-debugging-port`, and Chromium 136+ refuses
689
+ that flag on the default profile — so users had to keep a second, separate browser window open just
690
+ for watching. That was the whole reason this package felt like it needed a "special browser".
691
+
692
+ `extension/` is an MV3 extension that reads `<video>.currentTime` from the page you are actually
693
+ watching and POSTs it to the plugin's own localhost server (`127.0.0.1:9377/api/position`). After a
694
+ one-time install it works in **your normal browser**, with your bookmarks and your logins.
695
+
696
+ - `src/position-bridge.js` — the receiving end: writes each report to
697
+ `<cache>/position.json` (temp file + atomic rename) and treats anything older than 5 s as absent.
698
+ It goes through a file rather than memory because the CLI is a **different process** and has to
699
+ be able to read it too.
700
+ - `POST /api/position` and `GET /api/position` on the existing chat server, with CORS and a
701
+ Private-Network-Access opt-in (a page on https://bilibili.com talking to 127.0.0.1 needs both).
702
+ - `readPositionOrNull()` now tries the extension report when CDP is not configured or returns
703
+ nothing, so every existing call site gets the new channel for free.
704
+ - `doctor` grew an `extension` row and now treats "either channel works" as ready instead of
705
+ insisting on the debug port.
706
+ - `docs/BRIDGE.zh.md` — step-by-step install guide written for someone who has never heard of a
707
+ manifest file, including the eight failure modes people actually hit.
708
+ - `node watch.mjs install-extension` (and `scripts/install-extension.cmd`) does everything that
709
+ *can* be automated: copies the extension to `%LOCALAPPDATA%\\dsh-watch-together\\extension` so it
710
+ survives moving the repo, puts that path on the clipboard, and opens `edge://extensions`.
711
+ The last three clicks cannot be automated — Chrome 137 removed `--load-extension` from branded
712
+ builds and extension installs are HMAC-protected, deliberately, because silent install is the
713
+ malware channel. The guide says so plainly instead of pretending otherwise.
714
+ - **The extension now says hello on load** (`POST /api/hello`, persisted as `extension.json`).
715
+ Without it, "extension not installed" and "installed but no video playing" look identical from the
716
+ outside — both are silence. `doctor` and `bridge` can now tell them apart.
717
+ - `extension/welcome.html` opens on install/update: the three verification steps, plus what each
718
+ popup state means. Install is the one moment the user has no idea what to expect.
719
+ - `install-extension` no longer just prints and quits: it keeps the window open and **watches until
720
+ the extension proves it is loaded** (`✓ 扩展装上了`), then until a real position arrives
721
+ (`✅ 全部完成`). One double-click now covers install *and* verification, and the window cannot
722
+ vanish mid-instruction because it is still polling.
723
+ - `node watch.mjs install-extension --steps` re-prints just the three clicks without touching any
724
+ file — for when the window scrolled past or was closed.
725
+ - `install-extension` now waits for Enter when it has a TTY, so the instructions cannot vanish
726
+ before being read (running it from an IDE "Run" button has no TTY, which is the common way this
727
+ happened).
728
+ - `ensureWatchBrowser(port, url)` now passes the film through: with `launchBrowser: true`, saying
729
+ "陪我看这个 <link>" opens the dedicated window **at that link** instead of the Bilibili homepage.
730
+ That is the zero-install path — no extension, no port config, at the cost of watching in that
731
+ window. Both paths coexist; neither requires the other.
732
+ - `node watch.mjs bridge` (and `scripts/bridge.cmd`) starts just the position receiver and says
733
+ "✓ 收到上报" on the first report. Without it, a user who installs the extension and immediately
734
+ looks at the popup sees "not connected" — because the server only runs during `watch_together`
735
+ or `watch.mjs chat`, and concludes the install failed.
736
+
737
+ ### Added — closing the remaining "no one is listening" dead ends
738
+
739
+ - **Idle stop now wakes the model too.** Video-ended and video-changed already did; idle ("no movement
740
+ for two segments") did not — and since the loop is stopped, nothing polls the chat box afterwards,
741
+ so anything the user said next went nowhere. Now it wakes and says where it stopped.
742
+ - **Waiting is polled, not slept through.** The 500 ms tick in the blocking wait now uses
743
+ `sleepWithChat`, so a message is noticed within ~150 ms instead of up to 500 ms later.
744
+ - **The tool description now tells the model what an interruption is:** a result carrying `chat` means
745
+ "answer them first, then call again with the same arguments — the wait resumes, nothing is lost, and
746
+ the image is already in the cache". Without this the model had no way to know.
747
+ - **`doctor` distinguishes "nobody is receiving" from "extension not connected".** Both look like
748
+ silence, and the old wording told the user to reinstall the extension — but if no server is running
749
+ on 9377 the extension cannot report at all, and reinstalling would have changed nothing.
750
+ - Stale SMTC-era wording removed from the strings the *model* reads (`input`/`cursor`/`title`
751
+ descriptions, and the `browser:` line), which still talked about the OS media session.
752
+
753
+ ### Added — you can interrupt almost any wait, and it picks up where it left off
754
+
755
+ Every blocking wait in `watch_together` can now be interrupted by a message in the chat box, and in
756
+ all cases the answer is "reply to them, then call again with the same arguments" — the tool resumes:
757
+
758
+ - **Building a segment** (8–10 s, longer with ASR) and **filling the lookahead buffer** (up to 4
759
+ segments serially, 30 s+) — the most pointless kind of waiting, now interruptible.
760
+ - **Waiting for the video to appear** (`waitForVideo`, up to 2 min).
761
+ - **Waiting for a condition** (`waitUntil`) and **waiting for the next line** (`nextLine`).
762
+ - Waiting to the delivery point and `cue` already listened; they now share one watcher (below).
763
+
764
+ The interrupted work is **not cancelled**: the storyboard keeps building in the background and lands
765
+ in the cache, so the follow-up call returns it immediately instead of rebuilding it.
766
+
767
+ New `src/interrupt.js`:
768
+ - `raceChat(promise)` — polls the chat while a slow promise runs; returns `interrupted` with the
769
+ message, or `done`. Wakes on whichever happens first (the promise settling, or the next poll tick).
770
+ The first version slept a fixed 500 ms per tick, which added half a second to *every* build —
771
+ enough that playback passed the delivery point and the blocking wait returned instantly.
772
+ - `sleepWithChat(ms)` — sleep that can be cut short by a message.
773
+ - `chatWatcherShared()` — **one watcher for the whole process.** `makeChatWatcher()` baselines at
774
+ creation time, so a fresh one per wait silently dropped anything the user said while the model was
775
+ thinking, in the gap between two waits.
776
+
777
+ ### Added — it now reacts to what you do mid-video
778
+
779
+ Auditing the whole flow against the user's checklist surfaced three gaps where the plugin behaved
780
+ correctly but **never told the model**, leaving it silent until the user poked it:
781
+
782
+ - **Video ended / video changed now wake the model once.** Previously they only stopped the loop, so
783
+ the model sat blocked on the previous segment with no idea the film was over or had been replaced.
784
+ - **Large seeks (>60 s, forward or backward) wake the model once** with where the user jumped to and
785
+ from, with a 3-minute cooldown. Position tracking was already correct — it was the model that had
786
+ no idea. Rewatching does not re-speak already-spoken segments (no immediate-repeat chatter).
787
+ - **Only the visible tab reports** (`document.visibilityState`), plus a report on `visibilitychange`.
788
+ Every tab with a `<video>` reports once per second; with two such tabs open the server received
789
+ alternating positions and the plugin interpreted it as the user scrubbing wildly.
790
+ - The simulator can now jump the playhead (`seeks: [{at, to}]`), and there are four new scenario
791
+ tests covering: video changed wakes once, video ended wakes once, seek forward wakes once, rewatch
792
+ wakes once and does not re-speak.
793
+
794
+ Note the jump check must run **before** the anchor is refreshed — comparing the new reading against
795
+ the already-updated anchor measures zero. That was the first (failed) version.
796
+
797
+ ### Fixed
798
+
799
+ - **`bin/watch.mjs chat` ran its own copy of the chat server** — an inline `http.createServer` plus
800
+ duplicated copies of both HTML templates (92 lines). The copies had drifted: it served `/`,
801
+ `/widget`, `/api/messages`, `/api/say` but **not `/api/position` or `/api/hello`**. So running
802
+ only `watch.mjs chat` (instead of `bridge`) meant extension reports hit 404 and the CLI path could
803
+ never read a position. It also never called `attachSpeechToChat()`, so that chat box showed user
804
+ messages but no script lines. It now uses `startChatServer()` + `attachSpeechToChat()` like the
805
+ plugin and `bridge` do, and the duplicated templates are deleted.
806
+ - **`watch.mjs reply` wrote straight to the stream** with `appendChat('assistant', …)`, so the text
807
+ appeared in the chat box but was never handed to speech subscribers — a TTS adapter stayed silent
808
+ while the page showed the words. It now uses `appendAssistantSay()`, which writes the stream *and*
809
+ emits the speech event, matching what `watch_together({say})` does.
810
+
811
+ ### Fixed
812
+
813
+ - **The plugin passed the browser's debug port to `ensureChatSession()`**, so the chat server tried
814
+ to bind 9333 — the port the browser is already using. The bind failed, the error was swallowed,
815
+ and the chat box silently never came up in DSH. It now uses the chat port (9377) as intended.
816
+ This also mattered for the extension: that server is where reports land.
817
+
818
+ ### Removed — the OS media session (SMTC) backend is gone
819
+
820
+ Position used to have two sources: the browser's DevTools port, and Windows' system media controls
821
+ (read by a bundled `watch_smtc.py`). **SMTC is deleted**, along with everything that only existed
822
+ because of it:
823
+
824
+ - `src/watch-probe.js` (121 lines) and `src/watch_smtc.py` (62 lines)
825
+ - `src/resolve-playing.js` (153 lines) — it reversed a *title* into a source by searching filenames
826
+ and then Bilibili. With CDP the page URL is the source, so this whole "guess the film" path is
827
+ gone (it was also the thing most likely to pick the wrong video)
828
+ - the `winrt` Python dependency (three packages) and the interpreter search
829
+ - most of the extrapolation policy in `position.js`: the cap drops 180 s → 60 s, `FRESH_MS`
830
+ becomes 5 s, and the safety margin now only applies after a *missed* read
831
+ - `pickSession` / `probePlayback` / `describeStatus` and the `probe` injection point
832
+
833
+ Rationale: SMTC's `Position` only refreshes on player events (measured gaps of 143 s and 216 s), so
834
+ treating it as a live position required extrapolating, and extrapolating over a wrong pause means
835
+ every later segment is built on a wrong cursor. The benefit — "watch in whatever player you like" —
836
+ did not survive contact with how it actually behaved.
837
+
838
+ What you give up: you now watch inside the dedicated browser window
839
+ (`scripts/start-edge-debug.cmd`). Chromium 136+ refuses to open a DevTools port on the default
840
+ profile, so that window necessarily has its own profile and needs a one-time login.
841
+
842
+ ### Fixed
843
+
844
+ - **`loop.built` / `loop.dur` / `loop.sourceUrl` leaked across films.** Starting a second watch
845
+ session reused the previous film's duration, so the first read of the new film looked like a
846
+ "video changed" event and stopped the loop immediately; `built` made prefetch skip segments it had
847
+ built for the old film. Both are now reset when the source changes.
848
+ - **`startWatchLoop` used `Date.now()` for the anchor while pricing time off its injected clock**,
849
+ which made every simulated read look minutes old. It now uses the injected clock.
850
+ - **The CLI's `pos()` never read SMTC at all**, so the CLI was browser-only even while the plugin
851
+ had a fallback. Moot now that SMTC is gone, but it is why the tool seemed to demand a special
852
+ browser.
853
+
854
+ ### Removed — dead code trimmed so there is one decision path
855
+
856
+ Two functions that duplicated live logic and were never called in production are gone:
857
+
858
+ - `dueDecision` (in `src/timer.js`) — a pure "should I speak now" decision that shadowed
859
+ `position.shouldSpeak`. Nothing in the loop ever called it; only a test exercised the abandoned
860
+ design. The "pause too long → stop" intent it carried is now not implemented (see note below).
861
+ - `depthForBuffer` (in `src/batches.js`) — a count-based lookahead that duplicated `windowFor`,
862
+ which the loop actually uses (position-based, so the invariant holds at every position, not just
863
+ at segment starts). Its tests were redundant guards of that same invariant.
864
+
865
+ Net: 13 tests removed (8 for `dueDecision`, 5 for `depthForBuffer`); `windowFor`'s existing tests
866
+ already cover "lookahead ≥ N seconds at every position", so no coverage was lost.
867
+
868
+ ### Changed — idle auto-stop now also covers a paused-and-abandoned video
869
+
870
+ The loop used to only stop itself on "no movement" when the last reading was a *playing* sample
871
+ (`why === 'recent-refresh'`). A paused video reports a frozen position forever — `estimate` returns
872
+ `why: 'paused'`, never stale — so pausing and walking away left the loop polling indefinitely. The
873
+ idle check now also fires on a frozen *paused* position, after the same `2 × segment` grace period,
874
+ and wakes you with "停了一会儿" so you can resume by calling `watch_together` again.
875
+
876
+ ### Fixed — voice adapter no longer hard-codes a voice
877
+
878
+ `examples/voice-edge-tts/index.mjs` used to fall back to `zh-CN-XiaoxuanNeural` when
879
+ `~/.dsh/tts.json` had no `voice`. That baked one person's voice into the example, so shipping it
880
+ would have dragged that choice into everyone's install. It now falls back to the neutral
881
+ `zh-CN-YunxiNeural` and prints a one-line hint telling you to set `voice` in `~/.dsh/tts.json`
882
+ (e.g. `"voice": "zh-CN-XiaoxuanNeural"`). Nothing about the voice ships in the package — you mount
883
+ the adapter via `~/.dsh/voice.json` (or `DSH_VOICE_ADAPTER`) and pick the voice yourself.
884
+
885
+ ## Earlier — 0.1.0 draft, never published (2026-10-30)
886
+
887
+ The first cut as a standalone plugin. It was not published under this number; the version line now
888
+ 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
889
+ `src/watch/`; it is now its own package with its own entry point, its own version, and a one-way
890
+ dependency on `dsh-video-storyboard`.
891
+
892
+ ### Added
893
+
894
+ - **`watch_together`** — watch a video together with a text-only agent. Instead of one whole-film
895
+ storyboard, it follows the user's **real playback position** and hands over one segment at a time,
896
+ `lead` seconds before the segment ends. The next segment is built while the user is still watching
897
+ the current one, so delivery is perceived as instant (4/4 measured deliveries at 0.0 s).
898
+ - **Ramp-up start.** Segment lengths grow `[60, 120, 180, 240]` → `segment`, so the first line lands
899
+ around 45 s instead of after a full 5-minute batch. `ramp: []` disables the ladder.
900
+ - **Double buffering.** `depth: 2` keeps the current batch plus the next one built, and starts the
901
+ one after that while the user watches.
902
+ - **Playback position straight from the page.** It reads `<video>.currentTime` over the DevTools
903
+ protocol, so the value is exact, and the page URL becomes the source (`file:///D:/x.mp4` → local
904
+ path) — no searching, no downloading, no asking. Never released with the OS media session (SMTC)
905
+ backend documented below: SMTC's `Position` only refreshes on events, so using it as a live
906
+ position meant extrapolating, and a wrong position poisons every later segment.
907
+ - **Honest confidence levels.** The plugin reads every 15 s and extrapolates in between, which is
908
+ normal and self-correcting. What it refuses to do is keep extrapolating after it has *missed* a
909
+ read: past 20 s it demands an extra 5 s of margin before speaking, and past 60 s it stops
910
+ guessing and asks for `cursor` instead.
911
+ - **The speech seam, with no engine.** `src/speech-bus.js` exposes `onSpeech(handler, { voice })`,
912
+ `emitSpeech()`, `speechEvents()` and `lastSpeech()`. The plugin ships no engine, no default
913
+ adapter and no voice parameters; `watch_together` results carry `speech: [{ at, text, state }]`
914
+ and the loop emits `state: 'due'` when a line is actually due.
915
+ - **Adapters loaded by path.** `~/.dsh/voice.json` `{ "adapter": "<path or module>" }` (or
916
+ `DSH_VOICE_ADAPTER`) is `import()`ed once at startup; the module exports `attach(api)` and returns
917
+ a detach. Nothing is bundled, and a failure only logs a warning.
918
+ - **`examples/voice-edge-tts/`** — a working adapter (edge-tts → `ffplay` → system-voice fallback).
919
+ It prints `[voice 03:11.4] <line>` to stderr for every line that comes due; that log, not the
920
+ audio, is what you want when checking *when* text fires.
921
+ - **One text stream for the chat box.** `chat.jsonl` carries `line` (scripted), `assistant`
922
+ (interjection) and `user`, with `say: true` marking the speakable ones.
923
+ `watch_together({ say: "…" })` is how the model gets its interjection in — the plugin cannot read a
924
+ normal reply. `attachSpeechToChat()` subscribes with `voice: false`, so a display-only consumer can
925
+ never silence the loop.
926
+ - **A localhost chat page** (`/` full view, `/widget` capsule) with an `/api/messages` long-poll and
927
+ an `/api/say` callback. This is the only channel that actually reaches a blocked `watch_together`
928
+ call — messages typed into the host's own input box are appended to the session log *after* the
929
+ blocking call returns (measured: 42 s of polling, 0 bytes written).
930
+ - **`examples/floating-chat/window.py`** — a real floating window without a browser: frameless,
931
+ always-on-top, translucent, stdlib tkinter only. Reads the same `chat.jsonl`.
932
+ - **`bin/watch.mjs`** — a CLI shell for sessions that have no `watch_together` tool. It imports the
933
+ same `src/`, so behaviour cannot drift from the plugin.
934
+
935
+ ### Fixed
936
+
937
+ - **The CLI imported pre-refactor paths** (`src/browser-time.js`, `src/pipeline.js`, …) that no
938
+ longer exist, so `bin/watch.mjs` could not even start. All imports now resolve through the
939
+ `dsh-video-storyboard` package name.
940
+
941
+ ### Changed
942
+
943
+ - `detachAdapters()` no longer reaches into the bus's private subscriber map; it calls
944
+ `__resetSpeech()` from `speech-bus.js`.
945
+ - `watch-run.js` imported `./watch.js` twice; merged into one import.
946
+
947
+ ### Known limits
948
+
949
+ - **Speaker separation is not attempted.** Measured on the reference machine: per-sentence cam++
950
+ embeddings split single-speaker material into 6 speakers; demucs pre-separation made no difference
951
+ (median similarity 0.62 → 0.61); FunASR's `ClusterBackend` returns "one speaker" outright below 20
952
+ speech segments — short clips are outside its operating range by design.
953
+ - **Interjection audio can collide with a line already being spoken.** Windows mixes both SAPI
954
+ instances, so `say` occupies `quiet-until.json` before speaking and `cue` skips lines inside that
955
+ window (it skips rather than defers — deferring desynchronises from the picture). The remaining
956
+ gap is the 3–8 s while a line is mid-speech, which cannot be cut short.
957
+ - **CRLF-less assumption.** The chat page replaces `__PORT__` in the templates per start; changing
958
+ the port while a browser tab is already open requires a reload.