send-to-pi 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,9 +25,9 @@ Traditionally, sending webpage context to an agent means:
25
25
  Right-click on any selected text, link, or page ➔ **The text is instantly formatted into Markdown and prefilled into your Pi terminal input box**, with the source title & URL cleanly formatted.
26
26
  - 🎯 **Prefill Mode (No Auto-Submit)**: The prompt is populated into the editor without auto-submitting. You can review, refine, or append instructions before pressing <kbd>Enter</kbd>.
27
27
  - 📝 **HTML to Markdown Preservation**: Selection captures `<pre><code>` blocks, language tags, indentation, `<table>` grids, lists, quotes, and links without loss. Falls back gracefully when restricted.
28
- - 📖 **Clean Article Extraction (Readability Mode)**: Extract clean article markdown stripped of navigation, footers, sidebars, and ads. Pi gets immediate full-text context without extra fetching.
28
+ - 📖 **Clean Article Extraction (Readability Mode)**: Extract clean article markdown stripped of navigation, footers, sidebars, and ads. X/Twitter pages target the main tweet/article instead of scanning the entire body, then fall back to title and link.
29
29
  - ⌨️ **Keyboard Shortcut**: Instant delivery with <kbd>Alt+Shift+S</kbd> (<kbd>Cmd+Shift+S</kbd> on macOS) right after highlighting text or code.
30
- - 🔄 **Dynamic Port Discovery & Anti-Collision**: Pi sessions automatically probe 18091~18095 and track the most active session in `~/.pi/send-to-pi.json`.
30
+ - 🔄 **Dynamic Port Discovery & Session Routing**: Pi sessions probe 18091~18095 and register in `~/.pi/send-to-pi/sessions.json`. The Bridge routes to the most recent healthy session and keeps the legacy `~/.pi/send-to-pi.json` format compatible.
31
31
  - ⚡ **Cold-Start Auto-Wake**: If Pi isn't running, it automatically opens your terminal, starts Pi, and populates the text once the session boots up.
32
32
  - 🍏 **True Cross-Platform**: Native terminal launch support for **macOS** (Terminal.app, iTerm2, Ghostty, WezTerm), **Windows** (Windows Terminal, PowerShell), and **Linux**.
33
33
  - 🔒 **100% Local & Private**: All communication happens via `127.0.0.1`. No cloud proxy, no data logging.
@@ -47,7 +47,8 @@ sequenceDiagram
47
47
  User->>Browser: Select or Extract Article (Menu / Shortcut)
48
48
  Browser->>Bridge: HTTP POST /send (Markdown, URL, Title)
49
49
  alt Active Pi Running
50
- Bridge->>Bridge: Read ~/.pi/send-to-pi.json or probe ports
50
+ Bridge->>Bridge: Read and clean ~/.pi/send-to-pi/sessions.json
51
+ Bridge->>Bridge: Fall back to ~/.pi/send-to-pi.json or probe ports
51
52
  Bridge->>Pi: Forward to port /receive
52
53
  Pi->>Pi: ctx.ui.setEditorText() (Prefill)
53
54
  Bridge-->>Browser: 200 OK (Prefilled)
@@ -144,6 +145,13 @@ PI_TERMINAL=ghostty PI_WORKDIR=~/mycode npx send-to-pi start
144
145
 
145
146
  ---
146
147
 
148
+ ## 🆕 v1.2.0 Changes
149
+
150
+ - Fixed X/Twitter article extraction without reading the full page body.
151
+ - Preserved selection and link sending modes.
152
+ - Added multi-session registry and recent healthy-session routing.
153
+ - Added `activeAt`, `terminal`, and `window` session metadata for future terminal routing.
154
+
147
155
  ## 🤝 Contributing
148
156
 
149
157
  Contributions are warmly welcome! Whether it's:
package/README_CN.md CHANGED
@@ -25,9 +25,9 @@
25
25
  在任何网页上划选文字、提取文章或点击链接 ➔ **内容自动携带网页标题与来源 URL,毫秒级预填进 Pi 终端输入框**。
