send-to-pi 1.0.2 → 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.
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * send-to-pi Extension for Pi Coding Agent
3
3
  *
4
- * Listens on 127.0.0.1:18091 for incoming browser payloads.
5
- * Automatically prefills text into the terminal editor with setEditorText()
6
- * without executing immediately, giving the user full control to refine prompts!
4
+ * Dynamically binds to an available internal port (18091 ~ 18095).
5
+ * Updates ~/.pi/send-to-pi.json with the active session metadata.
6
+ * Prefills incoming payloads into terminal input without immediate execution.
7
7
  */
8
8
 
9
9
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -12,19 +12,129 @@ import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import * as os from "node:os";
14
14
 
15
- const INTERNAL_PORT = parseInt(process.env.PI_INTERNAL_PORT || "", 10) || 18091;
15
+ const DEFAULT_START_PORT = 18091;
16
+ const PORT_RANGE = 5; // 18091 ~ 18095
17
+
18
+ function getPiHomeDir(): string {
19
+ const dir = path.join(os.homedir(), ".pi");
20
+ if (!fs.existsSync(dir)) {
21
+ try {
22
+ fs.mkdirSync(dir, { recursive: true });
23
+ } catch {}
24
+ }
25
+ return dir;
26
+ }
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
+
40
+ function getActiveSessionFilePath(): string {
41
+ return path.join(getPiHomeDir(), "send-to-pi.json");
42
+ }
16
43
 
17
44
  function getPendingFilePaths(): string[] {
18
- const piHome = path.join(os.homedir(), ".pi");
45
+ const piHome = getPiHomeDir();
19
46
  return [
20
47
  path.join(piHome, "pending-browser-input.txt"),
21
48
  path.join(os.tmpdir(), "pi-pending-browser-input.txt"),
22
49
  ];
23
50
  }
