summaryrefslogtreecommitdiffhomepage
path: root/internal/llm/tools/bash_test.go
blob: 97be3683aa243f9c9b74fc84503e973959ac9e8a (plain)
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package tools

import (
	"context"
	"encoding/json"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/kujtimiihoxha/termai/internal/permission"
	"github.com/kujtimiihoxha/termai/internal/pubsub"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestBashTool_Info(t *testing.T) {
	tool := NewBashTool(newMockPermissionService(true))
	info := tool.Info()

	assert.Equal(t, BashToolName, info.Name)
	assert.NotEmpty(t, info.Description)
	assert.Contains(t, info.Parameters, "command")
	assert.Contains(t, info.Parameters, "timeout")
	assert.Contains(t, info.Required, "command")
}

func TestBashTool_Run(t *testing.T) {
	// Save original working directory
	origWd, err := os.Getwd()
	require.NoError(t, err)
	defer func() {
		os.Chdir(origWd)
	}()

	t.Run("executes command successfully", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "echo 'Hello World'",
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Equal(t, "Hello World\n", response.Content)
	})

	t.Run("handles invalid parameters", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		call := ToolCall{
			Name:  BashToolName,
			Input: "invalid json",
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Contains(t, response.Content, "invalid parameters")
	})

	t.Run("handles missing command", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "",
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Contains(t, response.Content, "missing command")
	})

	t.Run("handles banned commands", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))

		for _, bannedCmd := range bannedCommands {
			params := BashParams{
				Command: bannedCmd + " arg1 arg2",
			}

			paramsJSON, err := json.Marshal(params)
			require.NoError(t, err)

			call := ToolCall{
				Name:  BashToolName,
				Input: string(paramsJSON),
			}

			response, err := tool.Run(context.Background(), call)
			require.NoError(t, err)
			assert.Contains(t, response.Content, "not allowed", "Command %s should be blocked", bannedCmd)
		}
	})

	t.Run("handles multi-word safe commands without permission check", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(false))

		// Test with multi-word safe commands
		multiWordCommands := []string{
			"go env",
		}

		for _, cmd := range multiWordCommands {
			params := BashParams{
				Command: cmd,
			}

			paramsJSON, err := json.Marshal(params)
			require.NoError(t, err)

			call := ToolCall{
				Name:  BashToolName,
				Input: string(paramsJSON),
			}

			response, err := tool.Run(context.Background(), call)
			require.NoError(t, err)
			assert.NotContains(t, response.Content, "permission denied",
				"Command %s should be allowed without permission", cmd)
		}
	})

	t.Run("handles permission denied", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(false))

		// Test with a command that requires permission
		params := BashParams{
			Command: "mkdir test_dir",
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Contains(t, response.Content, "permission denied")
	})

	t.Run("handles command timeout", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "sleep 2",
			Timeout: 100, // 100ms timeout
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Contains(t, response.Content, "aborted")
	})

	t.Run("handles command with stderr output", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "echo 'error message' >&2",
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Contains(t, response.Content, "error message")
	})

	t.Run("handles command with both stdout and stderr", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "echo 'stdout message' && echo 'stderr message' >&2",
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Contains(t, response.Content, "stdout message")
		assert.Contains(t, response.Content, "stderr message")
	})

	t.Run("handles context cancellation", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "sleep 5",
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

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

		// Cancel the context after a short delay
		go func() {
			time.Sleep(100 * time.Millisecond)
			cancel()
		}()

		response, err := tool.Run(ctx, call)
		require.NoError(t, err)
		assert.Contains(t, response.Content, "aborted")
	})

	t.Run("respects max timeout", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "echo 'test'",
			Timeout: MaxTimeout + 1000, // Exceeds max timeout
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Equal(t, "test\n", response.Content)
	})

	t.Run("uses default timeout for zero or negative timeout", func(t *testing.T) {
		tool := NewBashTool(newMockPermissionService(true))
		params := BashParams{
			Command: "echo 'test'",
			Timeout: -100, // Negative timeout
		}

		paramsJSON, err := json.Marshal(params)
		require.NoError(t, err)

		call := ToolCall{
			Name:  BashToolName,
			Input: string(paramsJSON),
		}

		response, err := tool.Run(context.Background(), call)
		require.NoError(t, err)
		assert.Equal(t, "test\n", response.Content)
	})
}

func TestTruncateOutput(t *testing.T) {
	t.Run("does not truncate short output", func(t *testing.T) {
		output := "short output"
		result := truncateOutput(output)
		assert.Equal(t, output, result)
	})

	t.Run("truncates long output", func(t *testing.T) {
		// Create a string longer than MaxOutputLength
		longOutput := strings.Repeat("a\n", MaxOutputLength)
		result := truncateOutput(longOutput)

		// Check that the result is shorter than the original
		assert.Less(t, len(result), len(longOutput))

		// Check that the truncation message is included
		assert.Contains(t, result, "lines truncated")

		// Check that we have the beginning and end of the original string
		assert.True(t, strings.HasPrefix(result, "a\n"))
		assert.True(t, strings.HasSuffix(result, "a\n"))
	})
}

func TestCountLines(t *testing.T) {
	testCases := []struct {
		name     string
		input    string
		expected int
	}{
		{
			name:     "empty string",
			input:    "",
			expected: 0,
		},
		{
			name:     "single line",
			input:    "line1",
			expected: 1,
		},
		{
			name:     "multiple lines",
			input:    "line1\nline2\nline3",
			expected: 3,
		},
		{
			name:     "trailing newline",
			input:    "line1\nline2\n",
			expected: 3, // Empty string after last newline counts as a line
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			result := countLines(tc.input)
			assert.Equal(t, tc.expected, result)
		})
	}
}

// Mock permission service for testing
type mockPermissionService struct {
	*pubsub.Broker[permission.PermissionRequest]
	allow bool
}

func (m *mockPermissionService) GrantPersistant(permission permission.PermissionRequest) {
	// Not needed for tests
}

func (m *mockPermissionService) Grant(permission permission.PermissionRequest) {
	// Not needed for tests
}

func (m *mockPermissionService) Deny(permission permission.PermissionRequest) {
	// Not needed for tests
}

func (m *mockPermissionService) Request(opts permission.CreatePermissionRequest) bool {
	return m.allow
}

func newMockPermissionService(allow bool) permission.Service {
	return &mockPermissionService{
		Broker: pubsub.NewBroker[permission.PermissionRequest](),
		allow:  allow,
	}
}