Skip to content
126 changes: 121 additions & 5 deletions apps/server/src/bin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,16 @@ const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
return { result, output };
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));

const makeCliTestServerConfig = (baseDir: string) =>
const makeCliTestServerConfig = (
baseDir: string,
options?: { readonly stateVariant?: "userdata" | "dev" },
) =>
Effect.gen(function* () {
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
const asDev = options?.stateVariant === "dev";
const derivedPaths = yield* ServerConfig.deriveServerPaths(
baseDir,
asDev ? new URL("http://localhost:5733") : undefined,
);
return {
logLevel: "Info",
traceMinLevel: "Info",
Expand All @@ -83,7 +90,9 @@ const makeCliTestServerConfig = (baseDir: string) =>
baseDir,
...derivedPaths,
staticDir: undefined,
devUrl: undefined,
// Origin for open/attach is still the backend HTTP port; a recorded
// devUrl only selects the `dev/` state directory for this fixture.
devUrl: asDev ? "http://localhost:5733" : undefined,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "browser",
Expand Down Expand Up @@ -113,9 +122,13 @@ const readPersistedSnapshot = (baseDir: string) =>
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
});

const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
const withLiveProjectCliServer = <A, E, R>(
baseDir: string,
run: () => Effect.Effect<A, E, R>,
options?: { readonly stateVariant?: "userdata" | "dev" },
) =>
Effect.gen(function* () {
const config = yield* makeCliTestServerConfig(baseDir);
const config = yield* makeCliTestServerConfig(baseDir, options);
const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
Expand Down Expand Up @@ -572,6 +585,109 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);

it.effect("opens a directory on a running server instead of starting another", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-open-live-test-"));
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-open-live-workspace-"),
);

yield* withLiveProjectCliServer(baseDir, () =>
Effect.gen(function* () {
const first = yield* captureStdout(
runCli([workspaceRoot, "--base-dir", baseDir, "--no-browser"]),
);
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const afterAdd = yield* projectionSnapshotQuery.getSnapshot();
const addedProject = afterAdd.projects.find(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
assert.isTrue(addedProject !== undefined);
assert.include(first.output, "Opened project");
assert.include(first.output, workspaceRoot);

const second = yield* captureStdout(
runCli([workspaceRoot, "--base-dir", baseDir, "--no-browser"]),
);
const afterSecond = yield* projectionSnapshotQuery.getSnapshot();
const matching = afterSecond.projects.filter(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
assert.equal(matching.length, 1);
assert.include(second.output, addedProject?.id ?? "");
}),
);
}),
);

it.effect("opens a directory against a live server that only wrote the dev state dir", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-open-live-dev-test-"),
);
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-open-live-dev-workspace-"),
);

yield* withLiveProjectCliServer(
baseDir,
() =>
Effect.gen(function* () {
assert.isFalse(
NodeFS.existsSync(NodePath.join(baseDir, "userdata", "server-runtime.json")),
);
assert.isTrue(NodeFS.existsSync(NodePath.join(baseDir, "dev", "server-runtime.json")));

const { output } = yield* captureStdout(
runCli([workspaceRoot, "--base-dir", baseDir, "--no-browser"]),
);
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const afterAdd = yield* projectionSnapshotQuery.getSnapshot();
const addedProject = afterAdd.projects.find(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
assert.isTrue(addedProject !== undefined);
assert.include(output, "Opened project");
assert.include(output, workspaceRoot);
}),
{ stateVariant: "dev" },
);
}),
);

it.effect("surfaces open failures against a live server instead of starting another", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-open-live-fail-test-"),
);
const missingWorkspace = NodePath.join(
NodeOS.tmpdir(),
`t3-cli-open-live-missing-${Date.now()}`,
);

yield* withLiveProjectCliServer(baseDir, () =>
Effect.gen(function* () {
const error = yield* runCli([
missingWorkspace,
"--base-dir",
baseDir,
"--no-browser",
]).pipe(Effect.flip);
const rendered = String(
typeof error === "object" && error !== null && "message" in error
? error.message
: error,
);
assert.match(rendered, /does not exist|not exist|ENOENT|WorkspaceRoot/i);
// Soft-miss path must not have cleared the live runtime file.
assert.isTrue(
NodeFS.existsSync(NodePath.join(baseDir, "userdata", "server-runtime.json")),
);
}),
);
}),
);

