mlai-code 0.3.8 → 0.3.10

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.
package/worker/preview.py CHANGED
@@ -11,6 +11,15 @@ if sys.platform == 'win32':
11
11
  import winproc; winproc.install() # os.killpg / os.getpgid for the dev server it stops
12
12
 
13
13
 
14
+ LOOPBACK = '127.0.0.1'
15
+
16
+
17
+ def listen_host():
18
+ """BUG-0687: on a laptop the preview listens on this computer only (127.0.0.1); bound to 0.0.0.0 it served the
19
+ project's files to everyone on the same Wi-Fi. The cloud workspace keeps 0.0.0.0, which its preview address needs."""
20
+ return LOOPBACK if os.getenv('MINI_LAPTOP') == '1' or os.getenv('MINI_PREVIEW_HOST') == LOOPBACK else '0.0.0.0'
21
+
22
+
14
23
  def plan(repo):
15
24
  repo = pathlib.Path(repo).resolve()
16
25
  package = repo / 'package.json'
@@ -27,13 +36,13 @@ def plan(repo):
27
36
  if not isinstance(script, str): continue
28
37
  # Only standard framework entrypoints; compound scripts need agent review.
29
38
  if 'next' in deps and re.fullmatch(r'next (dev|start)(?: --(?:hostname|port) [a-zA-Z0-9.:-]+)*', script.strip()):
30
- return {'command': ['npm', 'run', name, '--', '--hostname', '0.0.0.0', '--port', '3000'], 'label': 'Next.js', 'cwd': str(repo)}
39
+ return {'command': ['npm', 'run', name, '--', '--hostname', listen_host(), '--port', str(PORT)], 'label': 'Next.js', 'cwd': str(repo)}
31
40
  if 'vite' in deps and re.fullmatch(r'vite(?: --host)?', script.strip()):
32
- return {'command': ['npm', 'run', name, '--', '--host', '0.0.0.0', '--port', '3000', '--strictPort'], 'label': 'Vite', 'cwd': str(repo)}
41
+ return {'command': ['npm', 'run', name, '--', '--host', listen_host(), '--port', str(PORT), '--strictPort'], 'label': 'Vite', 'cwd': str(repo)}
33
42
  return None
34
43
  index = repo / 'index.html'
35
44
  if index.is_file() and not index.is_symlink():
36
- return {'command': [sys.executable, str(pathlib.Path(__file__).resolve()), 'serve', '--root', str(repo)], 'label': 'Static website', 'cwd': str(repo)}
45
+ return {'command': [sys.executable, str(pathlib.Path(__file__).resolve()), 'serve', '--port', str(PORT), '--root', str(repo)], 'label': 'Static website', 'cwd': str(repo)}
37
46
  return None
38
47
 
39
48
 
@@ -106,7 +115,7 @@ def ensure_next_dev_origins(repo):
106
115
  def next_origin_blocked():
107
116
  """Next.js dev answers 403 'Unauthorized' to /_next requests from an origin outside allowedDevOrigins."""
108
117
  try:
109
- request = urllib.request.Request('http://127.0.0.1:3000/_next/mlai-origin-probe', headers={'Origin': 'https://preview.vercel.run', 'Host': 'preview.vercel.run'})
118
+ request = urllib.request.Request(base_url() + '/_next/mlai-origin-probe', headers={'Origin': 'https://preview.vercel.run', 'Host': 'preview.vercel.run'})
110
119
  opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
111
120
  with opener.open(request, timeout=3): return False
112
121
  except urllib.error.HTTPError as error:
@@ -119,7 +128,7 @@ def next_origin_blocked():
119
128
  def host_blocked():
120
129
  """Vite answers loopback but rejects the public preview host with 403 'Blocked request'."""
121
130
  try:
122
- request = urllib.request.Request('http://127.0.0.1:3000', headers={'Host': 'preview.vercel.run'})
131
+ request = urllib.request.Request(base_url(), headers={'Host': 'preview.vercel.run'})
123
132
  opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
124
133
  with opener.open(request, timeout=2): return False
125
134
  except urllib.error.HTTPError as error:
@@ -129,25 +138,26 @@ def host_blocked():
129
138
  except (OSError, urllib.error.URLError): return False
130
139
 
131
140
 
