Compare commits
2 Commits
ba8d43271b
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f5bffba8e | |||
| 2e554c1c07 |
+69
-7
@@ -53,6 +53,7 @@ kit/
|
||||
| `list_coursewares` | 列出本地缓存课件 | 否 |
|
||||
| `diff_courseware` | 对比两份课件,或「备份 vs 当前课件」;文字/样式/动画/切换/位置 | 否 |
|
||||
| `preflight_courseware` | 课前自检:结构 + 字号/超宽/挖空可见/动画顺序/切换/未同步 | 否 |
|
||||
| `diagnose_courseware` | 写前诊断:窗口数、备课/授课界面、内存与磁盘是否一致、未同步、截图接口是否活着 | 否(`checkRender` 会截图) |
|
||||
| `undo_last_edit` | 恢复最近一次 kit 写操作前的自动备份 | 是 |
|
||||
| `batch_replace_text` | 跨课件批量改文字(每份各自备份) | 是 |
|
||||
| `batch_set_text_style` | 跨课件批量改样式 | 是 |
|
||||
@@ -79,17 +80,23 @@ kit/
|
||||
|
||||
所有写工具最终都走 `runEdit`:
|
||||
|
||||
1. **检查**:如果目标课件正开着,先等它加载完(见下方「加载轮询」),
|
||||
比对内存页数/大小与磁盘索引;不一致且没传 `force` 就拒绝,避免丢掉未同步的新页。
|
||||
1. **检查**:如果目标课件正开着,先看三件事,任何一件不对都直接拒绝(除非 `force=true`):
|
||||
- 同一个课件开了几个窗口(>1 会互相覆盖);
|
||||
- 是不是停在授课(Display)界面(切回备课会丢该界面的改动);
|
||||
- 内存页数/大小与磁盘索引是否一致(避免丢掉未同步的新页)。
|
||||
通过后等它加载完(见下方「加载轮询」)。
|
||||
2. **关闭**:`close_current_courseware(syncBeforeClose=false)`,不保存内存改动。
|
||||
3. **备份**:自动快照到 `%TEMP%\opencode\seewo-kit-backups`,保留最近 10 份。
|
||||
4. **改文件**:改 XML,重算该文件 MD5/大小。
|
||||
5. **落盘**:更新索引 JSON 与 `CoursewareCacheData.db` 的 `Revision` / `SyncedRevision` / `Size` / 文件行。
|
||||
6. **重开**:`open_cloud_courseware`,等页面加载完成再返回。
|
||||
7. **可选同步**:`sync=true` 时先做一次「加页+删页」把课件弄脏,再上传。
|
||||
6. **核对**:比对改动前后的页面文件指纹,返回 `changedPages`;为 0 时给 `warnings`,
|
||||
提示「工具说成功但磁盘没变」,别再信返回值,用 `verify_courseware` 复查。
|
||||
7. **重开**:`open_cloud_courseware`,等页面加载完成再返回。
|
||||
8. **可选同步**:`sync=true` 时先做一次「加页+删页」把课件弄脏,再上传。
|
||||
|
||||
> 关闭/打开时先按名字匹配;本地存在同名副本时再用 `RemoteId` 逐个核对,防止操作到另一份。
|
||||
> 同步前会轮询到备课(Edit)界面;遇到「必须处于备课界面」会自动重新切界面并重试 3 轮。
|
||||
> 同步前会轮询到备课(Edit)界面;遇到「必须处于备课界面」会自动重新切界面并重试 3 轮,
|
||||
> 但**只有本来就在备课界面**才允许切——授课界面的改动不会在没告知的情况下被切掉。
|
||||
|
||||
## 各工具要点
|
||||
|
||||
@@ -215,6 +222,21 @@ kit/
|
||||
返回 `{ ok, ready, counts, issues[] }`:`ok` 只看 error,`ready` 还要求没有 warning。
|
||||
问题按 error → warn → info 排序,适合上课前跑一遍。
|
||||
|
||||
### diagnose_courseware
|
||||
|
||||
写操作前先跑这个,回答「现在能不能安全写」:
|
||||
|
||||
- `live.open`:同一个课件开了几个窗口;>1 时 `safeToWrite=false`,因为每个窗口各存一份,写谁都会被另一个覆盖;
|
||||
- `live.shells[].workingMode`:每个窗口停在 `Edit` 还是 `Display`。停在授课界面时切换会丢该界面的改动;
|
||||
- `live.shells[].transport`:每个窗口的 MCP 链路状态。`cloud` 是云端(7916)转发,`direct` 是该窗口自己的端口。
|
||||
云端代理坏掉时 `cloud=dead` + `direct=ok`,kit 会自动改走直连,写入不受影响,同时报 `proxy-dead`;
|
||||
- `pages` / `live.shells[].pages`:磁盘页数 vs 内存页数,不一致说明有没落盘的改动或还在加载;
|
||||
- `revision` / `syncedRevision`:本地改了没上传;
|
||||
- `checkRender=true`:顺手截一张图,验证截图链路(云端代理和直连都走不通时才报错,并明确要求重启希沃);
|
||||
- `latestBackups`:最近 3 份快照,出问题可以直接 `restore_courseware`。
|
||||
|
||||
返回 `{ ok, safeToWrite, issues[], tips[] }`。`safeToWrite=false` 时不要写课件。
|
||||
|
||||
### undo_last_edit
|
||||
|
||||
- 找到该课件最新一份 `note="auto-before-write"` 的备份并恢复,必须传 `confirm=true`。
|
||||
@@ -236,8 +258,8 @@ kit/
|
||||
- 默认导出全部页,或 `page` / `pages` 指定;输出到
|
||||
`%TEMP%\opencode\seewo-kit-export\<localId>-<时间>`,也可传 `outDir`(绝对路径或相对目录名)。
|
||||
- `fileNamePattern` 支持 `{page}`(原页码)和 `{index}`(补零),默认 `slide-01.png`。
|
||||
- 直接调用希沃原生 `get_slide_screenshot({ slideNumber, expectedPngImageFilePath })`,不额外调用
|
||||
`goto_slide`(少一次渲染等待,也少一个卡死点)。
|
||||
- 直接调用希沃原生 `get_slide_screenshot({ slideNumber, expectedPngImageFilePath })`。
|
||||
每页截图前先 `goto_slide` 到目标页(否则偶尔会拿到上一页的旧帧),失败也不中断。
|
||||
- 每页截图前会删掉 0 字节残留;成功标准是文件 ≥ `minBytes`(默认 2048)。
|
||||
- `timeoutSec` 默认 180 秒。超时会**停止后续页面**并返回 `ok: false`,同时提示确认希沃窗口在前台、
|
||||
课件已完整加载,必要时重启希沃;不会像以前那样反复重试把界面越拖越死。
|
||||
@@ -471,6 +493,46 @@ MCP 加的元素在 Display 模式下不会被保存;写操作前后尽量让
|
||||
需要精确对比时先用 `pages` 限定范围,或先让两份课件的页序一致。元素按 32 位 Id 对应;
|
||||
复制页面时 `copy_slides` 会重新生成 Id,所以「复制出来的页」在 diff 里会显示为整页元素新增,这是正常的。
|
||||
|
||||
### 15. 三个会让「写成功却看不见」的坑
|
||||
|
||||
这三个都是 2026-11 实操踩出来的,工具里已经加了拦截,这里说明原因,免得遇到时又去猜:
|
||||
|
||||
1. **同一个课件开了多个希沃窗口。** 每个窗口各持一份内存副本,后保存的覆盖先保存的。
|
||||
`diagnose_courseware` 会报 `multi-instance`;`closeForWrite` 遇到 >1 个窗口直接拒绝写入。
|
||||
处理:手动只留一个窗口,再写。
|
||||
2. **课件停在授课(Display)界面。** 切回备课会把授课界面里新建的页/元素丢掉。
|
||||
`closeForWrite` / `sync_courseware` 遇到非 `Edit` 界面会拒绝;`export_slides` 则**不切换**,直接截授课画面。
|
||||
确认这些改动不要了,才传 `force=true`。
|
||||
3. **截图拿到旧帧。** `get_slide_screenshot` 偶尔返回上一页/上一次的渲染结果,文件大小看起来完全正常。
|
||||
`export_slides` 现在每次先删目标文件、先 `goto_slide` 到目标页、再校验文件修改时间是否落在本次调用之后;
|
||||
连续两页超时就中止并提示重启希沃,而不是继续等。
|
||||
|
||||
### 16. 云端 MCP 的 shell 转发会永久挂起(已加直连回退)
|
||||
|
||||
希沃有两层 MCP:云端(7916)只有 11 个 `en_*` / 云课件工具,其余 52 个工具是**转发**给课件窗口进程(shell)执行的。
|
||||
每个 shell 进程自己也有完整 MCP 服务,端口随机,启动时写进日志。
|
||||
|
||||
2026-11-23 实测到,云端到某个 shell 的转发会**永久卡死**:
|
||||
|
||||
- `get_slide_info(shellId=7568)` 130 秒仍无返回,也没有任何超时错误;
|
||||
- 卡住期间云端进程**没有**向该 shell 的端口发起 TCP 连接,shell 日志里也**收不到**任何请求;
|
||||
- 同一个 shell 自己的端口(50100)用 HTTP 直接调,全部 10–130 ms 返回,截图也正常;
|
||||
- 另一个 shell(5628)走云端转发 11–86 ms 正常。
|
||||
|
||||
也就是说「希沃卡死 / 截图接口坏了」是误判,真正坏的是云端那条转发链,而且它不报错、不超时。
|
||||
|
||||
现在 `core.mjs` 的做法:
|
||||
|
||||
1. 每个 shell 第一次被用到时,用 `get_current_courseware_info` 做一次 4 秒探活;
|
||||
2. 云端代理超时 → 从 `%APPDATA%\Seewo\EasiNote5\Log\<时间>,<pid>\last_info.txt` 里读出
|
||||
`Shell MCP server started on port: N`,自动改走 `http://127.0.0.1:N/mcp`(直连时脱掉 `shellId`;
|
||||
端口变了会自动重新发现);
|
||||
3. 探活通过的调用仍走云端;单次调用中途超时也会立刻降级,不会让调用方干等;
|
||||
4. 路由按 shell 缓存,`diagnose_courseware` 的 `live.shells[].transport` 会直接显示 `cloud` / `direct` 状态。
|
||||
|
||||
所以云端代理坏掉时,读写照常,只是 `diagnose_courseware` 会报一条 `proxy-dead`。
|
||||
真正恢复云端代理需要重启希沃(只有重启才会重建转发客户端)。
|
||||
|
||||
## 排错
|
||||
|
||||
```bash
|
||||
|
||||
+531
-44
@@ -47,19 +47,55 @@ const stamp = () => {
|
||||
const isSlidePath = p => SLIDE_RE.test(String(p || '').replace(/\//g, '\\'));
|
||||
|
||||
// ---------------------------------------------------------------- 希沃 MCP 客户端
|
||||
let sessionId = null;
|
||||
let rpcId = 100;
|
||||
let initialized = false;
|
||||
//
|
||||
// 希沃有两层 MCP:
|
||||
// · 云端(7916,Cloud MCP,宿主是主窗口进程)只有 11 个 en_* / 云课件工具,
|
||||
// 其余 52 个「shell 工具」是它转发给某个课件窗口进程(shell)去执行的;
|
||||
// · 每个 shell 进程自己也有一个完整的 MCP 服务,端口随机,启动时会写进日志。
|
||||
//
|
||||
// 云端那条转发链【没有超时】:某个 shell 的代理一旦失效,所有带 shellId 的调用都会永久挂住
|
||||
// (实测 130 秒无响应,且 shell 侧收不到任何请求,连 TCP 都没连)。这会让写操作既写不进去,
|
||||
// 又长时间不报错。所以这里对每个 shell 做一次探活:代理不通就自动改走该 shell 的直连端口。
|
||||
// 直连端口从 %APPDATA%\Seewo\EasiNote5\Log\<时间>,<pid>\last_info.txt 里读取。
|
||||
const LOG_ROOT = path.join(os.homedir(), 'AppData', 'Roaming', 'Seewo', 'EasiNote5', 'Log');
|
||||
const PORT_RE = /Shell MCP server started on port:\s*(\d+)/g;
|
||||
const LISTEN_RE = /Listening on http:\/\/(?:127\.0\.0\.1|\[::1\]):(\d+)\//;
|
||||
|
||||
async function post(body, timeoutMs = 30000) {
|
||||
/** 只有云端才有的工具;其余工具在 shell 直连端口上也有,可以走直连 */
|
||||
const CLOUD_ONLY = new Set([
|
||||
'en_find_shells', 'en_bind_shell', 'en_goto_app_ui',
|
||||
'new_cloud_courseware', 'new_cloud_courseware_from_pptx', 'open_cloud_courseware',
|
||||
'search_cloud_courseware', 'generate_video_from_pptx',
|
||||
'ensys_open_file', 'switch_to_display_board_mode', 'recognition_document_and_goto_page',
|
||||
]);
|
||||
|
||||
const PROBE_TIMEOUT_MS = 4000;
|
||||
const DEFAULT_TIMEOUT_MS = 30000;
|
||||
|
||||
let rpcId = 100;
|
||||
const sessions = new Map(); // port -> { sid, initialized, rpcId }
|
||||
const routes = new Map(); // shellId -> { kind: 'cloud'|'direct'|'dead', port, reason, at }
|
||||
const shellPorts = new Map(); // shellId -> { port, dir }
|
||||
|
||||
function sessionOf(port) {
|
||||
let st = sessions.get(port);
|
||||
if (!st) {
|
||||
st = { sid: null, initialized: false };
|
||||
sessions.set(port, st);
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
async function postTo(port, body, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
||||
const st = sessionOf(port);
|
||||
const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' };
|
||||
if (sessionId) headers['Mcp-Session-Id'] = sessionId;
|
||||
const res = await fetch(`http://127.0.0.1:${MCP_PORT}/mcp`, {
|
||||
if (st.sid) headers['Mcp-Session-Id'] = st.sid;
|
||||
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
|
||||
method: 'POST', headers, body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
const sid = res.headers.get('mcp-session-id');
|
||||
if (sid) sessionId = sid;
|
||||
if (sid) st.sid = sid;
|
||||
const text = await res.text();
|
||||
if (text.includes('data:')) {
|
||||
const data = text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join('');
|
||||
@@ -68,33 +104,214 @@ async function post(body, timeoutMs = 30000) {
|
||||
try { return JSON.parse(text); } catch { return { raw: text }; }
|
||||
}
|
||||
|
||||
async function rpc(name, args = {}, { timeoutMs } = {}) {
|
||||
const r = await post({ jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }, timeoutMs);
|
||||
async function ensureInitOn(port, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
||||
const st = sessionOf(port);
|
||||
if (st.initialized) return;
|
||||
await postTo(port, {
|
||||
jsonrpc: '2.0', id: 1, method: 'initialize',
|
||||
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-kit', version: '1.1' } },
|
||||
}, timeoutMs);
|
||||
await postTo(port, { jsonrpc: '2.0', method: 'notifications/initialized' }, timeoutMs);
|
||||
st.initialized = true;
|
||||
}
|
||||
|
||||
async function rpcOn(port, name, args = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
||||
await ensureInitOn(port, timeoutMs);
|
||||
const r = await postTo(port, {
|
||||
jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args },
|
||||
}, timeoutMs);
|
||||
if (r.error) throw new Error(`${name}: ${JSON.stringify(r.error)}`);
|
||||
const txt = (r.result?.content ?? []).filter(c => c.type === 'text').map(c => c.text).join('\n');
|
||||
if (r.result?.isError) throw new Error(`${name}: ${txt}`);
|
||||
return { text: txt, data: r.result?.structuredContent };
|
||||
}
|
||||
|
||||
async function ensureInit() {
|
||||
if (initialized) return;
|
||||
await post({
|
||||
jsonrpc: '2.0', id: 1, method: 'initialize',
|
||||
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-kit', version: '1.0' } },
|
||||
});
|
||||
await post({ jsonrpc: '2.0', method: 'notifications/initialized' });
|
||||
initialized = true;
|
||||
const ensureInit = () => ensureInitOn(MCP_PORT);
|
||||
const rpc = (name, args, { timeoutMs } = {}) => rpcOn(MCP_PORT, name, args, timeoutMs);
|
||||
|
||||
/** 超时 / 连不上,才算「这条链路坏了」;业务报错说明对面是通的 */
|
||||
function isTransportError(e) {
|
||||
const n = String(e?.name || '');
|
||||
const m = String(e?.message || '');
|
||||
return n === 'TimeoutError' || n === 'AbortError'
|
||||
|| /aborted due to timeout|fetch failed|ECONNREFUSED|ECONNRESET|other side closed|socket/i.test(m);
|
||||
}
|
||||
|
||||
async function mcp(name, args = {}, { timeoutMs } = {}) {
|
||||
/** 找 shell 进程的日志目录(目录名形如 20261123_102339,7568) */
|
||||
function shellLogDirs(shellId) {
|
||||
if (!existsSync(LOG_ROOT)) return [];
|
||||
const want = String(shellId);
|
||||
const out = [];
|
||||
for (const name of readdirSync(LOG_ROOT)) {
|
||||
const m = name.match(/(?:,|_)(\d+)$/);
|
||||
if (!m || m[1] !== want) continue;
|
||||
const dir = path.join(LOG_ROOT, name);
|
||||
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
|
||||
out.push({ name, dir });
|
||||
}
|
||||
// 目录名自带时间戳,倒序即最新在前
|
||||
out.sort((a, b) => b.name.localeCompare(a.name));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 从日志里取这个 shell 的直连 MCP 端口 */
|
||||
function discoverShellPort(shellId, { fresh = false } = {}) {
|
||||
const id = String(shellId);
|
||||
if (!fresh) {
|
||||
const cached = shellPorts.get(id);
|
||||
if (cached) return cached.port;
|
||||
}
|
||||
for (const { dir } of shellLogDirs(id)) {
|
||||
for (const file of ['last_info.txt', 'all_info.txt']) {
|
||||
const f = path.join(dir, file);
|
||||
if (!existsSync(f)) continue;
|
||||
const txt = readFileSync(f, 'utf8');
|
||||
const hits = [...txt.matchAll(PORT_RE)];
|
||||
const port = hits.length ? hits[hits.length - 1][1] : txt.match(LISTEN_RE)?.[1];
|
||||
if (port) {
|
||||
shellPorts.set(id, { port, dir });
|
||||
return port;
|
||||
}
|
||||
}
|
||||
}
|
||||
shellPorts.delete(id);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直连调用:shell 服务本来就是「当前课件」作用域,shellId 要脱掉
|
||||
* (带上反而可能被判成 shellId 与绑定窗口不一致)。
|
||||
*/
|
||||
async function directRpc(port, name, args = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
||||
const once = async (a) => {
|
||||
try {
|
||||
return await rpcOn(port, name, a, timeoutMs);
|
||||
} catch (e) {
|
||||
// 端口被复用时旧会话会失效,重握手一次
|
||||
if (/session|会话/i.test(String(e.message))) {
|
||||
const st = sessionOf(port);
|
||||
st.sid = null;
|
||||
st.initialized = false;
|
||||
return await rpcOn(port, name, a, timeoutMs);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const clean = { ...args };
|
||||
const hadShell = Object.prototype.hasOwnProperty.call(clean, 'shellId');
|
||||
delete clean.shellId;
|
||||
try {
|
||||
return await once(clean);
|
||||
} catch (e) {
|
||||
if (hadShell && /shellId|绑定|绑定的|Usage error|请先调用/i.test(String(e.message))) {
|
||||
return await once(args);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** 判断这个 shell 该走云端还是直连;结果按 shell 缓存,避免每次都等超时 */
|
||||
async function routeFor(shellId) {
|
||||
const id = String(shellId);
|
||||
const cached = routes.get(id);
|
||||
if (cached && cached.kind !== 'dead') return cached;
|
||||
// 已知彻底不通时不要每次调用都重等两轮探测,15 秒后再试
|
||||
if (cached && cached.kind === 'dead' && Date.now() - (cached.at ?? 0) < 15000) return cached;
|
||||
|
||||
let cloudError = null;
|
||||
try {
|
||||
await rpcOn(MCP_PORT, 'get_current_courseware_info', { shellId: id }, PROBE_TIMEOUT_MS);
|
||||
const r = { kind: 'cloud', port: discoverShellPort(id), at: Date.now() };
|
||||
routes.set(id, r);
|
||||
return r;
|
||||
} catch (e) {
|
||||
if (!isTransportError(e)) {
|
||||
// 有业务返回,说明云端代理是通的
|
||||
const r = { kind: 'cloud', port: discoverShellPort(id), at: Date.now() };
|
||||
routes.set(id, r);
|
||||
return r;
|
||||
}
|
||||
cloudError = e;
|
||||
}
|
||||
|
||||
const port = discoverShellPort(id, { fresh: true });
|
||||
if (port) {
|
||||
try {
|
||||
await rpcOn(port, 'get_current_courseware_info', {}, PROBE_TIMEOUT_MS);
|
||||
const r = { kind: 'direct', port, reason: `云端代理无响应(${cloudError.message}),改走直连 ${port}`, at: Date.now() };
|
||||
routes.set(id, r);
|
||||
return r;
|
||||
} catch (e) {
|
||||
cloudError = new Error(`${cloudError.message};直连 ${port} 也失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
const r = { kind: 'dead', port, reason: String(cloudError?.message || '未知'), at: Date.now() };
|
||||
routes.set(id, r);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** 带 shellId 的工具调用:云端代理坏了就自动改直连 */
|
||||
async function callShellTool(name, args = {}, { timeoutMs = DEFAULT_TIMEOUT_MS, shellId } = {}) {
|
||||
const id = String(shellId);
|
||||
const route = await routeFor(id);
|
||||
|
||||
if (route.kind === 'dead') {
|
||||
throw new Error(
|
||||
`云端 MCP 到 shell ${id} 的代理没有响应,也找不到可用的直连端口。`
|
||||
+ `原因:${route.reason}。请重启希沃白板后重试。`,
|
||||
);
|
||||
}
|
||||
|
||||
if (route.kind === 'cloud') {
|
||||
try {
|
||||
return await rpcOn(MCP_PORT, name, args, timeoutMs);
|
||||
} catch (e) {
|
||||
if (!isTransportError(e)) throw e;
|
||||
// 探活通过但这次仍超时:立即降级,别让调用方干等
|
||||
const port = discoverShellPort(id, { fresh: true });
|
||||
if (port) {
|
||||
try {
|
||||
const r = await directRpc(port, name, args, timeoutMs);
|
||||
routes.set(id, { kind: 'direct', port, reason: `云端代理超时(${e.message}),改走直连 ${port}`, at: Date.now() });
|
||||
return r;
|
||||
} catch (e2) {
|
||||
routes.set(id, { kind: 'dead', port, reason: `${e.message};直连失败:${e2.message}`, at: Date.now() });
|
||||
throw e2;
|
||||
}
|
||||
}
|
||||
routes.set(id, { kind: 'dead', port: null, reason: e.message, at: Date.now() });
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return await directRpc(route.port, name, args, timeoutMs);
|
||||
} catch (e) {
|
||||
// shell 重启后端口会变,重新发现一次
|
||||
const port = discoverShellPort(id, { fresh: true });
|
||||
if (port && port !== route.port) {
|
||||
const r = await directRpc(port, name, args, timeoutMs);
|
||||
routes.set(id, { kind: 'direct', port, at: Date.now() });
|
||||
return r;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function mcp(name, args = {}, { timeoutMs, direct = false } = {}) {
|
||||
const shellId = args && args.shellId != null ? String(args.shellId) : null;
|
||||
if (!direct && shellId && !CLOUD_ONLY.has(name)) {
|
||||
return callShellTool(name, args, { timeoutMs: timeoutMs ?? DEFAULT_TIMEOUT_MS, shellId });
|
||||
}
|
||||
await ensureInit();
|
||||
try {
|
||||
return await rpc(name, args, { timeoutMs });
|
||||
} catch (e) {
|
||||
// 会话过期时重新握手一次
|
||||
if (/session|会话|ShellId/i.test(String(e.message))) {
|
||||
sessionId = null;
|
||||
initialized = false;
|
||||
if (/session|会话/i.test(String(e.message))) {
|
||||
const st = sessionOf(MCP_PORT);
|
||||
st.sid = null;
|
||||
st.initialized = false;
|
||||
await ensureInit();
|
||||
return await rpc(name, args, { timeoutMs });
|
||||
}
|
||||
@@ -102,10 +319,54 @@ async function mcp(name, args = {}, { timeoutMs } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 给结果用:这个 shell 当前实际走的链路(cloud / direct) */
|
||||
export function shellRouteOf(shellId) {
|
||||
const r = routes.get(String(shellId));
|
||||
if (!r) return null;
|
||||
return { kind: r.kind, port: r.port ?? null, ...(r.reason ? { reason: r.reason } : {}) };
|
||||
}
|
||||
|
||||
/** 给 diagnose 用:这个 shell 的云端代理 / 直连端口各自是否可用 */
|
||||
export async function shellTransportOf(shellId) {
|
||||
const id = String(shellId);
|
||||
let cloud;
|
||||
try {
|
||||
const info = await rpcOn(MCP_PORT, 'get_current_courseware_info', { shellId: id }, PROBE_TIMEOUT_MS);
|
||||
cloud = { ok: true, info };
|
||||
} catch (e) {
|
||||
cloud = { ok: false, error: e.message };
|
||||
}
|
||||
const port = discoverShellPort(id, { fresh: true });
|
||||
let direct = { ok: false, port: port ?? null, ...(port ? {} : { error: '日志里没有找到该 shell 的 MCP 端口' }) };
|
||||
if (port) {
|
||||
try {
|
||||
const info = await rpcOn(port, 'get_current_courseware_info', {}, PROBE_TIMEOUT_MS);
|
||||
direct = { ok: true, port, info };
|
||||
} catch (e) {
|
||||
direct = { ok: false, port, error: e.message };
|
||||
}
|
||||
}
|
||||
// 顺便把探活结果写进路由缓存,diagnose 之后的调用不用再等一次超时
|
||||
if (cloud.ok) routes.set(id, { kind: 'cloud', port: direct.port ?? null, at: Date.now() });
|
||||
else if (direct.ok) routes.set(id, { kind: 'direct', port, reason: `云端代理无响应(${cloud.error}),改走直连 ${port}`, at: Date.now() });
|
||||
else routes.set(id, { kind: 'dead', port: direct.port ?? null, reason: String(cloud.error || direct.error || '未知'), at: Date.now() });
|
||||
return { cloud, direct, route: routes.get(id) ?? null };
|
||||
}
|
||||
|
||||
const shells = () => mcp('en_find_shells', { searchingMode: 'All' })
|
||||
.then(r => r.data?.shells ?? [])
|
||||
.catch(() => []);
|
||||
|
||||
/**
|
||||
* 希沃有的工具只回文本 JSON、没有 structuredContent。
|
||||
* 只读 data 会让「内存页数/大小」检查悄悄失效,所以这里统一兜底解析。
|
||||
*/
|
||||
function infoOf(r) {
|
||||
if (!r) return null;
|
||||
if (r.data && typeof r.data === 'object') return r.data;
|
||||
try { return JSON.parse(String(r.text || '')); } catch { return null; }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 课件定位
|
||||
export function listCoursewares() {
|
||||
const out = [];
|
||||
@@ -923,7 +1184,7 @@ async function shellsForCourseware(cw) {
|
||||
const out = [];
|
||||
for (const s of sameName) {
|
||||
const info = await mcp('get_current_courseware_info', { shellId: s.id }, { timeoutMs: 12000 }).catch(() => null);
|
||||
const rid = String(info?.data?.remoteId ?? '').toLowerCase();
|
||||
const rid = String(infoOf(info)?.remoteId ?? '').toLowerCase();
|
||||
if (rid === want) out.push(s);
|
||||
}
|
||||
return out;
|
||||
@@ -947,7 +1208,7 @@ async function waitCoursewareLoaded(shellId, expectedPages, { timeoutMs = 25000
|
||||
await sleep(800);
|
||||
continue;
|
||||
}
|
||||
const d = info?.data ?? {};
|
||||
const d = infoOf(info) ?? {};
|
||||
if (typeof d.slideCount === 'number') {
|
||||
if (d.slideCount === expectedPages) return { loaded: true, info: d };
|
||||
if (last && d.slideCount === last.slideCount) stable++;
|
||||
@@ -964,12 +1225,34 @@ async function closeForWrite(cw, force) {
|
||||
await ensureInit();
|
||||
const open = await shellsForCourseware(cw);
|
||||
if (!open.length) return { wasOpen: false, closed: 0 };
|
||||
|
||||
// 多实例:每个窗口各存一份副本,后关闭的会覆盖先关闭的。
|
||||
if (open.length > 1 && !force) {
|
||||
throw new Error(
|
||||
`课件「${cw.name}」同时打开了 ${open.length} 个窗口(shell ${open.map(s => s.id).join(' / ')})。`
|
||||
+ '多个实例各自保存一份内容,写入后必然互相覆盖。'
|
||||
+ '请先手动关掉多余窗口只留一个,或传 force=true 让 kit 全部关掉后再写。',
|
||||
);
|
||||
}
|
||||
|
||||
// 授课模式:切回备课会把该模式下新建/修改的内容丢掉,不能悄悄替用户决定。
|
||||
const displayShells = open.filter(s => String(s.workingMode || 'Edit') !== 'Edit');
|
||||
if (displayShells.length && !force) {
|
||||
throw new Error(
|
||||
`课件「${cw.name}」当前在授课(Display)界面(shell ${displayShells.map(s => s.id).join(' / ')})。`
|
||||
+ '切回备课界面会丢弃在授课界面里新建/修改的页和元素,kit 不会替你做这个决定。'
|
||||
+ '请先在希沃里回到备课界面;确认这些改动不要了,再传 force=true。',
|
||||
);
|
||||
}
|
||||
|
||||
const diskPages = slideRecords(cw).length;
|
||||
const diskSize = cw.json.Courseware.Size;
|
||||
for (const s of open) {
|
||||
// 先切回备课界面:授课模式下页面列表可能还没就绪,get_current_courseware_info 会卡住或返回 0 页
|
||||
// 只有确实不在备课界面时才切:这个切换本身会丢掉授课模式下的改动
|
||||
if (String(s.workingMode || 'Edit') !== 'Edit') {
|
||||
await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {});
|
||||
await sleep(600);
|
||||
}
|
||||
let { loaded, info: d } = await waitCoursewareLoaded(s.id, diskPages);
|
||||
if (!loaded) {
|
||||
// 再给一次机会:重新切界面后再等
|
||||
@@ -1012,7 +1295,12 @@ async function closeForWrite(cw, force) {
|
||||
+ '请手动关闭课件或重启希沃后重试。',
|
||||
);
|
||||
}
|
||||
return { wasOpen: true, closed: open.length };
|
||||
return {
|
||||
wasOpen: true,
|
||||
closed: open.length,
|
||||
modes: open.map(s => String(s.workingMode || 'Edit')),
|
||||
discardedDisplayEdits: displayShells.length > 0 && !!force,
|
||||
};
|
||||
}
|
||||
|
||||
async function openCourseware(cwOrName, expectedPages = null) {
|
||||
@@ -1033,7 +1321,7 @@ async function openCourseware(cwOrName, expectedPages = null) {
|
||||
const want = String(cw.json?.Courseware?.RemoteId ?? '').toLowerCase();
|
||||
if (want) {
|
||||
const info = await mcp('get_current_courseware_info', { shellId: s.id }, { timeoutMs: 12000 }).catch(() => null);
|
||||
const got = String(info?.data?.remoteId ?? '').toLowerCase();
|
||||
const got = String(infoOf(info)?.remoteId ?? '').toLowerCase();
|
||||
if (got && got !== want) {
|
||||
await mcp('close_current_courseware', { shellId: s.id, syncBeforeClose: false }).catch(() => {});
|
||||
throw new Error(
|
||||
@@ -1050,7 +1338,7 @@ async function openCourseware(cwOrName, expectedPages = null) {
|
||||
/** 做一次无害改动,让希沃认为课件「未同步」,否则 sync 只会下载 */
|
||||
async function touch(shellId) {
|
||||
const info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 15000 }).catch(() => null);
|
||||
const count = info?.data?.slideCount ?? 0;
|
||||
const count = infoOf(info)?.slideCount ?? 0;
|
||||
if (!count) return;
|
||||
const add = await mcp('add_slide', { shellId, slideNumber: count }).catch(() => null);
|
||||
const added = add?.data?.slideNumber;
|
||||
@@ -1065,8 +1353,12 @@ async function ensureEditMode(shellId, { timeoutMs = 20000 } = {}) {
|
||||
let mode = null;
|
||||
let tries = 0;
|
||||
while (Date.now() < deadline) {
|
||||
// 首选云端窗口列表里的 workingMode(直连端口的 get_current_courseware_info 不带 shellContext)
|
||||
const cur = (await shells()).find(s => String(s.id) === String(shellId));
|
||||
mode = cur?.workingMode ?? mode;
|
||||
if (mode === 'Edit') return true;
|
||||
const info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 12000 }).catch(() => null);
|
||||
mode = info?.data?.shellContext?.workingMode ?? mode;
|
||||
mode = infoOf(info)?.shellContext?.workingMode ?? mode;
|
||||
if (mode === 'Edit') return true;
|
||||
if (tries % 2 === 0) await mcp('en_goto_app_ui', { ui: 'Edit', shellId }).catch(() => {});
|
||||
tries++;
|
||||
@@ -1075,7 +1367,18 @@ async function ensureEditMode(shellId, { timeoutMs = 20000 } = {}) {
|
||||
return mode === 'Edit';
|
||||
}
|
||||
|
||||
async function syncShell(shellId) {
|
||||
async function syncShell(shellId, { force = false } = {}) {
|
||||
// 授课模式下切到备课会丢掉该界面的改动,同步之前先拦住
|
||||
if (!force) {
|
||||
const cur = (await shells()).find(s => String(s.id) === String(shellId));
|
||||
const mode = cur?.workingMode ?? null;
|
||||
if (mode && mode !== 'Edit') {
|
||||
throw new Error(
|
||||
`课件当前停在「${mode}」界面,同步需要切回备课,而切换会丢弃在该界面里新建/修改的内容。`
|
||||
+ '请先在希沃里回到备课界面;确认改动不要了再传 force=true。',
|
||||
);
|
||||
}
|
||||
}
|
||||
const opts = { timeoutMs: 180000 };
|
||||
const push = () => mcp('sync_current_courseware', { shellId, waitUntilSynced: true, waitSeconds: 120 }, opts)
|
||||
.catch(e => ({ text: 'ERR ' + e.message }));
|
||||
@@ -1107,18 +1410,34 @@ function serial(fn) {
|
||||
return p;
|
||||
}
|
||||
|
||||
/** 写前给所有页面文件做一次指纹,用来确认「工具说成功了,磁盘上真的变了」 */
|
||||
function snapshotSlideFiles(cw) {
|
||||
const map = new Map();
|
||||
for (const rec of slideRecords(cw)) {
|
||||
try { map.set(rec.FileName, md5File(path.join(cw.dir, rec.FileName))); } catch { /* 读不到就跳过 */ }
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
async function runEdit(cw, opts, action) {
|
||||
return serial(async () => {
|
||||
const { wasOpen, closed } = await closeForWrite(cw, opts.force);
|
||||
const before = snapshotSlideFiles(cw);
|
||||
const { wasOpen, closed, modes = [], discardedDisplayEdits = false } = await closeForWrite(cw, opts.force);
|
||||
const backup = opts.backup === false ? null : backupCourseware({ courseware: cw.localId, note: 'auto-before-write' });
|
||||
let result;
|
||||
let changedPages = 0;
|
||||
try {
|
||||
result = await action(cw);
|
||||
finalize(cw);
|
||||
const after = snapshotSlideFiles(cw);
|
||||
changedPages = [...after.keys()].filter(k => before.get(k) !== after.get(k)).length;
|
||||
} catch (e) {
|
||||
e.message += backup ? `\n(改动前备份:${backup.backupId})` : '';
|
||||
throw e;
|
||||
}
|
||||
const warnings = [];
|
||||
if (!changedPages) warnings.push('工具返回成功,但磁盘上没有一页发生变化,请用 verify_courseware / inspect_courseware 确认改动是否真的落盘');
|
||||
if (discardedDisplayEdits) warnings.push('写入前课件在授课界面,按 force=true 切回备课,授课界面里未保存的改动已被丢弃');
|
||||
let shellId = null;
|
||||
let syncText = null;
|
||||
if (opts.reopen !== false) {
|
||||
@@ -1128,9 +1447,12 @@ async function runEdit(cw, opts, action) {
|
||||
return {
|
||||
...result,
|
||||
backupId: backup?.backupId ?? null,
|
||||
wasOpen, closed,
|
||||
wasOpen, closed, modes,
|
||||
changedPages,
|
||||
...(warnings.length ? { warnings } : {}),
|
||||
reopened: !!shellId,
|
||||
shellId,
|
||||
...(shellId ? { transport: shellRouteOf(shellId) } : {}),
|
||||
sync: syncText,
|
||||
};
|
||||
});
|
||||
@@ -1995,7 +2317,7 @@ export async function moveSlides({
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具:单独同步
|
||||
export async function syncCourseware({ courseware } = {}) {
|
||||
export async function syncCourseware({ courseware, force = false } = {}) {
|
||||
const cw = resolveCourseware(courseware);
|
||||
return serial(async () => {
|
||||
await ensureInit();
|
||||
@@ -2007,9 +2329,9 @@ export async function syncCourseware({ courseware } = {}) {
|
||||
shell = { id };
|
||||
opened = true;
|
||||
}
|
||||
const text = await syncShell(shell.id);
|
||||
const info = await mcp('get_current_courseware_info', { shellId: shell.id }, { timeoutMs: 15000 })
|
||||
.then(r => r.data ?? null).catch(() => null);
|
||||
const text = await syncShell(shell.id, { force });
|
||||
const info = infoOf(await mcp('get_current_courseware_info', { shellId: shell.id }, { timeoutMs: 15000 })
|
||||
.catch(() => null));
|
||||
return {
|
||||
courseware: cw.name,
|
||||
shellId: shell.id,
|
||||
@@ -2391,6 +2713,136 @@ export function preflightCourseware({
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具:写入前置诊断
|
||||
/**
|
||||
* 一次把「为什么会写丢」的几件事全查清楚:
|
||||
* 开了几个窗口、在备课还是授课、内存和磁盘页数/大小是否一致、有没有未同步改动、截图接口是否还活着。
|
||||
*/
|
||||
export async function diagnoseCourseware({ courseware, checkRender = false, renderPage = 1, timeoutSec = 45 } = {}) {
|
||||
const cw = resolveCourseware(courseware);
|
||||
const issues = [];
|
||||
const push = (level, code, message, extra = {}) => issues.push({ level, code, message, ...extra });
|
||||
|
||||
const slides = slidesInBoardOrder(cw);
|
||||
const revision = cw.json.Courseware.Revision;
|
||||
const syncedRevision = cw.json.Courseware.SyncedRevision;
|
||||
if (revision !== syncedRevision) {
|
||||
push('warn', 'unsynced', `本地 Revision=${revision},云端 SyncedRevision=${syncedRevision}(本地改动还没上传)`);
|
||||
}
|
||||
|
||||
const verify = verifyCourseware({ courseware: cw.localId, hashes: true, deep: false });
|
||||
for (const i of verify.issues) {
|
||||
if (i.level === 'error') push('error', `verify:${i.code}`, i.message);
|
||||
}
|
||||
|
||||
let live = { open: 0, shells: [] };
|
||||
try {
|
||||
await ensureInit();
|
||||
const list = (await shells()).filter(s => sameCourseware(s, cw));
|
||||
const details = [];
|
||||
for (const s of list) {
|
||||
const tr = await shellTransportOf(s.id);
|
||||
const info = tr.cloud.ok ? tr.cloud.info : (tr.direct.ok ? tr.direct.info : null);
|
||||
const d = infoOf(info) ?? {};
|
||||
if (!tr.cloud.ok && tr.direct.ok) {
|
||||
push('warn', 'proxy-dead',
|
||||
`shell ${s.id} 的云端 MCP 代理无响应(${tr.cloud.error}),kit 已自动改走直连端口 ${tr.direct.port};`
|
||||
+ '写操作仍可用,但云端代理要重启希沃才会恢复');
|
||||
} else if (!tr.cloud.ok && !tr.direct.ok) {
|
||||
push('error', 'shell-unreachable',
|
||||
`shell ${s.id} 的云端代理和直连端口都不可用(云端:${tr.cloud.error};直连:${tr.direct.error ?? '无端口'});此时不要写课件`);
|
||||
} else if (!info) {
|
||||
push('warn', 'shell-unresponsive', `shell ${s.id} 12 秒内没有响应(可能正在渲染、切换界面或关闭),此时不要写课件`);
|
||||
}
|
||||
details.push({
|
||||
shellId: String(s.id),
|
||||
workingMode: s.workingMode ?? d.shellContext?.workingMode ?? null,
|
||||
pages: typeof d.slideCount === 'number' ? d.slideCount : null,
|
||||
size: typeof d.size === 'number' ? d.size : null,
|
||||
remoteId: d.remoteId ?? null,
|
||||
transport: {
|
||||
cloud: tr.cloud.ok ? 'ok' : 'dead',
|
||||
...(tr.cloud.ok ? {} : { cloudError: tr.cloud.error }),
|
||||
direct: tr.direct.ok ? 'ok' : 'dead',
|
||||
directPort: tr.direct.port ?? null,
|
||||
...(tr.direct.ok ? {} : (tr.direct.error ? { directError: tr.direct.error } : {})),
|
||||
},
|
||||
});
|
||||
}
|
||||
live = { open: details.length, shells: details };
|
||||
} catch (e) {
|
||||
push('error', 'live', `查询希沃窗口失败:${e.message}`);
|
||||
}
|
||||
|
||||
if (live.open > 1) {
|
||||
push('error', 'multi-instance',
|
||||
`同时打开了 ${live.open} 个窗口(shell ${live.shells.map(s => s.shellId).join(' / ')}),写操作会互相覆盖;先关掉多余的,只留一个`);
|
||||
}
|
||||
for (const s of live.shells) {
|
||||
if (s.workingMode && s.workingMode !== 'Edit') {
|
||||
push('warn', 'display-mode', `shell ${s.shellId} 停在「${s.workingMode}」界面,切回备课会丢弃在该界面里新建/修改的内容`);
|
||||
}
|
||||
if (s.pages != null && s.pages !== slides.length) {
|
||||
push('warn', 'memory-pages', `shell ${s.shellId} 内存里 ${s.pages} 页,磁盘 ${slides.length} 页(未保存改动,或还在加载)`);
|
||||
}
|
||||
if (s.size != null && cw.json.Courseware.Size != null && s.size !== cw.json.Courseware.Size) {
|
||||
push('info', 'memory-size', `shell ${s.shellId} 内存大小 ${s.size},磁盘 ${cw.json.Courseware.Size}(有未落盘的改动)`);
|
||||
}
|
||||
}
|
||||
|
||||
let render = null;
|
||||
if (checkRender) {
|
||||
const target = live.shells[0];
|
||||
if (!target) {
|
||||
render = { ok: false, error: '课件没有打开,无法测试截图接口' };
|
||||
push('warn', 'render', render.error);
|
||||
} else {
|
||||
const file = path.join(TMP, `diag-${cw.localId}-p${renderPage}.png`);
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
if (existsSync(file)) rmSync(file, { force: true });
|
||||
await mcp('get_slide_screenshot',
|
||||
{ slideNumber: renderPage, expectedPngImageFilePath: file, shellId: target.shellId },
|
||||
{ timeoutMs: Math.max(10, Number(timeoutSec) || 45) * 1000 });
|
||||
const bytes = existsSync(file) ? statSync(file).size : 0;
|
||||
render = { ok: bytes > 2048, page: renderPage, bytes, ms: Date.now() - startedAt, path: file };
|
||||
if (!render.ok) push('warn', 'render', `截图只拿到 ${bytes} 字节,渲染可能没起来`);
|
||||
} catch (e) {
|
||||
render = { ok: false, page: renderPage, ms: Date.now() - startedAt, error: e.message };
|
||||
push('error', 'render', `截图 ${timeoutSec} 秒没返回(云端代理和 shell 直连都没成功);重启希沃后再继续`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { backups } = listBackups({ courseware: cw.localId, limit: 3 });
|
||||
const counts = {
|
||||
errors: issues.filter(x => x.level === 'error').length,
|
||||
warnings: issues.filter(x => x.level === 'warn').length,
|
||||
infos: issues.filter(x => x.level === 'info').length,
|
||||
};
|
||||
const order = { error: 0, warn: 1, info: 2 };
|
||||
issues.sort((x, y) => order[x.level] - order[y.level]);
|
||||
return {
|
||||
courseware: cw.name,
|
||||
localId: cw.localId,
|
||||
ok: counts.errors === 0,
|
||||
safeToWrite: counts.errors === 0,
|
||||
pages: slides.length,
|
||||
revision,
|
||||
syncedRevision,
|
||||
live,
|
||||
render,
|
||||
latestBackups: backups.map(b => ({ backupId: b.backupId, note: b.note, createdAt: b.createdAt })),
|
||||
counts,
|
||||
issues,
|
||||
tips: issues.length ? [
|
||||
'multi-instance/display-mode 两种报错都不是让你忽略的:它们说明希沃里有多份内容,任何一方保存都会覆盖另一方。',
|
||||
'proxy-dead 表示云端 MCP 到该窗口的转发链路坏了:kit 会自动走直连端口,写入不受影响,但重启希沃才会修好云端代理。',
|
||||
'render 报错时不要反复重试截图,重启希沃最快。',
|
||||
] : [],
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具:撤销上一次写操作
|
||||
export async function undoLastEdit({
|
||||
courseware, confirm = false, reopen = true, sync = false, force = false,
|
||||
@@ -2818,7 +3270,10 @@ export async function exportSlides({
|
||||
shell = { id };
|
||||
opened = true;
|
||||
}
|
||||
await ensureEditMode(shell.id);
|
||||
// 授课界面也能截图;这时千万不要切回备课,否则会把该界面的改动丢掉
|
||||
const modeNow = (await shells()).find(s => String(s.id) === String(shell.id))?.workingMode ?? null;
|
||||
const keptDisplayMode = modeNow === 'Display';
|
||||
if (!keptDisplayMode) await ensureEditMode(shell.id);
|
||||
|
||||
const dir = outDir
|
||||
? (path.isAbsolute(outDir) ? outDir : path.join(TMP, 'seewo-kit-export', outDir))
|
||||
@@ -2827,6 +3282,9 @@ export async function exportSlides({
|
||||
const pad = Math.max(2, String(Math.max(...nums)).length);
|
||||
const timeoutMs = Math.max(30, Number(timeoutSec) || 180) * 1000;
|
||||
const files = [];
|
||||
let consecutiveTimeouts = 0;
|
||||
let aborted = false;
|
||||
let abortedReason = null;
|
||||
for (const n of nums) {
|
||||
const name = fileNamePattern
|
||||
? String(fileNamePattern).replace(/\{page\}/g, String(n)).replace(/\{index\}/g, String(n).padStart(pad, '0'))
|
||||
@@ -2835,12 +3293,18 @@ export async function exportSlides({
|
||||
let bytes = 0;
|
||||
let lastError = null;
|
||||
let timedOut = false;
|
||||
let stale = false;
|
||||
let attempts = 0;
|
||||
for (let attempt = 0; attempt < Math.max(1, Number(retries) || 1); attempt++) {
|
||||
attempts = attempt + 1;
|
||||
// 上一次可能留下 0 字节文件;先删掉,避免把空文件当成成功
|
||||
if (existsSync(file) && statSync(file).size === 0) rmSync(file, { force: true });
|
||||
// 每次截图前都删掉旧文件:同路径残留的上一张图会被误当成这次的成功结果
|
||||
if (existsSync(file)) rmSync(file, { force: true });
|
||||
let startedAt = Date.now();
|
||||
try {
|
||||
// 先切到目标页,否则希沃偶尔把上一页的旧帧当成这一页返回
|
||||
await mcp('goto_slide', { slideNumber: n, shellId: shell.id }, { timeoutMs: 20000 }).catch(() => {});
|
||||
await sleep(Math.min(400, Math.max(0, Number(settleMs) || 0)));
|
||||
startedAt = Date.now();
|
||||
const r = await mcp(
|
||||
'get_slide_screenshot',
|
||||
{ slideNumber: n, expectedPngImageFilePath: file, shellId: shell.id },
|
||||
@@ -2848,9 +3312,14 @@ export async function exportSlides({
|
||||
);
|
||||
if (existsSync(file)) {
|
||||
bytes = statSync(file).size;
|
||||
if (bytes >= minBytes) break;
|
||||
const fresh = statSync(file).mtimeMs >= startedAt - 1000;
|
||||
if (bytes >= minBytes && fresh) break;
|
||||
if (bytes >= minBytes && !fresh) {
|
||||
stale = true;
|
||||
lastError = '截图接口返回的是本次调用之前生成的旧文件(可能是渲染线程卡住的旧帧)';
|
||||
}
|
||||
lastError = `截图接口返回了,但文件只有 ${bytes} 字节(${r.text.slice(0, 120)})`;
|
||||
}
|
||||
if (!lastError) lastError = `截图接口返回了,但文件只有 ${bytes} 字节(${r.text.slice(0, 120)})`;
|
||||
} catch (e) {
|
||||
lastError = e.message;
|
||||
timedOut = /abort|timeout|超时/i.test(String(e.message));
|
||||
@@ -2860,17 +3329,27 @@ export async function exportSlides({
|
||||
if (timedOut) break;
|
||||
}
|
||||
if (existsSync(file) && statSync(file).size < minBytes) rmSync(file, { force: true });
|
||||
const ok = bytes >= minBytes;
|
||||
const ok = bytes >= minBytes && !stale;
|
||||
consecutiveTimeouts = ok ? 0 : (timedOut ? consecutiveTimeouts + 1 : 0);
|
||||
files.push({
|
||||
page: n, path: file, bytes, attempts,
|
||||
...(ok ? {} : {
|
||||
error: timedOut
|
||||
? `截图超时(${timeoutSec} 秒)。请确认希沃窗口在前台、课件已完整加载;必要时重启希沃后重试,或调大 timeoutSec。`
|
||||
? `截图超时(${timeoutSec} 秒):云端代理和 shell 直连都没有返回。请确认希沃窗口已完整加载,必要时重启希沃,或调大 timeoutSec。`
|
||||
: (lastError ?? '没有生成截图文件'),
|
||||
timedOut,
|
||||
timedOut, ...(stale ? { stale: true } : {}),
|
||||
}),
|
||||
});
|
||||
if (!ok && stopOnError) break;
|
||||
if (!ok && stopOnError) {
|
||||
aborted = true;
|
||||
break;
|
||||
}
|
||||
// 连续两页超时基本可以断定链路已死,继续只会更慢
|
||||
if (consecutiveTimeouts >= 2) {
|
||||
aborted = true;
|
||||
abortedReason = `连续 ${consecutiveTimeouts} 页截图超时(云端代理与直连都不可用),请重启希沃后再导出`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const succeeded = files.filter(f => f.bytes >= minBytes).length;
|
||||
const failed = files.length - succeeded;
|
||||
@@ -2878,8 +3357,16 @@ export async function exportSlides({
|
||||
ok: failed === 0 && files.length === nums.length,
|
||||
courseware: cw.name, localId: cw.localId,
|
||||
shellId: shell.id, opened, outDir: dir,
|
||||
workingMode: modeNow,
|
||||
...(shellRouteOf(shell.id) ? { transport: shellRouteOf(shell.id) } : {}),
|
||||
...(keptDisplayMode ? { note: '课件停在授课界面:为免丢内容没有切回备课,截图即当前授课画面。' } : {}),
|
||||
count: files.length, requested: nums.length,
|
||||
succeeded, failed, skipped: nums.length - files.length,
|
||||
aborted,
|
||||
...(aborted ? {
|
||||
hint: abortedReason
|
||||
?? '已中止剩余页面:截图一直超时(云端代理与直连都不可用)。重启希沃、让课件完整加载后再导出,比继续等更快。',
|
||||
} : {}),
|
||||
timeoutSec, files,
|
||||
};
|
||||
}
|
||||
|
||||
+25
-2
@@ -8,8 +8,10 @@
|
||||
* 启动方式(OpenCode 配置):
|
||||
* "seewokit": { "type": "local", "command": ["node", "D:\\Documents\\Default Project\\seewo-anim\\kit\\server.mjs"] }
|
||||
*
|
||||
* 写操作内部会:关课件(不保存) → 自动备份 → 改缓存文件 → 更新索引/DB → 重新打开。
|
||||
* 写操作内部会:预检(多实例 / 停在授课界面 / 内存与磁盘页数不一致 → 直接拒绝)→ 关课件(不保存)
|
||||
* → 自动备份 → 改缓存文件 → 更新索引/DB → 重新打开 → 回报实际改动的页数和告警。
|
||||
* 前提:目标课件的未同步改动必须已经同步(内存页数/大小与磁盘不一致时会拒绝,除非 force=true)。
|
||||
* 想先看能不能安全写,用 diagnose_courseware。
|
||||
*/
|
||||
import { createInterface } from 'node:readline';
|
||||
import {
|
||||
@@ -20,6 +22,7 @@ import {
|
||||
diffCourseware, preflightCourseware, undoLastEdit,
|
||||
batchReplaceText, batchSetTextStyle, batchInspect,
|
||||
layoutElements, setSlideTransition, exportSlides, styleTextRange,
|
||||
diagnoseCourseware,
|
||||
} from './core.mjs';
|
||||
|
||||
const log = (...a) => console.error('[seewo-kit]', ...a);
|
||||
@@ -341,11 +344,13 @@ const TOOLS = [
|
||||
name: 'sync_courseware',
|
||||
description:
|
||||
'只做云同步,不改内容:课件没开会先打开,然后做一次无害改动(加页+删页)让希沃认为「有更新」,再上传。\n'
|
||||
+ '用于把本地 Revision 脏状态清干净,或把本地改动推上云。返回同步结果与 isSynced。',
|
||||
+ '用于把本地 Revision 脏状态清干净,或把本地改动推上云。返回同步结果与 isSynced。\n'
|
||||
+ '课件停在授课界面时会拒绝(切回备课会丢该界面的改动),确认不要了可传 force=true。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
courseware: { type: 'string', description: '课件名片段或 LocalId' },
|
||||
force: { type: 'boolean', default: false, description: '授课界面也强行切回备课再同步(会丢弃该界面的改动)' },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -385,6 +390,23 @@ const TOOLS = [
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'diagnose_courseware',
|
||||
description:
|
||||
'写操作前的诊断(只读,除 checkRender=true 时会截一张图)。'
|
||||
+ '一次查清:打开了几个希沃窗口、在备课还是授课界面、内存页数/大小与磁盘是否一致、有没有未同步改动、'
|
||||
+ '截图渲染线程是否还活着、最近备份。'
|
||||
+ 'safeToWrite=false 时不要写课件——最常见的原因是「同一个课件开了多个窗口」或「停在授课界面」,这两种都会让改动互相覆盖或直接丢失。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
courseware: { type: 'string', description: '课件名片段或 LocalId' },
|
||||
checkRender: { type: 'boolean', default: false, description: '是否顺手测一次截图接口(检测渲染线程是否卡死)' },
|
||||
renderPage: { type: 'integer', minimum: 1, default: 1, description: 'checkRender=true 时截哪一页' },
|
||||
timeoutSec: { type: 'integer', minimum: 10, default: 45, description: '截图超时秒数' },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'undo_last_edit',
|
||||
description:
|
||||
@@ -631,6 +653,7 @@ const HANDLERS = {
|
||||
remove_local_courseware: removeLocalCourseware,
|
||||
diff_courseware: diffCourseware,
|
||||
preflight_courseware: preflightCourseware,
|
||||
diagnose_courseware: diagnoseCourseware,
|
||||
undo_last_edit: undoLastEdit,
|
||||
batch_replace_text: batchReplaceText,
|
||||
batch_set_text_style: batchSetTextStyle,
|
||||
|
||||
Reference in New Issue
Block a user