Open History to see the last commit
1import "../../index.css";
2
3import {
4 type AuthAccessStreamEvent,
5 type AuthAccessSnapshot,
6 AuthSessionId,
7 DEFAULT_SERVER_SETTINGS,
8 EnvironmentId,
9 type DesktopBridge,
10 type DesktopUpdateState,
11 type LocalApi,
12 type ServerConfig,
13} from "@t3tools/contracts";
14import { DateTime } from "effect";
15import { page } from "vitest/browser";
16import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
17import { render } from "vitest-browser-react";
18
19import { __resetLocalApiForTests } from "../../localApi";
20import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
21import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
22import { ConnectionsSettings } from "./ConnectionsSettings";
23import { GeneralSettingsPanel } from "./SettingsPanels";
24
25const authAccessHarness = vi.hoisted(() => {
26 type Snapshot = AuthAccessSnapshot;
27 let snapshot: Snapshot = {
28 pairingLinks: [],
29 clientSessions: [],
30 };
31 let revision = 1;
32 const listeners = new Set<(event: AuthAccessStreamEvent) => void>();
33
34 const emitEvent = (event: AuthAccessStreamEvent) => {
35 for (const listener of listeners) {
36 listener(event);
37 }
38 };
39
40 return {
41 reset() {
42 snapshot = {
43 pairingLinks: [],
44 clientSessions: [],
45 };
46 revision = 1;
47 listeners.clear();
48 },
49 setSnapshot(next: Snapshot) {
50 snapshot = next;
51 },
52 emitSnapshot() {
53 emitEvent({
54 version: 1 as const,
55 revision,
56 type: "snapshot" as const,
57 payload: snapshot,
58 });
59 revision += 1;
60 },
61 emitEvent,
62 emitPairingLinkUpserted(pairingLink: Snapshot["pairingLinks"][number]) {
63 emitEvent({
64 version: 1,
65 revision,
66 type: "pairingLinkUpserted",
67 payload: pairingLink,
68 });
69 revision += 1;
70 },
71 emitPairingLinkRemoved(id: string) {
72 emitEvent({
73 version: 1,
74 revision,
75 type: "pairingLinkRemoved",
76 payload: { id },
77 });
78 revision += 1;
79 },
80 emitClientUpserted(clientSession: Snapshot["clientSessions"][number]) {
81 emitEvent({
82 version: 1,
83 revision,
84 type: "clientUpserted",
85 payload: clientSession,
86 });
87 revision += 1;
88 },
89 emitClientRemoved(sessionId: string) {
90 emitEvent({
91 version: 1,
92 revision,
93 type: "clientRemoved",
94 payload: {
95 sessionId: AuthSessionId.makeUnsafe(sessionId),
96 },
97 });
98 revision += 1;
99 },
100 subscribe(listener: (event: AuthAccessStreamEvent) => void) {
101 listeners.add(listener);
102 listener({
103 version: 1,
104 revision: 1,
105 type: "snapshot",
106 payload: snapshot,
107 });
108 return () => {
109 listeners.delete(listener);
110 };
111 },
112 };
113});
114
115vi.mock("../../environments/runtime", () => {
116 const primaryConnection = {
117 kind: "primary" as const,
118 knownEnvironment: {
119 id: "environment-local",
120 label: "Local environment",
121 source: "manual" as const,
122 environmentId: EnvironmentId.makeUnsafe("environment-local"),
123 target: {
124 httpBaseUrl: "http://localhost:3000",
125 wsBaseUrl: "ws://localhost:3000",
126 },
127 },
128 environmentId: EnvironmentId.makeUnsafe("environment-local"),
129 client: {
130 server: {
131 subscribeAuthAccess: (listener: Parameters<typeof authAccessHarness.subscribe>[0]) =>
132 authAccessHarness.subscribe(listener),
133 },
134 },
135 ensureBootstrapped: async () => undefined,
136 reconnect: async () => undefined,
137 dispose: async () => undefined,
138 };
139
140 return {
141 getEnvironmentHttpBaseUrl: () => "http://localhost:3000",
142 getSavedEnvironmentRecord: () => null,
143 getSavedEnvironmentRuntimeState: () => null,
144 hasSavedEnvironmentRegistryHydrated: () => true,
145 listSavedEnvironmentRecords: () => [],
146 resetSavedEnvironmentRegistryStoreForTests: () => undefined,
147 resetSavedEnvironmentRuntimeStoreForTests: () => undefined,
148 resolveEnvironmentHttpUrl: (_environmentId: unknown, path: string) =>
149 new URL(path, "http://localhost:3000").toString(),
150 waitForSavedEnvironmentRegistryHydration: async () => undefined,
151 addSavedEnvironment: vi.fn(),
152 disconnectSavedEnvironment: vi.fn(),
153 ensureEnvironmentConnectionBootstrapped: async () => undefined,
154 getPrimaryEnvironmentConnection: () => primaryConnection,
155 readEnvironmentConnection: () => primaryConnection,
156 reconnectSavedEnvironment: vi.fn(),
157 removeSavedEnvironment: vi.fn(),
158 requireEnvironmentConnection: () => primaryConnection,
159 resetEnvironmentServiceForTests: () => undefined,
160 startEnvironmentConnectionService: () => undefined,
161 subscribeEnvironmentConnections: () => () => {},
162 useSavedEnvironmentRegistryStore: (
163 selector: (state: { byId: Record<string, never> }) => unknown,
164 ) => selector({ byId: {} }),
165 useSavedEnvironmentRuntimeStore: (
166 selector: (state: { byId: Record<string, never> }) => unknown,
167 ) => selector({ byId: {} }),
168 };
169});
170
171function createBaseServerConfig(): ServerConfig {
172 return {
173 environment: {
174 environmentId: EnvironmentId.makeUnsafe("environment-local"),
175 label: "Local environment",
176 platform: { os: "darwin" as const, arch: "arm64" as const },
177 serverVersion: "0.0.0-test",
178 capabilities: { repositoryIdentity: true },
179 },
180 auth: {
181 policy: "loopback-browser",
182 bootstrapMethods: ["one-time-token"],
183 sessionMethods: ["browser-session-cookie", "bearer-session-token"],
184 sessionCookieName: "t3_session",
185 },
186 cwd: "/repo/project",
187 keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
188 keybindings: [],
189 issues: [],
190 providers: [],
191 availableEditors: ["cursor"],
192 observability: {
193 logsDirectoryPath: "/repo/project/.t3/logs",
194 localTracingEnabled: true,
195 otlpTracesUrl: "http://localhost:4318/v1/traces",
196 otlpTracesEnabled: true,
197 otlpMetricsEnabled: false,
198 },
199 settings: DEFAULT_SERVER_SETTINGS,
200 };
201}
202
203function makeUtc(value: string) {
204 return DateTime.makeUnsafe(Date.parse(value));
205}
206
207function makePairingLink(input: {
208 readonly id: string;
209 readonly credential: string;
210 readonly role: "owner" | "client";
211 readonly subject: string;
212 readonly label?: string;
213 readonly createdAt: string;
214 readonly expiresAt: string;
215}): AuthAccessSnapshot["pairingLinks"][number] {
216 return {
217 ...input,
218 createdAt: makeUtc(input.createdAt),
219 expiresAt: makeUtc(input.expiresAt),
220 };
221}
222
223function makeClientSession(input: {
224 readonly sessionId: string;
225 readonly subject: string;
226 readonly role: "owner" | "client";
227 readonly method: "browser-session-cookie";
228 readonly client?: {
229 readonly label?: string;
230 readonly ipAddress?: string;
231 readonly userAgent?: string;
232 readonly deviceType?: "desktop" | "mobile" | "tablet" | "bot" | "unknown";
233 readonly os?: string;
234 readonly browser?: string;
235 };
236 readonly issuedAt: string;
237 readonly expiresAt: string;
238 readonly lastConnectedAt?: string | null;
239 readonly connected: boolean;
240 readonly current: boolean;
241}): AuthAccessSnapshot["clientSessions"][number] {
242 return {
243 ...input,
244 client: {
245 deviceType: "unknown",
246 ...input.client,
247 },
248 sessionId: AuthSessionId.makeUnsafe(input.sessionId),
249 issuedAt: makeUtc(input.issuedAt),
250 expiresAt: makeUtc(input.expiresAt),
251 lastConnectedAt:
252 input.lastConnectedAt === undefined || input.lastConnectedAt === null
253 ? null
254 : makeUtc(input.lastConnectedAt),
255 };
256}
257
258const createDesktopBridgeStub = (overrides?: {
259 readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
260 readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
261}): DesktopBridge => {
262 const idleUpdateState: DesktopUpdateState = {
263 enabled: false,
264 status: "idle",
265 currentVersion: "0.0.0-test",
266 hostArch: "arm64",
267 appArch: "arm64",
268 runningUnderArm64Translation: false,
269 availableVersion: null,
270 downloadedVersion: null,
271 downloadPercent: null,
272 checkedAt: null,
273 message: null,
274 errorContext: null,
275 canRetry: false,
276 };
277
278 return {
279 getLocalEnvironmentBootstrap: () => ({
280 label: "Local environment",
281 httpBaseUrl: "http://127.0.0.1:3773",
282 wsBaseUrl: "ws://127.0.0.1:3773",
283 bootstrapToken: "desktop-bootstrap-token",
284 }),
285 getClientSettings: vi.fn().mockResolvedValue(null),
286 setClientSettings: vi.fn().mockResolvedValue(undefined),
287 getSavedEnvironmentRegistry: vi.fn().mockResolvedValue([]),
288 setSavedEnvironmentRegistry: vi.fn().mockResolvedValue(undefined),
289 getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null),
290 setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true),
291 removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined),
292 getServerExposureState: vi.fn().mockResolvedValue(
293 overrides?.serverExposureState ?? {
294 mode: "local-only",
295 endpointUrl: null,
296 advertisedHost: null,
297 },
298 ),
299 setServerExposureMode:
300 overrides?.setServerExposureMode ??
301 vi.fn().mockImplementation(async (mode) => ({
302 mode,
303 endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null,
304 advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null,
305 })),
306 pickFolder: vi.fn().mockResolvedValue(null),
307 confirm: vi.fn().mockResolvedValue(false),
308 setTheme: vi.fn().mockResolvedValue(undefined),
309 showContextMenu: vi.fn().mockResolvedValue(null),
310 openExternal: vi.fn().mockResolvedValue(true),
311 onMenuAction: () => () => {},
312 getUpdateState: vi.fn().mockResolvedValue(idleUpdateState),
313 checkForUpdate: vi.fn().mockResolvedValue({ checked: false, state: idleUpdateState }),
314 downloadUpdate: vi
315 .fn()
316 .mockResolvedValue({ accepted: false, completed: false, state: idleUpdateState }),
317 installUpdate: vi
318 .fn()
319 .mockResolvedValue({ accepted: false, completed: false, state: idleUpdateState }),
320 onUpdateState: () => () => {},
321 };
322};
323
324describe("GeneralSettingsPanel observability", () => {
325 let mounted:
326 | (Awaited<ReturnType<typeof render>> & {
327 cleanup?: () => Promise<void>;
328 unmount?: () => Promise<void>;
329 })
330 | null = null;
331
332 beforeEach(async () => {
333 resetServerStateForTests();
334 await __resetLocalApiForTests();
335 localStorage.clear();
336 authAccessHarness.reset();
337 });
338
339 afterEach(async () => {
340 if (mounted) {
341 const teardown = mounted.cleanup ?? mounted.unmount;
342 await teardown?.call(mounted).catch(() => {});
343 }
344 mounted = null;
345 vi.unstubAllGlobals();
346 Reflect.deleteProperty(window, "desktopBridge");
347 Reflect.deleteProperty(window, "nativeApi");
348 document.body.innerHTML = "";
349 resetServerStateForTests();
350 await __resetLocalApiForTests();
351 authAccessHarness.reset();
352 });
353
354 it("hides owner pairing tools in browser-served loopback builds without remote exposure", async () => {
355 Reflect.deleteProperty(window, "desktopBridge");
356 authAccessHarness.setSnapshot({
357 pairingLinks: [],
358 clientSessions: [
359 makeClientSession({
360 sessionId: "session-owner",
361 subject: "browser-owner",
362 role: "owner",
363 method: "browser-session-cookie",
364 client: {
365 label: "Chrome on Mac",
366 deviceType: "desktop",
367 os: "macOS",
368 browser: "Chrome",
369 ipAddress: "127.0.0.1",
370 },
371 issuedAt: "2036-04-07T00:00:00.000Z",
372 expiresAt: "2036-05-07T00:00:00.000Z",
373 connected: true,
374 current: true,
375 }),
376 ],
377 });
378 const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (input) => {
379 const url = String(input);
380 if (url.endsWith("/api/auth/session")) {
381 return new Response(
382 JSON.stringify({
383 authenticated: true,
384 auth: createBaseServerConfig().auth,
385 role: "owner",
386 sessionMethod: "browser-session-cookie",
387 expiresAt: "2036-05-07T00:00:00.000Z",
388 }),
389 {
390 status: 200,
391 headers: { "content-type": "application/json" },
392 },
393 );
394 }
395
396 throw new Error(`Unhandled fetch GET ${url}`);
397 });
398 vi.stubGlobal("fetch", fetchMock);
399
400 mounted = await render(
401 <AppAtomRegistryProvider>
402 <ConnectionsSettings />
403 </AppAtomRegistryProvider>,
404 );
405
406 await expect.element(page.getByText("Manage local backend")).toBeInTheDocument();
407 await expect.element(page.getByLabelText("Enable network access")).toBeDisabled();
408 await expect
409 .element(
410 page.getByText(
411 "This backend is only reachable on this machine. Restart it with a non-loopback host to enable remote pairing.",
412 ),
413 )
414 .toBeInTheDocument();
415 await expect.element(page.getByText("Authorized clients")).not.toBeInTheDocument();
416 await expect.element(page.getByText("Chrome on Mac")).not.toBeInTheDocument();
417 await expect
418 .element(page.getByRole("heading", { name: "Remote environments", exact: true }))
419 .toBeInTheDocument();
420 });
421
422 it("shows diagnostics inside About with a single logs-folder action", async () => {
423 setServerConfigSnapshot(createBaseServerConfig());
424
425 mounted = await render(
426 <AppAtomRegistryProvider>
427 <GeneralSettingsPanel />
428 </AppAtomRegistryProvider>,
429 );
430
431 await expect.element(page.getByText("About")).toBeInTheDocument();
432 await expect.element(page.getByText("Diagnostics")).toBeInTheDocument();
433 await expect.element(page.getByText("Open logs folder")).toBeInTheDocument();
434 await expect
435 .element(page.getByText("/repo/project/.t3/logs", { exact: true }))
436 .toBeInTheDocument();
437 await expect
438 .element(
439 page.getByText(
440 "Local trace file. OTLP exporting traces to http://localhost:4318/v1/traces.",
441 ),
442 )
443 .toBeInTheDocument();
444 });
445
446 it("creates and shows a pairing link when network access is enabled", async () => {
447 window.desktopBridge = createDesktopBridgeStub({
448 serverExposureState: {
449 mode: "network-accessible",
450 endpointUrl: "http://192.168.1.44:3773",
451 advertisedHost: "192.168.1.44",
452 },
453 });
454 let pairingLinks: Array<AuthAccessSnapshot["pairingLinks"][number]> = [];
455 let clientSessions: Array<AuthAccessSnapshot["clientSessions"][number]> = [
456 makeClientSession({
457 sessionId: "session-owner",
458 subject: "desktop-bootstrap",
459 role: "owner",
460 method: "browser-session-cookie",
461 client: {
462 label: "This Mac",
463 deviceType: "desktop",
464 os: "macOS",
465 browser: "Electron",
466 ipAddress: "127.0.0.1",
467 },
468 issuedAt: "2036-04-07T00:00:00.000Z",
469 expiresAt: "2036-05-07T00:00:00.000Z",
470 connected: true,
471 current: true,
472 }),
473 ];
474 authAccessHarness.setSnapshot({
475 pairingLinks,
476 clientSessions,
477 });
478 vi.stubGlobal(
479 "fetch",
480 vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
481 const url = String(input);
482 const method = init?.method ?? "GET";
483 if (url.endsWith("/api/auth/pairing-token") && method === "POST") {
484 pairingLinks = [
485 makePairingLink({
486 id: "pairing-link-1",
487 credential: "pairing-token",
488 role: "client",
489 subject: "one-time-token",
490 label: "Julius iPhone",
491 createdAt: "2036-04-07T00:00:00.000Z",
492 expiresAt: "2036-04-10T00:05:00.000Z",
493 }),
494 ];
495 clientSessions = [
496 ...clientSessions,
497 makeClientSession({
498 sessionId: "session-client",
499 subject: "one-time-token",
500 role: "client",
501 method: "browser-session-cookie",
502 client: {
503 label: "Julius iPhone",
504 deviceType: "mobile",
505 os: "iOS",
506 browser: "Safari",
507 ipAddress: "192.168.1.88",
508 },
509 issuedAt: "2036-04-07T00:01:00.000Z",
510 expiresAt: "2036-05-07T00:01:00.000Z",
511 connected: false,
512 current: false,
513 }),
514 ];
515 authAccessHarness.setSnapshot({
516 pairingLinks,
517 clientSessions,
518 });
519 return new Response(
520 JSON.stringify({
521 id: "pairing-link-1",
522 credential: "pairing-token",
523 label: "Julius iPhone",
524 expiresAt: "2036-04-10T00:05:00.000Z",
525 }),
526 {
527 status: 200,
528 headers: { "content-type": "application/json" },
529 },
530 );
531 }
532
533 throw new Error(`Unhandled fetch ${method} ${url}`);
534 }),
535 );
536
537 setServerConfigSnapshot(createBaseServerConfig());
538
539 mounted = await render(
540 <AppAtomRegistryProvider>
541 <ConnectionsSettings />
542 </AppAtomRegistryProvider>,
543 );
544
545 await expect.element(page.getByText("Authorized clients")).toBeInTheDocument();
546 await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
547 await expect.element(page.getByText("This Mac")).toBeInTheDocument();
548 await page.getByRole("button", { name: "Create link", exact: true }).click();
549 await expect.element(page.getByText("Create pairing link")).toBeInTheDocument();
550 await page.getByRole("button", { name: "Create link", exact: true }).click();
551 authAccessHarness.emitPairingLinkUpserted(pairingLinks[0]!);
552 authAccessHarness.emitClientUpserted(clientSessions[1]!);
553 await expect
554 .element(page.getByText("Client · Mobile · iOS · Safari · 192.168.1.88"))
555 .toBeInTheDocument();
556 await expect
557 .element(page.getByRole("button", { name: /^(Copy|Show link)$/ }))
558 .toBeInTheDocument();
559 await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
560 });
561
562 it("revokes all other paired clients from settings", async () => {
563 window.desktopBridge = createDesktopBridgeStub({
564 serverExposureState: {
565 mode: "network-accessible",
566 endpointUrl: "http://192.168.1.44:3773",
567 advertisedHost: "192.168.1.44",
568 },
569 });
570 let clientSessions: Array<AuthAccessSnapshot["clientSessions"][number]> = [
571 makeClientSession({
572 sessionId: "session-owner",
573 subject: "desktop-bootstrap",
574 role: "owner",
575 method: "browser-session-cookie",
576 client: {
577 label: "This Mac",
578 deviceType: "desktop",
579 os: "macOS",
580 browser: "Electron",
581 },
582 issuedAt: "2036-04-05T00:00:00.000Z",
583 expiresAt: "2036-05-05T00:00:00.000Z",
584 connected: true,
585 current: true,
586 }),
587 makeClientSession({
588 sessionId: "session-client",
589 subject: "one-time-token",
590 role: "client",
591 method: "browser-session-cookie",
592 client: {
593 label: "Julius iPhone",
594 deviceType: "mobile",
595 os: "iOS",
596 browser: "Safari",
597 ipAddress: "192.168.1.88",
598 },
599 issuedAt: "2036-04-05T00:01:00.000Z",
600 expiresAt: "2036-05-05T00:01:00.000Z",
601 connected: false,
602 current: false,
603 }),
604 ];
605 authAccessHarness.setSnapshot({
606 pairingLinks: [],
607 clientSessions,
608 });
609
610 const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
611 const url = String(input);
612 const method = init?.method ?? "GET";
613 if (url.endsWith("/api/auth/clients/revoke-others") && method === "POST") {
614 clientSessions = clientSessions.filter((session) => session.current);
615 authAccessHarness.setSnapshot({
616 pairingLinks: [],
617 clientSessions,
618 });
619 authAccessHarness.emitClientRemoved("session-client");
620 return new Response(JSON.stringify({ revokedCount: 1 }), {
621 status: 200,
622 headers: { "content-type": "application/json" },
623 });
624 }
625
626 throw new Error(`Unhandled fetch ${method} ${url}`);
627 });
628 vi.stubGlobal("fetch", fetchMock);
629
630 setServerConfigSnapshot(createBaseServerConfig());
631
632 mounted = await render(
633 <AppAtomRegistryProvider>
634 <ConnectionsSettings />
635 </AppAtomRegistryProvider>,
636 );
637
638 await expect.element(page.getByText("Julius iPhone")).toBeInTheDocument();
639 await page.getByRole("button", { name: "Revoke others", exact: true }).click();
640 await expect.element(page.getByText("This Mac")).toBeInTheDocument();
641 await expect.element(page.getByText("Julius iPhone")).not.toBeInTheDocument();
642 expect(fetchMock).toHaveBeenCalled();
643 });
644
645 it("shows a disabled network access toggle with guidance in desktop builds", async () => {
646 const desktopBridge = createDesktopBridgeStub();
647 window.desktopBridge = desktopBridge;
648
649 setServerConfigSnapshot(createBaseServerConfig());
650
651 mounted = await render(
652 <AppAtomRegistryProvider>
653 <ConnectionsSettings />
654 </AppAtomRegistryProvider>,
655 );
656
657 const networkAccessToggle = page.getByLabelText("Enable network access");
658 await expect.element(networkAccessToggle).not.toBeDisabled();
659 await networkAccessToggle.click();
660 await expect.element(page.getByText("Enable network access?")).toBeInTheDocument();
661 await expect
662 .element(page.getByText("T3 Code will restart to expose this environment over the network."))
663 .toBeInTheDocument();
664 await page.getByRole("button", { name: "Restart and enable", exact: true }).click();
665 await vi.waitFor(() => {
666 expect(desktopBridge.setServerExposureMode).toHaveBeenCalledWith("network-accessible");
667 });
668 await expect
669 .element(page.getByText("Reachable at http://192.168.1.44:3773"))
670 .toBeInTheDocument();
671 });
672
673 it("opens the logs folder in the preferred editor", async () => {
674 const openInEditor = vi.fn<LocalApi["shell"]["openInEditor"]>().mockResolvedValue(undefined);
675 window.nativeApi = {
676 shell: {
677 openInEditor,
678 },
679 } as unknown as LocalApi;
680
681 setServerConfigSnapshot(createBaseServerConfig());
682
683 mounted = await render(
684 <AppAtomRegistryProvider>
685 <GeneralSettingsPanel />
686 </AppAtomRegistryProvider>,
687 );
688
689 const openLogsButton = page.getByText("Open logs folder");
690 await openLogsButton.click();
691
692 expect(openInEditor).toHaveBeenCalledWith("/repo/project/.t3/logs", "cursor");
693 });
694});