Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCode2Client.test.ts

250 lines9.3 KB

1import { assert, it } from "@effect/vitest";
2import { Session } from "@opencode/client/effect";
3import * as Cause from "effect/Cause";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Redacted from "effect/Redacted";
9import * as Schema from "effect/Schema";
10import * as TestClock from "effect/testing/TestClock";
11import * as UrlParams from "effect/http/UrlParams";
12import * as HttpClient from "effect/http/HttpClient";
13import * as HttpClientResponse from "effect/http/HttpClientResponse";
14import { describe } from "vite-plus/test";
15​
16import * as OpenCode2Client from "./OpenCode2Client.ts";
17​
18const INFO_BODY = '{"version":"2.0.18","pid":4242,"urls":[],"paths":{"tmp":"/tmp"}}';
19​
20const authorizationFor = (password: string | Redacted.Redacted) => {
21 const seen: Array<string | undefined> = [];
22 const layerCapturing = Layer.succeed(
23 HttpClient.HttpClient,
24 HttpClient.make((request) =>
25 Effect.sync(() => {
26 seen.push(request.headers.authorization);
27 return HttpClientResponse.fromWeb(
28 request,
29 new Response(INFO_BODY, { headers: { "content-type": "application/json" } }),
30 );
31 }),
32 ),
33 );
34 return Effect.gen(function* () {
35 const opencode = yield* OpenCode2Client.OpenCode2Client;
36 const { client } = yield* opencode.connect({ baseUrl: "http://127.0.0.1:4096", password });
37 yield* client.server.info();
38 return seen[0];
39 }).pipe(Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(layerCapturing))));
40};
41​
42const utf8Basic = (password: string) =>
43 `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`;
44​
45describe("OpenCode2Client authorization", () => {
46 // OpenCode requires UTF-8 Basic auth; btoa rejects or misencodes non-ASCII.
47 it.effect("encodes non-ASCII passwords as UTF-8", () =>
48 Effect.gen(function* () {
49 assert.strictEqual(yield* authorizationFor("pässwörd"), utf8Basic("pässwörd"));
50 assert.strictEqual(yield* authorizationFor("pass€word"), utf8Basic("pass€word"));
51 assert.strictEqual(yield* authorizationFor(Redacted.make("pässwörd")), utf8Basic("pässwörd"));
52 }),
53 );
54});
55​
56describe("OpenCode2Client event subscription", () => {
57 it.effect("times out and cancels a subscription with no response headers", () =>
58 Effect.gen(function* () {
59 const cancelled = yield* Deferred.make<void>();
60 const transport = Layer.succeed(
61 HttpClient.HttpClient,
62 HttpClient.make((request) => {
63 assert.strictEqual(request.url, "http://127.0.0.1:4096/api/event");
64 return Effect.never.pipe(Effect.ensuring(Deferred.succeed(cancelled, undefined)));
65 }),
66 );
67 const opencode = yield* OpenCode2Client.OpenCode2Client.pipe(
68 Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(transport))),
69 );
70 const { events } = yield* opencode.connect({
71 baseUrl: "http://127.0.0.1:4096",
72 password: "test-password",
73 });
74 const opening = yield* events.pipe(Effect.flip, Effect.forkScoped);
75​
76 yield* TestClock.adjust("10 seconds");
77 assert.isTrue(yield* Deferred.isDone(cancelled));
78 const error = yield* Fiber.join(opening);
79 assert.strictEqual(error._tag, "HttpClientError");
80 assert.strictEqual(error.reason._tag, "TransportError");
81 assert.isTrue(Cause.isTimeoutError(error.cause));
82 }).pipe(Effect.scoped),
83 );
84});
85​
86const previous = {
87 id: "msg_repro088",
88 type: "synthetic",
89 text: "Fixture message 88",
90 time: { created: 1088 },
91};
92​
93const compaction = (fields: Record<string, unknown>) => ({
94 type: "compaction",
95 id: "msg_repro089",
96 time: { created: 1089 },
97 reason: "manual",
98 summary: "Fixture compaction",
99 ...fields,
100});
101​
102const listHistory = (messages: ReadonlyArray<unknown>) =>
103 Effect.gen(function* () {
104 const transport = Layer.succeed(
105 HttpClient.HttpClient,
106 HttpClient.make((request) =>
107 Effect.sync(() => {
108 assert.include(request.url, "/api/session/ses_repro/message");
109 return HttpClientResponse.fromWeb(
110 request,
111 new Response(JSON.stringify({ data: messages, cursor: {} }), {
112 headers: { "content-type": "application/json" },
113 }),
114 );
115 }),
116 ),
117 );
118 const opencode = yield* OpenCode2Client.OpenCode2Client.pipe(
119 Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(transport))),
120 );
121 const { client } = yield* opencode.connect({
122 baseUrl: "http://127.0.0.1:4096",
123 password: "test-password",
124 });
125 return yield* client.message.list({ sessionID: Session.ID.make("ses_repro"), order: "asc" });
126 });
127​
128describe("OpenCode2Client message history", () => {
129 it.effect.each([
130 { status: "running", shape: "native keepID", fields: { metadata: { keepID: previous.id } } },
131 { status: "completed", shape: "native keepID", fields: { metadata: { keepID: previous.id } } },
132 { status: "running", shape: "native without metadata", fields: {} },
133 { status: "completed", shape: "native without metadata", fields: {} },
134 {
135 status: "completed",
136 shape: "legacy metadata",
137 fields: { metadata: { recent: previous.id } },
138 },
139 { status: "running", shape: "top-level", fields: { recent: previous.id } },
140 ] as const)("decodes a $status compaction in the $shape format", ({ status, fields }) =>
141 Effect.gen(function* () {
142 const history = yield* listHistory([previous, compaction({ status, ...fields })]);
143​
144 assert.deepStrictEqual(
145 history.data.map((message) => message.id),
146 [previous.id, "msg_repro089"],
147 );
148 assert.deepInclude(history.data[1], {
149 type: "compaction",
150 status,
151 summary: "Fixture compaction",
152 recent:
153 "metadata" in fields && "recent" in fields.metadata ? previous.id : (fields.recent ?? ""),
154 });
155 }),
156 );
157​
158 it.effect.each([
159 { field: "recent", fields: { status: "completed", recent: 42 } },
160 { field: "reason", fields: { status: "completed", reason: "scheduled", recent: previous.id } },
161 ] as const)("keeps a compaction with an invalid $field an error", ({ field, fields }) =>
162 Effect.gen(function* () {
163 const error = yield* listHistory([compaction(fields)]).pipe(Effect.flip);
164​
165 assert.strictEqual(error._tag, "ClientError");
166 assert.isTrue(Schema.isSchemaError(error.cause));
167 assert.include(String(error.cause), field);
168 }),
169 );
170});
171​
172describe("OpenCode2Client native image jobs", () => {
173 it.effect.each([
174 { path: "/work/image.png", location: "/work" },
175 { path: "/tmp/images/session/image.png", location: "/tmp/images/session" },
176 ])("reads remote image $path through its native filesystem location", ({ path, location }) =>
177 Effect.gen(function* () {
178 const transport = HttpClient.make((request) =>
179 Effect.sync(() => {
180 assert.strictEqual(request.url, "http://remote.test/api/fs/read/image.png");
181 assert.deepEqual(UrlParams.toRecord(request.urlParams), {
182 "location[directory]": location,
183 });
184 return HttpClientResponse.fromWeb(
185 request,
186 new Response(Buffer.from("iVBORw0KGgo=", "base64")),
187 );
188 }),
189 );
190 const service = yield* OpenCode2Client.make.pipe(
191 Effect.provideService(HttpClient.HttpClient, transport),
192 );
193 const api = yield* service.connect({ baseUrl: "http://remote.test", password: "secret" });
194 assert.deepEqual(yield* api.readImage(path, "/work"), {
195 uri: "data:image/png;base64,iVBORw0KGgo=",
196 mime: "image/png",
197 });
198 }),
199 );
200​
201 it.effect("rejects remote previews above the shared image limit", () =>
202 Effect.gen(function* () {
203 const transport = HttpClient.make((request) =>
204 Effect.succeed(
205 HttpClientResponse.fromWeb(request, new Response(new Uint8Array(11 * 1024 * 1024))),
206 ),
207 );
208 const service = yield* OpenCode2Client.make.pipe(
209 Effect.provideService(HttpClient.HttpClient, transport),
210 );
211 const api = yield* service.connect({ baseUrl: "http://remote.test", password: "secret" });
212 const result = yield* api.readImage("/work/image.png", "/work").pipe(Effect.result);
213 assert.equal(result._tag, "Failure");
214 }),
215 );
216​
217 it.effect("reads scoped image jobs without accepting other sessions or job kinds", () =>
218 Effect.gen(function* () {
219 const job = {
220 kind: "image",
221 id: "image_test",
222 sessionID: "ses_owner",
223 status: "running",
224 path: "/work/image",
225 model: "test/image",
226 } as const;
227 const transport = HttpClient.make((request) =>
228 Effect.sync(() => {
229 assert.strictEqual(request.headers.authorization, utf8Basic("secret"));
230 return HttpClientResponse.fromWeb(
231 request,
232 Response.json({
233 data: [
234 job,
235 { ...job, sessionID: "ses_other" },
236 { ...job, kind: "shell" },
237 { ...job, status: "future" },
238 ],
239 }),
240 );
241 }),
242 );
243 const service = yield* OpenCode2Client.make.pipe(
244 Effect.provideService(HttpClient.HttpClient, transport),
245 );
246 const api = yield* service.connect({ baseUrl: "http://remote.test", password: "secret" });
247 assert.deepEqual(yield* api.imageJobs("ses_owner"), [job]);
248 }),
249 );
250});