sailfork / t3code-github / apps/ server/ src/ process/ externalLauncher.test.ts

// @effect-diagnostics nodeBuiltinImport:off - the Windows launch smoke tests use filesystem notifications to observe real PowerShell launches.
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Deferred from "effect/Deferred";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as TestClock from "effect/testing/TestClock";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";

import { EDITORS } from "@t3tools/contracts";
import { resolveEditorCommand } from "@t3tools/shared/editor";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import * as ExternalLauncher from "./externalLauncher.ts";

// Windows drive letters break mocked POSIX PATH splitting; these tests also require /bin/sh stubs.
const windowsHost = HostProcess.Platform.defaultValue() === "win32";

interface MockSpawnResult {
  readonly spawnError?: PlatformError.PlatformError;
  readonly exitCode?: number;
  readonly stdout?: string;
  readonly stall?: boolean;
}

function makeMockDetachedHandle(input: MockSpawnResult & { readonly onUnref?: () => void } = {}) {
  return ChildProcessSpawner.makeHandle({
    pid: ChildProcessSpawner.ProcessId(1),
    exitCode: input.stall
      ? Effect.never
      : Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
    isRunning: Effect.succeed(true),
    kill: () => Effect.void,
    unref: Effect.sync(() => {
      input.onUnref?.();
      return Effect.void;
    }),
    stdin: Sink.drain,
    stdout:
      input.stdout === undefined
        ? Stream.empty
        : Stream.make(new TextEncoder().encode(input.stdout)),
    stderr: Stream.empty,
    all: Stream.empty,
    getInputFd: () => Sink.drain,
    getOutputFd: () => Stream.empty,
  });
}

const layerTest = (input: {
  readonly platform: NodeJS.Platform;
  readonly env?: Record<string, string>;
  readonly resolveExecutable?: (command: string) => string | undefined;
  readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
  readonly onUnref?: () => void;
  readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined;
}) => {
  const layerSpawner = Layer.succeed(
    ChildProcessSpawner.ChildProcessSpawner,
    ChildProcessSpawner.make((command) =>
      Effect.gen(function* () {
        assert.equal(ChildProcess.isStandardCommand(command), true);
        if (!ChildProcess.isStandardCommand(command)) {
          throw new Error("Expected a standard command");
        }
        input.onSpawn?.(command);
        const result = input.spawnResult?.(command);
        if (result?.spawnError) return yield* result.spawnError;
        return makeMockDetachedHandle({
          ...(input.onUnref === undefined ? {} : { onUnref: input.onUnref }),
          ...result,
        });
      }),
    ),
  );

  return Layer.mergeAll(
    ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, layerSpawner))),
    Layer.succeed(HostProcess.Platform, input.platform),
    Layer.succeed(
      SpawnExecutableResolution,
      (command) => input.resolveExecutable?.(command) ?? command,
    ),
    ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
  );
};

