Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 654f8768d5 Format React Scan count artifacts
Co-authored-by: Julius Marminge <[email protected]>
2026-05-23 16:30:03 +00:00
Cursor AgentandJulius Marminge cf4a6a0af7 Refresh settings nav after recording
Co-authored-by: Julius Marminge <[email protected]>
2026-05-23 16:28:59 +00:00
Cursor AgentandJulius Marminge ea12bee21c Address settings nav doctor warnings
Co-authored-by: Julius Marminge <[email protected]>
2026-05-23 16:28:24 +00:00
Cursor AgentandJulius Marminge 0a10cb62c0 Add settings nav React Scan recordings
Co-authored-by: Julius Marminge <[email protected]>
2026-05-23 16:27:29 +00:00
Cursor AgentandJulius Marminge 2fccd1f3de Optimize settings sidebar nav renders
Co-authored-by: Julius Marminge <[email protected]>
2026-05-23 16:26:35 +00:00
13 changed files with 210 additions and 239 deletions

No files matched your search

@@ -1,7 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -16,7 +15,10 @@ const unusedTailscaleExternalServicesLayer = Layer.mergeAll(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected Tailscale HTTPS probe")),
),
Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale status process")),
),
);
describe("tailscale endpoint provider", () => {
@@ -32,8 +34,8 @@ describe("tailscale endpoint provider", () => {
const dnsName = yield* parseTailscaleMagicDnsName(
`{"Self":{"DNSName":"desktop.tail.ts.net."}}`,
);
assert.deepEqual(dnsName, Option.some("desktop.tail.ts.net"));
assert.deepEqual(yield* parseTailscaleMagicDnsName("{}"), Option.none());
assert.equal(dnsName, "desktop.tail.ts.net");
assert.equal(yield* parseTailscaleMagicDnsName("{}"), null);
const malformed = yield* Effect.result(parseTailscaleMagicDnsName("not-json"));
assert.isTrue(malformed._tag === "Failure");
}),
@@ -61,17 +61,17 @@ function resolveTailscaleIpAdvertisedEndpoints(input: {
const resolveTailscaleMagicDnsAdvertisedEndpoint = Effect.fn(
"resolveTailscaleMagicDnsAdvertisedEndpoint",
)(function* (input: {
readonly dnsName: Option.Option<string>;
readonly dnsName: string | null;
readonly serveEnabled: boolean;
readonly servePort?: number;
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
}): Effect.fn.Return<Option.Option<AdvertisedEndpoint>, never, HttpClient.HttpClient> {
if (Option.isNone(input.dnsName)) {
if (!input.dnsName) {
return Option.none();
}
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
magicDnsName: input.dnsName.value,
magicDnsName: input.dnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
});
const probe =
@@ -116,13 +116,13 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.statusJson === undefined
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(Option.none())),
Effect.catch(() => Effect.succeed(null)),
)
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.catch(() => Effect.succeed(Option.none())),
Effect.catch(() => Effect.succeed(null)),
)
: Option.none();
: null;
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
dnsName,
serveEnabled: input.serveEnabled === true,
@@ -1,4 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -41,7 +41,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
assert.deepEqual(rows, [
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
@@ -66,61 +66,6 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows process JSON through schema decoding", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
JSON.stringify([
{
ProcessId: 10,
ParentProcessId: 1,
Name: "node.exe",
CommandLine: "node server.js",
Status: "Running",
WorkingSetSize: 1024,
PercentProcessorTime: 1.5,
},
{
ProcessId: 11,
ParentProcessId: 10,
Name: "child.exe",
CommandLine: "",
WorkingSetSize: 2048.2,
},
{
ProcessId: "bad",
ParentProcessId: 10,
Name: "ignored.exe",
},
]),
);
assert.deepEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 1.5,
rssBytes: 1024,
elapsed: "",
command: "node server.js",
},
{
pid: 11,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 2048,
elapsed: "",
command: "child.exe",
},
]);
assert.deepEqual(ProcessDiagnostics.parseWindowsProcessRows("not-json"), []);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -180,21 +125,15 @@ describe("ProcessDiagnostics", () => {
],
});
assert.equal(diagnostics.serverPid, 100);
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
assert.equal(diagnostics.processCount, 2);
assert.equal(diagnostics.totalRssBytes, 6_000);
assert.equal(diagnostics.totalCpuPercent, 4.75);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102],
);
assert.deepEqual(
diagnostics.processes.map((process) => process.depth),
[0, 1],
);
assert.equal(Option.getOrNull(diagnostics.processes[0]!.pgid), 100);
assert.deepEqual(diagnostics.processes[0]?.childPids, [102]);
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
@@ -237,10 +176,7 @@ describe("ProcessDiagnostics", () => {
],
});
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102, 103],
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
@@ -248,8 +184,9 @@ describe("ProcessDiagnostics", () => {
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) => {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -263,8 +200,8 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
}),
);
},
});
}),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
@@ -272,11 +209,8 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[4242],
);
assert.deepEqual(commands, [
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
@@ -287,8 +221,9 @@ describe("ProcessDiagnostics", () => {
it.effect("does not allow signaling the diagnostics query process", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: () =>
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
stdout: [
@@ -297,7 +232,8 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
}),
),
});
),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
@@ -305,7 +241,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(result, {
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
@@ -26,7 +26,7 @@ export interface ProcessRow {
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
@@ -74,22 +74,6 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
const WindowsProcessRecord = Schema.Struct({
CommandLine: Schema.optional(Schema.Unknown),
Name: Schema.optional(Schema.Unknown),
ParentProcessId: Schema.optional(Schema.Unknown),
PercentProcessorTime: Schema.optional(Schema.Unknown),
ProcessId: Schema.optional(Schema.Unknown),
Status: Schema.optional(Schema.Unknown),
WorkingSetSize: Schema.optional(Schema.Unknown),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const WindowsProcessOutput = Schema.fromJsonString(
Schema.Union([WindowsProcessRecord, Schema.Array(WindowsProcessRecord)]),
);
const decodeWindowsProcessOutput = Schema.decodeUnknownOption(WindowsProcessOutput);
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -155,7 +139,9 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(record: WindowsProcessRecord): ProcessRow | null {
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
@@ -186,18 +172,18 @@ function normalizeWindowsProcessRow(record: WindowsProcessRecord): ProcessRow |
};
}
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
const parsed = decodeWindowsProcessOutput(output);
if (Option.isNone(parsed)) {
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
}
export function buildDescendantEntries(
@@ -323,7 +309,7 @@ const runProcess = Effect.fn("runProcess")(
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
@@ -0,0 +1,32 @@
import {
ArchiveIcon,
BotIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
Settings2Icon,
} from "lucide-react";
import type { ComponentType } from "react";
export type SettingsSectionPath =
| "/settings/general"
| "/settings/keybindings"
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/archived";
export interface SettingsNavItem {
readonly icon: ComponentType<{ className?: string }>;
readonly label: string;
readonly to: SettingsSectionPath;
}
export const SETTINGS_NAV_ITEMS: ReadonlyArray<SettingsNavItem> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
@@ -1,13 +1,5 @@
import { useCallback, type ComponentType } from "react";
import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
Settings2Icon,
} from "lucide-react";
import { useCallback } from "react";
import { ArrowLeftIcon } from "lucide-react";
import { useCanGoBack, useNavigate } from "@tanstack/react-router";
import {
@@ -20,27 +12,8 @@ import {
SidebarSeparator,
useSidebar,
} from "../ui/sidebar";
export type SettingsSectionPath =
| "/settings/general"
| "/settings/keybindings"
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
to: SettingsSectionPath;
icon: ComponentType<{ className?: string }>;
}> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
import { SETTINGS_NAV_ITEMS, type SettingsSectionPath } from "./SettingsSidebarNav.items";
import { SettingsSidebarNavItem } from "./SettingsSidebarNavItem";
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
const navigate = useNavigate();
@@ -71,33 +44,14 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
<SidebarContent className="overflow-x-hidden">
<SidebarGroup className="px-2 py-3">
<SidebarMenu>
{SETTINGS_NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to;
return (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
size="sm"
isActive={isActive}
className={
isActive
? "gap-2.5 px-2.5 py-2 text-left text-[13px] font-medium text-foreground"
: "gap-2.5 px-2.5 py-2 text-left text-[13px] text-muted-foreground/70 hover:text-foreground/80"
}
onClick={() => handleSectionClick(item.to)}
>
<Icon
className={
isActive
? "size-4 shrink-0 text-foreground"
: "size-4 shrink-0 text-muted-foreground/60"
}
/>
<span className="truncate">{item.label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
{SETTINGS_NAV_ITEMS.map((item) => (
<SettingsSidebarNavItem
key={item.to}
item={item}
isActive={pathname === item.to}
onSelect={handleSectionClick}
/>
))}
</SidebarMenu>
</SidebarGroup>
</SidebarContent>
@@ -108,7 +62,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
className="gap-2 p-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
onClick={handleBackClick}
>
<ArrowLeftIcon className="size-4" />
@@ -0,0 +1,45 @@
import { memo, useCallback } from "react";
import { SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
import type { SettingsNavItem, SettingsSectionPath } from "./SettingsSidebarNav.items";
interface SettingsSidebarNavItemProps {
readonly isActive: boolean;
readonly item: SettingsNavItem;
readonly onSelect: (to: SettingsSectionPath) => void;
}
export const SettingsSidebarNavItem = memo(function SettingsSidebarNavItem({
isActive,
item,
onSelect,
}: SettingsSidebarNavItemProps) {
const Icon = item.icon;
const selectSettingsSection = useCallback(() => {
onSelect(item.to);
}, [item.to, onSelect]);
return (
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
isActive={isActive}
className={
isActive
? "gap-2.5 px-2.5 py-2 text-left text-[13px] font-medium text-foreground"
: "gap-2.5 px-2.5 py-2 text-left text-[13px] text-muted-foreground/70 hover:text-foreground/80"
}
onClick={selectSettingsSection}
>
<Icon
className={
isActive
? "size-4 shrink-0 text-foreground"
: "size-4 shrink-0 text-muted-foreground/60"
}
/>
<span className="truncate">{item.label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
);
});
@@ -0,0 +1,13 @@
{
"Archive": 1,
"Bot": 3,
"GitBranch": 3,
"Keyboard": 3,
"Link2": 1,
"Settings2": 4,
"SettingsSidebarNav": 6,
"SettingsSidebarNavItem": 15,
"Sidebar": 6,
"SidebarMenuButton": 16,
"SidebarMenuItem": 16
}
Binary file not shown.
@@ -0,0 +1,12 @@
{
"Archive": 6,
"Bot": 6,
"GitBranch": 6,
"Keyboard": 6,
"Link2": 6,
"Settings2": 6,
"SettingsSidebarNav": 6,
"Sidebar": 6,
"SidebarMenuButton": 37,
"SidebarMenuItem": 37
}
Binary file not shown.
+9 -9
View File
@@ -1,7 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -42,15 +41,16 @@ function mockSpawnerLayer(
args: ReadonlyArray<string>,
) => { stdout?: string; stderr?: string; code?: number },
) {
return Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) => {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
},
});
}),
);
}
describe("tailscale", () => {
@@ -66,8 +66,8 @@ describe("tailscale", () => {
it.effect("parses MagicDNS names from tailscale status", () =>
Effect.gen(function* () {
const dnsName = yield* parseTailscaleMagicDnsName(tailscaleStatusJson);
assert.deepEqual(dnsName, Option.some("desktop.tail.ts.net"));
assert.deepEqual(yield* parseTailscaleMagicDnsName("{}"), Option.none());
assert.equal(dnsName, "desktop.tail.ts.net");
assert.equal(yield* parseTailscaleMagicDnsName("{}"), null);
}),
);
@@ -75,7 +75,7 @@ describe("tailscale", () => {
Effect.gen(function* () {
const status = yield* parseTailscaleStatus(tailscaleStatusJson);
assert.deepEqual(status, {
magicDnsName: Option.some("desktop.tail.ts.net"),
magicDnsName: "desktop.tail.ts.net",
tailnetIpv4Addresses: ["100.100.100.100"],
});
}),
@@ -106,7 +106,7 @@ describe("tailscale", () => {
return Effect.gen(function* () {
const status = yield* readTailscaleStatus.pipe(Effect.provide(layer));
assert.deepEqual(status, {
magicDnsName: Option.some("desktop.tail.ts.net"),
magicDnsName: "desktop.tail.ts.net",
tailnetIpv4Addresses: ["100.90.1.2"],
});
});
+35 -44
View File
@@ -1,4 +1,4 @@
import * as Duration from "effect/Duration";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -7,33 +7,24 @@ import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
export const TAILSCALE_STATUS_TIMEOUT = Duration.millis(1_500);
export const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
export const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);
export const TAILSCALE_STATUS_TIMEOUT_MS = 1_500;
export const TAILSCALE_SERVE_TIMEOUT_MS = 10_000;
export const TAILSCALE_PROBE_TIMEOUT_MS = 2_500;
export class TailscaleCommandError extends Schema.TaggedErrorClass<TailscaleCommandError>()(
"TailscaleCommandError",
{
command: Schema.Array(Schema.String),
message: Schema.String,
exitCode: Schema.NullOr(Schema.Number),
stderr: Schema.String,
},
) {}
export class TailscaleCommandError extends Data.TaggedError("TailscaleCommandError")<{
readonly command: readonly string[];
readonly message: string;
readonly exitCode: number | null;
readonly stderr: string;
}> {}
export class TailscaleStatusParseError extends Schema.TaggedErrorClass<TailscaleStatusParseError>()(
"TailscaleStatusParseError",
{
cause: Schema.Defect,
},
) {}
export class TailscaleStatusParseError extends Data.TaggedError("TailscaleStatusParseError")<{
readonly cause: unknown;
}> {}
export class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(
"TailscaleUnavailableError",
{
reason: Schema.String,
},
) {}
export class TailscaleUnavailableError extends Data.TaggedError("TailscaleUnavailableError")<{
readonly reason: string;
}> {}
const TailscaleStatusSelf = Schema.Struct({
DNSName: Schema.optional(Schema.Unknown),
@@ -48,7 +39,7 @@ export type TailscaleStatusSelf = typeof TailscaleStatusSelf.Type;
export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
export interface TailscaleStatus {
readonly magicDnsName: Option.Option<string>;
readonly magicDnsName: string | null;
readonly tailnetIpv4Addresses: readonly string[];
}
@@ -78,19 +69,19 @@ const tailscaleCommandError = (
const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
function normalizeMagicDnsName(status: TailscaleStatusJson): Option.Option<string> {
function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
const dnsName = status.Self?.DNSName;
if (typeof dnsName !== "string") {
return Option.none();
return null;
}
const normalized = dnsName.trim().replace(/\.$/u, "");
return normalized.length > 0 ? Option.some(normalized) : Option.none();
return normalized.length > 0 ? normalized : null;
}
export const parseTailscaleMagicDnsName = (
rawStatusJson: string,
): Effect.Effect<Option.Option<string>, TailscaleStatusParseError> =>
): Effect.Effect<string | null, TailscaleStatusParseError> =>
decodeTailscaleStatusJson(rawStatusJson).pipe(
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
Effect.map(normalizeMagicDnsName),
@@ -183,7 +174,7 @@ export const readTailscaleStatus: Effect.Effect<
return yield* parseTailscaleStatus(stdout);
}).pipe(
Effect.scoped,
Effect.timeoutOption(TAILSCALE_STATUS_TIMEOUT),
Effect.timeoutOption(TAILSCALE_STATUS_TIMEOUT_MS),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
@@ -215,7 +206,7 @@ const runTailscaleCommand = (
readonly runMessage: string;
readonly exitMessage: (exitCode: number) => string;
readonly timeoutMessage: string;
readonly timeout: Duration.Duration;
readonly timeoutMs: number;
},
): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.gen(function* () {
@@ -252,7 +243,7 @@ const runTailscaleCommand = (
}
}).pipe(
Effect.scoped,
Effect.timeoutOption(input.timeout),
Effect.timeoutOption(input.timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(tailscaleCommandError(args, input.timeoutMessage, null)),
@@ -274,7 +265,7 @@ export const ensureTailscaleServe = (input: {
runMessage: "Failed to run tailscale serve.",
exitMessage: (exitCode) => `Tailscale serve exited with code ${exitCode}.`,
timeoutMessage: "Tailscale serve timed out.",
timeout: TAILSCALE_SERVE_TIMEOUT,
timeoutMs: TAILSCALE_SERVE_TIMEOUT_MS,
});
};
@@ -290,13 +281,13 @@ export const disableTailscaleServe = (
runMessage: "Failed to run tailscale serve off.",
exitMessage: (exitCode) => `Tailscale serve off exited with code ${exitCode}.`,
timeoutMessage: "Tailscale serve off timed out.",
timeout: TAILSCALE_SERVE_TIMEOUT,
timeoutMs: TAILSCALE_SERVE_TIMEOUT_MS,
});
});
export const probeTailscaleHttpsEndpoint = (input: {
readonly baseUrl: string;
readonly timeout?: Duration.Duration;
readonly timeoutMs?: number;
}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
@@ -304,7 +295,7 @@ export const probeTailscaleHttpsEndpoint = (input: {
const url = new URL("/.well-known/t3/environment", input.baseUrl);
const request = HttpClientRequest.get(url.toString());
return yield* client.execute(request);
}).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
}).pipe(Effect.timeoutOption(input.timeoutMs ?? TAILSCALE_PROBE_TIMEOUT_MS));
return Option.match(response, {
onNone: () => false,
@@ -317,17 +308,17 @@ export const resolveTailscaleHttpsBaseUrl = (
readonly servePort?: number;
} = {},
): Effect.Effect<
Option.Option<string>,
string | null,
TailscaleCommandError | TailscaleStatusParseError,
ChildProcessSpawner.ChildProcessSpawner
> =>
readTailscaleStatus.pipe(
Effect.map((status) =>
Option.map(status.magicDnsName, (magicDnsName) =>
buildTailscaleHttpsBaseUrl({
magicDnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
}),
),
status.magicDnsName
? buildTailscaleHttpsBaseUrl({
magicDnsName: status.magicDnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
})
: null,
),
);