summaryrefslogtreecommitdiffhomepage
path: root/packages/cli/src/http.test.ts
blob: becfdbbc7263db0ba34950b92f25ccc48c355f6f (plain)
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
import type { AgentEvent } from "@dispatch/transport-contract";
import { describe, expect, it } from "vitest";
import { fetchModels, streamChat } from "./http.js";

function ndjsonLines(...events: AgentEvent[]): string {
	return `${events.map((e) => JSON.stringify(e)).join("\n")}\n`;
}

function makeFakeFetch(responseBody: string, headers?: Record<string, string>) {
	const fn = async (_url: string | URL | Request, _init?: RequestInit): Promise<Response> => {
		const encoder = new TextEncoder();
		const chunks = responseBody.split("|||");
		let i = 0;
		const stream = new ReadableStream<Uint8Array>({
			pull(controller) {
				if (i < chunks.length) {
					const chunk = chunks[i];
					if (chunk !== undefined) controller.enqueue(encoder.encode(chunk));
					i++;
				} else {
					controller.close();
				}
			},
		});
		return new Response(stream, {
			status: 200,
			headers: headers ?? {},
		});
	};
	return fn as unknown as typeof fetch;
}

describe("streamChat", () => {
	it("parses NDJSON events and returns conversationId", async () => {
		const event1: AgentEvent = {
			type: "text-delta",
			conversationId: "c1",
			turnId: "t1",
			delta: "Hello",
		};
		const event2: AgentEvent = {
			type: "done",
			conversationId: "c1",
			turnId: "t1",
			reason: "completed",
		};

		const body = ndjsonLines(event1, event2);
		const fakeFetch = makeFakeFetch(body, { "X-Conversation-Id": "c1" });

		const { conversationId, events } = await streamChat(
			{ fetchImpl: fakeFetch },
			{
				server: "http://localhost:24203",
				request: { message: "hi", model: "openai/gpt-4" },
			},
		);

		expect(conversationId).toBe("c1");

		const collected: AgentEvent[] = [];
		for await (const e of events) {
			collected.push(e);
		}

		expect(collected).toEqual([event1, event2]);
	});

	it("handles NDJSON split across chunks", async () => {
		const event1: AgentEvent = {
			type: "text-delta",
			conversationId: "c",
			turnId: "t",
			delta: "Hi",
		};
		const event2: AgentEvent = {
			type: "usage",
			conversationId: "c",
			turnId: "t",
			usage: { inputTokens: 10, outputTokens: 5 },
		};

		const fullNdjson = ndjsonLines(event1, event2);
		// Split mid-line: after 20 chars
		const mid = 20;
		const chunk1 = fullNdjson.slice(0, mid);
		const chunk2 = fullNdjson.slice(mid);

		const fakeFetch = makeFakeFetch(`${chunk1}|||${chunk2}`, {
			"X-Conversation-Id": "c",
		});

		const { events } = await streamChat(
			{ fetchImpl: fakeFetch },
			{
				server: "http://localhost:24203",
				request: { message: "hi" },
			},
		);

		const collected: AgentEvent[] = [];
		for await (const e of events) {
			collected.push(e);
		}

		expect(collected).toEqual([event1, event2]);
	});

	it("throws on non-OK status", async () => {
		const fakeFetch = (async (): Promise<Response> =>
			new Response("not found", { status: 404 })) as unknown as typeof fetch;

		await expect(
			streamChat(
				{ fetchImpl: fakeFetch },
				{
					server: "http://localhost:24203",
					request: { message: "hi" },
				},
			),
		).rejects.toThrow("POST /chat failed with status 404");
	});

	it("throws when response has no body", async () => {
		const fakeFetch = (async (): Promise<Response> =>
			new Response(null, { status: 200 })) as unknown as typeof fetch;

		await expect(
			streamChat(
				{ fetchImpl: fakeFetch },
				{
					server: "http://localhost:24203",
					request: { message: "hi" },
				},
			),
		).rejects.toThrow("no body");
	});
});

describe("fetchModels", () => {
	it("returns ModelsResponse on success", async () => {
		const models = { models: ["openai/gpt-4", "anthropic/claude-3"] };
		const fakeFetch = (async (): Promise<Response> =>
			new Response(JSON.stringify(models), {
				status: 200,
				headers: { "Content-Type": "application/json" },
			})) as unknown as typeof fetch;

		const result = await fetchModels(
			{ fetchImpl: fakeFetch },
			{ server: "http://localhost:24203" },
		);
		expect(result).toEqual(models);
	});

	it("throws on non-OK status", async () => {
		const fakeFetch = (async (): Promise<Response> =>
			new Response("server error", { status: 500 })) as unknown as typeof fetch;

		await expect(
			fetchModels({ fetchImpl: fakeFetch }, { server: "http://localhost:24203" }),
		).rejects.toThrow("GET /models failed with status 500");
	});
});