132
- PORT_CLASH = ('Two servers are using port 3000. The preview reaches the one that answers HTTP {code} (usually the API), and the web app '
141
+ PORT_CLASH = ('Two servers are using port {port}. The preview reaches the one that answers HTTP {code} (usually the API), and the web app '
133
142
  'answers on the other address. Ask the agent to move the API to another port, such as 3001, and proxy /api to it from the web server.')
134
143
 
135
144
 
136
145
  def loopback6_status(opener):
137
146
  try:
138
- with opener.open('http://[::1]:3000', timeout=2) as response: return response.status
147
+ with opener.open('http://[::1]:%d' % PORT, timeout=2) as response: return response.status
139
148
  except urllib.error.HTTPError as error: return error.code
140
149
  except (OSError, urllib.error.URLError, ValueError): return 0
141
150
 
142
151
 
143
152
  def status(state):
153
+ if PATHS.get('repo') and not CTX: bind(PATHS['repo'], state)
144
154
  code = 0
145
155
  try:
146
156
  # Do not follow redirects off the local app or send loopback through an HTTP proxy.
147
157
  class NoRedirect(urllib.request.HTTPRedirectHandler):
148
158
  def redirect_request(self, *args, **kwargs): return None
149
159
  opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
150
- with opener.open('http://127.0.0.1:3000', timeout=2) as response: code = response.status
160
+ with opener.open(base_url(), timeout=2) as response: code = response.status
151
161
  except urllib.error.HTTPError as error: code = error.code
152
162
  except (OSError, urllib.error.URLError): pass
153
163
  # Web Bug-035: a compound dev script can start the API and the web server on the same port 3000, one on the IPv4
@@ -163,6 +173,13 @@ def status(state):
163
173
  file.seek(0, 2);file.seek(max(0, file.tell() - 8000));log = file.read().decode(errors='replace')
164
174
  except OSError: pass
165
175
  ready = 200 <= code < 400
176
+ owner = server_owner() if code else {}
177
+ if owner.get('owner') == 'foreign':
178
+ # Something answers, but it is another app: never this project's preview, whatever its HTTP status.
179
+ return {'ready': False, 'running': running, 'httpStatus': code, 'port': PORT, 'url': base_url(), 'foreignServer': owner,
180
+ 'message': foreign_text(owner) + ' This is not the preview of this workspace, and browser checks against it do not count. '
181
+ + ('Start the preview again and it moves to a free port.' if alternate_ports() else 'Stop that server (it does not belong to this project), then start the preview again.'),
182
+ 'log': log}
166
183
  work = job(state); mode = meta.get('mode', 'dev') if running or ready else ''
167
184
  if work.get('alive') and (work.get('step') or '').startswith(('Building', 'Installing', 'Adding')): log = tail(state / 'preview-build.log', 8000) or log
168
185
  extra = {'mode': mode or None, 'notes': [n for n in work.get('notes') or [] if isinstance(n, str)][:4]}
@@ -178,15 +195,343 @@ def status(state):
178
195
  return {'ready': False, 'running': running, 'httpStatus': 403, 'hostBlocked': True, 'message': 'The dev server is blocking the preview address. Restart it with server.allowedHosts set (or ask the agent to restart the preview).', 'log': log}
179
196
  if ready: message = 'Live preview' if mode == 'prod' else ('Live preview (development). Preparing the production version…' if work.get('alive') else 'Live preview (development)')
180
197
  elif work.get('alive'): message = (work.get('step') or 'Preparing the preview') + '…'
181
- elif clash: message = PORT_CLASH.format(code=code); extra['portClash'] = True
182
- else: message = 'The app returned HTTP '+str(code)+'. Check the startup log.' if code else ('Starting your app…' if running else ('Preview could not start. ' + work['error'] if work.get('state') == 'failed' and work.get('error') else 'No app is running on port 3000.'))
183
- return {'ready': ready, 'running': running or bool(work.get('alive')), 'httpStatus': code or None, 'message': message, 'log': log, **extra}
198
+ elif clash: message = PORT_CLASH.format(code=code, port=PORT); extra['portClash'] = True
199
+ else: message = 'The app returned HTTP '+str(code)+'. Check the startup log.' if code else ('Starting your app…' if running else ('Preview could not start. ' + work['error'] if work.get('state') == 'failed' and work.get('error') else 'No app is running on port %d.' % PORT))
200
+ if ready and owner.get('owner') == 'unknown': extra['notes'].append('Could not confirm that the server on port %d belongs to this project (its process and page gave no clear sign).' % PORT)
201
+ if owner.get('owner') in ('ours', 'workspace', 'unknown'): extra['owner'] = owner['owner']
202
+ return {'ready': ready, 'running': running or bool(work.get('alive')), 'httpStatus': code or None, 'port': PORT, 'url': base_url(), 'message': message, 'log': log, **extra}
203
+
204
+
205
+
206
+ # ---------------------------------------------------------------- which app answers on the preview port
207
+ # CLI 0.3.8 (Notes app): port 3000 was already serving another workspace's app ("Pixel Demo Shop"); preview called it
208
+ # ready and the browser checks passed against the wrong application. A port counts as this project's preview only when
209
+ # the listening socket belongs to the process tree preview started (or a server running from this workspace), with a
210
+ # content check (the page's title and asset paths match files here) when ownership cannot be read.
211
+ DEFAULT_PORT = 3000
212
+ PORT = DEFAULT_PORT
213
+ CTX = {} # repo and state of the preview this command manages (set by bind)
214
+
215
+
216
+ def base_url(port=None):
217
+ return 'http://127.0.0.1:%d' % (port or PORT)
218
+
219
+
220
+ def recorded_port(state):
221
+ try: port = int(json.loads((pathlib.Path(state) / 'preview-port.json').read_text()).get('port'))
222
+ except (OSError, ValueError, TypeError, AttributeError): return DEFAULT_PORT
223
+ return port if 1024 <= port <= 65535 else DEFAULT_PORT
224
+
225
+
226
+ def bind(repo, state):
227
+ """Use this workspace's preview port (3000 unless an earlier start moved it off a port another app holds)."""
228
+ global PORT
229
+ CTX['repo'], CTX['state'] = pathlib.Path(repo).resolve(), pathlib.Path(state)
230
+ PORT = recorded_port(state)
231
+ return PORT
232
+
233
+
234
+ def alternate_ports():
235
+ """Laptop runs can move the preview to another port; the cloud preview address is fixed to port 3000."""
236
+ if os.getenv('MINI_LAPTOP') == '1' or os.getenv('MINI_PREVIEW_ALT_PORTS') == '1': return True
237
+ try: return bool(json.loads((CTX['state'] / 'preview-port.json').read_text()).get('alternates'))
238
+ except (KeyError, OSError, ValueError, AttributeError): return False
239
+
240
+
241
+ def free_port(start, tries=200):
242
+ import socket
243
+ for port in range(start, min(start + tries, 65535)):
244
+ if listening(port): continue
245
+ with socket.socket() as sock:
246
+ try: sock.bind(('0.0.0.0', port))
247
+ except OSError: continue
248
+ return port
249
+ return None
184
250
 
185
251
 
252
+ def _run(cmd, timeout=5):
253
+ try:
254
+ flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
255
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL, creationflags=flags).stdout or ''
256
+ except (OSError, subprocess.SubprocessError): return ''
257
+
258
+
259
+ def listener_pids(port=None):
260
+ """PIDs listening on the port, or None when this computer does not say (permissions, missing tools)."""
261
+ port = port or PORT
262
+ if sys.platform.startswith('linux'):
263
+ if not pathlib.Path('/proc/net/tcp').exists(): return None
264
+ owners = port_owners(port)
265
+ return owners or None # a socket another user owns has no readable fd: unknown, not "nobody"
266
+ if sys.platform == 'darwin':
267
+ found = {int(line[1:]) for line in _run(['lsof', '-nP', '-iTCP:%d' % port, '-sTCP:LISTEN', '-Fp']).splitlines() if line[1:].isdigit() and line[:1] == 'p'}
268
+ return found or None
269
+ if sys.platform == 'win32':
270
+ found = set()
271
+ for line in _run(['netstat', '-ano', '-p', 'TCP']).splitlines() + _run(['netstat', '-ano', '-p', 'TCPv6']).splitlines():
272
+ parts = line.split()
273
+ # Listening rows have a remote address ending in :0 (the state word is localized, so it is not read).
274
+ if len(parts) >= 5 and parts[0].upper().startswith('TCP') and parts[1].rsplit(':', 1)[-1] == str(port) and parts[2].rsplit(':', 1)[-1] == '0' and parts[-1].isdigit():
275
+ found.add(int(parts[-1]))
276
+ return found or None
277
+ return None
278
+
279
+
280
+ def _win_processes():
281
+ import ctypes
282
+ from ctypes import wintypes
283
+ class Entry(ctypes.Structure):
284
+ _fields_ = [('dwSize', wintypes.DWORD), ('cntUsage', wintypes.DWORD), ('th32ProcessID', wintypes.DWORD), ('th32DefaultHeapID', ctypes.c_size_t),
285
+ ('th32ModuleID', wintypes.DWORD), ('cntThreads', wintypes.DWORD), ('th32ParentProcessID', wintypes.DWORD), ('pcPriClassBase', ctypes.c_long),
286
+ ('dwFlags', wintypes.DWORD), ('szExeFile', ctypes.c_char * 260)]
287
+ k = ctypes.WinDLL('kernel32', use_last_error=True)
288
+ k.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
289
+ snap = k.CreateToolhelp32Snapshot(2, 0)
290
+ out = {}
291
+ if not snap or snap == wintypes.HANDLE(-1).value: return out
292
+ try:
293
+ entry = Entry(); entry.dwSize = ctypes.sizeof(Entry)
294
+ ok = k.Process32First(snap, ctypes.byref(entry))
295
+ while ok:
296
+ out[int(entry.th32ProcessID)] = {'ppid': int(entry.th32ParentProcessID), 'name': entry.szExeFile.decode(errors='replace')}
297
+ ok = k.Process32Next(snap, ctypes.byref(entry))
298
+ finally: k.CloseHandle(snap)
299
+ return out
300
+
301
+
302
+ def processes():
303
+ """pid -> {ppid, name, group, session} for every visible process (best effort on each system)."""
304
+ out = {}
305
+ if sys.platform.startswith('linux'):
306
+ for proc in pathlib.Path('/proc').iterdir():
307
+ if not proc.name.isdigit(): continue
308
+ try:
309
+ raw = (proc / 'stat').read_text(); name = raw[raw.find('(') + 1:raw.rfind(')')]; fields = raw.rsplit(')', 1)[1].split()
310
+ out[int(proc.name)] = {'ppid': int(fields[1]), 'group': int(fields[2]), 'session': int(fields[3]), 'name': name}
311
+ except (OSError, ValueError, IndexError): continue
312
+ elif sys.platform == 'win32':
313
+ try: out = _win_processes()
314
+ except Exception: out = {}
315
+ else:
316
+ for line in _run(['ps', '-axo', 'pid=,ppid=,pgid=,comm=']).splitlines():
317
+ parts = line.split(None, 3)
318
+ if len(parts) >= 3 and all(p.isdigit() for p in parts[:3]):
319
+ out[int(parts[0])] = {'ppid': int(parts[1]), 'group': int(parts[2]), 'name': parts[3] if len(parts) > 3 else ''}
320
+ return out
186
321
 