24
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
+
87
+ function recordActiveSession(port: number, workDir: string) {
88
+ try {
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,
95
+ pid: process.pid,
96
+ port,
97
+ workdir: workDir,
98
+ activeAt: now,
99
+ startedAt: now,
100
+ updatedAt: now,
101
+ terminal: process.env.PI_TERMINAL || null,
102
+ window: process.env.PI_WINDOW_ID || null,
103
+ };
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");
111
+ } catch (err: any) {
112
+ console.error("[SendToPi] Failed to write session registry:", err.message);
113
+ }
114
+ }
115
+
116
+ function clearActiveSession(port: number | null) {
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
+
124
+ const sessionFile = getActiveSessionFilePath();
125
+ if (fs.existsSync(sessionFile)) {
126
+ const parsed = JSON.parse(fs.readFileSync(sessionFile, "utf8"));
127
+ if (parsed.pid === process.pid && (port === null || parsed.port === port)) {
128
+ fs.unlinkSync(sessionFile);
129
+ }
130
+ }
131
+ } catch {}
132
+ }
133
+
25
134
  export default function (pi: ExtensionAPI) {
26
135
  let server: http.Server | null = null;
27
136
  let activeCtx: ExtensionContext | null = null;
137
+ let activePort: number | null = null;
28
138
 
29
139
  function prefillEditor(ctx: ExtensionContext, textToInsert: string) {
30
140
  if (!ctx || !ctx.ui) return;
@@ -42,6 +152,101 @@ export default function (pi: ExtensionAPI) {
42
152
  }
43
153
  }
44
154
 
155
+ function createServerInstance(ctx: ExtensionContext, port: number): Promise<http.Server> {
156
+ return new Promise((resolve, reject) => {
157
+ const app = http.createServer((req, res) => {
158
+ res.setHeader("Access-Control-Allow-Origin", "*");
159
+ res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
160
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
161
+
162
+ if (req.method === "OPTIONS") {
163
+ res.writeHead(204);
164
+ res.end();
165
+ return;
166
+ }
167
+
168
+ if (req.method === "GET" && req.url === "/health") {
169
+ res.writeHead(200, { "Content-Type": "application/json" });
170
+ res.end(
171
+ JSON.stringify({
172
+ status: "alive",
173
+ port,
174
+ pid: process.pid,
175
+ workdir: ctx?.cwd || process.cwd(),
176
+ updatedAt: Date.now(),
177
+ })
178
+ );
179
+ return;
180
+ }
181
+
182
+ if (req.method === "POST" && req.url === "/receive") {
183
+ const chunks: Buffer[] = [];
184
+ req.on("data", (chunk) => {
185
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
186
+ });
187
+
188
+ req.on("end", () => {
189
+ try {
190
+ const body = Buffer.concat(chunks).toString("utf8");
191
+ const data = JSON.parse(body || "{}");
192
+ const { content } = data;
193
+
194
+ if (content && activeCtx) {
195
+ prefillEditor(activeCtx, content);
196
+ }
197
+
198
+ // 每次成功接收更新活跃时间
199
+ recordActiveSession(port, ctx?.cwd || process.cwd());
200
+
201
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
202
+ res.end(JSON.stringify({ success: true, mode: "prefilled", port }));
203
+ } catch (err: any) {
204
+ res.writeHead(400, { "Content-Type": "application/json" });
205
+ res.end(JSON.stringify({ success: false, error: err.message }));
206
+ }
207
+ });
208
+ return;
209
+ }
210
+
211
+ res.writeHead(404, { "Content-Type": "application/json" });
212
+ res.end(JSON.stringify({ error: "Not Found" }));
213
+ });
214
+
215
+ const onError = (err: any) => {
216
+ app.removeListener("listening", onListening);
217
+ reject(err);
218
+ };
219
+
220
+ const onListening = () => {
221
+ app.removeListener("error", onError);
222
+ resolve(app);
223
+ };
224
+
225
+ app.once("error", onError);
226
+ app.once("listening", onListening);
227
+ app.listen(port, "127.0.0.1");
228
+ });
229
+ }
230
+
231
+ async function startHttpServer(ctx: ExtensionContext): Promise<number> {
232
+ const startPort = parseInt(process.env.PI_INTERNAL_PORT || "", 10) || DEFAULT_START_PORT;
233
+ const endPort = startPort + PORT_RANGE - 1;
234
+
235
+ for (let currentPort = startPort; currentPort <= endPort; currentPort++) {
236
+ try {
237
+ const boundServer = await createServerInstance(ctx, currentPort);
238
+ server = boundServer;
239
+ activePort = currentPort;
240
+ return currentPort;
241
+ } catch (err: any) {
242
+ if (err.code !== "EADDRINUSE") {
243
+ throw err;
244
+ }
245
+ }
246
+ }
247
+ throw new Error(`All ports in range ${startPort}-${endPort} are occupied.`);
248
+ }
249
+
45
250
  pi.on("session_start", async (_event, ctx) => {
46
251
  activeCtx = ctx;
47
252
 
@@ -61,61 +266,16 @@ export default function (pi: ExtensionAPI) {
61
266
  }
62
267
  }
63
268
 
64
- if (server) return;
65
-
66
- server = http.createServer((req, res) => {
67
- res.setHeader("Access-Control-Allow-Origin", "*");
68
- res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
69
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
70
-
71
- if (req.method === "OPTIONS") {
72
- res.writeHead(204);
73
- res.end();
74
- return;
269
+ if (!server) {
270
+ try {
271
+ const boundPort = await startHttpServer(ctx);
272
+ recordActiveSession(boundPort, ctx?.cwd || process.cwd());
273
+ } catch (err: any) {
274
+ console.error("[SendToPi] Failed to bind internal port:", err.message);
75
275
  }
76
-
77
- if (req.method === "GET" && req.url === "/health") {
78
- res.writeHead(200, { "Content-Type": "application/json" });
79
- res.end(JSON.stringify({ status: "alive", port: INTERNAL_PORT }));
80
- return;
81
- }
82
-
83
- if (req.method === "POST" && req.url === "/receive") {
84
- let body = "";
85
- req.on("data", (chunk) => {
86
- body += chunk;
87
- });
88
-
89
- req.on("end", () => {
90
- try {
91
- const data = JSON.parse(body || "{}");
92
- const { content } = data;
93
-
94
- if (content && activeCtx) {
95
- prefillEditor(activeCtx, content);
96
- }
97
-
98
- res.writeHead(200, { "Content-Type": "application/json" });
99
- res.end(JSON.stringify({ success: true, mode: "prefilled" }));
100
- } catch (err: any) {
101
- res.writeHead(400, { "Content-Type": "application/json" });
102
- res.end(JSON.stringify({ success: false, error: err.message }));
103
- }
104
- });
105
- return;
106
- }
107
-
108
- res.writeHead(404, { "Content-Type": "application/json" });
109
- res.end(JSON.stringify({ error: "Not Found" }));
110
- });
111
-
112
- server.listen(INTERNAL_PORT, "127.0.0.1");
113
-
114
- server.on("error", (e: any) => {
115
- if (e.code !== "EADDRINUSE") {
116
- console.error("[SendToPi Internal Server Error]:", e);
117
- }
118
- });
276
+ } else if (activePort) {
277
+ recordActiveSession(activePort, ctx?.cwd || process.cwd());
278
+ }
119
279
  });
120
280
 
121
281
  pi.on("session_shutdown", async () => {
@@ -123,6 +283,12 @@ export default function (pi: ExtensionAPI) {
123
283
  server.close();
124
284
  server = null;
125
285
  }
286
+ clearActiveSession(activePort);
126
287
  activeCtx = null;
288
+ activePort = null;
289
+ });
290
+
291
+ process.on("exit", () => {
292
+ clearActiveSession(activePort);
127
293
  });
128
294
  }
