forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpapi-exercise.ts
More file actions
2014 lines (1933 loc) · 71.9 KB
/
httpapi-exercise.ts
File metadata and controls
2014 lines (1933 loc) · 71.9 KB
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* End-to-end exerciser for the legacy Hono instance routes and the Effect HttpApi routes.
*
* The goal is not to be a normal unit test file. This is a route-coverage and parity
* harness we can run while deleting Hono: every public route should eventually have a
* small scenario that proves the Effect route decodes requests, uses the right instance
* context, mutates storage when expected, and returns a compatible response shape.
*
* The script intentionally isolates `OPENCODE_DB` before importing modules that touch
* storage. Scenarios may create/delete sessions and reset the database after each run,
* so this must never point at a developer's real session database.
*
* DSL shape:
* - `http.get/post/...` starts a scenario for one OpenAPI route key.
* - `.seeded(...)` creates typed per-scenario state using Effect helpers on `ctx`.
* - `.at(...)` builds the request from that typed state.
* - `.json(...)` / `.jsonEffect(...)` assert response shape and optional side effects.
* - `.mutating()` tells parity mode to run Effect and Hono in separate isolated contexts
* so destructive routes compare equivalent fresh setups instead of sharing one DB.
*/
import { Cause, ConfigProvider, Effect, Layer } from "effect"
import { HttpRouter } from "effect/unstable/http"
import { OpenApi } from "effect/unstable/httpapi"
import { Flag } from "@opencode-ai/core/flag/flag"
import { TestLLMServer } from "../test/lib/llm-server"
import type { Config } from "../src/config/config"
import { MessageID, PartID, type SessionID } from "../src/session/schema"
import { ModelID, ProviderID } from "../src/provider/schema"
import type { MessageV2 } from "../src/session/message-v2"
import type { Worktree } from "../src/worktree"
import type { Project } from "../src/project/project"
import path from "path"
const preserveExerciseGlobalRoot = !!process.env.OPENCODE_HTTPAPI_EXERCISE_GLOBAL
const exerciseGlobalRoot =
process.env.OPENCODE_HTTPAPI_EXERCISE_GLOBAL ??
path.join(process.env.TMPDIR ?? "/tmp", `opencode-httpapi-global-${process.pid}`)
process.env.XDG_DATA_HOME = path.join(exerciseGlobalRoot, "data")
process.env.XDG_CONFIG_HOME = path.join(exerciseGlobalRoot, "config")
process.env.XDG_STATE_HOME = path.join(exerciseGlobalRoot, "state")
process.env.XDG_CACHE_HOME = path.join(exerciseGlobalRoot, "cache")
process.env.OPENCODE_DISABLE_SHARE = "true"
const exerciseConfigDirectory = path.join(exerciseGlobalRoot, "config", "opencode")
const exerciseDataDirectory = path.join(exerciseGlobalRoot, "data", "opencode")
const preserveExerciseDatabase = !!process.env.OPENCODE_HTTPAPI_EXERCISE_DB
const exerciseDatabasePath =
process.env.OPENCODE_HTTPAPI_EXERCISE_DB ??
path.join(process.env.TMPDIR ?? "/tmp", `opencode-httpapi-exercise-${process.pid}.db`)
process.env.OPENCODE_DB = exerciseDatabasePath
Flag.OPENCODE_DB = exerciseDatabasePath
void (await import("@opencode-ai/core/util/log")).init({ print: false })
const OpenApiMethods = ["get", "post", "put", "delete", "patch"] as const
const Methods = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const
const color = {
dim: "\x1b[2m",
green: "\x1b[32m",
red: "\x1b[31m",
yellow: "\x1b[33m",
cyan: "\x1b[36m",
reset: "\x1b[0m",
}
type Method = (typeof Methods)[number]
type OpenApiMethod = (typeof OpenApiMethods)[number]
type Mode = "effect" | "parity" | "coverage"
type Backend = "effect" | "legacy"
type Comparison = "none" | "status" | "json"
type CaptureMode = "full" | "stream"
type ProjectOptions = { git?: boolean; config?: Partial<Config.Info>; llm?: boolean }
type OpenApiSpec = { paths?: Record<string, Partial<Record<OpenApiMethod, unknown>>> }
type JsonObject = Record<string, unknown>
type Options = {
mode: Mode
include: string | undefined
failOnMissing: boolean
failOnSkip: boolean
}
type RequestSpec = {
path: string
headers?: Record<string, string>
body?: unknown
}
type CallResult = {
status: number
contentType: string
body: unknown
text: string
}
type BackendApp = {
request(input: string | URL | Request, init?: RequestInit): Response | Promise<Response>
}
/** Effect-native helpers available while setting up and asserting a scenario. */
type ScenarioContext = {
directory: string | undefined
headers: (extra?: Record<string, string>) => Record<string, string>
file: (name: string, content: string) => Effect.Effect<void>
session: (input?: { title?: string; parentID?: SessionID }) => Effect.Effect<SessionInfo>
sessionGet: (sessionID: SessionID) => Effect.Effect<SessionInfo | undefined>
project: () => Effect.Effect<Project.Info>
message: (sessionID: SessionID, input?: { text?: string }) => Effect.Effect<MessageSeed>
messages: (sessionID: SessionID) => Effect.Effect<MessageV2.WithParts[]>
todos: (sessionID: SessionID, todos: TodoInfo[]) => Effect.Effect<void>
worktree: (input?: { name?: string }) => Effect.Effect<Worktree.Info>
worktreeRemove: (directory: string) => Effect.Effect<void>
llmText: (value: string) => Effect.Effect<void>
llmWait: (count: number) => Effect.Effect<void>
tuiRequest: (request: { path: string; body: unknown }) => Effect.Effect<void>
}
/** Scenario context after `.seeded(...)`; `state` preserves the seed return type in the DSL. */
type SeededContext<S> = ScenarioContext & {
state: S
}
type Scenario = ActiveScenario | TodoScenario
type ActiveScenario = {
kind: "active"
method: Method
path: string
name: string
project: ProjectOptions | undefined
seed: (ctx: ScenarioContext) => Effect.Effect<unknown>
request: (ctx: ScenarioContext, state: unknown) => RequestSpec
expect: (ctx: ScenarioContext, state: unknown, result: CallResult) => Effect.Effect<void>
compare: Comparison
capture: CaptureMode
mutates: boolean
reset: boolean
}
/** Internal builder state stays generic until `.json(...)` erases it into `ActiveScenario`. */
type BuilderState<S> = {
method: Method
path: string
name: string
project: ProjectOptions | undefined
seed: (ctx: ScenarioContext) => Effect.Effect<S>
request: (ctx: SeededContext<S>) => RequestSpec
capture: CaptureMode
mutates: boolean
reset: boolean
}
type TodoScenario = {
kind: "todo"
method: Method
path: string
name: string
reason: string
}
type Result =
| { status: "pass"; scenario: ActiveScenario }
| { status: "fail"; scenario: ActiveScenario; message: string }
| { status: "skip"; scenario: TodoScenario }
type SessionInfo = { id: SessionID; title: string; parentID?: SessionID }
type TodoInfo = { content: string; status: string; priority: string }
type MessageSeed = { info: MessageV2.User; part: MessageV2.TextPart }
const original = {
OPENCODE_EXPERIMENTAL_HTTPAPI: Flag.OPENCODE_EXPERIMENTAL_HTTPAPI,
OPENCODE_SERVER_PASSWORD: Flag.OPENCODE_SERVER_PASSWORD,
OPENCODE_SERVER_USERNAME: Flag.OPENCODE_SERVER_USERNAME,
}
type Runtime = {
PublicApi: (typeof import("../src/server/routes/instance/httpapi/public"))["PublicApi"]
ExperimentalHttpApiServer: (typeof import("../src/server/routes/instance/httpapi/server"))["ExperimentalHttpApiServer"]
Server: (typeof import("../src/server/server"))["Server"]
AppLayer: (typeof import("../src/effect/app-runtime"))["AppLayer"]
InstanceRef: (typeof import("../src/effect/instance-ref"))["InstanceRef"]
Instance: (typeof import("../src/project/instance"))["Instance"]
InstanceStore: (typeof import("../src/project/instance-store"))["InstanceStore"]
Session: (typeof import("../src/session/session"))["Session"]
Todo: (typeof import("../src/session/todo"))["Todo"]
Worktree: (typeof import("../src/worktree"))["Worktree"]
Project: (typeof import("../src/project/project"))["Project"]
Tui: typeof import("../src/server/shared/tui-control")
disposeAllInstances: (typeof import("../test/fixture/fixture"))["disposeAllInstances"]
tmpdir: (typeof import("../test/fixture/fixture"))["tmpdir"]
resetDatabase: (typeof import("../test/fixture/db"))["resetDatabase"]
}
let runtimePromise: Promise<Runtime> | undefined
function runtime() {
return (runtimePromise ??= (async () => {
const publicApi = await import("../src/server/routes/instance/httpapi/public")
const httpApiServer = await import("../src/server/routes/instance/httpapi/server")
const server = await import("../src/server/server")
const appRuntime = await import("../src/effect/app-runtime")
const instanceRef = await import("../src/effect/instance-ref")
const instance = await import("../src/project/instance")
const instanceStore = await import("../src/project/instance-store")
const session = await import("../src/session/session")
const todo = await import("../src/session/todo")
const worktree = await import("../src/worktree")
const project = await import("../src/project/project")
const tui = await import("../src/server/shared/tui-control")
const fixture = await import("../test/fixture/fixture")
const db = await import("../test/fixture/db")
return {
PublicApi: publicApi.PublicApi,
ExperimentalHttpApiServer: httpApiServer.ExperimentalHttpApiServer,
Server: server.Server,
AppLayer: appRuntime.AppLayer,
InstanceRef: instanceRef.InstanceRef,
Instance: instance.Instance,
InstanceStore: instanceStore.InstanceStore,
Session: session.Session,
Todo: todo.Todo,
Worktree: worktree.Worktree,
Project: project.Project,
Tui: tui,
disposeAllInstances: fixture.disposeAllInstances,
tmpdir: fixture.tmpdir,
resetDatabase: db.resetDatabase,
}
})())
}
class ScenarioBuilder<S = undefined> {
private readonly state: BuilderState<S>
constructor(method: Method, path: string, name: string) {
this.state = {
method,
path,
name,
project: { git: true },
seed: () => Effect.succeed(undefined as S),
request: (ctx) => ({ path, headers: ctx.headers() }),
capture: "full",
mutates: false,
reset: true,
}
}
global() {
return this.clone({ project: undefined, request: () => ({ path: this.state.path }) })
}
inProject(project: ProjectOptions = { git: true }) {
return this.clone({ project })
}
withLlm() {
return this.clone({ project: { ...(this.state.project ?? { git: true }), llm: true } })
}
at(request: BuilderState<S>["request"]) {
return this.clone({ request })
}
mutating() {
return this.clone({ mutates: true })
}
preserveDatabase() {
return this.clone({ reset: false })
}
stream() {
return this.clone({ capture: "stream" })
}
/** Assert a non-JSON or shape-only response. */
ok(status = 200, compare: Comparison = "status") {
return this.done(compare, (_ctx, result) =>
Effect.sync(() => {
if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`)
}),
)
}
status(
status = 200,
inspect?: (ctx: SeededContext<S>, result: CallResult) => Effect.Effect<void>,
compare: Comparison = "status",
) {
return this.done(compare, (ctx, result) =>
Effect.gen(function* () {
if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`)
if (inspect) yield* inspect(ctx, result)
}),
)
}
/** Assert JSON status/content-type plus an optional synchronous body check. */
json(status = 200, inspect?: (body: unknown, ctx: SeededContext<S>) => void, compare: Comparison = "json") {
return this.jsonEffect(status, inspect ? (body, ctx) => Effect.sync(() => inspect(body, ctx)) : undefined, compare)
}
/** Assert JSON status/content-type plus optional Effect assertions, e.g. DB side effects. */
jsonEffect(
status = 200,
inspect?: (body: unknown, ctx: SeededContext<S>) => Effect.Effect<void>,
compare: Comparison = "json",
) {
return this.done(compare, (ctx, result) =>
Effect.gen(function* () {
if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`)
if (!looksJson(result))
throw new Error(`expected JSON response, got ${result.contentType || "no content-type"}`)
if (inspect) yield* inspect(result.body, ctx)
}),
)
}
private clone(next: Partial<BuilderState<S>>) {
const builder = new ScenarioBuilder<S>(this.state.method, this.state.path, this.state.name)
Object.assign(builder.state, this.state, next)
return builder
}
/**
* Seed typed state before the HTTP request. The returned value becomes `ctx.state`
* for `.at(...)` and assertions, giving stateful route tests type-safe setup.
*/
seeded<Next>(seed: (ctx: ScenarioContext) => Effect.Effect<Next>) {
const builder = new ScenarioBuilder<Next>(this.state.method, this.state.path, this.state.name)
Object.assign(builder.state, this.state, { seed })
return builder
}
private done(
compare: Comparison,
expect: (ctx: SeededContext<S>, result: CallResult) => Effect.Effect<void>,
): ActiveScenario {
const state = this.state
return {
kind: "active",
method: state.method,
path: state.path,
name: state.name,
project: state.project,
seed: state.seed,
request: (ctx, seeded) => state.request({ ...ctx, state: seeded as S }),
expect: (ctx, seeded, result) => expect({ ...ctx, state: seeded as S }, result),
compare,
capture: state.capture,
mutates: state.mutates,
reset: state.reset,
}
}
}
const http = {
get: (path: string, name: string) => new ScenarioBuilder("GET", path, name),
post: (path: string, name: string) => new ScenarioBuilder("POST", path, name),
put: (path: string, name: string) => new ScenarioBuilder("PUT", path, name),
patch: (path: string, name: string) => new ScenarioBuilder("PATCH", path, name),
delete: (path: string, name: string) => new ScenarioBuilder("DELETE", path, name),
}
const pending = (method: Method, path: string, name: string, reason: string): TodoScenario => ({
kind: "todo",
method,
path,
name,
reason,
})
function route(template: string, params: Record<string, string>) {
return Object.entries(params).reduce(
(next, [key, value]) => next.replaceAll(`{${key}}`, value).replaceAll(`:${key}`, value),
template,
)
}
const scenarios: Scenario[] = [
http
.get("/global/health", "global.health")
.global()
.json(200, (body) => {
object(body)
check(body.healthy === true, "server should report healthy")
}),
http
.get("/global/event", "global.event")
.global()
.stream()
.status(
200,
(_ctx, result) =>
Effect.sync(() => {
check(result.contentType.includes("text/event-stream"), "global event should be an SSE stream")
check(result.text.includes("server.connected"), "global event should emit initial connection event")
}),
"status",
),
http.get("/global/config", "global.config.get").global().json(),
http
.patch("/global/config", "global.config.update")
.global()
.seeded(() =>
Effect.promise(() =>
Bun.write(
path.join(exerciseConfigDirectory, "opencode.jsonc"),
JSON.stringify({ username: "httpapi-global" }, null, 2),
),
),
)
.at(() => ({ path: "/global/config", body: { username: "httpapi-global" } }))
.jsonEffect(
200,
(body) =>
Effect.gen(function* () {
object(body)
check(body.username === "httpapi-global", "global config update should return patched config")
const text = yield* Effect.promise(() =>
Bun.file(path.join(exerciseConfigDirectory, "opencode.jsonc")).text(),
)
check(text.includes('"username": "httpapi-global"'), "global config update should write isolated config file")
}),
"status",
),
http
.post("/global/dispose", "global.dispose")
.global()
.mutating()
.json(
200,
(body) => {
check(body === true, "global dispose should return true")
},
"status",
),
http.get("/path", "path.get").json(200, (body, ctx) => {
object(body)
check(body.directory === ctx.directory, "directory should resolve from x-opencode-directory")
check(body.worktree === ctx.directory, "worktree should resolve from x-opencode-directory")
}),
http.get("/vcs", "vcs.get").json(),
http
.get("/vcs/diff", "vcs.diff")
.at((ctx) => ({ path: "/vcs/diff?mode=git", headers: ctx.headers() }))
.json(200, array),
http.get("/command", "command.list").json(200, array, "status"),
http.get("/agent", "app.agents").json(200, array, "status"),
http.get("/skill", "app.skills").json(200, array, "status"),
http.get("/lsp", "lsp.status").json(200, array),
http.get("/formatter", "formatter.status").json(200, array),
http.get("/config", "config.get").json(200, undefined, "status"),
http
.patch("/config", "config.update")
.mutating()
.at((ctx) => ({ path: "/config", headers: ctx.headers(), body: { username: "httpapi-local" } }))
.json(
200,
(body) => {
object(body)
check(body.username === "httpapi-local", "local config update should return patched config")
},
"status",
),
http
.patch("/config", "config.update.invalid")
.at((ctx) => ({ path: "/config", headers: ctx.headers(), body: { username: 1 } }))
.status(400),
http.get("/config/providers", "config.providers").json(),
http.get("/project", "project.list").json(200, array, "status"),
http.get("/project/current", "project.current").json(
200,
(body, ctx) => {
object(body)
check(body.worktree === ctx.directory, "current project should resolve from scenario directory")
},
"status",
),
http
.patch("/project/{projectID}", "project.update")
.mutating()
.seeded((ctx) => ctx.project())
.at((ctx) => ({
path: route("/project/{projectID}", { projectID: ctx.state.id }),
headers: ctx.headers(),
body: { name: "HTTP API Project", commands: { start: "bun --version" } },
}))
.json(
200,
(body) => {
object(body)
check(body.name === "HTTP API Project", "project update should return patched name")
check(
isRecord(body.commands) && body.commands.start === "bun --version",
"project update should return patched command",
)
},
"status",
),
http
.post("/project/git/init", "project.initGit")
.mutating()
.inProject({ git: false })
.json(
200,
(body, ctx) => {
object(body)
check(body.worktree === ctx.directory, "git init should return current project")
check(body.vcs === "git", "git init should mark the project as git-backed")
},
"status",
),
http.get("/provider", "provider.list").json(),
http.get("/provider/auth", "provider.auth").json(),
http
.post("/provider/{providerID}/oauth/authorize", "provider.oauth.authorize")
.at((ctx) => ({
path: route("/provider/{providerID}/oauth/authorize", { providerID: "httpapi" }),
headers: ctx.headers(),
body: { method: "bad" },
}))
.status(400),
http
.post("/provider/{providerID}/oauth/callback", "provider.oauth.callback")
.at((ctx) => ({
path: route("/provider/{providerID}/oauth/callback", { providerID: "httpapi" }),
headers: ctx.headers(),
body: { method: "bad" },
}))
.status(400),
http.get("/permission", "permission.list").json(200, array),
http
.post("/permission/{requestID}/reply", "permission.reply.invalid")
.at((ctx) => ({
path: route("/permission/{requestID}/reply", { requestID: "per_httpapi" }),
headers: ctx.headers(),
body: { reply: "bad" },
}))
.status(400),
http
.post("/permission/{requestID}/reply", "permission.reply")
.at((ctx) => ({
path: route("/permission/{requestID}/reply", { requestID: "per_httpapi" }),
headers: ctx.headers(),
body: { reply: "once" },
}))
.json(200, (body) => {
check(body === true, "permission reply should return true even when request is no longer pending")
}),
http.get("/question", "question.list").json(200, array),
http
.post("/question/{requestID}/reply", "question.reply.invalid")
.at((ctx) => ({
path: route("/question/{requestID}/reply", { requestID: "que_httpapi_reply" }),
headers: ctx.headers(),
body: { answers: "Yes" },
}))
.status(400),
http
.post("/question/{requestID}/reply", "question.reply")
.at((ctx) => ({
path: route("/question/{requestID}/reply", { requestID: "que_httpapi_reply" }),
headers: ctx.headers(),
body: { answers: [["Yes"]] },
}))
.json(200, (body) => {
check(body === true, "question reply should return true even when request is no longer pending")
}),
http
.post("/question/{requestID}/reject", "question.reject")
.at((ctx) => ({
path: route("/question/{requestID}/reject", { requestID: "que_httpapi_reject" }),
headers: ctx.headers(),
}))
.json(200, (body) => {
check(body === true, "question reject should return true even when request is no longer pending")
}),
http
.get("/file", "file.list")
.seeded((ctx) => ctx.file("hello.txt", "hello\n"))
.at((ctx) => ({ path: `/file?${new URLSearchParams({ path: "." })}`, headers: ctx.headers() }))
.json(200, array),
http
.get("/file/content", "file.read")
.seeded((ctx) => ctx.file("hello.txt", "hello\n"))
.at((ctx) => ({ path: `/file/content?${new URLSearchParams({ path: "hello.txt" })}`, headers: ctx.headers() }))
.json(200, (body) => {
object(body)
check(body.content === "hello", `content should match seeded file: ${JSON.stringify(body)}`)
}),
http
.get("/file/content", "file.read.missing")
.at((ctx) => ({ path: `/file/content?${new URLSearchParams({ path: "missing.txt" })}`, headers: ctx.headers() }))
.json(200, (body) => {
object(body)
check(body.type === "text" && body.content === "", "missing file content should return an empty text result")
}),
http.get("/file/status", "file.status").json(200, array),
http
.get("/find", "find.text")
.seeded((ctx) => ctx.file("hello.txt", "hello\n"))
.at((ctx) => ({ path: `/find?${new URLSearchParams({ pattern: "hello" })}`, headers: ctx.headers() }))
.json(200, array),
http
.get("/find/file", "find.files")
.seeded((ctx) => ctx.file("hello.txt", "hello\n"))
.at((ctx) => ({
path: `/find/file?${new URLSearchParams({ query: "hello", dirs: "false" })}`,
headers: ctx.headers(),
}))
.json(200, array),
http
.get("/find/symbol", "find.symbols")
.seeded((ctx) => ctx.file("hello.ts", "export const hello = 1\n"))
.at((ctx) => ({ path: `/find/symbol?${new URLSearchParams({ query: "hello" })}`, headers: ctx.headers() }))
.json(200, array),
http
.get("/event", "event.stream")
.stream()
.status(
200,
(_ctx, result) =>
Effect.sync(() => {
check(result.contentType.includes("text/event-stream"), "event should be an SSE stream")
check(result.text.includes("server.connected"), "event should emit initial connection event")
}),
"status",
),
http.get("/mcp", "mcp.status").json(),
http
.post("/mcp", "mcp.add")
.mutating()
.at((ctx) => ({
path: "/mcp",
headers: ctx.headers(),
body: { name: "httpapi-disabled", config: { type: "local", command: ["bun", "--version"], enabled: false } },
}))
.json(
200,
(body) => {
object(body)
object(body["httpapi-disabled"])
check(body["httpapi-disabled"].status === "disabled", "disabled MCP server should be added without spawning")
},
"status",
),
http
.post("/mcp", "mcp.add.invalid")
.at((ctx) => ({
path: "/mcp",
headers: ctx.headers(),
body: { name: "httpapi-invalid", config: { type: "invalid" } },
}))
.status(400),
http
.post("/mcp/{name}/auth", "mcp.auth.start")
.at((ctx) => ({ path: route("/mcp/{name}/auth", { name: "httpapi-missing" }), headers: ctx.headers() }))
.json(
400,
(body) => {
object(body)
check(typeof body.error === "string", "unsupported MCP OAuth response should include error")
},
"status",
),
http
.delete("/mcp/{name}/auth", "mcp.auth.remove")
.mutating()
.at((ctx) => ({ path: route("/mcp/{name}/auth", { name: "httpapi-missing" }), headers: ctx.headers() }))
.json(200, (body) => {
object(body)
check(body.success === true, "MCP auth removal should return success")
}),
http
.post("/mcp/{name}/auth/authenticate", "mcp.auth.authenticate")
.at((ctx) => ({
path: route("/mcp/{name}/auth/authenticate", { name: "httpapi-missing" }),
headers: ctx.headers(),
}))
.json(
400,
(body) => {
object(body)
check(typeof body.error === "string", "unsupported MCP OAuth authenticate response should include error")
},
"status",
),
http
.post("/mcp/{name}/auth/callback", "mcp.auth.callback")
.at((ctx) => ({
path: route("/mcp/{name}/auth/callback", { name: "httpapi-missing" }),
headers: ctx.headers(),
body: { code: 1 },
}))
.status(400),
http
.post("/mcp/{name}/connect", "mcp.connect")
.mutating()
.at((ctx) => ({ path: route("/mcp/{name}/connect", { name: "httpapi-missing" }), headers: ctx.headers() }))
.json(200, (body) => {
check(body === true, "missing MCP connect should remain a no-op success")
}),
http
.post("/mcp/{name}/disconnect", "mcp.disconnect")
.mutating()
.at((ctx) => ({ path: route("/mcp/{name}/disconnect", { name: "httpapi-missing" }), headers: ctx.headers() }))
.json(200, (body) => {
check(body === true, "missing MCP disconnect should remain a no-op success")
}),
http.get("/pty/shells", "pty.shells").json(200, array),
http.get("/pty", "pty.list").json(200, array),
http
.post("/pty", "pty.create")
.mutating()
.at((ctx) => ({ path: "/pty", headers: ctx.headers(), body: controlledPtyInput("HTTP API PTY") }))
.json(
200,
(body, ctx) => {
object(body)
check(body.title === "HTTP API PTY", "PTY create should return requested title")
check(body.command === "/bin/sh", "PTY create should use controlled shell command")
check(body.cwd === ctx.directory, "PTY create should default cwd to scenario directory")
},
"status",
),
http
.post("/pty", "pty.create.invalid")
.at((ctx) => ({ path: "/pty", headers: ctx.headers(), body: { command: 1 } }))
.status(400),
http
.get("/pty/{ptyID}", "pty.get")
.at((ctx) => ({ path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() }))
.status(404),
http
.put("/pty/{ptyID}", "pty.update")
.mutating()
.at((ctx) => ({
path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }),
headers: ctx.headers(),
body: { size: { rows: 0, cols: 0 } },
}))
.status(400),
http
.delete("/pty/{ptyID}", "pty.remove")
.mutating()
.at((ctx) => ({ path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() }))
.json(200, (body) => {
check(body === true, "PTY remove should return true")
}),
http
.get("/pty/{ptyID}/connect", "pty.connect")
.at((ctx) => ({ path: route("/pty/{ptyID}/connect", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() }))
.status(404, undefined, "none"),
http.get("/experimental/console", "experimental.console.get").json(),
http.get("/experimental/console/orgs", "experimental.console.listOrgs").json(),
http
.post("/experimental/console/switch", "experimental.console.switchOrg")
.at((ctx) => ({
path: "/experimental/console/switch",
headers: ctx.headers(),
body: { accountID: "httpapi-account", orgID: "httpapi-org" },
}))
.status(400, undefined, "none"),
http.get("/experimental/workspace/adapter", "experimental.workspace.adapter.list").json(200, array),
http.get("/experimental/workspace", "experimental.workspace.list").json(200, array),
http.get("/experimental/workspace/status", "experimental.workspace.status").json(200, array),
http
.post("/experimental/workspace", "experimental.workspace.create")
.at((ctx) => ({ path: "/experimental/workspace", headers: ctx.headers(), body: {} }))
.status(400),
http
.delete("/experimental/workspace/{id}", "experimental.workspace.remove")
.mutating()
.at((ctx) => ({
path: route("/experimental/workspace/{id}", { id: "wrk_httpapi_missing" }),
headers: ctx.headers(),
}))
.status(200),
http
.post("/experimental/workspace/warp", "experimental.workspace.warp")
.at((ctx) => ({
path: "/experimental/workspace/warp",
headers: ctx.headers(),
body: {},
}))
.status(400),
http
.get("/experimental/tool", "tool.list")
.at((ctx) => ({
path: `/experimental/tool?${new URLSearchParams({ provider: "opencode", model: "test" })}`,
headers: ctx.headers(),
}))
.json(200, array, "status"),
http.get("/experimental/tool/ids", "tool.ids").json(200, array),
http.get("/experimental/worktree", "worktree.list").json(200, array),
http
.post("/experimental/worktree", "worktree.create")
.mutating()
.at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { name: "api-dsl" } }))
.jsonEffect(
200,
(body, ctx) =>
Effect.gen(function* () {
object(body)
check(typeof body.directory === "string", "created worktree should include directory")
yield* ctx.worktreeRemove(body.directory)
}),
"status",
),
http
.post("/experimental/worktree", "worktree.create.invalid")
.at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { name: 1 } }))
.status(400),
http
.delete("/experimental/worktree", "worktree.remove")
.mutating()
.seeded((ctx) => ctx.worktree({ name: "api-remove" }))
.at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { directory: ctx.state.directory } }))
.json(200, (body) => {
check(body === true, "worktree remove should return true")
}),
http
.post("/experimental/worktree/reset", "worktree.reset")
.mutating()
.seeded((ctx) => ctx.worktree({ name: "api-reset" }))
.at((ctx) => ({
path: "/experimental/worktree/reset",
headers: ctx.headers(),
body: { directory: ctx.state.directory },
}))
.jsonEffect(200, (body, ctx) =>
Effect.gen(function* () {
check(body === true, "worktree reset should return true")
yield* ctx.worktreeRemove(ctx.state.directory)
}),
),
http.get("/experimental/session", "experimental.session.list").json(200, array),
http.get("/experimental/resource", "experimental.resource.list").json(),
http
.post("/sync/history", "sync.history.list")
.at((ctx) => ({ path: "/sync/history", headers: ctx.headers(), body: {} }))
.json(200, array),
http
.post("/sync/replay", "sync.replay")
.at((ctx) => ({ path: "/sync/replay", headers: ctx.headers(), body: { directory: ctx.directory, events: [] } }))
.status(400),
http
.post("/sync/start", "sync.start")
.mutating()
.preserveDatabase()
.json(200, (body) => {
check(body === true, "sync start should return true when no workspace sessions exist")
}),
http
.post("/instance/dispose", "instance.dispose")
.mutating()
.json(200, (body) => {
check(body === true, "instance dispose should return true")
}),
http
.post("/log", "app.log")
.global()
.at(() => ({ path: "/log", body: { service: "httpapi-exercise", level: "info", message: "route coverage" } }))
.json(200, (body) => {
check(body === true, "log route should return true")
}),
http
.put("/auth/{providerID}", "auth.set")
.global()
.at(() => ({ path: route("/auth/{providerID}", { providerID: "test" }), body: { type: "api", key: "test-key" } }))
.jsonEffect(200, (body) =>
Effect.gen(function* () {
check(body === true, "auth set should return true")
const auth = yield* Effect.promise(() => Bun.file(path.join(exerciseDataDirectory, "auth.json")).json())
object(auth)
check(isRecord(auth.test) && auth.test.key === "test-key", "auth set should write isolated auth file")
}),
),
http
.delete("/auth/{providerID}", "auth.remove")
.global()
.seeded(() =>
Effect.promise(() =>
Bun.write(
path.join(exerciseDataDirectory, "auth.json"),
JSON.stringify({ test: { type: "api", key: "remove-me" } }),
),
),
)
.at(() => ({ path: route("/auth/{providerID}", { providerID: "test" }) }))
.jsonEffect(200, (body) =>
Effect.gen(function* () {
check(body === true, "auth remove should return true")
const auth = yield* Effect.promise(() => Bun.file(path.join(exerciseDataDirectory, "auth.json")).json())
object(auth)
check(auth.test === undefined, "auth remove should delete provider from isolated auth file")
}),
),
http
.get("/session", "session.list")
.seeded((ctx) => ctx.session({ title: "List me" }))
.at((ctx) => ({ path: "/session?roots=true", headers: ctx.headers() }))
.json(200, (body, ctx) => {
array(body)
check(
body.some((item) => isRecord(item) && item.id === ctx.state.id && item.title === "List me"),
"seeded session should be listed",
)
}),
http
.get("/session/status", "session.status")
.seeded((ctx) => ctx.session({ title: "Status session" }))
.json(200, object),
http
.post("/session", "session.create")
.mutating()
.at((ctx) => ({ path: "/session", headers: ctx.headers(), body: { title: "Created session" } }))
.json(
200,
(body, ctx) => {
object(body)
check(body.title === "Created session", "created session should use requested title")
check(body.directory === ctx.directory, "created session should use scenario directory")
},
"status",
),
http
.get("/session/{sessionID}", "session.get")
.seeded((ctx) => ctx.session({ title: "Get me" }))
.at((ctx) => ({ path: route("/session/{sessionID}", { sessionID: ctx.state.id }), headers: ctx.headers() }))
.json(200, (body, ctx) => {
object(body)
check(body.id === ctx.state.id, "should return requested session")
check(body.title === "Get me", "should preserve seeded title")
}),
http
.get("/session/{sessionID}", "session.get.missing")
.at((ctx) => ({
path: route("/session/{sessionID}", { sessionID: "ses_httpapi_missing" }),
headers: ctx.headers(),
}))
.status(404),
http
.patch("/session/{sessionID}", "session.update")
.mutating()
.seeded((ctx) => ctx.session({ title: "Before rename" }))
.at((ctx) => ({
path: route("/session/{sessionID}", { sessionID: ctx.state.id }),
headers: ctx.headers(),
body: { title: "After rename" },
}))
.json(
200,
(body) => {
object(body)
check(body.title === "After rename", "updated session should use new title")
},
"status",
),
http
.patch("/session/{sessionID}", "session.update.invalid")
.mutating()
.at((ctx) => ({
path: route("/session/{sessionID}", { sessionID: "ses_httpapi_missing" }),
headers: ctx.headers(),
body: { title: 1 },
}))
.status(400),
http
.delete("/session/{sessionID}", "session.delete")
.mutating()
.seeded((ctx) => ctx.session({ title: "Delete me" }))
.at((ctx) => ({ path: route("/session/{sessionID}", { sessionID: ctx.state.id }), headers: ctx.headers() }))
.jsonEffect(200, (body, ctx) =>
Effect.gen(function* () {
check(body === true, "delete should return true")
check((yield* ctx.sessionGet(ctx.state.id)) === undefined, "deleted session should not remain in storage")
}),
),
http
.get("/session/{sessionID}/children", "session.children")
.seeded((ctx) =>
Effect.gen(function* () {
const parent = yield* ctx.session({ title: "Parent" })
const child = yield* ctx.session({ title: "Child", parentID: parent.id })
return { parent, child }
}),
)
.at((ctx) => ({
path: route("/session/{sessionID}/children", { sessionID: ctx.state.parent.id }),
headers: ctx.headers(),
}))
.json(200, (body, ctx) => {
array(body)
check(
body.some((item) => isRecord(item) && item.id === ctx.state.child.id && item.parentID === ctx.state.parent.id),
"children should include seeded child",
)
}),
http
.get("/session/{sessionID}/todo", "session.todo")