nodehop 0.2.0__py3-none-any.whl
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.
- nodehop/__init__.py +3 -0
- nodehop/__main__.py +3 -0
- nodehop/cli.py +807 -0
- nodehop/config.py +183 -0
- nodehop/core.py +642 -0
- nodehop/deploy.py +205 -0
- nodehop/doctor.py +285 -0
- nodehop/gui.py +338 -0
- nodehop/hooks.py +193 -0
- nodehop/icon.py +148 -0
- nodehop/modules/__init__.py +26 -0
- nodehop/modules/base.py +214 -0
- nodehop/modules/claude_code.py +309 -0
- nodehop/modules/codex.py +209 -0
- nodehop/modules/command.py +81 -0
- nodehop/onboard.py +210 -0
- nodehop/pairing.py +217 -0
- nodehop/runner.py +72 -0
- nodehop/state.py +120 -0
- nodehop/system.py +41 -0
- nodehop/train.py +200 -0
- nodehop/transport.py +107 -0
- nodehop/ui.py +140 -0
- nodehop/uninstall.py +145 -0
- nodehop-0.2.0.dist-info/METADATA +261 -0
- nodehop-0.2.0.dist-info/RECORD +30 -0
- nodehop-0.2.0.dist-info/WHEEL +5 -0
- nodehop-0.2.0.dist-info/entry_points.txt +2 -0
- nodehop-0.2.0.dist-info/licenses/LICENSE +21 -0
- nodehop-0.2.0.dist-info/top_level.txt +1 -0
nodehop/gui.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Desktop side of NodeHop: notifications with its own icon, and a window to settle a conflict.
|
|
2
|
+
|
|
3
|
+
- macOS: a tiny NodeHop.app (a JavaScript for Automation applet built with the
|
|
4
|
+
system's `osacompile`, carrying NodeHop's icon) posts the notifications, so
|
|
5
|
+
they show NodeHop's logo, and opens a native window (NSAlert: a bar per
|
|
6
|
+
machine, a button per choice). It then runs `nodehop resolve --keep …` itself.
|
|
7
|
+
- Linux: `notify-send` with action buttons when the notification server
|
|
8
|
+
supports them, `zenity` otherwise, and a plain notification as a last resort.
|
|
9
|
+
|
|
10
|
+
Everything is best-effort: without a desktop, `nodehop resolve` in a terminal
|
|
11
|
+
does the same.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import shlex
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import time
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import List, Optional, Tuple
|
|
25
|
+
|
|
26
|
+
from nodehop.config import home_dir
|
|
27
|
+
from nodehop.icon import ensure_icons
|
|
28
|
+
from nodehop.system import os_name
|
|
29
|
+
|
|
30
|
+
APP_VERSION = "6" # bump to rebuild the applet when its script changes
|
|
31
|
+
|
|
32
|
+
# JavaScript for Automation (built into macOS): a native window (NSAlert) with
|
|
33
|
+
# NodeHop's icon, one bar per machine and one button per choice.
|
|
34
|
+
APPLET_JS = r"""
|
|
35
|
+
ObjC.import('Cocoa');
|
|
36
|
+
|
|
37
|
+
const NODEHOP = __NODEHOP__;
|
|
38
|
+
|
|
39
|
+
function readRequest() {
|
|
40
|
+
const path = $.NSHomeDirectory().js + '/.config/nodehop/ui/request.json';
|
|
41
|
+
const s = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null);
|
|
42
|
+
if (!s || s.isNil()) return null;
|
|
43
|
+
return JSON.parse(s.js);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function label(text, x, y, w, h, size, bold, grey) {
|
|
47
|
+
const f = $.NSTextField.labelWithString(text);
|
|
48
|
+
f.font = bold ? $.NSFont.boldSystemFontOfSize(size) : $.NSFont.systemFontOfSize(size);
|
|
49
|
+
if (grey) f.textColor = $.NSColor.secondaryLabelColor;
|
|
50
|
+
f.frame = $.NSMakeRect(x, y, w, h);
|
|
51
|
+
return f;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function sidesView(sides) {
|
|
55
|
+
const W = 440, ROW = 50;
|
|
56
|
+
const view = $.NSView.alloc.initWithFrame($.NSMakeRect(0, 0, W, sides.length * ROW + 6));
|
|
57
|
+
const most = Math.max(1, ...sides.map(s => s.actions));
|
|
58
|
+
sides.forEach((s, i) => {
|
|
59
|
+
const y = (sides.length - 1 - i) * ROW + 6;
|
|
60
|
+
view.addSubview(label(s.name, 0, y + 24, 170, 18, 13, true, false));
|
|
61
|
+
view.addSubview(label(s.state, 0, y + 4, 170, 16, 11, false, true));
|
|
62
|
+
const bar = $.NSLevelIndicator.alloc.initWithFrame($.NSMakeRect(180, y + 27, W - 180, 12));
|
|
63
|
+
bar.levelIndicatorStyle = $.NSLevelIndicatorStyleContinuousCapacity;
|
|
64
|
+
bar.minValue = 0;
|
|
65
|
+
bar.maxValue = most;
|
|
66
|
+
bar.doubleValue = s.actions;
|
|
67
|
+
bar.warningValue = most + 1;
|
|
68
|
+
bar.criticalValue = most + 1;
|
|
69
|
+
view.addSubview(bar);
|
|
70
|
+
view.addSubview(label(s.detail, 180, y + 4, W - 180, 16, 11, false, true));
|
|
71
|
+
});
|
|
72
|
+
return view;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function shellQuote(t) { return "'" + String(t).replace(/'/g, "'\\''") + "'"; }
|
|
76
|
+
|
|
77
|
+
function run() {
|
|
78
|
+
const req = readRequest();
|
|
79
|
+
if (!req) return;
|
|
80
|
+
const sa = Application.currentApplication();
|
|
81
|
+
sa.includeStandardAdditions = true;
|
|
82
|
+
if (req.kind === 'notify') {
|
|
83
|
+
sa.displayNotification(req.message, {withTitle: 'NodeHop', subtitle: req.title});
|
|
84
|
+
delay(1);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
sa.displayNotification('Choose which version to keep', {withTitle: 'NodeHop', subtitle: req.title});
|
|
88
|
+
const app = $.NSApplication.sharedApplication;
|
|
89
|
+
app.setActivationPolicy($.NSApplicationActivationPolicyRegular);
|
|
90
|
+
app.activateIgnoringOtherApps(true);
|
|
91
|
+
const alert = $.NSAlert.alloc.init;
|
|
92
|
+
alert.messageText = req.title;
|
|
93
|
+
alert.informativeText = req.message;
|
|
94
|
+
alert.accessoryView = sidesView(req.sides);
|
|
95
|
+
req.choices.forEach(c => alert.addButtonWithTitle(c.label));
|
|
96
|
+
alert.addButtonWithTitle('Later');
|
|
97
|
+
alert.window.level = $.NSFloatingWindowLevel;
|
|
98
|
+
const index = alert.runModal - 1000;
|
|
99
|
+
if (index < 0 || index >= req.choices.length) return;
|
|
100
|
+
const choice = req.choices[index];
|
|
101
|
+
try {
|
|
102
|
+
sa.doShellScript(shellQuote(NODEHOP) + ' resolve ' + shellQuote(req.project) + ' --keep ' + choice.key + ' 2>&1');
|
|
103
|
+
sa.displayNotification(choice.label + ': done', {withTitle: 'NodeHop', subtitle: req.project});
|
|
104
|
+
} catch (e) {
|
|
105
|
+
const err = $.NSAlert.alloc.init;
|
|
106
|
+
err.messageText = 'NodeHop could not apply this choice';
|
|
107
|
+
err.informativeText = String(e);
|
|
108
|
+
err.runModal;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def ui_dir() -> Path:
|
|
115
|
+
return home_dir() / "ui"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def app_path() -> Path:
|
|
119
|
+
return Path.home() / "Applications" / "NodeHop.app"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def nodehop_command() -> str:
|
|
123
|
+
exe = shutil.which("nodehop") or os.path.abspath(sys.argv[0])
|
|
124
|
+
return shlex.quote(exe)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def ensure_app() -> Optional[Path]:
|
|
128
|
+
"""macOS: build (or rebuild) NodeHop.app. Returns its path, or None if it cannot be built."""
|
|
129
|
+
if os_name() != "macos" or not shutil.which("osacompile"):
|
|
130
|
+
return None
|
|
131
|
+
app = app_path()
|
|
132
|
+
stamp = app / "Contents" / "Resources" / "nodehop-version"
|
|
133
|
+
if stamp.exists() and stamp.read_text().strip() == APP_VERSION:
|
|
134
|
+
return app
|
|
135
|
+
ui_dir().mkdir(parents=True, exist_ok=True)
|
|
136
|
+
script = ui_dir() / "NodeHop.js"
|
|
137
|
+
exe = shutil.which("nodehop") or os.path.abspath(sys.argv[0])
|
|
138
|
+
script.write_text(APPLET_JS.replace("__NODEHOP__", json.dumps(exe)))
|
|
139
|
+
app.parent.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
if app.exists():
|
|
141
|
+
shutil.rmtree(app)
|
|
142
|
+
if subprocess.run(["osacompile", "-l", "JavaScript", "-o", str(app), str(script)], capture_output=True).returncode != 0:
|
|
143
|
+
return None
|
|
144
|
+
icns = ensure_icons().get("icns")
|
|
145
|
+
plist = app / "Contents" / "Info.plist"
|
|
146
|
+
if icns:
|
|
147
|
+
shutil.copy(icns, app / "Contents" / "Resources" / "applet.icns")
|
|
148
|
+
# Recent osacompile also puts the default icon in Assets.car, which wins over applet.icns.
|
|
149
|
+
(app / "Contents" / "Resources" / "Assets.car").unlink(missing_ok=True)
|
|
150
|
+
subprocess.run(["plutil", "-remove", "CFBundleIconName", str(plist)], capture_output=True)
|
|
151
|
+
subprocess.run(["plutil", "-replace", "CFBundleIdentifier", "-string", "dev.nodehop.app", str(plist)], capture_output=True)
|
|
152
|
+
subprocess.run(["plutil", "-replace", "CFBundleName", "-string", "NodeHop", str(plist)], capture_output=True)
|
|
153
|
+
stamp.write_text(APP_VERSION + "\n")
|
|
154
|
+
# Changing the bundle invalidates the applet's signature: sign it again (ad hoc, local use).
|
|
155
|
+
subprocess.run(["codesign", "--force", "--deep", "--sign", "-", str(app)], capture_output=True)
|
|
156
|
+
subprocess.run(["touch", str(app)], capture_output=True)
|
|
157
|
+
return app
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _write_request(request: dict) -> None:
|
|
161
|
+
ui_dir().mkdir(parents=True, exist_ok=True)
|
|
162
|
+
tmp = ui_dir() / "request.tmp"
|
|
163
|
+
tmp.write_text(json.dumps(request, ensure_ascii=False), encoding="utf-8")
|
|
164
|
+
tmp.replace(ui_dir() / "request.json")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def notify(title: str, message: str) -> bool:
|
|
168
|
+
"""A notification with NodeHop's icon. Returns False if nothing could be shown."""
|
|
169
|
+
try:
|
|
170
|
+
if os_name() == "macos":
|
|
171
|
+
app = ensure_app()
|
|
172
|
+
if app:
|
|
173
|
+
_write_request({"kind": "notify", "title": title, "message": message})
|
|
174
|
+
# -n: a fresh instance each time, even if a conflict window is still open
|
|
175
|
+
return subprocess.run(["open", "-n", "-g", str(app)], capture_output=True).returncode == 0
|
|
176
|
+
safe = message.replace('"', "'")
|
|
177
|
+
return subprocess.run(["osascript", "-e", f'display notification "{safe}" with title "NodeHop"'],
|
|
178
|
+
capture_output=True).returncode == 0
|
|
179
|
+
if os_name() == "linux" and shutil.which("notify-send"):
|
|
180
|
+
png = ensure_icons()["png"]
|
|
181
|
+
return subprocess.run(["notify-send", "--app-name=NodeHop", f"--icon={png}", f"NodeHop · {title}", message],
|
|
182
|
+
capture_output=True).returncode == 0
|
|
183
|
+
except OSError:
|
|
184
|
+
pass
|
|
185
|
+
return False
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# ---- conflict window ------------------------------------------------------------
|
|
189
|
+
def choices(report: dict) -> List[Tuple[str, str]]:
|
|
190
|
+
here, there = report["here"]["machine"], report["there"]["machine"]
|
|
191
|
+
return [
|
|
192
|
+
("here", f"Keep {here}"),
|
|
193
|
+
("there", f"Keep {there}"),
|
|
194
|
+
("merge", f"Keep {here} + {there}'s work"),
|
|
195
|
+
]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _ago(ts: Optional[float], now: float) -> str:
|
|
199
|
+
if not ts:
|
|
200
|
+
return "—"
|
|
201
|
+
secs = max(0, int(now - ts))
|
|
202
|
+
if secs < 90:
|
|
203
|
+
return f"{secs} s ago"
|
|
204
|
+
if secs < 5400:
|
|
205
|
+
return f"{secs // 60} min ago"
|
|
206
|
+
return f"{secs // 3600} h ago"
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _clock(ts: Optional[float]) -> str:
|
|
210
|
+
return time.strftime("%H:%M", time.localtime(ts)) if ts else "?"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def side_lines(p: dict, since: float, now: float) -> List[Tuple[str, str]]:
|
|
214
|
+
"""(label, value) rows describing what one agent did since `since`."""
|
|
215
|
+
if p.get("busy"):
|
|
216
|
+
state = "working right now"
|
|
217
|
+
elif p.get("running"):
|
|
218
|
+
state = "open, waiting at its prompt"
|
|
219
|
+
else:
|
|
220
|
+
state = "paused (stopped by NodeHop, nothing lost)"
|
|
221
|
+
rows = [("Status", state)]
|
|
222
|
+
if p.get("task"):
|
|
223
|
+
task = " ".join(p["task"].split())
|
|
224
|
+
rows.append(("Task", "“" + (task[:110] + "…" if len(task) > 110 else task) + "”"))
|
|
225
|
+
tools, msgs = p.get("tool_calls", p.get("actions")) or 0, p.get("messages") or 0
|
|
226
|
+
if tools or msgs:
|
|
227
|
+
span = ""
|
|
228
|
+
if p.get("first_activity") and p.get("last_activity"):
|
|
229
|
+
minutes = max(1, round((p["last_activity"] - p["first_activity"]) / 60))
|
|
230
|
+
span = f", over {minutes} min ({_clock(p['first_activity'])} → {_clock(p['last_activity'])})"
|
|
231
|
+
rows.append((f"Since {_clock(since)}", f"{tools} actions (commands, file edits), {msgs} replies{span}"))
|
|
232
|
+
else:
|
|
233
|
+
rows.append((f"Since {_clock(since)}", "did nothing"))
|
|
234
|
+
if p.get("last_action"):
|
|
235
|
+
rows.append(("Last action", f"{p['last_action']} ({_ago(p.get('last_activity'), now)})"))
|
|
236
|
+
details = p.get("file_details") or [{"path": f, "lines": None} for f in p.get("files") or []]
|
|
237
|
+
if details:
|
|
238
|
+
shown = ", ".join(d["path"] + (f" ({d['lines']} lines)" if d.get("lines") is not None else "") for d in details)
|
|
239
|
+
more = (p.get("files_count") or 0) - len(details)
|
|
240
|
+
rows.append(("Files changed", shown + (f" and {more} more" if more > 0 else "")))
|
|
241
|
+
else:
|
|
242
|
+
rows.append(("Files changed", "none"))
|
|
243
|
+
if p.get("last_message"):
|
|
244
|
+
msg = " ".join(p["last_message"].split())
|
|
245
|
+
rows.append(("Last words", "“" + (msg[:110] + "…" if len(msg) > 110 else msg) + "”"))
|
|
246
|
+
return rows
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def headline(report: dict) -> str:
|
|
250
|
+
there, here = report["there"]["machine"], report["here"]["machine"]
|
|
251
|
+
copy = report.get("copy_time")
|
|
252
|
+
return (f"{there} took over at {_clock(report['since'])}" + (f", from a copy taken at {copy}" if copy else "")
|
|
253
|
+
+ f", while {here} kept working. Both did some of the work since.")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def dialog_text(report: dict) -> str:
|
|
257
|
+
now = time.time()
|
|
258
|
+
out = [headline(report), ""]
|
|
259
|
+
for key in ("here", "there"):
|
|
260
|
+
p = report[key]
|
|
261
|
+
out.append(("▶ " + p["machine"] + (" (this Mac)" if key == "here" else "")).upper())
|
|
262
|
+
for label, value in side_lines(p, report["since"], now):
|
|
263
|
+
out.append(f"{label}: {value}")
|
|
264
|
+
out.append("")
|
|
265
|
+
out.append(f"The version you do not keep is saved in a backup folder, nothing is deleted.")
|
|
266
|
+
return "\n".join(out)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def short_side(p: dict, now: float, here: bool) -> dict:
|
|
270
|
+
tools = p.get("tool_calls", p.get("actions")) or 0
|
|
271
|
+
if p.get("busy"):
|
|
272
|
+
state = "● working now"
|
|
273
|
+
elif p.get("running"):
|
|
274
|
+
state = "● open, idle"
|
|
275
|
+
else:
|
|
276
|
+
state = "⏸ paused by NodeHop"
|
|
277
|
+
detail = f"{tools} actions" + (f" · last one {_ago(p.get('last_activity'), now)}" if p.get("last_activity") else "")
|
|
278
|
+
return {"name": p["machine"] + (" · this Mac" if here else ""), "state": state, "actions": tools, "detail": detail}
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def window_request(report: dict) -> dict:
|
|
282
|
+
"""What the conflict window shows: a title, one sentence, a bar per machine, the choices."""
|
|
283
|
+
now = time.time()
|
|
284
|
+
here, there = report["here"]["machine"], report["there"]["machine"]
|
|
285
|
+
return {
|
|
286
|
+
"kind": "ask",
|
|
287
|
+
"project": report["project"],
|
|
288
|
+
"title": f"Two agents worked on {report['project']} at the same time",
|
|
289
|
+
"message": f"{there} took over at {_clock(report['since'])} while {here} kept going. "
|
|
290
|
+
f"Keep one: the other is saved in a backup.",
|
|
291
|
+
"sides": [short_side(report["here"], now, True), short_side(report["there"], now, False)],
|
|
292
|
+
"choices": [{"key": k, "label": label} for k, label in choices(report)],
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def ask_conflict(report: dict) -> bool:
|
|
297
|
+
"""Show the conflict window (macOS app, or Linux notification/zenity). Non-blocking."""
|
|
298
|
+
title = f"Two agents on {report['project']}"
|
|
299
|
+
try:
|
|
300
|
+
if os_name() == "macos":
|
|
301
|
+
app = ensure_app()
|
|
302
|
+
if not app:
|
|
303
|
+
return False
|
|
304
|
+
_write_request(window_request(report))
|
|
305
|
+
return subprocess.run(["open", "-n", str(app)], capture_output=True).returncode == 0
|
|
306
|
+
if os_name() == "linux":
|
|
307
|
+
# Waiting for a click blocks: let a detached `nodehop gui-ask` do it.
|
|
308
|
+
subprocess.Popen(["nodehop", "gui-ask", report["project"]], start_new_session=True,
|
|
309
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
310
|
+
return True
|
|
311
|
+
except OSError:
|
|
312
|
+
pass
|
|
313
|
+
return False
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def linux_choose(report: dict) -> Optional[str]:
|
|
317
|
+
"""Linux, blocking: a notification with buttons, or a zenity list. Returns here/there/merge or None."""
|
|
318
|
+
title = f"Two agents worked in parallel on {report['project']}"
|
|
319
|
+
opts = choices(report)
|
|
320
|
+
png = str(ensure_icons()["png"])
|
|
321
|
+
if shutil.which("notify-send"):
|
|
322
|
+
help_text = subprocess.run(["notify-send", "--help"], capture_output=True, text=True).stdout
|
|
323
|
+
if "--action" in help_text:
|
|
324
|
+
argv = ["notify-send", "--app-name=NodeHop", f"--icon={png}", "--wait", "--urgency=critical"]
|
|
325
|
+
argv += [f"--action={k}={label}" for k, label in opts]
|
|
326
|
+
argv += [title, headline(report)]
|
|
327
|
+
picked = subprocess.run(argv, capture_output=True, text=True).stdout.strip()
|
|
328
|
+
return picked if picked in dict(opts) else None
|
|
329
|
+
if shutil.which("zenity"):
|
|
330
|
+
argv = ["zenity", "--list", "--title=NodeHop", f"--window-icon={png}", "--width=720", "--height=520",
|
|
331
|
+
f"--text={window_request(report)['message']}", "--column=key", "--column=Choice", "--hide-column=1",
|
|
332
|
+
"--print-column=1", "--ok-label=Apply", "--cancel-label=Decide later"]
|
|
333
|
+
for k, label in opts:
|
|
334
|
+
argv += [k, label]
|
|
335
|
+
picked = subprocess.run(argv, capture_output=True, text=True).stdout.strip()
|
|
336
|
+
return picked if picked in dict(opts) else None
|
|
337
|
+
notify(title, f"Run in a terminal: nodehop resolve {report['project']}")
|
|
338
|
+
return None
|
nodehop/hooks.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Sleep/wake hooks and the periodic pre-sync, per system.
|
|
2
|
+
|
|
3
|
+
Only the primary (the laptop) needs hooks: it hands work off when it goes to
|
|
4
|
+
sleep, takes it back when it wakes up, and pre-syncs every few minutes. The
|
|
5
|
+
always-on machine only needs an SSH server, NodeHop, tmux and the agent.
|
|
6
|
+
|
|
7
|
+
- macOS: SleepWatcher runs ~/.sleep and ~/.wakeup; a launchd agent pre-syncs.
|
|
8
|
+
- Linux: a systemd system-sleep script (installed with sudo once) runs
|
|
9
|
+
on-sleep / on-wake as the user; a systemd user timer pre-syncs.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import getpass
|
|
15
|
+
import os
|
|
16
|
+
import plistlib
|
|
17
|
+
import shlex
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import List, Optional, Tuple
|
|
20
|
+
|
|
21
|
+
BEGIN = "# >>> nodehop >>>"
|
|
22
|
+
END = "# <<< nodehop <<<"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def upsert_block(path: Path, body: str) -> None:
|
|
26
|
+
"""Insert or replace NodeHop's block in a shell script, keeping the user's own lines."""
|
|
27
|
+
block = f"{BEGIN}\n{body.rstrip()}\n{END}\n"
|
|
28
|
+
text = path.read_text() if path.exists() else "#!/bin/sh\n"
|
|
29
|
+
if BEGIN in text and END in text:
|
|
30
|
+
head, rest = text.split(BEGIN, 1)
|
|
31
|
+
_, tail = rest.split(END, 1)
|
|
32
|
+
text = head + block + tail.lstrip("\n")
|
|
33
|
+
else:
|
|
34
|
+
if not text.endswith("\n"):
|
|
35
|
+
text += "\n"
|
|
36
|
+
text += block
|
|
37
|
+
path.write_text(text)
|
|
38
|
+
path.chmod(path.stat().st_mode | 0o755)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def launch_agent(label: str, argv: List[str], extra_path: List[str], interval: Optional[int]) -> bytes:
|
|
42
|
+
home = str(Path.home())
|
|
43
|
+
path = ":".join(p.replace("$HOME", home) for p in extra_path) + ":/usr/bin:/bin:/usr/sbin:/sbin"
|
|
44
|
+
log = str(Path.home() / "Library" / "Logs" / f"{label}.log")
|
|
45
|
+
plist = {
|
|
46
|
+
"Label": label,
|
|
47
|
+
"ProgramArguments": argv,
|
|
48
|
+
"EnvironmentVariables": {"PATH": path},
|
|
49
|
+
"RunAtLoad": True,
|
|
50
|
+
"StandardOutPath": log,
|
|
51
|
+
"StandardErrorPath": log,
|
|
52
|
+
}
|
|
53
|
+
if interval:
|
|
54
|
+
plist["StartInterval"] = interval
|
|
55
|
+
else:
|
|
56
|
+
plist["KeepAlive"] = True
|
|
57
|
+
return plistlib.dumps(plist)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def systemd_units(nodehop_bin: str, extra_path: List[str], interval: int) -> Tuple[str, str]:
|
|
61
|
+
home = str(Path.home())
|
|
62
|
+
path = ":".join(p.replace("$HOME", home) for p in extra_path) + ":/usr/local/bin:/usr/bin:/bin"
|
|
63
|
+
service = (
|
|
64
|
+
"[Unit]\nDescription=NodeHop pre-sync (keeps the other machine warm)\n\n"
|
|
65
|
+
f"[Service]\nType=oneshot\nEnvironment=PATH={path}\nExecStart={shlex.quote(nodehop_bin)} sync\n"
|
|
66
|
+
)
|
|
67
|
+
timer = (
|
|
68
|
+
"[Unit]\nDescription=Run NodeHop pre-sync regularly\n\n"
|
|
69
|
+
f"[Timer]\nOnBootSec=2min\nOnUnitActiveSec={interval}s\nPersistent=true\n\n"
|
|
70
|
+
"[Install]\nWantedBy=timers.target\n"
|
|
71
|
+
)
|
|
72
|
+
return service, timer
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def linux_sleep_script(nodehop_bin: str, extra_path: List[str], user: str) -> str:
|
|
76
|
+
"""systemd runs this as root with `pre` before sleep (and waits for it) and `post` after wake-up."""
|
|
77
|
+
home = str(Path.home())
|
|
78
|
+
path = ":".join(p.replace("$HOME", home) for p in extra_path) + ":/usr/local/bin:/usr/bin:/bin"
|
|
79
|
+
run = f"runuser -u {shlex.quote(user)} -- env HOME={shlex.quote(home)} PATH={shlex.quote(path)} {shlex.quote(nodehop_bin)}"
|
|
80
|
+
return (
|
|
81
|
+
"#!/bin/sh\n"
|
|
82
|
+
f"# Installed by NodeHop for {user}. Remove this file to disable.\n"
|
|
83
|
+
'case "$1/$2" in\n'
|
|
84
|
+
f" pre/*) {run} on-sleep >/dev/null 2>&1 ;;\n"
|
|
85
|
+
f" post/*) ({run} on-wake >/dev/null 2>&1 &) ;;\n"
|
|
86
|
+
"esac\n"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _lingering(user: str) -> bool:
|
|
91
|
+
"""Linux: does the user's systemd keep running with nobody logged in?"""
|
|
92
|
+
import subprocess
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
out = subprocess.run(["loginctl", "show-user", user, "-p", "Linger", "--value"],
|
|
96
|
+
capture_output=True, text=True, timeout=10).stdout
|
|
97
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
98
|
+
return False
|
|
99
|
+
return out.strip() == "yes"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def install_watch(nodehop_bin: str, extra_path: List[str], system: str) -> Tuple[List[str], List[str]]:
|
|
103
|
+
"""Server: a background `nodehop watch` that takes over if the primary goes silent."""
|
|
104
|
+
home = Path.home()
|
|
105
|
+
if system == "macos":
|
|
106
|
+
label = "dev.nodehop.watch"
|
|
107
|
+
agents = home / "Library" / "LaunchAgents"
|
|
108
|
+
agents.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
plist_path = agents / f"{label}.plist"
|
|
110
|
+
plist_path.write_bytes(launch_agent(label, [nodehop_bin, "watch"], extra_path, None))
|
|
111
|
+
uid = os.getuid()
|
|
112
|
+
return [str(plist_path)], [f"launchctl bootout gui/{uid}/{label} 2>/dev/null; launchctl bootstrap gui/{uid} {plist_path}"]
|
|
113
|
+
if system == "linux":
|
|
114
|
+
units = home / ".config" / "systemd" / "user"
|
|
115
|
+
units.mkdir(parents=True, exist_ok=True)
|
|
116
|
+
path = ":".join(p.replace("$HOME", str(home)) for p in extra_path) + ":/usr/local/bin:/usr/bin:/bin"
|
|
117
|
+
(units / "nodehop-watch.service").write_text(
|
|
118
|
+
"[Unit]\nDescription=NodeHop fallback watcher\n\n"
|
|
119
|
+
f"[Service]\nEnvironment=PATH={path}\nExecStart={shlex.quote(nodehop_bin)} watch\nRestart=always\nRestartSec=30\n\n"
|
|
120
|
+
"[Install]\nWantedBy=default.target\n"
|
|
121
|
+
)
|
|
122
|
+
todo = ["systemctl --user daemon-reload && systemctl --user enable --now nodehop-watch.service"]
|
|
123
|
+
if not _lingering(getpass.getuser()):
|
|
124
|
+
todo.append(f"sudo loginctl enable-linger {getpass.getuser()} # keep it running with nobody logged in")
|
|
125
|
+
return [str(units / "nodehop-watch.service")], todo
|
|
126
|
+
raise RuntimeError("background services exist for macOS and Linux only")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def install(
|
|
130
|
+
nodehop_bin: str,
|
|
131
|
+
is_primary: bool,
|
|
132
|
+
extra_path: List[str],
|
|
133
|
+
sync_interval: int = 30,
|
|
134
|
+
system: Optional[str] = None,
|
|
135
|
+
) -> Tuple[List[str], List[str]]:
|
|
136
|
+
"""Write the hook files and return the commands the user still has to run (they may need sudo)."""
|
|
137
|
+
from nodehop.system import os_name, sleep_hook_path
|
|
138
|
+
|
|
139
|
+
system = system or os_name()
|
|
140
|
+
home = Path.home()
|
|
141
|
+
if not is_primary:
|
|
142
|
+
return install_watch(nodehop_bin, extra_path, system)
|
|
143
|
+
exe = shlex.quote(nodehop_bin)
|
|
144
|
+
written: List[str] = []
|
|
145
|
+
todo: List[str] = []
|
|
146
|
+
if system == "macos":
|
|
147
|
+
upsert_block(home / ".sleep", f"{exe} on-sleep >/dev/null 2>&1")
|
|
148
|
+
upsert_block(home / ".wakeup", f"{exe} on-wake >/dev/null 2>&1 &")
|
|
149
|
+
written += [str(home / ".sleep"), str(home / ".wakeup")]
|
|
150
|
+
label = "dev.nodehop.sync"
|
|
151
|
+
agents = home / "Library" / "LaunchAgents"
|
|
152
|
+
agents.mkdir(parents=True, exist_ok=True)
|
|
153
|
+
plist_path = agents / f"{label}.plist"
|
|
154
|
+
plist_path.write_bytes(launch_agent(label, [nodehop_bin, "sync"], extra_path, sync_interval))
|
|
155
|
+
written.append(str(plist_path))
|
|
156
|
+
uid = os.getuid()
|
|
157
|
+
todo += [
|
|
158
|
+
"brew install sleepwatcher && brew services start sleepwatcher",
|
|
159
|
+
f"launchctl bootout gui/{uid}/{label} 2>/dev/null; launchctl bootstrap gui/{uid} {plist_path}",
|
|
160
|
+
]
|
|
161
|
+
elif system == "linux":
|
|
162
|
+
units = home / ".config" / "systemd" / "user"
|
|
163
|
+
units.mkdir(parents=True, exist_ok=True)
|
|
164
|
+
service, timer = systemd_units(nodehop_bin, extra_path, sync_interval)
|
|
165
|
+
(units / "nodehop-sync.service").write_text(service)
|
|
166
|
+
(units / "nodehop-sync.timer").write_text(timer)
|
|
167
|
+
written += [str(units / "nodehop-sync.service"), str(units / "nodehop-sync.timer")]
|
|
168
|
+
script = home / ".config" / "nodehop" / "system-sleep-hook"
|
|
169
|
+
script.parent.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
script.write_text(linux_sleep_script(nodehop_bin, extra_path, getpass.getuser()))
|
|
171
|
+
script.chmod(0o755)
|
|
172
|
+
written.append(str(script))
|
|
173
|
+
todo += [
|
|
174
|
+
"systemctl --user daemon-reload && systemctl --user enable --now nodehop-sync.timer",
|
|
175
|
+
f"sudo install -m 755 {shlex.quote(str(script))} {sleep_hook_path()}",
|
|
176
|
+
]
|
|
177
|
+
else:
|
|
178
|
+
raise RuntimeError("sleep hooks exist for macOS and Linux only; use `nodehop handoff` / `nodehop pull` by hand")
|
|
179
|
+
return written, todo
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def apply(todo: List[str], runner) -> Tuple[List[dict], List[str]]:
|
|
183
|
+
"""Run the follow-up commands that need no administrator; return (ran, left for the person)."""
|
|
184
|
+
ran: List[dict] = []
|
|
185
|
+
left: List[str] = []
|
|
186
|
+
for command in todo:
|
|
187
|
+
if command.lstrip().startswith("sudo "):
|
|
188
|
+
left.append(command)
|
|
189
|
+
continue
|
|
190
|
+
result = runner.run(["sh", "-c", command.split(" #")[0]], check=False, timeout=900)
|
|
191
|
+
ran.append({"command": command, "ok": result.returncode == 0,
|
|
192
|
+
"output": (result.stderr or result.stdout or "").strip()[-300:]})
|
|
193
|
+
return ran, left
|
nodehop/icon.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""NodeHop's logo, drawn in pure Python (no image library): a baton hopping from one node to another.
|
|
2
|
+
|
|
3
|
+
`write_png(path, size)` renders it; `ensure_icons()` caches a PNG (Linux
|
|
4
|
+
notifications) and, on macOS, an .icns built with the system's sips/iconutil.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import shutil
|
|
11
|
+
import struct
|
|
12
|
+
import subprocess
|
|
13
|
+
import tempfile
|
|
14
|
+
import zlib
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Callable, List, Tuple
|
|
17
|
+
|
|
18
|
+
from nodehop.config import home_dir
|
|
19
|
+
|
|
20
|
+
Color = Tuple[float, float, float]
|
|
21
|
+
|
|
22
|
+
TOP: Color = (0.44, 0.33, 0.98) # violet
|
|
23
|
+
BOTTOM: Color = (0.12, 0.62, 0.95) # blue
|
|
24
|
+
WHITE: Color = (1.0, 1.0, 1.0)
|
|
25
|
+
GLOW: Color = (1.0, 0.82, 0.35) # warm baton
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _clamp(x: float) -> float:
|
|
29
|
+
return 0.0 if x < 0 else 1.0 if x > 1 else x
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _round_rect(px: float, py: float, half: float, radius: float) -> float:
|
|
33
|
+
qx, qy = abs(px) - half + radius, abs(py) - half + radius
|
|
34
|
+
outside = math.hypot(max(qx, 0.0), max(qy, 0.0))
|
|
35
|
+
return outside + min(max(qx, qy), 0.0) - radius
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _circle(px: float, py: float, cx: float, cy: float, r: float) -> float:
|
|
39
|
+
return math.hypot(px - cx, py - cy) - r
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _arc(px: float, py: float, cx: float, cy: float, r: float, width: float, a0: float, a1: float) -> float:
|
|
43
|
+
"""Distance to a stroked arc between angles a0..a1 (radians, y up), with round caps."""
|
|
44
|
+
ang = math.atan2(cy - py, px - cx)
|
|
45
|
+
if a0 <= ang <= a1:
|
|
46
|
+
return abs(math.hypot(px - cx, py - cy) - r) - width / 2
|
|
47
|
+
ends = [(cx + r * math.cos(a), cy - r * math.sin(a)) for a in (a0, a1)]
|
|
48
|
+
return min(math.hypot(px - ex, py - ey) for ex, ey in ends) - width / 2
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _triangle(px: float, py: float, pts: List[Tuple[float, float]]) -> float:
|
|
52
|
+
"""Signed distance to a triangle (negative inside)."""
|
|
53
|
+
d = float("inf")
|
|
54
|
+
sign = 1.0
|
|
55
|
+
for i in range(3):
|
|
56
|
+
(ax, ay), (bx, by) = pts[i], pts[(i + 1) % 3]
|
|
57
|
+
ex, ey = bx - ax, by - ay
|
|
58
|
+
wx, wy = px - ax, py - ay
|
|
59
|
+
t = _clamp((wx * ex + wy * ey) / (ex * ex + ey * ey))
|
|
60
|
+
d = min(d, math.hypot(wx - ex * t, wy - ey * t))
|
|
61
|
+
(ax, ay), (bx, by), (cx, cy) = pts
|
|
62
|
+
c1 = (bx - ax) * (py - ay) - (by - ay) * (px - ax)
|
|
63
|
+
c2 = (cx - bx) * (py - by) - (cy - by) * (px - bx)
|
|
64
|
+
c3 = (ax - cx) * (py - cy) - (ay - cy) * (px - cx)
|
|
65
|
+
if (c1 >= 0 and c2 >= 0 and c3 >= 0) or (c1 <= 0 and c2 <= 0 and c3 <= 0):
|
|
66
|
+
sign = -1.0
|
|
67
|
+
return sign * d
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def render(size: int) -> List[List[Tuple[int, int, int, int]]]:
|
|
71
|
+
s = size / 100.0 # design on a 100x100 grid
|
|
72
|
+
aa = 1.0 / s # one pixel, in grid units, for anti-aliasing
|
|
73
|
+
|
|
74
|
+
def cover(dist: float) -> float:
|
|
75
|
+
return _clamp(0.5 - dist / aa)
|
|
76
|
+
|
|
77
|
+
angle_tip = math.radians(34)
|
|
78
|
+
cx, cy, r = 50.0, 66.0, 25.0
|
|
79
|
+
tip = (cx + r * math.cos(angle_tip), cy - r * math.sin(angle_tip))
|
|
80
|
+
# Arrowhead along the arc's tangent at its end.
|
|
81
|
+
tx, ty = math.sin(angle_tip), math.cos(angle_tip) # direction of travel (clockwise, y down)
|
|
82
|
+
nx, ny = -ty, tx
|
|
83
|
+
head = [
|
|
84
|
+
(tip[0] + tx * 8.5, tip[1] + ty * 8.5),
|
|
85
|
+
(tip[0] - nx * 6.5 - tx * 1.0, tip[1] - ny * 6.5 - ty * 1.0),
|
|
86
|
+
(tip[0] + nx * 6.5 - tx * 1.0, tip[1] + ny * 6.5 - ty * 1.0),
|
|
87
|
+
]
|
|
88
|
+
shapes: List[Tuple[Callable[[float, float], float], Color]] = [
|
|
89
|
+
(lambda x, y: _arc(x, y, cx, cy, r, 6.0, math.radians(38), math.radians(168)), WHITE),
|
|
90
|
+
(lambda x, y: _triangle(x, y, head), WHITE),
|
|
91
|
+
(lambda x, y: _circle(x, y, 25.5, 70.0, 9.5), WHITE), # the laptop
|
|
92
|
+
(lambda x, y: _circle(x, y, 75.5, 72.0, 7.0), WHITE), # the always-on machine
|
|
93
|
+
(lambda x, y: _circle(x, y, 50.0, 41.0, 5.0), GLOW), # the baton, mid-hop
|
|
94
|
+
]
|
|
95
|
+
rows = []
|
|
96
|
+
for j in range(size):
|
|
97
|
+
y = (j + 0.5) / s
|
|
98
|
+
row = []
|
|
99
|
+
for i in range(size):
|
|
100
|
+
x = (i + 0.5) / s
|
|
101
|
+
bg = cover(_round_rect(x - 50, y - 50, 46, 21))
|
|
102
|
+
if bg <= 0:
|
|
103
|
+
row.append((0, 0, 0, 0))
|
|
104
|
+
continue
|
|
105
|
+
t = y / 100
|
|
106
|
+
col = [TOP[k] * (1 - t) + BOTTOM[k] * t for k in range(3)]
|
|
107
|
+
for dist, colour in shapes:
|
|
108
|
+
a = cover(dist(x, y))
|
|
109
|
+
if a > 0:
|
|
110
|
+
col = [col[k] * (1 - a) + colour[k] * a for k in range(3)]
|
|
111
|
+
row.append(tuple(int(round(c * 255)) for c in col) + (int(round(bg * 255)),))
|
|
112
|
+
rows.append(row)
|
|
113
|
+
return rows
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def write_png(path: Path, size: int = 256) -> Path:
|
|
117
|
+
rows = render(size)
|
|
118
|
+
raw = b"".join(b"\x00" + bytes(v for px in row for v in px) for row in rows)
|
|
119
|
+
|
|
120
|
+
def chunk(kind: bytes, data: bytes) -> bytes:
|
|
121
|
+
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
|
122
|
+
|
|
123
|
+
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0))
|
|
124
|
+
png += chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")
|
|
125
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
126
|
+
path.write_bytes(png)
|
|
127
|
+
return path
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def ensure_icons() -> dict:
|
|
131
|
+
"""Cached icon files: {"png": path, "icns": path or None}."""
|
|
132
|
+
folder = home_dir() / "assets"
|
|
133
|
+
png = folder / "nodehop.png"
|
|
134
|
+
if not png.exists():
|
|
135
|
+
write_png(png, 256)
|
|
136
|
+
icns = folder / "nodehop.icns"
|
|
137
|
+
if not icns.exists() and shutil.which("iconutil") and shutil.which("sips"):
|
|
138
|
+
big = write_png(folder / "nodehop-1024.png", 1024)
|
|
139
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
140
|
+
iconset = Path(tmp) / "nodehop.iconset"
|
|
141
|
+
iconset.mkdir()
|
|
142
|
+
for px in (16, 32, 128, 256, 512):
|
|
143
|
+
for scale in (1, 2):
|
|
144
|
+
out = iconset / (f"icon_{px}x{px}" + ("@2x" if scale == 2 else "") + ".png")
|
|
145
|
+
subprocess.run(["sips", "-z", str(px * scale), str(px * scale), str(big), "--out", str(out)],
|
|
146
|
+
capture_output=True, check=False)
|
|
147
|
+
subprocess.run(["iconutil", "-c", "icns", str(iconset), "-o", str(icns)], capture_output=True, check=False)
|
|
148
|
+
return {"png": png, "icns": icns if icns.exists() else None}
|