nandi/oripublic Fork 0
7895c1d1c9bb1048807dc04f7246dc456c47e025
Commits
Clone
git clone https://git.rickub.com/nandi/ori.git
git clone ssh://git@rickub.com/nandi/ori.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

forked from bots-garden/ori

agent_test.go · 278 lines · 8.5 KBGo Blame HistoryRaw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package agent_test

import (
	"context"
	"io"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"

	acp "github.com/coder/acp-go-sdk"

	"rickub.com/bots-garden/ori/internal/agent"
)

// mockAgent is a deterministic in-process ACP agent. The embedded acp.Agent
// interface satisfies the methods this test never exercises; calling one of
// them would panic, which is exactly what we want a test to do.
type mockAgent struct {
	acp.Agent
	conn *acp.AgentSideConnection

	mu        sync.Mutex
	cancelled bool
	// askPermission makes Prompt request a permission before answering.
	askPermission bool
	// readFile makes Prompt read this file through the client before answering.
	readFile string
	// writeFile makes Prompt write "written by agent" to this file.
	writeFile string
}

func (a *mockAgent) SetAgentConnection(conn *acp.AgentSideConnection) { a.conn = conn }

func (a *mockAgent) Initialize(_ context.Context, params acp.InitializeRequest) (acp.InitializeResponse, error) {
	return acp.InitializeResponse{ProtocolVersion: params.ProtocolVersion}, nil
}

func (a *mockAgent) NewSession(context.Context, acp.NewSessionRequest) (acp.NewSessionResponse, error) {
	return acp.NewSessionResponse{SessionId: "sess-mock"}, nil
}

func (a *mockAgent) Authenticate(context.Context, acp.AuthenticateRequest) (acp.AuthenticateResponse, error) {
	return acp.AuthenticateResponse{}, nil
}

func (a *mockAgent) Cancel(context.Context, acp.CancelNotification) error {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.cancelled = true
	return nil
}

func (a *mockAgent) Prompt(ctx context.Context, params acp.PromptRequest) (acp.PromptResponse, error) {
	send := func(text string) error {
		return a.conn.SessionUpdate(ctx, acp.SessionNotification{
			SessionId: params.SessionId,
			Update:    acp.UpdateAgentMessageText(text),
		})
	}
	if err := send("Hello "); err != nil {
		return acp.PromptResponse{}, err
	}
	if a.askPermission {
		resp, err := a.conn.RequestPermission(ctx, acp.RequestPermissionRequest{
			SessionId: params.SessionId,
			Options: []acp.PermissionOption{
				{OptionId: "allow", Name: "Allow", Kind: acp.PermissionOptionKindAllowOnce},
				{OptionId: "reject", Name: "Reject", Kind: acp.PermissionOptionKindRejectOnce},
			},
		})
		if err != nil {
			return acp.PromptResponse{}, err
		}
		if resp.Outcome.Selected == nil || resp.Outcome.Selected.OptionId != "allow" {
			return acp.PromptResponse{StopReason: acp.StopReasonRefusal}, nil
		}
	}
	if a.readFile != "" {
		if _, err := a.conn.ReadTextFile(ctx, acp.ReadTextFileRequest{SessionId: params.SessionId, Path: a.readFile}); err != nil {
			return acp.PromptResponse{}, err
		}
	}
	if a.writeFile != "" {
		if _, err := a.conn.WriteTextFile(ctx, acp.WriteTextFileRequest{SessionId: params.SessionId, Path: a.writeFile, Content: "written by agent"}); err != nil {
			return acp.PromptResponse{}, err
		}
	}
	if err := send("world"); err != nil {
		return acp.PromptResponse{}, err
	}
	return acp.PromptResponse{StopReason: acp.StopReasonEndTurn}, nil
}

// recordingHandler collects session updates and answers permission requests.
type recordingHandler struct {
	mu      sync.Mutex
	texts   []string
	granted bool
	asked   int
}

func (h *recordingHandler) HandleSessionUpdate(_ context.Context, n acp.SessionNotification) {
	h.mu.Lock()
	defer h.mu.Unlock()
	if chunk := n.Update.AgentMessageChunk; chunk != nil && chunk.Content.Text != nil {
		h.texts = append(h.texts, chunk.Content.Text.Text)
	}
}

func (h *recordingHandler) HandlePermissionRequest(_ context.Context, req acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.asked++
	choice := acp.PermissionOptionId("reject")
	if h.granted {
		choice = "allow"
	}
	_ = req
	return acp.RequestPermissionResponse{Outcome: acp.NewRequestPermissionOutcomeSelected(choice)}, nil
}

func (h *recordingHandler) joined() string {
	h.mu.Lock()
	defer h.mu.Unlock()
	return strings.Join(h.texts, "")
}

