send-to-pi 1.1.0 → 1.3.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.
@@ -2,31 +2,104 @@ const path = require('path');
2
2
  const os = require('os');
3
3
  const fs = require('fs');
4
4
 
5
- const BRIDGE_PORT = parseInt(process.env.PI_BRIDGE_PORT, 10) || 18090;
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
9
-
10
- // 确保 ~/.pi 目录存在
11
5
  const piHomeDir = path.join(os.homedir(), '.pi');
12
6
  if (!fs.existsSync(piHomeDir)) {
13
7
  try {
14
8
  fs.mkdirSync(piHomeDir, { recursive: true });
15
9
  } catch (_err) {
16
- // 忽略创建失败(如权限受限),由操作系统临时目录兜底
10
+ // Fallback to OS temp dir if ~/.pi cannot be created.
17
11
  }
18
12
  }
19
13
 
14
+ const SEND_TO_PI_DIR = path.join(piHomeDir, 'send-to-pi');
15
+ try {
16
+ fs.mkdirSync(SEND_TO_PI_DIR, { recursive: true });
17
+ } catch (_err) {
18
+ // Ignore creation errors.
19
+ }
20
+
21
+ const USER_CONFIG_FILE = path.join(SEND_TO_PI_DIR, 'config.json');
22
+ const SESSION_REGISTRY_FILE = path.join(SEND_TO_PI_DIR, 'sessions.json');
23
+ const LAST_TERMINAL_FILE = path.join(SEND_TO_PI_DIR, 'last-terminal.json');
20
24
  const ACTIVE_SESSION_FILE = path.join(piHomeDir, 'send-to-pi.json');
21
25
 
22
26
  const PENDING_FILE = fs.existsSync(piHomeDir)
23
27
  ? path.join(piHomeDir, 'pending-browser-input.txt')
24
28
  : path.join(os.tmpdir(), 'pi-pending-browser-input.txt');
25
29
 
