github-webhook-real.e2e.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /** Real CLI and DeepSeek evidence for a GitHub webhook-created Session. */
  2. import type { ChildProcess } from 'node:child_process'
  3. import { spawn } from 'node:child_process'
  4. import { createHmac } from 'node:crypto'
  5. import { existsSync } from 'node:fs'
  6. import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises'
  7. import { createServer } from 'node:net'
  8. import type { AddressInfo } from 'node:net'
  9. import { tmpdir } from 'node:os'
  10. import { join } from 'node:path'
  11. import { setTimeout as delay } from 'node:timers/promises'
  12. import { fileURLToPath } from 'node:url'
  13. import { describe, expect, it } from 'vitest'
  14. const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  15. const BUILT_BIN = join(REPO_ROOT, 'apps/cli/lib/bin.js')
  16. const OVERLAY = fileURLToPath(new URL(
  17. '../../../examples/web-github-review/tests/fixtures/real-cli/cordis.yml',
  18. import.meta.url,
  19. ))
  20. const SECRET = 'github-webhook-real-e2e-secret'
  21. const DELIVERY = 'github-webhook-real-e2e-delivery'
  22. const MARKER = 'DSH_GITHUB_WEBHOOK_REAL_E2E_OK'
  23. const TITLE = 'GitHub webhook real e2e'
  24. interface SessionList {
  25. items: Array<{
  26. sessionId: string
  27. cwd?: string
  28. agentPreset?: string
  29. blank: boolean
  30. }>
  31. }
  32. interface WorkspaceList {
  33. items: Array<{
  34. path: string
  35. sessionIds: string[]
  36. }>
  37. }
  38. interface HistoryPage {
  39. events: Array<{
  40. event: {
  41. type: string
  42. data: unknown
  43. }
  44. }>
  45. hasMore: boolean
  46. }
  47. interface ProcessObservation {
  48. readonly ready: Promise<string>
  49. readonly text: () => string
  50. }
  51. function isRecord(value: unknown): value is Record<string, unknown> {
  52. return typeof value === 'object' && value !== null
  53. }
  54. /** Capture bounded process output and resolve the public Web URL after settled boot. */
  55. function observeProcess(child: ChildProcess): ProcessObservation {
  56. let output = ''
  57. let settled = false
  58. let resolveReady!: (url: string) => void
  59. let rejectReady!: (error: Error) => void
  60. const ready = new Promise<string>((resolve, reject) => {
  61. resolveReady = resolve
  62. rejectReady = reject
  63. })
  64. const timer = setTimeout(() => {
  65. if (!settled) rejectReady(new Error(`dsh web did not become ready within 90s:\n${output}`))
  66. }, 90_000)
  67. timer.unref()
  68. const append = (chunk: Buffer | string): void => {
  69. output = `${output}${String(chunk)}`.slice(-100_000)
  70. const match = /dsh web: (http:\/\/[^\s]+)/u.exec(output)
  71. if (settled || match?.[1] === undefined) return
  72. settled = true
  73. clearTimeout(timer)
  74. resolveReady(match[1].replace('0.0.0.0', '127.0.0.1'))
  75. }
  76. child.stdout?.on('data', append)
  77. child.stderr?.on('data', append)
  78. child.once('error', (error) => {
  79. if (!settled) rejectReady(error)
  80. })
  81. child.once('exit', (code) => {
  82. if (!settled) rejectReady(new Error(`dsh web exited before readiness (code ${String(code)}):\n${output}`))
  83. })
  84. return { ready, text: () => output }
  85. }
  86. /** Reserve and release one loopback port for the isolated webhook listener. */
  87. async function freePort(): Promise<number> {
  88. const server = createServer()
  89. await new Promise<void>((resolve, reject) => {
  90. server.once('error', reject)
  91. server.listen(0, '127.0.0.1', resolve)
  92. })
  93. const port = (server.address() as AddressInfo).port
  94. await new Promise<void>((resolve, reject) => {
  95. server.close((error) => {
  96. if (error === undefined) resolve()
  97. else reject(error)
  98. })
  99. })
  100. return port
  101. }
  102. /** Invoke one public Web RPC method. */
  103. async function rpc<T>(baseUrl: string, method: string, payload: unknown): Promise<T> {
  104. const response = await fetch(`${baseUrl}/api/${method}`, {
  105. method: 'POST',
  106. headers: { 'content-type': 'application/json' },
  107. body: JSON.stringify({
  108. type: 'client-request',
  109. rpcId: `github-webhook-real-${method}`,
  110. method,
  111. payload,
  112. }),
  113. })
  114. if (!response.ok) throw new Error(`${method} returned HTTP ${String(response.status)}: ${await response.text()}`)
  115. const envelope = await response.json() as {
  116. result: { ok: true; value: T } | { ok: false; error: { code: string; message: string } }
  117. }
  118. if (!envelope.result.ok) {
  119. throw new Error(`${method} failed: ${envelope.result.error.code}: ${envelope.result.error.message}`)
  120. }
  121. return envelope.result.value
  122. }
  123. /** Poll a public observation until it satisfies the test's behavior predicate. */
  124. async function eventually<T>(
  125. child: ChildProcess,
  126. processOutput: () => string,
  127. label: string,
  128. probe: () => Promise<T>,
  129. accepts: (value: T) => boolean,
  130. timeoutMs: number,
  131. ): Promise<T> {
  132. const deadline = Date.now() + timeoutMs
  133. let lastValue: T | undefined
  134. let lastError: unknown
  135. while (Date.now() < deadline) {
  136. if (child.exitCode !== null) {
  137. throw new Error(`dsh web exited while waiting for ${label} (code ${String(child.exitCode)}):\n${processOutput()}`)
  138. }
  139. try {
  140. lastValue = await probe()
  141. if (accepts(lastValue)) return lastValue
  142. } catch (error) {
  143. lastError = error
  144. }
  145. await delay(300)
  146. }
  147. throw new Error(
  148. `timed out waiting for ${label}; last value=${JSON.stringify(lastValue)}; `
  149. + `last error=${String(lastError)}; process output:\n${processOutput()}`,
  150. )
  151. }
  152. /** Return every text block from durable assistant messages. */
  153. function assistantText(page: HistoryPage): string {
  154. const text: string[] = []
  155. for (const { event } of page.events) {
  156. if (event.type !== 'assistant/message' || !isRecord(event.data) || !isRecord(event.data.message)) continue
  157. const content = event.data.message.content
  158. if (!Array.isArray(content)) continue
  159. for (const block of content) {
  160. if (isRecord(block) && block.type === 'text' && typeof block.text === 'string') text.push(block.text)
  161. }
  162. }
  163. return text.join('\n')
  164. }
  165. /** Stop the spawned CLI through its normal signal path, escalating only on a stuck teardown. */
  166. async function stop(child: ChildProcess): Promise<void> {
  167. if (child.exitCode !== null) return
  168. let resolveClosed!: () => void
  169. const closed = new Promise<void>((resolve) => { resolveClosed = resolve })
  170. child.once('close', resolveClosed)
  171. child.kill('SIGTERM')
  172. if (await Promise.race([closed.then(() => true), delay(10_000, false, { ref: false })])) return
  173. if (child.exitCode === null) child.kill('SIGKILL')
  174. await Promise.race([closed, delay(5_000, undefined, { ref: false })])
  175. }
  176. /** Send the sole synthetic external interaction: one signed GitHub delivery. */
  177. async function sendGitHubDelivery(origin: string): Promise<Response> {
  178. const body = JSON.stringify({
  179. action: 'ready_for_review',
  180. number: 4242,
  181. repository: { full_name: 'deepseek-harness/deepseek-harness' },
  182. pull_request: {
  183. title: 'Real CLI webhook e2e',
  184. html_url: 'https://github.com/deepseek-harness/deepseek-harness/pull/4242',
  185. draft: false,
  186. user: { login: 'octocat' },
  187. base: { ref: 'master', sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' },
  188. head: { ref: 'webhook-e2e', sha: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' },
  189. },
  190. })
  191. const signature = `sha256=${createHmac('sha256', SECRET).update(body).digest('hex')}`
  192. return await fetch(`${origin}/github`, {
  193. method: 'POST',
  194. headers: {
  195. 'content-type': 'application/json',
  196. 'x-github-delivery': DELIVERY,
  197. 'x-github-event': 'pull_request',
  198. 'x-hub-signature-256': signature,
  199. },
  200. body,
  201. })
  202. }
  203. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('GitHub webhook through the real dsh CLI and model', () => {
  204. it('creates, attaches, prompts, and completes a Workspace Session', async () => {
  205. expect(existsSync(BUILT_BIN), `missing built CLI ${BUILT_BIN}; run pnpm run build:official`).toBe(true)
  206. const root = await mkdtemp(join(tmpdir(), 'dsh-github-webhook-real-'))
  207. const workspacePath = join(root, 'workspace')
  208. await mkdir(workspacePath)
  209. const canonicalWorkspacePath = await realpath(workspacePath)
  210. const webhookPort = await freePort()
  211. const child = spawn(process.execPath, [
  212. BUILT_BIN,
  213. 'web',
  214. '--patch', OVERLAY,
  215. '--no-open',
  216. '--host', '127.0.0.1',
  217. '--port', '0',
  218. ], {
  219. cwd: root,
  220. env: {
  221. ...process.env,
  222. DSH_AGENTS_HOME: join(root, '.agents'),
  223. DSH_GITHUB_E2E_MARKER: MARKER,
  224. DSH_GITHUB_E2E_WORKSPACE: workspacePath,
  225. DSH_GITHUB_WEBHOOK_PORT: String(webhookPort),
  226. DSH_GITHUB_WEBHOOK_SECRET: SECRET,
  227. DSH_HOME: join(root, '.dsh'),
  228. DSH_TELEMETRY_DISABLED: '1',
  229. },
  230. stdio: ['ignore', 'pipe', 'pipe'],
  231. })
  232. const observation = observeProcess(child)
  233. try {
  234. const baseUrl = await observation.ready
  235. const webhookOrigin = `http://127.0.0.1:${String(webhookPort)}`
  236. expect((await fetch(`${webhookOrigin}/api`)).status).toBe(404)
  237. expect((await sendGitHubDelivery(baseUrl)).status).not.toBe(202)
  238. expect((await sendGitHubDelivery(webhookOrigin)).status).toBe(202)
  239. const workspaces = await eventually(
  240. child,
  241. observation.text,
  242. 'one Workspace-attached Session',
  243. async () => await rpc<WorkspaceList>(baseUrl, 'workspace.list', {}),
  244. value => value.items.some(workspace =>
  245. workspace.path === canonicalWorkspacePath && workspace.sessionIds.length === 1),
  246. 30_000,
  247. )
  248. const workspace = workspaces.items.find(item => item.path === canonicalWorkspacePath)
  249. const sessionId = workspace?.sessionIds[0]
  250. if (sessionId === undefined) throw new Error('workspace.list did not expose the webhook Session')
  251. const sessions = await rpc<SessionList>(baseUrl, 'session.list', {})
  252. expect(sessions.items.find(session => session.sessionId === sessionId)).toMatchObject({
  253. agentPreset: 'minimal',
  254. blank: false,
  255. cwd: canonicalWorkspacePath,
  256. })
  257. const admitted = await eventually(
  258. child,
  259. observation.text,
  260. 'webhook provenance, title, and permission events',
  261. async () => await rpc<HistoryPage>(baseUrl, 'session.history', { sessionId, maxMessages: 100 }),
  262. (page) => {
  263. const events = page.events.map(item => item.event)
  264. const title = events.find(event => event.type === 'session/title')
  265. const permission = events.find(event =>
  266. event.type === 'permission/preset'
  267. && isRecord(event.data)
  268. && event.data.preset === 'read-only')
  269. const message = events.find(event =>
  270. event.type === 'user/message'
  271. && isRecord(event.data)
  272. && isRecord(event.data.source)
  273. && event.data.source.kind === 'webhook')
  274. return isRecord(title?.data) && title.data.title === TITLE
  275. && permission !== undefined
  276. && isRecord(message?.data) && isRecord(message.data.source)
  277. && message.data.source.provider === 'github'
  278. && message.data.source.deliveryId === DELIVERY
  279. },
  280. 30_000,
  281. )
  282. const webhookMessage = admitted.events.map(item => item.event)
  283. .find(event => event.type === 'user/message'
  284. && isRecord(event.data)
  285. && isRecord(event.data.source)
  286. && event.data.source.kind === 'webhook')
  287. expect(webhookMessage?.data).toMatchObject({
  288. content: [{ type: 'text', text: `Reply with exactly ${MARKER} and no other text. Do not call tools.` }],
  289. source: {
  290. kind: 'webhook',
  291. provider: 'github',
  292. deliveryId: DELIVERY,
  293. ruleId: 'github-real-e2e',
  294. source: 'github-real-e2e',
  295. },
  296. })
  297. const completed = await eventually(
  298. child,
  299. observation.text,
  300. 'a real DeepSeek assistant response',
  301. async () => await rpc<HistoryPage>(baseUrl, 'session.history', { sessionId, maxMessages: 100 }),
  302. page => assistantText(page).includes(MARKER),
  303. 150_000,
  304. )
  305. expect(assistantText(completed)).toContain(MARKER)
  306. } finally {
  307. await stop(child)
  308. await rm(root, { recursive: true, force: true })
  309. }
  310. }, 330_000)
  311. })