187
- def port_owners(port=3000):
322
+
323
+ def process_tree(roots, table):
324
+ """The roots and everything they started (by parent, process group or session)."""
325
+ roots = {r for r in roots if r in table}
326
+ tree = set(roots); changed = True
327
+ while changed:
328
+ changed = False
329
+ for pid, info in table.items():
330
+ if pid not in tree and (info.get('ppid') in tree or info.get('group') in roots or info.get('session') in roots):
331
+ tree.add(pid); changed = True
332
+ return tree
333
+
334
+
335
+ def started_pids(state):
336
+ """The server preview started for this workspace (and its supervisor job), when still running."""
337
+ pids = set()
338
+ for name in ('preview-process.json', 'preview-build.json'):
339
+ try: meta = json.loads((pathlib.Path(state) / name).read_text())
340
+ except (OSError, ValueError): continue
341
+ pid = meta.get('pid')
342
+ if not isinstance(pid, int) or pid <= 1: continue
343
+ if sys.platform.startswith('linux') and meta.get('start') and identity(pid) != meta.get('start'): continue # the PID was reused
344
+ pids.add(pid)
345
+ return pids
346
+
347
+
348
+ def _preview_process(pid, repo):
349
+ """True when pid still is a preview process of this project (not a PID the system gave to something else since)."""
350
+ if sys.platform.startswith('linux'): return True # started_pids already compared the start time
351
+ command, cwd = process_command(pid), process_cwd(pid)
352
+ if cwd and inside(cwd, repo): return True
353
+ if command: return 'preview.py' in command or str(repo) in command
354
+ return not cwd and sys.platform == 'win32'
355
+
356
+
357
+ def stop_session(repo, state):
358
+ """BUG-0687: stop the preview servers this session started (and anything they started), when the CLI session that
359
+ started them ends. They used to keep running, orphaned, after mlai exited. Other apps are never touched."""
360
+ import signal, time
361
+ repo, state = pathlib.Path(repo).resolve(), pathlib.Path(state)
362
+ roots = {pid for pid in started_pids(state) if _preview_process(pid, repo)}
363
+ if not roots: return {'stopped': []}
364
+ table = processes()
365
+ tree = process_tree(roots, table) if table else set(roots)
366
+ for pid in sorted(tree | roots):
367
+ try: os.killpg(pid, signal.SIGTERM) if pid in roots and os.name != 'nt' else os.kill(pid, signal.SIGTERM)
368
+ except OSError:
369
+ try: os.kill(pid, signal.SIGTERM)
370
+ except OSError: pass
371
+ def alive(pid):
372
+ if sys.platform.startswith('linux'): return identity(pid) is not None
373
+ try: os.kill(pid, 0); return True
374
+ except OSError: return False
375
+ until = time.time() + 3
376
+ while time.time() < until and any(alive(p) for p in tree | roots): time.sleep(0.1)
377
+ for pid in tree | roots:
378
+ if alive(pid):
379
+ try: os.kill(pid, getattr(signal, 'SIGKILL', signal.SIGTERM))
380
+ except OSError: pass
381
+ (state / 'preview-process.json').unlink(missing_ok=True)
382
+ return {'stopped': sorted(roots), 'port': PORT}
383
+
384
+
385
+ def process_cwd(pid):
386
+ if sys.platform.startswith('linux'):
387
+ try: return os.readlink('/proc/%d/cwd' % pid)
388
+ except OSError: return None
389
+ if sys.platform == 'darwin':
390
+ for line in _run(['lsof', '-a', '-p', str(pid), '-d', 'cwd', '-Fn']).splitlines():
391
+ if line.startswith('n/'): return line[1:]
392
+ return None
393
+
394
+
395
+ def process_command(pid):
396
+ if sys.platform.startswith('linux'):
397
+ try: return pathlib.Path('/proc/%d/cmdline' % pid).read_bytes().replace(b'\0', b' ').decode(errors='replace').strip()
398
+ except OSError: return ''
399
+ if sys.platform == 'darwin': return _run(['ps', '-o', 'command=', '-p', str(pid)]).strip()
400
+ return ''
401
+
402
+
403
+ def inside(path, repo):
404
+ try: path = pathlib.Path(path).resolve()
405
+ except (OSError, ValueError): return False
406
+ return path == repo or repo in path.parents
407
+
408
+
409
+ TITLE = re.compile(r'<title[^>]*>(.*?)</title>', re.I | re.S)
410
+ ASSET = re.compile(r'''(?:src|href)\s*=\s*["']([^"'#?]+)''', re.I)
411
+ GENERATED = ('/_next/', '/@vite', '/@react-refresh', '/@fs/', '/@id/', '/node_modules/', '/__', '/static/js/', '/assets/')
412
+ TEXT_SUFFIX = {'.html', '.htm', '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.vue', '.svelte', '.astro', '.json', '.md', '.mdx', '.py', '.erb'}
413
+
414
+
415
+ def page(port, path='/'):
416
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
417
+ def redirect_request(self, *args, **kwargs): return None
418
+ try:
419
+ with urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()).open(base_url(port) + path, timeout=3) as response:
420
+ return response.read(300000).decode(errors='replace')
421
+ except urllib.error.HTTPError as error:
422
+ try: return error.read(300000).decode(errors='replace')
423
+ except OSError: return ''
424
+ except (OSError, urllib.error.URLError, ValueError): return ''
425
+
426
+
427
+ def workspace_text(repo, needle, limit=4000):
428
+ """True when the text appears in one of the workspace's source files (bounded scan)."""
429
+ seen = 0
430
+ for base, dirs, files in os.walk(repo):
431
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith('.')]
432
+ for name in files:
433
+ if pathlib.Path(name).suffix.lower() not in TEXT_SUFFIX: continue
434
+ seen += 1
435
+ if seen > limit: return False
436
+ try:
437
+ f = pathlib.Path(base, name)
438
+ if f.is_symlink() or f.stat().st_size > 300000: continue
439
+ if needle in f.read_text(errors='replace'): return True
440
+ except OSError: continue
441
+ return False
442
+
443
+
444
+ def content_match(port, repo):
445
+ """Does the served page come from this workspace? True / False, or None when the page gives nothing to compare."""
446
+ import html as htmllib
447
+ body = page(port)
448
+ if not body: return None
449
+ repo = pathlib.Path(repo).resolve()
450
+ title = TITLE.search(body)
451
+ title = ' '.join(htmllib.unescape(title.group(1)).split()) if title else ''
452
+ if title:
453
+ # The title must come from this workspace's files (index.html, a layout's metadata, a component).
454
+ for needle in (title, htmllib.escape(title, quote=False)):
455
+ if workspace_text(repo, needle): return True
456
+ parts = [p for p in re.split(r'\s*[|\u2013\u2014\u00b7:-]\s+', title) if len(p) >= 3]
457
+ if len(parts) > 1 and all(workspace_text(repo, p) for p in parts): return True # templated titles ("Page | Site")
458
+ return False
459
+ assets = []
460
+ for ref in ASSET.findall(body):
461
+ if ref.startswith(('http:', 'https:', '//', 'data:', 'mailto:', 'javascript:')) or ref.startswith(GENERATED): continue
462
+ assets.append(ref.lstrip('./').lstrip('/'))
463
+ assets = [a for a in assets if a][:40]
464
+ if not assets: return None
465
+ return any((repo / a).is_file() or (repo / 'public' / a).is_file() for a in assets)
466
+
467
+
468
+ def describe(pid, table=None):
469
+ info = (table or {}).get(pid) or {}
470
+ name = info.get('name') or (process_command(pid).split(' ')[0].rsplit('/', 1)[-1] if process_command(pid) else '')
471
+ cwd = process_cwd(pid)
472
+ return {'pid': pid, 'name': name or 'unknown process', **({'folder': cwd} if cwd else {})}
473
+
474
+
475
+ def server_owner(port=None, repo=None, state=None):
476
+ """Who serves the port: 'none', 'ours' (the process tree preview started), 'workspace' (a server running from
477
+ this workspace, such as one the agent started), 'foreign' (another app) or 'unknown'. Includes the processes."""
478
+ port = port or PORT
479
+ repo = pathlib.Path(repo).resolve() if repo else CTX.get('repo')
480
+ state = pathlib.Path(state) if state else CTX.get('state')
481
+ if not listening(port): return {'owner': 'none', 'port': port}
482
+ if repo is None: return {'owner': 'unknown', 'port': port, 'how': 'no workspace'}
483
+ pids = listener_pids(port)
484
+ if pids:
485
+ table = processes()
486
+ tree = process_tree(started_pids(state), table) if state else set()
487
+ if pids & tree: return {'owner': 'ours', 'port': port, 'pids': sorted(pids), 'how': 'process'}
488
+ known = 0
489
+ for pid in sorted(pids):
490
+ cwd = process_cwd(pid)
491
+ if (cwd and inside(cwd, repo)) or str(repo) in process_command(pid): return {'owner': 'workspace', 'port': port, 'pids': sorted(pids), 'how': 'folder'}
492
+ known += bool(cwd)
493
+ if known == len(pids):
494
+ return {'owner': 'foreign', 'port': port, 'pids': sorted(pids), 'how': 'folder', 'processes': [describe(p, table) for p in sorted(pids)][:3]}
495
+ processes_seen = [describe(p, table) for p in sorted(pids)][:3]
496
+ else: processes_seen = []
497
+ match = content_match(port, repo)
498
+ if match: return {'owner': 'workspace', 'port': port, 'how': 'content', **({'pids': sorted(pids)} if pids else {})}
499
+ if match is False: return {'owner': 'foreign', 'port': port, 'how': 'content', **({'pids': sorted(pids), 'processes': processes_seen} if pids else {}), 'title': (lambda m: ' '.join(m.group(1).split())[:120] if m else '')(TITLE.search(page(port)))}
500
+ return {'owner': 'unknown', 'port': port, 'how': 'none', **({'pids': sorted(pids)} if pids else {})}
501
+
502
+
503
+ def foreign_text(owner):
504
+ who = []
505
+ for p in owner.get('processes') or []:
506
+ who.append('%s (pid %s%s)' % (p.get('name') or 'process', p.get('pid'), ', folder ' + p['folder'] if p.get('folder') else ''))
507
+ title = owner.get('title')
508
+ return ('Port %d is already in use by %s, which is not this project%s.' % (owner['port'], ' and '.join(who) if who else 'another app', ' (its page is titled "' + title + '")' if title else ''))
509
+
510
+
511
+ def claim_port(state):
512
+ """Before starting a server: when another app holds the preview port, move to a free one (laptop runs) and record it.
513
+ Returns (owner record of the busy port or None, moved)."""
514
+ owner = server_owner()
515
+ if owner.get('owner') != 'foreign': return None, False
516
+ if not alternate_ports(): return owner, False
517
+ port = free_port(PORT + 1)
518
+ if not port: return owner, False
519
+ use_port(state, port, alternates=True)
520
+ return owner, True
521
+
522
+
523
+ def use_port(state, port, alternates=None):
524
+ global PORT
525
+ data = {'port': int(port)}
526
+ if alternates is not None: data['alternates'] = bool(alternates)
527
+ elif alternate_ports(): data['alternates'] = True
528
+ path = pathlib.Path(state) / 'preview-port.json'; tmp = path.with_suffix('.tmp'); tmp.write_text(json.dumps(data)); tmp.replace(path)
529
+ PORT = int(port)
530
+
531
+
532
+ def port_owners(port=None):
188
533
  """PIDs holding a listening socket on the port (read from /proc; no lsof/fuser needed)."""
