summaryrefslogtreecommitdiffhomepage
path: root/src/app/App.test.ts
blob: 1534d1caf34237781b8d8d67e4fc22425565d3dc (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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import type { WsServerMessage } from "@dispatch/transport-contract";
import type { SurfaceServerMessage } from "@dispatch/ui-contract";
import { render, screen } from "@testing-library/svelte";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import type { WebSocketLike } from "../adapters/ws";
import App from "./App.svelte";
import { createAppStore } from "./store.svelte";

interface FakeSocket extends WebSocketLike {
	sent: string[];
	resolveOpen(): void;
	feedServerMessage(data: WsServerMessage): void;
	feedSurfaceMessage(data: SurfaceServerMessage): void;
}

function fakeSocket(): FakeSocket {
	let onopen: (() => void) | null = null;
	let onmessage: ((ev: { data: string }) => void) | null = null;
	const sent: string[] = [];

	const ws: FakeSocket = {
		send(data: string) {
			sent.push(data);
		},
		close() {},
		get onopen() {
			return onopen;
		},
		set onopen(fn) {
			onopen = fn;
		},
		get onmessage() {
			return onmessage;
		},
		set onmessage(fn) {
			onmessage = fn;
		},
		get onclose() {
			return null;
		},
		set onclose(_fn) {},
		resolveOpen() {
			onopen?.();
		},
		feedServerMessage(msg: WsServerMessage) {
			onmessage?.({ data: JSON.stringify(msg) });
		},
		feedSurfaceMessage(msg: SurfaceServerMessage) {
			onmessage?.({ data: JSON.stringify(msg) });
		},
		sent,
	};
	return ws;
}

function fakeFetchImpl(): typeof fetch {
	return async (input: string | URL | Request): Promise<Response> => {
		const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
		if (url.endsWith("/models")) {
			return new Response(JSON.stringify({ models: ["opencode/deepseek-v4-flash"] }), {
				status: 200,
			});
		}
		return new Response(JSON.stringify({ chunks: [], latestSeq: 0 }), { status: 200 });
	};
}

function createFakeStorage(): Storage {
	const map = new Map<string, string>();
	return {
		get length() {
			return map.size;
		},
		clear() {
			map.clear();
		},
		getItem(key: string): string | null {
			return map.get(key) ?? null;
		},
		key(_index: number): string | null {
			return null;
		},
		removeItem(key: string) {
			map.delete(key);
		},
		setItem(key: string, value: string) {
			map.set(key, value);
		},
	};
}

function sentMessages(ws: FakeSocket) {
	return ws.sent.map((s) => JSON.parse(s));
}

function activeConversationId(store: ReturnType<typeof createAppStore>): string {
	const id = store.activeConversationId;
	expect(id).not.toBeNull();
	return id as string;
}

describe("App component interaction tests", () => {
	it("renders the model selector and composer in draft mode", () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		render(App, { props: { store } });

		expect(screen.getByRole("textbox", { name: "Message input" })).toBeInTheDocument();
		expect(screen.getByRole("button", { name: "Send" })).toBeInTheDocument();
		expect(screen.getByRole("combobox", { name: "Model selector" })).toBeInTheDocument();

		store.dispose();
	});

	it("auto-subscribes to every catalog entry on render (no buttons to click)", () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		ws.sent.length = 0;
		ws.feedSurfaceMessage({
			type: "catalog",
			catalog: [
				{ id: "s1", region: "sidebar", title: "Surface One" },
				{ id: "s2", region: "panel", title: "Surface Two" },
			],
		});

		render(App, { props: { store } });

		const subscribed = sentMessages(ws)
			.filter((m: { type: string }) => m.type === "subscribe")
			.map((m: { surfaceId: string }) => m.surfaceId);
		expect(subscribed).toContain("s1");
		expect(subscribed).toContain("s2");

		store.dispose();
	});

	it("renders every surface expanded once their specs arrive", async () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		ws.feedSurfaceMessage({
			type: "catalog",
			catalog: [
				{ id: "s1", region: "sidebar", title: "Surface One" },
				{ id: "s2", region: "panel", title: "Surface Two" },
			],
		});

		render(App, { props: { store } });

		// No interaction: specs arrive and both surfaces render expanded.
		ws.feedSurfaceMessage({
			type: "surface",
			spec: {
				id: "s1",
				region: "sidebar",
				title: "Surface One",
				fields: [{ kind: "stat", label: "Tokens", value: "1,234" }],
			},
		});
		ws.feedSurfaceMessage({
			type: "surface",
			spec: { id: "s2", region: "panel", title: "Surface Two", fields: [] },
		});

		expect(await screen.findByRole("heading", { name: "Surface One" })).toBeInTheDocument();
		expect(await screen.findByRole("heading", { name: "Surface Two" })).toBeInTheDocument();
		expect(await screen.findByText("Tokens")).toBeInTheDocument();
		expect(await screen.findByText("1,234")).toBeInTheDocument();

		store.dispose();
	});

	it("an error message renders the alert banner", () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		ws.feedSurfaceMessage({
			type: "error",
			message: "Something went wrong",
		});

		render(App, { props: { store } });

		const alert = screen.getByRole("alert");
		expect(alert).toHaveTextContent("Something went wrong");

		store.dispose();
	});

	it("invoking a field action sends an invoke", async () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		ws.feedSurfaceMessage({
			type: "catalog",
			catalog: [{ id: "s1", region: "sidebar", title: "Surface One" }],
		});

		render(App, { props: { store } });

		const user = userEvent.setup();
		// Surface is auto-subscribed; its spec arrives and renders expanded.
		ws.feedSurfaceMessage({
			type: "surface",
			spec: {
				id: "s1",
				region: "sidebar",
				title: "Surface One",
				fields: [
					{
						kind: "toggle",
						label: "Dark Mode",
						value: false,
						action: { actionId: "toggle-dark" },
					},
				],
			},
		});

		ws.sent.length = 0;
		const checkbox = await screen.findByRole("checkbox", { name: "Dark Mode" });
		await user.click(checkbox);

		const msgs = sentMessages(ws);
		const invoke = msgs.find(
			(m: { type: string; surfaceId: string; actionId: string; payload: unknown }) =>
				m.type === "invoke" &&
				m.surfaceId === "s1" &&
				m.actionId === "toggle-dark" &&
				m.payload === true,
		);
		expect(invoke).toBeTruthy();

		store.dispose();
	});

	it("typing and sending a message posts chat.send on the socket", async () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		render(App, { props: { store } });

		const user = userEvent.setup();
		const textarea = screen.getByRole("textbox", { name: "Message input" });
		await user.type(textarea, "hello from UI");

		ws.sent.length = 0;
		const sendBtn = screen.getByRole("button", { name: "Send" });
		await user.click(sendBtn);

		const msgs = sentMessages(ws);
		const chatSend = msgs.find((m: { type: string }) => m.type === "chat.send") as
			| { type: string; conversationId: string; message: string }
			| undefined;
		expect(chatSend).toBeTruthy();
		expect(chatSend?.message).toBe("hello from UI");

		store.dispose();
	});

	it("incoming chat.delta renders text in the chat transcript", async () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		// Promote draft to tab
		store.send("test");
		const convId = activeConversationId(store);

		render(App, { props: { store } });

		ws.feedServerMessage({
			type: "chat.delta",
			event: {
				type: "turn-start",
				conversationId: convId,
				turnId: "turn-1",
			},
		});

		ws.feedServerMessage({
			type: "chat.delta",
			event: {
				type: "text-delta",
				conversationId: convId,
				turnId: "turn-1",
				delta: "Hi there!",
			},
		});

		expect(await screen.findByText("Hi there!")).toBeInTheDocument();

		store.dispose();
	});

	it("renders a custom 'table' field of a surface as a table", async () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		ws.feedSurfaceMessage({
			type: "catalog",
			catalog: [{ id: "s1", region: "sidebar", title: "Surface One" }],
		});

		render(App, { props: { store } });

		// Auto-subscribed; the custom-table spec arrives and renders expanded.
		ws.feedSurfaceMessage({
			type: "surface",
			spec: {
				id: "s1",
				region: "sidebar",
				title: "Surface One",
				fields: [
					{
						kind: "custom",
						rendererId: "table",
						payload: {
							columns: ["Name", "Scope"],
							rows: [["cache-warm", "backend"]],
						},
					},
				],
			},
		});

		expect(await screen.findByRole("columnheader", { name: "Name" })).toBeInTheDocument();
		expect(await screen.findByText("cache-warm")).toBeInTheDocument();
		expect(await screen.findByText("backend")).toBeInTheDocument();

		store.dispose();
	});

	it("the Extensions view lists frontend modules aggregated from feature manifests", () => {
		const ws = fakeSocket();
		const store = createAppStore({
			socketFactory: () => ws,
			fetchImpl: fakeFetchImpl(),
			localStorage: createFakeStorage(),
		});
		ws.resolveOpen();

		render(App, { props: { store } });

		// Extensions is the default view, so the modules table renders immediately.
		expect(screen.getByRole("columnheader", { name: "Module" })).toBeInTheDocument();
		for (const name of [
			"chat",
			"tabs",
			"surface-host",
			"views",
			"conversation-cache",
			"markdown",
		]) {
			expect(screen.getByRole("cell", { name })).toBeInTheDocument();
		}

		store.dispose();
	});
});