@@ -4,17 +4,29 @@ const fs = require('fs');
4
4
 
5
5
  const BRIDGE_PORT = parseInt(process.env.PI_BRIDGE_PORT, 10) || 18090;
6
6
  const PI_INTERNAL_PORT = parseInt(process.env.PI_INTERNAL_PORT, 10) || 18091;
7
+ const PI_INTERNAL_PORT_START = PI_INTERNAL_PORT;
8
+ const PI_INTERNAL_PORT_END = PI_INTERNAL_PORT + 4; // 18091 ~ 18095
7
9
 
8
10
  // 确保 ~/.pi 目录存在
9
11
  const piHomeDir = path.join(os.homedir(), '.pi');
10
12
  if (!fs.existsSync(piHomeDir)) {
11
13
  try {
12
14
  fs.mkdirSync(piHomeDir, { recursive: true });
13
- } catch (err) {
15
+ } catch (_err) {
14
16
  // 忽略创建失败(如权限受限),由操作系统临时目录兜底
15
17
  }
16
18
  }
17
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');
28
+ const ACTIVE_SESSION_FILE = path.join(piHomeDir, 'send-to-pi.json');
29
+
18
30
  const PENDING_FILE = fs.existsSync(piHomeDir)
19
31
  ? path.join(piHomeDir, 'pending-browser-input.txt')
20
32
  : path.join(os.tmpdir(), 'pi-pending-browser-input.txt');
