-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathCoderSSHRuntime.test.ts
More file actions
993 lines (843 loc) · 34.9 KB
/
Copy pathCoderSSHRuntime.test.ts
File metadata and controls
993 lines (843 loc) · 34.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
import { describe, expect, it, mock, beforeEach, afterEach, spyOn, type Mock } from "bun:test";
import type { CoderService } from "@/node/services/coderService";
import type { RuntimeConfig } from "@/common/types/runtime";
import * as runtimeHelpers from "@/node/utils/runtime/helpers";
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};
import type { InitLogger, RuntimeStatusEvent, WorkspaceInitParams } from "./Runtime";
import { CoderSSHRuntime, type CoderSSHRuntimeConfig } from "./CoderSSHRuntime";
import { SSHRuntime } from "./SSHRuntime";
import { createSSHTransport } from "./transports";
/**
* Create a minimal mock CoderService for testing.
* Only mocks methods used by the tested code paths.
*/
function createMockCoderService(overrides?: Partial<CoderService>): CoderService {
const provisioningSession = {
token: "token",
dispose: mock(() => Promise.resolve()),
};
return {
createWorkspace: mock(() => asyncLines([])),
deleteWorkspace: mock(() => Promise.resolve()),
deleteWorkspaceEventually: mock(() =>
Promise.resolve({ success: true as const, data: undefined })
),
ensureProvisioningSession: mock(() => Promise.resolve(provisioningSession)),
verifyAuthenticatedSession: mock(() => Promise.resolve()),
takeProvisioningSession: mock(() => provisioningSession),
disposeProvisioningSession: mock(() => Promise.resolve()),
ensureMuxCoderSSHConfig: mock(() => Promise.resolve()),
getWorkspaceStatus: mock(() =>
Promise.resolve({ kind: "ok" as const, status: "running" as const })
),
listWorkspaces: mock(() => Promise.resolve({ ok: true, workspaces: [] })),
waitForStartupScripts: mock(() => asyncLines([])),
workspaceExists: mock(() => Promise.resolve(false)),
...overrides,
} as unknown as CoderService;
}
/**
* Create a CoderSSHRuntime with minimal config for testing.
*/
function createRuntime(
coderConfig: {
existingWorkspace?: boolean;
workspaceName?: string;
template?: string;
},
coderService: CoderService
): CoderSSHRuntime {
const template = "template" in coderConfig ? coderConfig.template : "default-template";
const config: CoderSSHRuntimeConfig = {
host: "placeholder.mux--coder",
srcBaseDir: "~/src",
coder: {
existingWorkspace: coderConfig.existingWorkspace ?? false,
workspaceName: coderConfig.workspaceName,
template,
},
};
const transport = createSSHTransport(config, false);
return new CoderSSHRuntime(config, transport, coderService);
}
/**
* Create an SSH+Coder RuntimeConfig for finalizeConfig tests.
*/
function createSSHCoderConfig(coder: {
existingWorkspace?: boolean;
workspaceName?: string;
}): RuntimeConfig {
return {
type: "ssh",
host: "placeholder.mux--coder",
srcBaseDir: "~/src",
coder: {
existingWorkspace: coder.existingWorkspace ?? false,
workspaceName: coder.workspaceName,
template: "default-template",
},
};
}
function asyncLines(lines: string[], error?: Error): AsyncGenerator<string, void, unknown> {
return (async function* (): AsyncGenerator<string, void, unknown> {
await Promise.resolve();
for (const line of lines) {
yield line;
}
if (error) {
throw error;
}
})();
}
function createInitLogger(overrides: Partial<InitLogger> = {}): InitLogger {
return {
logStep: noop,
logStdout: noop,
logStderr: noop,
logComplete: noop,
...overrides,
};
}
function createPostCreateSetupParams(
workspaceName: string,
initLogger: InitLogger = createInitLogger()
): WorkspaceInitParams {
return {
initLogger,
projectPath: "/project",
branchName: "branch",
trunkBranch: "main",
workspacePath: `/home/user/src/my-project/${workspaceName}`,
};
}
describe("CoderSSHRuntime constructor", () => {
it("normalizes host to .mux--coder when workspaceName is present", () => {
const coderService = createMockCoderService();
const config: CoderSSHRuntimeConfig = {
host: "ws.coder",
srcBaseDir: "~/src",
coder: {
existingWorkspace: true,
workspaceName: "ws",
template: "default-template",
},
};
const transport = createSSHTransport(config, false);
const runtime = new CoderSSHRuntime(config, transport, coderService);
expect(runtime.getConfig().host).toBe("ws.mux--coder");
});
});
// =============================================================================
// Test Suite 1: finalizeConfig (name/host derivation)
// =============================================================================
describe("CoderSSHRuntime.finalizeConfig", () => {
let coderService: CoderService;
let runtime: CoderSSHRuntime;
beforeEach(() => {
coderService = createMockCoderService();
runtime = createRuntime({}, coderService);
});
describe("new workspace mode", () => {
it("derives Coder name from branch name when not provided", async () => {
const config = createSSHCoderConfig({ existingWorkspace: false });
const result = await runtime.finalizeConfig("my-feature", config);
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.type).toBe("ssh");
if (result.data.type === "ssh") {
expect(result.data.coder?.workspaceName).toBe("mux-my-feature");
expect(result.data.host).toBe("mux-my-feature.mux--coder");
}
}
});
it("converts underscores to hyphens", async () => {
const config = createSSHCoderConfig({ existingWorkspace: false });
const result = await runtime.finalizeConfig("my_feature_branch", config);
expect(result.success).toBe(true);
if (result.success && result.data.type === "ssh") {
expect(result.data.coder?.workspaceName).toBe("mux-my-feature-branch");
expect(result.data.host).toBe("mux-my-feature-branch.mux--coder");
}
});
it("collapses multiple hyphens and trims leading/trailing", async () => {
const config = createSSHCoderConfig({ existingWorkspace: false });
const result = await runtime.finalizeConfig("--my--feature--", config);
expect(result.success).toBe(true);
if (result.success && result.data.type === "ssh") {
expect(result.data.coder?.workspaceName).toBe("mux-my-feature");
}
});
it("rejects names that fail regex after conversion", async () => {
const config = createSSHCoderConfig({ existingWorkspace: false });
// Name with special chars that can't form a valid Coder name (only hyphens/underscores become invalid)
const result = await runtime.finalizeConfig("@#$%", config);
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error).toContain("cannot be converted to a valid Coder name");
}
});
it("returns error when provisioning session creation fails", async () => {
const verifyAuthenticatedSession = mock(() => Promise.resolve());
const ensureProvisioningSession = mock(() => Promise.reject(new Error("nope")));
coderService = createMockCoderService({
verifyAuthenticatedSession,
ensureProvisioningSession,
});
runtime = createRuntime({}, coderService);
const config = createSSHCoderConfig({ existingWorkspace: false });
const result = await runtime.finalizeConfig("branch", config);
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error).toContain("Failed to prepare Coder provisioning session");
expect(result.error).toContain("nope");
}
expect(ensureProvisioningSession).toHaveBeenCalledWith("mux-branch");
});
it("uses provided workspaceName over branch name", async () => {
const config = createSSHCoderConfig({
existingWorkspace: false,
workspaceName: "custom-name",
});
const result = await runtime.finalizeConfig("branch-name", config);
expect(result.success).toBe(true);
if (result.success && result.data.type === "ssh") {
expect(result.data.coder?.workspaceName).toBe("custom-name");
expect(result.data.host).toBe("custom-name.mux--coder");
}
});
});
describe("existing workspace mode", () => {
it("requires workspaceName to be provided", async () => {
const config = createSSHCoderConfig({ existingWorkspace: true });
const result = await runtime.finalizeConfig("branch-name", config);
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error).toContain("required for existing workspaces");
}
});
it("keeps provided workspaceName and sets host", async () => {
const config = createSSHCoderConfig({
existingWorkspace: true,
workspaceName: "existing-ws",
});
const result = await runtime.finalizeConfig("branch-name", config);
expect(result.success).toBe(true);
if (result.success && result.data.type === "ssh") {
expect(result.data.coder?.workspaceName).toBe("existing-ws");
expect(result.data.host).toBe("existing-ws.mux--coder");
}
});
it("returns Err when Coder auth verification fails for existing workspace", async () => {
const verifyAuthenticatedSession = mock(() => Promise.reject(new Error("not logged in")));
coderService = createMockCoderService({ verifyAuthenticatedSession });
runtime = createRuntime({}, coderService);
const config = createSSHCoderConfig({
existingWorkspace: true,
workspaceName: "existing-ws",
});
const result = await runtime.finalizeConfig("branch-name", config);
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error).toContain("Failed to verify Coder authentication");
}
expect(verifyAuthenticatedSession).toHaveBeenCalledTimes(1);
});
it("does not call ensureProvisioningSession for existing workspace even when auth succeeds", async () => {
const verifyAuthenticatedSession = mock(() => Promise.resolve());
const ensureProvisioningSession = mock(() =>
Promise.resolve({ token: "token", dispose: mock(() => Promise.resolve()) })
);
coderService = createMockCoderService({
verifyAuthenticatedSession,
ensureProvisioningSession,
});
runtime = createRuntime({}, coderService);
const config = createSSHCoderConfig({
existingWorkspace: true,
workspaceName: "existing-ws",
});
const result = await runtime.finalizeConfig("branch-name", config);
expect(result.success).toBe(true);
expect(verifyAuthenticatedSession).toHaveBeenCalledTimes(1);
expect(ensureProvisioningSession).not.toHaveBeenCalled();
});
});
it("passes through non-SSH configs unchanged", async () => {
const config: RuntimeConfig = { type: "local" };
const result = await runtime.finalizeConfig("branch", config);
expect(result.success).toBe(true);
if (result.success) {
expect(result.data).toEqual(config);
}
});
it("passes through SSH configs without coder unchanged", async () => {
const config: RuntimeConfig = { type: "ssh", host: "example.com", srcBaseDir: "/src" };
const result = await runtime.finalizeConfig("branch", config);
expect(result.success).toBe(true);
if (result.success) {
expect(result.data).toEqual(config);
}
});
});
// =============================================================================
// Test Suite 2: deleteWorkspace behavior
// =============================================================================
describe("CoderSSHRuntime.deleteWorkspace", () => {
/**
* For deleteWorkspace tests, we mock SSHRuntime.prototype.deleteWorkspace
* to control the parent class behavior.
*/
let sshDeleteSpy: Mock<typeof SSHRuntime.prototype.deleteWorkspace>;
beforeEach(() => {
sshDeleteSpy = spyOn(SSHRuntime.prototype, "deleteWorkspace").mockResolvedValue({
success: true,
deletedPath: "/path",
});
});
afterEach(() => {
sshDeleteSpy.mockRestore();
});
it("never calls coderService.deleteWorkspaceEventually when existingWorkspace=true", async () => {
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: true, workspaceName: "existing-ws" },
coderService
);
await runtime.deleteWorkspace("/project", "ws", false);
expect(deleteWorkspaceEventually).not.toHaveBeenCalled();
});
it("skips Coder deletion when workspaceName is not set", async () => {
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ deleteWorkspaceEventually });
// No workspaceName provided
const runtime = createRuntime({ existingWorkspace: false }, coderService);
const result = await runtime.deleteWorkspace("/project", "ws", false);
expect(deleteWorkspaceEventually).not.toHaveBeenCalled();
expect(result.success).toBe(true);
});
it("skips Coder deletion when SSH delete fails and force=false", async () => {
sshDeleteSpy.mockResolvedValue({ success: false, error: "dirty workspace" });
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
const result = await runtime.deleteWorkspace("/project", "ws", false);
expect(deleteWorkspaceEventually).not.toHaveBeenCalled();
expect(result.success).toBe(false);
});
it("calls Coder deletion (no SSH) when force=true", async () => {
sshDeleteSpy.mockResolvedValue({ success: false, error: "dirty workspace" });
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
await runtime.deleteWorkspace("/project", "ws", true);
expect(sshDeleteSpy).not.toHaveBeenCalled();
expect(deleteWorkspaceEventually).toHaveBeenCalledWith(
"my-ws",
expect.objectContaining({ waitForExistence: true, waitForExistenceTimeoutMs: 10_000 })
);
});
it("returns combined error when SSH succeeds but Coder delete fails", async () => {
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: false as const, error: "Coder API error" })
);
const coderService = createMockCoderService({ deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
const result = await runtime.deleteWorkspace("/project", "ws", false);
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error).toContain("SSH delete succeeded");
expect(result.error).toContain("Coder API error");
}
});
it("succeeds immediately when Coder workspace is already deleted", async () => {
// getWorkspaceStatus returns { kind: "not_found" } when workspace doesn't exist
const getWorkspaceStatus = mock(() => Promise.resolve({ kind: "not_found" as const }));
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ getWorkspaceStatus, deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
const result = await runtime.deleteWorkspace("/project", "ws", false);
// Should succeed without calling SSH delete or Coder delete
expect(result.success).toBe(true);
expect(sshDeleteSpy).not.toHaveBeenCalled();
expect(deleteWorkspaceEventually).not.toHaveBeenCalled();
});
it("passes abort signal to the Coder status check during delete", async () => {
const getWorkspaceStatus = mock(() => Promise.resolve({ kind: "not_found" as const }));
const coderService = createMockCoderService({ getWorkspaceStatus });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
const abortController = new AbortController();
await runtime.deleteWorkspace("/project", "ws", false, abortController.signal);
expect(getWorkspaceStatus).toHaveBeenCalledWith(
"my-ws",
expect.objectContaining({ signal: abortController.signal })
);
});
it("proceeds with SSH cleanup when status check fails with API error", async () => {
// API error (auth, network) - should NOT treat as "already deleted"
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "error" as const, error: "coder timed out" })
);
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ getWorkspaceStatus, deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
const result = await runtime.deleteWorkspace("/project", "ws", false);
// Should proceed with SSH cleanup (which succeeds), then Coder delete
expect(sshDeleteSpy).toHaveBeenCalled();
expect(deleteWorkspaceEventually).toHaveBeenCalled();
expect(result.success).toBe(true);
});
it("deletes stopped Coder workspace without SSH cleanup", async () => {
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "stopped" as const })
);
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ getWorkspaceStatus, deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
const result = await runtime.deleteWorkspace("/project", "ws", false);
expect(result.success).toBe(true);
expect(sshDeleteSpy).not.toHaveBeenCalled();
expect(deleteWorkspaceEventually).toHaveBeenCalledWith(
"my-ws",
expect.objectContaining({ waitForExistence: false })
);
});
it("succeeds immediately when Coder workspace status is 'deleting'", async () => {
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "deleting" as const })
);
const deleteWorkspaceEventually = mock(() =>
Promise.resolve({ success: true as const, data: undefined })
);
const coderService = createMockCoderService({ getWorkspaceStatus, deleteWorkspaceEventually });
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws" },
coderService
);
const result = await runtime.deleteWorkspace("/project", "ws", false);
// Should succeed without calling SSH delete or Coder delete (workspace already dying)
expect(result.success).toBe(true);
expect(sshDeleteSpy).not.toHaveBeenCalled();
expect(deleteWorkspaceEventually).not.toHaveBeenCalled();
});
});
// =============================================================================
// Test Suite 3: validateBeforePersist (collision detection)
// =============================================================================
describe("CoderSSHRuntime.validateBeforePersist", () => {
it("returns error when Coder workspace already exists", async () => {
const workspaceExists = mock(() => Promise.resolve(true));
const coderService = createMockCoderService({ workspaceExists });
const runtime = createRuntime({}, coderService);
const config = createSSHCoderConfig({
existingWorkspace: false,
workspaceName: "my-ws",
});
const result = await runtime.validateBeforePersist("branch", config);
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error).toContain("already exists");
}
expect(workspaceExists).toHaveBeenCalledWith("my-ws");
});
it("skips collision check for existingWorkspace=true", async () => {
const workspaceExists = mock(() => Promise.resolve(true));
const coderService = createMockCoderService({ workspaceExists });
const runtime = createRuntime({}, coderService);
const config = createSSHCoderConfig({
existingWorkspace: true,
workspaceName: "existing-ws",
});
const result = await runtime.validateBeforePersist("branch", config);
expect(result.success).toBe(true);
expect(workspaceExists).not.toHaveBeenCalled();
});
});
// =============================================================================
// Test Suite 4: postCreateSetup (provisioning)
// =============================================================================
describe("CoderSSHRuntime.postCreateSetup", () => {
let execBufferedSpy: ReturnType<typeof spyOn<typeof runtimeHelpers, "execBuffered">>;
beforeEach(() => {
execBufferedSpy = spyOn(runtimeHelpers, "execBuffered").mockResolvedValue({
stdout: "",
stderr: "",
exitCode: 0,
duration: 0,
});
});
afterEach(() => {
execBufferedSpy.mockRestore();
});
it("creates a new Coder workspace and prepares the directory", async () => {
const createWorkspace = mock(() => asyncLines(["build line 1", "build line 2"]));
const ensureMuxCoderSSHConfig = mock(() => Promise.resolve());
const provisioningSession = {
token: "token",
dispose: mock(() => Promise.resolve()),
};
const takeProvisioningSession = mock(() => provisioningSession);
// Start with workspace not found, then return running after creation
let workspaceCreated = false;
const getWorkspaceStatus = mock(() =>
Promise.resolve(
workspaceCreated
? { kind: "ok" as const, status: "running" as const }
: { kind: "not_found" as const }
)
);
const coderService = createMockCoderService({
createWorkspace,
ensureMuxCoderSSHConfig,
getWorkspaceStatus,
takeProvisioningSession,
});
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws", template: "my-template" },
coderService
);
// Before postCreateSetup, ensureReady should fail (workspace doesn't exist on server)
const beforeReady = await runtime.ensureReady();
expect(beforeReady.ready).toBe(false);
if (!beforeReady.ready) {
expect(beforeReady.errorType).toBe("runtime_not_ready");
}
// Simulate workspace being created by postCreateSetup
workspaceCreated = true;
const steps: string[] = [];
const stdout: string[] = [];
const stderr: string[] = [];
const initLogger = {
logStep: (s: string) => {
steps.push(s);
},
logStdout: (s: string) => {
stdout.push(s);
},
logStderr: (s: string) => {
stderr.push(s);
},
logComplete: noop,
};
await runtime.postCreateSetup(createPostCreateSetupParams("my-ws", initLogger));
expect(takeProvisioningSession).toHaveBeenCalledWith("my-ws");
expect(createWorkspace).toHaveBeenCalledWith(
"my-ws",
"my-template",
undefined,
undefined,
undefined,
provisioningSession
);
expect(provisioningSession.dispose).toHaveBeenCalled();
expect(ensureMuxCoderSSHConfig).toHaveBeenCalled();
expect(execBufferedSpy).toHaveBeenCalled();
// After postCreateSetup, ensureReady should succeed (workspace exists on server)
const afterReady = await runtime.ensureReady();
expect(afterReady.ready).toBe(true);
expect(stdout).toEqual(["build line 1", "build line 2"]);
expect(stderr).toEqual([]);
expect(steps.join("\n")).toContain("Creating Coder workspace");
expect(steps.join("\n")).toContain("Configuring SSH");
expect(steps.join("\n")).toContain("Preparing workspace directory");
});
it("disposes provisioning session when workspace creation fails", async () => {
const createWorkspace = mock(() => asyncLines(["Starting workspace..."], new Error("boom")));
const provisioningSession = {
token: "token",
dispose: mock(() => Promise.resolve()),
};
const takeProvisioningSession = mock(() => provisioningSession);
const coderService = createMockCoderService({
createWorkspace,
takeProvisioningSession,
});
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws", template: "my-template" },
coderService
);
let caughtError: Error | undefined;
try {
await runtime.postCreateSetup(createPostCreateSetupParams("my-ws"));
} catch (err) {
caughtError = err as Error;
}
expect(caughtError?.message).toContain("Failed to create Coder workspace");
expect(takeProvisioningSession).toHaveBeenCalledWith("my-ws");
expect(createWorkspace).toHaveBeenCalledWith(
"my-ws",
"my-template",
undefined,
undefined,
undefined,
provisioningSession
);
expect(provisioningSession.dispose).toHaveBeenCalled();
});
it("skips workspace creation when existingWorkspace=true and workspace is running", async () => {
const createWorkspace = mock(() => asyncLines(["should not happen"]));
const waitForStartupScripts = mock(() => asyncLines(["Already running"]));
const ensureMuxCoderSSHConfig = mock(() => Promise.resolve());
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "running" as const })
);
const coderService = createMockCoderService({
createWorkspace,
waitForStartupScripts,
ensureMuxCoderSSHConfig,
getWorkspaceStatus,
});
const runtime = createRuntime(
{ existingWorkspace: true, workspaceName: "existing-ws" },
coderService
);
await runtime.postCreateSetup(createPostCreateSetupParams("existing-ws"));
expect(createWorkspace).not.toHaveBeenCalled();
// waitForStartupScripts is called (it handles running workspaces quickly)
expect(waitForStartupScripts).toHaveBeenCalled();
expect(ensureMuxCoderSSHConfig).toHaveBeenCalled();
expect(execBufferedSpy).toHaveBeenCalled();
});
it("uses waitForStartupScripts for existing stopped workspace (auto-starts via coder ssh)", async () => {
const createWorkspace = mock(() => asyncLines(["should not happen"]));
const waitForStartupScripts = mock(() =>
asyncLines(["Starting workspace...", "Build complete", "Startup scripts finished"])
);
const ensureMuxCoderSSHConfig = mock(() => Promise.resolve());
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "stopped" as const })
);
const coderService = createMockCoderService({
createWorkspace,
waitForStartupScripts,
ensureMuxCoderSSHConfig,
getWorkspaceStatus,
});
const runtime = createRuntime(
{ existingWorkspace: true, workspaceName: "existing-ws" },
coderService
);
const loggedStdout: string[] = [];
await runtime.postCreateSetup(
createPostCreateSetupParams(
"existing-ws",
createInitLogger({ logStdout: (line) => loggedStdout.push(line) })
)
);
expect(createWorkspace).not.toHaveBeenCalled();
expect(waitForStartupScripts).toHaveBeenCalled();
expect(loggedStdout).toContain("Starting workspace...");
expect(loggedStdout).toContain("Startup scripts finished");
expect(ensureMuxCoderSSHConfig).toHaveBeenCalled();
});
it("polls until stopping workspace becomes stopped before connecting", async () => {
let pollCount = 0;
const getWorkspaceStatus = mock(() => {
pollCount++;
// First 2 calls return "stopping", then "stopped"
if (pollCount <= 2) {
return Promise.resolve({ kind: "ok" as const, status: "stopping" as const });
}
return Promise.resolve({ kind: "ok" as const, status: "stopped" as const });
});
const waitForStartupScripts = mock(() => asyncLines(["Ready"]));
const ensureMuxCoderSSHConfig = mock(() => Promise.resolve());
const coderService = createMockCoderService({
getWorkspaceStatus,
waitForStartupScripts,
ensureMuxCoderSSHConfig,
});
const runtime = createRuntime(
{ existingWorkspace: true, workspaceName: "stopping-ws" },
coderService
);
// Avoid real sleeps in this polling test
interface RuntimeWithSleep {
sleep: (ms: number, abortSignal?: AbortSignal) => Promise<void>;
}
spyOn(runtime as unknown as RuntimeWithSleep, "sleep").mockResolvedValue(undefined);
const loggedSteps: string[] = [];
await runtime.postCreateSetup(
createPostCreateSetupParams(
"stopping-ws",
createInitLogger({ logStep: (step) => loggedSteps.push(step) })
)
);
// Should have polled status multiple times
expect(pollCount).toBeGreaterThan(2);
expect(loggedSteps.some((s) => s.includes("Waiting for Coder workspace"))).toBe(true);
expect(waitForStartupScripts).toHaveBeenCalled();
});
it("throws when workspaceName is missing", () => {
const coderService = createMockCoderService();
const runtime = createRuntime({ existingWorkspace: false, template: "tmpl" }, coderService);
return expect(runtime.postCreateSetup(createPostCreateSetupParams("ws"))).rejects.toThrow(
"Coder workspace name is required"
);
});
it("throws when template is missing for new workspaces", () => {
const coderService = createMockCoderService();
const runtime = createRuntime(
{ existingWorkspace: false, workspaceName: "my-ws", template: undefined },
coderService
);
return expect(runtime.postCreateSetup(createPostCreateSetupParams("ws"))).rejects.toThrow(
"Coder template is required"
);
});
});
// =============================================================================
// Test Suite 5: ensureReady (runtime readiness + status events)
// =============================================================================
describe("CoderSSHRuntime.ensureReady", () => {
it("returns ready when workspace is already running", async () => {
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "running" as const })
);
const waitForStartupScripts = mock(() => asyncLines(["should not be called"]));
const coderService = createMockCoderService({ getWorkspaceStatus, waitForStartupScripts });
const runtime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws" },
coderService
);
const events: RuntimeStatusEvent[] = [];
const result = await runtime.ensureReady({
statusSink: (e) => events.push(e),
});
expect(result).toEqual({ ready: true });
expect(getWorkspaceStatus).toHaveBeenCalled();
// Short-circuited because status is already "running"
expect(waitForStartupScripts).not.toHaveBeenCalled();
expect(events.map((e) => e.phase)).toEqual(["checking", "ready"]);
expect(events[0]?.runtimeType).toBe("ssh");
});
it("reuses recent activity across recreated runtime instances", async () => {
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "running" as const })
);
const coderService = createMockCoderService({ getWorkspaceStatus });
const firstRuntime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws-recreated" },
coderService
);
const secondRuntime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws-recreated" },
coderService
);
expect(await firstRuntime.ensureReady()).toEqual({ ready: true });
expect(await secondRuntime.ensureReady()).toEqual({ ready: true });
expect(getWorkspaceStatus).toHaveBeenCalledTimes(1);
});
it("expires the cross-runtime activity cache after the fast-path window", async () => {
let now = 1_700_000_000_000;
const nowSpy = spyOn(Date, "now").mockImplementation(() => now);
try {
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "running" as const })
);
const coderService = createMockCoderService({ getWorkspaceStatus });
const firstRuntime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws-expiring" },
coderService
);
expect(await firstRuntime.ensureReady()).toEqual({ ready: true });
const cachedRuntime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws-expiring" },
coderService
);
expect(await cachedRuntime.ensureReady()).toEqual({ ready: true });
expect(getWorkspaceStatus).toHaveBeenCalledTimes(1);
now += 5 * 60 * 1000 + 1;
const expiredRuntime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws-expiring" },
coderService
);
expect(await expiredRuntime.ensureReady()).toEqual({ ready: true });
expect(getWorkspaceStatus).toHaveBeenCalledTimes(2);
} finally {
nowSpy.mockRestore();
}
});
it("connects via waitForStartupScripts when status is stopped (auto-starts)", async () => {
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "stopped" as const })
);
const waitForStartupScripts = mock(() =>
asyncLines(["Starting workspace...", "Workspace started"])
);
const coderService = createMockCoderService({ getWorkspaceStatus, waitForStartupScripts });
const runtime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws" },
coderService
);
const events: RuntimeStatusEvent[] = [];
const result = await runtime.ensureReady({
statusSink: (e) => events.push(e),
});
expect(result).toEqual({ ready: true });
expect(waitForStartupScripts).toHaveBeenCalled();
// We should see checking, then starting, then ready
expect(events[0]?.phase).toBe("checking");
expect(events.some((e) => e.phase === "starting")).toBe(true);
expect(events.at(-1)?.phase).toBe("ready");
});
it("returns runtime_start_failed when waitForStartupScripts fails", async () => {
const getWorkspaceStatus = mock(() =>
Promise.resolve({ kind: "ok" as const, status: "stopped" as const })
);
const waitForStartupScripts = mock(() =>
asyncLines(["Starting workspace..."], new Error("connection failed"))
);
const coderService = createMockCoderService({ getWorkspaceStatus, waitForStartupScripts });
const runtime = createRuntime(
{ existingWorkspace: true, workspaceName: "my-ws" },
coderService
);
const events: RuntimeStatusEvent[] = [];
const result = await runtime.ensureReady({
statusSink: (e) => events.push(e),
});
expect(result.ready).toBe(false);
if (!result.ready) {
expect(result.errorType).toBe("runtime_start_failed");
expect(result.error).toContain("Failed to connect");
}
expect(events.at(-1)?.phase).toBe("error");
});
});