1import os
2import platform
3import socket
4import subprocess
5import sys
6import tomllib
7from importlib.metadata import entry_points
8from importlib.util import find_spec
9from pathlib import Path
10
11import click
12from plain.cli.print import print_event
13from plain.runtime import APP_PATH, PLAIN_TEMP_PATH
14from rich.columns import Columns
15from rich.console import Console
16from rich.text import Text
17
18from .mkcert import MkcertManager
19from .process import Supervisor
20from .state import find_project_root
21from .utils import has_pyproject_toml
22
23ENTRYPOINT_GROUP = "plain.dev"
24
25
26class DevSupervisor(Supervisor):
27 state_filename = "dev.pid"
28 log_dir = PLAIN_TEMP_PATH / "dev" / "logs" / "run"
29 background_command = ("dev",)
30 display_name = "`plain dev`"
31
32 def setup(
33 self, *, port: int | None, hostname: str | None, log_level: str | None
34 ) -> None:
35 if not hostname:
36 project_name = os.path.basename(
37 os.getcwd()
38 ) # Use directory name by default
39
40 if has_pyproject_toml(APP_PATH.parent):
41 with open(Path(APP_PATH.parent, "pyproject.toml"), "rb") as f:
42 pyproject = tomllib.load(f)
43 project_name = pyproject.get("project", {}).get(
44 "name", project_name
45 )
46
47 hostname = f"{project_name.lower()}.localhost"
48
49 self.hostname = hostname
50 self.log_level = log_level
51
52 self.prepare_log()
53
54 if port:
55 self.port = int(port)
56 if not self._port_available(self.port):
57 click.secho(f"Port {self.port} in use", fg="red")
58 raise SystemExit(1)
59 else:
60 self.port = self._find_open_port(8443)
61 if self.port != 8443:
62 click.secho(f"Port 8443 in use, using {self.port}", fg="yellow")
63
64 self.ssl_key_path = None
65 self.ssl_cert_path = None
66
67 self.url = f"https://{self.hostname}:{self.port}"
68 self.tunnel_url = os.environ.get("DEV_TUNNEL_URL", "")
69
70 self.plain_env = {
71 "PYTHONUNBUFFERED": "true",
72 "PLAIN_SERVER_ACCESS_LOG_FIELDS": '["method", "url", "status", "duration_ms", "size"]',
73 "FORCE_COLOR": "1",
74 "PYTHONWARNINGS": "default::DeprecationWarning,default::PendingDeprecationWarning",
75 **os.environ,
76 }
77
78 if log_level:
79 self.plain_env["PLAIN_FRAMEWORK_LOG_LEVEL"] = log_level.upper()
80 self.plain_env["PLAIN_LOG_LEVEL"] = log_level.upper()
81
82 self.custom_process_env = {
83 **self.plain_env,
84 "PORT": str(self.port),
85 "DEV_URL": self.url,
86 }
87
88 if self.tunnel_url:
89 status_bar = Columns(
90 [
91 Text.from_markup(
92 f"[bold]Tunnel[/bold] [underline][link={self.tunnel_url}]{self.tunnel_url}[/link][/underline]"
93 ),
94 Text.from_markup(
95 f"[dim][bold]Server[/bold] [link={self.url}]{self.url}[/link][/dim]"
96 ),
97 Text.from_markup(
98 "[dim][bold]Ctrl+C[/bold] to stop[/dim]",
99 justify="right",
100 ),
101 ],
102 expand=True,
103 )
104 else:
105 status_bar = Columns(
106 [
107 Text.from_markup(
108 f"[bold]Server[/bold] [underline][link={self.url}]{self.url}[/link][/underline]"
109 ),
110 Text.from_markup(
111 "[dim][bold]Ctrl+C[/bold] to stop[/dim]", justify="right"
112 ),
113 ],
114 expand=True,
115 )
116 self.console = Console(markup=False, highlight=False)
117 self.console_status = self.console.status(status_bar)
118
119 self.init_poncho(self.console.out)
120
121 def _find_open_port(self, start_port: int) -> int:
122 port = start_port
123 while not self._port_available(port):
124 port += 1
125 return port
126
127 def _port_available(self, port: int) -> bool:
128 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
129 sock.settimeout(0.5)
130 result = sock.connect_ex(("127.0.0.1", port))
131 return result != 0
132
133 def run(self, *, reinstall_ssl: bool = False) -> int:
134 if not self.acquire():
135 click.secho(self.already_running_message(self.read_pidfile()), fg="yellow")
136 return 1
137
138 mkcert_manager = MkcertManager()
139 mkcert_manager.setup_mkcert(force_reinstall=reinstall_ssl)
140 self.ssl_cert_path, self.ssl_key_path = mkcert_manager.generate_certs(
141 domain=self.hostname,
142 storage_path=Path(PLAIN_TEMP_PATH) / "dev" / "certs",
143 force_regenerate=reinstall_ssl,
144 )
145
146 self.symlink_plain_src()
147 self.install_agent()
148 self.modify_hosts_file()
149
150 print_event("Running preflight checks...", newline=False)
151 self.run_preflight()
152
153 if find_spec("plain.postgres"):
154 # Shared-DB divergence guard (managed DBs only). If this checkout
155 # borrowed another checkout's database and would apply a divergent
156 # migration, fork to a private copy first so the shared DB is never
157 # silently mutated. No-op for BYO. Never block dev on it.
158 try:
159 from .postgres.branch_switch import check_branch_switch
160 from .postgres.guard import guard_dev_database
161 from .postgres.resolve import INJECTED_URL_ENV_VAR
162
163 # The app directory is often a level below the project root
164 # (`example/`, `backend/`). Anchor on the same root the rest of
165 # the flow uses, or the guard reads a nonexistent cache path,
166 # decides nothing is managed, and silently does nothing.
167 project_root = find_project_root(Path(APP_PATH).parent)
168
169 guarded_url = guard_dev_database(project_root)
170 if guarded_url:
171 self.plain_env[INJECTED_URL_ENV_VAR] = guarded_url
172 os.environ[INJECTED_URL_ENV_VAR] = guarded_url
173
174 # Advisory only — tells you when this database still carries a
175 # branch you've moved away from.
176 check_branch_switch(project_root)
177 except Exception as e:
178 click.secho(f"Database checks skipped: {e}", fg="yellow", err=True)
179
180 print_event("Waiting for database...", newline=False)
181 subprocess.run(
182 [sys.executable, "-m", "plain", "postgres", "wait"],
183 env=self.plain_env,
184 check=True,
185 )
186
187 print_event("Syncing database...")
188 subprocess.run(
189 [sys.executable, "-m", "plain", "postgres", "sync"],
190 env=self.plain_env,
191 check=True,
192 )
193
194 print_event("Starting app...")
195
196 # Manually start the status bar now so it isn't bungled by
197 # another thread checking db stuff...
198 self.console_status.start()
199
200 assert self.poncho is not None, "poncho should be initialized"
201
202 self.add_server()
203 self.add_entrypoints()
204 self.add_pyproject_run()
205
206 # The status bar is invisible in piped output and the log file,
207 # so print the URLs as regular lines too.
208 self.poncho.system_print(f"Server running at {self.url}\n")
209 if self.tunnel_url:
210 self.poncho.system_print(f"Tunnel running at {self.tunnel_url}\n")
211
212 try:
213 # Start processes we know about and block the main thread
214 self.poncho.loop()
215
216 # Remove the status bar
217 self.console_status.stop()
218 finally:
219 self.release()
220 self.close()
221
222 assert self.poncho.returncode is not None, "returncode should be set after loop"
223 return self.poncho.returncode
224
225 def symlink_plain_src(self) -> None:
226 """Symlink the plain package into .plain so we can look at it easily"""
227 spec = find_spec("plain.runtime")
228 if spec is None or spec.origin is None:
229 return
230 plain_path = Path(spec.origin).parent.parent
231 if not PLAIN_TEMP_PATH.exists():
232 PLAIN_TEMP_PATH.mkdir()
233
234 symlink_path = PLAIN_TEMP_PATH / "src"
235
236 # The symlink is broken
237 if symlink_path.is_symlink() and not symlink_path.exists():
238 symlink_path.unlink()
239
240 # The symlink exists but points to the wrong place
241 if (
242 symlink_path.is_symlink()
243 and symlink_path.exists()
244 and symlink_path.resolve() != plain_path
245 ):
246 symlink_path.unlink()
247
248 if plain_path.exists() and not symlink_path.exists():
249 symlink_path.symlink_to(plain_path)
250
251 def install_agent(self) -> None:
252 """Install AI agent skills and hooks."""
253 try:
254 result = subprocess.run(
255 [sys.executable, "-m", "plain", "agent", "install"],
256 check=False,
257 capture_output=True,
258 text=True,
259 )
260 if result.returncode != 0 and result.stderr:
261 click.secho(
262 f"Warning: Failed to install agent: {result.stderr}",
263 fg="yellow",
264 err=True,
265 )
266 except Exception as e:
267 click.secho(
268 f"Warning: Failed to install agent: {e}",
269 fg="yellow",
270 err=True,
271 )
272
273 def modify_hosts_file(self) -> None:
274 """Modify the hosts file to map the custom domain to 127.0.0.1."""
275 # Check if the hostname already resolves to loopback (e.g., *.localhost on modern OS)
276 try:
277 results = socket.getaddrinfo(self.hostname, None)
278 addrs = {r[4][0] for r in results}
279 if addrs <= {"127.0.0.1", "::1"}:
280 return
281 except socket.gaierror:
282 pass # Doesn't resolve; fall through to modify hosts file
283
284 entry_identifier = "# Added by plain"
285 hosts_entry = f"127.0.0.1 {self.hostname} {entry_identifier}"
286
287 if platform.system() == "Windows":
288 hosts_path = Path(r"C:\Windows\System32\drivers\etc\hosts")
289 try:
290 with hosts_path.open("r") as f:
291 content = f.read()
292
293 if hosts_entry in content:
294 return # Entry already exists; no action needed
295
296 # Entry does not exist; add it
297 with hosts_path.open("a") as f:
298 f.write(f"{hosts_entry}\n")
299 click.secho(f"Added {self.hostname} to {hosts_path}", bold=True)
300 except PermissionError:
301 click.secho(
302 "Permission denied while modifying hosts file. Please run the script as an administrator.",
303 fg="red",
304 )
305 sys.exit(1)
306 else:
307 # For macOS and Linux
308 hosts_path = Path("/etc/hosts")
309 try:
310 with hosts_path.open("r") as f:
311 content = f.read()
312
313 if hosts_entry in content:
314 return # Entry already exists; no action needed
315
316 # Entry does not exist; append it using sudo
317 click.secho(
318 f"Adding {self.hostname} to /etc/hosts file. You may be prompted for your password.\n",
319 bold=True,
320 )
321 cmd = f"echo '{hosts_entry}' | sudo tee -a {hosts_path} >/dev/null"
322 subprocess.run(cmd, shell=True, check=True)
323 click.secho(f"Added {self.hostname} to {hosts_path}\n", bold=True)
324 except PermissionError:
325 click.secho(
326 "Permission denied while accessing hosts file.",
327 fg="red",
328 )
329 sys.exit(1)
330 except subprocess.CalledProcessError:
331 click.secho(
332 "Failed to modify hosts file. Please ensure you have sudo privileges.",
333 fg="red",
334 )
335 sys.exit(1)
336
337 def run_preflight(self) -> None:
338 if subprocess.run(
339 ["plain", "preflight", "--quiet"], env=self.plain_env, check=False
340 ).returncode:
341 click.secho("Preflight check failed!", fg="red")
342 sys.exit(1)
343
344 def add_server(self) -> None:
345 """Add the Plain HTTP server process."""
346 assert self.poncho is not None
347 server_cmd = [
348 sys.executable,
349 "-m",
350 "plain",
351 "server",
352 "--bind",
353 f"{self.hostname}:{self.port}",
354 "--certfile",
355 str(self.ssl_cert_path),
356 "--keyfile",
357 str(self.ssl_key_path),
358 "--threads",
359 "4",
360 "--timeout",
361 "60",
362 "--workers",
363 "1",
364 "--reload", # Enable auto-reload for development
365 ]
366
367 server = " ".join(server_cmd)
368 self.poncho.add_process("plain", server, env=self.plain_env)
369
370 def add_entrypoints(self) -> None:
371 assert self.poncho is not None
372 for entry_point in entry_points().select(group=ENTRYPOINT_GROUP):
373 self.poncho.add_process(
374 entry_point.name,
375 f"plain dev entrypoint {entry_point.name}",
376 env=self.plain_env,
377 )
378
379 def add_pyproject_run(self) -> None:
380 """Additional processes that only run during `plain dev`."""
381 assert self.poncho is not None
382 if not has_pyproject_toml(APP_PATH.parent):
383 return
384
385 with open(Path(APP_PATH.parent, "pyproject.toml"), "rb") as f:
386 pyproject = tomllib.load(f)
387
388 run_commands = (
389 pyproject.get("tool", {}).get("plain", {}).get("dev", {}).get("run", {})
390 )
391 for name, data in run_commands.items():
392 env = {
393 **self.custom_process_env,
394 **data.get("env", {}),
395 }
396 self.poncho.add_process(name, data["cmd"], env=env)