package pi import ( "context" "encoding/json" "errors" "io" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) // A Pi that stops reading its stdin cannot hold the runner: a write // gives up when its context ends, a command too, and other writes wait // their turn without blocking the client. func TestClientWritesAreCancellable(t *testing.T) { stdinR, stdinW := io.Pipe() // nobody reads stdinR defer stdinR.Close() stdoutR, stdoutW := io.Pipe() defer stdoutW.Close() c := NewClient(stdoutR, stdinW) for _, call := range []func(context.Context) error{ func(ctx context.Context) error { return c.Send(ctx, map[string]string{"type": "abort"}) }, func(ctx context.Context) error { _, err := c.Call(ctx, map[string]any{"type": "abort"}); return err }, } { ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) start := time.Now() err := call(ctx) cancel() if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 2*time.Second { t.Fatalf("a write to a stdin nobody reads: %v after %v", err, time.Since(start)) } } } // stuckProcess is a Pi whose stdin nobody reads; its stdout answers // get_state, then says nothing more. type stuckProcess struct { stdinR *io.PipeReader stdinW *io.PipeWriter stdoutR *io.PipeReader stdoutW *io.PipeWriter } func (p *stuckProcess) Stdin() io.WriteCloser { return p.stdinW } func (p *stuckProcess) Stdout() io.ReadCloser { return p.stdoutR } func (p *stuckProcess) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("")) } func (p *stuckProcess) ID() string { return "stuck" } func (p *stuckProcess) Wait(ctx context.Context) (provider.Exit, error) { <-ctx.Done() return provider.Exit{}, ctx.Err() } type stuckHost struct{ p *stuckProcess } func (h stuckHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { go func() { // Read get_state, answer it, then stop reading for good. buf := make([]byte, 4096) n, _ := h.p.stdinR.Read(buf) var cmd struct{ ID string } json.Unmarshal(buf[:n], &cmd) raw, _ := json.Marshal(map[string]any{"type": "response", "id": cmd.ID, "command": "get_state", "success": true, "data": map[string]any{"sessionId": "01234567-89ab", "model": map[string]string{"id": l.Selection.Model, "provider": l.Selection.Provider}}}) h.p.stdoutW.Write(append(raw, '\n')) // And a question it waits on, so an interrupt has a dialog to // cancel first. h.p.stdoutW.Write([]byte(`{"type":"extension_ui_request","id":"ui-1","method":"confirm","title":"equipo:tool_call","message":"{}"}` + "\n")) }() return h.p, nil } func TestLauncherInterruptIsBounded(t *testing.T) { p := &stuckProcess{} p.stdinR, p.stdinW = io.Pipe() p.stdoutR, p.stdoutW = io.Pipe() defer p.stdoutW.Close() defer p.stdinR.Close() l, _ := New(stuckHost{p}) sess, err := l.openWith(context.Background(), context.Background(), provider.Launch{Selection: provider.Selection{Provider: "tensorx", Model: "m"}}, []string{"/opt/node"}) if err != nil { t.Fatal(err) } events, _ := l.Events(context.Background(), sess) if e := <-events; e.Kind != KindAsk { t.Fatalf("event %s", e.Kind) } ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() start := time.Now() if err := l.Interrupt(ctx, sess); err == nil || time.Since(start) > 2*time.Second { t.Fatalf("an interrupt Pi never reads: %v after %v", err, time.Since(start)) } ctx2, cancel2 := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel2() if err := l.StartTurn(ctx2, sess, provider.Turn{ID: "t", Prompt: "x"}); err == nil { t.Fatal("a prompt Pi never reads went through") } } // What Pi sends is held to a budget: records wait in the client only up // to its bytes, Pi waits for the rest (it honours stdout backpressure), // and a record over the size limit ends the stream. func TestClientQueueIsBounded(t *testing.T) { stdoutR, stdoutW := io.Pipe() defer stdoutW.Close() c := newClientLimits(stdoutR, io.Discard, 1000, 300) line := strings.Repeat("x", 90) go func() { for range 20 { if _, err := stdoutW.Write([]byte(`{"type":"` + line + `"}` + "\n")); err != nil { return } } }() time.Sleep(300 * time.Millisecond) if q := c.queuedBytes(); q > 300 || len(c.Records) > 3 { t.Fatalf("queued %d bytes in %d records with a budget of 300", q, len(c.Records)) } // Taking one lets one more in. got := <-c.Records c.Release(len(got)) time.Sleep(100 * time.Millisecond) if q := c.queuedBytes(); q > 300 || q == 0 { t.Fatalf("queued %d", q) } big := newClientLimits(strings.NewReader(`{"type":"`+strings.Repeat("y", 2000)+`"}`+"\n"+`{"type":"after"}`+"\n"), io.Discard, 1000, 300) n := 0 for range big.Records { n++ } if n != 0 { t.Fatalf("an oversized record did not end the stream: %d records after it", n) } } // A tool call's arguments in an event are clipped; the call itself is // Pi's to run. func TestDecodeClipsToolArguments(t *testing.T) { d := &Decoder{} evs, err := d.Decode([]byte(`{"type":"tool_execution_start","toolCallId":"c","toolName":"write","args":{"content":"` + strings.Repeat("z", 200000) + `"}}`)) if err != nil || len(evs) != 1 { t.Fatal(err) } if len(evs[0].Payload) > maxEventArgs+1024 { t.Fatalf("payload of %d bytes", len(evs[0].Payload)) } }