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