From e922124c561fe577bf8a7781652e22b1bf49859f Mon Sep 17 00:00:00 2001 From: Ayusharyan Sinha <130640449+Ayushsinha2004@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:54:12 +0530 Subject: [PATCH] fix(js-debug): read the child session so Node.js commands stop hanging js-debug is multi-session: the connection dap launches on is only a session manager, and the debuggee runs in a child session on a second connection. setupChildSession swapped d.client to the child but never started a reader on it, while readLoop stayed pinned to the parent. The child's StoppedEvent and TerminatedEvent therefore never reached expectCh, and every execution command (debug, step, continue) blocked forever. - readLoop takes its connection and channel explicitly; setupChildSession starts a second loop on the child connection with the same channel, so exactly one live loop closes it. - The parent keeps draining its socket after the hand-off (it only mirrors the child's terminated event) and declines a further startDebugging instead of leaving it unanswered. - Answer startDebugging on the loop's own connection instead of d.client, which may already point at the child. Adds TestReadLoop_ChildSessionHandoff, which drives the daemon against a fake multi-session adapter and needs no js-debug, so it runs in CI where the Node e2e tests skip. TestE2E_DebugNode timed out on master and now passes in ~3.5s. Adds TestE2E_DebugTypeScript (compiled JS + source map, breakpoint in the .ts source). Co-Authored-By: Claude Fable 5.1 --- daemon.go | 72 +++++++++++------ daemon_test.go | 141 ++++++++++++++++++++++++++++++++++ e2e_test.go | 60 +++++++++++++++ testdata/node/ts/greet.js | 7 ++ testdata/node/ts/greet.js.map | 7 ++ testdata/node/ts/greet.ts | 12 +++ 6 files changed, 276 insertions(+), 23 deletions(-) create mode 100644 testdata/node/ts/greet.js create mode 100644 testdata/node/ts/greet.js.map create mode 100644 testdata/node/ts/greet.ts diff --git a/daemon.go b/daemon.go index baddbe9..68ecaa4 100644 --- a/daemon.go +++ b/daemon.go @@ -258,12 +258,17 @@ func (d *Daemon) readExpected() (godap.Message, error) { // ├─ ExitedEvent ───────┤ // ├─ ResponseMessage ───┘ // └─ default ──► DROP (ProcessEvent, ThreadEvent, ModuleEvent, etc.) -func (d *Daemon) readLoop() { - defer close(d.expectCh) - // Pin the client for this loop's lifetime: stopSession() sets d.client = nil, - // which would race with d.client.ReadMessage() here and panic. The client's - // Close() will unblock ReadMessage() with an error and the loop returns. - client := d.getClient() +// +// The loop owns ch until it hands off to a child session (js-debug multi-session, +// see the startDebugging case); the client is pinned for the loop's lifetime +// because stopSession() sets d.client = nil, and Close() unblocks ReadMessage(). +func (d *Daemon) readLoop(client *DAPClient, ch chan godap.Message) { + handedOff := false + defer func() { + if !handedOff { + close(ch) + } + }() if client == nil { return } @@ -272,6 +277,17 @@ func (d *Daemon) readLoop() { if err != nil { return } + if handedOff { + // The child session owns the conversation and receives program output; + // the parent only mirrors the child's terminated event from here on. + // Keep draining so the adapter never blocks on a full send buffer, and + // decline further startDebugging requests rather than leave them unanswered. + if req, ok := msg.(*godap.StartDebuggingRequest); ok { + log.Printf("startDebugging: declined, a child session is already active") + _ = client.send(startDebuggingResponse(req, false)) + } + continue + } switch m := msg.(type) { case *godap.OutputEvent: if d.captureOutput { @@ -283,40 +299,48 @@ func (d *Daemon) readLoop() { } } case *godap.StoppedEvent, *godap.TerminatedEvent, *godap.InitializedEvent, *godap.ExitedEvent: - d.expectCh <- msg + ch <- msg case *godap.SetBreakpointsResponse: d.checkBreakpointWarnings(m) - d.expectCh <- msg + ch <- msg case godap.ResponseMessage: - d.expectCh <- msg + ch <- msg case *godap.StartDebuggingRequest: // Reverse request from js-debug to create a child debug session. // js-debug uses multi-session: parent = session manager, child = actual debuggee. // We respond with success, create a new connection for the child session, // do full init (initialize → launch → breakpoints → configDone), - // and swap d.client so readLoop continues on the child. - resp := &godap.StartDebuggingResponse{} - resp.Type = "response" - resp.Command = m.Command - resp.RequestSeq = m.Seq - resp.Seq = 0 - resp.Success = true - _ = d.client.send(resp) + // and hand d.client and ch to a read loop on the child connection. + _ = client.send(startDebuggingResponse(m, true)) if d.adapterAddr == "" { log.Printf("startDebugging: no adapter address for child session") continue } - if err := d.setupChildSession(m.Arguments.Configuration); err != nil { + if err := d.setupChildSession(m.Arguments.Configuration, ch); err != nil { log.Printf("startDebugging: %v", err) continue } + handedOff = true default: // Silently drop: ProcessEvent, ThreadEvent, ModuleEvent, ContinuedEvent, etc. } } } +// startDebuggingResponse acknowledges (or declines) js-debug's startDebugging reverse request. +func startDebuggingResponse(req *godap.StartDebuggingRequest, ok bool) *godap.StartDebuggingResponse { + resp := &godap.StartDebuggingResponse{} + resp.Type = "response" + resp.Command = req.Command + resp.RequestSeq = req.Seq + resp.Success = ok + if !ok { + resp.Message = "a child session is already active" + } + return resp +} + // waitForStopped waits for a StoppedEvent or TerminatedEvent, skipping responses and other events. // ExitedEvent → captures exit code, continues waiting for TerminatedEvent. // contextLines overrides the default source context window; 0 means use default. @@ -571,7 +595,7 @@ func (d *Daemon) handleDebug(rawArgs json.RawMessage) *Response { } d.setClient(client) d.expectCh = make(chan godap.Message, 64) - go d.readLoop() + go d.readLoop(client, d.expectCh) if err := d.initializeDAP(backend); err != nil { return errResponse(err.Error()) @@ -1326,7 +1350,7 @@ func (d *Daemon) startAdapter(backend Backend) error { } d.setClient(client) d.expectCh = make(chan godap.Message, 64) - go d.readLoop() + go d.readLoop(client, d.expectCh) return nil } @@ -1358,8 +1382,8 @@ func (d *Daemon) initializeDAP(backend Backend) error { // setupChildSession creates a child debug session for js-debug's multi-session architecture. // It connects a new DAP client, initializes it, sends launch + breakpoints + configDone, -// and swaps d.client so readLoop continues reading from the child session. -func (d *Daemon) setupChildSession(config map[string]any) error { +// then swaps d.client to the child and starts a read loop on it that takes over ch. +func (d *Daemon) setupChildSession(config map[string]any, ch chan godap.Message) error { childClient, err := newDAPClient(d.adapterAddr) if err != nil { return fmt.Errorf("connecting child session: %w", err) @@ -1418,8 +1442,10 @@ func (d *Daemon) setupChildSession(config map[string]any) error { log.Printf("child configuration done: %v", err) } - // Swap to child session — readLoop continues reading from child + // Without a loop of its own, the child's StoppedEvent/TerminatedEvent would + // never reach ch and every execution command would block forever. d.setClient(childClient) + go d.readLoop(childClient, ch) return nil } diff --git a/daemon_test.go b/daemon_test.go index a349289..ea7b409 100644 --- a/daemon_test.go +++ b/daemon_test.go @@ -1,12 +1,16 @@ package dap import ( + "bufio" "encoding/json" "fmt" + "net" "os/exec" "strings" "testing" "time" + + godap "github.com/google/go-dap" ) func TestOutputBufferBoundedAtWrite(t *testing.T) { @@ -492,3 +496,140 @@ func TestMergeBreakpoints(t *testing.T) { }) } } + +// serveChildSession plays the child side of a js-debug style adapter: it answers +// the daemon's handshake on conn and emits a StoppedEvent once configurationDone +// arrives. It returns when the connection closes. +func serveChildSession(conn net.Conn) { + r := bufio.NewReader(conn) + seq := 100 + next := func() int { seq++; return seq } + for { + msg, err := godap.ReadProtocolMessage(r) + if err != nil { + return + } + req, ok := msg.(godap.RequestMessage) + if !ok { + continue + } + cmd := req.GetRequest().Command + if cmd == "launch" { + _ = godap.WriteProtocolMessage(conn, &godap.InitializedEvent{ + Event: godap.Event{ProtocolMessage: godap.ProtocolMessage{Seq: next(), Type: "event"}, Event: "initialized"}, + }) + } + _ = godap.WriteProtocolMessage(conn, &godap.Response{ + ProtocolMessage: godap.ProtocolMessage{Seq: next(), Type: "response"}, + RequestSeq: req.GetRequest().Seq, + Success: true, + Command: cmd, + }) + if cmd == "configurationDone" { + _ = godap.WriteProtocolMessage(conn, &godap.StoppedEvent{ + Event: godap.Event{ProtocolMessage: godap.ProtocolMessage{Seq: next(), Type: "event"}, Event: "stopped"}, + Body: godap.StoppedEventBody{Reason: "breakpoint", ThreadId: 1}, + }) + } + } +} + +// TestReadLoop_ChildSessionHandoff mirrors js-debug's multi-session protocol with +// a fake adapter: the parent connection only asks for a child session through the +// startDebugging reverse request, and the debuggee's events arrive on a second +// connection. Without a reader on that child connection the StoppedEvent below +// never reaches the channel and every execution command hangs. Needs no js-debug. +func TestReadLoop_ChildSessionHandoff(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = ln.Close() }() + + d := &Daemon{backend: &jsDebugBackend{}, adapterAddr: ln.Addr().String()} + + parentAck := make(chan godap.Message, 1) + go func() { + parent, err := ln.Accept() + if err != nil { + return + } + defer func() { _ = parent.Close() }() + _ = godap.WriteProtocolMessage(parent, &godap.StartDebuggingRequest{ + Request: godap.Request{ProtocolMessage: godap.ProtocolMessage{Seq: 1, Type: "request"}, Command: "startDebugging"}, + Arguments: godap.StartDebuggingRequestArguments{ + Configuration: map[string]any{"type": "pwa-node", "name": "child"}, + Request: "launch", + }, + }) + // The acknowledgement must come back on the parent connection. + ack, err := godap.ReadProtocolMessage(bufio.NewReader(parent)) + if err != nil { + return + } + parentAck <- ack + + child, err := ln.Accept() + if err != nil { + return + } + defer func() { _ = child.Close() }() + serveChildSession(child) + }() + + parentClient, err := newDAPClient(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer parentClient.Close() + d.setClient(parentClient) + ch := make(chan godap.Message, 64) + go d.readLoop(parentClient, ch) + + deadline := time.After(5 * time.Second) + var stopped *godap.StoppedEvent + for stopped == nil { + select { + case msg, ok := <-ch: + if !ok { + t.Fatal("channel closed before the child's StoppedEvent arrived") + } + stopped, _ = msg.(*godap.StoppedEvent) + case <-deadline: + t.Fatal("the child session's StoppedEvent never reached the channel") + } + } + if stopped.Body.Reason != "breakpoint" { + t.Errorf("stopped reason = %q, want breakpoint", stopped.Body.Reason) + } + + select { + case ack := <-parentAck: + if _, ok := ack.(*godap.StartDebuggingResponse); !ok { + t.Errorf("parent connection received %T, want *godap.StartDebuggingResponse", ack) + } + case <-time.After(5 * time.Second): + t.Fatal("startDebugging was never acknowledged on the parent connection") + } + + child := d.getClient() + if child == parentClient { + t.Fatal("d.client still points at the parent session") + } + + // Ending both connections ends both loops; the channel must close exactly + // once (a second close would panic). + child.Close() + parentClient.Close() + deadline = time.After(5 * time.Second) + for { + select { + case _, ok := <-ch: + if !ok { + return + } + case <-deadline: + t.Fatal("channel was not closed after both connections ended") + } + } +} diff --git a/e2e_test.go b/e2e_test.go index 181b3d1..6901f60 100644 --- a/e2e_test.go +++ b/e2e_test.go @@ -1135,6 +1135,66 @@ func TestE2E_DebugNode(t *testing.T) { } } +// TestE2E_DebugTypeScript debugs compiled JavaScript and breaks on a line of the +// original .ts source, covering the common TypeScript workflow end to end. Like +// TestE2E_DebugNode, it depends on the daemon reading js-debug's child session. +// +// The breakpoint is added after --stop-on-entry because a sub-second script can +// finish before a launch-time .ts breakpoint binds. +// +// testdata/node/ts/greet.js(.map) is committed so the test needs no compiler. +// Regenerate with: esbuild greet.ts --outfile=greet.js --format=cjs --platform=node --sourcemap +func TestE2E_DebugTypeScript(t *testing.T) { + if FindJSDebugServer() == "" { + t.Skip("js-debug not found") + } + + env := newE2EEnv(t) + dir := filepath.Join(projectRoot(t), "testdata", "node", "ts") + program := filepath.Join(dir, "greet.js") + source := filepath.Join(dir, "greet.ts") + + out, err := env.run("debug", program, "--stop-on-entry") + if err != nil { + t.Fatalf("debug failed: %v\n%s", err, out) + } + if !strings.Contains(out, "greet.ts") { + t.Errorf("expected entry location mapped to greet.ts, got:\n%s", out) + } + + // greet.ts:8 is the return statement inside greet(); it compiles to greet.js:3. + if out, err = env.run("break", "add", source+":8"); err != nil { + t.Fatalf("break add failed: %v\n%s", err, out) + } + + out, err = env.run("continue") + if err != nil { + t.Fatalf("continue failed: %v\n%s", err, out) + } + if !strings.Contains(out, "Stopped: breakpoint") || !strings.Contains(out, "greet.ts:8") { + t.Fatalf("expected to stop at greet.ts:8, got:\n%s", out) + } + if !strings.Contains(out, "adult") { + t.Errorf("expected local label=adult, got:\n%s", out) + } + + out, err = env.run("continue") + if err != nil { + t.Fatalf("continue failed: %v\n%s", err, out) + } + if !strings.Contains(out, "terminated") { + t.Errorf("expected terminated, got:\n%s", out) + } + + out, err = env.run("stop") + if err != nil { + t.Fatalf("stop failed: %v\n%s", err, out) + } + if !strings.Contains(out, "OK") { + t.Errorf("expected OK, got:\n%s", out) + } +} + // --- Remote attach tests --- // TestE2E_RemoteAttach_Python tests attaching to a remote debugpy instance. diff --git a/testdata/node/ts/greet.js b/testdata/node/ts/greet.js new file mode 100644 index 0000000..bf2df8c --- /dev/null +++ b/testdata/node/ts/greet.js @@ -0,0 +1,7 @@ +function greet(p) { + const label = p.age >= 18 ? "adult" : "minor"; + return `Hello ${p.name} (${label})`; +} +const message = greet({ name: "Ada", age: 36 }); +console.log(message); +//# sourceMappingURL=greet.js.map diff --git a/testdata/node/ts/greet.js.map b/testdata/node/ts/greet.js.map new file mode 100644 index 0000000..3e341a7 --- /dev/null +++ b/testdata/node/ts/greet.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["greet.ts"], + "sourcesContent": ["interface Person {\n name: string;\n age: number;\n}\n\nfunction greet(p: Person): string {\n const label: string = p.age >= 18 ? \"adult\" : \"minor\";\n return `Hello ${p.name} (${label})`;\n}\n\nconst message: string = greet({ name: \"Ada\", age: 36 });\nconsole.log(message);\n"], + "mappings": "AAKA,SAAS,MAAM,GAAmB;AAChC,QAAM,QAAgB,EAAE,OAAO,KAAK,UAAU;AAC9C,SAAO,SAAS,EAAE,IAAI,KAAK,KAAK;AAClC;AAEA,MAAM,UAAkB,MAAM,EAAE,MAAM,OAAO,KAAK,GAAG,CAAC;AACtD,QAAQ,IAAI,OAAO;", + "names": [] +} diff --git a/testdata/node/ts/greet.ts b/testdata/node/ts/greet.ts new file mode 100644 index 0000000..31af9ba --- /dev/null +++ b/testdata/node/ts/greet.ts @@ -0,0 +1,12 @@ +interface Person { + name: string; + age: number; +} + +function greet(p: Person): string { + const label: string = p.age >= 18 ? "adult" : "minor"; + return `Hello ${p.name} (${label})`; +} + +const message: string = greet({ name: "Ada", age: 36 }); +console.log(message);