26
- // 默认工作目录:环境变量优先,其次当前工作目录,兜底家目录
30
+ function readJsonSafe(filePath) {
31
+ try {
32
+ if (!fs.existsSync(filePath)) return null;
33
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
34
+ } catch (_err) {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function readUserConfigFile() {
40
+ const parsed = readJsonSafe(USER_CONFIG_FILE);
41
+ return parsed && typeof parsed === 'object' ? parsed : {};
42
+ }
43
+
44
+ function readLastTerminal() {
45
+ const parsed = readJsonSafe(LAST_TERMINAL_FILE);
46
+ return parsed && typeof parsed === 'object' ? parsed : null;
47
+ }
48
+
49
+ function loadUserConfig() {
50
+ const fileCfg = readUserConfigFile();
51
+ const bridgePort =
52
+ parseInt(process.env.PI_BRIDGE_PORT, 10) ||
53
+ parseInt(fileCfg.bridgePort, 10) ||
54
+ 18090;
55
+ const internalPort =
56
+ parseInt(process.env.PI_INTERNAL_PORT, 10) ||
57
+ parseInt(fileCfg.internalPort, 10) ||
58
+ 18091;
59
+ const terminal = (
60
+ process.env.PI_TERMINAL ||
61
+ fileCfg.terminal ||
62
+ ''
63
+ ).trim().toLowerCase();
64
+ const launchCommand = (
65
+ process.env.PI_LAUNCH_CMD ||
66
+ fileCfg.launchCommand ||
67
+ ''
68
+ ).trim();
69
+ const workDir = (process.env.PI_WORKDIR || fileCfg.workDir || '').trim();
70
+ const focusEnv = (process.env.PI_FOCUS_ON_SEND || '').trim().toLowerCase();
71
+ const focusOnSend =
72
+ focusEnv !== ''
73
+ ? focusEnv === '1' || focusEnv === 'true' || focusEnv === 'yes'
74
+ : Boolean(fileCfg.focusOnSend);
75
+
76
+ return {
77
+ bridgePort,
78
+ internalPort,
79
+ internalPortStart: internalPort,
80
+ internalPortEnd: internalPort + 4,
81
+ terminal,
82
+ launchCommand,
83
+ workDir,
84
+ focusOnSend,
85
+ };
86
+ }
87
+
88
+ const initialCfg = loadUserConfig();
89
+ const BRIDGE_PORT = initialCfg.bridgePort;
90
+ const PI_INTERNAL_PORT = initialCfg.internalPort;
91
+ const PI_INTERNAL_PORT_START = initialCfg.internalPortStart;
92
+ const PI_INTERNAL_PORT_END = initialCfg.internalPortEnd;
93
+
94
+ // Workdir priority: PI_WORKDIR -> config.json -> last active Pi workdir -> cwd -> homedir
27
95
  function getWorkDir() {
28
- if (process.env.PI_WORKDIR && fs.existsSync(process.env.PI_WORKDIR)) {
29
- return process.env.PI_WORKDIR;
96
+ const cfg = loadUserConfig();
97
+ if (cfg.workDir && fs.existsSync(cfg.workDir)) {
98
+ return cfg.workDir;
99
+ }
100
+ const last = readLastTerminal();
101
+ if (last && last.workdir && fs.existsSync(last.workdir)) {
102
+ return last.workdir;
30
103
  }
31
104
  const cwd = process.cwd();
32
105
  if (cwd && fs.existsSync(cwd) && cwd !== '/' && !cwd.endsWith('\\Windows\\system32')) {
@@ -35,12 +108,36 @@ function getWorkDir() {
35
108
  return os.homedir();
36
109
  }
37
110
 
111
+ function getPreferredTerminal() {
112
+ const cfg = loadUserConfig();
113
+ return cfg.terminal || '';
114
+ }
115
+
116
+ function getCustomLaunchCommand() {
117
+ const cfg = loadUserConfig();
118
+ return cfg.launchCommand || '';
119
+ }
120
+
121
+ function shouldFocusOnSend() {
122
+ const cfg = loadUserConfig();
123
+ return cfg.focusOnSend;
124
+ }
125
+
38
126
  module.exports = {
39
127
  BRIDGE_PORT,
40
128
  PI_INTERNAL_PORT,
41
129
  PI_INTERNAL_PORT_START,
42
130
  PI_INTERNAL_PORT_END,
131
+ SEND_TO_PI_DIR,
132
+ USER_CONFIG_FILE,
43
133
  ACTIVE_SESSION_FILE,
134
+ SESSION_REGISTRY_FILE,
135
+ LAST_TERMINAL_FILE,
44
136
  PENDING_FILE,
137
+ loadUserConfig,
138
+ readLastTerminal,
45
139
  getWorkDir,
140
+ getPreferredTerminal,
141
+ getCustomLaunchCommand,
142
+ shouldFocusOnSend,
46
143
  };
@@ -2,21 +2,27 @@
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
+ * Supports 4-layer adaptive cold-start terminal launching & clipboard fallback.
6
7
  */
7
8
 
8
9
  const http = require('http');
9
10
  const fs = require('fs');
11
+ const path = require('path');
10
12
  const {
11
13
  BRIDGE_PORT,
12
14
  PI_INTERNAL_PORT,
13
15
  PI_INTERNAL_PORT_START,
14
16
  PI_INTERNAL_PORT_END,
15
17
  ACTIVE_SESSION_FILE,
18
+ SESSION_REGISTRY_FILE,
16
19
  PENDING_FILE,
17
20
  getWorkDir,
21
+ readLastTerminal,
22
+ shouldFocusOnSend,
18
23
  } = require('./config');
19
- const { launchTerminal } = require('./launchers');
24
+ const { launchTerminal, focusTerminal } = require('./launchers');
25
+ const { copyToClipboard } = require('./clipboard');
20
26
 
21
27
  function checkPiHealth(port) {
22
28
  return new Promise((resolve) => {
@@ -55,29 +61,99 @@ function checkPiHealth(port) {
55
61
  });
56
62
  }
57
63
 
64
+ function readSessionRegistry() {
65
+ if (!fs.existsSync(SESSION_REGISTRY_FILE)) return null;
66
+
67
+ try {
68
+ const parsed = JSON.parse(fs.readFileSync(SESSION_REGISTRY_FILE, 'utf8'));
69
+ const sessions = Array.isArray(parsed) ? parsed : parsed && parsed.sessions;
70
+ if (!Array.isArray(sessions)) return null;
71
+ return sessions.filter((session) => session && Number.isInteger(Number(session.port)));
72
+ } catch (_e) {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ function writeSessionRegistry(sessions) {
78
+ try {
79
+ const directory = path.dirname(SESSION_REGISTRY_FILE);
80
+ fs.mkdirSync(directory, { recursive: true });
81
+ const temporaryFile = `${SESSION_REGISTRY_FILE}.tmp-${process.pid}-${Date.now()}`;
82
+ fs.writeFileSync(
83
+ temporaryFile,
84
+ JSON.stringify({ version: 2, sessions }, null, 2),
85
+ 'utf8'
86
+ );
87
+ fs.renameSync(temporaryFile, SESSION_REGISTRY_FILE);
88
+ } catch (_e) {
89
+ // Registry cleanup is best effort.
90
+ }
91
+ }
92
+
93
+ async function discoverAllActivePis(portStart = PI_INTERNAL_PORT_START, portEnd = PI_INTERNAL_PORT_END) {
94
+ const byPort = new Map();
95
+
96
+ // Probe full port range in parallel so no live Pi is ever missed.
97
+ const ports = [];
98
+ for (let p = portStart; p <= portEnd; p++) ports.push(p);
99
+
100
+ const registeredSessions = readSessionRegistry() || [];
101
+ for (const s of registeredSessions) {
102
+ const p = Number(s.port);
103
+ if (Number.isInteger(p) && !ports.includes(p)) ports.push(p);
104
+ }
105
+
106
+ const healthResults = await Promise.all(ports.map((p) => checkPiHealth(p)));
107
+ const registryByPort = new Map(registeredSessions.map((s) => [Number(s.port), s]));
108
+
109
+ for (const h of healthResults) {
110
+ if (!h.ok) continue;
111
+ const reg = registryByPort.get(h.port) || {};
112
+ const merged = {
113
+ ...reg,
114
+ ...(h.info || {}),
115
+ port: h.port,
116
+ activeAt: Math.max(
117
+ Number((h.info && (h.info.activeAt || h.info.updatedAt)) || 0),
118
+ Number(reg.activeAt || reg.updatedAt || 0)
119
+ ),
120
+ };
121
+ byPort.set(h.port, merged);
122
+ }
123
+
124
+ const alive = Array.from(byPort.values()).sort(
125
+ (a, b) => Number(b.activeAt || b.updatedAt || 0) - Number(a.activeAt || a.updatedAt || 0)
126
+ );
127
+
128
+ // Clean stale dead sessions from registry if it existed.
129
+ if (registeredSessions.length > 0 && alive.length !== registeredSessions.length) {
130
+ writeSessionRegistry(alive);
131
+ }
132
+
133
+ return alive;
134
+ }
135
+
58
136
  async function findActivePi() {
59
- // 1. 优先读取 ~/.pi/send-to-pi.json 活跃单例信息
137
+ const all = await discoverAllActivePis();
138
+ if (all.length > 0) {
139
+ return { port: all[0].port, source: 'active-discovery', session: all[0] };
140
+ }
141
+
142
+ // Legacy fallback file check (in case user runs on a custom port outside 18091~18095).
60
143
  if (fs.existsSync(ACTIVE_SESSION_FILE)) {
61
144
  try {
62
- const raw = fs.readFileSync(ACTIVE_SESSION_FILE, 'utf8');
63
- const session = JSON.parse(raw);
145
+ const session = JSON.parse(fs.readFileSync(ACTIVE_SESSION_FILE, 'utf8'));
64
146
  if (session && session.port) {
65
- const health = await checkPiHealth(session.port);
147
+ const health = await checkPiHealth(Number(session.port));
66
148
  if (health.ok) {
67
- return { port: session.port, source: 'session-file', session };
149
+ return {
150
+ port: Number(session.port),
151
+ source: 'session-file',
152
+ session: { ...session, ...(health.info || {}) },
153
+ };
68
154
  }
69
155
  }
70
- } catch (_e) {
71
- // 忽略文件解析错误,继续范围扫描
72
- }
73
- }
74
-
75
- // 2. 备用兜底:顺序探测端口范围 (18091 ~ 18095)
76
- for (let port = PI_INTERNAL_PORT_START; port <= PI_INTERNAL_PORT_END; port++) {
77
- const health = await checkPiHealth(port);
78
- if (health.ok) {
79
- return { port, source: 'port-scan', session: health.info };
80
- }
156
+ } catch (_e) {}
81
157
  }
82
158
 
83
159
  return null;
@@ -93,17 +169,25 @@ function forwardToPi(port, content) {
93
169
  path: '/receive',
94
170
  method: 'POST',
95
171
  headers: {
96
- 'Content-Type': 'application/json',
172
+ 'Content-Type': 'application/json; charset=utf-8',
97
173
  'Content-Length': Buffer.byteLength(data),
98
174
  },
99
175
  timeout: 1500,
100
176
  },
101
177
  (res) => {
102
- if (res.statusCode === 200) {
103
- resolve(true);
104
- } else {
105
- reject(new Error(`Pi receiver on port ${port} responded with HTTP ${res.statusCode}`));
106
- }
178
+ let raw = '';
179
+ res.on('data', (c) => (raw += c));
180
+ res.on('end', () => {
181
+ if (res.statusCode === 200) {
182
+ try {
183
+ resolve(JSON.parse(raw || '{}'));
184
+ } catch {
185
+ resolve({ success: true, port });
186
+ }
187
+ } else {
188
+ reject(new Error(`Pi receiver on port ${port} responded with HTTP ${res.statusCode}`));
189
+ }
190
+ });
107
191
  }
108
192
  );
109
193
 
@@ -140,7 +224,13 @@ function formatContent(payload) {
140
224
  return `${titleLabel}: ${title || (isZh ? '网页' : 'Page')}\n${linkLabel}: ${url || ''}\n\n`;
141
225
  }
142
226
 
143
- function createBridgeServer() {
227
+ function createBridgeServer(deps = {}) {
228
+ const launch = deps.launchTerminal || launchTerminal;
229
+ const focus = deps.focusTerminal || focusTerminal;
230
+ const clipboard = deps.copyToClipboard || copyToClipboard;
231
+ const discover = deps.findActivePi || findActivePi;
232
+ const discoverAll = deps.discoverAllActivePis || discoverAllActivePis;
233
+
144
234
  const server = http.createServer(async (req, res) => {
145
235
  res.setHeader('Access-Control-Allow-Origin', '*');
146
236
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
@@ -153,15 +243,28 @@ function createBridgeServer() {
153
243
  }
154
244
 
155
245
  if (req.method === 'GET' && req.url === '/health') {
156
- const activePi = await findActivePi();
157
- res.writeHead(200, { 'Content-Type': 'application/json' });
246
+ const sessions = await discoverAll();
247
+ const activePi = sessions[0] || null;
248
+ const lastTerminal = readLastTerminal();
249
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
158
250
  res.end(
159
251
  JSON.stringify({
160
252
  status: 'ok',
253
+ version: '1.3.0',
161
254
  platform: process.platform,
162
255
  bridgePort: BRIDGE_PORT,
163
256
  defaultInternalPort: PI_INTERNAL_PORT,
164
- activePi: activePi ? { port: activePi.port, source: activePi.source } : null,
257
+ activePi: activePi
258
+ ? {
259
+ port: activePi.port,
260
+ workdir: activePi.workdir,
261
+ terminal: activePi.terminal || null,
262
+ appName: activePi.appName || null,
263
+ activeAt: activePi.activeAt || null,
264
+ }
265
+ : null,
266
+ sessions,
267
+ lastTerminal,
165
268
  workDir: getWorkDir(),
166
269
  })
167
270
  );
@@ -169,28 +272,36 @@ function createBridgeServer() {
169
272
  }
170
273
 
171
274
  if (req.method === 'POST' && req.url === '/send') {
172
- let body = '';
275
+ const chunks = [];
173
276
  req.on('data', (chunk) => {
174
- body += chunk;
277
+ chunks.push(chunk);
175
278
  });
176
279
 
177
280
  req.on('end', async () => {
281
+ const body = Buffer.concat(chunks).toString('utf8');
178
282
  try {
179
283
  const payload = JSON.parse(body || '{}');
180
284
  const content = formatContent(payload);
181
285
 
182
- // 1. 尝试动态发现当前活跃的 Pi 实例并转发
183
- const activePi = await findActivePi();
286
+ // 1. Hot delivery to the most recently active Pi session (100% terminal-agnostic).
287
+ const activePi = await discover();
184
288
  if (activePi) {
185
289
  try {
186
- await forwardToPi(activePi.port, content);
187
- console.log(`[Bridge] Successfully forwarded content to Pi terminal on port ${activePi.port}.`);
188
- res.writeHead(200, { 'Content-Type': 'application/json' });
290
+ const reply = await forwardToPi(activePi.port, content);
291
+ const sessionMeta = { ...(activePi.session || {}), ...(reply || {}) };
292
+ if (shouldFocusOnSend()) {
293
+ focus(sessionMeta).catch(() => {});
294
+ }
295
+ console.log(`[Bridge] Forwarded content to Pi on port ${activePi.port} (${sessionMeta.terminal || 'unknown'}).`);
296
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
189
297
  res.end(
190
298
  JSON.stringify({
191
299
  success: true,
192
300
  mode: 'prefilled',
193
301
  port: activePi.port,
302
+ workdir: sessionMeta.workdir || null,
303
+ terminal: sessionMeta.terminal || null,
304
+ appName: sessionMeta.appName || null,
194
305
  message: '已直接填入活跃的 Pi 输入框!',
195
306
  })
196
307
  );
@@ -200,31 +311,58 @@ function createBridgeServer() {
200
311
  }
201
312
  }
202
313
 
203
- // 2. 当前没有运行中的 Pi,进行冷启动唤醒流程
314
+ // 2. Cold-start flow: write pending file and launch terminal via 4-layer adaptive launcher.
204
315
  console.log('[Bridge] No active Pi detected. Writing pending file and launching terminal...');
205
316
  fs.writeFileSync(PENDING_FILE, content, 'utf8');
206
317
 
207
318
  const workDir = getWorkDir();
208
- const launchResult = await launchTerminal(workDir);
319
+ const launchResult = await launch(workDir);
320
+
321
+ if (launchResult && launchResult.success) {
322
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
323
+ res.end(
324
+ JSON.stringify({
325
+ success: true,
326
+ mode: 'launched',
327
+ terminal: launchResult.terminal || 'Default Terminal',
328
+ message: '已启动终端唤醒 Pi,内容已在输入框备好!',
329
+ })
330
+ );
331
+ return;
332
+ }
333
+
334
+ // 3. Layer 4 fallback: copy formatted Markdown to clipboard so content is never lost.
335
+ const copied = await clipboard(content);
336
+ if (copied) {
337
+ console.warn('[Bridge] Terminal launch failed; copied content to system clipboard as fallback.');
338
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
339
+ res.end(
340
+ JSON.stringify({
341
+ success: true,
342
+ mode: 'clipboard',
343
+ error: launchResult && launchResult.error,
344
+ message: '未能自动拉起终端,已复制到剪贴板,请直接粘贴!',
345
+ })
346
+ );
347
+ return;
348
+ }
209
349
 
210
- res.writeHead(200, { 'Content-Type': 'application/json' });
350
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
211
351
  res.end(
212
352
  JSON.stringify({
213
- success: true,
214
- mode: 'launched',
215
- terminal: launchResult.terminal || 'Default Terminal',
216
- message: '已启动终端唤醒 Pi,内容已在输入框备好!',
353
+ success: false,
354
+ error: (launchResult && launchResult.error) || 'Failed to launch terminal and clipboard fallback failed.',
217
355
  })
218
356
  );
219
357
  } catch (e) {
220
- res.writeHead(400, { 'Content-Type': 'application/json' });
358
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
221
359
  res.end(JSON.stringify({ success: false, error: e.message }));
222
360
  }
223
361
  });
224
362
  return;
225
363
  }
226
364
 
227
- res.writeHead(404, { 'Content-Type': 'application/json' });
365
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
228
366
  res.end(JSON.stringify({ error: 'Not Found' }));
229
367
  });
230
368
 
@@ -236,7 +374,7 @@ function startDaemon() {
236
374
 
237
375
  server.listen(BRIDGE_PORT, '127.0.0.1', () => {
238
376
  console.log(`===============================================`);
239
- console.log(`🚀 send-to-pi Bridge Daemon is running!`);
377
+ console.log(`🚀 send-to-pi Bridge Daemon v1.3.0 is running!`);
240
378
  console.log(`📡 Listening on: http://127.0.0.1:${BRIDGE_PORT}`);
241
379
  console.log(`💻 Platform: ${process.platform}`);
242
380
  console.log(`📂 Work Dir: ${getWorkDir()}`);
@@ -260,4 +398,10 @@ if (require.main === module) {
260
398
  startDaemon();
261
399
  }
262
400
 
263
- module.exports = { startDaemon, createBridgeServer, findActivePi, formatContent };
401
+ module.exports = {
402
+ startDaemon,
403
+ createBridgeServer,
404
+ findActivePi,
405
+ discoverAllActivePis,
406
+ formatContent,
407
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Layer 1 Escape Hatch: Custom user-defined terminal launch command template.
3
+ *
4
+ * Example (~/.pi/send-to-pi/config.json or PI_LAUNCH_CMD):
5
+ * rex run --interactive --cwd "{workdir}" --keep-open -- pi
6
+ * kitty --directory "{workdir}" pi
7
+ */
8
+
9
+ const { spawn } = require('child_process');
10
+
11
+ function shellEscape(value) {
12
+ if (process.platform === 'win32') {
13
+ return String(value).replace(/"/g, '""');
14
+ }
15
+ return String(value).replace(/(["\\$`])/g, '\\$1');
16
+ }
17
+
18
+ function launchCustomCommand(template, workDir) {
19
+ return new Promise((resolve) => {
20
+ const trimmed = (template || '').trim();
21
+ if (!trimmed) {
22
+ resolve({ success: false, error: 'Empty custom launch command' });
23
+ return;
24
+ }
25
+
26
+ const command = trimmed.replace(/\{workdir\}/gi, shellEscape(workDir));
27
+
28
+ try {
29
+ const child = spawn(command, {
30
+ cwd: workDir,
31
+ env: { ...process.env, PI_WORKDIR: workDir },
32
+ shell: true,
33
+ detached: true,
34
+ stdio: 'ignore',
35
+ });
36
+
37
+ let failed = false;
38
+ child.on('error', (err) => {
39
+ failed = true;
40
+ resolve({ success: false, error: err.message });
41
+ });
42
+
43
+ child.unref();
44
+ setTimeout(() => {
45
+ if (!failed) {
46
+ resolve({ success: true, terminal: 'Custom Command', command });
47
+ }
48
+ }, 250);
49
+ } catch (err) {
50
+ resolve({ success: false, error: err.message });
51
+ }
52
+ });
53
+ }
54
+
55
+ module.exports = { launchCustomCommand };