Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Choose the default terminal shell](./docs/user/terminal-shell.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
Expand Down
54 changes: 54 additions & 0 deletions apps/desktop/resources/installer.nsh
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
!include "getProcessInfo.nsh"

Var pid

!macro setInstallerPhaseText TEXT
!ifndef BUILD_UNINSTALLER
${IfNot} ${Silent}
FindWindow $0 "#32770" "" $hwndparent
FindWindow $0 "#32770" "" $hwndparent $0
GetDlgItem $0 $0 1000
SendMessage $0 ${WM_SETTEXT} 0 "STR:${TEXT}"
${EndIf}
!endif
!macroend

# electron-builder calls this immediately before checking for and removing the
# installed version. Keep its standard app-running check, then make the long
# silent-uninstaller phase explicit in the one-click installer banner.
!macro customCheckAppRunning
!insertmacro IS_POWERSHELL_AVAILABLE
!insertmacro _CHECK_APP_RUNNING
!insertmacro setInstallerPhaseText "Removing the previous version..."
!macroend

# electron-builder delegates these hooks the old uninstaller result handling.
# Preserve its standard failure behavior before advancing the phase text.
!macro handleOldUninstallerResult NEXT_TEXT
IfErrors 0 +3
DetailPrint `Uninstall was not successful. Not able to launch uninstaller!`
Return

${If} $R0 != 0
MessageBox MB_OK|MB_ICONEXCLAMATION "$(uninstallFailed): $R0"
DetailPrint `Uninstall was not successful. Uninstaller error code: $R0.`
SetErrorLevel 2
Quit
${EndIf}

!insertmacro setInstallerPhaseText "${NEXT_TEXT}"
!macroend

!macro customUnInstallCheck
# An all-users installation can also remove a per-user installation next.
# Keep showing the removal phase until both checks have completed.
${If} $installMode == "all"
!insertmacro handleOldUninstallerResult "Removing the previous version..."
${Else}
!insertmacro handleOldUninstallerResult "Installing the new version..."
${EndIf}
!macroend

!macro customUnInstallCheckCurrentUser
!insertmacro handleOldUninstallerResult "Installing the new version..."
!macroend
24 changes: 6 additions & 18 deletions apps/desktop/src/shell/DesktopShellEnvironment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ describe("DesktopShellEnvironment", () => {
}),
);

it.effect("loads PowerShell profile environment on Windows", () =>
it.effect("hydrates the Windows PATH without starting a shell", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
Expand All @@ -206,41 +206,29 @@ describe("DesktopShellEnvironment", () => {
USERPROFILE: "C:\\Users\\testuser",
};

const commands: ChildProcess.Command[] = [];
yield* runShellEnvironment({
env,
platform: "win32",
handler: (command) => {
if (command._tag !== "StandardCommand") return "";
const loadProfile = !command.args.includes("-NoProfile");
return loadProfile
? envOutput({
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
})
: envOutput({ PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" });
commands.push(command);
return "";
},
});

assert.equal(
env.PATH,
[
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
assert.equal(
env.FNM_MULTISHELL_PATH,
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
);
assert.lengthOf(commands, 0);
}),
);

Expand Down
79 changes: 4 additions & 75 deletions apps/desktop/src/shell/DesktopShellEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,7 @@ interface ShellEnvironmentConfig {
readonly userShell: Option.Option<string>;
}

interface WindowsProbeOptions {
readonly loadProfile: boolean;
}

const DesktopShellEnvironmentProbe = Schema.Literals([
"login-shell",
"launchctl-path",
"powershell-profile",
"powershell-no-profile",
]);
const DesktopShellEnvironmentProbe = Schema.Literals(["login-shell", "launchctl-path"]);
type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;

const desktopShellEnvironmentCommandFields = {
Expand Down Expand Up @@ -83,8 +74,6 @@ const LOGIN_SHELL_ENV_NAMES = [
"XDG_SESSION_TYPE",
"WAYLAND_DISPLAY",
] as const;
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
Expand Down Expand Up @@ -238,19 +227,6 @@ const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
})
.join("; ");

const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
[
"$ErrorActionPreference = 'Stop'",
...names.flatMap((name) => {
return [
`Write-Output '${startMarker(name)}'`,
`$value = [Environment]::GetEnvironmentVariable('${name}')`,
"if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
`Write-Output '${endMarker(name)}'`,
];
}),
].join("; ");

const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
const environment: EnvironmentPatch = {};

Expand Down Expand Up @@ -343,64 +319,17 @@ const readLaunchctlPath = runCommandOutput({
timeout: LAUNCHCTL_TIMEOUT,
}).pipe(Effect.map(trimNonEmpty));

const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
function* (
names: ReadonlyArray<string>,
options: WindowsProbeOptions,
): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
if (names.length === 0) return {};

const args = [
"-NoLogo",
...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
"-NonInteractive",
"-Command",
captureWindowsEnvironmentCommand(names),
];

for (const command of WINDOWS_SHELL_CANDIDATES) {
const output = yield* runCommandOutput({
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
command,
args,
timeout: LOGIN_SHELL_TIMEOUT,
});
const environment = extractEnvironment(output, names);
if (Object.keys(environment).length > 0) {
return environment;
}
}

return {};
},
);

const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
loadProfile: true,
});
const installWindowsEnvironment = (config: ShellEnvironmentConfig): Effect.Effect<void> =>
Effect.sync(() => {
const mergedPath = mergePaths("win32", [
trimNonEmpty(profile.PATH),
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
trimNonEmpty(noProfile.PATH),
readEnvPath(config.env),
]);

if (Option.isSome(mergedPath)) {
config.env.PATH = mergedPath.value;
}
if (!config.env.FNM_DIR && profile.FNM_DIR) {
config.env.FNM_DIR = profile.FNM_DIR;
}
if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
}
},
);
});