189
- inodes = set()
534
+ port = port or PORT; inodes = set()
190
535
  for table in ('/proc/net/tcp', '/proc/net/tcp6'):
191
536
  try: lines = pathlib.Path(table).read_text().splitlines()[1:]
192
537
  except OSError: continue
@@ -194,6 +539,7 @@ def port_owners(port=3000):
194
539
  parts = line.split()
195
540
  if len(parts) > 9 and parts[3] == '0A' and int(parts[1].rsplit(':', 1)[1], 16) == port: inodes.add(parts[9])
196
541
  owners = set()
542
+ if not inodes: return owners
197
543
  for proc in pathlib.Path('/proc').iterdir():
198
544
  if not proc.name.isdigit(): continue
199
545
  try:
@@ -204,9 +550,13 @@ def port_owners(port=3000):
204
550
  return owners
205
551
 
206
552
 
207
- def stop_port(port=3000):
553
+ def stop_port(port=None):
554
+ """Stop this workspace's server on the port. Another app's server is never stopped (it is not ours to stop)."""
208
555
  import signal, time
209
- for pid in port_owners(port):
556
+ port = port or PORT
557
+ owners = port_owners(port)
558
+ if CTX.get('repo') and owners and server_owner(port).get('owner') not in ('ours', 'workspace'): return False
559
+ for pid in owners:
210
560
  try: os.killpg(os.getpgid(pid), signal.SIGTERM)
