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

server.test.ts

1,402 lines44.6 KB

1import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
2import * as NodeSocket from "@effect/platform-node/NodeSocket";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import {
5 CommandId,
6 DEFAULT_SERVER_SETTINGS,
7 GitCommandError,
8 KeybindingRule,
9 OpenError,
10 TerminalNotRunningError,
11 type OrchestrationEvent,
12 ORCHESTRATION_WS_METHODS,
13 ProjectId,
14 ResolvedKeybindingRule,
15 ThreadId,
16 WS_METHODS,
17 WsRpcGroup,
18 EditorId,
19} from "@t3tools/contracts";
20import { assert, it } from "@effect/vitest";
21import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
22import { Effect, FileSystem, Layer, Path, Stream } from "effect";
23import { HttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
24import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
25​
26import type { ServerConfigShape } from "./config.ts";
27import { deriveServerPaths, ServerConfig } from "./config.ts";
28import { makeRoutesLayer } from "./server.ts";
29import { resolveAttachmentRelativePath } from "./attachmentPaths.ts";
30import {
31 CheckpointDiffQuery,
32 type CheckpointDiffQueryShape,
33} from "./checkpointing/Services/CheckpointDiffQuery.ts";
34import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
35import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
36import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
37import { Open, type OpenShape } from "./open.ts";
38import {
39 OrchestrationEngineService,
40 type OrchestrationEngineShape,
41} from "./orchestration/Services/OrchestrationEngine.ts";
42import {
43 ProjectionSnapshotQuery,
44 type ProjectionSnapshotQueryShape,
45} from "./orchestration/Services/ProjectionSnapshotQuery.ts";
46import { PersistenceSqlError } from "./persistence/Errors.ts";
47import {
48 ProviderRegistry,
49 type ProviderRegistryShape,
50} from "./provider/Services/ProviderRegistry.ts";
51import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts";
52import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
53import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
54import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts";
55import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
56import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
57import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
58import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
59​
60const defaultProjectId = ProjectId.makeUnsafe("project-default");
61const defaultThreadId = ThreadId.makeUnsafe("thread-default");
62const defaultModelSelection = {
63 provider: "codex",
64 model: "gpt-5-codex",
65} as const;
66​
67const makeDefaultOrchestrationReadModel = () => {
68 const now = new Date().toISOString();
69 return {
70 snapshotSequence: 0,
71 updatedAt: now,
72 projects: [
73 {
74 id: defaultProjectId,
75 title: "Default Project",
76 workspaceRoot: "/tmp/default-project",
77 defaultModelSelection,
78 scripts: [],
79 createdAt: now,
80 updatedAt: now,
81 deletedAt: null,
82 },
83 ],
84 threads: [
85 {
86 id: defaultThreadId,
87 projectId: defaultProjectId,
88 title: "Default Thread",
89 modelSelection: defaultModelSelection,
90 interactionMode: "default" as const,
91 runtimeMode: "full-access" as const,
92 branch: null,
93 worktreePath: null,
94 createdAt: now,
95 updatedAt: now,
96 archivedAt: null,
97 latestTurn: null,
98 messages: [],
99 session: null,
100 activities: [],
101 proposedPlans: [],
102 checkpoints: [],
103 deletedAt: null,
104 },
105 ],
106 };
107};
108​
109const workspaceAndProjectServicesLayer = Layer.mergeAll(
110 WorkspacePathsLive,
111 WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)),
112 WorkspaceFileSystemLive.pipe(
113 Layer.provide(WorkspacePathsLive),
114 Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
115 ),
116 ProjectFaviconResolverLive,
117);
118​
119const buildAppUnderTest = (options?: {
120 config?: Partial<ServerConfigShape>;
121 layers?: {
122 keybindings?: Partial<KeybindingsShape>;
123 providerRegistry?: Partial<ProviderRegistryShape>;
124 serverSettings?: Partial<ServerSettingsShape>;
125 open?: Partial<OpenShape>;
126 gitCore?: Partial<GitCoreShape>;
127 gitManager?: Partial<GitManagerShape>;
128 terminalManager?: Partial<TerminalManagerShape>;
129 orchestrationEngine?: Partial<OrchestrationEngineShape>;
130 projectionSnapshotQuery?: Partial<ProjectionSnapshotQueryShape>;
131 checkpointDiffQuery?: Partial<CheckpointDiffQueryShape>;
132 serverLifecycleEvents?: Partial<ServerLifecycleEventsShape>;
133 serverRuntimeStartup?: Partial<ServerRuntimeStartupShape>;
134 };
135}) =>
136 Effect.gen(function* () {
137 const fileSystem = yield* FileSystem.FileSystem;
138 const tempBaseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-test-" });
139 const baseDir = options?.config?.baseDir ?? tempBaseDir;
140 const devUrl = options?.config?.devUrl;
141 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
142 const config = {
143 logLevel: "Info",
144 mode: "web",
145 port: 0,
146 host: "127.0.0.1",
147 cwd: process.cwd(),
148 baseDir,
149 ...derivedPaths,
150 staticDir: undefined,
151 devUrl,
152 noBrowser: true,
153 authToken: undefined,
154 autoBootstrapProjectFromCwd: false,
155 logWebSocketEvents: false,
156 ...options?.config,
157 } satisfies ServerConfigShape;
158 const layerConfig = Layer.succeed(ServerConfig, config);
159​
160 const appLayer = HttpRouter.serve(makeRoutesLayer, {
161 disableListenLog: true,
162 disableLogger: true,
163 }).pipe(
164 Layer.provide(
165 Layer.mock(Keybindings)({
166 streamChanges: Stream.empty,
167 ...options?.layers?.keybindings,
168 }),
169 ),
170 Layer.provide(
171 Layer.mock(ProviderRegistry)({
172 getProviders: Effect.succeed([]),
173 refresh: () => Effect.succeed([]),
174 streamChanges: Stream.empty,
175 ...options?.layers?.providerRegistry,
176 }),
177 ),
178 Layer.provide(
179 Layer.mock(ServerSettingsService)({
180 start: Effect.void,
181 ready: Effect.void,
182 getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
183 updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
184 streamChanges: Stream.empty,
185 ...options?.layers?.serverSettings,
186 }),
187 ),
188 Layer.provide(
189 Layer.mock(Open)({
190 ...options?.layers?.open,
191 }),
192 ),
193 Layer.provide(
194 Layer.mock(GitCore)({
195 ...options?.layers?.gitCore,
196 }),
197 ),
198 Layer.provide(
199 Layer.mock(GitManager)({
200 ...options?.layers?.gitManager,
201 }),
202 ),
203 Layer.provide(
204 Layer.mock(TerminalManager)({
205 ...options?.layers?.terminalManager,
206 }),
207 ),
208 Layer.provide(
209 Layer.mock(OrchestrationEngineService)({
210 getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
211 readEvents: () => Stream.empty,
212 dispatch: () => Effect.succeed({ sequence: 0 }),
213 streamDomainEvents: Stream.empty,
214 ...options?.layers?.orchestrationEngine,
215 }),
216 ),
217 Layer.provide(
218 Layer.mock(ProjectionSnapshotQuery)({
219 getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
220 ...options?.layers?.projectionSnapshotQuery,
221 }),
222 ),
223 Layer.provide(
224 Layer.mock(CheckpointDiffQuery)({
225 getTurnDiff: () =>
226 Effect.succeed({
227 threadId: defaultThreadId,
228 fromTurnCount: 0,
229 toTurnCount: 0,
230 diff: "",
231 }),
232 getFullThreadDiff: () =>
233 Effect.succeed({
234 threadId: defaultThreadId,
235 fromTurnCount: 0,
236 toTurnCount: 0,
237 diff: "",
238 }),
239 ...options?.layers?.checkpointDiffQuery,
240 }),
241 ),
242 Layer.provide(
243 Layer.mock(ServerLifecycleEvents)({
244 publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }),
245 snapshot: Effect.succeed({ sequence: 0, events: [] }),
246 stream: Stream.empty,
247 ...options?.layers?.serverLifecycleEvents,
248 }),
249 ),
250 Layer.provide(
251 Layer.mock(ServerRuntimeStartup)({
252 awaitCommandReady: Effect.void,
253 markHttpListening: Effect.void,
254 enqueueCommand: (effect) => effect,
255 ...options?.layers?.serverRuntimeStartup,
256 }),
257 ),
258 Layer.provide(workspaceAndProjectServicesLayer),
259 Layer.provide(layerConfig),
260 );
261​
262 yield* Layer.build(appLayer);
263 return config;
264 });
265​
266const wsRpcProtocolLayer = (wsUrl: string) =>
267 RpcClient.layerProtocolSocket().pipe(
268 Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
269 Layer.provide(RpcSerialization.layerJson),
270 );
271​
272const makeWsRpcClient = RpcClient.make(WsRpcGroup);
273type WsRpcClient =
274 typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never;
275​
276const withWsRpcClient = <A, E, R>(
277 wsUrl: string,
278 f: (client: WsRpcClient) => Effect.Effect<A, E, R>,
279) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl)));
280​
281const getHttpServerUrl = (pathname = "") =>
282 Effect.gen(function* () {
283 const server = yield* HttpServer.HttpServer;
284 const address = server.address as HttpServer.TcpAddress;
285 return `http://127.0.0.1:${address.port}${pathname}`;
286 });
287​
288const getWsServerUrl = (pathname = "") =>
289 Effect.gen(function* () {
290 const server = yield* HttpServer.HttpServer;
291 const address = server.address as HttpServer.TcpAddress;
292 return `ws://127.0.0.1:${address.port}${pathname}`;
293 });
294​
295it.layer(NodeServices.layer)("server router seam", (it) => {
296 it.effect("serves static index content for GET / when staticDir is configured", () =>
297 Effect.gen(function* () {
298 const fileSystem = yield* FileSystem.FileSystem;
299 const path = yield* Path.Path;
300 const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-static-" });
301 const indexPath = path.join(staticDir, "index.html");
302 yield* fileSystem.writeFileString(indexPath, "<html>router-static-ok</html>");
303​
304 yield* buildAppUnderTest({ config: { staticDir } });
305​
306 const response = yield* HttpClient.get("/");
307 assert.equal(response.status, 200);
308 assert.include(yield* response.text, "router-static-ok");
309 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
310 );
311​
312 it.effect("redirects to dev URL when configured", () =>
313 Effect.gen(function* () {
314 yield* buildAppUnderTest({
315 config: { devUrl: new URL("http://127.0.0.1:5173") },
316 });
317​
318 const url = yield* getHttpServerUrl("/foo/bar");
319 const response = yield* Effect.promise(() => fetch(url, { redirect: "manual" }));
320​
321 assert.equal(response.status, 302);
322 assert.equal(response.headers.get("location"), "http://127.0.0.1:5173/");
323 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
324 );
325​
326 it.effect("serves project favicon requests before the dev URL redirect", () =>
327 Effect.gen(function* () {
328 const fileSystem = yield* FileSystem.FileSystem;
329 const path = yield* Path.Path;
330 const projectDir = yield* fileSystem.makeTempDirectoryScoped({
331 prefix: "t3-router-project-favicon-",
332 });
333 yield* fileSystem.writeFileString(
334 path.join(projectDir, "favicon.svg"),
335 "<svg>router-project-favicon</svg>",
336 );
337​
338 yield* buildAppUnderTest({
339 config: { devUrl: new URL("http://127.0.0.1:5173") },
340 });
341​
342 const response = yield* HttpClient.get(
343 `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`,
344 );
345​
346 assert.equal(response.status, 200);
347 assert.equal(yield* response.text, "<svg>router-project-favicon</svg>");
348 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
349 );
350​
351 it.effect("serves the fallback project favicon when no icon exists", () =>
352 Effect.gen(function* () {
353 const fileSystem = yield* FileSystem.FileSystem;
354 const projectDir = yield* fileSystem.makeTempDirectoryScoped({
355 prefix: "t3-router-project-favicon-fallback-",
356 });
357​
358 yield* buildAppUnderTest({
359 config: { devUrl: new URL("http://127.0.0.1:5173") },
360 });
361​
362 const response = yield* HttpClient.get(
363 `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`,
364 );
365​
366 assert.equal(response.status, 200);
367 assert.include(yield* response.text, 'data-fallback="project-favicon"');
368 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
369 );
370​
371 it.effect("serves attachment files from state dir", () =>
372 Effect.gen(function* () {
373 const fileSystem = yield* FileSystem.FileSystem;
374 const path = yield* Path.Path;
375 const attachmentId = "thread-11111111-1111-4111-8111-111111111111";
376​
377 const config = yield* buildAppUnderTest();
378 const attachmentPath = resolveAttachmentRelativePath({
379 attachmentsDir: config.attachmentsDir,
380 relativePath: `${attachmentId}.bin`,
381 });
382 assert.isNotNull(attachmentPath, "Attachment path should be resolvable");
383​
384 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true });
385 yield* fileSystem.writeFileString(attachmentPath, "attachment-ok");
386​
387 const response = yield* HttpClient.get(`/attachments/${attachmentId}`);
388 assert.equal(response.status, 200);
389 assert.equal(yield* response.text, "attachment-ok");
390 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
391 );
392​
393 it.effect("serves attachment files for URL-encoded paths", () =>
394 Effect.gen(function* () {
395 const fileSystem = yield* FileSystem.FileSystem;
396 const path = yield* Path.Path;
397​
398 const config = yield* buildAppUnderTest();
399 const attachmentPath = resolveAttachmentRelativePath({
400 attachmentsDir: config.attachmentsDir,
401 relativePath: "thread%20folder/message%20folder/file%20name.png",
402 });
403 assert.isNotNull(attachmentPath, "Attachment path should be resolvable");
404​
405 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true });
406 yield* fileSystem.writeFileString(attachmentPath, "attachment-encoded-ok");
407​
408 const response = yield* HttpClient.get(
409 "/attachments/thread%20folder/message%20folder/file%20name.png",
410 );
411 assert.equal(response.status, 200);
412 assert.equal(yield* response.text, "attachment-encoded-ok");
413 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
414 );
415​
416 it.effect("returns 404 for missing attachment id lookups", () =>
417 Effect.gen(function* () {
418 yield* buildAppUnderTest();
419​
420 const response = yield* HttpClient.get(
421 "/attachments/missing-11111111-1111-4111-8111-111111111111",
422 );
423 assert.equal(response.status, 404);
424 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
425 );
426​
427 it.effect("routes websocket rpc server.upsertKeybinding", () =>
428 Effect.gen(function* () {
429 const rule: KeybindingRule = {
430 command: "terminal.toggle",
431 key: "ctrl+k",
432 };
433 const resolved: ResolvedKeybindingRule = {
434 command: "terminal.toggle",
435 shortcut: {
436 key: "k",
437 metaKey: false,
438 ctrlKey: true,
439 shiftKey: false,
440 altKey: false,
441 modKey: true,
442 },
443 };
444​
445 yield* buildAppUnderTest({
446 layers: {
447 keybindings: {
448 upsertKeybindingRule: () => Effect.succeed([resolved]),
449 },
450 },
451 });
452​
453 const wsUrl = yield* getWsServerUrl("/ws");
454 const response = yield* Effect.scoped(
455 withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverUpsertKeybinding](rule)),
456 );
457​
458 assert.deepEqual(response.issues, []);
459 assert.deepEqual(response.keybindings, [resolved]);
460 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
461 );
462​
463 it.effect("rejects websocket rpc handshake when auth token is missing", () =>
464 Effect.gen(function* () {
465 const fs = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-required-" });
468 yield* fs.writeFileString(
469 path.join(workspaceDir, "needle-file.ts"),
470 "export const needle = 1;",
471 );
472​
473 yield* buildAppUnderTest({
474 config: {
475 authToken: "secret-token",
476 },
477 });
478​
479 const wsUrl = yield* getWsServerUrl("/ws");
480 const result = yield* Effect.scoped(
481 withWsRpcClient(wsUrl, (client) =>
482 client[WS_METHODS.projectsSearchEntries]({
483 cwd: workspaceDir,
484 query: "needle",
485 limit: 10,
486 }),
487 ).pipe(Effect.result),
488 );
489​
490 assertTrue(result._tag === "Failure");
491 assertInclude(String(result.failure), "SocketOpenError");
492 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
493 );
494​
495 it.effect("accepts websocket rpc handshake when auth token is provided", () =>
496 Effect.gen(function* () {
497 const fs = yield* FileSystem.FileSystem;
498 const path = yield* Path.Path;
499 const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-ok-" });
500 yield* fs.writeFileString(
501 path.join(workspaceDir, "needle-file.ts"),
502 "export const needle = 1;",
503 );
504​
505 yield* buildAppUnderTest({
506 config: {
507 authToken: "secret-token",
508 },
509 });
510​
511 const wsUrl = yield* getWsServerUrl("/ws?token=secret-token");
512 const response = yield* Effect.scoped(
513 withWsRpcClient(wsUrl, (client) =>
514 client[WS_METHODS.projectsSearchEntries]({
515 cwd: workspaceDir,
516 query: "needle",
517 limit: 10,
518 }),
519 ),
520 );
521​
522 assert.isAtLeast(response.entries.length, 1);
523 assert.equal(response.truncated, false);
524 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
525 );
526​
527 it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () =>
528 Effect.gen(function* () {
529 const providers = [] as const;
530 const changeEvent = {
531 keybindings: [],
532 issues: [],
533 } as const;
534​
535 yield* buildAppUnderTest({
536 layers: {
537 keybindings: {
538 loadConfigState: Effect.succeed({
539 keybindings: [],
540 issues: [],
541 }),
542 streamChanges: Stream.succeed(changeEvent),
543 },
544 providerRegistry: {
545 getProviders: Effect.succeed(providers),
546 },
547 },
548 });
549​
550 const wsUrl = yield* getWsServerUrl("/ws");
551 const events = yield* Effect.scoped(
552 withWsRpcClient(wsUrl, (client) =>
553 client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect),
554 ),
555 );
556​
557 const [first, second] = Array.from(events);
558 assert.equal(first?.type, "snapshot");
559 if (first?.type === "snapshot") {
560 assert.equal(first.version, 1);
561 assert.deepEqual(first.config.keybindings, []);
562 assert.deepEqual(first.config.issues, []);
563 assert.deepEqual(first.config.providers, providers);
564 assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS);
565 }
566 assert.deepEqual(second, {
567 version: 1,
568 type: "keybindingsUpdated",
569 payload: { issues: [] },
570 });
571 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
572 );
573​
574 it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>
575 Effect.gen(function* () {
576 const providers = [] as const;
577​
578 yield* buildAppUnderTest({
579 layers: {
580 keybindings: {
581 loadConfigState: Effect.succeed({
582 keybindings: [],
583 issues: [],
584 }),
585 streamChanges: Stream.empty,
586 },
587 providerRegistry: {
588 getProviders: Effect.succeed([]),
589 streamChanges: Stream.succeed(providers),
590 },
591 },
592 });
593​
594 const wsUrl = yield* getWsServerUrl("/ws");
595 const events = yield* Effect.scoped(
596 withWsRpcClient(wsUrl, (client) =>
597 client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect),
598 ),
599 );
600​
601 const [first, second] = Array.from(events);
602 assert.equal(first?.type, "snapshot");
603 assert.deepEqual(second, {
604 version: 1,
605 type: "providerStatuses",
606 payload: { providers },
607 });
608 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
609 );
610​
611 it.effect(
612 "routes websocket rpc subscribeServerLifecycle replays snapshot and streams updates",
613 () =>
614 Effect.gen(function* () {
615 const lifecycleEvents = [
616 {
617 version: 1 as const,
618 sequence: 1,
619 type: "welcome" as const,
620 payload: {
621 cwd: "/tmp/project",
622 projectName: "project",
623 },
624 },
625 ] as const;
626 const liveEvents = Stream.make({
627 version: 1 as const,
628 sequence: 2,
629 type: "ready" as const,
630 payload: { at: new Date().toISOString() },
631 });
632​
633 yield* buildAppUnderTest({
634 layers: {
635 serverLifecycleEvents: {
636 snapshot: Effect.succeed({
637 sequence: 1,
638 events: lifecycleEvents,
639 }),
640 stream: liveEvents,
641 },
642 },
643 });
644​
645 const wsUrl = yield* getWsServerUrl("/ws");
646 const events = yield* Effect.scoped(
647 withWsRpcClient(wsUrl, (client) =>
648 client[WS_METHODS.subscribeServerLifecycle]({}).pipe(Stream.take(2), Stream.runCollect),
649 ),
650 );
651​
652 const [first, second] = Array.from(events);
653 assert.equal(first?.type, "welcome");
654 assert.equal(first?.sequence, 1);
655 assert.equal(second?.type, "ready");
656 assert.equal(second?.sequence, 2);
657 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
658 );
659​
660 it.effect("routes websocket rpc projects.searchEntries", () =>
661 Effect.gen(function* () {
662 const fs = yield* FileSystem.FileSystem;
663 const path = yield* Path.Path;
664 const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-search-" });
665 yield* fs.writeFileString(
666 path.join(workspaceDir, "needle-file.ts"),
667 "export const needle = 1;",
668 );
669​
670 yield* buildAppUnderTest();
671​
672 const wsUrl = yield* getWsServerUrl("/ws");
673 const response = yield* Effect.scoped(
674 withWsRpcClient(wsUrl, (client) =>
675 client[WS_METHODS.projectsSearchEntries]({
676 cwd: workspaceDir,
677 query: "needle",
678 limit: 10,
679 }),
680 ),
681 );
682​
683 assert.isAtLeast(response.entries.length, 1);
684 assert.isTrue(response.entries.some((entry) => entry.path === "needle-file.ts"));
685 assert.equal(response.truncated, false);
686 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
687 );
688​
689 it.effect("routes websocket rpc projects.searchEntries errors", () =>
690 Effect.gen(function* () {
691 yield* buildAppUnderTest();
692​
693 const wsUrl = yield* getWsServerUrl("/ws");
694 const result = yield* Effect.scoped(
695 withWsRpcClient(wsUrl, (client) =>
696 client[WS_METHODS.projectsSearchEntries]({
697 cwd: "/definitely/not/a/real/workspace/path",
698 query: "needle",
699 limit: 10,
700 }),
701 ).pipe(Effect.result),
702 );
703​
704 assertTrue(result._tag === "Failure");
705 assertTrue(result.failure._tag === "ProjectSearchEntriesError");
706 assertInclude(
707 result.failure.message,
708 "Workspace root does not exist: /definitely/not/a/real/workspace/path",
709 );
710 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
711 );
712​
713 it.effect("routes websocket rpc projects.writeFile", () =>
714 Effect.gen(function* () {
715 const fs = yield* FileSystem.FileSystem;
716 const path = yield* Path.Path;
717 const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" });
718​
719 yield* buildAppUnderTest();
720​
721 const wsUrl = yield* getWsServerUrl("/ws");
722 const response = yield* Effect.scoped(
723 withWsRpcClient(wsUrl, (client) =>
724 client[WS_METHODS.projectsWriteFile]({
725 cwd: workspaceDir,
726 relativePath: "nested/created.txt",
727 contents: "written-by-rpc",
728 }),
729 ),
730 );
731​
732 assert.equal(response.relativePath, "nested/created.txt");
733 const persisted = yield* fs.readFileString(path.join(workspaceDir, "nested", "created.txt"));
734 assert.equal(persisted, "written-by-rpc");
735 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
736 );
737​
738 it.effect("routes websocket rpc projects.writeFile errors", () =>
739 Effect.gen(function* () {
740 const fs = yield* FileSystem.FileSystem;
741 const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" });
742​
743 yield* buildAppUnderTest();
744​
745 const wsUrl = yield* getWsServerUrl("/ws");
746 const result = yield* Effect.scoped(
747 withWsRpcClient(wsUrl, (client) =>
748 client[WS_METHODS.projectsWriteFile]({
749 cwd: workspaceDir,
750 relativePath: "../escape.txt",
751 contents: "nope",
752 }),
753 ).pipe(Effect.result),
754 );
755​
756 assertTrue(result._tag === "Failure");
757 assertTrue(result.failure._tag === "ProjectWriteFileError");
758 assert.equal(
759 result.failure.message,
760 "Workspace file path must stay within the project root.",
761 );
762 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
763 );
764​
765 it.effect("routes websocket rpc shell.openInEditor", () =>
766 Effect.gen(function* () {
767 let openedInput: { cwd: string; editor: EditorId } | null = null;
768 yield* buildAppUnderTest({
769 layers: {
770 open: {
771 openInEditor: (input) =>
772 Effect.sync(() => {
773 openedInput = input;
774 }),
775 },
776 },
777 });
778​
779 const wsUrl = yield* getWsServerUrl("/ws");
780 yield* Effect.scoped(
781 withWsRpcClient(wsUrl, (client) =>
782 client[WS_METHODS.shellOpenInEditor]({
783 cwd: "/tmp/project",
784 editor: "cursor",
785 }),
786 ),
787 );
788​
789 assert.deepEqual(openedInput, { cwd: "/tmp/project", editor: "cursor" });
790 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
791 );
792​
793 it.effect("routes websocket rpc shell.openInEditor errors", () =>
794 Effect.gen(function* () {
795 const openError = new OpenError({ message: "Editor command not found: cursor" });
796 yield* buildAppUnderTest({
797 layers: {
798 open: {
799 openInEditor: () => Effect.fail(openError),
800 },
801 },
802 });
803​
804 const wsUrl = yield* getWsServerUrl("/ws");
805 const result = yield* Effect.scoped(
806 withWsRpcClient(wsUrl, (client) =>
807 client[WS_METHODS.shellOpenInEditor]({
808 cwd: "/tmp/project",
809 editor: "cursor",
810 }),
811 ).pipe(Effect.result),
812 );
813​
814 assertFailure(result, openError);
815 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
816 );
817​
818 it.effect("routes websocket rpc git methods", () =>
819 Effect.gen(function* () {
820 yield* buildAppUnderTest({
821 layers: {
822 gitManager: {
823 status: () =>
824 Effect.succeed({
825 branch: "main",
826 hasWorkingTreeChanges: false,
827 workingTree: { files: [], insertions: 0, deletions: 0 },
828 hasUpstream: true,
829 aheadCount: 0,
830 behindCount: 0,
831 pr: null,
832 }),
833 runStackedAction: (input, options) =>
834 Effect.gen(function* () {
835 const result = {
836 action: "commit" as const,
837 branch: { status: "skipped_not_requested" as const },
838 commit: {
839 status: "created" as const,
840 commitSha: "abc123",
841 subject: "feat: demo",
842 },
843 push: { status: "skipped_not_requested" as const },
844 pr: { status: "skipped_not_requested" as const },
845 toast: {
846 title: "Committed abc123",
847 description: "feat: demo",
848 cta: {
849 kind: "run_action" as const,
850 label: "Push",
851 action: {
852 kind: "push" as const,
853 },
854 },
855 },
856 };
857​
858 yield* (
859 options?.progressReporter?.publish({
860 actionId: options.actionId ?? input.actionId,
861 cwd: input.cwd,
862 action: input.action,
863 kind: "phase_started",
864 phase: "commit",
865 label: "Committing...",
866 }) ?? Effect.void
867 );
868​
869 yield* (
870 options?.progressReporter?.publish({
871 actionId: options.actionId ?? input.actionId,
872 cwd: input.cwd,
873 action: input.action,
874 kind: "action_finished",
875 result,
876 }) ?? Effect.void
877 );
878​
879 return result;
880 }),
881 resolvePullRequest: () =>
882 Effect.succeed({
883 pullRequest: {
884 number: 1,
885 title: "Demo PR",
886 url: "https://example.com/pr/1",
887 baseBranch: "main",
888 headBranch: "feature/demo",
889 state: "open",
890 },
891 }),
892 preparePullRequestThread: () =>
893 Effect.succeed({
894 pullRequest: {
895 number: 1,
896 title: "Demo PR",
897 url: "https://example.com/pr/1",
898 baseBranch: "main",
899 headBranch: "feature/demo",
900 state: "open",
901 },
902 branch: "feature/demo",
903 worktreePath: null,
904 }),
905 },
906 gitCore: {
907 pullCurrentBranch: () =>
908 Effect.succeed({
909 status: "pulled",
910 branch: "main",
911 upstreamBranch: "origin/main",
912 }),
913 listBranches: () =>
914 Effect.succeed({
915 branches: [
916 {
917 name: "main",
918 current: true,
919 isDefault: true,
920 worktreePath: null,
921 },
922 ],
923 isRepo: true,
924 hasOriginRemote: true,
925 }),
926 createWorktree: () =>
927 Effect.succeed({
928 worktree: { path: "/tmp/wt", branch: "feature/demo" },
929 }),
930 removeWorktree: () => Effect.void,
931 createBranch: () => Effect.void,
932 checkoutBranch: () => Effect.void,
933 initRepo: () => Effect.void,
934 },
935 },
936 });
937​
938 const wsUrl = yield* getWsServerUrl("/ws");
939​
940 const status = yield* Effect.scoped(
941 withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitStatus]({ cwd: "/tmp/repo" })),
942 );
943 assert.equal(status.branch, "main");
944​
945 const pull = yield* Effect.scoped(
946 withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
947 );
948 assert.equal(pull.status, "pulled");
949​
950 const stackedEvents = yield* Effect.scoped(
951 withWsRpcClient(wsUrl, (client) =>
952 client[WS_METHODS.gitRunStackedAction]({
953 actionId: "action-1",
954 cwd: "/tmp/repo",
955 action: "commit",
956 }).pipe(
957 Stream.runCollect,
958 Effect.map((events) => Array.from(events)),
959 ),
960 ),
961 );
962 const lastStackedEvent = stackedEvents.at(-1);
963 assert.equal(lastStackedEvent?.kind, "action_finished");
964 if (lastStackedEvent?.kind === "action_finished") {
965 assert.equal(lastStackedEvent.result.action, "commit");
966 }
967​
968 const resolvedPr = yield* Effect.scoped(
969 withWsRpcClient(wsUrl, (client) =>
970 client[WS_METHODS.gitResolvePullRequest]({
971 cwd: "/tmp/repo",
972 reference: "1",
973 }),
974 ),
975 );
976 assert.equal(resolvedPr.pullRequest.number, 1);
977​
978 const prepared = yield* Effect.scoped(
979 withWsRpcClient(wsUrl, (client) =>
980 client[WS_METHODS.gitPreparePullRequestThread]({
981 cwd: "/tmp/repo",
982 reference: "1",
983 mode: "local",
984 }),
985 ),
986 );
987 assert.equal(prepared.branch, "feature/demo");
988​
989 const branches = yield* Effect.scoped(
990 withWsRpcClient(wsUrl, (client) =>
991 client[WS_METHODS.gitListBranches]({ cwd: "/tmp/repo" }),
992 ),
993 );
994 assert.equal(branches.branches[0]?.name, "main");
995​
996 const worktree = yield* Effect.scoped(
997 withWsRpcClient(wsUrl, (client) =>
998 client[WS_METHODS.gitCreateWorktree]({
999 cwd: "/tmp/repo",
1000 branch: "main",
1001 path: null,
1002 }),
1003 ),
1004 );
1005 assert.equal(worktree.worktree.branch, "feature/demo");
1006​
1007 yield* Effect.scoped(
1008 withWsRpcClient(wsUrl, (client) =>
1009 client[WS_METHODS.gitRemoveWorktree]({
1010 cwd: "/tmp/repo",
1011 path: "/tmp/wt",
1012 }),
1013 ),
1014 );
1015​
1016 yield* Effect.scoped(
1017 withWsRpcClient(wsUrl, (client) =>
1018 client[WS_METHODS.gitCreateBranch]({
1019 cwd: "/tmp/repo",
1020 branch: "feature/new",
1021 }),
1022 ),
1023 );
1024​
1025 yield* Effect.scoped(
1026 withWsRpcClient(wsUrl, (client) =>
1027 client[WS_METHODS.gitCheckout]({
1028 cwd: "/tmp/repo",
1029 branch: "main",
1030 }),
1031 ),
1032 );
1033​
1034 yield* Effect.scoped(
1035 withWsRpcClient(wsUrl, (client) =>
1036 client[WS_METHODS.gitInit]({
1037 cwd: "/tmp/repo",
1038 }),
1039 ),
1040 );
1041 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
1042 );
1043​
1044 it.effect("routes websocket rpc git.pull errors", () =>
1045 Effect.gen(function* () {
1046 const gitError = new GitCommandError({
1047 operation: "pull",
1048 command: "git pull --ff-only",
1049 cwd: "/tmp/repo",
1050 detail: "upstream missing",
1051 });
1052 yield* buildAppUnderTest({
1053 layers: {
1054 gitCore: {
1055 pullCurrentBranch: () => Effect.fail(gitError),
1056 },
1057 },
1058 });
1059​
1060 const wsUrl = yield* getWsServerUrl("/ws");
1061 const result = yield* Effect.scoped(
1062 withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })).pipe(
1063 Effect.result,
1064 ),
1065 );
1066​
1067 assertFailure(result, gitError);
1068 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
1069 );
1070​
1071 it.effect("routes websocket rpc orchestration methods", () =>
1072 Effect.gen(function* () {
1073 const now = new Date().toISOString();
1074 const snapshot = {
1075 snapshotSequence: 1,
1076 updatedAt: now,
1077 projects: [
1079 id: ProjectId.makeUnsafe("project-a"),
1080 title: "Project A",
1081 workspaceRoot: "/tmp/project-a",
1082 defaultModelSelection,
1083 scripts: [],
1084 createdAt: now,
1085 updatedAt: now,
1086 deletedAt: null,
1087 },
1088 ],
1089 threads: [
1091 id: ThreadId.makeUnsafe("thread-1"),
1092 projectId: ProjectId.makeUnsafe("project-a"),
1093 title: "Thread A",
1094 modelSelection: defaultModelSelection,
1095 interactionMode: "default" as const,
1096 runtimeMode: "full-access" as const,
1097 branch: null,
1098 worktreePath: null,
1099 createdAt: now,
1100 updatedAt: now,
1101 archivedAt: null,
1102 latestTurn: null,
1103 messages: [],
1104 session: null,
1105 activities: [],
1106 proposedPlans: [],
1107 checkpoints: [],
1108 deletedAt: null,
1109 },
1110 ],
1111 };
1112​
1113 yield* buildAppUnderTest({
1114 layers: {
1115 projectionSnapshotQuery: {
1116 getSnapshot: () => Effect.succeed(snapshot),
1117 },
1118 orchestrationEngine: {
1119 dispatch: () => Effect.succeed({ sequence: 7 }),
1120 readEvents: () => Stream.empty,
1121 },
1122 checkpointDiffQuery: {
1123 getTurnDiff: () =>
1124 Effect.succeed({
1125 threadId: ThreadId.makeUnsafe("thread-1"),
1126 fromTurnCount: 0,
1127 toTurnCount: 1,
1128 diff: "turn-diff",
1129 }),
1130 getFullThreadDiff: () =>
1131 Effect.succeed({
1132 threadId: ThreadId.makeUnsafe("thread-1"),
1133 fromTurnCount: 0,
1134 toTurnCount: 1,
1135 diff: "full-diff",
1136 }),
1137 },
1138 },
1139 });
1140​
1141 const wsUrl = yield* getWsServerUrl("/ws");
1142 const snapshotResult = yield* Effect.scoped(
1143 withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})),
1144 );
1145 assert.equal(snapshotResult.snapshotSequence, 1);
1146​
1147 const dispatchResult = yield* Effect.scoped(
1148 withWsRpcClient(wsUrl, (client) =>
1149 client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
1150 type: "thread.session.stop",
1151 commandId: CommandId.makeUnsafe("cmd-1"),
1152 threadId: ThreadId.makeUnsafe("thread-1"),
1153 createdAt: now,
1154 }),
1155 ),
1156 );
1157 assert.equal(dispatchResult.sequence, 7);
1158​
1159 const turnDiffResult = yield* Effect.scoped(
1160 withWsRpcClient(wsUrl, (client) =>
1161 client[ORCHESTRATION_WS_METHODS.getTurnDiff]({
1162 threadId: ThreadId.makeUnsafe("thread-1"),
1163 fromTurnCount: 0,
1164 toTurnCount: 1,
1165 }),
1166 ),
1167 );
1168 assert.equal(turnDiffResult.diff, "turn-diff");
1169​
1170 const fullDiffResult = yield* Effect.scoped(
1171 withWsRpcClient(wsUrl, (client) =>
1172 client[ORCHESTRATION_WS_METHODS.getFullThreadDiff]({
1173 threadId: ThreadId.makeUnsafe("thread-1"),
1174 toTurnCount: 1,
1175 }),
1176 ),
1177 );
1178 assert.equal(fullDiffResult.diff, "full-diff");
1179​
1180 const replayResult = yield* Effect.scoped(
1181 withWsRpcClient(wsUrl, (client) =>
1182 client[ORCHESTRATION_WS_METHODS.replayEvents]({
1183 fromSequenceExclusive: 0,
1184 }),
1185 ),
1186 );
1187 assert.deepEqual(replayResult, []);
1188 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
1189 );
1190​
1191 it.effect(
1192 "routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience",
1193 () =>
1194 Effect.gen(function* () {
1195 const now = new Date().toISOString();
1196 const threadId = ThreadId.makeUnsafe("thread-1");
1197 let replayCursor: number | null = null;
1198 const makeEvent = (sequence: number): OrchestrationEvent =>
1199 ({
1200 sequence,
1201 eventId: `event-${sequence}`,
1202 aggregateKind: "thread",
1203 aggregateId: threadId,
1204 occurredAt: now,
1205 commandId: null,
1206 causationEventId: null,
1207 correlationId: null,
1208 metadata: {},
1209 type: "thread.reverted",
1210 payload: {
1211 threadId,
1212 turnCount: sequence,
1213 },
1214 }) as OrchestrationEvent;
1215​
1216 yield* buildAppUnderTest({
1217 layers: {
1218 orchestrationEngine: {
1219 getReadModel: () =>
1220 Effect.succeed({
1221 ...makeDefaultOrchestrationReadModel(),
1222 snapshotSequence: 1,
1223 }),
1224 readEvents: (fromSequenceExclusive) => {
1225 replayCursor = fromSequenceExclusive;
1226 return Stream.make(makeEvent(2), makeEvent(3));
1227 },
1228 streamDomainEvents: Stream.make(makeEvent(3), makeEvent(4)),
1229 },
1230 },
1231 });
1232​
1233 const wsUrl = yield* getWsServerUrl("/ws");
1234 const events = yield* Effect.scoped(
1235 withWsRpcClient(wsUrl, (client) =>
1236 client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe(
1237 Stream.take(3),
1238 Stream.runCollect,
1239 ),
1240 ),
1241 );
1242​
1243 assert.equal(replayCursor, 1);
1244 assert.deepEqual(
1245 Array.from(events).map((event) => event.sequence),
1246 [2, 3, 4],
1247 );
1248 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
1249 );
1250​
1251 it.effect("routes websocket rpc orchestration.getSnapshot errors", () =>
1252 Effect.gen(function* () {
1253 yield* buildAppUnderTest({
1254 layers: {
1255 projectionSnapshotQuery: {
1256 getSnapshot: () =>
1257 Effect.fail(
1258 new PersistenceSqlError({
1259 operation: "ProjectionSnapshotQuery.getSnapshot",
1260 detail: "projection unavailable",
1261 }),
1262 ),
1263 },
1264 },
1265 });
1266​
1267 const wsUrl = yield* getWsServerUrl("/ws");
1268 const result = yield* Effect.scoped(
1269 withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})).pipe(
1270 Effect.result,
1271 ),
1272 );
1273​
1274 assertTrue(result._tag === "Failure");
1275 assertTrue(result.failure._tag === "OrchestrationGetSnapshotError");
1276 assertInclude(result.failure.message, "Failed to load orchestration snapshot");
1277 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
1278 );
1279​
1280 it.effect("routes websocket rpc terminal methods", () =>
1281 Effect.gen(function* () {
1282 const snapshot = {
1283 threadId: "thread-1",
1284 terminalId: "default",
1285 cwd: "/tmp/project",
1286 status: "running" as const,
1287 pid: 1234,
1288 history: "",
1289 exitCode: null,
1290 exitSignal: null,
1291 updatedAt: new Date().toISOString(),
1292 };
1293​
1294 yield* buildAppUnderTest({
1295 layers: {
1296 terminalManager: {
1297 open: () => Effect.succeed(snapshot),
1298 write: () => Effect.void,
1299 resize: () => Effect.void,
1300 clear: () => Effect.void,
1301 restart: () => Effect.succeed(snapshot),
1302 close: () => Effect.void,
1303 },
1304 },
1305 });
1306​
1307 const wsUrl = yield* getWsServerUrl("/ws");
1308​
1309 const opened = yield* Effect.scoped(
1310 withWsRpcClient(wsUrl, (client) =>
1311 client[WS_METHODS.terminalOpen]({
1312 threadId: "thread-1",
1313 terminalId: "default",
1314 cwd: "/tmp/project",
1315 }),
1316 ),
1317 );
1318 assert.equal(opened.terminalId, "default");
1319​
1320 yield* Effect.scoped(
1321 withWsRpcClient(wsUrl, (client) =>
1322 client[WS_METHODS.terminalWrite]({
1323 threadId: "thread-1",
1324 terminalId: "default",
1325 data: "echo hi\n",
1326 }),
1327 ),
1328 );
1329​
1330 yield* Effect.scoped(
1331 withWsRpcClient(wsUrl, (client) =>
1332 client[WS_METHODS.terminalResize]({
1333 threadId: "thread-1",
1334 terminalId: "default",
1335 cols: 120,
1336 rows: 40,
1337 }),
1338 ),
1339 );
1340​
1341 yield* Effect.scoped(
1342 withWsRpcClient(wsUrl, (client) =>
1343 client[WS_METHODS.terminalClear]({
1344 threadId: "thread-1",
1345 terminalId: "default",
1346 }),
1347 ),
1348 );
1349​
1350 const restarted = yield* Effect.scoped(
1351 withWsRpcClient(wsUrl, (client) =>
1352 client[WS_METHODS.terminalRestart]({
1353 threadId: "thread-1",
1354 terminalId: "default",
1355 cwd: "/tmp/project",
1356 cols: 120,
1357 rows: 40,
1358 }),
1359 ),
1360 );
1361 assert.equal(restarted.terminalId, "default");
1362​
1363 yield* Effect.scoped(
1364 withWsRpcClient(wsUrl, (client) =>
1365 client[WS_METHODS.terminalClose]({
1366 threadId: "thread-1",
1367 terminalId: "default",
1368 }),
1369 ),
1370 );
1371 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
1372 );
1373​
1374 it.effect("routes websocket rpc terminal.write errors", () =>
1375 Effect.gen(function* () {
1376 const terminalError = new TerminalNotRunningError({
1377 threadId: "thread-1",
1378 terminalId: "default",
1379 });
1380 yield* buildAppUnderTest({
1381 layers: {
1382 terminalManager: {
1383 write: () => Effect.fail(terminalError),
1384 },
1385 },
1386 });
1387​
1388 const wsUrl = yield* getWsServerUrl("/ws");
1389 const result = yield* Effect.scoped(
1390 withWsRpcClient(wsUrl, (client) =>
1391 client[WS_METHODS.terminalWrite]({
1392 threadId: "thread-1",
1393 terminalId: "default",
1394 data: "echo fail\n",
1395 }),
1396 ).pipe(Effect.result),
1397 );
1398​
1399 assertFailure(result, terminalError);
1400 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
1401 );
1402});