Improve WSL project selection for desktop local backends
This commit is contained in:
1 parent
520144f76c
commit
97b008ec81
13 files changed
+705
-337
No files matched your search
@@ -47,6 +47,7 @@ import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { desktopLocalBackendId } from "../connection/desktopLocal";
|
||||
import { filesystemEnvironment } from "../state/filesystem";
|
||||
import { projectEnvironment } from "../state/projects";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
@@ -79,6 +80,7 @@ import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import { parseWslUncPath, resolveWslProjectSelection } from "../wslPaths";
|
||||
import {
|
||||
ADDON_ICON_CLASS,
|
||||
buildBrowseGroups,
|
||||
@@ -500,6 +502,18 @@ function OpenCommandPaletteDialog(props: {
|
||||
return options;
|
||||
}, [environments]);
|
||||
const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null;
|
||||
const wslAddProjectEnvironmentOption = useMemo(
|
||||
() =>
|
||||
addProjectEnvironmentOptions.find((option) => {
|
||||
const environment = environments.find(
|
||||
(candidate) => candidate.environmentId === option.environmentId,
|
||||
);
|
||||
return environment
|
||||
? desktopLocalBackendId(environment.entry.target)?.startsWith("wsl:") === true
|
||||
: false;
|
||||
}) ?? null,
|
||||
[addProjectEnvironmentOptions, environments],
|
||||
);
|
||||
const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
|
||||
const browseEnvironment =
|
||||
environments.find((environment) => environment.environmentId === browseEnvironmentId) ?? null;
|
||||
@@ -984,6 +998,21 @@ function OpenCommandPaletteDialog(props: {
|
||||
},
|
||||
});
|
||||
|
||||
if (wslAddProjectEnvironmentOption) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:add-project:wsl-folder",
|
||||
searchTerms: ["add project", "open", "wsl", "linux", "folder", "directory"],
|
||||
title: "Open WSL folder",
|
||||
description: wslAddProjectEnvironmentOption.label,
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectBrowse(wslAddProjectEnvironmentOption.environmentId);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:settings",
|
||||
@@ -1016,11 +1045,16 @@ function OpenCommandPaletteDialog(props: {
|
||||
threadSearchItems: allThreadItems,
|
||||
});
|
||||
|
||||
const handleAddProject = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
if (!browseEnvironmentId) return;
|
||||
const handleAddProjectForEnvironment = useCallback(
|
||||
async (input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly rawCwd: string;
|
||||
readonly platform: string;
|
||||
readonly currentProjectCwd: string | null;
|
||||
}) => {
|
||||
const rawCwd = input.rawCwd;
|
||||
|
||||
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
|
||||
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), input.platform)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
@@ -1031,7 +1065,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
|
||||
if (isExplicitRelativeProjectPath(rawCwd.trim()) && !input.currentProjectCwd) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
@@ -1042,11 +1076,11 @@ function OpenCommandPaletteDialog(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse);
|
||||
const cwd = resolveProjectPathForDispatch(rawCwd, input.currentProjectCwd);
|
||||
if (cwd.length === 0) return;
|
||||
|
||||
const existing = findProjectByPath(
|
||||
projects.filter((project) => project.environmentId === browseEnvironmentId),
|
||||
projects.filter((project) => project.environmentId === input.environmentId),
|
||||
cwd,
|
||||
);
|
||||
if (existing) {
|
||||
@@ -1084,7 +1118,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
const projectId = newProjectId();
|
||||
const createResult = await createProject({
|
||||
environmentId: browseEnvironmentId,
|
||||
environmentId: input.environmentId,
|
||||
input: {
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(cwd),
|
||||
@@ -1111,7 +1145,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
}
|
||||
|
||||
const navigationResult = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(browseEnvironmentId, projectId)),
|
||||
handleNewThread(scopeProjectRef(input.environmentId, projectId)),
|
||||
);
|
||||
if (navigationResult._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(navigationResult);
|
||||
@@ -1127,9 +1161,6 @@ function OpenCommandPaletteDialog(props: {
|
||||
setOpen(false);
|
||||
},
|
||||
[
|
||||
browseEnvironmentId,
|
||||
browseEnvironmentPlatform,
|
||||
currentProjectCwdForBrowse,
|
||||
handleNewThread,
|
||||
createProject,
|
||||
navigate,
|
||||
@@ -1140,6 +1171,24 @@ function OpenCommandPaletteDialog(props: {
|
||||
],
|
||||
);
|
||||
|
||||
const handleAddProject = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
if (!browseEnvironmentId) return;
|
||||
await handleAddProjectForEnvironment({
|
||||
environmentId: browseEnvironmentId,
|
||||
rawCwd,
|
||||
platform: browseEnvironmentPlatform,
|
||||
currentProjectCwd: currentProjectCwdForBrowse,
|
||||
});
|
||||
},
|
||||
[
|
||||
browseEnvironmentId,
|
||||
browseEnvironmentPlatform,
|
||||
currentProjectCwdForBrowse,
|
||||
handleAddProjectForEnvironment,
|
||||
],
|
||||
);
|
||||
|
||||
function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
|
||||
return getAddProjectInitialQueryForEnvironment(environmentId);
|
||||
}
|
||||
@@ -1369,11 +1418,13 @@ function OpenCommandPaletteDialog(props: {
|
||||
query.trim().length > 0 &&
|
||||
!isRemoteProjectPending;
|
||||
const fileManagerName = getLocalFileManagerName(navigator.platform);
|
||||
const browseDesktopLocalBackendId = browseEnvironment
|
||||
? desktopLocalBackendId(browseEnvironment.entry.target)
|
||||
: null;
|
||||
const canOpenProjectFromFileManager =
|
||||
isBrowsing &&
|
||||
browseEnvironmentId !== null &&
|
||||
primaryEnvironmentId !== null &&
|
||||
browseEnvironmentId === primaryEnvironmentId &&
|
||||
(browseEnvironmentId === primaryEnvironmentId || browseDesktopLocalBackendId !== null) &&
|
||||
typeof window !== "undefined" &&
|
||||
window.desktopBridge !== undefined;
|
||||
const fileManagerInitialPath = useMemo(() => {
|
||||
@@ -1469,8 +1520,14 @@ function OpenCommandPaletteDialog(props: {
|
||||
setIsPickingProjectFolder(true);
|
||||
let pickedPath: string | null = null;
|
||||
try {
|
||||
const pickerOptions = {
|
||||
...(fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : {}),
|
||||
...(browseDesktopLocalBackendId
|
||||
? { targetEnvironmentId: browseDesktopLocalBackendId }
|
||||
: {}),
|
||||
};
|
||||
pickedPath = await api.dialogs.pickFolder(
|
||||
fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined,
|
||||
Object.keys(pickerOptions).length > 0 ? pickerOptions : undefined,
|
||||
);
|
||||
} catch {
|
||||
// Ignore picker failures and leave the palette open.
|
||||
@@ -1481,11 +1538,40 @@ function OpenCommandPaletteDialog(props: {
|
||||
if (!pickedPath) {
|
||||
return;
|
||||
}
|
||||
if (parseWslUncPath(pickedPath)) {
|
||||
const selection = resolveWslProjectSelection(
|
||||
pickedPath,
|
||||
environments.flatMap((environment) => {
|
||||
const backendId = desktopLocalBackendId(environment.entry.target);
|
||||
return backendId ? [{ environmentId: environment.environmentId, backendId }] : [];
|
||||
}),
|
||||
);
|
||||
if (!selection) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not add WSL project",
|
||||
description: "Start the matching WSL backend, then choose the folder again.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await handleAddProjectForEnvironment({
|
||||
environmentId: selection.environmentId,
|
||||
rawCwd: selection.linuxPath,
|
||||
platform: "Linux",
|
||||
currentProjectCwd: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await handleAddProject(pickedPath);
|
||||
}, [
|
||||
browseDesktopLocalBackendId,
|
||||
canOpenProjectFromFileManager,
|
||||
environments,
|
||||
fileManagerInitialPath,
|
||||
handleAddProject,
|
||||
handleAddProjectForEnvironment,
|
||||
isPickingProjectFolder,
|
||||
]);
|
||||
|
||||
|
||||
@@ -15,16 +15,14 @@ import {
|
||||
/**
|
||||
* A local environment is either the same-origin primary backend or a
|
||||
* desktop-local secondary (the parallel WSL backend), which connects over
|
||||
* loopback with a bearer token and carries a `local:<environmentId>`
|
||||
* loopback with a bearer token and carries a `local:<backendInstanceId>`
|
||||
* connection id. SSH, relay, and other remote targets are excluded.
|
||||
*/
|
||||
function isLocalConnectionTarget(target: ConnectionCatalogEntry["target"]): boolean {
|
||||
return target._tag === "PrimaryConnectionTarget" || isDesktopLocalConnectionTarget(target);
|
||||
}
|
||||
|
||||
function normalizeConnectionState(
|
||||
phase: string | undefined,
|
||||
): EnvironmentUpdateConnectionState {
|
||||
function normalizeConnectionState(phase: string | undefined): EnvironmentUpdateConnectionState {
|
||||
switch (phase) {
|
||||
case "connected":
|
||||
return "ready";
|
||||
|
||||
@@ -19,7 +19,7 @@ import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
/**
|
||||
* True when a desktop-local secondary backend (the parallel WSL backend) is
|
||||
* present alongside the primary. Local secondaries connect over loopback with a
|
||||
* `local:<environmentId>` bearer connection id; everything else (SSH, relay,
|
||||
* `local:<backendInstanceId>` bearer connection id; everything else (SSH, relay,
|
||||
* remote) is ignored. Gating on this keeps non-WSL users on the unchanged
|
||||
* single-prompt flow.
|
||||
*/
|
||||
@@ -27,9 +27,7 @@ function useHasLocalSecondaryEnvironment(): boolean {
|
||||
const { environments } = useEnvironments();
|
||||
return useMemo(
|
||||
() =>
|
||||
environments.some((environment) =>
|
||||
isDesktopLocalConnectionTarget(environment.entry.target),
|
||||
),
|
||||
environments.some((environment) => isDesktopLocalConnectionTarget(environment.entry.target)),
|
||||
[environments],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -135,6 +135,11 @@ import {
|
||||
refreshDesktopNetworkAccessState,
|
||||
} from "~/state/desktopNetworkAccess";
|
||||
import { desktopSshHostsStateAtom } from "~/state/desktopSshHosts";
|
||||
import {
|
||||
desktopWslStateAtom,
|
||||
refreshDesktopWslState,
|
||||
setDesktopWslStateSnapshot,
|
||||
} from "~/state/desktopWslState";
|
||||
import {
|
||||
type EnvironmentPresentation,
|
||||
useEnvironments,
|
||||
@@ -1536,7 +1541,9 @@ function SavedBackendListRow({
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isConnecting || removingEnvironmentId === environmentId}
|
||||
onClick={() => void (isConnected ? onRemove(environmentId) : onConnect(environmentId))}
|
||||
onClick={() =>
|
||||
void (isConnected ? onRemove(environmentId) : onConnect(environmentId))
|
||||
}
|
||||
>
|
||||
{isConnected
|
||||
? removingEnvironmentId === environmentId
|
||||
@@ -2096,10 +2103,8 @@ export function ConnectionsSettings() {
|
||||
const [isUpdatingDesktopServerExposure, setIsUpdatingDesktopServerExposure] = useState(false);
|
||||
const [isDesktopServerExposureDialogOpen, setIsDesktopServerExposureDialogOpen] = useState(false);
|
||||
const [isUpdatingTailscaleServe, setIsUpdatingTailscaleServe] = useState(false);
|
||||
const [desktopWslState, setDesktopWslState] = useState<DesktopWslState | null>(null);
|
||||
const [isUpdatingWslBackend, setIsUpdatingWslBackend] = useState(false);
|
||||
const [desktopWslError, setDesktopWslError] = useState<string | null>(null);
|
||||
const [isLoadingWslState, setIsLoadingWslState] = useState(false);
|
||||
const [desktopWslMutationError, setDesktopWslMutationError] = useState<string | null>(null);
|
||||
// Pending WSL setting change waiting on user confirmation. Set when
|
||||
// the user tries a destructive change (disable, switch distro,
|
||||
// toggle wsl-only) while the WSL backend has saved-env state on this
|
||||
@@ -2158,6 +2163,12 @@ export function ConnectionsSettings() {
|
||||
? desktopSshHostsStateAtom
|
||||
: null,
|
||||
);
|
||||
const desktopWsl = useEnvironmentQuery(
|
||||
canManageLocalBackend && desktopBridge ? desktopWslStateAtom : null,
|
||||
);
|
||||
const desktopWslState = desktopWsl.data;
|
||||
const desktopWslError = desktopWslMutationError ?? desktopWsl.error;
|
||||
const isLoadingWslState = desktopWsl.isPending && desktopWsl.data === null;
|
||||
const discoveredSshHosts = desktopSshHosts.data ?? EMPTY_DISCOVERED_SSH_HOSTS;
|
||||
const unsavedDiscoveredSshHosts = useMemo(
|
||||
() =>
|
||||
@@ -2859,17 +2870,17 @@ export function ConnectionsSettings() {
|
||||
async (apply: () => Promise<DesktopWslState>) => {
|
||||
if (!desktopBridge) return;
|
||||
setIsUpdatingWslBackend(true);
|
||||
setDesktopWslError(null);
|
||||
setDesktopWslMutationError(null);
|
||||
try {
|
||||
const next = await apply();
|
||||
setDesktopWslState(next);
|
||||
setDesktopWslStateSnapshot(next);
|
||||
// The connection platform source polls the desktop bootstrap list and
|
||||
// reconciles the environment catalog automatically, so toggling the WSL
|
||||
// backend on/off or switching distros is picked up here without an
|
||||
// explicit renderer reconcile.
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to update WSL backend.";
|
||||
setDesktopWslError(message);
|
||||
setDesktopWslMutationError(message);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
@@ -2879,7 +2890,7 @@ export function ConnectionsSettings() {
|
||||
);
|
||||
await desktopBridge
|
||||
.getWslState()
|
||||
.then((state) => setDesktopWslState(state))
|
||||
.then((state) => setDesktopWslStateSnapshot(state))
|
||||
.catch(() => undefined);
|
||||
} finally {
|
||||
setIsUpdatingWslBackend(false);
|
||||
@@ -2888,40 +2899,12 @@ export function ConnectionsSettings() {
|
||||
[desktopBridge],
|
||||
);
|
||||
|
||||
// Load the WSL backend state from the desktop bridge. Clears the error only on
|
||||
// success, so a failed load's message stays visible (including across an
|
||||
// in-flight retry, rather than the row flickering away), and tracks a loading
|
||||
// flag for the retry control. Reused by the retry control in renderWslRow.
|
||||
// Reload the keep-alive WSL state atom. Clearing the mutation error before
|
||||
// refresh lets the atom-owned load error become the visible retry state.
|
||||
const loadWslState = useCallback(() => {
|
||||
if (!desktopBridge) {
|
||||
return;
|
||||
}
|
||||
setIsLoadingWslState(true);
|
||||
void desktopBridge
|
||||
.getWslState()
|
||||
.then((state) => {
|
||||
setDesktopWslState(state);
|
||||
setDesktopWslError(null);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
setDesktopWslError(error instanceof Error ? error.message : "Failed to load WSL state.");
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoadingWslState(false);
|
||||
});
|
||||
}, [desktopBridge]);
|
||||
|
||||
// Seed the WSL backend state on mount (and when local-backend management
|
||||
// becomes available). Without this, desktopWslState stays null and
|
||||
// renderWslRow() bails, hiding the WSL settings UI entirely. The broader
|
||||
// desktop access-management state is owned by desktopNetworkAccess upstream;
|
||||
// this only owns the WSL picker's state.
|
||||
useEffect(() => {
|
||||
if (!canManageLocalBackend) {
|
||||
return;
|
||||
}
|
||||
loadWslState();
|
||||
}, [canManageLocalBackend, loadWslState]);
|
||||
setDesktopWslMutationError(null);
|
||||
refreshDesktopWslState();
|
||||
}, []);
|
||||
|
||||
// True when a desktop-local WSL backend is currently registered as an
|
||||
// environment on this machine. We use this as a proxy for "the user has work
|
||||
@@ -3174,8 +3157,9 @@ export function ConnectionsSettings() {
|
||||
/>
|
||||
{desktopWslState.enabled ? (
|
||||
<SettingsRow
|
||||
title="Run WSL only"
|
||||
title="WSL only"
|
||||
description="Stop the Windows backend and run only the WSL backend. Useful if you develop entirely inside WSL and don't want a second backend process. T3 Code restarts when you change this."
|
||||
className="bg-muted/20 pl-7 sm:pl-8"
|
||||
control={
|
||||
<Switch
|
||||
checked={desktopWslState.wslOnly}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
BearerConnectionTarget,
|
||||
PrimaryConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
desktopLocalBackendId,
|
||||
desktopLocalConnectionId,
|
||||
isDesktopLocalConnectionTarget,
|
||||
} from "./desktopLocal";
|
||||
|
||||
describe("desktop local connection identity", () => {
|
||||
it("preserves the desktop backend instance id", () => {
|
||||
const target = new BearerConnectionTarget({
|
||||
connectionId: desktopLocalConnectionId("wsl:Ubuntu"),
|
||||
environmentId: EnvironmentId.make("environment-wsl"),
|
||||
label: "WSL (Ubuntu)",
|
||||
});
|
||||
|
||||
expect(isDesktopLocalConnectionTarget(target)).toBe(true);
|
||||
expect(desktopLocalBackendId(target)).toBe("wsl:Ubuntu");
|
||||
});
|
||||
|
||||
it("does not classify the primary environment as desktop-local", () => {
|
||||
const target = new PrimaryConnectionTarget({
|
||||
environmentId: EnvironmentId.make("environment-primary"),
|
||||
httpBaseUrl: "http://127.0.0.1:3773",
|
||||
label: "This device",
|
||||
wsBaseUrl: "ws://127.0.0.1:3773",
|
||||
});
|
||||
|
||||
expect(isDesktopLocalConnectionTarget(target)).toBe(false);
|
||||
expect(desktopLocalBackendId(target)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -15,17 +15,25 @@ import { PRIMARY_LOCAL_ENVIRONMENT_ID, type DesktopEnvironmentBootstrap } from "
|
||||
*/
|
||||
export const DESKTOP_LOCAL_CONNECTION_ID_PREFIX = "local:";
|
||||
|
||||
export function desktopLocalConnectionId(environmentId: string): string {
|
||||
return `${DESKTOP_LOCAL_CONNECTION_ID_PREFIX}${environmentId}`;
|
||||
export function desktopLocalConnectionId(backendId: string): string {
|
||||
return `${DESKTOP_LOCAL_CONNECTION_ID_PREFIX}${backendId}`;
|
||||
}
|
||||
|
||||
export function isDesktopLocalConnectionTarget(target: ConnectionTarget): boolean {
|
||||
export function isDesktopLocalConnectionTarget(
|
||||
target: ConnectionTarget,
|
||||
): target is Extract<ConnectionTarget, { readonly _tag: "BearerConnectionTarget" }> {
|
||||
return (
|
||||
target._tag === "BearerConnectionTarget" &&
|
||||
target.connectionId.startsWith(DESKTOP_LOCAL_CONNECTION_ID_PREFIX)
|
||||
);
|
||||
}
|
||||
|
||||
export function desktopLocalBackendId(target: ConnectionTarget): string | null {
|
||||
return isDesktopLocalConnectionTarget(target)
|
||||
? target.connectionId.slice(DESKTOP_LOCAL_CONNECTION_ID_PREFIX.length)
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the desktop's secondary local backends (everything except the primary)
|
||||
* from the bridge. Returns an empty list off-desktop or if the bridge throws.
|
||||
|
||||
@@ -325,7 +325,11 @@ const loadSecondaryConnectionRegistration = Effect.fn(
|
||||
scopes: AuthStandardClientScopes,
|
||||
clientMetadata: clientMetadata(),
|
||||
}).pipe(Effect.mapError(mapRemoteEnvironmentError));
|
||||
const connectionId = desktopLocalConnectionId(descriptor.environmentId);
|
||||
// Keep the desktop pool's stable backend id in the connection id. The
|
||||
// descriptor environment id still scopes projects and RPC state, while the
|
||||
// backend id lets desktop-only operations (notably the WSL folder picker)
|
||||
// route back to the instance that owns the environment.
|
||||
const connectionId = desktopLocalConnectionId(entry.id);
|
||||
// Prefer the desktop's bootstrap label (it identifies the backend and distro,
|
||||
// e.g. "WSL: Ubuntu") over the generic descriptor label, so consumers can show
|
||||
// a meaningful name without recovering it from the bootstrap list later.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { DesktopWslState } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { createDesktopWslStateAtom } from "./desktopWslState";
|
||||
|
||||
const wslState: DesktopWslState = {
|
||||
available: true,
|
||||
distro: null,
|
||||
distros: [
|
||||
{
|
||||
isDefault: true,
|
||||
name: "Ubuntu",
|
||||
version: 2,
|
||||
},
|
||||
],
|
||||
enabled: true,
|
||||
preflightError: null,
|
||||
wslOnly: false,
|
||||
};
|
||||
|
||||
describe("desktopWslState", () => {
|
||||
it("retains the loaded snapshot when the settings screen remounts", async () => {
|
||||
const getWslState = vi.fn(async () => wslState);
|
||||
const atom = createDesktopWslStateAtom(() => ({ getWslState }));
|
||||
const registry = AtomRegistry.make();
|
||||
|
||||
const unmount = registry.mount(atom);
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.value(registry.get(atom))).toEqual(
|
||||
expect.objectContaining({ _tag: "Some", value: wslState }),
|
||||
);
|
||||
});
|
||||
unmount();
|
||||
|
||||
const remount = registry.mount(atom);
|
||||
expect(AsyncResult.value(registry.get(atom))).toEqual(
|
||||
expect.objectContaining({ _tag: "Some", value: wslState }),
|
||||
);
|
||||
expect(getWslState).toHaveBeenCalledTimes(1);
|
||||
|
||||
remount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("retains the desktop bridge failure as the load error cause", async () => {
|
||||
const cause = new Error("wsl unavailable");
|
||||
const atom = createDesktopWslStateAtom(() => ({
|
||||
getWslState: async () => Promise.reject(cause),
|
||||
}));
|
||||
const registry = AtomRegistry.make();
|
||||
registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
|
||||
const result = registry.get(atom);
|
||||
if (!AsyncResult.isFailure(result)) throw new Error("Expected WSL state load to fail.");
|
||||
|
||||
expect(Cause.squash(result.cause)).toEqual(
|
||||
expect.objectContaining({
|
||||
_tag: "DesktopWslStateLoadError",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
registry.dispose();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { DesktopBridge, DesktopWslState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "~/rpc/atomRegistry";
|
||||
|
||||
const DESKTOP_WSL_STATE_STALE_TIME_MS = 30_000;
|
||||
|
||||
type DesktopWslStateBridge = Pick<DesktopBridge, "getWslState">;
|
||||
|
||||
class DesktopWslStateUnavailableError extends Schema.TaggedErrorClass<DesktopWslStateUnavailableError>()(
|
||||
"DesktopWslStateUnavailableError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Desktop WSL state is unavailable.";
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopWslStateLoadError extends Schema.TaggedErrorClass<DesktopWslStateLoadError>()(
|
||||
"DesktopWslStateLoadError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to load WSL state.";
|
||||
}
|
||||
}
|
||||
|
||||
function getDesktopWslStateBridge(): DesktopWslStateBridge | undefined {
|
||||
return typeof window === "undefined" ? undefined : window.desktopBridge;
|
||||
}
|
||||
|
||||
export function createDesktopWslStateAtom(getBridge: () => DesktopWslStateBridge | undefined) {
|
||||
return createDesktopWslStateAtoms(getBridge).stateAtom;
|
||||
}
|
||||
|
||||
function createDesktopWslStateAtoms(getBridge: () => DesktopWslStateBridge | undefined) {
|
||||
const loadDesktopWslState = Effect.fn("loadDesktopWslState")(function* () {
|
||||
const bridge = getBridge();
|
||||
if (!bridge) {
|
||||
return yield* new DesktopWslStateUnavailableError();
|
||||
}
|
||||
return yield* Effect.tryPromise({
|
||||
try: (): Promise<DesktopWslState> => bridge.getWslState(),
|
||||
catch: (cause) => new DesktopWslStateLoadError({ cause }),
|
||||
});
|
||||
});
|
||||
|
||||
const loadAtom = Atom.make(loadDesktopWslState()).pipe(
|
||||
Atom.swr({
|
||||
staleTime: DESKTOP_WSL_STATE_STALE_TIME_MS,
|
||||
revalidateOnMount: true,
|
||||
}),
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("desktop:wsl-state:load"),
|
||||
);
|
||||
|
||||
const snapshotAtom = Atom.make<DesktopWslState | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("desktop:wsl-state:snapshot"),
|
||||
);
|
||||
|
||||
const stateAtom = Atom.make((get) => {
|
||||
const snapshot = get(snapshotAtom);
|
||||
return snapshot ? AsyncResult.success(snapshot) : get(loadAtom);
|
||||
}).pipe(Atom.keepAlive, Atom.withLabel("desktop:wsl-state"));
|
||||
|
||||
return { loadAtom, snapshotAtom, stateAtom };
|
||||
}
|
||||
|
||||
const desktopWslStateAtoms = createDesktopWslStateAtoms(getDesktopWslStateBridge);
|
||||
|
||||
export const desktopWslStateAtom = desktopWslStateAtoms.stateAtom;
|
||||
|
||||
export function refreshDesktopWslState(): void {
|
||||
appAtomRegistry.set(desktopWslStateAtoms.snapshotAtom, null);
|
||||
appAtomRegistry.refresh(desktopWslStateAtoms.loadAtom);
|
||||
}
|
||||
|
||||
export function setDesktopWslStateSnapshot(state: DesktopWslState): void {
|
||||
appAtomRegistry.set(desktopWslStateAtoms.snapshotAtom, state);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { parseWslUncPath } from "./wslPaths";
|
||||
import { parseWslUncPath, resolveWslProjectSelection } from "./wslPaths";
|
||||
|
||||
describe("parseWslUncPath", () => {
|
||||
it("parses wsl.localhost UNC paths into distro and POSIX path", () => {
|
||||
@@ -22,3 +22,39 @@ describe("parseWslUncPath", () => {
|
||||
expect(parseWslUncPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslProjectSelection", () => {
|
||||
it("routes a UNC path to the matching WSL backend", () => {
|
||||
expect(
|
||||
resolveWslProjectSelection("\\\\wsl.localhost\\Ubuntu\\home\\theo\\repo", [
|
||||
{ environmentId: "env-debian", backendId: "wsl:Debian" },
|
||||
{ environmentId: "env-ubuntu", backendId: "wsl:Ubuntu" },
|
||||
]),
|
||||
).toEqual({
|
||||
distro: "Ubuntu",
|
||||
environmentId: "env-ubuntu",
|
||||
linuxPath: "/home/theo/repo",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the only WSL backend for a default-distro instance", () => {
|
||||
expect(
|
||||
resolveWslProjectSelection("\\\\wsl.localhost\\Ubuntu\\home\\theo\\repo", [
|
||||
{ environmentId: "env-wsl", backendId: "wsl:default" },
|
||||
]),
|
||||
).toEqual({
|
||||
distro: "Ubuntu",
|
||||
environmentId: "env-wsl",
|
||||
linuxPath: "/home/theo/repo",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not guess when multiple WSL backends fail to match", () => {
|
||||
expect(
|
||||
resolveWslProjectSelection("\\\\wsl.localhost\\Fedora\\home\\theo\\repo", [
|
||||
{ environmentId: "env-debian", backendId: "wsl:Debian" },
|
||||
{ environmentId: "env-ubuntu", backendId: "wsl:Ubuntu" },
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,15 @@ export interface WslUncPath {
|
||||
readonly linuxPath: string;
|
||||
}
|
||||
|
||||
export interface WslEnvironmentCandidate<TEnvironmentId extends string = string> {
|
||||
readonly environmentId: TEnvironmentId;
|
||||
readonly backendId: string;
|
||||
}
|
||||
|
||||
export interface WslProjectSelection<TEnvironmentId extends string = string> extends WslUncPath {
|
||||
readonly environmentId: TEnvironmentId;
|
||||
}
|
||||
|
||||
const WSL_UNC_PREFIXES = ["\\\\wsl.localhost\\", "\\\\wsl$\\"] as const;
|
||||
const WSL_DISTRO_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
|
||||
|
||||
@@ -16,7 +25,8 @@ export function parseWslUncPath(input: string): WslUncPath | null {
|
||||
}
|
||||
|
||||
const rest = normalized.slice(prefix.length);
|
||||
const [distro, ...segments] = rest.split("\\").filter((segment) => segment.length > 0);
|
||||
const segments = rest.split("\\").filter((segment) => segment.length > 0);
|
||||
const distro = segments.shift();
|
||||
if (!distro || !WSL_DISTRO_NAME_PATTERN.test(distro)) {
|
||||
return null;
|
||||
}
|
||||
@@ -26,3 +36,20 @@ export function parseWslUncPath(input: string): WslUncPath | null {
|
||||
linuxPath: segments.length === 0 ? "/" : `/${segments.join("/")}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveWslProjectSelection<TEnvironmentId extends string>(
|
||||
input: string,
|
||||
candidates: ReadonlyArray<WslEnvironmentCandidate<TEnvironmentId>>,
|
||||
): WslProjectSelection<TEnvironmentId> | null {
|
||||
const parsed = parseWslUncPath(input);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const wslCandidates = candidates.filter((candidate) => candidate.backendId.startsWith("wsl:"));
|
||||
const exact = wslCandidates.find(
|
||||
(candidate) => candidate.backendId.toLowerCase() === `wsl:${parsed.distro}`.toLowerCase(),
|
||||
);
|
||||
const candidate = exact ?? (wslCandidates.length === 1 ? wslCandidates[0] : undefined);
|
||||
return candidate ? { ...parsed, environmentId: candidate.environmentId } : null;
|
||||
}
|
||||
Generated
+270
-260
File diff suppressed because it is too large.
Load diff
@@ -365,6 +365,29 @@ export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedErrorClas
|
||||
}
|
||||
}
|
||||
|
||||
export class WslNodePtyPrebuildMissingError extends Schema.TaggedErrorClass<WslNodePtyPrebuildMissingError>()(
|
||||
"WslNodePtyPrebuildMissingError",
|
||||
{
|
||||
prebuildPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `WSL node-pty prebuild not found at ${this.prebuildPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WslNodePtyManifestReadError extends Schema.TaggedErrorClass<WslNodePtyManifestReadError>()(
|
||||
"WslNodePtyManifestReadError",
|
||||
{
|
||||
manifestPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not read node-pty version from ${this.manifestPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class LinuxIconResizeError extends Schema.TaggedErrorClass<LinuxIconResizeError>()(
|
||||
"LinuxIconResizeError",
|
||||
{
|
||||
@@ -1470,8 +1493,8 @@ const stageWslNodePtyPrebuild = Effect.fn("stageWslNodePtyPrebuild")(function* (
|
||||
.exists(input.prebuildPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!prebuildExists) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `WSL node-pty prebuild not found at ${input.prebuildPath}.`,
|
||||
return yield* new WslNodePtyPrebuildMissingError({
|
||||
prebuildPath: input.prebuildPath,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1480,12 +1503,13 @@ const stageWslNodePtyPrebuild = Effect.fn("stageWslNodePtyPrebuild")(function* (
|
||||
const nodePtyLink = path.join(input.stageAppDir, "node_modules", "node-pty");
|
||||
const nodePtyDir = yield* fs.realPath(nodePtyLink).pipe(Effect.orElseSucceed(() => nodePtyLink));
|
||||
|
||||
const pkgRaw = yield* fs.readFileString(path.join(nodePtyDir, "package.json"));
|
||||
const manifestPath = path.join(nodePtyDir, "package.json");
|
||||
const pkgRaw = yield* fs.readFileString(manifestPath);
|
||||
const manifest = yield* decodeNodePtyManifest(pkgRaw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BuildScriptError({
|
||||
message: `Could not read node-pty version from ${nodePtyDir}.`,
|
||||
new WslNodePtyManifestReadError({
|
||||
manifestPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -1676,7 +1700,11 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
// host's (win32), so promote the Linux x64 fff binaries too; without them
|
||||
// file-finding in WSL fails to load @ff-labs/fff-bin-linux-x64-gnu.
|
||||
...(options.platform === "win"
|
||||
? resolveFffNativeDependencies("linux", "x64", serverPackageJson.dependencies["@ff-labs/fff-node"])
|
||||
? resolveFffNativeDependencies(
|
||||
"linux",
|
||||
"x64",
|
||||
serverPackageJson.dependencies["@ff-labs/fff-node"],
|
||||
)
|
||||
: {}),
|
||||
};
|
||||
const stagePnpmConfig = createStagePnpmConfig(workspacePatchedDependencies, stageDependencies);
|
||||
|
||||
Reference in new issue
Block a user