Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions apps/web/modules/nova/harness/bridge-messages.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { expect, spyOn, test } from "bun:test"

import { startSchema } from "../../../../supercode-cli/server/src/nova-bridge/protocol"
import { formatLocalAttachmentsContext, localAttachmentsSchema } from "../attachments/contracts"
import { prepareBridgeMessages, streamOriginalHarness } from "./bridge"
import { createBridgeFixture } from "./bridge-fixture.test-helper"

test("packed local files reach the CLI bridge without violating its message limit", async () => {
const files = localAttachmentsSchema.parse(Array.from({ length: 2 }, (_, index) => ({
id: `source-${index}`, name: `source-${index}.ts`, kind: "text", mediaType: "text/plain", size: 120_000, text: "x".repeat(120_000),
})))
const content = formatLocalAttachmentsContext(files)
const body = { version: "nova-cli-harness/1", mode: "agent", messages: [{ role: "user", content }], tools: [], budget: 30 }
expect(startSchema.safeParse(body).success).toBe(false)
let forwarded: unknown
const fixture = createBridgeFixture()
const fetchSpy = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async (_url: Parameters<typeof fetch>[0], options?: Parameters<typeof fetch>[1]) => {
const request = new Request(String(_url), options)
const value = JSON.parse(String(options?.body))
if (new URL(request.url).pathname.endsWith("/turn")) {
forwarded = value
const parsed = startSchema.safeParse(forwarded)
if (!parsed.success) return Response.json({ error: "Invalid CLI harness protocol" }, { status: 400 })
expect(parsed.data.messages.map((message) => message.content).join("")).toBe(content)
}
return await fixture(request, value) ?? new Response(null, { status: 404 })
}, { preconnect: globalThis.fetch.preconnect }))
try {
const events = []
for await (const event of streamOriginalHarness({
token: "fixture", provider: "fixture", model: "fixture", mode: "agent", messages: [{ role: "user", content }], tools: [], execute: async () => ({}),
chatTransport: async function* (input) {
expect(input.messages.filter((message) => message.role === "user").map((message) => message.content).join("")).toBe(content)
yield { type: "text", content: "Read the packed sources." }
yield { type: "finish", reason: "stop" }
},
})) events.push(event)
expect(events.some((event) => event.type === "finish")).toBe(true)
expect(startSchema.safeParse(forwarded).success).toBe(true)
} finally {
fetchSpy.mockRestore()
}
})

test("bridge splitting preserves roles, order, and Unicode without mutating messages", () => {
const content = "a".repeat(199_999) + "😀" + "b".repeat(200_001)
const original = [{ role: "user" as const, content }]
const prepared = prepareBridgeMessages(original)
expect(prepared.map((message) => message.content).join("")).toBe(content)
expect(prepared.every((message) => message.role === "user" && String(message.content).length <= 200_000)).toBe(true)
expect(prepared[0]?.content).toBe("a".repeat(199_999))
expect(original).toEqual([{ role: "user", content }])
const small = { role: "system" as const, content: "Keep this first" }
expect(prepareBridgeMessages([small, ...original])[0]).toBe(small)
})

test("oversized conversation counts fail explicitly rather than losing source context", () => {
expect(() => prepareBridgeMessages(Array.from({ length: 101 }, () => ({ role: "user", content: "source" })))).toThrow("100-message limit")
})
23 changes: 21 additions & 2 deletions apps/web/modules/nova/harness/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@ import { InteractionPending, type createDurableJournal } from "./durable"
import { terminalHarnessUrl, streamHarnessChat, type HarnessChatMessage, type HarnessChatTool, type HarnessStreamEvent } from "./client"

const VERSION = "nova-cli-harness/1"

export function prepareBridgeMessages(messages: HarnessChatMessage[]): HarnessChatMessage[] {
const prepared = messages.flatMap((message) => {
if (typeof message.content !== "string" || message.content.length <= 200_000) return [message]
const parts: HarnessChatMessage[] = []
for (let start = 0; start < message.content.length;) {
let end = Math.min(start + 200_000, message.content.length)
const last = message.content.charCodeAt(end - 1)
if (end < message.content.length && last >= 0xd800 && last <= 0xdbff) end--
parts.push({ ...message, content: message.content.slice(start, end) })
start = end
}
return parts
})
if (prepared.length > 100) throw new Error("Local context exceeds the CLI harness's 100-message limit. Start a new thread or select fewer files.")
return prepared
}
export type BridgeEvent = HarnessStreamEvent | { type: "tool-result"; toolName: string; toolCallId: string; args: Record<string, unknown>; content: string; status: "completed" | "failed" | "denied"; message: string }
export type BridgeInput = {
token: string
Expand All @@ -29,11 +46,13 @@ export async function* streamOriginalHarness(input: BridgeInput): AsyncGenerator
const headers = { Authorization: `Bearer ${input.token}`, "Content-Type": "application/json", Accept: "application/x-ndjson" }
const response = await fetch(`${terminalHarnessUrl()}/api/nova/harness/turn`, {
method: "POST", headers, signal: input.signal, cache: "no-store", redirect: "error",
body: JSON.stringify({ version: VERSION, mode: input.mode, messages: input.messages, tools: input.tools, budget: input.budget ?? 30 }),
body: JSON.stringify({ version: VERSION, mode: input.mode, messages: prepareBridgeMessages(input.messages), tools: input.tools, budget: input.budget ?? 30 }),
})
if (!response.ok || !response.body) {
await response.body?.cancel()
throw new Error(`Original CLI harness bridge unavailable (HTTP ${response.status}). Deploy matching CLI server and Nova versions.`)
throw new Error(response.status === 400
? "CLI harness rejected the request (HTTP 400). Check message and tool limits and CLI server compatibility."
: `Original CLI harness bridge unavailable (HTTP ${response.status}). Check CLI server availability and compatibility.`)
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
Expand Down
Loading