211
561
  except OSError:
212
562
  try: os.kill(pid, signal.SIGTERM)
@@ -260,7 +610,7 @@ NETWORK_ENV = ('HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_pro
260
610
  def preview_env():
261
611
  # Only what installs and servers need to reach the registry; never model keys, Vault secrets or registry tokens.
262
612
  env = {k: v for k, v in os.environ.items() if k in SAFE_ENV or k in NETWORK_ENV}
263
- env.update({'PORT': '3000', 'HOST': '0.0.0.0', 'BROWSER': 'none', '__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS': '.vercel.run', 'NEXT_TELEMETRY_DISABLED': '1', 'npm_config_update_notifier': 'false'})
613
+ env.update({'PORT': str(PORT), 'HOST': listen_host(), **({'MINI_PREVIEW_HOST': LOOPBACK} if listen_host() == LOOPBACK else {}), 'BROWSER': 'none', '__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS': '.vercel.run', 'NEXT_TELEMETRY_DISABLED': '1', 'npm_config_update_notifier': 'false'})
264
614
  return env
265
615
 
266
616
 
@@ -314,13 +664,13 @@ def prod_plan(repo):
314
664
  if selected['label'] == 'Next.js':
315
665
  direct = [str(bin_dir / 'next'), 'build']
316
666
  build = ['npm', 'run', 'build'] if NEXT_BUILD.fullmatch(script.strip()) else direct
317
- serve = me + [str(repo / 'out')] if static_export(repo) else [str(bin_dir / 'next'), 'start', '--hostname', '0.0.0.0', '--port', '3000']
667
+ serve = me[:-1] + ['--port', str(PORT), '--root', str(repo / 'out')] if static_export(repo) else [str(bin_dir / 'next'), 'start', '--hostname', listen_host(), '--port', str(PORT)]
318
668
  # Next.js 16+ builds into .next while dev uses .next/dev, so the dev preview keeps serving during the build.
319
669
  return {'label': 'Next.js', 'build': build, 'fallback': direct if build != direct else None, 'serve': serve, 'concurrent': next_major(repo) >= 16, 'artifact': 'out' if static_export(repo) else '.next/BUILD_ID'}
320
670
  direct = [str(bin_dir / 'vite'), 'build']
321
671
  build = ['npm', 'run', 'build'] if VITE_BUILD.fullmatch(script.strip()) else direct
322
672
  server = node_app_server(repo)
323
- serve = ['node', server] if server else [str(bin_dir / 'vite'), 'preview', '--host', '0.0.0.0', '--port', '3000', '--strictPort']
673
+ serve = ['node', server] if server else [str(bin_dir / 'vite'), 'preview', '--host', listen_host(), '--port', str(PORT), '--strictPort']
324
674
  return {'label': 'Vite', 'build': build, 'fallback': direct if build != direct else None, 'serve': serve, 'concurrent': True, 'artifact': 'dist/index.html'}
325
675
 
326
676
 
@@ -586,11 +936,11 @@ def wait_ready(seconds, proc=None):
586
936
  end = time.time() + seconds
587
937
  while time.time() < end:
588
938
  if proc is not None and proc.poll() is not None: return False
589
- if listening(3000):
939
+ if listening(PORT) and server_owner().get('owner') != 'foreign':
590
940
  try:
591
941
  class NoRedirect(urllib.request.HTTPRedirectHandler):
592
942
  def redirect_request(self, *args, **kwargs): return None
593
- with urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()).open('http://127.0.0.1:3000', timeout=20) as r: return r.status < 500
943
+ with urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()).open(base_url(), timeout=20) as r: return r.status < 500
594
944
  except urllib.error.HTTPError as error: return error.code < 500