26
26
  - 🎯 **Prefill 预填模式(绝不自作主张回车)**:内容送到输入框后,光标停留在末尾,你可以从容补充具体指令(如“请根据这段代码重构...”),最后按回车自主发送。
27
27
  - 📝 **HTML 智能转 Markdown(保留代码与表格格式)**:划词内容自动识别并还原 `<pre><code>` 语言/缩进、`<table>` 表格、列表、引用及超链接;页面受限时自动平滑降级。
28
- - 📖 **整页正文提取(Readability 模式)**:右键点击“发送精简文章”,自动剔除页眉、页脚、侧边栏及广告噪声,将干净的正文转为 Markdown 一键交付,终端无需再额外发起网络请求。
28
+ - 📖 **整页正文提取(Readability 模式)**:自动剔除页眉、页脚、侧边栏及广告噪声。X/Twitter 页面只提取主 tweet/article,不读取整个 body;失败时回退为标题与链接。
29
29
  - ⌨️ **快捷键一键直达**:支持全局划选快捷键(默认 <kbd>Alt+Shift+S</kbd> / Mac <kbd>Cmd+Shift+S</kbd>),无需右键鼠标二次点击。
30
- - 🔄 **动态端口发现与防串台**:Pi 会话自动在 18091~18095 范围内探测可用端口,并通过 `~/.pi/send-to-pi.json` 维护活跃实例,多窗口共存不冲突。
30
+ - 🔄 **动态端口发现与会话路由**:Pi 会话自动探测 18091~18095,并写入 `~/.pi/send-to-pi/sessions.json`。Bridge 优先路由最近的健康会话,并兼容旧版 `~/.pi/send-to-pi.json`。
31
31
  - ⚡ **冷启动自动唤醒终端**:若当前未运行 Pi,自动为你拉起终端、启动 `pi`,并在会话初始化完成后自动填入内容!
32
32
  - 🍏 **全平台终端适配**:原生支持 **macOS**(Terminal.app、iTerm2、Ghostty、WezTerm 等)、**Windows**(Windows Terminal、PowerShell)以及 **Linux**。
33
33
  - 🔒 **纯本地与隐私安全**:全链路通过本地环回地址 `127.0.0.1` 传输,无云端中转,零数据收集。
@@ -47,7 +47,8 @@ sequenceDiagram
47
47
  User->>Browser: 划选/文章提取 (右键或快捷键)
48
48
  Browser->>Bridge: HTTP POST /send (Markdown、URL、标题)
49
49
  alt 存在活跃 Pi 会话
50
- Bridge->>Bridge: 读取 ~/.pi/send-to-pi.json 或端口探测
50
+ Bridge->>Bridge: 读取并清理 ~/.pi/send-to-pi/sessions.json
51
+ Bridge->>Bridge: 回退读取 ~/.pi/send-to-pi.json 或端口探测
51
52
  Bridge->>Pi: 转发至对应端口 /receive
52
53
  Pi->>Pi: ctx.ui.setEditorText() (预填到输入框)
53
54
  Bridge-->>Browser: 200 OK (已填入输入框)
@@ -147,6 +148,13 @@ PI_TERMINAL=ghostty PI_WORKDIR=~/mycode npx send-to-pi start
147
148
 
148
149
  ---
149
150
 
151
+ ## 🆕 v1.2.0 变更
152
+
153
+ - 修复 X/Twitter 文章提取,避免读取整个页面 body。
154
+ - 保留选中内容与链接发送模式。
155
+ - 新增多 Pi 会话注册表及最近健康会话路由。
156
+ - 注册会话预留 `activeAt`、`terminal`、`window` 字段。
157
+
150
158
  ## 🤝 欢迎贡献
151
159
 
152
160
  欢迎提交 PR 或 Issue!无论是:
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Send to Pi - Chrome Background Service Worker
3
- * Version: 1.1.0
3
+ * Version: 1.2.0
4
4
  */
5
5
 
6
6
  const DEFAULT_PORT = 18090;
@@ -279,6 +279,53 @@ function inPageExtractor(mode) {
279
279
  }
280
280
 