it.effect.skipIf(windowsHost)(
  "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE",
  () =>
    Effect.gen(function* () {
      const fileSystem = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
      const codePath = path.join(binDir, "code");
      yield* fileSystem.writeFileString(codePath, "#!/bin/sh\n");
      yield* fileSystem.chmod(codePath, 0o755);

      const spawned: ChildProcess.StandardCommand[] = [];
      yield* Effect.gen(function* () {
        const launcher = yield* ExternalLauncher.ExternalLauncher;
        yield* launcher.launchBrowser("https://example.com");
        yield* launcher.launchEditor({ editor: "vscode", cwd: "/workspace" });
      }).pipe(
        Effect.provide(
          layerTest({
            platform: "linux",
            env: { PATH: binDir, DISPLAY: ":0" },
            onSpawn: (command) => spawned.push(command),
          }),
        ),
        Effect.provideService(HostProcess.Environment, {
          PATH: binDir,
          DISPLAY: ":0",
          ELECTRON_RUN_AS_NODE: "1",
        }),
      );

      assert.deepEqual(
        spawned.map((command) => ({
          command: command.command,
          env: command.options.env,
          extendEnv: command.options.extendEnv,
        })),
        ["xdg-open", "code"].map((command) => ({
          command,
          env: { PATH: binDir, DISPLAY: ":0" },
          extendEnv: false,
        })),
      );
    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

// Windows drive letters cannot resolve the POSIX editor stub.
it.effect.skipIf(windowsHost)(
  "a Linux editor launch without a display takes the desktop session's display from the systemd user manager",
  () =>
    Effect.gen(function* () {
      const fileSystem = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
      const codiumPath = path.join(binDir, "codium");
      yield* fileSystem.writeFileString(codiumPath, "#!/bin/sh\n");
      yield* fileSystem.chmod(codiumPath, 0o755);

      const launchEnv = (sessionManager: MockSpawnResult) =>
        Effect.gen(function* () {
          const spawned: ChildProcess.StandardCommand[] = [];
          yield* Effect.gen(function* () {
            const launcher = yield* ExternalLauncher.ExternalLauncher;
            yield* launcher.launchEditor({ editor: "vscodium", cwd: "/workspace" });
            yield* launcher.launchBrowser("https://example.com");
          }).pipe(
            Effect.provide(
              layerTest({
                platform: "linux",
                env: { PATH: binDir },
                onSpawn: (command) => spawned.push(command),
                spawnResult: (command) =>
                  command.command === "busctl" ? sessionManager : undefined,
              }),
            ),
            Effect.provideService(HostProcess.Environment, { PATH: binDir }),
          );
          // Only editors borrow the session display; a browser must not open on that screen.
          assert.deepEqual(spawned.find((command) => command.command === "xdg-open")?.options.env, {
            PATH: binDir,
          });
          return spawned.find((command) => command.command === "codium")?.options.env;
        });

      assert.deepEqual(
        yield* launchEnv({
          stdout: JSON.stringify({
            type: "as",
            data: [
              "DISPLAY=:0",
              "HOME=/home/user",
              "WAYLAND_DISPLAY=wayland-1",
              "XAUTHORITY=/home/user/auth files/cookie",
            ],
          }),
        }),
        {
          PATH: binDir,
          DISPLAY: ":0",
          WAYLAND_DISPLAY: "wayland-1",
          // Raw, not the 
		
		
		
		
	

...' quoting `systemctl show-environment` would print.
          XAUTHORITY: "/home/user/auth files/cookie",
        },
      );
      assert.deepEqual(yield* launchEnv({ stdout: "invalid JSON" }), { PATH: binDir });
      assert.deepEqual(yield* launchEnv({ stdout: '{"data":[42]}' }), { PATH: binDir });
      assert.deepEqual(
        yield* launchEnv({
          spawnError: PlatformError.systemError({
            _tag: "NotFound",
            module: "ChildProcess",
            method: "spawn",
          }),
        }),
        { PATH: binDir },
      );
    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect("launches an installed editor with platform-safe arguments", () =>
  Effect.gen(function* () {
    const fileSystem = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
    yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");

    let spawned: ChildProcess.StandardCommand | undefined;
    yield* Effect.gen(function* () {
      const launcher = yield* ExternalLauncher.ExternalLauncher;
      yield* launcher.launchEditor({
        editor: "vscode",
        cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
      });
    }).pipe(
      Effect.provide(
        layerTest({
          platform: "win32",
          env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
          resolveExecutable: (command) =>
            command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
          onSpawn: (command) => {
            spawned = command;
          },
        }),
      ),
    );

    assert.ok(spawned);
    assert.equal(
      spawned.command,
      [
        '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"',
        '^"--goto^"',
        '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
      ].join(" "),
    );
    assert.deepEqual(spawned.args, []);
    assert.equal(spawned.options.shell, true);
    assert.equal(spawned.options.detached, true);
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect.skipIf(windowsHost)(
  "reveals a WSL file in Windows File Explorer through its UNC path",
  () =>
    Effect.gen(function* () {
      const fileSystem = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
      for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) {
        const filePath = path.join(binDir, name);
        yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
        yield* fileSystem.chmod(filePath, 0o755);
      }

      let spawned: ChildProcess.StandardCommand | undefined;
      const result = yield* Effect.gen(function* () {
        const launcher = yield* ExternalLauncher.ExternalLauncher;
        const kind = yield* launcher.resolveFileManagerRevealKind();
        const editors = yield* launcher.resolveAvailableEditors();
        yield* launcher.launchEditor({
          editor: "file-manager",
          cwd: "/home/t3/workspace [draft]/author's $media/clip|draft.mp4",
          reveal: true,
        });
        return { kind, editors };
      }).pipe(
        Effect.provide(
          layerTest({
            platform: "linux",
            env: {
              PATH: binDir,
              WSL_DISTRO_NAME: "Ubuntu-24.04",
              WSL_INTEROP: "/run/WSL/1_interop",
            },
            onSpawn: (command) => {
              spawned = command;
            },
          }),
        ),
      );

      assert.equal(result.kind, "file-explorer");
      assert.equal(result.editors.includes("file-manager"), true);
      assert.ok(spawned);
      assert.equal(spawned.command, "powershell.exe");
      assert.equal(spawned.options.detached, true);
      const encodedCommand = String(spawned.args[spawned.args.length - 1] ?? "");
      const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
      assert.equal(
        decodedCommand,
        "$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media' } else { Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media\\clip|draft.mp4' + '\"') }",
      );
    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

for (const wsl of [false, true]) {
  it.effect.skipIf(windowsHost)(
    "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"),
    () =>
      Effect.gen(function* () {
        const fileSystem = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
        for (const name of ["xdg-open", "xdg-mime", "gdbus", ...(wsl ? ["explorer.exe"] : [])]) {
          const filePath = path.join(binDir, name);
          yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
          yield* fileSystem.chmod(filePath, 0o755);
        }
        const target = "/workspace/media/a 'quoted' \"clip\" #100% ? é\\name.mp4";
        const spawnedCommands: ChildProcess.StandardCommand[] = [];
        yield* Effect.gen(function* () {
          const launcher = yield* ExternalLauncher.ExternalLauncher;
          yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true });
        }).pipe(
          Effect.provide(
            layerTest({
              platform: "linux",
              env: {
                PATH: binDir,
                WAYLAND_DISPLAY: "wayland-1",
                ...(wsl
                  ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" }
                  : {}),
              },
              onSpawn: (command) => spawnedCommands.push(command),
              spawnResult: (command) =>
                command.command === "xdg-mime"
                  ? { stdout: "com.thisisgm.flea.desktop\n" }
                  : undefined,
            }),
          ),
        );

        const reveal = spawnedCommands.find((command) => command.command === "gdbus");
        assert.ok(reveal);
        assert.deepEqual(reveal.args, [
          "call",
          "--session",
          "--dest",
          "org.freedesktop.FileManager1",
          "--object-path",
          "/org/freedesktop/FileManager1",
          "--method",
          "org.freedesktop.FileManager1.ShowItems",
          "[\"file:///workspace/media/a%20'quoted'%20%22clip%22%20%23100%25%20%3F%20%C3%A9%5Cname.mp4\"]",
          "",
        ]);
        assert.deepEqual(
          spawnedCommands.filter((command) => command.command !== "xdg-mime"),
          [reveal],
        );
      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
  );
}

for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12:4"]) {
  it.effect.skipIf(windowsHost)(
    `opens ${cwd} with the macOS Zed bundle when another zed is on PATH`,
    () =>
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-collision-" });
        const executable = path.join(home, "Applications/Zed.app/Contents/MacOS/cli");
        const binDir = path.join(home, "zfs/bin");
        yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
        yield* fs.makeDirectory(binDir, { recursive: true });
        for (const command of [executable, path.join(binDir, "zed")]) {
          yield* fs.writeFileString(command, "#!/bin/sh\n");
          yield* fs.chmod(command, 0o755);
        }

        let spawned: ChildProcess.StandardCommand | undefined;
        yield* Effect.gen(function* () {
          const launcher = yield* ExternalLauncher.ExternalLauncher;
          assert.include(yield* launcher.resolveAvailableEditors(), "zed");
          yield* launcher.launchEditor({ editor: "zed", cwd });
        }).pipe(
          Effect.provide(
            layerTest({
              platform: "darwin",
              env: { HOME: home, PATH: binDir },
              onSpawn: (command) => {
                spawned = command;
              },
            }),
          ),
        );
        assert.ok(spawned);
        assert.equal(spawned.command, executable);
        assert.deepEqual(spawned.args, [cwd]);
        assert.equal(spawned.options.shell, false);
      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
  );
}

for (const { layout, pathNames, fallbackNames, expected } of [
  { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" },
  {
    layout: "mixed locations",
    pathNames: ["zed"],
    fallbackNames: ["zeditor"],
    expected: "fallback",
  },
  {
    layout: "fallback directory",
    pathNames: [],
    fallbackNames: ["zed", "zeditor"],
    expected: "fallback",
  },
]) {
  it.effect.skipIf(windowsHost)(`prefers the Zed editor on Linux with ${layout}`, () =>
    Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-linux-" });
      const binDir = path.join(home, "bin");
      const fallbackDir = path.join(home, ".local/bin");
      for (const [dir, names] of [
        [binDir, pathNames],
        [fallbackDir, fallbackNames],
      ] as const) {
        yield* fs.makeDirectory(dir, { recursive: true });
        for (const name of names) {
          yield* fs.writeFileString(path.join(dir, name), "#!/bin/sh\n");
          yield* fs.chmod(path.join(dir, name), 0o755);
        }
      }

      let spawned: ChildProcess.StandardCommand | undefined;
      yield* Effect.gen(function* () {
        const launcher = yield* ExternalLauncher.ExternalLauncher;
        assert.include(yield* launcher.resolveAvailableEditors(), "zed");
        yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" });
      }).pipe(
        Effect.provide(
          layerTest({
            platform: "linux",
            env: { HOME: home, PATH: binDir },
            onSpawn: (command) => {
              spawned = command;
            },
          }),
        ),
      );
      assert.ok(spawned);
      assert.equal(
        spawned.command,
        expected === "fallback" ? path.join(fallbackDir, "zeditor") : expected,
      );
      assert.deepEqual(spawned.args, ["/workspace"]);
    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
  );
}

it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directory", () =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-fallback-" });
    const localBin = path.join(home, ".local/bin");
    const systemBin = path.join(home, "system-bin");
    for (const [dir, name] of [
      [localBin, "zed"],
      [systemBin, "zeditor"],
    ] as const) {
      yield* fs.makeDirectory(dir, { recursive: true });
      const executable = path.join(dir, name);
      yield* fs.writeFileString(executable, "#!/bin/sh\n");
      yield* fs.chmod(executable, 0o755);
    }
    const editor = EDITORS.find((editor) => editor.id === "zed")!;
    const resolve = resolveEditorCommand(editor, { HOME: home, PATH: "" }).pipe(
      Effect.provideService(HostProcess.Platform, "linux"),
      Effect.provideService(Path.Path, {
        ...path,
        join: (...parts) =>
          path.join(
            ...parts.map((part) =>
              ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part,
            ),
          ),
      }),
    );
    assert.deepEqual(
      yield* resolve,
      Option.some({ command: path.join(systemBin, "zeditor"), baseArgs: [] }),
    );
    yield* fs.remove(path.join(systemBin, "zeditor"));
    assert.deepEqual(
      yield* resolve,
      Option.some({ command: path.join(localBin, "zed"), baseArgs: [] }),
    );
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect.each([
  { editor: "webstorm", installPath: "Applications/WebStorm 2026.2.app/Contents/MacOS/webstorm" },
  { editor: "idea", installPath: "Applications/IntelliJ IDEA 2026.1.4.app/Contents/MacOS/idea" },
] as const)(
  "discovers and launches $editor from a versioned macOS bundle",
  ({ editor, installPath }) =>
    Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-versioned-" });
      const executable = path.join(home, installPath);
      yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
      yield* fs.writeFileString(executable, "#!/bin/sh\n");
      yield* fs.chmod(executable, 0o755);

      let spawned: ChildProcess.StandardCommand | undefined;
      yield* Effect.gen(function* () {
        const launcher = yield* ExternalLauncher.ExternalLauncher;
        assert.include(yield* launcher.resolveAvailableEditors(), editor);
        yield* launcher.launchEditor({ editor, cwd: "/workspace with spaces/file.ts:12:4" });
      }).pipe(
        Effect.provide(
          layerTest({
            platform: "darwin",
            env: { HOME: home, PATH: path.join(home, "empty") },
            onSpawn: (command) => {
              spawned = command;
            },
          }),
        ),
      );

      assert.ok(spawned);
      assert.equal(spawned.command, executable);
      assert.deepEqual(spawned.args, [
        "--line",
        "12",
        "--column",
        "3",
        "/workspace with spaces/file.ts",
      ]);
    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect("matches macOS bundles on the name boundary only", () =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const unrelatedHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-unrelated-" });
    const unrelated = path.join(
      unrelatedHome,
      "Applications/WebStormHelper.app/Contents/MacOS/webstorm",
    );
    yield* fs.makeDirectory(path.dirname(unrelated), { recursive: true });
    yield* fs.writeFileString(unrelated, "#!/bin/sh\n");
    yield* fs.chmod(unrelated, 0o755);

    const editorsFor = (home: string) =>
      Effect.gen(function* () {
        const launcher = yield* ExternalLauncher.ExternalLauncher;
        return yield* launcher.resolveAvailableEditors();
      }).pipe(
        Effect.provide(
          layerTest({ platform: "darwin", env: { HOME: home, PATH: path.join(home, "bin") } }),
        ),
      );

    assert.notInclude(yield* editorsFor(unrelatedHome), "webstorm");

    const exactHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-exact-" });
    const exact = path.join(exactHome, "Applications/WebStorm.app/Contents/MacOS/webstorm");
    yield* fs.makeDirectory(path.dirname(exact), { recursive: true });
    yield* fs.writeFileString(exact, "#!/bin/sh\n");
    yield* fs.chmod(exact, 0o755);

    assert.include(yield* editorsFor(exactHome), "webstorm");
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect("keeps the macOS VS Code Insiders bundle out of stable VS Code", () =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-insiders-" });
    // The real Insiders bundle ships both `code-insiders` and `code`.
    const bin = path.join(
      home,
      "Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin",
    );
    yield* fs.makeDirectory(bin, { recursive: true });
    for (const name of ["code", "code-insiders"]) {
      yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n");
      yield* fs.chmod(path.join(bin, name), 0o755);
    }

    let spawned: ChildProcess.StandardCommand | undefined;
    const editors = yield* Effect.gen(function* () {
      const launcher = yield* ExternalLauncher.ExternalLauncher;
      const available = yield* launcher.resolveAvailableEditors();
      yield* launcher.launchEditor({ editor: "vscode-insiders", cwd: "/workspace/file.ts" });
      return available;
    }).pipe(
      Effect.provide(
        layerTest({
          platform: "darwin",
          env: { HOME: home, PATH: path.join(home, "empty") },
          onSpawn: (command) => {
            spawned = command;
          },
        }),
      ),
    );

    assert.notInclude(editors, "vscode");
    assert.include(editors, "vscode-insiders");
    assert.equal(spawned?.command, path.join(bin, "code-insiders"));
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

for (const { platform, installPath, onPath } of [
  { platform: "darwin", installPath: ".local/bin/agy", onPath: true },
  { platform: "linux", installPath: ".local/bin/agy", onPath: false },
  { platform: "win32", installPath: "agy/bin/agy.cmd", onPath: true },
] as const) {
  it.effect.skipIf(windowsHost && platform !== "win32")(
    `does not report the agy CLI as the Antigravity IDE on ${platform}`,
    () =>
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-cli-" });
        const executable = path.join(home, installPath);
        yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
        yield* fs.writeFileString(executable, "#!/bin/sh\n");
        yield* fs.chmod(executable, 0o755);
        const editors = yield* Effect.gen(function* () {
          const launcher = yield* ExternalLauncher.ExternalLauncher;
          return yield* launcher.resolveAvailableEditors();
        }).pipe(
          Effect.provide(
            layerTest({
              platform,
              env: {
                HOME: home,
                LOCALAPPDATA: home,
                PATH: onPath ? path.dirname(executable) : path.join(home, "empty"),
                PATHEXT: ".COM;.EXE;.BAT;.CMD",
              },
            }),
          ),
        );
        assert.notInclude(editors, "antigravity");
      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
  );
}

it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launchers first", () =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-priority-" });
    const executable = path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/code");
    const env = { HOME: home, PATH: path.join(home, "bin") };
    const discover = Effect.gen(function* () {
      const launcher = yield* ExternalLauncher.ExternalLauncher;
      return yield* launcher.resolveAvailableEditors();
    });
    const before = yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env })));
    yield* fs.makeDirectory(executable, { recursive: true });
    assert.deepEqual(
      yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
      before,
    );
    yield* fs.remove(executable, { recursive: true });
    yield* fs.writeFileString(executable, "#!/bin/sh\n");
    yield* fs.chmod(executable, 0o644);
    assert.deepEqual(
      yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
      before,
    );
    yield* fs.chmod(executable, 0o755);
    yield* fs.makeDirectory(env.PATH);
    yield* fs.writeFileString(path.join(env.PATH, "cursor"), "#!/bin/sh\n");
    yield* fs.chmod(path.join(env.PATH, "cursor"), 0o755);
    let spawned: ChildProcess.StandardCommand | undefined;
    yield* Effect.gen(function* () {
      const launcher = yield* ExternalLauncher.ExternalLauncher;
      yield* launcher.launchEditor({ editor: "cursor", cwd: "/workspace" });
    }).pipe(
      Effect.provide(
        layerTest({
          platform: "darwin",
          env: { ...env, PATH: `${env.PATH}:/usr/bin` },
          onSpawn: (command) => {
            spawned = command;
          },
        }),
      ),
    );
    assert.equal(spawned?.command, "cursor");
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect(
  "memoizes editor discovery and refreshes in the background after the cache window",
  () => {
    let statCalls = 0;
    const rescanned = Deferred.makeUnsafe<void>();
    let initialScanDone = false;
    const fileInfo = { type: "File" } as FileSystem.File.Info;
    const layerLauncher = ExternalLauncher.layer.pipe(
      Layer.provide(
        Layer.mergeAll(
          FileSystem.layerNoop({
            stat: () =>
              Effect.sync(() => {
                statCalls += 1;
                return fileInfo;
              }).pipe(
                Effect.tap(() =>
                  initialScanDone ? Deferred.succeed(rescanned, undefined) : Effect.void,
                ),
              ),
          }),
          Path.layer,
          Layer.succeed(
            ChildProcessSpawner.ChildProcessSpawner,
            ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
          ),
        ),
      ),
    );

    return Effect.gen(function* () {
      const launcher = yield* ExternalLauncher.ExternalLauncher;

      const first = yield* launcher.resolveAvailableEditors();
      assert.equal(first.includes("vscode"), true);
      const statCallsAfterFirstScan = statCalls;
      initialScanDone = true;
      assert.isAbove(statCallsAfterFirstScan, 0);

      // Past the shared command-resolution cache TTL (30s) but within the
      // discovery cache window: the memoized set is reused without any scan.
      yield* TestClock.adjust("31 seconds");
      const second = yield* launcher.resolveAvailableEditors();
      assert.deepEqual([...second], [...first]);
      assert.equal(statCalls, statCallsAfterFirstScan);

      // Past the discovery cache window the next call still answers from the
      // memoized set and rescans in the background.
      yield* TestClock.adjust("30 seconds");
      const third = yield* launcher.resolveAvailableEditors();
      assert.deepEqual([...third], [...first]);
      yield* Deferred.await(rescanned);
      assert.isAbove(statCalls, statCallsAfterFirstScan);
    }).pipe(
      Effect.provide(
        Layer.mergeAll(
          layerLauncher,
          Layer.succeed(HostProcess.Platform, "win32"),
          ConfigProvider.layer(
            ConfigProvider.fromEnv({
              env: {
                PATH: "C:\\t3-editor-discovery-cache-test",
                PATHEXT: ".COM;.EXE;.BAT;.CMD",
              },
            }),
          ),
          TestClock.layer(),
        ),
      ),
    );
  },
);

it.effect("keeps scanning after the caller is interrupted and shares that scan", () => {
  const fileInfo = { type: "File" } as FileSystem.File.Info;
  const release = Deferred.makeUnsafe<void>();
  let parkedStats = 0;
  const layerLauncher = ExternalLauncher.layer.pipe(
    Layer.provide(
      Layer.mergeAll(
        FileSystem.layerNoop({
          stat: () =>
            Effect.gen(function* () {
              if (!Deferred.isDoneUnsafe(release)) {
                parkedStats += 1;
                yield* Deferred.await(release);
              }
              return fileInfo;
            }),
        }),
        Path.layer,
        Layer.succeed(
          ChildProcessSpawner.ChildProcessSpawner,
          ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
        ),
      ),
    ),
  );

  return Effect.gen(function* () {
    const launcher = yield* ExternalLauncher.ExternalLauncher;

    const interrupted = yield* Effect.forkChild(launcher.resolveAvailableEditors());
    yield* Effect.yieldNow;
    yield* Fiber.interrupt(interrupted);

    const next = yield* Effect.forkChild(launcher.resolveAvailableEditors());
    yield* Effect.yieldNow;
    assert.equal(parkedStats, 1);

    yield* Deferred.succeed(release, undefined);
    const editors = yield* Fiber.join(next);
    assert.equal(editors.includes("vscode"), true);
  }).pipe(
    Effect.provide(
      Layer.mergeAll(
        layerLauncher,
        Layer.succeed(HostProcess.Platform, "win32"),
        ConfigProvider.layer(
          ConfigProvider.fromEnv({
            env: {
              PATH: "C:\\t3-editor-discovery-interrupt-test",
              PATHEXT: ".COM;.EXE;.BAT;.CMD",
            },
          }),
        ),
      ),
    ),
  );
});

const launchWindowsShimEditor = (cwd: string) =>
  Effect.gen(function* () {
    const fileSystem = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
    yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
    let spawned: ChildProcess.StandardCommand | undefined;
    const exit = yield* Effect.gen(function* () {
      const launcher = yield* ExternalLauncher.ExternalLauncher;
      return yield* launcher.launchEditor({ editor: "vscode", cwd }).pipe(Effect.exit);
    }).pipe(
      Effect.provide(
        layerTest({
          platform: "win32",
          env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
          resolveExecutable: (command) =>
            command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
          onSpawn: (command) => {
            spawned = command;
          },
        }),
      ),
    );
    return { exit, spawned };
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));

it.effect.each([
  ["CRLF", "C:\\workspace\\file.ts\r\ncalc.exe"],
  ["LF", "C:\\workspace\\file.ts\ncalc.exe"],
  ["double quote", 'C:\\workspace\\file.ts" & calc.exe & "'],
] as const)("does not start a Windows command shim for a path with a $0", ([, cwd]) =>
  Effect.gen(function* () {
    const { exit, spawned } = yield* launchWindowsShimEditor(cwd);
    assert.equal(spawned, undefined);
    assert.isTrue(Exit.isFailure(exit));
    if (Exit.isFailure(exit)) {
      assert.instanceOf(
        Cause.squash(exit.cause),
        ExternalLauncher.ExternalLauncherUnsupportedTargetError,
      );
    }
  }),
);

it.effect("starts a Windows command shim for unicode paths with cmd metacharacters", () =>
  Effect.gen(function* () {
    const { exit, spawned } = yield* launchWindowsShimEditor(
      "C:\\Users\\jö\\R&D (100%)\\naïve ^file!.ts:3:7",
    );
    assert.isTrue(Exit.isSuccess(exit));
    assert.ok(spawned);
    assert.equal(spawned.options.shell, true);
    assert.deepEqual(spawned.args, []);
    assert.isTrue(
      spawned.command.endsWith(
        ' ^"--goto^" ^"C:\\Users\\jö\\R^&D^ ^(100^%^)\\naïve^ ^^file^!.ts:3:7^"',
      ),
    );
  }),
);
...' quoting `systemctl show-environment` would print.\n XAUTHORITY: \"/home/user/auth files/cookie\",\n },\n );\n assert.deepEqual(yield* launchEnv({ stdout: \"invalid JSON\" }), { PATH: binDir });\n assert.deepEqual(yield* launchEnv({ stdout: '{\"data\":[42]}' }), { PATH: binDir });\n assert.deepEqual(\n yield* launchEnv({\n spawnError: PlatformError.systemError({\n _tag: \"NotFound\",\n module: \"ChildProcess\",\n method: \"spawn\",\n }),\n }),\n { PATH: binDir },\n );\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nit.effect(\"launches an installed editor with platform-safe arguments\", () =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: \"t3-editors-\" });\n yield* fileSystem.writeFileString(path.join(binDir, \"code.CMD\"), \"@echo off\\r\\n\");\n\n let spawned: ChildProcess.StandardCommand | undefined;\n yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n yield* launcher.launchEditor({\n editor: \"vscode\",\n cwd: \"C:\\\\workspace with spaces\\\\src\\\\index.ts:12:4\",\n });\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"win32\",\n env: { PATH: binDir, PATHEXT: \".COM;.EXE;.BAT;.CMD\" },\n resolveExecutable: (command) =>\n command === \"code\" ? \"C:\\\\Program Files\\\\Microsoft VS Code\\\\bin\\\\code.CMD\" : command,\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n\n assert.ok(spawned);\n assert.equal(\n spawned.command,\n [\n '^\"C:\\\\Program^ Files\\\\Microsoft^ VS^ Code\\\\bin\\\\code.CMD^\"',\n '^\"--goto^\"',\n '^\"C:\\\\workspace^ with^ spaces\\\\src\\\\index.ts:12:4^\"',\n ].join(\" \"),\n );\n assert.deepEqual(spawned.args, []);\n assert.equal(spawned.options.shell, true);\n assert.equal(spawned.options.detached, true);\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nit.effect.skipIf(windowsHost)(\n \"reveals a WSL file in Windows File Explorer through its UNC path\",\n () =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: \"t3-editors-\" });\n for (const name of [\"explorer.exe\", \"powershell.exe\", \"xdg-open\"]) {\n const filePath = path.join(binDir, name);\n yield* fileSystem.writeFileString(filePath, \"#!/bin/sh\\n\");\n yield* fileSystem.chmod(filePath, 0o755);\n }\n\n let spawned: ChildProcess.StandardCommand | undefined;\n const result = yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n const kind = yield* launcher.resolveFileManagerRevealKind();\n const editors = yield* launcher.resolveAvailableEditors();\n yield* launcher.launchEditor({\n editor: \"file-manager\",\n cwd: \"/home/t3/workspace [draft]/author's $media/clip|draft.mp4\",\n reveal: true,\n });\n return { kind, editors };\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"linux\",\n env: {\n PATH: binDir,\n WSL_DISTRO_NAME: \"Ubuntu-24.04\",\n WSL_INTEROP: \"/run/WSL/1_interop\",\n },\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n\n assert.equal(result.kind, \"file-explorer\");\n assert.equal(result.editors.includes(\"file-manager\"), true);\n assert.ok(spawned);\n assert.equal(spawned.command, \"powershell.exe\");\n assert.equal(spawned.options.detached, true);\n const encodedCommand = String(spawned.args[spawned.args.length - 1] ?? \"\");\n const decodedCommand = Buffer.from(encodedCommand, \"base64\").toString(\"utf16le\");\n assert.equal(\n decodedCommand,\n \"$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\\\Directory\\\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath '\\\\\\\\wsl.localhost\\\\Ubuntu-24.04\\\\home\\\\t3\\\\workspace [draft]\\\\author''s $media' } else { Start-Process 'explorer.exe' -ArgumentList ('/select,\\\"' + '\\\\\\\\wsl.localhost\\\\Ubuntu-24.04\\\\home\\\\t3\\\\workspace [draft]\\\\author''s $media\\\\clip|draft.mp4' + '\\\"') }\",\n );\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nfor (const wsl of [false, true]) {\n it.effect.skipIf(windowsHost)(\n \"selects a file over D-Bus on \" + (wsl ? \"WSLg without interop PowerShell\" : \"Linux\"),\n () =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: \"t3-editors-\" });\n for (const name of [\"xdg-open\", \"xdg-mime\", \"gdbus\", ...(wsl ? [\"explorer.exe\"] : [])]) {\n const filePath = path.join(binDir, name);\n yield* fileSystem.writeFileString(filePath, \"#!/bin/sh\\n\");\n yield* fileSystem.chmod(filePath, 0o755);\n }\n const target = \"/workspace/media/a 'quoted' \\\"clip\\\" #100% ? é\\\\name.mp4\";\n const spawnedCommands: ChildProcess.StandardCommand[] = [];\n yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n yield* launcher.launchEditor({ editor: \"file-manager\", cwd: target, reveal: true });\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"linux\",\n env: {\n PATH: binDir,\n WAYLAND_DISPLAY: \"wayland-1\",\n ...(wsl\n ? { WSL_DISTRO_NAME: \"Ubuntu-24.04\", WSL_INTEROP: \"/run/WSL/1_interop\" }\n : {}),\n },\n onSpawn: (command) => spawnedCommands.push(command),\n spawnResult: (command) =>\n command.command === \"xdg-mime\"\n ? { stdout: \"com.thisisgm.flea.desktop\\n\" }\n : undefined,\n }),\n ),\n );\n\n const reveal = spawnedCommands.find((command) => command.command === \"gdbus\");\n assert.ok(reveal);\n assert.deepEqual(reveal.args, [\n \"call\",\n \"--session\",\n \"--dest\",\n \"org.freedesktop.FileManager1\",\n \"--object-path\",\n \"/org/freedesktop/FileManager1\",\n \"--method\",\n \"org.freedesktop.FileManager1.ShowItems\",\n \"[\\\"file:///workspace/media/a%20'quoted'%20%22clip%22%20%23100%25%20%3F%20%C3%A9%5Cname.mp4\\\"]\",\n \"\",\n ]);\n assert.deepEqual(\n spawnedCommands.filter((command) => command.command !== \"xdg-mime\"),\n [reveal],\n );\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n );\n}\n\nfor (const cwd of [\"/workspace with spaces/\", \"/workspace with spaces/file.ts:12:4\"]) {\n it.effect.skipIf(windowsHost)(\n `opens ${cwd} with the macOS Zed bundle when another zed is on PATH`,\n () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const home = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-zed-collision-\" });\n const executable = path.join(home, \"Applications/Zed.app/Contents/MacOS/cli\");\n const binDir = path.join(home, \"zfs/bin\");\n yield* fs.makeDirectory(path.dirname(executable), { recursive: true });\n yield* fs.makeDirectory(binDir, { recursive: true });\n for (const command of [executable, path.join(binDir, \"zed\")]) {\n yield* fs.writeFileString(command, \"#!/bin/sh\\n\");\n yield* fs.chmod(command, 0o755);\n }\n\n let spawned: ChildProcess.StandardCommand | undefined;\n yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n assert.include(yield* launcher.resolveAvailableEditors(), \"zed\");\n yield* launcher.launchEditor({ editor: \"zed\", cwd });\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"darwin\",\n env: { HOME: home, PATH: binDir },\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n assert.ok(spawned);\n assert.equal(spawned.command, executable);\n assert.deepEqual(spawned.args, [cwd]);\n assert.equal(spawned.options.shell, false);\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n );\n}\n\nfor (const { layout, pathNames, fallbackNames, expected } of [\n { layout: \"PATH\", pathNames: [\"zed\", \"zeditor\"], fallbackNames: [], expected: \"zeditor\" },\n {\n layout: \"mixed locations\",\n pathNames: [\"zed\"],\n fallbackNames: [\"zeditor\"],\n expected: \"fallback\",\n },\n {\n layout: \"fallback directory\",\n pathNames: [],\n fallbackNames: [\"zed\", \"zeditor\"],\n expected: \"fallback\",\n },\n]) {\n it.effect.skipIf(windowsHost)(`prefers the Zed editor on Linux with ${layout}`, () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const home = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-zed-linux-\" });\n const binDir = path.join(home, \"bin\");\n const fallbackDir = path.join(home, \".local/bin\");\n for (const [dir, names] of [\n [binDir, pathNames],\n [fallbackDir, fallbackNames],\n ] as const) {\n yield* fs.makeDirectory(dir, { recursive: true });\n for (const name of names) {\n yield* fs.writeFileString(path.join(dir, name), \"#!/bin/sh\\n\");\n yield* fs.chmod(path.join(dir, name), 0o755);\n }\n }\n\n let spawned: ChildProcess.StandardCommand | undefined;\n yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n assert.include(yield* launcher.resolveAvailableEditors(), \"zed\");\n yield* launcher.launchEditor({ editor: \"zed\", cwd: \"/workspace\" });\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"linux\",\n env: { HOME: home, PATH: binDir },\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n assert.ok(spawned);\n assert.equal(\n spawned.command,\n expected === \"fallback\" ? path.join(fallbackDir, \"zeditor\") : expected,\n );\n assert.deepEqual(spawned.args, [\"/workspace\"]);\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n );\n}\n\nit.effect.skipIf(windowsHost)(\"prefers zeditor in a later Linux fallback directory\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const home = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-zed-fallback-\" });\n const localBin = path.join(home, \".local/bin\");\n const systemBin = path.join(home, \"system-bin\");\n for (const [dir, name] of [\n [localBin, \"zed\"],\n [systemBin, \"zeditor\"],\n ] as const) {\n yield* fs.makeDirectory(dir, { recursive: true });\n const executable = path.join(dir, name);\n yield* fs.writeFileString(executable, \"#!/bin/sh\\n\");\n yield* fs.chmod(executable, 0o755);\n }\n const editor = EDITORS.find((editor) => editor.id === \"zed\")!;\n const resolve = resolveEditorCommand(editor, { HOME: home, PATH: \"\" }).pipe(\n Effect.provideService(HostProcess.Platform, \"linux\"),\n Effect.provideService(Path.Path, {\n ...path,\n join: (...parts) =>\n path.join(\n ...parts.map((part) =>\n [\"/usr/local/bin\", \"/usr/bin\", \"/snap/bin\"].includes(part) ? systemBin : part,\n ),\n ),\n }),\n );\n assert.deepEqual(\n yield* resolve,\n Option.some({ command: path.join(systemBin, \"zeditor\"), baseArgs: [] }),\n );\n yield* fs.remove(path.join(systemBin, \"zeditor\"));\n assert.deepEqual(\n yield* resolve,\n Option.some({ command: path.join(localBin, \"zed\"), baseArgs: [] }),\n );\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nit.effect.each([\n { editor: \"webstorm\", installPath: \"Applications/WebStorm 2026.2.app/Contents/MacOS/webstorm\" },\n { editor: \"idea\", installPath: \"Applications/IntelliJ IDEA 2026.1.4.app/Contents/MacOS/idea\" },\n] as const)(\n \"discovers and launches $editor from a versioned macOS bundle\",\n ({ editor, installPath }) =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const home = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-editor-versioned-\" });\n const executable = path.join(home, installPath);\n yield* fs.makeDirectory(path.dirname(executable), { recursive: true });\n yield* fs.writeFileString(executable, \"#!/bin/sh\\n\");\n yield* fs.chmod(executable, 0o755);\n\n let spawned: ChildProcess.StandardCommand | undefined;\n yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n assert.include(yield* launcher.resolveAvailableEditors(), editor);\n yield* launcher.launchEditor({ editor, cwd: \"/workspace with spaces/file.ts:12:4\" });\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"darwin\",\n env: { HOME: home, PATH: path.join(home, \"empty\") },\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n\n assert.ok(spawned);\n assert.equal(spawned.command, executable);\n assert.deepEqual(spawned.args, [\n \"--line\",\n \"12\",\n \"--column\",\n \"3\",\n \"/workspace with spaces/file.ts\",\n ]);\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nit.effect(\"matches macOS bundles on the name boundary only\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const unrelatedHome = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-editor-unrelated-\" });\n const unrelated = path.join(\n unrelatedHome,\n \"Applications/WebStormHelper.app/Contents/MacOS/webstorm\",\n );\n yield* fs.makeDirectory(path.dirname(unrelated), { recursive: true });\n yield* fs.writeFileString(unrelated, \"#!/bin/sh\\n\");\n yield* fs.chmod(unrelated, 0o755);\n\n const editorsFor = (home: string) =>\n Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n return yield* launcher.resolveAvailableEditors();\n }).pipe(\n Effect.provide(\n layerTest({ platform: \"darwin\", env: { HOME: home, PATH: path.join(home, \"bin\") } }),\n ),\n );\n\n assert.notInclude(yield* editorsFor(unrelatedHome), \"webstorm\");\n\n const exactHome = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-editor-exact-\" });\n const exact = path.join(exactHome, \"Applications/WebStorm.app/Contents/MacOS/webstorm\");\n yield* fs.makeDirectory(path.dirname(exact), { recursive: true });\n yield* fs.writeFileString(exact, \"#!/bin/sh\\n\");\n yield* fs.chmod(exact, 0o755);\n\n assert.include(yield* editorsFor(exactHome), \"webstorm\");\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nit.effect(\"keeps the macOS VS Code Insiders bundle out of stable VS Code\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const home = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-editor-insiders-\" });\n // The real Insiders bundle ships both `code-insiders` and `code`.\n const bin = path.join(\n home,\n \"Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin\",\n );\n yield* fs.makeDirectory(bin, { recursive: true });\n for (const name of [\"code\", \"code-insiders\"]) {\n yield* fs.writeFileString(path.join(bin, name), \"#!/bin/sh\\n\");\n yield* fs.chmod(path.join(bin, name), 0o755);\n }\n\n let spawned: ChildProcess.StandardCommand | undefined;\n const editors = yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n const available = yield* launcher.resolveAvailableEditors();\n yield* launcher.launchEditor({ editor: \"vscode-insiders\", cwd: \"/workspace/file.ts\" });\n return available;\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"darwin\",\n env: { HOME: home, PATH: path.join(home, \"empty\") },\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n\n assert.notInclude(editors, \"vscode\");\n assert.include(editors, \"vscode-insiders\");\n assert.equal(spawned?.command, path.join(bin, \"code-insiders\"));\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nfor (const { platform, installPath, onPath } of [\n { platform: \"darwin\", installPath: \".local/bin/agy\", onPath: true },\n { platform: \"linux\", installPath: \".local/bin/agy\", onPath: false },\n { platform: \"win32\", installPath: \"agy/bin/agy.cmd\", onPath: true },\n] as const) {\n it.effect.skipIf(windowsHost && platform !== \"win32\")(\n `does not report the agy CLI as the Antigravity IDE on ${platform}`,\n () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const home = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-agy-cli-\" });\n const executable = path.join(home, installPath);\n yield* fs.makeDirectory(path.dirname(executable), { recursive: true });\n yield* fs.writeFileString(executable, \"#!/bin/sh\\n\");\n yield* fs.chmod(executable, 0o755);\n const editors = yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n return yield* launcher.resolveAvailableEditors();\n }).pipe(\n Effect.provide(\n layerTest({\n platform,\n env: {\n HOME: home,\n LOCALAPPDATA: home,\n PATH: onPath ? path.dirname(executable) : path.join(home, \"empty\"),\n PATHEXT: \".COM;.EXE;.BAT;.CMD\",\n },\n }),\n ),\n );\n assert.notInclude(editors, \"antigravity\");\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n );\n}\n\nit.effect.skipIf(windowsHost)(\"ignores unusable app bundles and keeps PATH launchers first\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const home = yield* fs.makeTempDirectoryScoped({ prefix: \"t3-editor-priority-\" });\n const executable = path.join(home, \"Applications/Cursor.app/Contents/Resources/app/bin/code\");\n const env = { HOME: home, PATH: path.join(home, \"bin\") };\n const discover = Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n return yield* launcher.resolveAvailableEditors();\n });\n const before = yield* discover.pipe(Effect.provide(layerTest({ platform: \"darwin\", env })));\n yield* fs.makeDirectory(executable, { recursive: true });\n assert.deepEqual(\n yield* discover.pipe(Effect.provide(layerTest({ platform: \"darwin\", env }))),\n before,\n );\n yield* fs.remove(executable, { recursive: true });\n yield* fs.writeFileString(executable, \"#!/bin/sh\\n\");\n yield* fs.chmod(executable, 0o644);\n assert.deepEqual(\n yield* discover.pipe(Effect.provide(layerTest({ platform: \"darwin\", env }))),\n before,\n );\n yield* fs.chmod(executable, 0o755);\n yield* fs.makeDirectory(env.PATH);\n yield* fs.writeFileString(path.join(env.PATH, \"cursor\"), \"#!/bin/sh\\n\");\n yield* fs.chmod(path.join(env.PATH, \"cursor\"), 0o755);\n let spawned: ChildProcess.StandardCommand | undefined;\n yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n yield* launcher.launchEditor({ editor: \"cursor\", cwd: \"/workspace\" });\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"darwin\",\n env: { ...env, PATH: `${env.PATH}:/usr/bin` },\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n assert.equal(spawned?.command, \"cursor\");\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),\n);\n\nit.effect(\n \"memoizes editor discovery and refreshes in the background after the cache window\",\n () => {\n let statCalls = 0;\n const rescanned = Deferred.makeUnsafe\u003cvoid>();\n let initialScanDone = false;\n const fileInfo = { type: \"File\" } as FileSystem.File.Info;\n const layerLauncher = ExternalLauncher.layer.pipe(\n Layer.provide(\n Layer.mergeAll(\n FileSystem.layerNoop({\n stat: () =>\n Effect.sync(() => {\n statCalls += 1;\n return fileInfo;\n }).pipe(\n Effect.tap(() =>\n initialScanDone ? Deferred.succeed(rescanned, undefined) : Effect.void,\n ),\n ),\n }),\n Path.layer,\n Layer.succeed(\n ChildProcessSpawner.ChildProcessSpawner,\n ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),\n ),\n ),\n ),\n );\n\n return Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n\n const first = yield* launcher.resolveAvailableEditors();\n assert.equal(first.includes(\"vscode\"), true);\n const statCallsAfterFirstScan = statCalls;\n initialScanDone = true;\n assert.isAbove(statCallsAfterFirstScan, 0);\n\n // Past the shared command-resolution cache TTL (30s) but within the\n // discovery cache window: the memoized set is reused without any scan.\n yield* TestClock.adjust(\"31 seconds\");\n const second = yield* launcher.resolveAvailableEditors();\n assert.deepEqual([...second], [...first]);\n assert.equal(statCalls, statCallsAfterFirstScan);\n\n // Past the discovery cache window the next call still answers from the\n // memoized set and rescans in the background.\n yield* TestClock.adjust(\"30 seconds\");\n const third = yield* launcher.resolveAvailableEditors();\n assert.deepEqual([...third], [...first]);\n yield* Deferred.await(rescanned);\n assert.isAbove(statCalls, statCallsAfterFirstScan);\n }).pipe(\n Effect.provide(\n Layer.mergeAll(\n layerLauncher,\n Layer.succeed(HostProcess.Platform, \"win32\"),\n ConfigProvider.layer(\n ConfigProvider.fromEnv({\n env: {\n PATH: \"C:\\\\t3-editor-discovery-cache-test\",\n PATHEXT: \".COM;.EXE;.BAT;.CMD\",\n },\n }),\n ),\n TestClock.layer(),\n ),\n ),\n );\n },\n);\n\nit.effect(\"keeps scanning after the caller is interrupted and shares that scan\", () => {\n const fileInfo = { type: \"File\" } as FileSystem.File.Info;\n const release = Deferred.makeUnsafe\u003cvoid>();\n let parkedStats = 0;\n const layerLauncher = ExternalLauncher.layer.pipe(\n Layer.provide(\n Layer.mergeAll(\n FileSystem.layerNoop({\n stat: () =>\n Effect.gen(function* () {\n if (!Deferred.isDoneUnsafe(release)) {\n parkedStats += 1;\n yield* Deferred.await(release);\n }\n return fileInfo;\n }),\n }),\n Path.layer,\n Layer.succeed(\n ChildProcessSpawner.ChildProcessSpawner,\n ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),\n ),\n ),\n ),\n );\n\n return Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n\n const interrupted = yield* Effect.forkChild(launcher.resolveAvailableEditors());\n yield* Effect.yieldNow;\n yield* Fiber.interrupt(interrupted);\n\n const next = yield* Effect.forkChild(launcher.resolveAvailableEditors());\n yield* Effect.yieldNow;\n assert.equal(parkedStats, 1);\n\n yield* Deferred.succeed(release, undefined);\n const editors = yield* Fiber.join(next);\n assert.equal(editors.includes(\"vscode\"), true);\n }).pipe(\n Effect.provide(\n Layer.mergeAll(\n layerLauncher,\n Layer.succeed(HostProcess.Platform, \"win32\"),\n ConfigProvider.layer(\n ConfigProvider.fromEnv({\n env: {\n PATH: \"C:\\\\t3-editor-discovery-interrupt-test\",\n PATHEXT: \".COM;.EXE;.BAT;.CMD\",\n },\n }),\n ),\n ),\n ),\n );\n});\n\nconst launchWindowsShimEditor = (cwd: string) =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: \"t3-editors-\" });\n yield* fileSystem.writeFileString(path.join(binDir, \"code.CMD\"), \"@echo off\\r\\n\");\n let spawned: ChildProcess.StandardCommand | undefined;\n const exit = yield* Effect.gen(function* () {\n const launcher = yield* ExternalLauncher.ExternalLauncher;\n return yield* launcher.launchEditor({ editor: \"vscode\", cwd }).pipe(Effect.exit);\n }).pipe(\n Effect.provide(\n layerTest({\n platform: \"win32\",\n env: { PATH: binDir, PATHEXT: \".COM;.EXE;.BAT;.CMD\" },\n resolveExecutable: (command) =>\n command === \"code\" ? \"C:\\\\Program Files\\\\Microsoft VS Code\\\\bin\\\\code.CMD\" : command,\n onSpawn: (command) => {\n spawned = command;\n },\n }),\n ),\n );\n return { exit, spawned };\n }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));\n\nit.effect.each([\n [\"CRLF\", \"C:\\\\workspace\\\\file.ts\\r\\ncalc.exe\"],\n [\"LF\", \"C:\\\\workspace\\\\file.ts\\ncalc.exe\"],\n [\"double quote\", 'C:\\\\workspace\\\\file.ts\" & calc.exe & \"'],\n] as const)(\"does not start a Windows command shim for a path with a $0\", ([, cwd]) =>\n Effect.gen(function* () {\n const { exit, spawned } = yield* launchWindowsShimEditor(cwd);\n assert.equal(spawned, undefined);\n assert.isTrue(Exit.isFailure(exit));\n if (Exit.isFailure(exit)) {\n assert.instanceOf(\n Cause.squash(exit.cause),\n ExternalLauncher.ExternalLauncherUnsupportedTargetError,\n );\n }\n }),\n);\n\nit.effect(\"starts a Windows command shim for unicode paths with cmd metacharacters\", () =>\n Effect.gen(function* () {\n const { exit, spawned } = yield* launchWindowsShimEditor(\n \"C:\\\\Users\\\\jö\\\\R&D (100%)\\\\naïve ^file!.ts:3:7\",\n );\n assert.isTrue(Exit.isSuccess(exit));\n assert.ok(spawned);\n assert.equal(spawned.options.shell, true);\n assert.deepEqual(spawned.args, []);\n assert.isTrue(\n spawned.command.endsWith(\n ' ^\"--goto^\" ^\"C:\\\\Users\\\\jö\\\\R^&D^ ^(100^%^)\\\\naïve^ ^^file^!.ts:3:7^\"',\n ),\n );\n }),\n);\n","preview":null,"history":null,"version":"9f975ee209e3df2557ebda46f11d4745fe658739"},"/_session?shell=1":null}