595
945
  except (OSError, urllib.error.URLError): pass
596
946
  time.sleep(0.5)
@@ -608,9 +958,11 @@ def supervise(repo, state, mode):
608
958
  """Background preview job: packages, then the dev server, or a production build swapped in once it works."""
609
959
  import time
610
960
  repo, state = pathlib.Path(repo).resolve(), pathlib.Path(state)
961
+ bind(repo, state)
611
962
  with (state / 'preview-build.lock').open('a') as lock:
612
963
  try: lock_file(lock, blocking=False)
613
964
  except OSError: return {'skipped': 'another preview job is running'}
965
+ claim_port(state) # another app took the preview port: move off it (laptop) before starting anything
614
966
  env = preview_env(); build_log = state / 'preview-build.log'
615
967
  build_log.write_bytes(b'')
616
968
  data = read_package(repo)
@@ -623,7 +975,10 @@ def supervise(repo, state, mode):
623
975
  if mode == 'dev':
624
976
  selected = plan(repo)
625
977
  if not selected: set_job(state, state='failed', error=unsupported_reason(repo)); return {}
626
- if not listening(3000): start_server(selected['command'], selected['cwd'], state, env, 'dev')
978
+ claim_port(state); selected = plan(repo); env = preview_env()
979
+ if not listening(PORT): start_server(selected['command'], selected['cwd'], state, env, 'dev')
980
+ elif server_owner().get('owner') == 'foreign':
981
+ set_job(state, state='failed', step='Port busy', error=foreign_text(server_owner())); return {'error': 'port busy'}
627
982
  set_job(state, state='done', step='Development preview', seconds=round(time.time() - started, 1)); return {'mode': 'dev'}
