test: strengthen background shell output verification
This commit is contained in:
@@ -77,49 +77,81 @@ func main() {
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
if err := verifyShellReadback(ctx, endpoint, *exited); err != nil {
|
||||
shellReadbacks, err := verifyShellReadback(ctx, endpoint, *exited)
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
<-ctx.Done()
|
||||
shutdown, stop := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
pipelinesErr := pipelinesServer.Shutdown(shutdown)
|
||||
upstreamErr := upstreamServer.Shutdown(shutdown)
|
||||
stop()
|
||||
if pipelinesErr != nil {
|
||||
fatal(pipelinesErr)
|
||||
}
|
||||
if upstreamErr != nil {
|
||||
fatal(upstreamErr)
|
||||
}
|
||||
info := buildinfo.Current()
|
||||
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{
|
||||
"endpoint": endpoint, "upstream_endpoint": upstreamURL, "backend": attached.Connection.Backend,
|
||||
"revision": info.Commit, "session_id": server.LargeChatFixtureSessionID, "workspace": workspace,
|
||||
"newest_readback": readbacks[0], "older_readback": readbacks[1],
|
||||
"shell_readbacks": shellReadbacks, "clean_shutdown": true, "shutdown_exit_status": 0,
|
||||
})
|
||||
<-ctx.Done()
|
||||
shutdown, stop := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer stop()
|
||||
_ = pipelinesServer.Shutdown(shutdown)
|
||||
_ = upstreamServer.Shutdown(shutdown)
|
||||
}
|
||||
|
||||
func verifyShellReadback(ctx context.Context, endpoint string, exited bool) error {
|
||||
func verifyShellReadback(ctx context.Context, endpoint string, exited bool) (map[string]any, error) {
|
||||
evidence := map[string]any{"test_id": "fixture-shell-owned-and-foreign-refusal", "negative": []string{}}
|
||||
ws, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(endpoint, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
return evidence, err
|
||||
}
|
||||
defer ws.Close(websocket.StatusNormalClosure, "fixture complete")
|
||||
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatShells, ID: "fixture-shells", ChatQuery: &protocol.ChatQuery{SessionID: server.LargeChatFixtureSessionID}}); err != nil {
|
||||
return err
|
||||
return evidence, err
|
||||
}
|
||||
var listed protocol.Message
|
||||
if listed, err = readFixtureResponse(ctx, ws, protocol.ChatShells); err != nil {
|
||||
return err
|
||||
return evidence, err
|
||||
}
|
||||
if !exited && (len(listed.ChatShells) != 1 || listed.ChatShells[0].ID != server.LargeChatFixtureShellID) {
|
||||
return fmt.Errorf("fixture shell is not listed")
|
||||
return evidence, fmt.Errorf("fixture shell is not listed")
|
||||
}
|
||||
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "fixture-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: server.LargeChatFixtureSessionID, ShellID: server.LargeChatFixtureShellID, Limit: 64 << 10}}); err != nil {
|
||||
return err
|
||||
return evidence, err
|
||||
}
|
||||
page, err := readFixtureResponse(ctx, ws, protocol.ChatShellOutput)
|
||||
if err != nil {
|
||||
return err
|
||||
return evidence, err
|
||||
}
|
||||
if page.ChatShellOutput == nil || page.ChatShellOutput.Output != server.LargeChatFixtureShellOutput || page.ChatShellOutput.Shell.Status != map[bool]string{true: "exited", false: "running"}[exited] {
|
||||
return fmt.Errorf("unexpected shell readback: %+v", page.ChatShellOutput)
|
||||
return evidence, fmt.Errorf("unexpected shell readback: %+v", page.ChatShellOutput)
|
||||
}
|
||||
return nil
|
||||
evidence["owned"] = map[string]any{"shell_id": page.ChatShellOutput.Shell.ID, "output": page.ChatShellOutput.Output, "cursor": page.ChatShellOutput.Cursor, "status": page.ChatShellOutput.Shell.Status}
|
||||
negative := evidence["negative"].([]string)
|
||||
negativeRequests := []protocol.Message{
|
||||
{Type: protocol.ChatShells, ID: "foreign-list", ChatQuery: &protocol.ChatQuery{SessionID: server.LargeChatFixtureForeignSessionID}},
|
||||
{Type: protocol.ChatShells, ID: "unknown-list", ChatQuery: &protocol.ChatQuery{SessionID: "ses_unregistered_fixture"}},
|
||||
{Type: protocol.ChatShellOutput, ID: "foreign-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: server.LargeChatFixtureSessionID, ShellID: server.LargeChatFixtureForeignShellID, Limit: 64 << 10}},
|
||||
{Type: protocol.ChatShellOutput, ID: "unknown-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: "ses_unregistered_fixture", ShellID: server.LargeChatFixtureShellID, Limit: 64 << 10}},
|
||||
}
|
||||
for _, request := range negativeRequests {
|
||||
if err := wsjson.Write(ctx, ws, request); err != nil {
|
||||
return evidence, err
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, ws, &response); err != nil {
|
||||
return evidence, err
|
||||
}
|
||||
if response.Type != protocol.Error || strings.Contains(response.Error, server.LargeChatFixtureForeignShellOutput) {
|
||||
return evidence, fmt.Errorf("negative request %s leaked or succeeded: %+v", request.ID, response)
|
||||
}
|
||||
negative = append(negative, request.ID)
|
||||
}
|
||||
evidence["negative"] = negative
|
||||
evidence["negative_count"] = len(negative)
|
||||
return evidence, nil
|
||||
}
|
||||
|
||||
func verifyBroker(ctx context.Context, endpoint string) ([2]map[string]any, error) {
|
||||
|
||||
@@ -12,13 +12,29 @@ Stale shared documentation: the packaged OpenCode operational references under
|
||||
`internal/author/skill/references/` need a later docs-fold update describing the
|
||||
two additive websocket messages, 64 KiB maximum page, and current-only history.
|
||||
|
||||
Fixture evidence (2026-10-18): `go build -o /tmp/pipelines-large-chat-fixture-stage
|
||||
./cmd/pipelines-large-chat-fixture`; then `/tmp/pipelines-large-chat-fixture-stage
|
||||
-scratch-dir /var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/pipelines-shell-fixture-pxnc95h2
|
||||
-shell-exited`, stopped with SIGTERM. The foreground run exercised authenticated
|
||||
`chat_sessions`, three reconnecting history pages, `chat_shells`, and bounded
|
||||
`chat_shell_output` readback against scratch DB/workspace only, and exited 0 after
|
||||
clean shutdown. Recorded revision `fd4c329eafc46d1ce32dc9bc36fd9bd09b34e058`,
|
||||
session `ses_large_chat_fixture`, shell `sh_large_chat_fixture`, and fixed marker
|
||||
`fixture shell output marker\n`. The selected exited shell is read directly by id;
|
||||
the current list remains running-shell discovery.
|
||||
Fixture evidence (2026-10-18): `go build -o <scratch>/pipelines-large-chat-fixture
|
||||
./cmd/pipelines-large-chat-fixture`; then `<scratch>/pipelines-large-chat-fixture
|
||||
-scratch-dir <scratch>/run -shell-exited`, stopped with SIGTERM and awaited. The
|
||||
foreground run exercised authenticated `chat_sessions`, three reconnecting history
|
||||
pages, `chat_shells`, bounded `chat_shell_output`, and four executable negative
|
||||
readbacks (`foreign-list`, `unknown-list`, `foreign-output`, `unknown-output`) against
|
||||
scratch DB/workspace only. Its JSON contains `clean_shutdown: true` and
|
||||
`shutdown_exit_status: 0`, plus the selected exited shell's `exit: 0` readback.
|
||||
The evidence revision was `ded79277783b6ccdc25eb4ea25fe55d8632b89c7`; session
|
||||
`ses_large_chat_fixture`, shell `sh_large_chat_fixture`, and fixed marker
|
||||
`fixture shell output marker\n`. The current list remains running-shell discovery.
|
||||
|
||||
Integration coverage added: `TestChatShellOutputRejectsBoundsBeforeRegistryOrProvider`,
|
||||
`TestChatShellOutputRealHandlerWebsocketOwnedAndForeign`, and
|
||||
`TestChatShellOutputRealHandlerExitedReadback`,
|
||||
`TestChatShellOutputRealHandlerUnavailableAndReconnect`, and
|
||||
`TestChatShellOutputRejectsMalformedAndOversizedProviderPages`, and
|
||||
`TestChatShellOutputRealHandlerCancellationStopsProvider` in
|
||||
`internal/server/chat_shell_output_test.go`. Run with
|
||||
`go test ./internal/server -run 'TestChatShellOutput' -count=1 -v` and
|
||||
`go test -race ./internal/server -run 'TestChatShellOutput(RealHandler|RejectsBounds)' -count=1 -v`.
|
||||
These tests use an authenticated in-process HTTP provider, a scratch SQLite operator
|
||||
registry, and real `/connect` websocket traffic. The fixture executes foreign
|
||||
session/shell refusal requests and records positive/negative JSON readbacks under
|
||||
`shell_readbacks`; it remains scratch-only evidence, not evidence of a real provider,
|
||||
model, production workspace, or device.
|
||||
|
||||
@@ -33,6 +33,10 @@ type Chat struct {
|
||||
conn *Connection
|
||||
shellMu sync.Mutex
|
||||
shells map[string]*ChatStreamState
|
||||
// shellOwners retains ownership from the last authoritative global shell
|
||||
// listing so a shell known to belong to another session is rejected before
|
||||
// its detail or output endpoint is queried.
|
||||
shellOwners map[string]string
|
||||
// mu serializes the adapter's HTTP calls. Connection records its last
|
||||
// operation and status on the shared connection, so two calls must not
|
||||
// overlap; the permission poller runs alongside the read loop's
|
||||
@@ -405,6 +409,16 @@ func (c *Chat) Shells(ctx context.Context, sessionID string) ([]protocol.ChatShe
|
||||
return nil, fmt.Errorf("invalid OpenCode shell response")
|
||||
}
|
||||
}
|
||||
c.shellMu.Lock()
|
||||
if c.shellOwners == nil {
|
||||
c.shellOwners = make(map[string]string)
|
||||
}
|
||||
for _, info := range response.Data {
|
||||
if ValidShellID(info.ID) && ValidSessionID(info.shellSessionID()) {
|
||||
c.shellOwners[info.ID] = info.shellSessionID()
|
||||
}
|
||||
}
|
||||
c.shellMu.Unlock()
|
||||
out := make([]protocol.ChatShell, 0, len(response.Data))
|
||||
for _, info := range response.Data {
|
||||
if info.ID == "" || info.shellSessionID() != sessionID || (info.Status != "" && info.Status != protocol.ChatShellRunning && info.Status != protocol.ChatShellExited) {
|
||||
@@ -440,6 +454,12 @@ func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQu
|
||||
if !ValidSessionID(query.SessionID) || !ValidShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
|
||||
return protocol.ChatShellOutputPage{}, fmt.Errorf("invalid shell output query")
|
||||
}
|
||||
c.shellMu.Lock()
|
||||
owner := c.shellOwners[query.ShellID]
|
||||
c.shellMu.Unlock()
|
||||
if owner != "" && owner != query.SessionID {
|
||||
return protocol.ChatShellOutputPage{}, fmt.Errorf("shell is not available for this session")
|
||||
}
|
||||
data, err := c.call(ctx, "get", "/api/shell/"+query.ShellID, nil)
|
||||
if err != nil {
|
||||
if c.conn.LastHTTPStatus == 404 {
|
||||
|
||||
@@ -2,8 +2,18 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -45,3 +55,226 @@ func TestChatShellOutputRejectsBoundsBeforeRegistryOrProvider(t *testing.T) {
|
||||
t.Fatalf("invalid queries reached provider %d times", broker.outputCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatShellOutputRealHandlerWebsocketOwnedAndForeign drives the real
|
||||
// authenticated adapter, HTTP fixture, HandlerWithOptions, and /connect path.
|
||||
// The foreign detail deliberately has a marker that would be returned by its
|
||||
// output route; the session metadata check must reject it first.
|
||||
func TestChatShellOutputRealHandlerWebsocketOwnedAndForeign(t *testing.T) {
|
||||
testChatShellOutputOwnedAndForeign(t, false)
|
||||
}
|
||||
|
||||
func TestChatShellOutputRealHandlerExitedReadback(t *testing.T) {
|
||||
testChatShellOutputOwnedAndForeign(t, true)
|
||||
}
|
||||
|
||||
func testChatShellOutputOwnedAndForeign(t *testing.T, exited bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var providerRequests atomic.Int32
|
||||
fixtureHandler := LargeChatFixtureHandlerWithShell(t.TempDir(), exited)
|
||||
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
providerRequests.Add(1)
|
||||
fixtureHandler.ServeHTTP(w, r)
|
||||
}))
|
||||
defer fixture.Close()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, LargeChatFixtureSessionID, t.TempDir(), "owned", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{Chat: opencode.NewChat(attached.Connection), OperatorRegistry: store}))
|
||||
defer srv.Close()
|
||||
ws := dialShellOutputWebsocket(t, ctx, srv)
|
||||
defer ws.CloseNow()
|
||||
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShells, ID: "owned-shells", ChatQuery: &protocol.ChatQuery{SessionID: LargeChatFixtureSessionID}})
|
||||
owned := readShellOutputMessage(t, ctx, ws)
|
||||
if owned.Type != protocol.ChatShells || (exited && len(owned.ChatShells) != 0) || (!exited && (len(owned.ChatShells) != 1 || owned.ChatShells[0].ID != LargeChatFixtureShellID || owned.ChatShells[0].Status != protocol.ChatShellRunning)) {
|
||||
t.Fatalf("owned shell listing = %+v", owned)
|
||||
}
|
||||
wantStatus := protocol.ChatShellRunning
|
||||
if exited {
|
||||
wantStatus = protocol.ChatShellExited
|
||||
}
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "owned-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: LargeChatFixtureSessionID, ShellID: LargeChatFixtureShellID, Limit: protocol.ChatShellOutputLimit}})
|
||||
page := readShellOutputMessage(t, ctx, ws)
|
||||
if page.Type != protocol.ChatShellOutput || page.ChatShellOutput == nil || page.ChatShellOutput.Output != LargeChatFixtureShellOutput || page.ChatShellOutput.Cursor != int64(len(LargeChatFixtureShellOutput)) || page.ChatShellOutput.Shell.Status != wantStatus {
|
||||
t.Fatalf("owned output page = %+v", page)
|
||||
}
|
||||
if exited {
|
||||
if page.ChatShellOutput.Shell.Exit == nil || *page.ChatShellOutput.Shell.Exit != 0 {
|
||||
t.Fatalf("selected exited shell readback = %+v", page.ChatShellOutput.Shell)
|
||||
}
|
||||
} else if page.ChatShellOutput.Shell.Exit != nil {
|
||||
t.Fatalf("running shell unexpectedly has exit = %+v", page.ChatShellOutput.Shell.Exit)
|
||||
}
|
||||
if page.ChatShellOutput.Cursor != int64(len(page.ChatShellOutput.Output)) || page.ChatShellOutput.Size != page.ChatShellOutput.Cursor {
|
||||
t.Fatalf("non-deterministic output cursor/size = %+v", page.ChatShellOutput)
|
||||
}
|
||||
refusals := []struct {
|
||||
name string
|
||||
request protocol.Message
|
||||
}{
|
||||
{name: "foreign-output", request: protocol.Message{Type: protocol.ChatShellOutput, ID: "foreign-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: LargeChatFixtureSessionID, ShellID: LargeChatFixtureForeignShellID, Limit: protocol.ChatShellOutputLimit}}},
|
||||
{name: "foreign-list", request: protocol.Message{Type: protocol.ChatShells, ID: "foreign-list", ChatQuery: &protocol.ChatQuery{SessionID: LargeChatFixtureForeignSessionID}}},
|
||||
{name: "syntax-invalid-list", request: protocol.Message{Type: protocol.ChatShells, ID: "invalid-list", ChatQuery: &protocol.ChatQuery{SessionID: "ses_bad/invalid"}}},
|
||||
{name: "unknown-output", request: protocol.Message{Type: protocol.ChatShellOutput, ID: "unknown-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: "ses_unregistered_fixture", ShellID: LargeChatFixtureShellID, Limit: protocol.ChatShellOutputLimit}}},
|
||||
}
|
||||
for _, refusal := range refusals {
|
||||
beforeRefusal := providerRequests.Load()
|
||||
writeChat(t, ctx, ws, refusal.request)
|
||||
response := readShellOutputMessage(t, ctx, ws)
|
||||
if response.Type != protocol.Error || strings.Contains(response.Error, LargeChatFixtureForeignShellOutput) {
|
||||
t.Fatalf("%s response leaked or succeeded: %+v", refusal.name, response)
|
||||
}
|
||||
if got := providerRequests.Load(); got != beforeRefusal {
|
||||
t.Fatalf("%s reached provider: requests %d -> %d", refusal.name, beforeRefusal, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatShellOutputRealHandlerUnavailableAndReconnect(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
fixture := httptest.NewServer(LargeChatFixtureHandlerWithShell(t.TempDir(), false))
|
||||
defer fixture.Close()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, LargeChatFixtureSessionID, t.TempDir(), "owned", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{Chat: opencode.NewChat(attached.Connection), OperatorRegistry: store}))
|
||||
defer srv.Close()
|
||||
ws := dialShellOutputWebsocket(t, ctx, srv)
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "missing-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: LargeChatFixtureSessionID, ShellID: "sh_missing_fixture", Limit: 64}})
|
||||
missing := readShellOutputMessage(t, ctx, ws)
|
||||
if missing.Type != protocol.ChatShellOutput || missing.ChatShellOutput == nil || !missing.ChatShellOutput.Unavailable {
|
||||
t.Fatalf("404 shell output = %+v", missing)
|
||||
}
|
||||
ws = dialShellOutputWebsocket(t, ctx, srv)
|
||||
defer ws.CloseNow()
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShells, ID: "reconnect", ChatQuery: &protocol.ChatQuery{SessionID: LargeChatFixtureSessionID}})
|
||||
if got := readShellOutputMessage(t, ctx, ws); got.Type != protocol.ChatShells {
|
||||
t.Fatalf("reconnect shell listing = %+v", got)
|
||||
}
|
||||
if _, err := opencode.OpenEndpointAttached(ctx, fixture.URL, "wrong-password", "", ""); err == nil {
|
||||
t.Fatal("wrong provider authentication unexpectedly succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatShellOutputRejectsMalformedAndOversizedProviderPages(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
output string
|
||||
}{
|
||||
{name: "malformed", output: `{"data":{"output":"x"}}`},
|
||||
{name: "oversized", output: fmt.Sprintf(`{"data":{"output":%q,"cursor":%d,"size":%d,"truncated":false}}`, strings.Repeat("x", protocol.ChatShellOutputLimit+1), protocol.ChatShellOutputLimit+1, protocol.ChatShellOutputLimit+1)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/info":
|
||||
_, _ = w.Write([]byte(`{"version":"fixture","urls":[]}`))
|
||||
case "/api/event":
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
case "/api/shell/sh_malformed_fixture":
|
||||
_, _ = w.Write([]byte(`{"data":{"id":"sh_malformed_fixture","status":"running","metadata":{"sessionID":"ses_malformed_fixture"}}}`))
|
||||
case "/api/shell/sh_malformed_fixture/output":
|
||||
_, _ = w.Write([]byte(tc.output))
|
||||
default:
|
||||
if r.URL.Path == "/api/shell" {
|
||||
_, _ = w.Write([]byte(`{"data":[]}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer fixture.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = opencode.NewChat(attached.Connection).ShellOutput(ctx, protocol.ChatShellOutputQuery{SessionID: "ses_malformed_fixture", ShellID: "sh_malformed_fixture", Limit: protocol.ChatShellOutputLimit})
|
||||
if err == nil {
|
||||
t.Fatalf("%s provider page was accepted", tc.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatShellOutputRealHandlerCancellationStopsProvider(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
started := make(chan struct{})
|
||||
canceled := make(chan struct{})
|
||||
fixtureHandler := LargeChatFixtureHandlerWithShell(t.TempDir(), false)
|
||||
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/shell/sh_cancel_fixture" {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
close(canceled)
|
||||
return
|
||||
}
|
||||
fixtureHandler.ServeHTTP(w, r)
|
||||
}))
|
||||
defer fixture.Close()
|
||||
attached, err := opencode.OpenEndpointAttached(ctx, fixture.URL, LargeChatFixturePassword, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, "ses_cancel_fixture", t.TempDir(), "cancel", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
serverCtx, serverCancel := context.WithCancel(ctx)
|
||||
defer serverCancel()
|
||||
srv := httptest.NewServer(HandlerWithOptions(serverCtx, Options{Chat: opencode.NewChat(attached.Connection), OperatorRegistry: store}))
|
||||
defer srv.Close()
|
||||
ws := dialShellOutputWebsocket(t, ctx, srv)
|
||||
writeChat(t, ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "cancel-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: "ses_cancel_fixture", ShellID: "sh_cancel_fixture", Limit: 64}})
|
||||
select {
|
||||
case <-started:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("provider detail request did not start")
|
||||
}
|
||||
serverCancel()
|
||||
select {
|
||||
case <-canceled:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("canceling handler did not cancel provider request")
|
||||
}
|
||||
}
|
||||
|
||||
func dialShellOutputWebsocket(t *testing.T, ctx context.Context, srv *httptest.Server) *websocket.Conn {
|
||||
t.Helper()
|
||||
ws, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
func readShellOutputMessage(t *testing.T, ctx context.Context, ws *websocket.Conn) protocol.Message {
|
||||
t.Helper()
|
||||
var message protocol.Message
|
||||
if err := wsjson.Read(ctx, ws, &message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ const LargeChatFixtureSessionID = "ses_large_chat_fixture"
|
||||
const LargeChatFixturePassword = "large-chat-fixture"
|
||||
const LargeChatFixtureShellID = "sh_large_chat_fixture"
|
||||
const LargeChatFixtureShellOutput = "fixture shell output marker\n"
|
||||
const LargeChatFixtureForeignSessionID = "ses_foreign_fixture"
|
||||
const LargeChatFixtureForeignShellID = "sh_foreign_fixture"
|
||||
const LargeChatFixtureForeignShellOutput = "FOREIGN SHELL MARKER MUST NOT LEAK\n"
|
||||
|
||||
const (
|
||||
LargeChatFixtureNewestAnswer = "Controlled newest answer: large history fixture"
|
||||
@@ -80,7 +83,7 @@ func LargeChatFixtureHandlerWithShell(workspace string, exited bool) http.Handle
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":[{"id":%q,"status":%q,"command":"printf fixture","metadata":{"sessionID":%q}}]}`, LargeChatFixtureShellID, status, LargeChatFixtureSessionID))
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":[{"id":%q,"status":%q,"command":"printf fixture","metadata":{"sessionID":%q}},{"id":%q,"status":"running","command":"printf foreign","metadata":{"sessionID":%q}}]}`, LargeChatFixtureShellID, status, LargeChatFixtureSessionID, LargeChatFixtureForeignShellID, LargeChatFixtureForeignSessionID))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureShellID, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
@@ -92,6 +95,12 @@ func LargeChatFixtureHandlerWithShell(workspace string, exited bool) http.Handle
|
||||
}
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"id":%q,"status":%q,"command":"printf fixture","exit":%s,"metadata":{"sessionID":%q}}}`, LargeChatFixtureShellID, status, exit, LargeChatFixtureSessionID))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureForeignShellID, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"id":%q,"status":"running","command":"printf foreign","metadata":{"sessionID":%q}}}`, LargeChatFixtureForeignShellID, LargeChatFixtureForeignSessionID))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureShellID+"/output", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
@@ -99,6 +108,13 @@ func LargeChatFixtureHandlerWithShell(workspace string, exited bool) http.Handle
|
||||
cursor := int64(len(LargeChatFixtureShellOutput))
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"output":%q,"cursor":%d,"size":%d,"truncated":false}}`, LargeChatFixtureShellOutput, cursor, cursor))
|
||||
})
|
||||
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureForeignShellID+"/output", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !largeChatFixtureAuthenticated(w, r) {
|
||||
return
|
||||
}
|
||||
cursor := int64(len(LargeChatFixtureForeignShellOutput))
|
||||
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"output":%q,"cursor":%d,"size":%d,"truncated":false}}`, LargeChatFixtureForeignShellOutput, cursor, cursor))
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
}
|
||||
for {
|
||||
var request protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &request); err != nil {
|
||||
if err := wsjson.Read(connCtx, conn, &request); err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version)
|
||||
|
||||
Reference in New Issue
Block a user