dsh-watch-together 0.2.0 → 0.2.2

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/src/index.js CHANGED
@@ -1,130 +1,156 @@
1
- /**
2
- * index.js — **dsh-watch-together** 的 DSH 插件入口。只做注册:
3
- *
4
- * watch_together 陪看:按用户真实播放进度,一段一段往下看
5
- *
6
- * 这一个工具就够。它和 `dsh-video-storyboard` 的四个 `video_*` 工具是**两个插件**:
7
- * 那个负责"把一段视频变成一张可引用的宫格",这个负责"跟着你一段段看下去"。
8
- * 这里不注册任何 `video_*` —— 那是另一个包的职责。
9
- *
10
- * 契约要点(对着 @deepseek-ai/dsh-tools 的类型定义核对过):
11
- * - `apply` 返回 disposer(把所有 `ctx.tools.register()` 的返回值串起来)
12
- * - `execute` 返回**规范值**(要过 output.schema)
13
- * - `output.render(args, value)` 把规范值渲染成 ContentBlock[],图片块是
14
- * `{ type: 'image', attachment: ImageAttachmentRef }`,ref 必须由
15
- * `ctx.attachments.saveImage()` 提交过后才能拿到(不能自己编)
16
- * - saveImage 要的是**真正编码后的字节**(PNG/JPEG),不是裸 RGB —— 它会解码校验
17
- */
18
-
19
- import { attachSpeechToChat } from './chat.js';
20
- import { watchTools } from './register.js';
21
- import { attachConfiguredVoice } from './voice.js';
22
-
23
- export const name = 'dsh-watch-together';
24
- // **只声明 tools**:cordis 的 inject 是硬依赖,服务缺失时 apply 永远不会被调用,
25
- // 插件就停在"加载中"(用户侧:装完插件 DSH 卡死)。attachments 只在截图那条路上用,
26
- // 改成运行期探测(src/handler.js),没有它就返回文本。
27
- export const inject = ['tools'];
28
-
29
- /**
30
- * 解析宿主的 dsh-tools。正常安装时裸包名就能解析;本地开发/测试时
31
- * 用 `DSH_TOOLS_PATH` 指向安装里的 lib/index.js。
32
- */
33
- async function loadDefineTool() {
34
- try {
35
- const mod = await import('@deepseek-ai/dsh-tools');
36
- if (mod?.defineTool) return mod.defineTool;
37
- } catch {
38
- /* 落到环境变量 */
39
- }
40
- const override = process.env.DSH_TOOLS_PATH;
41
- if (override) {
42
- const { pathToFileURL } = await import('node:url');
43
- const mod = await import(pathToFileURL(override).href);
44
- if (mod?.defineTool) return mod.defineTool;
45
- }
46
- throw new Error('cannot resolve @deepseek-ai/dsh-tools (set DSH_TOOLS_PATH for local dev)');
47
- }
48
-
49
- const APPLY_TIMEOUT_MS = 15_000;
50
-
51
- export async function apply(ctx) {
52
- try {
53
- return await withTimeout(registerAll(ctx), APPLY_TIMEOUT_MS, 'registerAll');
54
- } catch (e) {
55
- // **最坏的情况是插件不能用,不是应用起不来**。
56
- // 真实事故:在 apply 里做 ctx 探测,`Object.keys(ctx)` 在 cordis 上下文上抛错,
57
- // 整个 DSH 直接崩在启动阶段("The application could not start")。
58
- // 所以 apply 的异常一律吞掉并记录,交回一个空 disposer。
59
- try {
60
- ctx?.logger?.error?.(`[dsh-watch-together] failed to load: ${e?.stack ?? e}`);
61
- } catch { /* 连日志都写不了就算了 */ }
62
- // DSH_VIDEO_DEBUG=1 时把错误抛出去 —— 否则"插件静默不工作"很难查
63
- if (process.env.DSH_VIDEO_DEBUG) throw e;
64
- return () => {};
65
- }
66
- }
67
-
68
- async function registerAll(ctx) {
69
- const defineTool = await loadDefineTool();
70
-
71
- // 当前会话:从 session/event 里拿(`session.header.id`)。这是 dsh-fish 的做法,
72
- // 比反射 ctx 安全得多 —— 反射会把整个应用搞崩(见 apply 的注释)。
73
- let lastSessionId = null;
74
-
75
- // 陪看跨调用复用同一批已建好的段(一部电影几十段,只留最近 8 段)
76
- const watchCache = new Map();
77
-
78
- const tools = [
79
- ...watchTools(defineTool, ctx, { getSessionId: () => lastSessionId, cache: watchCache }),
80
- ];
81
-
82
- // **disposers 必须在最前面声明**:它曾经声明在 ctx.on 之后,于是 `disposers.push(off)`
83
- // 撞上 const 的暂时性死区,抛 ReferenceError,又被下面的 catch 静默吞掉 ——
84
- // 监听器注册成功了,解绑函数却从来没登记过(插件卸载时不会解绑,而且没人知道出过错)。
85
- const disposers = [];
86
- if (typeof ctx.on === 'function') {
87
- try {
88
- const off = ctx.on('session/event', (session) => {
89
- const id = session?.header?.id ?? session?.id;
90
- if (id) lastSessionId = id;
91
- });
92
- if (typeof off === 'function') disposers.push(off);
93
- } catch (e) {
94
- // 拿不到就退化成"只能手动触发",但要说出来 —— 静默失败是这类 bug 的温床
95
- try {
96
- ctx?.logger?.warn?.(`[dsh-watch-together] session/event hook failed: ${e?.message ?? e}`);
97
- } catch { /* 日志都没有就只能算了 */ }
98
- }
99
- }
100
-
101
- // 声音适配器(可选)。核心**不内置任何引擎**:只按 `~/.dsh/voice.json` 里写的那个路径
102
- // 去 dynamic import,挂不上就算了 —— 声音是加分项,装坏了不能让插件起不来。
103
- try {
104
- const v = await attachConfiguredVoice({ log: (m) => ctx?.logger?.info?.(m) });
105
- if (!v.ok && v.reason !== 'not-configured') {
106
- ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter not loaded: ${v.reason}`);
107
- }
108
- } catch (e) {
109
- ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter crashed: ${e?.message ?? e}`);
110
- }
111
-
112
- // 到点的台词写进**统一文本流**(聊天框 / 悬浮窗读同一份,声音也从这里取)。
113
- // 订阅时带 `voice: false` —— 只做展示,不该让循环以为"有人会念"而不再叫醒模型。
114
- disposers.push(attachSpeechToChat());
115
-
116
- disposers.push(...tools.map((tool) => ctx.tools.register(tool)));
117
- return () => {
118
- for (const dispose of disposers.reverse()) dispose?.();
119
- };
120
- }
121
-
122
- /** 看门狗:apply 里任何 await 卡住都会拖住宿主启动,超时就交回空 disposer。 */
123
- function withTimeout(promise, ms, label) {
124
- let timer;
125
- const timeout = new Promise((_, reject) => {
126
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
127
- timer.unref?.();
128
- });
129
- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
130
- }
1
+ /**
2
+ * index.js — **dsh-watch-together** 的 DSH 插件入口。只做注册:
3
+ *
4
+ * watch_together 陪看:按用户真实播放进度,一段一段往下看
5
+ *
6
+ * 这一个工具就够。它和 `dsh-video-storyboard` 的四个 `video_*` 工具是**两个插件**:
7
+ * 那个负责"把一段视频变成一张可引用的宫格",这个负责"跟着你一段段看下去"。
8
+ * 这里不注册任何 `video_*` —— 那是另一个包的职责。
9
+ *
10
+ * 契约要点(对着 @deepseek-ai/dsh-tools 的类型定义核对过):
11
+ * - `apply` 返回 disposer(把所有 `ctx.tools.register()` 的返回值串起来)
12
+ * - `execute` 返回**规范值**(要过 output.schema)
13
+ * - `output.render(args, value)` 把规范值渲染成 ContentBlock[],图片块是
14
+ * `{ type: 'image', attachment: ImageAttachmentRef }`,ref 必须由
15
+ * `ctx.attachments.saveImage()` 提交过后才能拿到(不能自己编)
16
+ * - saveImage 要的是**真正编码后的字节**(PNG/JPEG),不是裸 RGB —— 它会解码校验
17
+ */
18
+
19
+ import { attachSpeechToChat } from './chat.js';
20
+ import { watchTools } from './register.js';
21
+ import { attachConfiguredVoice } from './voice.js';
22
+ import { createSettingsPage } from './settings/server.js';
23
+
24
+ export const name = 'dsh-watch-together';
25
+ // **只声明 tools**:cordis 的 inject 是硬依赖,服务缺失时 apply 永远不会被调用,
26
+ // 插件就停在"加载中"(用户侧:装完插件 DSH 卡死)。attachments 只在截图那条路上用,
27
+ // 改成运行期探测(src/handler.js),没有它就返回文本。
28
+ export const inject = ['tools'];
29
+
30
+ /**
31
+ * 解析宿主的 dsh-tools。正常安装时裸包名就能解析;本地开发/测试时
32
+ * 用 `DSH_TOOLS_PATH` 指向安装里的 lib/index.js。
33
+ */
34
+ async function loadDefineTool() {
35
+ try {
36
+ const mod = await import('@deepseek-ai/dsh-tools');
37
+ if (mod?.defineTool) return mod.defineTool;
38
+ } catch {
39
+ /* 落到环境变量 */
40
+ }
41
+ const override = process.env.DSH_TOOLS_PATH;
42
+ if (override) {
43
+ const { pathToFileURL } = await import('node:url');
44
+ const mod = await import(pathToFileURL(override).href);
45
+ if (mod?.defineTool) return mod.defineTool;
46
+ }
47
+ throw new Error('cannot resolve @deepseek-ai/dsh-tools (set DSH_TOOLS_PATH for local dev)');
48
+ }
49
+
50
+ const APPLY_TIMEOUT_MS = 15_000;
51
+
52
+ export async function apply(ctx) {
53
+ try {
54
+ return await withTimeout(registerAll(ctx), APPLY_TIMEOUT_MS, 'registerAll');
55
+ } catch (e) {
56
+ // **最坏的情况是插件不能用,不是应用起不来**。
57
+ // 真实事故:在 apply 里做 ctx 探测,`Object.keys(ctx)` 在 cordis 上下文上抛错,
58
+ // 整个 DSH 直接崩在启动阶段("The application could not start")。
59
+ // 所以 apply 的异常一律吞掉并记录,交回一个空 disposer。
60
+ try {
61
+ ctx?.logger?.error?.(`[dsh-watch-together] failed to load: ${e?.stack ?? e}`);
62
+ } catch { /* 连日志都写不了就算了 */ }
63
+ // DSH_VIDEO_DEBUG=1 时把错误抛出去 —— 否则"插件静默不工作"很难查
64
+ if (process.env.DSH_VIDEO_DEBUG) throw e;
65
+ return () => {};
66
+ }
67
+ }
68
+
69
+ async function registerAll(ctx) {
70
+ const defineTool = await loadDefineTool();
71
+
72
+ // 当前会话:从 session/event 里拿(`session.header.id`)。这是 dsh-fish 的做法,
73
+ // 比反射 ctx 安全得多 —— 反射会把整个应用搞崩(见 apply 的注释)。
74
+ let lastSessionId = null;
75
+
76
+ // 陪看跨调用复用同一批已建好的段(一部电影几十段,只留最近 8 段)
77
+ const watchCache = new Map();
78
+
79
+ const tools = [
80
+ ...watchTools(defineTool, ctx, { getSessionId: () => lastSessionId, cache: watchCache }),
81
+ ];
82
+
83
+ // **disposers 必须在最前面声明**:它曾经声明在 ctx.on 之后,于是 `disposers.push(off)`
84
+ // 撞上 const 的暂时性死区,抛 ReferenceError,又被下面的 catch 静默吞掉 ——
85
+ // 监听器注册成功了,解绑函数却从来没登记过(插件卸载时不会解绑,而且没人知道出过错)。
86
+ const disposers = [];
87
+ if (typeof ctx.on === 'function') {
88
+ try {
89
+ const off = ctx.on('session/event', (session) => {
90
+ const id = session?.header?.id ?? session?.id;
91
+ if (id) lastSessionId = id;
92
+ });
93
+ if (typeof off === 'function') disposers.push(off);
94
+ } catch (e) {
95
+ // 拿不到就退化成"只能手动触发",但要说出来 —— 静默失败是这类 bug 的温床
96
+ try {
97
+ ctx?.logger?.warn?.(`[dsh-watch-together] session/event hook failed: ${e?.message ?? e}`);
98
+ } catch { /* 日志都没有就只能算了 */ }
99
+ }
100
+ }
101
+
102
+ // 声音适配器(可选)。核心**不内置任何引擎**:只按 `~/.dsh/voice.json` 里写的那个路径
103
+ // 去 dynamic import,挂不上就算了 —— 声音是加分项,装坏了不能让插件起不来。
104
+ try {
105
+ const v = await attachConfiguredVoice({ log: (m) => ctx?.logger?.info?.(m) });
106
+ if (!v.ok && v.reason !== 'not-configured') {
107
+ ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter not loaded: ${v.reason}`);
108
+ }
109
+ } catch (e) {
110
+ ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter crashed: ${e?.message ?? e}`);
111
+ }
112
+
113
+ // 到点的台词写进**统一文本流**(聊天框 / 悬浮窗读同一份,声音也从这里取)。
114
+ // 订阅时带 `voice: false` —— 只做展示,不该让循环以为"有人会念"而不再叫醒模型。
115
+ disposers.push(attachSpeechToChat());
116
+
117
+ disposers.push(...tools.map((tool) => ctx.tools.register(tool)));
118
+
119
+ // 设置页是可选能力:没有本机 webServer 的宿主只注册 watch_together。
120
+ const attachSettings = (settingsCtx) => {
121
+ try {
122
+ const settings = createSettingsPage({ ctx: settingsCtx, env: process.env, log: (message) => settingsCtx?.logger?.warn?.(message) });
123
+ if (settings) {
124
+ disposers.push(settings.dispose);
125
+ disposers.push(settingsCtx.tools.register(defineTool(settings.tool)));
126
+ }
127
+ } catch (e) {
128
+ try { settingsCtx?.logger?.warn?.('[dsh-watch-together] settings page failed: ' + String(e?.message ?? e)); } catch { /* ignore */ }
129
+ }
130
+ };
131
+ // webServer 可能晚于插件就绪;动态 inject 比 apply 时硬探测更可靠。
132
+ if (typeof ctx.inject === 'function') {
133
+ try {
134
+ const off = ctx.inject(['webServer'], (webCtx) => attachSettings(webCtx));
135
+ if (typeof off === 'function') disposers.push(off);
136
+ } catch (e) {
137
+ try { ctx?.logger?.warn?.('[dsh-watch-together] settings injection failed: ' + String(e?.message ?? e)); } catch { /* ignore */ }
138
+ }
139
+ } else {
140
+ attachSettings(ctx);
141
+ }
142
+
143
+ return () => {
144
+ for (const dispose of disposers.reverse()) dispose?.();
145
+ };
146
+ }
147
+
148
+ /** 看门狗:apply 里任何 await 卡住都会拖住宿主启动,超时就交回空 disposer。 */
149
+ function withTimeout(promise, ms, label) {
150
+ let timer;
151
+ const timeout = new Promise((_, reject) => {
152
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
153
+ timer.unref?.();
154
+ });
155
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
156
+ }
@@ -1,154 +1,156 @@
1
- /**
2
- * input-surface.js — "用户能在哪儿插话"的那一侧:悬浮窗 + 聊天服务 + 一句要告诉模型的话。
3
- *
4
- * 为什么单独成文件:这块和"陪看"没有关系 —— 它不知道段、不知道播放位置、不知道模型,
5
- * 只回答一个问题:"用户现在能在哪儿打字/说话,我该怎么告诉他"。
6
- * 以前它长在 `handler.js` 里,于是那个**只该做分流**的文件有四十行 UI 准备,
7
- * 还带一个 `widgetNote` 变量从函数头传到函数尾。
8
- *
9
- * 三个坑(都真踩过):
10
- * ① **两个端口毫无关系**:聊天服务固定 9377,浏览器调试端口 9333。
11
- * 以前把调试端口当聊天端口传进 `ensureChatSession`,那个端口被浏览器占着,
12
- * listen 必然失败、异常又被吞掉 —— "聊天框一直没起来"没人知道为什么。
13
- * ② **只 listen 不会在屏幕上出现任何东西**。真要阻塞时得把悬浮窗开起来,
14
- * 否则用户只能去宿主输入框打字,而宿主的输入框送不进阻塞中的调用 ——
15
- * 表现就是"插话没反应、只能干等"。
16
- * ③ **自己 listen 失败不代表没得用**:另一个实例占着 9377 时,页面照样开得出来、
17
- * 插话照样通 —— 因为写的是同一个 `chat.jsonl`。
18
- *
19
- * 输入框的主入口是 Python 悬浮窗(`examples/floating-chat/window.py`);
20
- * 浏览器页面只剩只读兜底(`chatPageUrl()`),不再自动打开,也没有置顶小窗。
21
- */
22
-
23
- import {
24
- DEFAULT_CHAT_PORT, appendSpoken, chatAlive, chatPageUrl, ensureChatSession,
25
- } from './chat.js';
26
- import { floatingWindowAlive, openFloatingWindow } from './floating-window.js';
27
- import { loopStatus, stopWatchLoop } from './watch-loop.js';
28
- import { clearHungUp, isHungUp, markHungUp } from './watch-state.js';
29
- import { attachConfiguredVoice, attachedAdapters, configuredVoiceAdapter } from './voice.js';
30
-
31
- /**
32
- * 造一个"准备输入面"的函数:**幂等**,同一个 execute 里调几次都只开一次窗。
33
- *
34
- * 返回值是 `{ note }` —— `note` 是要附在工具结果后面的一句话(模型据此告诉用户去哪儿说话)。
35
- * 用 `??=` 缓存的是 Promise 而不是结果:第二次调用直接复用第一次的,不会各开一个窗口。
36
- *
37
- * @returns {() => Promise<{note: string}>}
38
- */
39
- export function createInputSurface() {
40
- let prepared = null;
41
- /**
42
- * @param {{start?: boolean}} [o]
43
- * `start: true` = 这是一次**新的开始**(没有正在跑的陪看)→ 窗口没了就重开;
44
- * 否则(同一场陪看中途再调)→ 窗口没了**不要**偷偷重开,而是判定"用户关了窗"并停止。
45
- *
46
- * 为什么要区分:用户的原话是"我刚才关了悬浮窗又自己弹出来了"。关窗是他表达
47
- * "我不看了"的方式,下一次调用立刻又把窗口顶回来,等于把他的动作撤销了。
48
- */
49
- return ({ start = false, input = null, reopen = false } = {}) => {
50
- prepared ??= open({ start, input, reopen });
51
- return prepared;
52
- };
53
- }
54
-
55
- /** 这个进程里"悬浮窗已开"这句话只说一次 —— 用户看到两条一模一样的系统提示会以为出错了 */
56
- let announced = false;
57
-
58
- /** 声音适配器:没挂就挂上(挂过就直接复用)。返回一句给人看的状态。 */
59
- async function ensureVoice() {
60
- let spec = '';
61
- try {
62
- spec = String(configuredVoiceAdapter() ?? '').trim();
63
- } catch { spec = ''; }
64
- if (!spec) return { ok: false, reason: 'voice.json 没配 adapter' };
65
- if (attachedAdapters().includes(spec)) return { ok: true, name: tail(spec), cached: true };
66
- const r = await attachConfiguredVoice({ log: () => {} })
67
- .catch((e) => ({ ok: false, reason: String(e?.message ?? e) }));
68
- return { ok: r?.ok === true, name: r?.name ?? tail(spec), reason: r?.reason };
69
- }
70
-
71
- const tail = (p) => String(p).split(/[\\/]/).filter(Boolean).pop() || String(p);
72
-
73
- async function open({ start = false, input = null, reopen = false } = {}) {
74
- // 0) 声音:每次开始陪看都确认一次 —— 不挂的话台词只会写进流、一句也不念
75
- const voice = await ensureVoice();
76
- const voiceNote = voice.ok
77
- ? `声音:${voice.name}${voice.cached ? ' 已在' : ' 已挂上'}`
78
- : `声音:没挂(${voice.reason ?? '未知原因'}),台词只写不念`;
79
-
80
- // 1) 悬浮窗(Python tkinter,无边框/置顶;里面还有「麦」可以语音输入)
81
- //
82
- // **关窗 = 用户说不看了**。所以:
83
- // · 新开一场(start)→ 窗口不在就开
84
- // · 同一场中途调用 → 窗口不在就**判定被关**:停钟、返回"已中止",绝不偷偷重开
85
- const running = loopStatus();
86
- // **用户关过窗就不要再顶回来** —— 哪怕这一轮看起来像"新开一场"。
87
- // 只有明确要求重开(`open: true`)才清掉这条记录。
88
- //
89
- // 判定只认 `input`:`start: true` 意味着"这是新的一场陪看",那时候要允许开窗
90
- // (插件重启之后 loop 里没有 input,用"最近挂断过"去挡它,会让刚重启的用户永远开不出窗)。
91
- const hung = input ? await isHungUp(input).catch(() => false) : false;
92
- if (hung) {
93
- if (reopen) {
94
- await clearHungUp().catch(() => {});
95
- } else if (!floatingWindowAlive()) {
96
- return {
97
- windowOpen: false,
98
- closedByUser: true,
99
- note: '\n[widget] 悬浮窗已被关掉(是你自己关的),我没有重开 —— 陪看就停在这儿。'
100
- + '想接着看就说一声「重新打开悬浮窗」,我再开。'
101
- + `\n[voice] ${voiceNote}。`,
102
- };
103
- }
104
- }
105
- if (!start && running.active && !floatingWindowAlive()) {
106
- stopWatchLoop('widget-closed');
107
- if (input) await markHungUp(input).catch(() => {});
108
- return {
109
- windowOpen: false,
110
- closedByUser: true,
111
- note: '\n[widget] 悬浮窗已被关掉 —— 陪看按你关窗的意思停在这里,我不再挂着、也不重开。'
112
- + '要接着看就再说一声,我会重新开窗。'
113
- + `\n[voice] ${voiceNote}。`,
114
- };
115
- }
116
- const win = openFloatingWindow({ log: () => {} });
117
- // 2) 聊天服务(扩展上报位置走它,记录页也由它提供)
118
- const srv = await ensureChatSession().catch(() => null);
119
- const port = srv?.port ?? DEFAULT_CHAT_PORT;
120
- const alive = srv ? true : await chatAlive(port).catch(() => false);
121
-
122
- if (win.ok) {
123
- if (!announced) {
124
- announced = true;
125
- try {
126
- // 走统一出口(写盘 + 语音)—— 窗口里出现的每一句都给念,这条也不例外
127
- appendSpoken('assistant', '[一起看] 悬浮窗已开 —— 在那里打字,或点「麦」直接说话,我等待时会立刻收到。');
128
- } catch { /* 写不进流不影响陪看 */ }
129
- }
130
- return {
131
- windowOpen: true,
132
- note: `\n[widget] 悬浮窗已打开(${win.python} ${win.script}):`
133
- + '在里面打字、或点「麦」说话,我等待时会立刻被唤醒。'
134
- + `\n[voice] ${voiceNote}。`,
135
- };
136
- }
137
- if (win.reason === 'already-opened') {
138
- return {
139
- windowOpen: true,
140
- note: '\n[widget] 悬浮窗已经开着 —— 直接在里打字/说话即可。'
141
- + `\n[voice] ${voiceNote}。`,
142
- };
143
- }
144
- // 开不起来要说清楚原因,并给一条能走通的兜底:只有 Python 悬浮窗和(只读的)聊天记录页
145
- return {
146
- windowOpen: false,
147
- note: `\n[widget] 悬浮窗没开起来(${win.reason})。`
148
- + (alive
149
- ? `兜底:浏览器打开 ${chatPageUrl(port)}(只读记录 + 可输入),`
150
- + '或双击 examples/floating-chat/launch.cmd。'
151
- : '')
152
- + `\n[voice] ${voiceNote}。`,
153
- };
154
- }
1
+ /**
2
+ * input-surface.js — "用户能在哪儿插话"的那一侧:悬浮窗 + 聊天服务 + 一句要告诉模型的话。
3
+ *
4
+ * 为什么单独成文件:这块和"陪看"没有关系 —— 它不知道段、不知道播放位置、不知道模型,
5
+ * 只回答一个问题:"用户现在能在哪儿打字/说话,我该怎么告诉他"。
6
+ * 以前它长在 `handler.js` 里,于是那个**只该做分流**的文件有四十行 UI 准备,
7
+ * 还带一个 `widgetNote` 变量从函数头传到函数尾。
8
+ *
9
+ * 三个坑(都真踩过):
10
+ * ① **两个端口毫无关系**:聊天服务固定 9377,浏览器调试端口 9333。
11
+ * 以前把调试端口当聊天端口传进 `ensureChatSession`,那个端口被浏览器占着,
12
+ * listen 必然失败、异常又被吞掉 —— "聊天框一直没起来"没人知道为什么。
13
+ * ② **只 listen 不会在屏幕上出现任何东西**。真要阻塞时得把悬浮窗开起来,
14
+ * 否则用户只能去宿主输入框打字,而宿主的输入框送不进阻塞中的调用 ——
15
+ * 表现就是"插话没反应、只能干等"。
16
+ * ③ **自己 listen 失败不代表没得用**:另一个实例占着 9377 时,页面照样开得出来、
17
+ * 插话照样通 —— 因为写的是同一个 `chat.jsonl`。
18
+ *
19
+ * 输入框的主入口是 Python 悬浮窗(`examples/floating-chat/window.py`);
20
+ * 浏览器页面只剩只读兜底(`chatPageUrl()`),不再自动打开,也没有置顶小窗。
21
+ */
22
+
23
+ import {
24
+ DEFAULT_CHAT_PORT, appendSpoken, chatAlive, chatPageUrl, ensureChatSession,
25
+ } from './chat.js';
26
+ import { floatingWindowAlive, openFloatingWindow } from './floating-window.js';
27
+ import { loopStatus, stopWatchLoop } from './watch-loop.js';
28
+ import { clearHungUp, isHungUp, markHungUp } from './watch-state.js';
29
+ import { attachConfiguredVoice, attachedAdapters, configuredVoiceAdapter } from './voice.js';
30
+
31
+ /**
32
+ * 造一个"准备输入面"的函数:**幂等**,同一个 execute 里调几次都只开一次窗。
33
+ *
34
+ * 返回值是 `{ note }` —— `note` 是要附在工具结果后面的一句话(模型据此告诉用户去哪儿说话)。
35
+ * 用 `??=` 缓存的是 Promise 而不是结果:第二次调用直接复用第一次的,不会各开一个窗口。
36
+ *
37
+ * @returns {() => Promise<{note: string}>}
38
+ */
39
+ export function createInputSurface({ windowService = null } = {}) {
40
+ let prepared = null;
41
+ /**
42
+ * @param {{start?: boolean}} [o]
43
+ * `start: true` = 这是一次**新的开始**(没有正在跑的陪看)→ 窗口没了就重开;
44
+ * 否则(同一场陪看中途再调)→ 窗口没了**不要**偷偷重开,而是判定"用户关了窗"并停止。
45
+ *
46
+ * 为什么要区分:用户的原话是"我刚才关了悬浮窗又自己弹出来了"。关窗是他表达
47
+ * "我不看了"的方式,下一次调用立刻又把窗口顶回来,等于把他的动作撤销了。
48
+ */
49
+ return ({ start = false, input = null, reopen = false } = {}) => {
50
+ prepared ??= open({ start, input, reopen, windowService });
51
+ return prepared;
52
+ };
53
+ }
54
+
55
+ /** 这个进程里"悬浮窗已开"这句话只说一次 —— 用户看到两条一模一样的系统提示会以为出错了 */
56
+ let announced = false;
57
+
58
+ /** 声音适配器:没挂就挂上(挂过就直接复用)。返回一句给人看的状态。 */
59
+ async function ensureVoice() {
60
+ let spec = '';
61
+ try {
62
+ spec = String(configuredVoiceAdapter() ?? '').trim();
63
+ } catch { spec = ''; }
64
+ if (!spec) return { ok: false, reason: 'voice.json 没配 adapter' };
65
+ if (attachedAdapters().includes(spec)) return { ok: true, name: tail(spec), cached: true };
66
+ const r = await attachConfiguredVoice({ log: () => {} })
67
+ .catch((e) => ({ ok: false, reason: String(e?.message ?? e) }));
68
+ return { ok: r?.ok === true, name: r?.name ?? tail(spec), reason: r?.reason };
69
+ }
70
+
71
+ const tail = (p) => String(p).split(/[\\/]/).filter(Boolean).pop() || String(p);
72
+
73
+ async function open({ start = false, input = null, reopen = false, windowService = null } = {}) {
74
+ const winAlive = () => (windowService ? windowService.alive() : floatingWindowAlive());
75
+ const winOpen = (opts) => (windowService ? windowService.open(opts) : openFloatingWindow(opts));
76
+ // 0) 声音:每次开始陪看都确认一次 —— 不挂的话台词只会写进流、一句也不念
77
+ const voice = await ensureVoice();
78
+ const voiceNote = voice.ok
79
+ ? `声音:${voice.name}${voice.cached ? ' 已在' : ' 已挂上'}`
80
+ : `声音:没挂(${voice.reason ?? '未知原因'}),台词只写不念`;
81
+
82
+ // 1) 悬浮窗(Python tkinter,无边框/置顶;里面还有「麦」可以语音输入)
83
+ //
84
+ // **关窗 = 用户说不看了**。所以:
85
+ // · 新开一场(start)→ 窗口不在就开
86
+ // · 同一场中途调用 → 窗口不在就**判定被关**:停钟、返回"已中止",绝不偷偷重开
87
+ const running = loopStatus();
88
+ // **用户关过窗就不要再顶回来** —— 哪怕这一轮看起来像"新开一场"。
89
+ // 只有明确要求重开(`open: true`)才清掉这条记录。
90
+ //
91
+ // 判定只认 `input`:`start: true` 意味着"这是新的一场陪看",那时候要允许开窗
92
+ // (插件重启之后 loop 里没有 input,用"最近挂断过"去挡它,会让刚重启的用户永远开不出窗)。
93
+ const hung = input ? await isHungUp(input).catch(() => false) : false;
94
+ if (hung) {
95
+ if (reopen) {
96
+ await clearHungUp().catch(() => {});
97
+ } else if (!winAlive()) {
98
+ return {
99
+ windowOpen: false,
100
+ closedByUser: true,
101
+ note: '\n[widget] 悬浮窗已被关掉(是你自己关的),我没有重开 —— 陪看就停在这儿。'
102
+ + '想接着看就说一声「重新打开悬浮窗」,我再开。'
103
+ + `\n[voice] ${voiceNote}。`,
104
+ };
105
+ }
106
+ }
107
+ if (!start && running.active && !winAlive()) {
108
+ stopWatchLoop('widget-closed');
109
+ if (input) await markHungUp(input).catch(() => {});
110
+ return {
111
+ windowOpen: false,
112
+ closedByUser: true,
113
+ note: '\n[widget] 悬浮窗已被关掉 —— 陪看按你关窗的意思停在这里,我不再挂着、也不重开。'
114
+ + '要接着看就再说一声,我会重新开窗。'
115
+ + `\n[voice] ${voiceNote}。`,
116
+ };
117
+ }
118
+ const win = winOpen({ log: () => {} });
119
+ // 2) 聊天服务(扩展上报位置走它,记录页也由它提供)
120
+ const srv = await ensureChatSession().catch(() => null);
121
+ const port = srv?.port ?? DEFAULT_CHAT_PORT;
122
+ const alive = srv ? true : await chatAlive(port).catch(() => false);
123
+
124
+ if (win.ok) {
125
+ if (!announced) {
126
+ announced = true;
127
+ try {
128
+ // 走统一出口(写盘 + 语音)—— 窗口里出现的每一句都给念,这条也不例外
129
+ appendSpoken('assistant', '[一起看] 悬浮窗已开 —— 在那里打字,或点「麦」直接说话,我等待时会立刻收到。');
130
+ } catch { /* 写不进流不影响陪看 */ }
131
+ }
132
+ return {
133
+ windowOpen: true,
134
+ note: `\n[widget] 悬浮窗已打开(${win.python} ${win.script}):`
135
+ + '在里面打字、或点「麦」说话,我等待时会立刻被唤醒。'
136
+ + `\n[voice] ${voiceNote}。`,
137
+ };
138
+ }
139
+ if (win.reason === 'already-opened') {
140
+ return {
141
+ windowOpen: true,
142
+ note: '\n[widget] 悬浮窗已经开着 —— 直接在里打字/说话即可。'
143
+ + `\n[voice] ${voiceNote}。`,
144
+ };
145
+ }
146
+ // 开不起来要说清楚原因,并给一条能走通的兜底:只有 Python 悬浮窗和(只读的)聊天记录页
147
+ return {
148
+ windowOpen: false,
149
+ note: `\n[widget] 悬浮窗没开起来(${win.reason})。`
150
+ + (alive
151
+ ? `兜底:浏览器打开 ${chatPageUrl(port)}(只读记录 + 可输入),`
152
+ + '或双击 examples/floating-chat/launch.cmd。'
153
+ : '')
154
+ + `\n[voice] ${voiceNote}。`,
155
+ };
156
+ }