-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcontainer-runner.test.ts
More file actions
230 lines (195 loc) · 6.14 KB
/
Copy pathcontainer-runner.test.ts
File metadata and controls
230 lines (195 loc) · 6.14 KB
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
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { EventEmitter } from 'events';
import { PassThrough } from 'stream';
// Sentinel markers must match container-runner.ts
const OUTPUT_START_MARKER = '---GHOSTCLAW_OUTPUT_START---';
const OUTPUT_END_MARKER = '---GHOSTCLAW_OUTPUT_END---';
// Mock config
vi.mock('./config.js', () => ({
CONTAINER_IMAGE: 'ghostclaw-agent:latest',
CONTAINER_MAX_OUTPUT_SIZE: 10485760,
CONTAINER_TIMEOUT: 1800000, // 30min
DATA_DIR: '/tmp/ghostclaw-test-data',
GROUPS_DIR: '/tmp/ghostclaw-test-groups',
IDLE_TIMEOUT: 1800000, // 30min
AGENT_IDLE_TIMEOUT: 5000, // 5s in tests
AGENT_ABSOLUTE_TIMEOUT: 10000, // 10s in tests
TIMEZONE: 'America/Los_Angeles',
}));
// Mock logger
vi.mock('./logger.js', () => ({
logger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
// Mock fs
vi.mock('fs', async () => {
const actual = await vi.importActual<typeof import('fs')>('fs');
return {
...actual,
default: {
...actual,
existsSync: vi.fn(() => false),
mkdirSync: vi.fn(),
writeFileSync: vi.fn(),
readFileSync: vi.fn(() => ''),
readdirSync: vi.fn(() => []),
statSync: vi.fn(() => ({ isDirectory: () => false })),
copyFileSync: vi.fn(),
},
};
});
// Create a controllable fake ChildProcess
function createFakeProcess() {
const proc = new EventEmitter() as EventEmitter & {
stdin: PassThrough;
stdout: PassThrough;
stderr: PassThrough;
kill: ReturnType<typeof vi.fn>;
pid: number;
};
proc.stdin = new PassThrough();
proc.stdout = new PassThrough();
proc.stderr = new PassThrough();
proc.kill = vi.fn();
proc.pid = 12345;
return proc;
}
let fakeProc: ReturnType<typeof createFakeProcess>;
// Mock child_process.spawn
vi.mock('child_process', async () => {
const actual =
await vi.importActual<typeof import('child_process')>('child_process');
return {
...actual,
spawn: vi.fn(() => fakeProc),
execSync: vi.fn(() => ''),
exec: vi.fn(
(_cmd: string, _opts: unknown, cb?: (err: Error | null) => void) => {
if (cb) cb(null);
return new EventEmitter();
},
),
};
});
import { runContainerAgent, ContainerOutput } from './container-runner.js';
import type { RegisteredGroup } from './types.js';
const testGroup: RegisteredGroup = {
name: 'Test Group',
folder: 'test-group',
trigger: '@Andy',
added_at: new Date().toISOString(),
};
const testInput = {
prompt: 'Hello',
groupFolder: 'test-group',
chatJid: 'test@g.us',
isMain: false,
};
function emitOutputMarker(
proc: ReturnType<typeof createFakeProcess>,
output: ContainerOutput,
) {
const json = JSON.stringify(output);
proc.stdout.push(`${OUTPUT_START_MARKER}\n${json}\n${OUTPUT_END_MARKER}\n`);
}
describe('container-runner timeout behavior', () => {
beforeEach(() => {
vi.useFakeTimers();
fakeProc = createFakeProcess();
});
afterEach(() => {
vi.useRealTimers();
});
it('absolute timeout after output resolves as success', async () => {
const onOutput = vi.fn(async () => {});
const resultPromise = runContainerAgent(
testGroup,
testInput,
() => {},
onOutput,
);
// Emit output with a result (also resets idle timer via stdout data)
emitOutputMarker(fakeProc, {
status: 'success',
result: 'Here is my response',
newSessionId: 'session-123',
});
// Let output processing settle
await vi.advanceTimersByTimeAsync(10);
// Fire the absolute ceiling (AGENT_ABSOLUTE_TIMEOUT = 10000ms in tests)
await vi.advanceTimersByTimeAsync(10000);
// Emit close event (as if process was stopped by the timeout)
fakeProc.emit('close', 137);
await vi.advanceTimersByTimeAsync(10);
const result = await resultPromise;
expect(result.status).toBe('success');
expect(result.newSessionId).toBe('session-123');
expect(onOutput).toHaveBeenCalledWith(
expect.objectContaining({ result: 'Here is my response' }),
);
});
it('idle timeout with no stdout resolves as error', async () => {
const onOutput = vi.fn(async () => {});
const resultPromise = runContainerAgent(
testGroup,
testInput,
() => {},
onOutput,
);
// No stdout at all — fire the idle timeout (AGENT_IDLE_TIMEOUT = 5000ms in tests)
await vi.advanceTimersByTimeAsync(5000);
fakeProc.emit('close', 137);
await vi.advanceTimersByTimeAsync(10);
const result = await resultPromise;
expect(result.status).toBe('error');
expect(result.error).toContain('timed out');
expect(onOutput).not.toHaveBeenCalled();
});
it('stdout activity resets idle timer', async () => {
const onOutput = vi.fn(async () => {});
const resultPromise = runContainerAgent(
testGroup,
testInput,
() => {},
onOutput,
);
// Emit raw stdout at 4s — just before idle timeout (5s in tests)
await vi.advanceTimersByTimeAsync(4000);
fakeProc.stdout.push('thinking...\n');
// Idle timer should have reset — advance another 4s (total 8s, but idle only 4s since last stdout)
await vi.advanceTimersByTimeAsync(4000);
// Agent hasn't timed out yet — now emit proper output and close normally
emitOutputMarker(fakeProc, { status: 'success', result: 'Done' });
await vi.advanceTimersByTimeAsync(10);
fakeProc.emit('close', 0);
await vi.advanceTimersByTimeAsync(10);
const result = await resultPromise;
expect(result.status).toBe('success');
});
it('normal exit after output resolves as success', async () => {
const onOutput = vi.fn(async () => {});
const resultPromise = runContainerAgent(
testGroup,
testInput,
() => {},
onOutput,
);
// Emit output
emitOutputMarker(fakeProc, {
status: 'success',
result: 'Done',
newSessionId: 'session-456',
});
await vi.advanceTimersByTimeAsync(10);
// Normal exit (no timeout)
fakeProc.emit('close', 0);
await vi.advanceTimersByTimeAsync(10);
const result = await resultPromise;
expect(result.status).toBe('success');
expect(result.newSessionId).toBe('session-456');
});
});