const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
Expand Down
55 changes: 53 additions & 2 deletions apps/server/src/os-jank.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import * as NodeOS from "node:os";
import { assert, it } from "vite-plus/test";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { AsyncWindowsShellEnvironment } from "@t3tools/shared/shell";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";

import { hydratePosixHome } from "./os-jank.ts";
import {
HostEnvironmentHydration,
hostEnvironmentHydrationLayer,
hydratePosixHome,
} from "./os-jank.ts";

it("hydrates HOME for minimal service environments from the user account", () => {
const env: NodeJS.ProcessEnv = {};
Expand Down Expand Up @@ -38,3 +48,44 @@ it("preserves an explicitly configured HOME", () => {

assert.equal(env.HOME, "/custom/home");
});

it.effect("does not block startup on a PowerShell profile and eventually hydrates tools", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\test\\AppData\\Roaming",
};
const started = Deferred.makeUnsafe<void>();
const release = Deferred.makeUnsafe<void>();
const reader = () =>
Deferred.succeed(started, undefined).pipe(
Effect.andThen(Deferred.await(release)),
Effect.as({
PATH: "C:\\Profile\\mise\\shims;C:\\Tools\\custom",
FNM_DIR: "C:\\Users\\test\\AppData\\Roaming\\fnm",
}),
);
const layer = hostEnvironmentHydrationLayer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, "win32"),
Layer.succeed(HostProcessEnvironment, env),
Layer.succeed(AsyncWindowsShellEnvironment, reader),
NodeServices.layer,
),
),
);

return Effect.gen(function* () {
const hydration = yield* HostEnvironmentHydration;
yield* Deferred.await(started);
assert.notInclude(env.PATH, "C:\\Profile\\mise\\shims");
yield* Deferred.succeed(release, undefined);
assert.equal(hydration.windowsProfile._tag, "Some");
if (hydration.windowsProfile._tag === "Some") {
yield* hydration.windowsProfile.value;
}
assert.include(env.PATH, "C:\\Profile\\mise\\shims");
assert.include(env.PATH, "C:\\Tools\\custom");
assert.equal(env.FNM_DIR, "C:\\Users\\test\\AppData\\Roaming\\fnm");
}).pipe(Effect.provide(layer));
});
47 changes: 47 additions & 0 deletions apps/server/src/os-jank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ import {
mergePathEntries,
readPathFromLoginShell,
readPathFromLaunchctl,
resolveWindowsBaselineEnvironment,
resolveWindowsEnvironment,
resolveWindowsProfileEnvironment,
} from "@t3tools/shared/shell";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as NodeOS from "node:os";

Expand Down Expand Up @@ -91,6 +97,47 @@ export const fixPath = Effect.fn("fixPath")(function* (): Effect.fn.Return<
);
});

export const HostEnvironmentHydration = Context.Reference<{
readonly windowsProfile: Option.Option<Effect.Effect<void>>;
}>("t3/os-jank/HostEnvironmentHydration", {
defaultValue: () => ({ windowsProfile: Option.none() }),
});

function applyEnvironmentPatch(env: NodeJS.ProcessEnv, patch: Partial<NodeJS.ProcessEnv>): void {
for (const [key, value] of Object.entries(patch)) {
if (value !== undefined) env[key] = value;
}
}

export const hostEnvironmentHydrationLayer = Layer.effect(
HostEnvironmentHydration,
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const env = yield* HostProcessEnvironment;
if (platform !== "win32") {
yield* fixPath();
return { windowsProfile: Option.none() };
}

yield* Effect.sync(() => applyEnvironmentPatch(env, resolveWindowsBaselineEnvironment(env)));
const completed = yield* Deferred.make<void>();
yield* resolveWindowsProfileEnvironment(env).pipe(
Effect.tap((patch) => Effect.sync(() => applyEnvironmentPatch(env, patch))),
Effect.catchCause((cause) =>
Effect.sync(() =>
logPathHydrationWarning("Failed to hydrate PATH from the PowerShell profile.", cause),
),
),
Effect.ensuring(Deferred.succeed(completed, undefined)),
Effect.forkScoped,
);

return {
windowsProfile: Option.some(Deferred.await(completed)),
};
}),
);

export const expandHomePath = Effect.fn(function* (input: string) {
const { join } = yield* Path.Path;
if (input === "~") {
Expand Down
Loading
Loading