@@ -34,6 +46,10 @@ function getWorkDir() {
34
46
  module.exports = {
35
47
  BRIDGE_PORT,
36
48
  PI_INTERNAL_PORT,
49
+ PI_INTERNAL_PORT_START,
50
+ PI_INTERNAL_PORT_END,
51
+ ACTIVE_SESSION_FILE,
52
+ SESSION_REGISTRY_FILE,
37
53
  PENDING_FILE,
38
54
  getWorkDir,
39
55
  };
@@ -2,34 +2,164 @@
2
2
  * send-to-pi Bridge Daemon
3
3
  *
4
4
  * Listens on: 127.0.0.1:18090 (receives Chrome extension requests)
5
- * Probes: 127.0.0.1:18091 (internal receiver in active Pi session)
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 { BRIDGE_PORT, PI_INTERNAL_PORT, PENDING_FILE, getWorkDir } = require('./config');
10
+ const path = require('path');
11
+ const {
12
+ BRIDGE_PORT,
13
+ PI_INTERNAL_PORT,
14
+ PI_INTERNAL_PORT_START,
15
+ PI_INTERNAL_PORT_END,
16
+ ACTIVE_SESSION_FILE,
17
+ SESSION_REGISTRY_FILE,
18
+ PENDING_FILE,
19
+ getWorkDir,
20
+ } = require('./config');
11
21
  const { launchTerminal } = require('./launchers');
12
22
 
13
- function forwardToActivePi(content) {
23
+ function checkPiHealth(port) {
24
+ return new Promise((resolve) => {
25
+ const req = http.request(
26
+ {
27
+ hostname: '127.0.0.1',
28
+ port,
29
+ path: '/health',
30
+ method: 'GET',
31
+ timeout: 400,
32
+ },
33
+ (res) => {
34
+ if (res.statusCode === 200) {
35
+ let raw = '';
36
+ res.on('data', (c) => (raw += c));
37
+ res.on('end', () => {
38
+ try {
39
+ const info = JSON.parse(raw);
40
+ resolve({ ok: true, port, info });
41
+ } catch {
42
+ resolve({ ok: true, port });
43
+ }
44
+ });
45
+ } else {
46
+ resolve({ ok: false, port });
47
+ }
48
+ }
49
+ );
50
+
51
+ req.on('error', () => resolve({ ok: false, port }));
52
+ req.on('timeout', () => {
53
+ req.destroy();
54
+ resolve({ ok: false, port });
55
+ });
56
+ req.end();
57
+ });
58
+ }
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
+
89
+ async function findActivePi() {
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 活跃单例信息。
118
+ if (fs.existsSync(ACTIVE_SESSION_FILE)) {
119
+ try {
120
+ const session = JSON.parse(fs.readFileSync(ACTIVE_SESSION_FILE, 'utf8'));
121
+ if (session && session.port) {
122
+ const health = await checkPiHealth(Number(session.port));
123
+ if (health.ok) {
124
+ return { port: Number(session.port), source: 'session-file', session };
125
+ }
126
+ }
127
+ } catch (_e) {
128
+ // 忽略文件解析错误,继续范围扫描。
129
+ }
130
+ }
131
+
132
+ // 3. 备用兜底:顺序探测端口范围 (18091 ~ 18095)。
133
+ for (let port = PI_INTERNAL_PORT_START; port <= PI_INTERNAL_PORT_END; port++) {
134
+ const health = await checkPiHealth(port);
135
+ if (health.ok) {
136
+ return { port, source: 'port-scan', session: health.info };
137
+ }
138
+ }
139
+
140
+ return null;
141
+ }
142
+
143
+ function forwardToPi(port, content) {
14
144
  return new Promise((resolve, reject) => {
15
145
  const data = JSON.stringify({ content });
16
146
  const req = http.request(
17
147
  {
18
148
  hostname: '127.0.0.1',
19
- port: PI_INTERNAL_PORT,
149
+ port,
20
150
  path: '/receive',
21
151
  method: 'POST',
22
152
  headers: {
23
- 'Content-Type': 'application/json',
153
+ 'Content-Type': 'application/json; charset=utf-8',
24
154
  'Content-Length': Buffer.byteLength(data),
25
155
  },
26
- timeout: 1000,
156
+ timeout: 1500,
27
157
  },
28
158
  (res) => {
29
159
  if (res.statusCode === 200) {
30
160
  resolve(true);
31
161
  } else {
32
- reject(new Error(`Pi receiver responded with HTTP ${res.statusCode}`));
162
+ reject(new Error(`Pi receiver on port ${port} responded with HTTP ${res.statusCode}`));
33
163
  }
34
164
  }
35
165
  );
@@ -37,7 +167,7 @@ function forwardToActivePi(content) {
37
167
  req.on('error', (err) => reject(err));
38
168
  req.on('timeout', () => {
39
169
  req.destroy();
40
- reject(new Error('Pi receiver request timed out'));
170
+ reject(new Error(`Pi receiver on port ${port} timed out`));
41
171
  });
42
172
 
43
173
  req.write(data);
@@ -53,6 +183,11 @@ function formatContent(payload) {
53
183
  const label = isZh ? '【来源】' : '[Source]';
54
184
  return `${label}: ${title || (isZh ? '网页摘录' : 'Web Snippet')} (${url || ''})\n\n${text}\n\n`;
55
185
  }
186
+ if (type === 'article') {
187
+ const titleLabel = isZh ? '【网页文章】' : '[Web Article]';
188
+ const linkLabel = isZh ? '【网页链接】' : '[Link]';
189
+ return `${titleLabel}: ${title || (isZh ? '正文' : 'Article')}\n${linkLabel}: ${url || ''}\n\n${text}\n\n`;
190
+ }
56
191
  if (type === 'link') {
57
192
  const label = isZh ? '【网页链接】' : '[Link]';
58
193
  return `${label}: ${url}\n\n`;
@@ -75,13 +210,15 @@ function createBridgeServer() {
75
210
  }
76
211
 
77
212
  if (req.method === 'GET' && req.url === '/health') {
213
+ const activePi = await findActivePi();
78
214
  res.writeHead(200, { 'Content-Type': 'application/json' });
79
215
  res.end(
80
216
  JSON.stringify({
81
217
  status: 'ok',
82
218
  platform: process.platform,
83
219
  bridgePort: BRIDGE_PORT,
84
- internalPort: PI_INTERNAL_PORT,
220
+ defaultInternalPort: PI_INTERNAL_PORT,
221
+ activePi: activePi ? { port: activePi.port, source: activePi.source } : null,
85
222
  workDir: getWorkDir(),
86
223
  })
87
224
  );
@@ -89,47 +226,54 @@ function createBridgeServer() {
89
226
  }
90
227
 
91
228
  if (req.method === 'POST' && req.url === '/send') {
92
- let body = '';
229
+ const chunks = [];
93
230
  req.on('data', (chunk) => {
94
- body += chunk;
231
+ chunks.push(chunk);
95
232
  });
96
233
 
97
234
  req.on('end', async () => {
235
+ const body = Buffer.concat(chunks).toString('utf8');
98
236
  try {
99
237
  const payload = JSON.parse(body || '{}');
100
238
  const content = formatContent(payload);
101
239
 
102
- // 1. 尝试直接转发给当前正在运行的 Pi 会话
103
- try {
104
- await forwardToActivePi(content);
105
- console.log('[Bridge] Successfully prefilled text into active Pi terminal.');
106
- res.writeHead(200, { 'Content-Type': 'application/json' });
107
- res.end(
108
- JSON.stringify({
109
- success: true,
110
- mode: 'prefilled',
111
- message: '已直接填入活跃的 Pi 输入框!',
112
- })
113
- );
114
- return;
115
- } catch (_err) {
116
- // 2. 当前没有运行中的 Pi,进行冷启动唤醒流程
117
- console.log('[Bridge] No active Pi detected. Writing pending file and launching terminal...');
118
- fs.writeFileSync(PENDING_FILE, content, 'utf8');
119
-
120
- const workDir = getWorkDir();
121
- const launchResult = await launchTerminal(workDir);
122
-
123
- res.writeHead(200, { 'Content-Type': 'application/json' });
124
- res.end(
125
- JSON.stringify({
126
- success: true,
127
- mode: 'launched',
128
- terminal: launchResult.terminal || 'Default Terminal',
129
- message: '已启动终端唤醒 Pi,内容已在输入框备好!',
130
- })
131
- );
240
+ // 1. 尝试动态发现当前活跃的 Pi 实例并转发
241
+ const activePi = await findActivePi();
242
+ if (activePi) {
243
+ try {
244
+ await forwardToPi(activePi.port, content);
245
+ console.log(`[Bridge] Successfully forwarded content to Pi terminal on port ${activePi.port}.`);
246
+ res.writeHead(200, { 'Content-Type': 'application/json' });
247
+ res.end(
248
+ JSON.stringify({
249
+ success: true,
250
+ mode: 'prefilled',
251
+ port: activePi.port,
252
+ message: '已直接填入活跃的 Pi 输入框!',
253
+ })
254
+ );
255
+ return;
256
+ } catch (err) {
257
+ console.warn(`[Bridge] Forward to port ${activePi.port} failed: ${err.message}, falling back to cold start.`);
258
+ }
132
259
  }
260
+
261
+ // 2. 当前没有运行中的 Pi,进行冷启动唤醒流程
262
+ console.log('[Bridge] No active Pi detected. Writing pending file and launching terminal...');
263
+ fs.writeFileSync(PENDING_FILE, content, 'utf8');
264
+
265
+ const workDir = getWorkDir();
266
+ const launchResult = await launchTerminal(workDir);
267
+
268
+ res.writeHead(200, { 'Content-Type': 'application/json' });
269
+ res.end(
270
+ JSON.stringify({
271
+ success: true,
272
+ mode: 'launched',
273
+ terminal: launchResult.terminal || 'Default Terminal',
274
+ message: '已启动终端唤醒 Pi,内容已在输入框备好!',
275
+ })
276
+ );
133
277
  } catch (e) {
134
278
  res.writeHead(400, { 'Content-Type': 'application/json' });
135
279
  res.end(JSON.stringify({ success: false, error: e.message }));
@@ -174,4 +318,4 @@ if (require.main === module) {
174
318
  startDaemon();
175
319
  }
176
320
 
177
- module.exports = { startDaemon, createBridgeServer };
321
+ module.exports = { startDaemon, createBridgeServer, findActivePi, formatContent };