it.effect("rejects dev-url on project commands", () =>
Effect.gen(function* () {
const workspaceRoot = NodeFS.mkdtempSync(
Expand Down
60 changes: 57 additions & 3 deletions apps/server/src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,60 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Console from "effect/Console";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { Argument, Command } from "effect/unstable/cli";
import * as CliError from "effect/unstable/cli/CliError";

import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { connectCommand } from "./cli/connect.ts";
import { tryLaunchDesktopApp } from "./cli/desktopLaunch.ts";
import { pairCommand } from "./cli/pair.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { openLiveProjectIfPresent, projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { serviceCommand } from "./cli/service.ts";
import { servicePreflightCommand } from "./cli/servicePreflight.ts";

const DESKTOP_OPEN_POLL_ATTEMPTS = 40;
const DESKTOP_OPEN_POLL_DELAY = Duration.millis(500);

const openProjectViaDesktopOrLiveServer = Effect.fn("openProjectViaDesktopOrLiveServer")(
function* (flags: {
readonly baseDir: Option.Option<string>;
readonly cwd: Option.Option<string>;
}) {
// Already attached to whatever is serving this home (CLI or desktop backend).
// Never clear discovery here: a transient miss must not delete a live
// desktop/server runtime file before we launch/poll.
if (yield* openLiveProjectIfPresent({ ...flags, clearOnFailure: false })) {
return true;
}

// No live backend: try the installed desktop app, then attach once it is up.
if (!(yield* tryLaunchDesktopApp())) {
return false;
}

for (let attempt = 0; attempt < DESKTOP_OPEN_POLL_ATTEMPTS; attempt += 1) {
yield* Effect.sleep(DESKTOP_OPEN_POLL_DELAY);
if (yield* openLiveProjectIfPresent({ ...flags, clearOnFailure: false })) {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return true;
}
}

yield* Console.error(
"Launched T3 Code desktop, but it did not become ready in time. Falling back to the CLI server.",
);
return false;
},
);

const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);

const connectPublicConfigMissingMessage =
Expand Down Expand Up @@ -45,8 +83,24 @@ const connectUnavailableCommand = Command.make("connect", {

export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
Command.make("t3", { ...sharedServerCommandFlags }).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) => runServerCommand(flags)),
Command.withDescription(
"Run the T3 Code server, or open a directory in the desktop app / a running server.",
),
Command.withHandler((flags) =>
Effect.gen(function* () {
const cwd = flags.cwd ?? Option.none();
if (
Option.isSome(cwd) &&
(yield* openProjectViaDesktopOrLiveServer({
baseDir: flags.baseDir ?? Option.none(),
cwd,
}))
) {
return;
}
return yield* runServerCommand(flags);
}),
),
Command.withSubcommands([
startCommand,
serveCommand,
Expand Down
4 changes: 1 addition & 3 deletions apps/server/src/cli/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,7 @@ export const sharedServerCommandFlags = {
host: hostFlag,
baseDir: baseDirFlag,
cwd: Argument.string("cwd").pipe(
Argument.withDescription(
"Working directory for provider sessions (defaults to the current directory).",
),
Argument.withDescription("Directory to open as a project (defaults to the current directory)."),
Argument.optional,
),
devUrl: devUrlFlag,
Expand Down
64 changes: 64 additions & 0 deletions apps/server/src/cli/desktopLaunch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import * as NodePath from "node:path";

import { assert, it } from "@effect/vitest";

import {
DESKTOP_APP_NAMES,
isT3LinuxDesktopEntry,
linuxDesktopEntryLaunchIds,
windowsDesktopExecutableCandidates,
} from "./desktopLaunch.ts";

it("lists stable and nightly desktop app names", () => {
assert.include(DESKTOP_APP_NAMES as ReadonlyArray<string>, "T3 Code (Alpha)");
assert.include(DESKTOP_APP_NAMES as ReadonlyArray<string>, "T3 Code (Nightly)");
});

it("resolves common Windows install paths under Local AppData", () => {
const localAppData = "/Users/test/AppData/Local";
const candidates = windowsDesktopExecutableCandidates(localAppData);
assert.include(
candidates,
NodePath.join(localAppData, "Programs", "t3-code", "T3 Code (Alpha).exe"),
);
assert.include(
candidates,
NodePath.join(localAppData, "Programs", "T3 Code (Nightly)", "T3 Code (Nightly).exe"),
);
});

it("recognizes AppImage-minted Linux desktop entries for gtk-launch", () => {
assert.isTrue(
isT3LinuxDesktopEntry(`[Desktop Entry]
Name=T3 Code (Alpha)
Exec=/home/user/T3-Code-Alpha.AppImage %U
Type=Application
`),
);
assert.deepEqual(
linuxDesktopEntryLaunchIds([
{
fileName: "appimagekit_7f3a-T3_Code_Alpha.desktop",
contents: `[Desktop Entry]
Name=T3 Code (Alpha)
Exec=/tmp/T3-Code-Alpha.AppImage
`,
},
{
fileName: "firefox.desktop",
contents: `[Desktop Entry]
Name=Firefox
Exec=firefox
`,
},
{
fileName: "com.t3tools.t3code.desktop",
contents: `[Desktop Entry]
Name=T3 Code
StartupWMClass=com.t3tools.t3code
`,
},
]),
["appimagekit_7f3a-T3_Code_Alpha", "com.t3tools.t3code"],
);
});
Loading
Loading