281
281
  if (mode === "article") {
282
+ // X/Twitter 页面不能读取整个 body:只尝试主 tweet 或文章节点。
283
+ const isXTwitter = /(^|\.)((twitter|x)\.com)$/i.test(window.location.hostname);
284
+ if (isXTwitter) {
285
+ const xSelectors = [
286
+ 'main [data-testid="twitter-article"]',
287
+ 'main [data-testid="article"]',
288
+ 'main article[data-testid="tweet"]',
289
+ '[data-testid="twitter-article"]',
290
+ '[data-testid="article"]',
291
+ 'article[data-testid="tweet"]',
292
+ 'main article',
293
+ 'article',
294
+ ];
295
+ let mainTweet = null;
296
+ for (const selector of xSelectors) {
297
+ mainTweet = document.querySelector(selector);
298
+ if (mainTweet) break;
299
+ }
300
+
301
+ // 某些 X 版本只标记 tweetText,向上定位其所属主 article。
302
+ if (!mainTweet) {
303
+ const tweetText = document.querySelector('[data-testid="tweetText"]');
304
+ mainTweet = tweetText ? tweetText.closest('article') : null;
305
+ }
306
+
307
+ if (!mainTweet) return null;
308
+
309
+ // X 的主 article 同时包含作者栏、头像、媒体和互动按钮。
310
+ // 只保留正文结构,避免把整个帖子壳层发送给 Pi。
311
+ const cleanTweet = mainTweet.cloneNode(true);
312
+ [
313
+ '[data-testid="User-Name"]',
314
+ '[data-testid="User-Names"]',
315
+ '[data-testid="UserDescription"]',
316
+ '[data-testid="tweetPhoto"]',
317
+ '[data-testid="videoPlayer"]',
318
+ '[role="group"]',
319
+ 'time',
320
+ 'img',
321
+ ].forEach((selector) => {
322
+ cleanTweet.querySelectorAll(selector).forEach((el) => el.remove());
323
+ });
324
+
325
+ const xMarkdown = domToMarkdown(cleanTweet);
326
+ return xMarkdown || null;
327
+ }
328
+
282
329
  // Readability 简版:整页正文提取
283
330
  const clone = document.body.cloneNode(true);
284
331
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Send to Pi (发送给 Pi)",
4
- "version": "1.1.0",
4
+ "version": "1.2.0",
5
5
  "description": "Send webpage snippets, URLs, or articles directly to your local Pi coding agent terminal.",
6
6
  "permissions": [
7
7
  "contextMenus",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "send-to-pi",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Send webpage snippets, URLs, or articles directly to your local Pi coding agent terminal.",
5
5
  "main": "server/src/index.js",
6
6
  "bin": {
@@ -4,9 +4,10 @@
4
4
 
5
5
  ## 作用
6
6
  1. 监听本地内部端口 `127.0.0.1:18091`,接收调度服务(Bridge Daemon)转发过来的网页摘录;
7
- 2. 收到内容后,通过 Pi 的原生 API `ctx.ui.setEditorText()` **预填到终端输入框(Prefill 模式)**;
8
- 3. **绝不自作主张自动回车发送**,光标停留在内容末尾,让开发者可以自由补充指令或微调内容;
9
- 4. 终端会话启动时,自动读取冷启动时暂存的文件(`~/.pi/pending-browser-input.txt`),无缝实现“唤醒终端并填入内容”。
7
+ 2. 将每个 Pi 会话注册到 `~/.pi/send-to-pi/sessions.json`,记录最近活跃时间及 `terminal`、`window` 路由元数据;
8
+ 3. 收到内容后,通过 Pi 的原生 API `ctx.ui.setEditorText()` **预填到终端输入框(Prefill 模式)**;
9
+ 4. **绝不自作主张自动回车发送**,光标停留在内容末尾,让开发者可以自由补充指令或微调内容;
10
+ 5. 终端会话启动时,自动读取冷启动时暂存的文件(`~/.pi/pending-browser-input.txt`),无缝实现“唤醒终端并填入内容”。
10
11
 
11
12
  ## 安装方式
12
13
 
@@ -25,6 +25,18 @@ function getPiHomeDir(): string {
25
25
  return dir;
26
26
  }
27
27
 
28
+ function getSendToPiDir(): string {
29
+ const dir = path.join(getPiHomeDir(), "send-to-pi");
30
+ try {
31
+ fs.mkdirSync(dir, { recursive: true });
32
+ } catch {}
33
+ return dir;
34
+ }
35
+
36
+ function getSessionRegistryFilePath(): string {
37
+ return path.join(getSendToPiDir(), "sessions.json");
38
+ }
39
+
28
40
  function getActiveSessionFilePath(): string {
29
41
  return path.join(getPiHomeDir(), "send-to-pi.json");
30
42
  }
@@ -37,28 +49,82 @@ function getPendingFilePaths(): string[] {
37
49
  ];
38
50
  }
39
51
 
52
+ type SessionRecord = {
53
+ id: string;
54
+ pid: number;
55
+ port: number;
56
+ workdir: string;
57
+ activeAt: number;
58
+ startedAt: number;
59
+ updatedAt: number;
60
+ terminal: string | null;
61
+ window: string | null;
62
+ };
63
+
64
+ function readSessionRecords(): SessionRecord[] {
65
+ try {
66
+ const registryFile = getSessionRegistryFilePath();
67
+ if (!fs.existsSync(registryFile)) return [];
68
+ const parsed = JSON.parse(fs.readFileSync(registryFile, "utf8"));
69
+ const sessions = Array.isArray(parsed) ? parsed : parsed?.sessions;
70
+ return Array.isArray(sessions) ? sessions : [];
71
+ } catch {
72
+ return [];
73
+ }
74
+ }
75
+
76
+ function writeSessionRecords(sessions: SessionRecord[]) {
77
+ const registryFile = getSessionRegistryFilePath();
78
+ const temporaryFile = `${registryFile}.tmp-${process.pid}`;
79
+ fs.writeFileSync(
80
+ temporaryFile,
81
+ JSON.stringify({ version: 1, sessions }, null, 2),
82
+ "utf8"
83
+ );
84
+ fs.renameSync(temporaryFile, registryFile);
85
+ }
86
+
40
87
  function recordActiveSession(port: number, workDir: string) {
41
88
  try {
42
- const sessionFile = getActiveSessionFilePath();
43
- const data = {
89
+ const now = Date.now();
90
+ const sessionId = `${process.pid}-${port}`;
91
+ const existingSessions = readSessionRecords();
92
+ const sessions = existingSessions.filter((session) => session.id !== sessionId);
93
+ const data: SessionRecord = {
94
+ id: sessionId,
44
95
  pid: process.pid,
45
96
  port,
46
97
  workdir: workDir,
47
- updatedAt: Date.now(),
98
+ activeAt: now,
99
+ startedAt: now,
100
+ updatedAt: now,
101
+ terminal: process.env.PI_TERMINAL || null,
102
+ window: process.env.PI_WINDOW_ID || null,
48
103
  };
49
- fs.writeFileSync(sessionFile, JSON.stringify(data, null, 2), "utf8");
104
+ const previous = existingSessions.find((session) => session.id === sessionId);
105
+ if (previous) data.startedAt = previous.startedAt;
106
+ sessions.push(data);
107
+ writeSessionRecords(sessions);
108
+
109
+ // Keep the pre-1.2.0 single-session file for older Bridge versions.
110
+ fs.writeFileSync(getActiveSessionFilePath(), JSON.stringify(data, null, 2), "utf8");
50
111
  } catch (err: any) {
51
- console.error("[SendToPi] Failed to write active session file:", err.message);
112
+ console.error("[SendToPi] Failed to write session registry:", err.message);
52
113
  }
53
114
  }
54
115
 
55
- function clearActiveSession() {
116
+ function clearActiveSession(port: number | null) {
56
117
  try {
118
+ const sessionId = port === null ? null : `${process.pid}-${port}`;
119
+ const sessions = readSessionRecords().filter(
120
+ (session) => session.id !== sessionId && !(session.pid === process.pid && session.port === port)
121
+ );
122
+ writeSessionRecords(sessions);
123
+
57
124
  const sessionFile = getActiveSessionFilePath();
58
125
  if (fs.existsSync(sessionFile)) {
59
- const content = fs.readFileSync(sessionFile, "utf8");
60
- const parsed = JSON.parse(content);
61
- if (parsed.pid === process.pid) {
126
+ const parsed = JSON.parse(fs.readFileSync(sessionFile, "utf8"));
127
+ if (parsed.pid === process.pid && (port === null || parsed.port === port)) {
62
128
  fs.unlinkSync(sessionFile);
63
129
  }
64
130
  }
@@ -114,13 +180,14 @@ export default function (pi: ExtensionAPI) {
114
180
  }
115
181
 
116
182
  if (req.method === "POST" && req.url === "/receive") {
117
- let body = "";
183
+ const chunks: Buffer[] = [];
118
184
  req.on("data", (chunk) => {
119
- body += chunk;
185
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
120
186
  });
121
187
 
122
188
  req.on("end", () => {
123
189
  try {
190
+ const body = Buffer.concat(chunks).toString("utf8");
124
191
  const data = JSON.parse(body || "{}");
125
192
  const { content } = data;
126
193
 
@@ -131,7 +198,7 @@ export default function (pi: ExtensionAPI) {
131
198
  // 每次成功接收更新活跃时间
132
199
  recordActiveSession(port, ctx?.cwd || process.cwd());
133
200
 
134
- res.writeHead(200, { "Content-Type": "application/json" });
201
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
135
202
  res.end(JSON.stringify({ success: true, mode: "prefilled", port }));
136
203
  } catch (err: any) {
137
204
  res.writeHead(400, { "Content-Type": "application/json" });
@@ -216,12 +283,12 @@ export default function (pi: ExtensionAPI) {
216
283
  server.close();
217
284
  server = null;
218
285
  }
219
- clearActiveSession();
286
+ clearActiveSession(activePort);
220
287
  activeCtx = null;
221
288
  activePort = null;
222
289
  });
223
290
 
224
291
  process.on("exit", () => {
225
- clearActiveSession();
292
+ clearActiveSession(activePort);
226
293
  });
227
294
  }
@@ -17,6 +17,14 @@ if (!fs.existsSync(piHomeDir)) {
17
17
  }
18
18
  }
19
19
 
20
+ const SEND_TO_PI_DIR = path.join(piHomeDir, 'send-to-pi');
21
+ try {
22
+ fs.mkdirSync(SEND_TO_PI_DIR, { recursive: true });
23
+ } catch (_err) {
24
+ // Ignore creation failures and let callers use the legacy path or temp file.
25
+ }
26
+
27
+ const SESSION_REGISTRY_FILE = path.join(SEND_TO_PI_DIR, 'sessions.json');
20
28
  const ACTIVE_SESSION_FILE = path.join(piHomeDir, 'send-to-pi.json');
21
29
 
22
30
  const PENDING_FILE = fs.existsSync(piHomeDir)
@@ -41,6 +49,7 @@ module.exports = {
41
49
  PI_INTERNAL_PORT_START,
42
50
  PI_INTERNAL_PORT_END,
43
51
  ACTIVE_SESSION_FILE,
52
+ SESSION_REGISTRY_FILE,
44
53
  PENDING_FILE,
45
54
  getWorkDir,
46
55
  };
@@ -2,17 +2,19 @@
2
2
  * send-to-pi Bridge Daemon
3
3
  *
4
4
  * Listens on: 127.0.0.1:18090 (receives Chrome extension requests)
5
- * Dynamically discovers active Pi sessions (18091 ~ 18095 or ~/.pi/send-to-pi.json)
5
+ * Dynamically discovers active Pi sessions (18091 ~ 18095 or ~/.pi/send-to-pi/sessions.json)
6
6
  */
7
7
 
8
8
  const http = require('http');
9
9
  const fs = require('fs');
10
+ const path = require('path');
10
11
  const {
11
12
  BRIDGE_PORT,
12
13
  PI_INTERNAL_PORT,
13
14
  PI_INTERNAL_PORT_START,
14
15
  PI_INTERNAL_PORT_END,
15
16
  ACTIVE_SESSION_FILE,
17
+ SESSION_REGISTRY_FILE,
16
18
  PENDING_FILE,
17
19
  getWorkDir,
18
20
  } = require('./config');
@@ -55,24 +57,79 @@ function checkPiHealth(port) {
55
57
  });
56
58
  }
57
59
 
60
+ function readSessionRegistry() {
61
+ if (!fs.existsSync(SESSION_REGISTRY_FILE)) return null;
62
+
63
+ try {
64
+ const parsed = JSON.parse(fs.readFileSync(SESSION_REGISTRY_FILE, 'utf8'));
65
+ const sessions = Array.isArray(parsed) ? parsed : parsed && parsed.sessions;
66
+ if (!Array.isArray(sessions)) return null;
67
+ return sessions.filter((session) => session && Number.isInteger(Number(session.port)));
68
+ } catch (_e) {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ function writeSessionRegistry(sessions) {
74
+ try {
75
+ const directory = path.dirname(SESSION_REGISTRY_FILE);
76
+ fs.mkdirSync(directory, { recursive: true });
77
+ const temporaryFile = `${SESSION_REGISTRY_FILE}.tmp-${process.pid}`;
78
+ fs.writeFileSync(
79
+ temporaryFile,
80
+ JSON.stringify({ version: 1, sessions }, null, 2),
81
+ 'utf8'
82
+ );
83
+ fs.renameSync(temporaryFile, SESSION_REGISTRY_FILE);
84
+ } catch (_e) {
85
+ // Registry cleanup is best effort. The legacy file and port scan remain available.
86
+ }
87
+ }
88
+
58
89
  async function findActivePi() {
59
- // 1. 优先读取 ~/.pi/send-to-pi.json 活跃单例信息
90
+ // 1. 优先读取会话注册表,并按最近活跃时间路由。
91
+ const registeredSessions = readSessionRegistry();
92
+ if (registeredSessions) {
93
+ const candidates = [...registeredSessions].sort(
94
+ (a, b) => Number(b.activeAt || b.updatedAt || 0) - Number(a.activeAt || a.updatedAt || 0)
95
+ );
96
+ const activeSessions = [];
97
+ let selected = null;
98
+
99
+ for (const session of candidates) {
100
+ const port = Number(session.port);
101
+ const health = await checkPiHealth(port);
102
+ if (!health.ok) continue;
103
+
104
+ const activeSession = { ...session, ...(health.info || {}), port };
105
+ activeSessions.push(activeSession);
106
+ if (!selected) {
107
+ selected = { port, source: 'session-registry', session: activeSession };
108
+ }
109
+ }
110
+
111
+ if (activeSessions.length !== registeredSessions.length) {
112
+ writeSessionRegistry(activeSessions);
113
+ }
114
+ if (selected) return selected;
115
+ }
116
+
117
+ // 2. 兼容旧版 ~/.pi/send-to-pi.json 活跃单例信息。
60
118
  if (fs.existsSync(ACTIVE_SESSION_FILE)) {
61
119
  try {
62
- const raw = fs.readFileSync(ACTIVE_SESSION_FILE, 'utf8');
63
- const session = JSON.parse(raw);
120
+ const session = JSON.parse(fs.readFileSync(ACTIVE_SESSION_FILE, 'utf8'));
64
121
  if (session && session.port) {
65
- const health = await checkPiHealth(session.port);
122
+ const health = await checkPiHealth(Number(session.port));
66
123
  if (health.ok) {
67
- return { port: session.port, source: 'session-file', session };
124
+ return { port: Number(session.port), source: 'session-file', session };
68
125
  }
69
126
  }
70
127
  } catch (_e) {
71
- // 忽略文件解析错误,继续范围扫描
128
+ // 忽略文件解析错误,继续范围扫描。
72
129
  }
73
130
  }
74
131
 
75
- // 2. 备用兜底:顺序探测端口范围 (18091 ~ 18095)
132
+ // 3. 备用兜底:顺序探测端口范围 (18091 ~ 18095)。
76
133
  for (let port = PI_INTERNAL_PORT_START; port <= PI_INTERNAL_PORT_END; port++) {
77
134
  const health = await checkPiHealth(port);
78
135
  if (health.ok) {
@@ -93,7 +150,7 @@ function forwardToPi(port, content) {
93
150
  path: '/receive',
94
151
  method: 'POST',
95
152
  headers: {
96
- 'Content-Type': 'application/json',
153
+ 'Content-Type': 'application/json; charset=utf-8',
97
154
  'Content-Length': Buffer.byteLength(data),
98
155
  },
99
156
  timeout: 1500,
@@ -169,12 +226,13 @@ function createBridgeServer() {
169
226
  }
170
227
 
171
228
  if (req.method === 'POST' && req.url === '/send') {
172
- let body = '';
229
+ const chunks = [];
173
230
  req.on('data', (chunk) => {
174
- body += chunk;
231
+ chunks.push(chunk);
175
232
  });
176
233
 
177
234
  req.on('end', async () => {
235
+ const body = Buffer.concat(chunks).toString('utf8');
178
236
  try {
179
237
  const payload = JSON.parse(body || '{}');
180
238
  const content = formatContent(payload);
@@ -2,35 +2,56 @@
2
2
  * Windows Terminal Launcher for send-to-pi
3
3
  *
4
4
  * Supports:
5
- * - Windows Terminal (wt.exe)
5
+ * - Tern Terminal (D:\Tern\tern.exe)
6
+ * - Windows Terminal (wt.exe fallback)
6
7
  * - PowerShell (powershell.exe fallback)
7
8
  * - Command Prompt (cmd.exe fallback)
8
9
  */
9
10
 
10
11
  const { spawn } = require('child_process');
12
+ const fs = require('fs');
11
13
 
12
14
  function launchWin32(workDir) {
13
15
  return new Promise((resolve) => {
14
- // 1. 尝试 Windows Terminal (wt.exe)
15
- try {
16
- const wtArgs = ['-d', workDir, 'powershell', '-NoExit', '-Command', 'pi'];
17
- const child = spawn('wt.exe', wtArgs, {
18
- detached: true,
19
- stdio: 'ignore',
20
- });
16
+ // 1. 优先尝试 Tern Terminal (主力终端)
17
+ const ternPath = 'D:\\Tern\\tern.exe';
18
+ if (fs.existsSync(ternPath)) {
19
+ try {
20
+ const ternArgs = ['-e', 'powershell', '-NoExit', '-Command', `Set-Location '${workDir}'; pi`];
21
+ const child = spawn(ternPath, ternArgs, {
22
+ detached: true,
23
+ stdio: 'ignore',
24
+ });
25
+ child.on('error', () => fallbackWT(workDir, resolve));
26
+ child.unref();
27
+ setTimeout(() => resolve({ success: true, terminal: 'Tern' }), 300);
28
+ return;
29
+ } catch (_e) {
30
+ // continue
31
+ }
32
+ }
33
+ fallbackWT(workDir, resolve);
34
+ });
35
+ }
21
36
 
22
- child.on('error', (_err) => {
23
- // wt.exe 不存在或失败,回退到 powershell.exe
24
- fallbackPowerShell(workDir, resolve);
25
- });
37
+ function fallbackWT(workDir, resolve) {
38
+ // 2. 回退尝试 Windows Terminal (wt.exe)
39
+ try {
40
+ const wtArgs = ['-d', workDir, 'powershell', '-NoExit', '-Command', 'pi'];
41
+ const child = spawn('wt.exe', wtArgs, {
42
+ detached: true,
43
+ stdio: 'ignore',
44
+ });
26
45
 
27
- child.unref();
28
- // 在 Windows 上若成功触发 spawn 且无即时报错即视为已拉起
29
- setTimeout(() => resolve({ success: true, terminal: 'Windows Terminal' }), 300);
30
- } catch (_e) {
46
+ child.on('error', (_err) => {
31
47
  fallbackPowerShell(workDir, resolve);
32
- }
33
- });
48
+ });
49
+
50
+ child.unref();
51
+ setTimeout(() => resolve({ success: true, terminal: 'Windows Terminal' }), 300);
52
+ } catch (_e) {
53
+ fallbackPowerShell(workDir, resolve);
54
+ }
34
55
  }
35
56
 
36
57
  function fallbackPowerShell(workDir, resolve) {