628
983
  pp = prod_plan(repo)
629
984
  if not pp: set_job(state, state='failed', error=unsupported_reason(repo)); return {}
@@ -632,7 +987,7 @@ def supervise(repo, state, mode):
632
987
  dev = plan(repo); interim = None
633
988
  if not cached:
634
989
  if not pp['concurrent']: stop_port()
635
- elif not listening(3000) and dev and dev['label'] != 'Static website':
990
+ elif not listening(PORT) and dev and dev['label'] != 'Static website':
636
991
  # Show the dev preview right away while the production build runs (Next.js 16+ and Vite build into separate folders).
637
992
  if next_dev(repo): ensure_next_dev_origins(repo)
638
993
  interim = start_server(dev['command'], dev['cwd'], state, env, 'dev')
@@ -660,7 +1015,7 @@ def supervise(repo, state, mode):
660
1015
  set_job(state, state='failed', step='Production build failed', error=error, fixed=fixed, seconds=round(time.time() - started, 1))
661
1016
  # An older production server would show stale code; replace it with the dev server so the preview matches the files.
662
1017
  if serving_mode(state).get('mode') == 'prod' and not (state / 'run.lock').exists(): stop_port()
663
- if not listening(3000) and dev and not (state / 'run.lock').exists():
1018
+ if not listening(PORT) and dev and not (state / 'run.lock').exists():
664
1019
  if next_dev(repo): ensure_next_dev_origins(repo)
665
1020
  start_server(dev['command'], dev['cwd'], state, env, 'dev')
666
1021
  return {'error': error}
@@ -670,6 +1025,7 @@ def supervise(repo, state, mode):
670
1025
  if (state / 'run.lock').exists(): set_job(state, state='cancelled', step='The agent started a new task'); return {}
671
1026
  set_job(state, step='Switching to the production version')
672
1027
  stop_port()
1028
+ if claim_port(state)[1]: pp, dev, env = prod_plan(repo), plan(repo), preview_env()
673
1029
  proc = start_server(pp['serve'], repo, state, env, 'prod', fp)
674
1030
  if wait_ready(SERVE_WAIT, proc):
675
1031
  set_job(state, state='done', step='Production preview', seconds=round(time.time() - started, 1)); return {'mode': 'prod'}
@@ -705,8 +1061,17 @@ def launch(repo, state, confirmed=False, agent=False, mode=None):
705
1061
  mode = mode or ('dev' if agent else 'prod')
706
1062
  with (state / 'preview.lock').open('a') as lock:
707
1063
  lock_file(lock)
1064
+ bind(repo, state)
1065
+ if os.getenv('MINI_LAPTOP') == '1' and not (state / 'preview-port.json').exists(): use_port(state, PORT, alternates=True)
708
1066
  changed = ensure_next_dev_origins(repo) if next_dev(repo) else ''
709
1067
  current = status(state)
