Elffuss BraidHub

utopia-ia/elffuss-code public

Bridge 1.1.2: a stop kills the whole command tree, and a stop right after exec is not lost

A stop (the agent's stop, Ctrl+C in the terminal, a timeout) killed only
the `sh -c` the bridge started. Whatever that shell had started kept
running: the node of an `npm run dev`, the second half of `a; b`, the
children of `npm install`, holding their ports while the web said
"stopped". Closing the socket killed nothing at all.

- Every command starts in its own process group (Setpgid). A stop sends
  SIGTERM to the group and SIGKILL after a short grace if anything is
  left. On Windows, taskkill /T /F on the cmd.exe tree.
- When a socket closes, every command of that session is stopped.
- Commands no longer share the bridge's process group, so a Ctrl+C in the
  bridge window would not reach them any more: on SIGINT, SIGTERM or
  SIGHUP the bridge stops every command, gives them the grace period,
  kills what is left and exits.
- A command is registered when its exec message is read, before its
  goroutine starts it. A stop that came in that gap found nothing and was
  dropped, while the client had already resolved with 130 and ignored the
  later exit, so the command ran to the end. A stop for a command that
  has not started yet now prevents the start (exit 130), one that lands
  during the start kills it as soon as it exists, and a stop for an id
  that has not arrived yet is remembered.

The five binaries in web/bridge-dl are rebuilt the same way as before
(CGO_ENABLED=0 go build -trimpath -ldflags='-s -w', same targets and
names); none carries a path from the build machine.

Tests: bridge/stop_unix_test.go (go test) covers the tree kill, a stop
right after exec in ten rounds, a stop before exec and a socket close.
All four fail against the 1.1.1 code. tests/bridge.mjs adds `node …;
echo`, `npm run dev` with a node script, twelve stops right behind their
exec, a socket close with a forked command and a Ctrl+C to the bridge,
all checked with `pgrep -f <marker>` (pgrep -P only sees direct children,
and an orphan stops being one). Against the shipped 1.1.1 binary four of
those checks fail.
Changeset6f1d4db0d43a3d49e6147798800bcb230683b4e3d651c882f878d6a778234feb
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 18:25 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-10 18:25 +02:00
Parentse78f1991eaff

Browse the files at this changeset

10 files changed

modified bridge/main.go +179 −17
@@ -28,15 +28,17 @@
2828 "net/http"
2929 "os"
3030 "os/exec"
31+ "os/signal"
3132 "path/filepath"
3233 "runtime"
3334 "strings"
3435 "sync"
36+ "time"
3537
3638 "github.com/gorilla/websocket"
3739 )
3840
39-const version = "1.1.1"
41+const version = "1.1.2"
4042
4143 // Tope de salida por comando: evita que un proceso que escupe sin fin inunde el
4244 // WebSocket (DoS de memoria). Al superarlo se corta y se avisa.
@@ -105,14 +107,27 @@
105107 }
106108
107109 type session struct {
108- conn *websocket.Conn
109- writeMu sync.Mutex
110- authed bool
111- root string // carpeta raíz permitida (absoluta), "" = sin restricción
112- procsMu sync.Mutex
113- procs map[string]*exec.Cmd
110+ conn *websocket.Conn
111+ writeMu sync.Mutex
112+ authed bool
113+ root string // carpeta raíz permitida (absoluta), "" = sin restricción
114+ procsMu sync.Mutex
115+ procs map[string]*job
116+ earlyStops map[string]bool // «stop» de un id que aún no había llegado
114117 }
115118
119+// Un comando de la sesión. Se apunta en cuanto llega el «exec», ANTES de
120+// arrancar el proceso: antes solo se apuntaba tras Start(), en su goroutine, y
121+// un «stop» que llegaba en ese hueco no encontraba nada y se perdía. El cliente
122+// ya había dado el comando por parado y el comando corría hasta el final.
123+type job struct {
124+ cmd *exec.Cmd // nil hasta que arranca
125+ stopped bool // se pidió pararlo (antes o después de arrancar)
126+}
127+
128+// Máximo de «stop» adelantados que se recuerdan; solo protege la memoria.
129+const maxEarlyStops = 256
130+
116131 func (s *session) send(m outMsg) {
117132 s.writeMu.Lock()
118133 defer s.writeMu.Unlock()
@@ -120,10 +135,14 @@
120135 }
121136
122137 func shellFor(cmdline string) *exec.Cmd {
138+ var c *exec.Cmd
123139 if runtime.GOOS == "windows" {
124- return exec.Command("cmd", "/C", cmdline)
140+ c = exec.Command("cmd", "/C", cmdline)
141+ } else {
142+ c = exec.Command("sh", "-c", cmdline)
125143 }
126- return exec.Command("sh", "-c", cmdline)
144+ prepareTree(c) // su propio grupo de procesos, para poder matar el árbol entero
145+ return c
127146 }
128147
129148 // resolveCwd valida el directorio de trabajo pedido contra la raíz permitida.
@@ -153,33 +172,81 @@
153172 return abs, ""
154173 }
155174
175+// Código de salida de un comando parado antes de arrancar: el mismo que da una
176+// shell con Ctrl+C (128 + SIGINT), el que el cliente ya usa para «parado».
177+const exitStopped = 130
178+
179+// reserve apunta el comando en cuanto llega su «exec», en el mismo bucle de
180+// lectura que luego procesa su «stop»: así un «stop» siempre lo encuentra.
181+func (s *session) reserve(id string) {
182+ s.procsMu.Lock()
183+ defer s.procsMu.Unlock()
184+ j := s.procs[id]
185+ if j == nil {
186+ j = &job{}
187+ s.procs[id] = j
188+ }
189+ if s.earlyStops[id] {
190+ j.stopped = true
191+ delete(s.earlyStops, id)
192+ }
193+}
194+
195+func (s *session) forget(id string) {
196+ s.procsMu.Lock()
197+ delete(s.procs, id)
198+ s.procsMu.Unlock()
199+}
200+
156201 func (s *session) runExec(m inMsg) {
157202 if strings.TrimSpace(m.Cmd) == "" {
203+ s.forget(m.ID)
158204 s.send(outMsg{Type: "error", ID: m.ID, Data: "comando vacío"})
159205 s.send(outMsg{Type: "exit", ID: m.ID, Code: -1})
160206 return
161207 }
162208 cwd, why := s.resolveCwd(strings.TrimSpace(m.Cwd))
163209 if why != "" {
210+ s.forget(m.ID)
164211 s.send(outMsg{Type: "error", ID: m.ID, Data: why})
165212 s.send(outMsg{Type: "exit", ID: m.ID, Code: -1})
166213 return
167214 }
215+ s.procsMu.Lock()
216+ j := s.procs[m.ID]
217+ if j == nil { // llamado sin reserve(): se apunta aquí
218+ j = &job{}
219+ s.procs[m.ID] = j
220+ }
221+ stoppedEarly := j.stopped
222+ s.procsMu.Unlock()
223+ if stoppedEarly {
224+ // Parado antes de arrancar: no se arranca.
225+ s.forget(m.ID)
226+ s.send(outMsg{Type: "exit", ID: m.ID, Code: exitStopped})
227+ return
228+ }
168229 c := shellFor(m.Cmd)
169230 c.Dir = cwd
170231 stdout, err1 := c.StdoutPipe()
171232 stderr, err2 := c.StderrPipe()
172233 if err1 != nil || err2 != nil {
234+ s.forget(m.ID)
173235 s.send(outMsg{Type: "error", ID: m.ID, Data: "no pude preparar el proceso"})
174236 return
175237 }
176238 if err := c.Start(); err != nil {
239+ s.forget(m.ID)
177240 s.send(outMsg{Type: "error", ID: m.ID, Data: "no pude arrancar: " + err.Error()})
178241 return
179242 }
180243 s.procsMu.Lock()
181- s.procs[m.ID] = c
244+ j.cmd = c
245+ stopNow := j.stopped // el «stop» llegó mientras arrancaba
182246 s.procsMu.Unlock()
247+ if stopNow {
248+ killTree(c)
249+ }
183250
184251 var sent int64
185252 var sentMu sync.Mutex
@@ -222,19 +289,102 @@
222289 code = -1
223290 }
224291 }
225- s.procsMu.Lock()
226- delete(s.procs, m.ID)
227- s.procsMu.Unlock()
292+ s.forget(m.ID)
228293 s.send(outMsg{Type: "exit", ID: m.ID, Code: code})
229294 }
230295
296+// stop mata el comando con TODO lo que haya lanzado. Antes mataba solo el
297+// «sh -c» que arranca el bridge: lo que ese sh hubiera lanzado (el node de un
298+// `npm run dev`, la segunda mitad de `a; b`, los hijos de `npm install`) seguía
299+// vivo, con su puerto, mientras la web lo daba por parado.
231300 func (s *session) stop(id string) {
232301 s.procsMu.Lock()
233- c := s.procs[id]
302+ j := s.procs[id]
303+ if j == nil {
304+ // Aún no había llegado su «exec»: se recuerda para cuando llegue.
305+ if len(s.earlyStops) < maxEarlyStops {
306+ s.earlyStops[id] = true
307+ }
308+ s.procsMu.Unlock()
309+ return
310+ }
311+ j.stopped = true
312+ c := j.cmd
234313 s.procsMu.Unlock()
235- if c != nil && c.Process != nil {
236- _ = c.Process.Kill()
314+ if c != nil {
315+ killTree(c)
316+ }
317+}
318+
319+// stopAll mata todo lo de la sesión: al cerrarse el socket ya no queda nadie
320+// para pararlo, y el cliente ya lo ha dado por terminado («[bridge
321+// desconectado]»). Antes seguía corriendo.
322+func (s *session) stopAll() {
323+ for _, c := range s.running(true) {
324+ killTree(c)
325+ }
326+}
327+
328+// running devuelve los procesos arrancados de la sesión (y los marca parados
329+// si se pide).
330+func (s *session) running(markStopped bool) []*exec.Cmd {
331+ s.procsMu.Lock()
332+ defer s.procsMu.Unlock()
333+ var cmds []*exec.Cmd
334+ for _, j := range s.procs {
335+ if markStopped {
336+ j.stopped = true
337+ }
338+ if j.cmd != nil {
339+ cmds = append(cmds, j.cmd)
340+ }
237341 }
342+ return cmds
343+}
344+
345+// Las sesiones abiertas, para pararlo todo cuando se cierra el bridge.
346+var (
347+ sessionsMu sync.Mutex
348+ sessions = map[*session]bool{}
349+)
350+
351+// stopOnShutdown: cada comando corre en su propio grupo de procesos, así que el
352+// Ctrl+C de la ventana del bridge ya no les llega (antes compartían el grupo
353+// del bridge y caían con él). Al recibir la señal de cierre el bridge para
354+// todos los comandos, les da el margen para terminar por las buenas, remata lo
355+// que quede y sale.
356+func stopOnShutdown() {
357+ sigs := make(chan os.Signal, 1)
358+ signal.Notify(sigs, shutdownSignals...)
359+ go func() {
360+ <-sigs
361+ sessionsMu.Lock()
362+ var all []*session
363+ for s := range sessions {
364+ all = append(all, s)
365+ }
366+ sessionsMu.Unlock()
367+ for _, s := range all {
368+ s.stopAll()
369+ }
370+ quedan := func() bool {
371+ for _, s := range all {
372+ if len(s.running(false)) > 0 {
373+ return true
374+ }
375+ }
376+ return false
377+ }
378+ for limite := time.Now().Add(killGrace); quedan() && time.Now().Before(limite); {
379+ time.Sleep(50 * time.Millisecond)
380+ }
381+ for _, s := range all {
382+ for _, c := range s.running(false) {
383+ forceKill(c)
384+ }
385+ }
386+ os.Exit(130)
387+ }()
238388 }
239389
240390 func serveWS(token, root string) http.HandlerFunc {
@@ -251,7 +401,16 @@
251401 return
252402 }
253403 defer conn.Close()
254- s := &session{conn: conn, procs: map[string]*exec.Cmd{}, root: root}
404+ s := &session{conn: conn, procs: map[string]*job{}, earlyStops: map[string]bool{}, root: root}
405+ sessionsMu.Lock()
406+ sessions[s] = true
407+ sessionsMu.Unlock()
408+ defer func() {
409+ s.stopAll()
410+ sessionsMu.Lock()
411+ delete(sessions, s)
412+ sessionsMu.Unlock()
413+ }()
255414 log.Println("nueva conexión desde", r.RemoteAddr, "origin:", r.Header.Get("Origin"))
256415 attempts := 0
257416 for {
@@ -277,6 +436,7 @@
277436 s.send(outMsg{Type: "error", ID: m.ID, Data: "no autenticado"})
278437 continue
279438 }
439+ s.reserve(m.ID)
280440 go s.runExec(m)
281441 case "stop":
282442 if s.authed {
@@ -331,6 +491,8 @@
331491 fmt.Println()
332492 fmt.Println(" Ctrl+C para parar. Deja esta ventana abierta mientras lo uses.")
333493
494+ stopOnShutdown()
495+
334496 mux := http.NewServeMux()
335497 mux.HandleFunc("/ws", serveWS(token, root))
336498 mux.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
added bridge/proc_unix.go +49 −0
@@ -0,0 +1,49 @@
1+//go:build !windows
2+
3+package main
4+
5+import (
6+ "os"
7+ "os/exec"
8+ "syscall"
9+ "time"
10+)
11+
12+// Señales con las que se cierra el bridge (Ctrl+C, kill, cerrar la ventana).
13+var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
14+
15+// Margen entre SIGTERM y SIGKILL: lo justo para que npm o un servidor de
16+// desarrollo terminen por las buenas.
17+const killGrace = 2 * time.Second
18+
19+// prepareTree arranca el comando en su propio grupo de procesos: todo lo que
20+// lance (el node de un `npm run dev`, cada parte de `a; b`) queda en ese grupo.
21+func prepareTree(c *exec.Cmd) {
22+ c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
23+}
24+
25+// killTree para el grupo entero: SIGTERM y, si alguno sigue vivo pasado el
26+// margen, SIGKILL.
27+func killTree(c *exec.Cmd) {
28+ if c.Process == nil {
29+ return
30+ }
31+ pgid := c.Process.Pid // con Setpgid el grupo lleva el pid del sh
32+ if err := syscall.Kill(-pgid, syscall.SIGTERM); err != nil {
33+ _ = c.Process.Kill()
34+ return
35+ }
36+ go func() {
37+ time.Sleep(killGrace)
38+ if syscall.Kill(-pgid, 0) == nil {
39+ _ = syscall.Kill(-pgid, syscall.SIGKILL)
40+ }
41+ }()
42+}
43+
44+// forceKill remata el grupo sin margen (al cerrar el bridge).
45+func forceKill(c *exec.Cmd) {
46+ if c.Process != nil {
47+ _ = syscall.Kill(-c.Process.Pid, syscall.SIGKILL)
48+ }
49+}
added bridge/proc_windows.go +33 −0
@@ -0,0 +1,33 @@
1+//go:build windows
2+
3+package main
4+
5+import (
6+ "os"
7+ "os/exec"
8+ "strconv"
9+ "time"
10+)
11+
12+// Señales con las que se cierra el bridge (Ctrl+C en su ventana).
13+var shutdownSignals = []os.Signal{os.Interrupt}
14+
15+// taskkill /F no espera a nadie: no hace falta margen.
16+const killGrace = 0 * time.Second
17+
18+func prepareTree(c *exec.Cmd) {}
19+
20+// forceKill: en Windows killTree ya es a la fuerza.
21+func forceKill(c *exec.Cmd) { killTree(c) }
22+
23+// killTree para el árbol entero: taskkill /T sigue a los hijos del cmd.exe que
24+// arranca el bridge (/F: sin esperar a que acepten). Si taskkill falla, al menos
25+// el cmd.exe.
26+func killTree(c *exec.Cmd) {
27+ if c.Process == nil {
28+ return
29+ }
30+ if err := exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(c.Process.Pid)).Run(); err != nil {
31+ _ = c.Process.Kill()
32+ }
33+}
added bridge/stop_unix_test.go +170 −0
@@ -0,0 +1,170 @@
1+//go:build !windows
2+
3+package main
4+
5+import (
6+ "bufio"
7+ "net/http"
8+ "net/http/httptest"
9+ "os"
10+ "path/filepath"
11+ "strconv"
12+ "strings"
13+ "syscall"
14+ "testing"
15+ "time"
16+
17+ "github.com/gorilla/websocket"
18+)
19+
20+// vivo: ¿existe todavía el proceso? (un zombi cuenta hasta que lo recogen)
21+func vivo(pid int) bool { return syscall.Kill(pid, 0) == nil }
22+
23+func esperaMuerto(t *testing.T, pid int) bool {
24+ t.Helper()
25+ for i := 0; i < 100; i++ {
26+ if !vivo(pid) {
27+ return true
28+ }
29+ time.Sleep(50 * time.Millisecond)
30+ }
31+ return false
32+}
33+
34+// Parar un comando mata también lo que el sh lanzó, no solo el sh.
35+func TestKillTreeKillsWhatTheShellStarted(t *testing.T) {
36+ c := shellFor("sleep 30 & echo $!; wait")
37+ out, err := c.StdoutPipe()
38+ if err != nil {
39+ t.Fatal(err)
40+ }
41+ if err := c.Start(); err != nil {
42+ t.Fatal(err)
43+ }
44+ line, err := bufio.NewReader(out).ReadString('\n')
45+ if err != nil {
46+ t.Fatal(err)
47+ }
48+ hijo, err := strconv.Atoi(strings.TrimSpace(line))
49+ if err != nil || !vivo(hijo) {
50+ t.Fatalf("no hay hijo vivo que parar: %q", line)
51+ }
52+ killTree(c)
53+ _ = c.Wait()
54+ if !esperaMuerto(t, hijo) {
55+ _ = syscall.Kill(hijo, syscall.SIGKILL)
56+ t.Fatalf("el hijo del sh (%d) sigue vivo tras parar", hijo)
57+ }
58+}
59+
60+const tokenPrueba = "token-de-prueba-del-bridge-0123456789"
61+
62+type cliente struct {
63+ t *testing.T
64+ conn *websocket.Conn
65+}
66+
67+func conecta(t *testing.T, root string) (*cliente, func()) {
68+ t.Helper()
69+ srv := httptest.NewServer(serveWS(tokenPrueba, root))
70+ url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws"
71+ conn, _, err := websocket.DefaultDialer.Dial(url, http.Header{"Origin": {"http://localhost:8799"}})
72+ if err != nil {
73+ srv.Close()
74+ t.Fatal(err)
75+ }
76+ cl := &cliente{t: t, conn: conn}
77+ cl.manda(inMsg{Type: "auth", Token: tokenPrueba})
78+ if m := cl.lee(); m.Type != "auth-ok" {
79+ t.Fatalf("sin auth-ok: %+v", m)
80+ }
81+ return cl, func() { conn.Close(); srv.Close() }
82+}
83+
84+func (c *cliente) manda(m inMsg) {
85+ if err := c.conn.WriteJSON(m); err != nil {
86+ c.t.Fatal(err)
87+ }
88+}
89+
90+func (c *cliente) lee() outMsg {
91+ c.t.Helper()
92+ var m outMsg
93+ _ = c.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
94+ if err := c.conn.ReadJSON(&m); err != nil {
95+ c.t.Fatal(err)
96+ }
97+ return m
98+}
99+
100+// lee hasta el «exit» de ese id
101+func (c *cliente) salida(id string) outMsg {
102+ c.t.Helper()
103+ for {
104+ m := c.lee()
105+ if m.ID == id && (m.Type == "exit" || m.Type == "error") {
106+ return m
107+ }
108+ }
109+}
110+
111+// Un «stop» que llega antes de que el proceso haya arrancado no se pierde: antes
112+// el bridge no encontraba el id y el comando corría hasta el final.
113+func TestStopRightAfterExecIsNotLost(t *testing.T) {
114+ root := t.TempDir()
115+ cl, cerrar := conecta(t, root)
116+ defer cerrar()
117+ for i := 0; i < 10; i++ {
118+ id := "pronto-" + strconv.Itoa(i)
119+ marca := filepath.Join(root, id)
120+ cl.manda(inMsg{Type: "exec", ID: id, Cmd: "sleep 1; touch '" + marca + "'"})
121+ cl.manda(inMsg{Type: "stop", ID: id})
122+ cl.salida(id)
123+ }
124+ time.Sleep(1500 * time.Millisecond)
125+ for i := 0; i < 10; i++ {
126+ if _, err := os.Stat(filepath.Join(root, "pronto-"+strconv.Itoa(i))); err == nil {
127+ t.Errorf("el comando %d se paró nada más mandarlo y aun así terminó", i)
128+ }
129+ }
130+}
131+
132+// Y un «stop» de un id que todavía no ha llegado se recuerda para cuando llegue.
133+func TestStopBeforeExecIsRemembered(t *testing.T) {
134+ root := t.TempDir()
135+ cl, cerrar := conecta(t, root)
136+ defer cerrar()
137+ marca := filepath.Join(root, "antes")
138+ cl.manda(inMsg{Type: "stop", ID: "x"})
139+ cl.manda(inMsg{Type: "exec", ID: "x", Cmd: "touch '" + marca + "'"})
140+ if m := cl.salida("x"); m.Type != "exit" || m.Code != exitStopped {
141+ t.Errorf("esperaba exit %d sin arrancar, llegó %+v", exitStopped, m)
142+ }
143+ time.Sleep(300 * time.Millisecond)
144+ if _, err := os.Stat(marca); err == nil {
145+ t.Error("el comando corrió aunque su «stop» llegó antes")
146+ }
147+}
148+
149+// Cerrar el socket con un comando en marcha mata el comando y lo que lanzó.
150+func TestSocketCloseKillsTheTree(t *testing.T) {
151+ root := t.TempDir()
152+ cl, cerrar := conecta(t, root)
153+ defer cerrar()
154+ cl.manda(inMsg{Type: "exec", ID: "largo", Cmd: "sleep 30 & echo $!; wait"})
155+ var hijo int
156+ for hijo == 0 {
157+ m := cl.lee()
158+ if m.ID == "largo" && m.Type == "stdout" {
159+ hijo, _ = strconv.Atoi(strings.TrimSpace(m.Data))
160+ }
161+ }
162+ if !vivo(hijo) {
163+ t.Fatalf("el hijo %d no llegó a estar vivo", hijo)
164+ }
165+ cl.conn.Close()
166+ if !esperaMuerto(t, hijo) {
167+ _ = syscall.Kill(hijo, syscall.SIGKILL)
168+ t.Fatalf("cerrar el socket dejó vivo el hijo %d", hijo)
169+ }
170+}
modified tests/bridge.mjs +89 −2
@@ -7,13 +7,16 @@
77 // y el proceso desaparece), cerrar el socket suelta los trabajos pendientes en
88 // vez de dejarlos colgados para siempre, Ctrl+C en el terminal corta el
99 // comando en curso, y parar a la elfa a mitad de un terminal.run mata el
10-// comando.
10+// comando. Lo que muere es el ÁRBOL: un `npm run dev`, un `a; b` o lo que siga
11+// corriendo al cerrar el socket. Se comprueba con `pgrep -f <marca>`, porque
12+// `pgrep -P` solo ve hijos directos del bridge y un huérfano deja de serlo. Y un
13+// «stop» que sale justo detrás del «exec» no se pierde.
1114 //
1215 // Necesita el puerto 8765 (el del bridge, fijo en bridge.js) y servir la web en
1316 // http://localhost:8799 (el único origen local que el bridge acepta).
1417 import { chromium } from 'playwright';
1518 import { spawn, execFileSync } from 'node:child_process';
16-import { mkdtempSync, realpathSync } from 'node:fs';
19+import { mkdtempSync, realpathSync, writeFileSync, existsSync } from 'node:fs';
1720 import { tmpdir } from 'node:os';
1821 import { join } from 'node:path';
1922 const BASE = process.env.BASE || 'http://localhost:8799';
@@ -106,6 +109,62 @@
106109 await esperar(500);
107110 ok(' …y el bridge mató el proceso (ya no es hijo suyo)', hijosDelBridge().length === 0, `${hijosDelBridge().length} hijos vivos`);
108111
112+ // 1b. Una cadena `a; b`: el sh lanza node y espera. Parar mata los dos (antes
113+ // solo el sh: node seguía vivo y el «; echo» no importaba).
114+ const MARK_CADENA = 'CADENA-' + Math.floor(Math.random() * 1e6);
115+ const r1b = await p.evaluate(async (mark) => {
116+ const br = await import('/js/bridge.js');
117+ const ac = new AbortController();
118+ let out = '';
119+ const prom = br.exec(`node -e "setTimeout(()=>{},30000)" ${mark}; echo despues-${mark}`, { signal: ac.signal, onOut: t => { out += t; } });
120+ await new Promise(r => setTimeout(r, 900));
121+ ac.abort();
122+ const code = await prom;
123+ await new Promise(r => setTimeout(r, 600));
124+ return { code, out };
125+ }, MARK_CADENA);
126+ await esperar(1500);
127+ ok('`node …; echo` parado: resuelve con 130', r1b.code === 130, String(r1b.code));
128+ ok(' …y node, que lanzó el sh, también muere', vivos(MARK_CADENA) === 0, `${vivos(MARK_CADENA)} procesos con la marca`);
129+ ok(' …y la segunda mitad de la cadena no llega a correr', !r1b.out.includes('despues-'), JSON.stringify(r1b.out));
130+
131+ // 1c. `npm run dev` (la línea exacta que arma shell.js) con un script que
132+ // lanza node: parar mata el node del script, no solo el npm.
133+ const MARK_NPM = 'NPMDEV-' + Math.floor(Math.random() * 1e6);
134+ writeFileSync(join(ROOT, 'package.json'), JSON.stringify({ name: 'parar-npm', version: '1.0.0', scripts: { dev: `node -e "setTimeout(()=>{},30000)" ${MARK_NPM}` } }));
135+ const r1c = p.evaluate(async () => {
136+ const br = await import('/js/bridge.js');
137+ window.__acNpm = new AbortController();
138+ return br.exec(`npm 'run' 'dev'`, { signal: window.__acNpm.signal });
139+ });
140+ let antesNpm = 0;
141+ for (let i = 0; i < 40 && !antesNpm; i++) { await esperar(250); antesNpm = vivos(MARK_NPM); }
142+ await p.evaluate(() => window.__acNpm.abort());
143+ const codeNpm = await r1c;
144+ await esperar(2500);
145+ ok('`npm run dev` corría de verdad (su node tenía la marca)', antesNpm >= 1, `${antesNpm} procesos con la marca`);
146+ ok(' …parado: resuelve con 130 y el node del script muere', codeNpm === 130 && vivos(MARK_NPM) === 0, `código ${codeNpm} · ${vivos(MARK_NPM)} procesos con la marca`);
147+
148+ // 1d. Un «stop» justo detrás del «exec» (en el mismo tick, o uno después):
149+ // antes el bridge aún no había apuntado el proceso, ignoraba el «stop» y el
150+ // comando corría entero aunque la web ya lo diera por parado.
151+ const r1d = await p.evaluate(async (root) => {
152+ const br = await import('/js/bridge.js');
153+ const codes = [];
154+ for (let i = 0; i < 12; i++) {
155+ const ac = new AbortController();
156+ const prom = br.exec(`sleep 1; touch '${root}/pronto-${i}'`, { signal: ac.signal });
157+ if (i % 2) await new Promise(r => setTimeout(r, 0)); // uno de cada dos, con un turno de por medio
158+ ac.abort();
159+ codes.push(await prom);
160+ }
161+ return codes;
162+ }, ROOT);
163+ await esperar(2000);
164+ const corrieron = Array.from({ length: 12 }, (_, i) => i).filter(i => existsSync(join(ROOT, `pronto-${i}`)));
165+ ok('«stop» justo detrás del «exec»: ninguno de los 12 comandos llega a terminar', r1d.every(c => c === 130) && corrieron.length === 0,
166+ `códigos ${[...new Set(r1d)].join(',')} · terminaron ${corrieron.length}`);
167+
109168 // 2. Cerrar el socket con un comando en marcha: el trabajo se resuelve (-1) y
110169 // se avisa, en vez de quedarse pendiente para siempre.
111170 const r2 = await p.evaluate(async () => {
@@ -119,6 +178,19 @@
119178 });
120179 ok('cerrar el socket suelta el trabajo pendiente (resuelve con -1)', r2.code === -1, String(r2.code));
121180 ok(' …y lo dice: «[bridge desconectado]»', /\[bridge desconectado\]/.test(r2.err), JSON.stringify(r2.err));
181+ // 2b. …y el bridge mata lo que corría por ese socket, con lo que haya lanzado.
182+ const reconecta2 = await p.evaluate(async (tok) => { const br = await import('/js/bridge.js'); try { await br.connect(tok); return br.isConnected(); } catch (e) { return e.message; } }, TOKEN);
183+ const MARK_SOCK = 'SOCKET-' + Math.floor(Math.random() * 1e6);
184+ const r2b = await p.evaluate(async (mark) => {
185+ const br = await import('/js/bridge.js');
186+ const prom = br.exec(`node -e "setTimeout(()=>{},30000)" ${mark}; true`);
187+ await new Promise(r => setTimeout(r, 900));
188+ br.disconnect();
189+ return prom;
190+ }, MARK_SOCK);
191+ await esperar(1500);
192+ ok('cerrar el socket mata el comando en marcha y lo que lanzó', reconecta2 === true && r2b === -1 && vivos(MARK_SOCK) === 0,
193+ `reconectado ${reconecta2} · código ${r2b} · ${vivos(MARK_SOCK)} procesos con la marca`);
122194 // reconectar para lo que sigue
123195 const reconecta = await p.evaluate(async (tok) => { const br = await import('/js/bridge.js'); try { await br.connect(tok); return br.isConnected(); } catch (e) { return e.message; } }, TOKEN);
124196 ok('se vuelve a conectar tras el corte', reconecta === true, String(reconecta));
@@ -172,6 +244,21 @@
172244 // origen NO permitido: el bridge debe rechazar conexiones de otro origen
173245 const originCheck = await fetch(`http://127.0.0.1:${PORT}/ping`, { headers: { Origin: 'https://evil.example' } }).then(r => r.status).catch(() => 'err');
174246 ok('el bridge RECHAZA orígenes no permitidos (seguridad)', originCheck === 403, `status ${originCheck}`);
247+
248+ // Cerrar el BRIDGE (Ctrl+C en su ventana) con un comando en marcha: cada
249+ // comando va en su propio grupo de procesos y la señal ya no le llega sola,
250+ // así que es el bridge el que los para antes de salir. Va al final: después
251+ // ya no hay bridge.
252+ const MARK_CIERRE = 'CIERRE-' + Math.floor(Math.random() * 1e6);
253+ await p.evaluate(async (mark) => { const br = await import('/js/bridge.js'); br.exec(`node -e "setTimeout(()=>{},30000)" ${mark}; true`); }, MARK_CIERRE);
254+ let antesCierre = 0;
255+ for (let i = 0; i < 20 && !antesCierre; i++) { await esperar(200); antesCierre = vivos(MARK_CIERRE); }
256+ const salio = new Promise(r => bp.once('exit', () => r(true)));
257+ process.kill(bp.pid, 'SIGINT'); // solo al bridge, como el Ctrl+C de su ventana
258+ const bridgeSalio = await Promise.race([salio, esperar(6000).then(() => false)]);
259+ await esperar(500);
260+ ok('Ctrl+C al bridge con un comando en marcha: el bridge sale y el comando muere',
261+ antesCierre >= 1 && bridgeSalio && vivos(MARK_CIERRE) === 0, `antes ${antesCierre} · salió ${bridgeSalio} · ${vivos(MARK_CIERRE)} procesos con la marca`);
175262 } finally {
176263 await b.close().catch(() => {});
177264 try { process.kill(-bp.pid, 'SIGTERM'); } catch { /* ya no estaba */ }
modified web/bridge-dl/elffuss-bridge-linux +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified web/bridge-dl/elffuss-bridge-linux-arm64 +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified web/bridge-dl/elffuss-bridge-mac-arm64 +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified web/bridge-dl/elffuss-bridge-mac-intel +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified web/bridge-dl/elffuss-bridge-windows.exe +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.