feat(ai-harness): build artifacts, worker mode, and remote harnessText #1521
ClosedAlemTuzlakwants to merge 8 commits into
feat/harness-p4-subagents fromfeat/harness-p5-buildopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) assignedjherr
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
- @@ -0,0 +50,21 @@50+51+function run(52+ command: string,53+ args: Array<string>,54+ cwd: string,55+): Promise<string> {56+ // On Windows, npm installs Bun as a `.cmd` shim, which only a shell can57+ // start. The arguments are paths this module builds, quoted for cmd.58+ const viaShell = process.platform === 'win32' && !/\.exe$/i.test(command)59+ return new Promise((done, fail) => {60+ const child = viaShell61+ ? spawn(62+ command,63+ args.map((arg) => `"${arg}"`),64+ { cwd, stdio: ['ignore', 'pipe', 'pipe'], shell: true },65+ )66+ : spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] })67+ let stdout = ''68+ let stderr = ''69+ child.stdout.on('data', (data: Buffer) => (stdout += data.toString()))70+ child.stderr.on('data', (data: Buffer) => (stderr += data.toString()))@@ -0,0 +115,21 @@115+ )116+ await mkdir(outDir, { recursive: true })117+118+ // Temporary files sit next to the entry, so its imports resolve the same way.119+ const id = randomUUID().slice(0, 8)120+ const bootstrap = join(dirname(entry), `.harness-worker-${id}.mjs`)121+ const describe = join(dirname(entry), `.harness-describe-${id}.mjs`)122+ await writeFile(123+ bootstrap,124+ [125+ `import * as entry from ${JSON.stringify(entryPath)}`,126+ `import { runHarnessWorker } from ${JSON.stringify(workerModule)}`,127+ `await runHarnessWorker(entry[${JSON.stringify(exportName)}])`,128+ ].join('\n'),129+ )130+ await writeFile(131+ describe,132+ [133+ `const entry = await import(${JSON.stringify(entryPath)})`,134+ `const harness = entry[${JSON.stringify(exportName)}]`,135+ `if (!harness || harness.kind !== 'tanstack-ai-harness') throw new Error('Export ${exportName} of ${entry.replace(/\\/g, '/')} is not a harness.')`,@@ -0,0 +253,21 @@253+ const frame = JSON.parse(line) as HostFrame254+ for (const listener of listeners) listener(frame)255+ } catch {256+ // A line that is not a frame (for example a stray log) is skipped.257+ }258+ })259+ const send = (frame: object) =>260+ child.stdin.write(`${JSON.stringify(frame)}\n`)261+ send({ type: 'harness.subscribe', threadId })262+ return {263+ send,264+ frames: (listener) => {265+ listeners.add(listener)266+ return () => listeners.delete(listener)267+ },268+ kill: () => {269+ child.stdin.end()270+ child.kill()271+ },272+ }273+}@@ -56,0 +82,21 @@82+/** Stream the SSE `data:` payloads of a response. */83+async function* sseData(response: Response): AsyncGenerator<unknown> {84+ if (!response.body) return85+ const reader = response.body.getReader()86+ const decoder = new TextDecoder()87+ let buffer = ''88+ while (true) {89+ const { value, done } = await reader.read()90+ if (done) break91+ buffer += decoder.decode(value, { stream: true })92+ const blocks = buffer.split('\n\n')93+ buffer = blocks.pop() ?? ''94+ for (const block of blocks) {95+ const data = block96+ .split('\n')97+ .find((line) => line.startsWith('data: '))98+ ?.slice(6)99+ if (data) yield JSON.parse(data)100+ }101+ }102+}@@ -56,0 +107,21 @@107+ return {108+ kind: 'text',109+ name: 'harness-remote',110+ model: base,111+ '~types': TYPES,112+ structuredOutput: () =>113+ Promise.reject(114+ new Error('harnessText does not support structured output.'),115+ ),116+ chatStream: (chatOptions) =>117+ (async function* (): AsyncGenerator<StreamChunk> {118+ const threadId = chatOptions.threadId ?? 'default'119+ const runId = chatOptions.runId ?? `harness-${Date.now().toString(36)}`120+ const response = await doFetch(`${base}/run`, {121+ method: 'POST',122+ headers: {123+ 'Content-Type': 'application/json',124+ ...(remote.token125+ ? { Authorization: `Bearer ${remote.token}` }126+ : {}),127+ },@@ -0,0 +39,21 @@39+ try {40+ for await (const line of lines) {41+ if (line.trim() === '') continue42+ try {43+ const frame = parseControlFrame(line)44+ if (frame.type === 'harness.subscribe') {45+ if (session) throw new Error('Already subscribed.')46+ session = await host.open(harness, { threadId: frame.threadId })47+ send({48+ type: 'harness.hello',49+ v: HARNESS_PROTOCOL_VERSION,50+ threadId: frame.threadId,51+ })52+ const events = session.events({53+ ...(frame.from ? { from: frame.from } : {}),54+ signal: reader.signal,55+ })56+ void (async () => {57+ for await (const entry of events)58+ send({ type: 'harness.event', ...entry })59+ })()@@ -48,3 +52,20 @@4852 const host = createHarnessHost({ persistence })4953 try {5054 const session = await host.open(harness, { threadId: 'e2e-thread' })55+ if (body.scenario === 'remote') {56+ // A harness on "another machine": the protocol route of this app,57+ // called over HTTP.58+ const remote = harnessText({59+ url: new URL('/api/harness-protocol', request.url).href,60+ token: 'e2e-token',61+ })62+ let answer = ''63+ for await (const chunk of chat({64+ adapter: remote,65+ messages: [{ role: 'user', content: '[harness-protocol] hello' }],66+ threadId: `remote-${testId ?? 'default'}`,67+ })) {68+ if (chunk.type === 'TEXT_MESSAGE_CONTENT') answer += chunk.delta69+ }70+ return Response.json({ answer })71+ }
AlemTuzlak closed this
Sign in to join this conversation.
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository: TanStack/ai/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
2beb2ad9-d2b5-4973-9484-6dd68a3c442b📥 Commits
Reviewing files that changed from the base of the PR and between b68dd4776275bd9bbef52b7a501ea9da7649dfee and 59aae84ae057aad5685a18e19d360e42a5dcc7f4.
📒 Files selected for processing (1)
docs/config.jsonIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 1 remain after this review.
📝 Walkthrough
Walkthrough#
Adds NDJSON worker sessions, APIs to build and run harness artifacts, and remote harness support in
harnessText. Adds package exports, deployment documentation, and tests for worker, artifact, and remote request flows.Changes#
Harness deployment and remote access
packages/ai-harness/src/worker.ts,packages/ai-harness/tests/build.test.ts,packages/ai-harness/tests/remote-worker.test.tsrunHarnessWorkerto process subscription, snapshot, and input frames, stream events, and close the host when input ends. Tests cover session frames and worker edge cases.packages/ai-harness/src/build.ts,packages/ai-harness/package.json,packages/ai-harness/vite.config.ts,packages/ai-harness/tests/build-stub.test.ts,packages/ai-harness/tests/build.test.ts,docs/config.json,docs/harness/deploy.md,.changeset/harness-p5-build.mdartifactText, which verifies bundle digests and manages workers per thread. Adds package entry points, build tests, a changeset, and deployment documentation.packages/ai-harness/src/harness-text.ts,packages/ai-harness/src/index.ts,packages/ai-harness/tests/build.test.ts,packages/ai-harness/tests/remote-worker.test.ts,testing/e2e/src/routes/api.harness-test.ts,testing/e2e/tests/harness.spec.ts,docs/harness/deploy.mdharnessText, with bearer-token requests, SSE event forwarding, and error handling. Adds remote adapter tests, an end-to-end scenario, and documentation for remote connections.Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~30 minutes
Change: Feature
Sequence Diagram(s)#
Merge Risk: 🟡 Moderate · up to
59aaeWorker failures may hang artifact streams or crash the host, and remote calls over HTTP may expose bearer credentials. These deployment risks remain relevant to the new harness paths.
Security Architecture Review#
Security architecture risk: 🟠 High · up to
59aaeThe documented cross-machine setup sends a service bearer token over HTTP, where someone on the network could capture and reuse it. Worker failures can also leave active requests waiting indefinitely. The remote setup is optional, but its recommended configuration makes the credential exposure significant.
Retained concerns
Security review details
Security Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 10 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share