// connectMock wires a mock agent and an agent.Session together with in-memory
// pipes, no subprocess involved.
func connectMock(t *testing.T, mock *mockAgent, handler agent.Handler) *agent.Session {
	t.Helper()
	clientToAgentR, clientToAgentW := io.Pipe()
	agentToClientR, agentToClientW := io.Pipe()

	mock.SetAgentConnection(acp.NewAgentSideConnection(mock, agentToClientW, clientToAgentR))

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	t.Cleanup(cancel)
	session, err := agent.Connect(ctx, clientToAgentW, agentToClientR, agent.Options{
		Cwd:     t.TempDir(),
		Handler: handler,
	})
	if err != nil {
		t.Fatalf("Connect returned an error: %v", err)
	}
	return session
}

func TestConnectPerformsHandshake(t *testing.T) {
	session := connectMock(t, &mockAgent{}, &recordingHandler{})
	if session.ID() != "sess-mock" {
		t.Errorf("session ID = %q, want %q", session.ID(), "sess-mock")
	}
}

func TestConnectRequiresHandler(t *testing.T) {
	_, err := agent.Connect(context.Background(), io.Discard, strings.NewReader(""), agent.Options{})
	if err == nil {
		t.Fatal("Connect accepted a nil Handler, want an error")
	}
}

func TestPromptStreamsUpdates(t *testing.T) {
	handler := &recordingHandler{}
	session := connectMock(t, &mockAgent{}, handler)

	stop, err := session.PromptText(context.Background(), "hi")
	if err != nil {
		t.Fatalf("PromptText returned an error: %v", err)
	}
	if stop != acp.StopReasonEndTurn {
		t.Errorf("stop reason = %q, want %q", stop, acp.StopReasonEndTurn)
	}
	if got := handler.joined(); got != "Hello world" {
		t.Errorf("streamed text = %q, want %q", got, "Hello world")
	}
}

func TestPermissionGrantedFlowsBackToAgent(t *testing.T) {
	handler := &recordingHandler{granted: true}
	session := connectMock(t, &mockAgent{askPermission: true}, handler)

	stop, err := session.PromptText(context.Background(), "do something sensitive")
	if err != nil {
		t.Fatalf("PromptText returned an error: %v", err)
	}
	if stop != acp.StopReasonEndTurn {
		t.Errorf("stop reason = %q, want %q (permission was granted)", stop, acp.StopReasonEndTurn)
	}
	if handler.asked != 1 {
		t.Errorf("permission requests seen by handler = %d, want 1", handler.asked)
	}
}

func TestPermissionRejectedStopsTheTurn(t *testing.T) {
	handler := &recordingHandler{granted: false}
	session := connectMock(t, &mockAgent{askPermission: true}, handler)

	stop, err := session.PromptText(context.Background(), "do something sensitive")
	if err != nil {
		t.Fatalf("PromptText returned an error: %v", err)
	}
	if stop != acp.StopReasonRefusal {
		t.Errorf("stop reason = %q, want %q (permission was rejected)", stop, acp.StopReasonRefusal)
	}
}

func TestCancelReachesTheAgent(t *testing.T) {
	mock := &mockAgent{}
	session := connectMock(t, mock, &recordingHandler{})

	if err := session.Cancel(context.Background()); err != nil {
		t.Fatalf("Cancel returned an error: %v", err)
	}
	// Cancel is a notification: poll briefly for its arrival.
	deadline := time.Now().Add(2 * time.Second)
	for {
		mock.mu.Lock()
		cancelled := mock.cancelled
		mock.mu.Unlock()
		if cancelled {
			return
		}
		if time.Now().After(deadline) {
			t.Fatal("agent never received the cancel notification")
		}
		time.Sleep(10 * time.Millisecond)
	}
}

func TestAgentCanReadClientFiles(t *testing.T) {
	file := filepath.Join(t.TempDir(), "note.txt")
	if err := os.WriteFile(file, []byte("line 1\nline 2"), 0o644); err != nil {
		t.Fatal(err)
	}
	session := connectMock(t, &mockAgent{readFile: file}, &recordingHandler{})

	if _, err := session.PromptText(context.Background(), "read it"); err != nil {
		t.Fatalf("PromptText returned an error: %v", err)
	}
}

func TestAgentCanWriteClientFiles(t *testing.T) {
	file := filepath.Join(t.TempDir(), "sub", "out.txt")
	session := connectMock(t, &mockAgent{writeFile: file}, &recordingHandler{})

	if _, err := session.PromptText(context.Background(), "write it"); err != nil {
		t.Fatalf("PromptText returned an error: %v", err)
	}
	content, err := os.ReadFile(file)
	if err != nil {
		t.Fatalf("the agent's write never landed: %v", err)
	}
	if string(content) != "written by agent" {
		t.Errorf("written content = %q, want %q", content, "written by agent")
	}
}

func TestStartRejectsMissingCommand(t *testing.T) {
	_, err := agent.Start(context.Background(), agent.Options{Handler: &recordingHandler{}})
	if err == nil {
		t.Fatal("Start accepted an empty Command, want an error")
	}
}

func TestStartReportsUnknownExecutable(t *testing.T) {
	_, err := agent.Start(context.Background(), agent.Options{
		Command: []string{"/does/not/exist-ori-agent"},
		Cwd:     t.TempDir(),
		Handler: &recordingHandler{},
	})
	if err == nil {
		t.Fatal("Start accepted a non-existent executable, want an error")
	}
}