Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/pkg/tools/terminal.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,10 @@ func (t *terminal) ExecCommand(

if detach {
resultChan := make(chan execResult, 1)
detachedCtx := context.WithoutCancel(ctx)

go func() {
output, err := t.getExecResult(ctx, createResp.ID, timeout)
output, err := t.getExecResult(detachedCtx, createResp.ID, timeout)
Comment on lines 176 to +180
Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new detached execution behavior (using context.WithoutCancel) isn’t covered by tests. Since other tools in this package have unit tests, consider adding a terminal ExecCommand test that cancels the parent ctx and asserts the detached goroutine continues (e.g., via a mock dockerClient that would otherwise abort when ctx.Done() closes), while the command still stops on its own timeout.

Copilot uses AI. Check for mistakes.
Copy link
Contributor Author

@mason5052 mason5052 Mar 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid suggestion. However, writing a meaningful test for this requires mocking the Docker client (ContainerExecCreate, ContainerExecAttach, etc.) and verifying goroutine behavior under cancellation -- which is fairly involved and would require test infrastructure that does not exist yet in this package. For a 2-line bugfix that uses an idiomatic Go pattern (context.WithoutCancel), I think the current verification (manual code review + go vet + build) is proportionate. Happy to add tests in a follow-up PR if the maintainers prefer.

resultChan <- execResult{output: output, err: err}
}()

Expand Down
186 changes: 186 additions & 0 deletions backend/pkg/tools/terminal_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package tools

import (
"bufio"
"context"
"io"
"net"
"testing"
"time"

"pentagi/pkg/database"
"pentagi/pkg/docker"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/stretchr/testify/assert"
)

// contextTestTermLogProvider implements TermLogProvider for context tests.
type contextTestTermLogProvider struct{}

func (m *contextTestTermLogProvider) PutMsg(_ context.Context, _ database.TermlogType, _ string,
_ int64, _, _ *int64) (int64, error) {
return 1, nil
}

var _ TermLogProvider = (*contextTestTermLogProvider)(nil)

// contextAwareMockDockerClient tracks whether the context was canceled
// when getExecResult runs, proving context.WithoutCancel works.
type contextAwareMockDockerClient struct {
isRunning bool
execCreateResp container.ExecCreateResponse
attachOutput []byte
attachDelay time.Duration
inspectResp container.ExecInspect

// Set by ContainerExecAttach to track if ctx was canceled during attach
ctxWasCanceled bool
}

func (m *contextAwareMockDockerClient) SpawnContainer(_ context.Context, _ string, _ database.ContainerType,
_ int64, _ *container.Config, _ *container.HostConfig) (database.Container, error) {
return database.Container{}, nil
}
func (m *contextAwareMockDockerClient) StopContainer(_ context.Context, _ string, _ int64) error {
return nil
}
func (m *contextAwareMockDockerClient) DeleteContainer(_ context.Context, _ string, _ int64) error {
return nil
}
func (m *contextAwareMockDockerClient) IsContainerRunning(_ context.Context, _ string) (bool, error) {
return m.isRunning, nil
}
func (m *contextAwareMockDockerClient) ContainerExecCreate(_ context.Context, _ string, _ container.ExecOptions) (container.ExecCreateResponse, error) {
return m.execCreateResp, nil
}
func (m *contextAwareMockDockerClient) ContainerExecAttach(ctx context.Context, _ string, _ container.ExecAttachOptions) (types.HijackedResponse, error) {
// Wait for the configured delay, simulating a long-running command
if m.attachDelay > 0 {
select {
case <-time.After(m.attachDelay):
// Command completed normally
case <-ctx.Done():
// Context was canceled -- this is the bug behavior (without WithoutCancel)
m.ctxWasCanceled = true
return types.HijackedResponse{}, ctx.Err()
}
}

// Check if context was already canceled by the time we get here
select {
case <-ctx.Done():
m.ctxWasCanceled = true
return types.HijackedResponse{}, ctx.Err()
default:
}

pr, pw := net.Pipe()
go func() {
pw.Write(m.attachOutput)
pw.Close()
}()

return types.HijackedResponse{
Conn: pr,
Reader: bufio.NewReader(pr),
}, nil
}
func (m *contextAwareMockDockerClient) ContainerExecInspect(_ context.Context, _ string) (container.ExecInspect, error) {
return m.inspectResp, nil
}
func (m *contextAwareMockDockerClient) CopyToContainer(_ context.Context, _ string, _ string, _ io.Reader, _ container.CopyToContainerOptions) error {
return nil
}
func (m *contextAwareMockDockerClient) CopyFromContainer(_ context.Context, _ string, _ string) (io.ReadCloser, container.PathStat, error) {
return io.NopCloser(nil), container.PathStat{}, nil
}
func (m *contextAwareMockDockerClient) Cleanup(_ context.Context) error { return nil }
func (m *contextAwareMockDockerClient) GetDefaultImage() string { return "test-image" }

var _ docker.DockerClient = (*contextAwareMockDockerClient)(nil)

func TestExecCommandDetachSurvivesParentCancel(t *testing.T) {
// This test validates the fix for Issue #176:
// Detached commands must NOT be killed when the parent context is canceled.
//
// Before the fix: detached goroutine used parent ctx directly, so when the
// parent was canceled (e.g., agent delegation timeout), ctx.Done() fired
// in getExecResult and killed the background command.
//
// After the fix: context.WithoutCancel(ctx) creates an isolated context
// that preserves values but ignores parent cancellation.

mock := &contextAwareMockDockerClient{
isRunning: true,
execCreateResp: container.ExecCreateResponse{ID: "exec-cancel-test"},
attachOutput: []byte("background result"),
attachDelay: 2 * time.Second, // simulates a long-running command
inspectResp: container.ExecInspect{ExitCode: 0},
}

term := &terminal{
flowID: 1,
containerID: 1,
containerLID: "test-container",
dockerClient: mock,
tlp: &contextTestTermLogProvider{},
}

// Create a cancellable parent context
parentCtx, cancel := context.WithCancel(context.Background())

// Start ExecCommand with detach=true (returns quickly due to quick check timeout)
output, err := term.ExecCommand(parentCtx, "/work", "long-running-scan", true, 5*time.Minute)
assert.NoError(t, err)
assert.Contains(t, output, "Command started in background")

// Cancel the parent context -- simulating agent delegation timeout
cancel()

// Wait enough time for the detached goroutine to complete its work.
// If context.WithoutCancel is working correctly, the goroutine should
// NOT see ctx.Done() and should complete normally after attachDelay.
// If the fix regresses, ctxWasCanceled will be true.
time.Sleep(3 * time.Second)

assert.False(t, mock.ctxWasCanceled,
"detached goroutine should NOT see parent context cancellation (context.WithoutCancel must be used)")
}

func TestExecCommandNonDetachRespectsParentCancel(t *testing.T) {
// Counterpart: non-detached commands SHOULD respect parent cancellation.
// This ensures we didn't accidentally apply WithoutCancel to the non-detach path.

mock := &contextAwareMockDockerClient{
isRunning: true,
execCreateResp: container.ExecCreateResponse{ID: "exec-nondetach-cancel"},
attachOutput: []byte("should not complete"),
attachDelay: 5 * time.Second, // longer than cancel delay
inspectResp: container.ExecInspect{ExitCode: 0},
}

term := &terminal{
flowID: 1,
containerID: 1,
containerLID: "test-container",
dockerClient: mock,
tlp: &contextTestTermLogProvider{},
}

parentCtx, cancel := context.WithCancel(context.Background())

// Cancel after 200ms -- non-detached command should see this
go func() {
time.Sleep(200 * time.Millisecond)
cancel()
}()

_, err := term.ExecCommand(parentCtx, "/work", "long-command", false, 5*time.Minute)

// Non-detached command should fail with context error
assert.Error(t, err)
assert.True(t, mock.ctxWasCanceled,
"non-detached command SHOULD see parent context cancellation")
}