1068
+ busy_port = None
1069
+ if current.get('foreignServer'):
1070
+ busy_port, moved = claim_port(state)
1071
+ if not moved:
1072
+ return {**current, 'portBusy': True, 'running': False}
1073
+ current = status(state) # the new port is free
1074
+ current['movedFrom'] = busy_port['port']
710
1075
  # A confirmed start replaces a dev server that rejects the preview host (for example one started without allowedHosts / allowedDevOrigins).
711
1076
  if current.get('hostBlocked') and (agent or not (state / 'run.lock').exists()):
712
1077
  stop_port();current = status(state)
@@ -740,7 +1105,9 @@ def launch(repo, state, confirmed=False, agent=False, mode=None):
740
1105
  spawn(state, mode, repo.parent)
741
1106
  message = 'Installing packages and starting your app…' if mode == 'dev' else ('Preparing the production preview…' if not current['ready'] else current['message'])
742
1107
  building = mode == 'prod' and selected['label'] != 'Static website'
743
- return {'ready': bool(current['ready']) and building, 'running': True, 'building': building, 'message': message, 'log': '', **({'configChanged': changed} if changed else {}), **({'warning': current['warning']} if current.get('warning') else {})}
1108
+ if busy_port: message = foreign_text(busy_port) + ' The preview of this project runs on ' + base_url() + ' instead. ' + message
1109
+ return {'ready': bool(current['ready']) and building, 'running': True, 'building': building, 'message': message, 'log': '', 'port': PORT, 'url': base_url(),
1110
+ **({'foreignServer': busy_port, 'movedFrom': busy_port['port']} if busy_port else {}), **({'configChanged': changed} if changed else {}), **({'warning': current['warning']} if current.get('warning') else {})}
744
1111
 
745
1112
 
746
1113
  def agent_takeover(repo, state):
@@ -811,7 +1178,8 @@ def revive(repo, state):
811
1178
  try: meta = json.loads((state / 'preview-process.json').read_text())
812
1179
  except (OSError, ValueError): return done
813
1180
  if meta.get('pid') and identity(meta['pid']) == meta.get('start'): return done
814
- if listening(3000): return done
1181
+ bind(repo, state)
1182
+ if listening(PORT) and server_owner().get('owner') != 'foreign': return done
815
1183
  try: last = json.loads((state / 'preview-revive.json').read_text())
816
1184
  except (OSError, ValueError): last = {}
817
1185
  recent = [t for t in last.get('times', []) if time.time() - t < 600]
@@ -833,7 +1201,7 @@ def static_path_allowed(repo, request_path):
833
1201
  return candidate.resolve().is_relative_to(pathlib.Path(repo).resolve()) and not any(p.is_symlink() for p in [candidate, *candidate.parents] if p != pathlib.Path(repo).parent)
834
1202
 
835
1203
 
836
- def serve(repo):
1204
+ def serve(repo, port=None):
837
1205
  from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
838
1206
  class Handler(SimpleHTTPRequestHandler):
839
1207
  def __init__(self, *args, **kwargs): super().__init__(*args, directory=str(repo), **kwargs)
@@ -843,17 +1211,19 @@ def serve(repo):
843
1211
  return super().send_head()
844
1212
  def list_directory(self, path):
845
1213
  self.send_error(403);return None
846
- ThreadingHTTPServer(('0.0.0.0', 3000), Handler).serve_forever()
1214
+ ThreadingHTTPServer((listen_host(), int(port or os.getenv('PORT') or PORT)), Handler).serve_forever()
847
1215
 
848
1216
 
849
1217
  PATHS = {} # explicit repo/state (laptop runs keep the session state apart from the user's folder)
850
1218
 
851
1219
  def main():
852
- parser = argparse.ArgumentParser();parser.add_argument('action', choices=['status', 'start', 'serve', 'supervise', 'finalize']);parser.add_argument('--mode', choices=['dev', 'prod']);parser.add_argument('--root', default='/vercel/sandbox');parser.add_argument('--repo');parser.add_argument('--state');parser.add_argument('--confirmed', action='store_true');parser.add_argument('--agent', action='store_true');parser.add_argument('--revive', action='store_true');args = parser.parse_args()
1220
+ parser = argparse.ArgumentParser();parser.add_argument('action', choices=['status', 'start', 'serve', 'supervise', 'finalize', 'stop']);parser.add_argument('--mode', choices=['dev', 'prod']);parser.add_argument('--root', default='/vercel/sandbox');parser.add_argument('--repo');parser.add_argument('--state');parser.add_argument('--confirmed', action='store_true');parser.add_argument('--agent', action='store_true');parser.add_argument('--revive', action='store_true');parser.add_argument('--port', type=int);args = parser.parse_args()
853
1221
  root = pathlib.Path(args.root);state = pathlib.Path(args.state) if args.state else root / '.mini'
854
- if args.action == 'serve': return serve(root)
1222
+ if args.action == 'serve': return serve(root, args.port)
855
1223
  repo = pathlib.Path(args.repo) if args.repo else root / 'repo'
856
1224
  if args.repo: PATHS['repo'] = repo
1225
+ bind(repo, state)
1226
+ if args.action == 'stop': print(json.dumps(stop_session(repo, state))); return
857
1227
  if args.action in ('supervise', 'finalize'):
858
1228
  result = supervise(repo, state, args.mode or 'prod') if args.action == 'supervise' else finalize(repo, state)
859
1229
  print(json.dumps(result)); return