forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskRunner.test.ts
More file actions
246 lines (216 loc) · 8.65 KB
/
Copy pathtaskRunner.test.ts
File metadata and controls
246 lines (216 loc) · 8.65 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { candidateAgents, cancelTask, runCodingAgentTask } from './taskRunner'
import { AcpError } from './acp'
import { ADAPTER_PROFILES, adapterConfiguredCommand, adapterIsActivated } from './adapterRegistry'
import type {
AdapterAttemptContext,
AdapterEventSink,
AdapterAttemptResult,
OpenBindingInput,
OpenedBinding,
ProductionAdapterId,
RuntimeAdapter
} from './interface'
import { adapterCapabilitiesFor } from './interface'
import type { CodingAgentEvent } from '../../shared/types'
vi.mock('./adapterRegistry', async () => {
const actual = await vi.importActual<typeof import('./adapterRegistry')>('./adapterRegistry')
return {
...actual,
// Profiles keep their real shape; tests swap createAdapter per adapter id.
ADAPTER_PROFILES: Object.fromEntries(
Object.entries(actual.ADAPTER_PROFILES).map(([id, profile]) => [id, { ...profile }])
),
adapterIsActivated: vi.fn(),
adapterConfiguredCommand: vi.fn(() => undefined)
}
})
type FakeScript = {
/** Throw from openBinding (simulates a dead/unconfigured adapter). */
failOpen?: boolean
/** Text deltas to stream before resolving. */
stream?: string[]
/** Emit the internal main-chat hosted-dispatch boundary. */
emitHostedBoundary?: boolean
/** Throw from executeAttempt after streaming (post-output failure). */
failAfterStream?: boolean
/** Throw this exact error from executeAttempt before any output. */
failWithError?: Error
/** Resolve the attempt only when the signal aborts (for cancel tests). */
hangUntilAborted?: boolean
}
function fakeAdapter(adapterId: ProductionAdapterId, script: FakeScript): RuntimeAdapter {
return {
adapterId,
capabilities: adapterCapabilitiesFor(adapterId),
start: async () => {},
stop: async () => {},
openBinding: async (input: OpenBindingInput): Promise<OpenedBinding> => {
if (script.failOpen) throw new Error(`${adapterId} refused to start`)
return {
sessionId: input.sessionId,
adapterId,
adapterNativeSessionId: `${adapterId}-native`,
resumeFidelity: 'none',
cwd: input.cwd
}
},
resumeBinding: async () => {
throw new Error('not used')
},
executeAttempt: async (
context: AdapterAttemptContext,
sink: AdapterEventSink,
signal: AbortSignal
): Promise<AdapterAttemptResult> => {
if (script.failWithError) throw script.failWithError
if (script.emitHostedBoundary) sink({ type: 'hosted_request_started' })
for (const text of script.stream ?? []) {
sink({ type: 'text_delta', text })
}
if (script.failAfterStream) throw new Error(`${adapterId} crashed mid-run`)
if (script.hangUntilAborted) {
await new Promise<void>((resolve) => {
if (signal.aborted) return resolve()
signal.addEventListener('abort', () => resolve(), { once: true })
})
throw new Error('aborted')
}
return {
text: (script.stream ?? []).join(''),
adapterSessionId: context.binding.adapterNativeSessionId,
terminalStatus: signal.aborted ? 'cancelled' : 'succeeded'
}
},
cancelAttempt: async () => ({
accepted: true,
dispatchAttempted: true,
adapterAcknowledged: false
})
}
}
function script(adapters: Partial<Record<ProductionAdapterId, FakeScript>>): void {
for (const [id, s] of Object.entries(adapters) as Array<[ProductionAdapterId, FakeScript]>) {
ADAPTER_PROFILES[id].createAdapter = () => fakeAdapter(id, s)
}
}
function activate(...ids: ProductionAdapterId[]): void {
vi.mocked(adapterIsActivated).mockImplementation(((id: ProductionAdapterId) =>
ids.includes(id)) as never)
}
describe('candidateAgents', () => {
beforeEach(() => {
vi.mocked(adapterIsActivated).mockReset()
vi.mocked(adapterConfiguredCommand).mockReturnValue(undefined)
})
it('orders unnamed tasks Claude Code first, connected agents only', () => {
activate('acp', 'codex')
expect(candidateAgents(undefined, {})).toEqual(['acp', 'codex'])
})
it('puts the named agent first with the rest as fallbacks', () => {
activate('acp', 'openclaw', 'hermes')
expect(candidateAgents('hermes', {})).toEqual(['hermes', 'acp', 'openclaw'])
})
})
describe('runCodingAgentTask', () => {
beforeEach(() => {
vi.mocked(adapterIsActivated).mockReset()
vi.mocked(adapterConfiguredCommand).mockReturnValue(undefined)
})
it('runs the named agent and streams its output', async () => {
activate('acp', 'openclaw')
script({ openclaw: { stream: ['done ', 'and dusted'], emitHostedBoundary: true } })
const events: CodingAgentEvent[] = []
const result = await runCodingAgentTask(
{ taskId: 't1', prompt: 'fix it', agentId: 'openclaw' },
(e) => events.push(e)
)
expect(result).toMatchObject({ ok: true, adapterId: 'openclaw', text: 'done and dusted' })
expect(events[0]).toMatchObject({
type: 'agent_selected',
adapterId: 'openclaw',
fallback: false
})
expect(events.filter((e) => e.type === 'text_delta')).toHaveLength(2)
expect(events.map((event) => event.type)).not.toContain('hosted_request_started')
})
it('falls back to the next connected agent when the first fails before producing output', async () => {
activate('acp', 'openclaw', 'hermes')
script({
openclaw: { failOpen: true },
acp: { stream: ['fallback answer'] }
})
const events: CodingAgentEvent[] = []
const result = await runCodingAgentTask(
{ taskId: 't2', prompt: 'fix it', agentId: 'openclaw' },
(e) => events.push(e)
)
expect(result).toMatchObject({ ok: true, adapterId: 'acp', text: 'fallback answer' })
const selections = events.filter((e) => e.type === 'agent_selected')
expect(selections.map((e) => (e.type === 'agent_selected' ? e.adapterId : ''))).toEqual([
'openclaw',
'acp'
])
expect(selections[1]).toMatchObject({ fallback: true })
expect(events.some((e) => e.type === 'status' && /trying the next agent/.test(e.message))).toBe(
true
)
})
it('does NOT retry elsewhere once the failing agent already produced visible output', async () => {
activate('acp', 'openclaw')
script({
openclaw: { stream: ['partial answer…'], failAfterStream: true },
acp: { stream: ['should never run'] }
})
const events: CodingAgentEvent[] = []
const result = await runCodingAgentTask(
{ taskId: 't3', prompt: 'fix it', agentId: 'openclaw' },
(e) => events.push(e)
)
expect(result.ok).toBe(false)
expect(result.adapterId).toBe('openclaw')
expect(events.filter((e) => e.type === 'agent_selected')).toHaveLength(1)
})
it('reports failure when every candidate fails', async () => {
activate('acp')
script({ acp: { failOpen: true } })
const result = await runCodingAgentTask({ taskId: 't4', prompt: 'fix it' }, () => {})
expect(result.ok).toBe(false)
expect(result.error).toBeTruthy()
})
it('emits auth_required and stops (no fallback) when Claude Code hits an auth error', async () => {
activate('acp', 'openclaw')
script({
acp: { failWithError: new AcpError('Authentication required', -32000) },
openclaw: { stream: ['should never run'] }
})
const events: CodingAgentEvent[] = []
const result = await runCodingAgentTask(
{ taskId: 't-auth', prompt: 'fix it', agentId: 'acp' },
(e) => events.push(e)
)
expect(result).toMatchObject({ ok: false, adapterId: 'acp' })
expect(result.error).toMatch(/Sign in to Claude/)
expect(events).toContainEqual({ type: 'auth_required', taskId: 't-auth', adapterId: 'acp' })
// A login fixes it — don't silently retry another agent for the same task.
expect(events.filter((e) => e.type === 'agent_selected')).toHaveLength(1)
})
it('reports no-agents-connected when nothing is activated', async () => {
activate()
const result = await runCodingAgentTask({ taskId: 't5', prompt: 'fix it' }, () => {})
expect(result).toMatchObject({ ok: false, adapterId: null })
expect(result.error).toContain('No coding agents are connected')
})
it('cancelTask aborts a running task', async () => {
activate('acp')
script({ acp: { hangUntilAborted: true } })
const running = runCodingAgentTask({ taskId: 't6', prompt: 'never finishes' }, () => {})
// Let the task reach executeAttempt before cancelling.
await new Promise((resolve) => setTimeout(resolve, 10))
expect(cancelTask('t6')).toBe(true)
const result = await running
expect(result.ok).toBe(false)
expect(result.error).toBe('Cancelled.')
expect(cancelTask('t6')).toBe(false) // already finished/cleaned up
})
})