-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdev
More file actions
executable file
·406 lines (333 loc) · 14.8 KB
/
dev
File metadata and controls
executable file
·406 lines (333 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env python3
# This script is an entrypoint for all developer activities in this project.
import argparse
import os
import subprocess
import sys
def cmd(cmds: argparse._SubParsersAction, name: str, help: str):
"""Decorator that registers subcommands as functions to be executed."""
def wrapper(func):
p = cmds.add_parser(name, help=help, add_help=False)
p.set_defaults(func=func)
return p
return wrapper
def run(cmd: str, args: list = [], capture_output=False, env: os._Environ = os.environ):
"""Helper to run cmd in a shell."""
if args:
if args[0] == "--":
args = args[1:]
cmd += " -- " + " ".join(args)
return subprocess.run(
cmd, check=True, shell=True, capture_output=capture_output, env=env
)
def main():
if not os.getenv("DIRENV_DIR"):
print("Direnv is not enabled. Fix it first! See README.md for instructions.")
sys.exit(1)
cli = argparse.ArgumentParser(
usage="./dev COMMAND [FLAGS...]",
description="CLI for developing Seed Hyper Media. Provides commands for most common developer tasks in this project.",
)
cmds = cli.add_subparsers(
title="commands",
# This is ugly, but otherwise argparse prints the redundant list of subcommands.
# And if we just use an empty string it messes up help message alignment for some subcommands.
metavar=" ",
)
@cmd(
cmds,
"gen",
"Check the generated code is up to date and run the code generation process to fix it.",
)
def gen(args):
targets_to_check = (
run(
f"plz query filter -i 'generated:check' {str.join(' ', args)}",
capture_output=True,
)
.stdout.decode("utf-8")
.split("\n")
)
out = run(f"plz run parallel {' '.join(targets_to_check)}", capture_output=True)
targets_to_gen = []
for line in out.stdout.decode("utf-8").split("\n"):
idx = line.find("plz run")
if idx == -1:
continue
targets_to_gen.append(line[idx + 7 : -1]) # 7 is length of 'plz run'
if len(targets_to_gen) == 0:
return
return run("plz run parallel " + " ".join(targets_to_gen))
@cmd(cmds, "run-desktop", "Run frontend desktop app for development.")
def run_desktop(args):
run("node scripts/cleanup-desktop.js")
run("plz build //:pnpm")
if "SEED_NO_DAEMON_SPAWN" not in os.environ:
run("plz build //backend:seed-daemon")
return run("pnpm desktop", args=args)
@cmd(
cmds,
"2-run-desktop",
"Run TWO desktop instances: packages SeedDev.app for instance B (alt ports + alt appdata), ad-hoc signs it, launches its binary directly to bypass Gatekeeper, then runs the normal dev in the foreground. Pass --skip-package to reuse the existing packaged build.",
)
def run_desktop_2(args):
import atexit
import pathlib
import platform
import time
skip_package = "--skip-package" in args
forward_args = [a for a in args if a != "--skip-package"]
# Alt instance ports/appdata — bumped by +100 from the standard dev values in .env.vars.
# Packaged bundle is Seed.app (forge.config.ts IS_PROD_DEV reads from package.json,
# not an env var). Launching the Mach-O binary directly (not via `open`) avoids
# LaunchServices bundle-id registration, so two Seed.app copies coexist fine as long as
# their userData paths (VITE_DESKTOP_APPDATA) and daemon ports differ.
# Each instance gets its own VITE_VERSION so the in-app version label /
# debug indicator make it obvious which window is which. Instance B's
# value is baked at package time; instance A's is set at dev launch.
instance_a_version = os.environ.get("VITE_VERSION", "0.0.0.local") + "-A"
instance_b_version = os.environ.get("VITE_VERSION", "0.0.0.local") + "-B"
alt_env_overrides = {
"VITE_DESKTOP_P2P_PORT": "58100",
"VITE_DESKTOP_HTTP_PORT": "58101",
"VITE_DESKTOP_GRPC_PORT": "58102",
"VITE_METRIC_SERVER_HTTP_PORT": "58103",
"VITE_DESKTOP_API_PORT": "58104",
"VITE_DESKTOP_APPDATA": "Seed-local-2",
"DAEMON_HTTP_PORT": "58101",
"DAEMON_HTTP_URL": "http://localhost:58101",
"DAEMON_FILE_URL": "http://localhost:58101",
"SEED_P2P_PORT": "58100",
"SEED_HTTP_PORT": "58101",
"SEED_GRPC_PORT": "58102",
"SEED_P2P_TESTNET_NAME": os.environ.get("SEED_P2P_TESTNET_NAME", "dev"),
"VITE_VERSION": instance_b_version,
}
desktop_dir = pathlib.Path("frontend/apps/desktop").resolve()
system = platform.system()
machine = platform.machine()
arch = "arm64" if machine in ("arm64", "aarch64") else "x64"
if system == "Darwin":
app_bundle = desktop_dir / "out" / f"Seed-darwin-{arch}" / "Seed.app"
binary_path = app_bundle / "Contents" / "MacOS" / "Seed"
elif system == "Linux":
app_bundle = desktop_dir / "out" / f"Seed-linux-{arch}"
binary_path = app_bundle / "Seed"
else:
app_bundle = desktop_dir / "out" / f"Seed-win32-{arch}"
binary_path = app_bundle / "Seed.exe"
if skip_package:
print(
"⚠️ --skip-package: Instance B will run the EXISTING packaged bundle. "
"If you've changed renderer/main source since the last package, the dev "
"instance (A) will see your changes but the packaged instance (B) will "
"NOT. Re-run without --skip-package to repackage with current source."
)
if not skip_package:
run("node scripts/cleanup-desktop.js")
run("plz build //:pnpm")
if "SEED_NO_DAEMON_SPAWN" not in os.environ:
run("plz build //backend:seed-daemon")
package_env = os.environ.copy()
package_env.update(alt_env_overrides)
print(
"📦 Packaging Seed.app for instance B (alt ports + alt appdata '{}')…".format(
alt_env_overrides["VITE_DESKTOP_APPDATA"]
)
)
run("pnpm --filter @shm/desktop package", env=package_env)
if not binary_path.exists():
print(f"❌ Packaged binary not found at {binary_path}. Re-run without --skip-package.")
sys.exit(1)
# macOS bundle: ad-hoc codesign + strip quarantine xattr. Launching the
# Mach-O binary directly (not via `open`) bypasses Gatekeeper's
# LaunchServices check, but hardened-runtime Electron still needs a
# valid (ad-hoc) signature or it fails with "cannot be opened because
# of a problem." Sign AFTER any file mutations.
if system == "Darwin":
subprocess.run(
f'xattr -cr "{app_bundle}" 2>/dev/null || true',
shell=True,
)
sign = subprocess.run(
f'codesign --force --deep --sign - "{app_bundle}"',
shell=True,
capture_output=True,
)
if sign.returncode != 0:
print("⚠️ codesign --sign - failed:")
print(sign.stderr.decode("utf-8", errors="replace"))
log_path = os.path.abspath(".ai/desktop-2.log")
os.makedirs(os.path.dirname(log_path), exist_ok=True)
instance_b_log = open(log_path, "w")
print(f"📝 Instance B logs → {log_path}")
print(f"🅱️ Launching {binary_path} (version '{instance_b_version}')")
instance_b_env = os.environ.copy()
instance_b_env.update(alt_env_overrides)
instance_b = subprocess.Popen(
[str(binary_path)],
env=instance_b_env,
stdout=instance_b_log,
stderr=subprocess.STDOUT,
start_new_session=True,
)
def stop_instance_b():
if instance_b.poll() is None:
print(f"🛑 Stopping instance B (pid {instance_b.pid})…")
try:
os.killpg(os.getpgid(instance_b.pid), 15)
except ProcessLookupError:
pass
atexit.register(stop_instance_b)
# Give instance B a couple of seconds to fail fast on bad bundle / signing
# before we fire up instance A.
for _ in range(3):
time.sleep(1)
if instance_b.poll() is not None:
print(f"❌ Instance B exited early (code {instance_b.returncode}). Check {log_path}.")
sys.exit(1)
print(f"🅰️ Starting instance A (dev ports, appdata 'Seed-local', version '{instance_a_version}')…")
instance_a_env = os.environ.copy()
instance_a_env["VITE_VERSION"] = instance_a_version
try:
return run("pnpm desktop", args=forward_args, env=instance_a_env)
finally:
stop_instance_b()
@cmd(cmds, "run-desktop-mainnet", "Run frontend desktop app for dev, on mainnet.")
def run_desktop_mainnet(args):
run("node scripts/cleanup-desktop.js")
run("plz build //:pnpm")
if "SEED_NO_DAEMON_SPAWN" not in os.environ:
run("plz build //backend:seed-daemon")
del os.environ["SEED_P2P_TESTNET_NAME"]
return run("pnpm desktop", args=args)
@cmd(cmds, "run-desktop-profiler", "Run desktop app with memory profiler window.")
def run_desktop_profiler(args):
run("node scripts/cleanup-desktop.js")
run("plz build //:pnpm")
if "SEED_NO_DAEMON_SPAWN" not in os.environ:
run("plz build //backend:seed-daemon")
os.environ["MEMORY_PROFILER"] = "1"
return run("pnpm desktop", args=args)
@cmd(cmds, "run-desktop-fixture", "Run desktop app against test fixture data.")
def run_desktop_fixture(args):
run("plz build //:pnpm")
if "SEED_NO_DAEMON_SPAWN" not in os.environ:
run("plz build //backend:seed-daemon")
# Point entire desktop userData to fixture directory
fixture_dir = os.path.abspath("test-fixtures/desktop")
os.environ["SEED_FIXTURE_DATA_DIR"] = fixture_dir
os.environ["SEED_P2P_TESTNET_NAME"] = "fixture"
return run("pnpm desktop", args=args)
@cmd(cmds, "build-desktop", "Builds the desktop app for the current platform. Use --profiler to enable React Profiler.")
def build_desktop(args):
# run("node scripts/cleanup-desktop.js")
# run("./scripts/cleanup-frontend.sh")
run("pnpm install")
run("plz build //backend:seed-daemon //:pnpm")
# build-desktop always targets mainnet, regardless of the ambient SEED_P2P_TESTNET_NAME.
os.environ["SEED_P2P_TESTNET_NAME"] = ""
os.environ["VITE_LIGHTNING_API_URL"] = "https://ln.seed.hyper.media"
host_url = "https://host.seed.hyper.media"
gateway_url = "https://hyper.media"
# Enable React Profiler if --profiler flag is passed
if "--profiler" in args:
os.environ["REACT_PROFILER"] = "1"
args = [a for a in args if a != "--profiler"]
env_prefix = f"VITE_DESKTOP_APPDATA=Seed-local SHOW_OB_RESET_BTN=0 VITE_SEED_HOST_URL={host_url} VITE_GATEWAY_URL={gateway_url}"
if os.environ.get("REACT_PROFILER"):
env_prefix = f"REACT_PROFILER=1 {env_prefix}"
run(f"{env_prefix} pnpm desktop:make")
@cmd(cmds, "test-desktop", "Run frontend desktop tests.")
def test_desktop(args):
run("node scripts/cleanup-desktop.js")
run("plz build //backend:seed-daemon //:pnpm")
testnet_var = "SEED_P2P_TESTNET_NAME"
if testnet_var not in os.environ:
os.environ[testnet_var] = "dev"
return run("pnpm desktop:test", args=args)
@cmd(cmds, "run-web", "Run Web app for development.")
def run_web(args):
run("./scripts/cleanup-web.sh")
run("pnpm install")
run("plz build //:pnpm")
return run(
"pnpm web",
args=args,
)
@cmd(cmds, "build-web", "Build web app for production.")
def build_web(args):
run("./scripts/cleanup-frontend.sh")
run("./scripts/cleanup-web.sh")
run("pnpm install")
run("plz build //:pnpm")
return run(
"pnpm web:prod",
args=args,
)
@cmd(cmds, "frontend-validate", "Formats, Validates")
def frontend_validate(args):
run("node scripts/cleanup-desktop.js")
run("pnpm validate")
@cmd(
cmds,
"run-backend",
"Build and run seed-daemon binary for the current platform.",
)
def run_backend(args):
env = os.environ.copy()
env["LLAMA_LOG"] = "error"
return run("plz run //backend:seed-daemon", args=args, env=env)
@cmd(cmds, "build-backend", "Build seed-daemon binary for the current platform.")
def build_backend(args):
return run("plz build //backend:seed-daemon")
@cmd(cmds, "run-gw-backend", "Build and run backend for seed web gateway.")
def run_gateway(args):
return run("plz run //backend:seed-gateway", args=args)
@cmd(cmds, "ping-p2p", "Execute ping utility to check visibility.")
def ping_p2p(args):
return run("plz run //backend:pingp2p", args=args)
@cmd(
cmds,
"install-cli",
"Build and install the seed-cli command into ~/.local/bin.",
)
def install_cli(args):
import pathlib
run("pnpm install")
run("pnpm --filter @seed-hypermedia/cli build")
cli_dist = pathlib.Path(__file__).resolve().parent / "frontend" / "apps" / "cli" / "dist" / "index.js"
if not cli_dist.exists():
print(f"Error: build output not found at {cli_dist}")
sys.exit(1)
bin_dir = pathlib.Path.home() / ".local" / "bin"
bin_dir.mkdir(parents=True, exist_ok=True)
link = bin_dir / "seed-cli"
if link.exists() or link.is_symlink():
link.unlink()
link.symlink_to(cli_dist)
print(f"Installed: {link} -> {cli_dist}")
@cmd(
cmds,
"release",
"Create a new Release. this will create a new tag and push it to the remote repository",
)
def release(args):
# run("pnpm validate")
# run("pnpm test")
run("node scripts/tag.mjs")
if len(sys.argv) == 1:
cli.print_help()
return
namespace, args = cli.parse_known_args()
try:
namespace.func(args)
except ValueError as err:
print(str(err))
sys.exit(1)
except subprocess.CalledProcessError:
sys.exit(1)
except KeyboardInterrupt:
return
if __name__ == "__main__":
main()