An open-source, faster Devin alternative
TypeScript
cancel source-side gRPC stream on release + suppress fake 0x03 exit marker when handler exits without a real process exit; ws-edge integration tests 05-08
Brian Reardon4f8c7a0f07aa
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex e5a2dc03..c4d4ee99 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -386,7 +386,7 @@ func main() {if qemuMgr != nil {qemuMgr.SetMigrationOutgoingCallback(func(sandboxID string) {ptyMgr.ReleaseForSandbox(sandboxID)- execMgr.RemoveSessions(sandboxID)+ execMgr.ReleaseForSandbox(sandboxID)})}@@ -974,6 +974,7 @@ func rebindExecSessionQEMU(agent *qm.AgentClient, sandboxID, sessionID string) (scrollback := sandbox.NewScrollbackBuffer(0)done := make(chan struct{})stdinR, stdinW := io.Pipe()+ streamCtx, cancel := context.WithCancel(context.Background())handle := &sandbox.ExecSessionHandle{ID: sessionID,@@ -987,6 +988,7 @@ func rebindExecSessionQEMU(agent *qm.AgentClient, sandboxID, sessionID string) (stdinW.Close()return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))},+ Cancel: cancel,}// Same goroutine shape as the create path — attach + send first message@@ -995,17 +997,17 @@ func rebindExecSessionQEMU(agent *qm.AgentClient, sandboxID, sessionID string) (// gone, causing consumeExecOutput to return immediately; the caller's// timeout on the WS upgrade will then fail. Acceptable for an edge case// where the user reconnects right as the exec process exits.- go runExecRebindQEMU(agent, sessionID, stdinR, done, scrollback, handle)+ go runExecRebindQEMU(streamCtx, agent, sessionID, stdinR, done, scrollback, handle)return handle, nil}// runExecRebindQEMU mirrors runExecStreamQEMU but binds to an existing// session_id instead of expecting Create to have just allocated it.-func runExecRebindQEMU(agent *qm.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {+func runExecRebindQEMU(ctx context.Context, agent *qm.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {defer close(done)defer stdinR.Close()- stream, err := agent.ExecSessionAttach(context.Background())+ stream, err := agent.ExecSessionAttach(ctx)if err != nil {return}@@ -1035,6 +1037,7 @@ func createExecSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.Exscrollback := sandbox.NewScrollbackBuffer(0)done := make(chan struct{})stdinR, stdinW := io.Pipe()+ streamCtx, cancel := context.WithCancel(context.Background())handle := &sandbox.ExecSessionHandle{ID: sessionID,@@ -1050,18 +1053,19 @@ func createExecSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.ExstdinW.Close()return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))},+ Cancel: cancel,}- go runExecStreamQEMU(agent, sessionID, stdinR, done, scrollback, handle)+ go runExecStreamQEMU(streamCtx, agent, sessionID, stdinR, done, scrollback, handle)return handle, nil}// runExecStreamQEMU attaches to an exec session stream (QEMU backend).-func runExecStreamQEMU(agent *qm.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {+func runExecStreamQEMU(ctx context.Context, agent *qm.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {defer close(done)defer stdinR.Close()- stream, err := agent.ExecSessionAttach(context.Background())+ stream, err := agent.ExecSessionAttach(ctx)if err != nil {return}diff --git a/internal/sandbox/exec_session.go b/internal/sandbox/exec_session.goindex 0958566e..ede19ff0 100644--- a/internal/sandbox/exec_session.go+++ b/internal/sandbox/exec_session.go@@ -34,6 +34,13 @@ type ExecSessionHandle struct {StdinWriter io.WriterOnKill func(signal int) error++ // Cancel terminates the gRPC ExecSessionAttach stream this handle is+ // driven by, without signaling the in-VM session to exit. Called by+ // ReleaseForSandbox on the source side of a live migration so the+ // worker's WS handler unblocks immediately and the edge DO sees an+ // upstream close (→ redial → destination rebind). Nil-safe.+ Cancel func()}// NewExecSessionManager creates a stub exec session manager (Podman — not supported).@@ -67,16 +74,14 @@ func (m *ExecSessionManager) RebindFromAgent(sandboxID, sessionID string) (*Execif m.rebindFunc == nil {return nil, fmt.Errorf("exec session %s not found", sessionID)}- // Drop stale local entry first — its gRPC stream targets the old worker.+ // Defensive: drop any stale local entry — after a normal migration the+ // source worker's onMigrationOutgoing hook has already released this+ // sandbox's sessions, so the map should be empty here. If it isn't, the+ // fresh handle we install below supersedes the stale one; we don't try+ // to actively reclaim the old gRPC stream because its context is owned+ // by a goroutine we don't have a handle to from here.m.mu.Lock()- if stale, ok := m.sessions[sessionID]; ok {- delete(m.sessions, sessionID)- if stale.OnKill != nil {- // Don't actually kill — just release local pipes. The agent owns- // the process and we want it to keep running.- _ = stale- }- }+ delete(m.sessions, sessionID)m.mu.Unlock()handle, err := m.rebindFunc(sandboxID, sessionID)@@ -181,3 +186,28 @@ func (m *ExecSessionManager) RemoveSessions(sandboxID string) {}}}++// ReleaseForSandbox drops every local exec session for sandboxID and cancels+// its gRPC ExecSessionAttach stream so the worker's WS handler — blocked on+// the scrollback subscription — unblocks via session.Done. Does NOT invoke+// OnKill (which would tell the in-VM agent to terminate the process); the+// session is alive on another worker post-migration.+//+// Counterpart to PTYManager.ReleaseForSandbox; same role for the source side+// of a live migration.+func (m *ExecSessionManager) ReleaseForSandbox(sandboxID string) {+ m.mu.Lock()+ var toRelease []*ExecSessionHandle+ for id, s := range m.sessions {+ if s.SandboxID == sandboxID {+ toRelease = append(toRelease, s)+ delete(m.sessions, id)+ }+ }+ m.mu.Unlock()+ for _, s := range toRelease {+ if s.Cancel != nil {+ s.Cancel()+ }+ }+}diff --git a/internal/worker/handlers.go b/internal/worker/handlers.goindex 0b379fc3..01d8d2e7 100644--- a/internal/worker/handlers.go+++ b/internal/worker/handlers.go@@ -236,14 +236,19 @@ func (s *HTTPServer) execSessionWebSocket(c echo.Context) error {}}sendExit:- exitMsg := make([]byte, 5)- exitMsg[0] = 0x03- exitCode := 0+ // Only emit the 0x03 exit-code marker when the process actually+ // exited (ExitCode is non-nil — consumeExecOutput only sets it on+ // an EXIT message from the agent). When the goroutine was canceled+ // for other reasons (e.g. source-side ReleaseForSandbox during+ // live migration), ExitCode stays nil and emitting a fake 0x03+ // would be misread by the edge DO as "exec completed" → close+ // client instead of redialing.if session.ExitCode != nil {- exitCode = *session.ExitCode+ exitMsg := make([]byte, 5)+ exitMsg[0] = 0x03+ binary.BigEndian.PutUint32(exitMsg[1:], uint32(int32(*session.ExitCode)))+ _ = ws.WriteMessage(websocket.BinaryMessage, exitMsg)}- binary.BigEndian.PutUint32(exitMsg[1:], uint32(int32(exitCode)))- _ = ws.WriteMessage(websocket.BinaryMessage, exitMsg)ws.WriteControl(websocket.CloseMessage,websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),diff --git a/scripts/integration-tests/05-ws-multi-client.py b/scripts/integration-tests/05-ws-multi-client.pynew file mode 100644index 00000000..566694a7--- /dev/null+++ b/scripts/integration-tests/05-ws-multi-client.py@@ -0,0 +1,71 @@+"""05 — Two concurrent WS sessions on the same sandbox stay independent.++Validates the multi-session refactor in sandbox_ws_gateway.ts (v7). Pre-fix,+the second WS upgrade to the same sandbox_id clobbered the first's+clientWs/upstreamWs singletons on the DO instance — the first connection+would silently stop receiving frames. Post-fix, each upgrade gets its own+Session in a Set and they bridge to independent upstreams.++Run with OPENCOMPUTER_API_URL + OPENCOMPUTER_API_KEY set in env.+"""+import asyncio+import sys+import time++import websockets++from _ws_common import create_sandbox, delete_sandbox, edge_client, open_pty+++def log(m: str) -> None:+ print(f"[05] {time.strftime('%H:%M:%S')} {m}", flush=True)+++async def main() -> int:+ async with edge_client() as c:+ sb = await create_sandbox(c)+ sid = sb["sandboxID"]+ log(f"sandbox={sid}")+ try:+ pid_a, ws_a = await open_pty(c, sid)+ pid_b, ws_b = await open_pty(c, sid)+ log(f"opened pty_a={pid_a} pty_b={pid_b}")++ sink_a, sink_b = bytearray(), bytearray()++ async def drain(ws, sink):+ while True:+ try:+ f = await asyncio.wait_for(ws.recv(), timeout=2.0)+ except asyncio.TimeoutError:+ continue+ except websockets.ConnectionClosed:+ return+ b = f if isinstance(f, bytes) else f.encode()+ if b:+ sink.extend(b)++ da = asyncio.create_task(drain(ws_a, sink_a))+ db = asyncio.create_task(drain(ws_b, sink_b))+ await asyncio.sleep(1.0)+ await ws_a.send("echo MARKER_FROM_A\n")+ await ws_b.send("echo MARKER_FROM_B\n")+ await asyncio.sleep(3.0)+ da.cancel(); db.cancel()+ await asyncio.gather(da, db, return_exceptions=True)+ await ws_a.close(); await ws_b.close()++ a_own = b"MARKER_FROM_A" in sink_a+ b_own = b"MARKER_FROM_B" in sink_b+ a_cross = b"MARKER_FROM_B" in sink_a+ b_cross = b"MARKER_FROM_A" in sink_b+ ok = a_own and b_own and not a_cross and not b_cross+ log(f"a_own={a_own} b_own={b_own} a_cross={a_cross} b_cross={b_cross}")+ log("PASS" if ok else "FAIL")+ return 0 if ok else 1+ finally:+ await delete_sandbox(c, sid)+++if __name__ == "__main__":+ sys.exit(asyncio.run(main()))diff --git a/scripts/integration-tests/06-ws-exec-exit-clean.py b/scripts/integration-tests/06-ws-exec-exit-clean.pynew file mode 100644index 00000000..9fd5c970--- /dev/null+++ b/scripts/integration-tests/06-ws-exec-exit-clean.py@@ -0,0 +1,63 @@+"""06 — Exec session that exits cleanly closes the client WS exactly once.++Validates the v6 exec-exit suppression in sandbox_ws_gateway.ts. Without it,+the DO would see the worker's clean 1000 close (sent on session.Done) as a+transient drop, redial, reattach to the now-completed session, re-receive+scrollback + exit byte + close 1000, redial again, etc. — an infinite loop+that previously emitted 4000+ scrollback_end markers per session.++Run with OPENCOMPUTER_API_URL + OPENCOMPUTER_API_KEY set in env.+"""+import asyncio+import sys+import time++import websockets++from _ws_common import create_sandbox, delete_sandbox, edge_client, open_exec+++def log(m: str) -> None:+ print(f"[06] {time.strftime('%H:%M:%S')} {m}", flush=True)+++async def main() -> int:+ async with edge_client() as c:+ sb = await create_sandbox(c)+ sid = sb["sandboxID"]+ log(f"sandbox={sid}")+ try:+ _, ws = await open_exec(c, sid, "for i in $(seq 1 5); do echo OUT_$i; sleep 0.3; done")+ scrollback_ends = 0+ exit_markers = 0+ close_code = close_reason = None+ try:+ while True:+ try:+ f = await asyncio.wait_for(ws.recv(), timeout=15.0)+ except asyncio.TimeoutError:+ log("FAIL — timeout, exec never closed cleanly")+ return 1+ b = f if isinstance(f, bytes) else f.encode()+ if len(b) == 1 and b[0] == 0x04:+ scrollback_ends += 1+ if len(b) == 5 and b[0] == 0x03:+ exit_markers += 1+ except websockets.ConnectionClosed as e:+ close_code = e.code; close_reason = e.reason++ log(f"close=({close_code}, {close_reason!r}) scrollback_ends={scrollback_ends} exit_markers={exit_markers}")+ ok = (+ close_code == 1000+ and (close_reason or "") == "exec completed"+ and scrollback_ends == 1+ and exit_markers == 1+ )+ log("PASS" if ok else "FAIL")+ return 0 if ok else 1+ finally:+ await delete_sandbox(c, sid)+++if __name__ == "__main__":+ sys.exit(asyncio.run(main()))diff --git a/scripts/integration-tests/07-ws-pty-survives-migration.py b/scripts/integration-tests/07-ws-pty-survives-migration.pynew file mode 100644index 00000000..9a52396d--- /dev/null+++ b/scripts/integration-tests/07-ws-pty-survives-migration.py@@ -0,0 +1,97 @@+"""07 — PTY session survives live worker migration with the WS held open.++Validates the lazy-rebind path: when the destination worker's local+ptyManager misses for an inbound WS, handlers.go falls back to+ptyManager.RebindFromAgent which opens a fresh agent.PTYAttach. The in-VM+bash + PTY are preserved across the migration (the agent owns them), so the+rebind succeeds and the user's terminal continues.++Source-side ReleaseForSandbox is also exercised: without it the source+worker's gRPC PTY stream would linger on a dead vsock and the edge DO+would never see the upstream close that triggers the redial.++Skips if the cluster has only one worker.++Run with OPENCOMPUTER_API_URL + OPENCOMPUTER_API_KEY set in env.+"""+import asyncio+import sys+import time++import websockets++from _ws_common import create_sandbox, delete_sandbox, edge_client, list_workers, open_pty+++def log(m: str) -> None:+ print(f"[07] {time.strftime('%H:%M:%S')} {m}", flush=True)+++async def main() -> int:+ async with edge_client() as c:+ sb = await create_sandbox(c)+ sid = sb["sandboxID"]+ src = sb["workerID"]+ workers = await list_workers(c)+ others = [w["worker_id"] for w in workers if w["worker_id"] != src]+ if not others:+ log("SKIP — only one worker in the cluster")+ await delete_sandbox(c, sid)+ return 0+ tgt = others[0]+ log(f"sandbox={sid} src={src} tgt={tgt}")+ try:+ _, ws = await open_pty(c, sid)+ sink = bytearray()+ closed: tuple | None = None++ async def reader():+ nonlocal closed+ while True:+ try:+ f = await asyncio.wait_for(ws.recv(), timeout=2.0)+ except asyncio.TimeoutError:+ continue+ except websockets.ConnectionClosed as e:+ closed = (e.code, e.reason)+ return+ b = f if isinstance(f, bytes) else f.encode()+ if b:+ sink.extend(b)++ rt = asyncio.create_task(reader())+ await ws.send("echo PRE_MIG && echo H > /tmp/x\n")+ await asyncio.sleep(2)+ r = await c.post(f"/api/sandboxes/{sid}/migrate", json={"targetWorker": tgt}, timeout=120)+ log(f"migrate {r.status_code} ms={r.json().get('elapsedMs')}")++ # Retry POST_MIG send for up to 30s — covers the DO redial window+ # during which client→upstream frames are dropped.+ deadline = time.time() + 30+ while time.time() < deadline:+ if b"POST_MIG" in sink: break+ if closed:+ log(f"FAIL — WS dropped during migration: {closed}")+ rt.cancel(); return 1+ try:+ await ws.send("cat /tmp/x && echo POST_MIG\n")+ except Exception:+ pass+ await asyncio.sleep(3)+ rt.cancel()+ try: await ws.close()+ except: pass++ pre = b"PRE_MIG" in sink+ post = b"POST_MIG" in sink+ file_ok = b"H\r" in sink or b"H\n" in sink+ log(f"pre={pre} post={post} file={file_ok} closed={closed}")+ ok = pre and post and file_ok and closed is None+ log("PASS" if ok else "FAIL")+ return 0 if ok else 1+ finally:+ await delete_sandbox(c, sid)+++if __name__ == "__main__":+ sys.exit(asyncio.run(main()))diff --git a/scripts/integration-tests/08-ws-exec-survives-migration.py b/scripts/integration-tests/08-ws-exec-survives-migration.pynew file mode 100644index 00000000..be0943fa--- /dev/null+++ b/scripts/integration-tests/08-ws-exec-survives-migration.py@@ -0,0 +1,97 @@+"""08 — Exec session survives live worker migration.++Same lazy-rebind path as 07, but for ExecSessionAttach. Requires the+matching pieces:+ - ExecSessionHandle.Cancel + ExecSessionManager.ReleaseForSandbox so the+ source worker's gRPC stream is canceled on outgoing migration (without+ this, the worker's exec WS handler stays blocked on the scrollback+ subscription and the DO never sees an upstream close).+ - handlers.go exec WS handler skips emitting the 0x03 exit marker when+ ExitCode is nil (without this, a cancel looks like a process exit to+ the edge DO and triggers "exec completed" close instead of redial).++Skips if the cluster has only one worker.++Run with OPENCOMPUTER_API_URL + OPENCOMPUTER_API_KEY set in env.+"""+import asyncio+import re+import sys+import time++import websockets++from _ws_common import create_sandbox, delete_sandbox, edge_client, list_workers, open_exec+++def log(m: str) -> None:+ print(f"[08] {time.strftime('%H:%M:%S')} {m}", flush=True)+++async def main() -> int:+ async with edge_client() as c:+ sb = await create_sandbox(c)+ sid = sb["sandboxID"]+ src = sb["workerID"]+ workers = await list_workers(c)+ others = [w["worker_id"] for w in workers if w["worker_id"] != src]+ if not others:+ log("SKIP — only one worker in the cluster")+ await delete_sandbox(c, sid)+ return 0+ tgt = others[0]+ log(f"sandbox={sid} src={src} tgt={tgt}")+ try:+ _, ws = await open_exec(c, sid, "for i in $(seq 1 30); do echo OUT_$i; sleep 1; done")+ seen: dict[int, int] = {}+ closed: tuple | None = None+ scrollback_ends = 0+ t0 = time.time()+ events: list[tuple[float, str]] = []++ async def reader():+ nonlocal closed, scrollback_ends+ while True:+ try:+ f = await asyncio.wait_for(ws.recv(), timeout=2.0)+ except asyncio.TimeoutError:+ continue+ except websockets.ConnectionClosed as e:+ closed = (e.code, e.reason)+ return+ b = f if isinstance(f, bytes) else f.encode()+ if not b: continue+ if len(b) == 1 and b[0] == 0x04:+ scrollback_ends += 1+ events.append((time.time() - t0, "scrollback_end"))+ continue+ payload = b[1:] if (len(b) >= 1 and b[0] in (0x01, 0x02)) else b+ for m in re.findall(rb"OUT_(\d+)", payload):+ n = int(m)+ if n not in seen:+ events.append((time.time() - t0, f"OUT_{n}"))+ seen[n] = seen.get(n, 0) + 1++ rt = asyncio.create_task(reader())+ await asyncio.sleep(5)+ r = await c.post(f"/api/sandboxes/{sid}/migrate", json={"targetWorker": tgt}, timeout=120)+ log(f"migrate {r.status_code} ms={r.json().get('elapsedMs')}")++ await asyncio.sleep(35) # let the 30s loop finish + headroom+ rt.cancel()+ try: await ws.close()+ except: pass++ log(f"unique OUT_ markers: {len(seen)}/30 scrollback_ends={scrollback_ends} close={closed}")+ pre_mig = any(t < 5.5 and ev.startswith("OUT_") for t, ev in events)+ post_mig = any(t > 7.0 and ev.startswith("OUT_") for t, ev in events)+ ok = pre_mig and post_mig and closed is not None and closed[0] == 1000+ log(f"pre_mig={pre_mig} post_mig={post_mig}")+ log("PASS" if ok else "FAIL")+ return 0 if ok else 1+ finally:+ await delete_sandbox(c, sid)+++if __name__ == "__main__":+ sys.exit(asyncio.run(main()))diff --git a/scripts/integration-tests/README.md b/scripts/integration-tests/README.mdindex 50e1bec1..0247edee 100644--- a/scripts/integration-tests/README.md+++ b/scripts/integration-tests/README.md@@ -1,20 +1,39 @@-# Integration tests for fork/hibernate/wake fixes+# Integration tests-One test per fix in PR #128. Each test is self-contained, creates its own-resources, cleans up in finally, and exits non-zero on regression.+Each test is self-contained, creates its own resources, cleans up in finally,+and exits non-zero on regression. 01-04 are TypeScript SDK tests for the+fork/hibernate/wake fixes in PR #128. 05-08 are Python tests for the+WS-via-DO + migration-survival work in PR #350 — they hit the edge directly+with httpx + websockets so they exercise the actual `/api/sandboxes/...`+edge routes (the SDK takes a different path for PTY/exec WS).-| # | Test file | Validates | Commit |-| - | ----------------------------------------- | ------------------------------------------------------------------------------------------- | ------- |-| 1 | `01-fork-sync-hibernate.ts` | `createFromCheckpoint` blocks until worker has the VM registered (no "sandbox not found") | 08d5320 |-| 2 | `02-fork-no-corruption.ts` | Forks from savevm-based checkpoints have correct workspace state (no EBADMSG / git segv) | 1caf148 + b2aa416 |-| 3 | `03-hibernate-wake-routing.ts` | Data-plane requests route to the current worker after wake (no "auto-wake failed") | f4e3600 |-| 4 | `04-hibernate-wake-data-preserved.ts` | Wake does not shadow `/home/sandbox` with an empty mount; all files are readable post-wake | 9f550e2 |+| # | Test file | Validates | PR |+| - | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ------ |+| 1 | `01-fork-sync-hibernate.ts` | `createFromCheckpoint` blocks until worker has the VM registered (no "sandbox not found") | #128 |+| 2 | `02-fork-no-corruption.ts` | Forks from savevm-based checkpoints have correct workspace state (no EBADMSG / git segv) | #128 |+| 3 | `03-hibernate-wake-routing.ts` | Data-plane requests route to the current worker after wake (no "auto-wake failed") | #128 |+| 4 | `04-hibernate-wake-data-preserved.ts` | Wake does not shadow `/home/sandbox` with an empty mount; all files are readable post-wake | #128 |+| 5 | `05-ws-multi-client.py` | Two concurrent PTYs on the same sandbox don't clobber each other (DO Session-set refactor) | #350 |+| 6 | `06-ws-exec-exit-clean.py` | An exec that exits cleanly closes the WS with `1000 'exec completed'` exactly once — no post-completion redial loop | #350 |+| 7 | `07-ws-pty-survives-migration.py` | Live worker migration with a PTY WS held open: client never closes, file written pre-mig is readable post-mig (lazy rebind) | #350 |+| 8 | `08-ws-exec-survives-migration.py` | Live migration of an exec session: output continues through the migration window, final close is the real `exec completed` | #350 |## Running+TypeScript:+```OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... \npx tsx scripts/integration-tests/01-fork-sync-hibernate.ts```-Each script exits 0 on success, 1 on any failure.+Python (requires `httpx` and `websockets`):++```+OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... \+ python3 scripts/integration-tests/05-ws-multi-client.py+```++Each script exits 0 on success, 1 on any failure. The Python tests share a+small `_ws_common.py` helper for env-var resolution and sandbox/session+setup; each test file stays focused on the assertion it's checking.diff --git a/scripts/integration-tests/_ws_common.py b/scripts/integration-tests/_ws_common.pynew file mode 100644index 00000000..561687bd--- /dev/null+++ b/scripts/integration-tests/_ws_common.py@@ -0,0 +1,88 @@+"""Shared helpers for the WS edge integration tests (05-08).++Reads OPENCOMPUTER_API_URL + OPENCOMPUTER_API_KEY from env. Exits 2 with a+useful message if either is missing so the tests don't surface NameErrors.+"""+from __future__ import annotations++import os+import sys+from contextlib import asynccontextmanager++import httpx+import websockets+++def _env(name: str) -> str:+ v = os.environ.get(name)+ if not v:+ print(+ f"missing required env var {name}; "+ "set OPENCOMPUTER_API_URL + OPENCOMPUTER_API_KEY (see scripts/integration-tests/README.md)",+ file=sys.stderr,+ )+ sys.exit(2)+ return v+++API_URL = _env("OPENCOMPUTER_API_URL").rstrip("/")+API_KEY = _env("OPENCOMPUTER_API_KEY")+WS_URL = API_URL.replace("https://", "wss://").replace("http://", "ws://")+++@asynccontextmanager+async def edge_client():+ """httpx client preconfigured against the edge with the API key."""+ headers = {"X-API-Key": API_KEY, "content-type": "application/json"}+ async with httpx.AsyncClient(base_url=API_URL, headers=headers, timeout=60.0) as c:+ yield c+++async def create_sandbox(client: httpx.AsyncClient, template: str = "base", timeout_s: int = 3600) -> dict:+ r = await client.post("/api/sandboxes", json={"templateID": template, "timeout": timeout_s})+ r.raise_for_status()+ return r.json()+++async def delete_sandbox(client: httpx.AsyncClient, sandbox_id: str) -> None:+ try:+ await client.delete(f"/api/sandboxes/{sandbox_id}")+ except Exception:+ # best-effort cleanup; test result has already been decided+ pass+++async def list_workers(client: httpx.AsyncClient) -> list[dict]:+ r = await client.get("/api/workers")+ r.raise_for_status()+ return r.json()+++async def open_pty(client: httpx.AsyncClient, sandbox_id: str, cols: int = 80, rows: int = 24):+ """POST /pty to create a session, then upgrade WS to /pty/{session_id}.+ Returns (session_id, websocket)."""+ pty = (await client.post(+ f"/api/sandboxes/{sandbox_id}/pty",+ json={"cols": cols, "rows": rows},+ )).json()+ sid = pty["sessionID"]+ ws = await websockets.connect(+ f"{WS_URL}/api/sandboxes/{sandbox_id}/pty/{sid}?api_key={API_KEY}",+ additional_headers={"X-API-Key": API_KEY},+ )+ return sid, ws+++async def open_exec(client: httpx.AsyncClient, sandbox_id: str, shell_cmd: str):+ """POST /exec to spawn `bash -lc <shell_cmd>`, then upgrade WS to+ /exec/{session_id}. Returns (session_id, websocket)."""+ es = (await client.post(+ f"/api/sandboxes/{sandbox_id}/exec",+ json={"cmd": "bash", "args": ["-lc", shell_cmd]},+ )).json()+ sid = es["sessionID"]+ ws = await websockets.connect(+ f"{WS_URL}/api/sandboxes/{sandbox_id}/exec/{sid}?api_key={API_KEY}",+ additional_headers={"X-API-Key": API_KEY},+ )+ return sid, ws