Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
4let mockSavedRecords: Array<Record<string, unknown>> = [];
5
6const mockResolveRemotePairingTarget = vi.fn();
7const mockFetchRemoteEnvironmentDescriptor = vi.fn();
8const mockBootstrapRemoteBearerSession = vi.fn();
9const mockFetchRemoteSessionState = vi.fn();
10const mockIsRemoteEnvironmentAuthHttpError = vi.fn((_: unknown) => false);
11const mockResolveRemoteWebSocketConnectionUrl = vi.fn();
12const mockBootstrapSshBearerSession = vi.fn();
13const mockFetchSshSessionState = vi.fn();
14const mockPersistSavedEnvironmentRecord = vi.fn();
15const mockWriteSavedEnvironmentBearerToken = vi.fn();
16const mockSetSavedEnvironmentRegistry = vi.fn();
17const mockGetSavedEnvironmentRecord = vi.fn((environmentId: EnvironmentId) => {
18 return mockSavedRecords.find((record) => record.environmentId === environmentId) ?? null;
19});
20const mockReadSavedEnvironmentBearerToken = vi.fn();
21const mockRemoveSavedEnvironmentBearerToken = vi.fn();
22const mockPatchRuntime = vi.fn();
23const mockClearRuntime = vi.fn();
24const mockRegistrySetState = vi.fn((next: { byId: Record<string, Record<string, unknown>> }) => {
25 mockSavedRecords = Object.values(next.byId);
26});
27const mockRemove = vi.fn((environmentId: EnvironmentId) => {
28 mockSavedRecords = mockSavedRecords.filter((record) => record.environmentId !== environmentId);
29});
30const mockMarkConnected = vi.fn((environmentId: EnvironmentId, connectedAt: string) => {
31 mockSavedRecords = mockSavedRecords.map((record) =>
32 record.environmentId === environmentId ? { ...record, lastConnectedAt: connectedAt } : record,
33 );
34});
35const mockRename = vi.fn((environmentId: EnvironmentId, label: string) => {
36 mockSavedRecords = mockSavedRecords.map((record) =>
37 record.environmentId === environmentId ? { ...record, label } : record,
38 );
39});
40const mockUpsert = vi.fn((record: Record<string, unknown>) => {
41 mockSavedRecords = [
42 ...mockSavedRecords.filter((entry) => entry.environmentId !== record.environmentId),
43 record,
44 ];
45});
46const mockListSavedEnvironmentRecords = vi.fn(() => mockSavedRecords);
47const mockEnsureSshEnvironment = vi.fn();
48const mockDisconnectSshEnvironment = vi.fn();
49const mockFetchSshEnvironmentDescriptor = vi.fn();
50const mockToPersistedSavedEnvironmentRecord = vi.fn((record) => record);
51const mockCreateEnvironmentConnection = vi.fn();
52const mockClientGetConfig = vi.fn(async () => ({
53 environment: {
54 environmentId: EnvironmentId.make("environment-1"),
55 label: "Remote environment",
56 },
57}));
58
59vi.mock("../remote/target", () => ({
60 resolveRemotePairingTarget: mockResolveRemotePairingTarget,
61}));
62
63vi.mock("../remote/api", () => ({
64 bootstrapRemoteBearerSession: mockBootstrapRemoteBearerSession,
65 fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,
66 fetchRemoteSessionState: mockFetchRemoteSessionState,
67 isRemoteEnvironmentAuthHttpError: mockIsRemoteEnvironmentAuthHttpError,
68 resolveRemoteWebSocketConnectionUrl: mockResolveRemoteWebSocketConnectionUrl,
69}));
70
71vi.mock("~/localApi", () => ({
72 ensureLocalApi: () => ({
73 persistence: {
74 setSavedEnvironmentRegistry: mockSetSavedEnvironmentRegistry,
75 },
76 }),
77}));
78
79vi.mock("./catalog", () => ({
80 getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
81 hasSavedEnvironmentRegistryHydrated: vi.fn(),
82 listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
83 persistSavedEnvironmentRecord: mockPersistSavedEnvironmentRecord,
84 readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
85 removeSavedEnvironmentBearerToken: mockRemoveSavedEnvironmentBearerToken,
86 toPersistedSavedEnvironmentRecord: mockToPersistedSavedEnvironmentRecord,
87 useSavedEnvironmentRegistryStore: {
88 getState: () => ({
89 upsert: mockUpsert,
90 remove: mockRemove,
91 markConnected: mockMarkConnected,
92 rename: mockRename,
93 }),
94 setState: mockRegistrySetState,
95 subscribe: vi.fn(() => () => {}),
96 },
97 useSavedEnvironmentRuntimeStore: {
98 getState: () => ({
99 ensure: vi.fn(),
100 patch: mockPatchRuntime,
101 clear: mockClearRuntime,
102 }),
103 },
104 waitForSavedEnvironmentRegistryHydration: vi.fn(),
105 writeSavedEnvironmentBearerToken: mockWriteSavedEnvironmentBearerToken,
106}));
107
108vi.mock("./connection", () => ({
109 createEnvironmentConnection: mockCreateEnvironmentConnection,
110}));
111
112vi.mock("../../rpc/wsRpcClient", () => ({
113 createWsRpcClient: vi.fn(() => ({
114 server: {
115 getConfig: mockClientGetConfig,
116 },
117 orchestration: {
118 subscribeThread: vi.fn(() => () => {}),
119 },
120 })),
121}));
122
123vi.mock("../../rpc/wsTransport", () => ({
124 WsTransport: vi.fn(),
125}));
126
127describe("addSavedEnvironment", () => {
128 afterEach(() => {
129 vi.useRealTimers();
130 });
131
132 beforeEach(() => {
133 vi.resetModules();
134 vi.clearAllMocks();
135 mockSavedRecords = [];
136 vi.stubGlobal("window", {
137 desktopBridge: {
138 ensureSshEnvironment: mockEnsureSshEnvironment,
139 disconnectSshEnvironment: mockDisconnectSshEnvironment,
140 fetchSshEnvironmentDescriptor: mockFetchSshEnvironmentDescriptor,
141 bootstrapSshBearerSession: mockBootstrapSshBearerSession,
142 fetchSshSessionState: mockFetchSshSessionState,
143 issueSshWebSocketToken: vi.fn(),
144 },
145 });
146 mockResolveRemotePairingTarget.mockImplementation(
147 (input: { host?: string; pairingCode?: string }) => ({
148 httpBaseUrl: input.host
149 ? input.host.endsWith("/")
150 ? input.host
151 : `${input.host}/`
152 : "https://remote.example.com/",
153 wsBaseUrl: input.host
154 ? input.host.replace(/^http/u, "ws").endsWith("/")
155 ? input.host.replace(/^http/u, "ws")
156 : `${input.host.replace(/^http/u, "ws")}/`
157 : "wss://remote.example.com/",
158 credential: input.pairingCode ?? "pairing-code",
159 }),
160 );
161 mockFetchRemoteEnvironmentDescriptor.mockResolvedValue({
162 environmentId: EnvironmentId.make("environment-1"),
163 label: "Remote environment",
164 });
165 mockBootstrapRemoteBearerSession.mockResolvedValue({
166 sessionToken: "bearer-token",
167 role: "owner",
168 });
169 mockFetchRemoteSessionState.mockResolvedValue({
170 authenticated: true,
171 role: "owner",
172 });
173 mockIsRemoteEnvironmentAuthHttpError.mockReturnValue(false);
174 mockResolveRemoteWebSocketConnectionUrl.mockResolvedValue(
175 "wss://remote.example.com/?wsToken=remote-token",
176 );
177 mockFetchSshEnvironmentDescriptor.mockResolvedValue({
178 environmentId: EnvironmentId.make("environment-1"),
179 label: "Remote environment",
180 });
181 mockBootstrapSshBearerSession.mockResolvedValue({
182 sessionToken: "ssh-bearer-token",
183 role: "owner",
184 });
185 mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);
186 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
187 mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined);
188 mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
189 mockRemoveSavedEnvironmentBearerToken.mockResolvedValue(undefined);
190 mockFetchSshSessionState.mockResolvedValue({
191 authenticated: true,
192 role: "owner",
193 });
194 mockCreateEnvironmentConnection.mockImplementation(
195 (input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => ({
196 kind: "saved",
197 environmentId: input.knownEnvironment.environmentId,
198 knownEnvironment: input.knownEnvironment,
199 client: input.client,
200 ensureBootstrapped: async () => undefined,
201 reconnect: async () => undefined,
202 dispose: async () => undefined,
203 }),
204 );
205 mockClientGetConfig.mockResolvedValue({
206 environment: {
207 environmentId: EnvironmentId.make("environment-1"),
208 label: "Remote environment",
209 },
210 });
211 mockEnsureSshEnvironment.mockResolvedValue({
212 target: {
213 alias: "devbox",
214 hostname: "devbox.example.com",
215 username: "julius",
216 port: 22,
217 },
218 httpBaseUrl: "http://127.0.0.1:3774/",
219 wsBaseUrl: "ws://127.0.0.1:3774/",
220 pairingToken: "ssh-pairing-code",
221 });
222 mockDisconnectSshEnvironment.mockResolvedValue(undefined);
223 });
224
225 it("rolls back persisted metadata when bearer token persistence fails", async () => {
226 const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
227
228 await expect(
229 addSavedEnvironment({
230 label: "Remote environment",
231 host: "remote.example.com",
232 pairingCode: "123456",
233 }),
234 ).rejects.toThrow("Unable to persist saved environment credentials.");
235
236 expect(mockPersistSavedEnvironmentRecord).toHaveBeenCalledTimes(1);
237 expect(mockWriteSavedEnvironmentBearerToken).toHaveBeenCalledWith(
238 EnvironmentId.make("environment-1"),
239 "bearer-token",
240 );
241 expect(mockSetSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
242 expect(mockUpsert).not.toHaveBeenCalled();
243
244 await resetEnvironmentServiceForTests();
245 });
246
247 it("restores unrelated saved environments when credential persistence rollback runs", async () => {
248 mockSavedRecords = [
249 {
250 environmentId: EnvironmentId.make("environment-existing"),
251 label: "Existing environment",
252 httpBaseUrl: "https://existing.example.com/",
253 wsBaseUrl: "wss://existing.example.com/",
254 createdAt: "2026-04-14T00:00:00.000Z",
255 lastConnectedAt: null,
256 },
257 ];
258
259 const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
260
261 await expect(
262 addSavedEnvironment({
263 label: "Remote environment",
264 host: "remote.example.com",
265 pairingCode: "123456",
266 }),
267 ).rejects.toThrow("Unable to persist saved environment credentials.");
268
269 expect(mockSetSavedEnvironmentRegistry).toHaveBeenCalledWith([
270 expect.objectContaining({
271 environmentId: EnvironmentId.make("environment-existing"),
272 }),
273 ]);
274
275 await resetEnvironmentServiceForTests();
276 });
277
278 it("persists the server label after saved environment metadata refresh", async () => {
279 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
280 mockClientGetConfig.mockResolvedValue({
281 environment: {
282 environmentId: EnvironmentId.make("environment-1"),
283 label: "Julius's Mac mini",
284 },
285 });
286
287 const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
288
289 await expect(
290 addSavedEnvironment({
291 label: "100.65.180.100",
292 host: "remote.example.com",
293 pairingCode: "123456",
294 }),
295 ).resolves.toMatchObject({
296 environmentId: EnvironmentId.make("environment-1"),
297 });
298
299 expect(mockRename).toHaveBeenCalledWith(
300 EnvironmentId.make("environment-1"),
301 "Julius's Mac mini",
302 );
303 expect(mockSavedRecords).toEqual([
304 expect.objectContaining({
305 environmentId: EnvironmentId.make("environment-1"),
306 label: "Julius's Mac mini",
307 }),
308 ]);
309
310 await resetEnvironmentServiceForTests();
311 });
312
313 it("removes an older ssh record when the same target returns a new environment id", async () => {
314 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
315 mockFetchSshEnvironmentDescriptor.mockResolvedValue({
316 environmentId: EnvironmentId.make("environment-2"),
317 label: "Remote environment",
318 });
319 mockSavedRecords = [
320 {
321 environmentId: EnvironmentId.make("environment-1"),
322 label: "Old ssh environment",
323 httpBaseUrl: "http://127.0.0.1:3774/",
324 wsBaseUrl: "ws://127.0.0.1:3774/",
325 createdAt: "2026-04-14T00:00:00.000Z",
326 lastConnectedAt: null,
327 desktopSsh: {
328 alias: "devbox",
329 hostname: "devbox.example.com",
330 username: "julius",
331 port: 22,
332 },
333 },
334 ];
335
336 const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
337
338 await expect(
339 addSavedEnvironment({
340 label: "Remote environment",
341 host: "http://127.0.0.1:3774/",
342 pairingCode: "ssh-pairing-code",
343 desktopSsh: {
344 alias: "devbox",
345 hostname: "devbox.example.com",
346 username: "julius",
347 port: 22,
348 },
349 }),
350 ).resolves.toMatchObject({
351 environmentId: EnvironmentId.make("environment-2"),
352 });
353
354 expect(mockUpsert).toHaveBeenCalledWith(
355 expect.objectContaining({
356 environmentId: EnvironmentId.make("environment-2"),
357 }),
358 );
359 expect(mockRemove).toHaveBeenCalledWith(EnvironmentId.make("environment-1"));
360 expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
361 EnvironmentId.make("environment-1"),
362 );
363
364 await resetEnvironmentServiceForTests();
365 });
366
367 it("retries desktop ssh session refresh when the forwarded endpoint returns ssh_http 401", async () => {
368 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
369 mockBootstrapSshBearerSession
370 .mockResolvedValueOnce({
371 sessionToken: "ssh-bearer-token",
372 role: "owner",
373 })
374 .mockResolvedValueOnce({
375 sessionToken: "ssh-bearer-token-2",
376 role: "owner",
377 });
378 mockFetchSshSessionState
379 .mockRejectedValueOnce(new Error("[ssh_http:401] Unauthorized"))
380 .mockResolvedValueOnce({
381 authenticated: true,
382 role: "owner",
383 });
384
385 const { connectDesktopSshEnvironment, resetEnvironmentServiceForTests } =
386 await import("./service");
387
388 await expect(
389 connectDesktopSshEnvironment({
390 alias: "devbox",
391 hostname: "devbox",
392 username: null,
393 port: null,
394 }),
395 ).resolves.toMatchObject({
396 environmentId: EnvironmentId.make("environment-1"),
397 });
398
399 expect(mockEnsureSshEnvironment).toHaveBeenCalled();
400 expect(mockBootstrapSshBearerSession).toHaveBeenCalledTimes(2);
401 expect(mockFetchSshSessionState).toHaveBeenCalledTimes(2);
402
403 await resetEnvironmentServiceForTests();
404 });
405
406 it("does not attempt desktop ssh bearer recovery for non-ssh saved environments", async () => {
407 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
408 const authError = {
409 status: 401,
410 message: "Unauthorized",
411 };
412 mockFetchRemoteSessionState.mockRejectedValueOnce(authError);
413 mockIsRemoteEnvironmentAuthHttpError.mockImplementation(
414 (error: unknown) => error === authError,
415 );
416
417 const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
418
419 await expect(
420 addSavedEnvironment({
421 label: "Remote environment",
422 host: "remote.example.com",
423 pairingCode: "123456",
424 }),
425 ).rejects.toThrow("Saved environment credential expired. Pair it again.");
426
427 expect(mockEnsureSshEnvironment).not.toHaveBeenCalled();
428 expect(mockBootstrapSshBearerSession).not.toHaveBeenCalled();
429 expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
430 EnvironmentId.make("environment-1"),
431 );
432
433 await resetEnvironmentServiceForTests();
434 });
435
436 it("only registers the retried ssh connection after bearer re-issuance succeeds", async () => {
437 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
438 mockBootstrapSshBearerSession
439 .mockResolvedValueOnce({
440 sessionToken: "ssh-bearer-token",
441 role: "owner",
442 })
443 .mockResolvedValueOnce({
444 sessionToken: "ssh-bearer-token-2",
445 role: "owner",
446 });
447 mockFetchSshSessionState
448 .mockRejectedValueOnce(new Error("[ssh_http:401] Unauthorized"))
449 .mockResolvedValueOnce({
450 authenticated: true,
451 role: "owner",
452 });
453
454 const createdConnections: Array<{
455 readonly environmentId: EnvironmentId;
456 readonly dispose: ReturnType<typeof vi.fn>;
457 }> = [];
458 mockCreateEnvironmentConnection.mockImplementation(
459 (input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => {
460 const connection = {
461 kind: "saved" as const,
462 environmentId: input.knownEnvironment.environmentId,
463 knownEnvironment: input.knownEnvironment,
464 client: input.client,
465 ensureBootstrapped: async () => undefined,
466 reconnect: async () => undefined,
467 dispose: vi.fn(async () => undefined),
468 };
469 createdConnections.push(connection);
470 return connection;
471 },
472 );
473
474 const {
475 connectDesktopSshEnvironment,
476 listEnvironmentConnections,
477 resetEnvironmentServiceForTests,
478 } = await import("./service");
479
480 await connectDesktopSshEnvironment({
481 alias: "devbox",
482 hostname: "devbox",
483 username: null,
484 port: null,
485 });
486
487 expect(createdConnections).toHaveLength(2);
488 expect(createdConnections[0]?.dispose).toHaveBeenCalledTimes(1);
489 expect(listEnvironmentConnections()).toHaveLength(1);
490 expect(listEnvironmentConnections()[0]).toBe(createdConnections[1]);
491
492 await resetEnvironmentServiceForTests();
493 });
494
495 it("marks desktop ssh reconnect failures as runtime errors when bearer recovery fails", async () => {
496 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
497
498 const connection = {
499 kind: "saved" as const,
500 environmentId: EnvironmentId.make("environment-1"),
501 knownEnvironment: {
502 environmentId: EnvironmentId.make("environment-1"),
503 },
504 client: {},
505 ensureBootstrapped: async () => undefined,
506 reconnect: vi.fn(async () => {
507 throw new Error("socket closed");
508 }),
509 dispose: async () => undefined,
510 };
511 mockCreateEnvironmentConnection.mockReturnValue(connection);
512
513 const { addSavedEnvironment, reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
514 await import("./service");
515
516 await addSavedEnvironment({
517 label: "Remote environment",
518 host: "http://127.0.0.1:3774/",
519 pairingCode: "ssh-pairing-code",
520 desktopSsh: {
521 alias: "devbox",
522 hostname: "devbox.example.com",
523 username: "julius",
524 port: 22,
525 },
526 });
527
528 mockSavedRecords = [
529 {
530 environmentId: EnvironmentId.make("environment-1"),
531 label: "Remote environment",
532 httpBaseUrl: "http://127.0.0.1:3774/",
533 wsBaseUrl: "ws://127.0.0.1:3774/",
534 createdAt: "2026-04-14T00:00:00.000Z",
535 lastConnectedAt: null,
536 desktopSsh: {
537 alias: "devbox",
538 hostname: "devbox.example.com",
539 username: "julius",
540 port: 22,
541 },
542 },
543 ];
544 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
545
546 await expect(reconnectSavedEnvironment(EnvironmentId.make("environment-1"))).rejects.toThrow(
547 "Unable to persist saved environment credentials.",
548 );
549
550 expect(mockPatchRuntime).toHaveBeenCalledWith(
551 EnvironmentId.make("environment-1"),
552 expect.objectContaining({
553 connectionState: "error",
554 lastError: "Unable to persist saved environment credentials.",
555 }),
556 );
557
558 await resetEnvironmentServiceForTests();
559 });
560
561 it("bootstraps a desktop ssh environment through the desktop bridge", async () => {
562 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
563
564 const { connectDesktopSshEnvironment, resetEnvironmentServiceForTests } =
565 await import("./service");
566
567 await expect(
568 connectDesktopSshEnvironment({
569 alias: "devbox",
570 hostname: "devbox",
571 username: null,
572 port: null,
573 }),
574 ).resolves.toMatchObject({
575 environmentId: EnvironmentId.make("environment-1"),
576 });
577
578 expect(mockEnsureSshEnvironment).toHaveBeenCalledWith(
579 {
580 alias: "devbox",
581 hostname: "devbox",
582 username: null,
583 port: null,
584 },
585 { issuePairingToken: true },
586 );
587 expect(mockResolveRemotePairingTarget).toHaveBeenCalledWith({
588 host: "http://127.0.0.1:3774/",
589 pairingCode: "ssh-pairing-code",
590 });
591 expect(mockFetchSshEnvironmentDescriptor).toHaveBeenCalledWith("http://127.0.0.1:3774/");
592 expect(mockBootstrapSshBearerSession).toHaveBeenCalledWith(
593 "http://127.0.0.1:3774/",
594 "ssh-pairing-code",
595 );
596 expect(mockFetchRemoteEnvironmentDescriptor).not.toHaveBeenCalled();
597 expect(mockBootstrapRemoteBearerSession).not.toHaveBeenCalled();
598 expect(mockUpsert.mock.invocationCallOrder[0]).toBeLessThan(
599 mockCreateEnvironmentConnection.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
600 );
601
602 await resetEnvironmentServiceForTests();
603 });
604
605 it("disconnects the desktop ssh process before removing a saved ssh environment", async () => {
606 mockSavedRecords = [
607 {
608 environmentId: EnvironmentId.make("environment-1"),
609 label: "Remote environment",
610 httpBaseUrl: "http://127.0.0.1:3774/",
611 wsBaseUrl: "ws://127.0.0.1:3774/",
612 createdAt: "2026-04-14T00:00:00.000Z",
613 lastConnectedAt: null,
614 desktopSsh: {
615 alias: "devbox",
616 hostname: "devbox.example.com",
617 username: "julius",
618 port: 22,
619 },
620 },
621 ];
622
623 const { removeSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
624
625 await removeSavedEnvironment(EnvironmentId.make("environment-1"));
626
627 expect(mockDisconnectSshEnvironment).toHaveBeenCalledWith({
628 alias: "devbox",
629 hostname: "devbox.example.com",
630 username: "julius",
631 port: 22,
632 });
633 expect(mockRemove).toHaveBeenCalledWith(EnvironmentId.make("environment-1"));
634 expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
635 EnvironmentId.make("environment-1"),
636 );
637 expect(mockDisconnectSshEnvironment.mock.invocationCallOrder[0]).toBeLessThan(
638 mockRemove.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
639 );
640
641 await resetEnvironmentServiceForTests();
642 });
643
644 it("disconnects a saved ssh environment without removing its saved record", async () => {
645 mockSavedRecords = [
646 {
647 environmentId: EnvironmentId.make("environment-1"),
648 label: "Remote environment",
649 httpBaseUrl: "http://127.0.0.1:3774/",
650 wsBaseUrl: "ws://127.0.0.1:3774/",
651 createdAt: "2026-04-14T00:00:00.000Z",
652 lastConnectedAt: null,
653 desktopSsh: {
654 alias: "devbox",
655 hostname: "devbox.example.com",
656 username: "julius",
657 port: 22,
658 },
659 },
660 ];
661
662 const { disconnectSavedEnvironment, resetEnvironmentServiceForTests } =
663 await import("./service");
664
665 await disconnectSavedEnvironment(EnvironmentId.make("environment-1"));
666
667 expect(mockDisconnectSshEnvironment).toHaveBeenCalledWith({
668 alias: "devbox",
669 hostname: "devbox.example.com",
670 username: "julius",
671 port: 22,
672 });
673 expect(mockRemove).not.toHaveBeenCalled();
674 expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
675 EnvironmentId.make("environment-1"),
676 );
677
678 await resetEnvironmentServiceForTests();
679 });
680
681 it("keeps remote environment credentials when disconnecting a non-ssh saved environment", async () => {
682 mockSavedRecords = [
683 {
684 environmentId: EnvironmentId.make("environment-1"),
685 label: "Remote environment",
686 httpBaseUrl: "https://remote.example.com/",
687 wsBaseUrl: "wss://remote.example.com/",
688 createdAt: "2026-04-14T00:00:00.000Z",
689 lastConnectedAt: null,
690 },
691 ];
692
693 const { disconnectSavedEnvironment, resetEnvironmentServiceForTests } =
694 await import("./service");
695
696 await disconnectSavedEnvironment(EnvironmentId.make("environment-1"));
697
698 expect(mockDisconnectSshEnvironment).not.toHaveBeenCalled();
699 expect(mockRemove).not.toHaveBeenCalled();
700 expect(mockRemoveSavedEnvironmentBearerToken).not.toHaveBeenCalled();
701
702 await resetEnvironmentServiceForTests();
703 });
704
705 it("cancels a pending saved environment connection when disconnected", async () => {
706 mockSavedRecords = [
707 {
708 environmentId: EnvironmentId.make("environment-1"),
709 label: "Remote environment",
710 httpBaseUrl: "https://remote.example.com/",
711 wsBaseUrl: "wss://remote.example.com/",
712 createdAt: "2026-04-14T00:00:00.000Z",
713 lastConnectedAt: null,
714 },
715 ];
716 mockReadSavedEnvironmentBearerToken.mockResolvedValue("bearer-token");
717 const dispose = vi.fn(async () => undefined);
718 mockCreateEnvironmentConnection.mockImplementation(
719 (input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => ({
720 kind: "saved" as const,
721 environmentId: input.knownEnvironment.environmentId,
722 knownEnvironment: input.knownEnvironment,
723 client: input.client,
724 ensureBootstrapped: async () => undefined,
725 reconnect: async () => undefined,
726 dispose,
727 }),
728 );
729 let resolveSessionState!: (value: {
730 readonly authenticated: true;
731 readonly role: "owner";
732 }) => void;
733 mockFetchRemoteSessionState.mockReturnValue(
734 new Promise((resolve) => {
735 resolveSessionState = resolve;
736 }),
737 );
738
739 const {
740 disconnectSavedEnvironment,
741 listEnvironmentConnections,
742 reconnectSavedEnvironment,
743 resetEnvironmentServiceForTests,
744 } = await import("./service");
745
746 const reconnectPromise = reconnectSavedEnvironment(EnvironmentId.make("environment-1"));
747 await vi.waitFor(() => {
748 expect(mockFetchRemoteSessionState).toHaveBeenCalledOnce();
749 });
750
751 await disconnectSavedEnvironment(EnvironmentId.make("environment-1"));
752 resolveSessionState({
753 authenticated: true,
754 role: "owner",
755 });
756 await expect(reconnectPromise).resolves.toBeUndefined();
757
758 expect(listEnvironmentConnections()).toHaveLength(0);
759 expect(dispose).toHaveBeenCalledOnce();
760 expect(mockPatchRuntime).not.toHaveBeenCalledWith(
761 EnvironmentId.make("environment-1"),
762 expect.objectContaining({
763 connectionState: "error",
764 }),
765 );
766
767 await resetEnvironmentServiceForTests();
768 });
769
770 it("reissues ssh pairing credentials when connecting after a manual ssh disconnect", async () => {
771 mockSavedRecords = [
772 {
773 environmentId: EnvironmentId.make("environment-1"),
774 label: "Remote environment",
775 httpBaseUrl: "http://127.0.0.1:3774/",
776 wsBaseUrl: "ws://127.0.0.1:3774/",
777 createdAt: "2026-04-14T00:00:00.000Z",
778 lastConnectedAt: null,
779 desktopSsh: {
780 alias: "devbox",
781 hostname: "devbox.example.com",
782 username: "julius",
783 port: 22,
784 },
785 },
786 ];
787 mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
788 mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
789
790 const { reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
791 await import("./service");
792
793 await reconnectSavedEnvironment(EnvironmentId.make("environment-1"));
794
795 expect(mockEnsureSshEnvironment).toHaveBeenCalledWith(
796 {
797 alias: "devbox",
798 hostname: "devbox.example.com",
799 username: "julius",
800 port: 22,
801 },
802 { issuePairingToken: true },
803 );
804 expect(mockBootstrapSshBearerSession).toHaveBeenCalledWith(
805 "http://127.0.0.1:3774/",
806 "ssh-pairing-code",
807 );
808 expect(mockWriteSavedEnvironmentBearerToken).toHaveBeenCalledWith(
809 EnvironmentId.make("environment-1"),
810 "ssh-bearer-token",
811 );
812
813 await resetEnvironmentServiceForTests();
814 });
815
816 it("rolls back ssh registry metadata when pairing token issuance fails", async () => {
817 const originalRecord = {
818 environmentId: EnvironmentId.make("environment-1"),
819 label: "Remote environment",
820 httpBaseUrl: "http://127.0.0.1:3773/",
821 wsBaseUrl: "ws://127.0.0.1:3773/",
822 createdAt: "2026-04-14T00:00:00.000Z",
823 lastConnectedAt: null,
824 desktopSsh: {
825 alias: "devbox",
826 hostname: "devbox.example.com",
827 username: "julius",
828 port: 22,
829 },
830 };
831 mockSavedRecords = [originalRecord];
832 mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
833 mockEnsureSshEnvironment.mockResolvedValue({
834 target: {
835 alias: "devbox",
836 hostname: "devbox.example.com",
837 username: "julius",
838 port: 22,
839 },
840 httpBaseUrl: "http://127.0.0.1:3774/",
841 wsBaseUrl: "ws://127.0.0.1:3774/",
842 pairingToken: null,
843 });
844
845 const { reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
846 await import("./service");
847
848 await expect(reconnectSavedEnvironment(EnvironmentId.make("environment-1"))).rejects.toThrow(
849 "Desktop SSH launch did not return a pairing token.",
850 );
851
852 expect(mockPersistSavedEnvironmentRecord).toHaveBeenCalledWith(
853 expect.objectContaining({
854 httpBaseUrl: "http://127.0.0.1:3774/",
855 }),
856 );
857 expect(mockSetSavedEnvironmentRegistry).toHaveBeenCalledWith([originalRecord]);
858 expect(mockSavedRecords).toEqual([originalRecord]);
859 expect(mockBootstrapSshBearerSession).not.toHaveBeenCalled();
860
861 await resetEnvironmentServiceForTests();
862 });
863
864 it("surfaces desktop ssh bootstrap failures during saved ssh reconnect", async () => {
865 mockSavedRecords = [
866 {
867 environmentId: EnvironmentId.make("environment-1"),
868 label: "Remote environment",
869 httpBaseUrl: "http://127.0.0.1:3774/",
870 wsBaseUrl: "ws://127.0.0.1:3774/",
871 createdAt: "2026-04-14T00:00:00.000Z",
872 lastConnectedAt: null,
873 desktopSsh: {
874 alias: "devbox",
875 hostname: "devbox.example.com",
876 username: "julius",
877 port: 22,
878 },
879 },
880 ];
881 mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
882 mockEnsureSshEnvironment.mockRejectedValue(new Error("SSH command timed out after 60000ms."));
883
884 const { reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
885 await import("./service");
886
887 await expect(reconnectSavedEnvironment(EnvironmentId.make("environment-1"))).rejects.toThrow(
888 "SSH command timed out after 60000ms.",
889 );
890 expect(mockPatchRuntime).toHaveBeenCalledWith(
891 EnvironmentId.make("environment-1"),
892 expect.objectContaining({
893 connectionState: "connecting",
894 }),
895 );
896 expect(mockPatchRuntime).toHaveBeenCalledWith(
897 EnvironmentId.make("environment-1"),
898 expect.objectContaining({
899 connectionState: "error",
900 lastError: "SSH command timed out after 60000ms.",
901 }),
902 );
903
904 await resetEnvironmentServiceForTests();
905 });
906});