feat(cli): open projects in the running desktop app (#8824)
This commit is contained in:
1 parent
beae2147a9
commit
04efa7907e
26 files changed
+1890
-3
No files matched your search
@@ -11,6 +11,7 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppActivation from "./DesktopAppActivation.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
@@ -148,6 +149,7 @@ const bootstrap = Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
|
||||
yield* logBootstrapInfo("bootstrap start");
|
||||
|
||||
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
|
||||
@@ -210,6 +212,10 @@ const bootstrap = Effect.gen(function* () {
|
||||
}
|
||||
yield* primaryBackend.start;
|
||||
yield* logBootstrapInfo("bootstrap backend start requested");
|
||||
yield* appActivation.start.pipe(
|
||||
Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
|
||||
Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
|
||||
);
|
||||
// Bring up the WSL backend if the user previously enabled it. The
|
||||
// primary is already starting; reconcile fires off the WSL register
|
||||
// in parallel rather than blocking primary readiness on a possibly
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off -- This adapter test binds a real local socket or Windows named pipe and verifies its cleanup.
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeNet from "node:net";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type DesktopAppActivationRequest,
|
||||
type DesktopAppActivationResponse,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppControl";
|
||||
import { HostProcessPlatform, HostProcessUserId } from "@t3tools/shared/hostProcess";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { afterEach, describe, expect } from "vite-plus/test";
|
||||
|
||||
import { startDesktopAppControlServer } from "./DesktopAppActivation.ts";
|
||||
|
||||
const openServers: Array<{ close: () => Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(openServers.splice(0).map((server) => server.close()));
|
||||
});
|
||||
|
||||
function makeTarget(stateDir: string, platform: NodeJS.Platform, userId: number | undefined) {
|
||||
return resolveDesktopAppControlAddress({
|
||||
stateDir,
|
||||
platform,
|
||||
tempDir: NodeOS.tmpdir(),
|
||||
userId,
|
||||
joinPath: NodePath.join,
|
||||
});
|
||||
}
|
||||
|
||||
function request(requestId: string, platform: NodeJS.Platform): DesktopAppActivationRequest {
|
||||
return {
|
||||
version: 1,
|
||||
requestId,
|
||||
type: "open-workspace",
|
||||
workspaceRoot: NodePath.join(NodeOS.tmpdir(), "project"),
|
||||
platform: platform === "win32" ? "win32" : platform === "darwin" ? "darwin" : "linux",
|
||||
};
|
||||
}
|
||||
|
||||
function exchange(address: string, payload: DesktopAppActivationRequest) {
|
||||
return new Promise<DesktopAppActivationResponse>((resolve, reject) => {
|
||||
const socket = NodeNet.createConnection(address);
|
||||
socket.setEncoding("utf8");
|
||||
let buffer = "";
|
||||
socket.once("error", reject);
|
||||
socket.once("connect", () => socket.write(`${JSON.stringify(payload)}\n`));
|
||||
socket.on("data", (chunk) => {
|
||||
buffer += chunk;
|
||||
const newline = buffer.indexOf("\n");
|
||||
if (newline === -1) return;
|
||||
socket.destroy();
|
||||
resolve(JSON.parse(buffer.slice(0, newline)) as DesktopAppActivationResponse);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("desktop app control server", () => {
|
||||
it.effect("roundtrips a request and removes its socket on shutdown", () =>
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const userId = yield* HostProcessUserId;
|
||||
yield* Effect.promise(async () => {
|
||||
const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-app-control-test-"));
|
||||
const target = makeTarget(NodePath.join(root, "userdata"), platform, userId);
|
||||
const received: DesktopAppActivationRequest[] = [];
|
||||
const server = await startDesktopAppControlServer({
|
||||
...target,
|
||||
userId,
|
||||
handle: async (input) => {
|
||||
received.push(input);
|
||||
return {
|
||||
version: 1,
|
||||
requestId: input.requestId,
|
||||
ok: true,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
},
|
||||
cancel: () => undefined,
|
||||
});
|
||||
openServers.push(server);
|
||||
|
||||
const response = await exchange(target.address, request("request-1", platform));
|
||||
|
||||
expect(received).toHaveLength(1);
|
||||
expect(response).toMatchObject({ ok: true, requestId: "request-1" });
|
||||
await server.close();
|
||||
openServers.splice(openServers.indexOf(server), 1);
|
||||
if (target.directory !== null) {
|
||||
await expect(NodeFSP.stat(target.address)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
}
|
||||
await NodeFSP.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("cancels a queued request when the client disconnects", () =>
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const userId = yield* HostProcessUserId;
|
||||
yield* Effect.promise(async () => {
|
||||
const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-app-cancel-test-"));
|
||||
const target = makeTarget(NodePath.join(root, "userdata"), platform, userId);
|
||||
let resolveCanceled: (requestId: string) => void = () => undefined;
|
||||
const canceled = new Promise<string>((resolve) => {
|
||||
resolveCanceled = resolve;
|
||||
});
|
||||
const server = await startDesktopAppControlServer({
|
||||
...target,
|
||||
userId,
|
||||
handle: () => new Promise(() => undefined),
|
||||
cancel: resolveCanceled,
|
||||
});
|
||||
openServers.push(server);
|
||||
const socket = NodeNet.createConnection(target.address);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.once("connect", () => {
|
||||
socket.write(`${JSON.stringify(request("request-canceled", platform))}\n`, () => {
|
||||
socket.destroy();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
await expect(canceled).resolves.toBe("request-canceled");
|
||||
await server.close();
|
||||
openServers.splice(openServers.indexOf(server), 1);
|
||||
await NodeFSP.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off -- Local socket ownership checks need lstat uid and an atomic stale-socket unlink at the Node adapter boundary.
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeNet from "node:net";
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import {
|
||||
DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
|
||||
DesktopAppActivationRequest,
|
||||
type DesktopAppActivationResponse,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppControl";
|
||||
import { HostProcessUserId } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import { DesktopAppActivationBroker } from "./DesktopAppActivationBroker.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
|
||||
const MAX_REQUEST_BYTES = 64 * 1024;
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
const isDesktopAppActivationRequest = Schema.is(DesktopAppActivationRequest);
|
||||
|
||||
export class DesktopAppActivationStartError extends Schema.TaggedErrorClass<DesktopAppActivationStartError>()(
|
||||
"DesktopAppActivationStartError",
|
||||
{
|
||||
address: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not start the desktop app control socket at ${this.address}.`;
|
||||
}
|
||||
}
|
||||
|
||||
interface RunningControlServer {
|
||||
readonly close: () => Promise<void>;
|
||||
}
|
||||
|
||||
function invalidResponse(requestId: string, message: string): DesktopAppActivationResponse {
|
||||
return {
|
||||
version: DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
|
||||
requestId,
|
||||
ok: false,
|
||||
code: "invalid-request",
|
||||
message,
|
||||
};
|
||||
}
|
||||
|
||||
function requestIdFromUnknown(value: unknown): string {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"requestId" in value &&
|
||||
typeof value.requestId === "string" &&
|
||||
value.requestId.trim().length > 0
|
||||
) {
|
||||
return value.requestId;
|
||||
}
|
||||
return "invalid-request";
|
||||
}
|
||||
|
||||
async function prepareUnixSocket(input: {
|
||||
readonly address: string;
|
||||
readonly directory: string;
|
||||
readonly userId: number | undefined;
|
||||
}): Promise<void> {
|
||||
await NodeFSP.mkdir(input.directory, { recursive: true, mode: 0o700 });
|
||||
const stat = await NodeFSP.lstat(input.directory);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
||||
throw new Error(`${input.directory} is not a directory.`);
|
||||
}
|
||||
if (input.userId !== undefined && stat.uid !== input.userId) {
|
||||
throw new Error(`${input.directory} is owned by another user.`);
|
||||
}
|
||||
await NodeFSP.chmod(input.directory, 0o700);
|
||||
await NodeFSP.unlink(input.address).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
});
|
||||
}
|
||||
|
||||
export async function startDesktopAppControlServer(input: {
|
||||
readonly address: string;
|
||||
readonly directory: string | null;
|
||||
readonly userId: number | undefined;
|
||||
readonly handle: (request: DesktopAppActivationRequest) => Promise<DesktopAppActivationResponse>;
|
||||
readonly cancel: (requestId: string) => void;
|
||||
}): Promise<RunningControlServer> {
|
||||
if (input.directory !== null) {
|
||||
await prepareUnixSocket({
|
||||
address: input.address,
|
||||
directory: input.directory,
|
||||
userId: input.userId,
|
||||
});
|
||||
}
|
||||
|
||||
const sockets = new Set<NodeNet.Socket>();
|
||||
const server = NodeNet.createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.setEncoding("utf8");
|
||||
let buffer = "";
|
||||
let handled = false;
|
||||
let responseSent = false;
|
||||
let activeRequestId: string | null = null;
|
||||
|
||||
socket.setTimeout(5_000, () => socket.destroy());
|
||||
|
||||
const finish = (response: DesktopAppActivationResponse) => {
|
||||
responseSent = true;
|
||||
if (!socket.destroyed) socket.end(`${JSON.stringify(response)}\n`);
|
||||
};
|
||||
|
||||
socket.on("data", (chunk) => {
|
||||
if (handled) return;
|
||||
buffer += chunk;
|
||||
if (Buffer.byteLength(buffer, "utf8") > MAX_REQUEST_BYTES) {
|
||||
handled = true;
|
||||
finish(invalidResponse("invalid-request", "The desktop app request is too large."));
|
||||
return;
|
||||
}
|
||||
|
||||
const newline = buffer.indexOf("\n");
|
||||
if (newline === -1) return;
|
||||
handled = true;
|
||||
socket.setTimeout(0);
|
||||
const line = buffer.slice(0, newline);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
finish(invalidResponse("invalid-request", "The desktop app request is not valid JSON."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isDesktopAppActivationRequest(parsed)) {
|
||||
finish(
|
||||
invalidResponse(requestIdFromUnknown(parsed), "The desktop app request is invalid."),
|
||||
);
|
||||
return;
|
||||
}
|
||||
activeRequestId = parsed.requestId;
|
||||
void input.handle(parsed).then(finish, () => {
|
||||
finish(
|
||||
invalidResponse(parsed.requestId, "T3 Code could not process the desktop app request."),
|
||||
);
|
||||
});
|
||||
});
|
||||
socket.on("error", () => socket.destroy());
|
||||
socket.on("close", () => {
|
||||
sockets.delete(socket);
|
||||
if (!responseSent && activeRequestId !== null) input.cancel(activeRequestId);
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => {
|
||||
server.removeListener("listening", onListening);
|
||||
reject(error);
|
||||
};
|
||||
const onListening = () => {
|
||||
server.removeListener("error", onError);
|
||||
resolve();
|
||||
};
|
||||
server.once("error", onError);
|
||||
server.once("listening", onListening);
|
||||
server.listen(input.address);
|
||||
});
|
||||
|
||||
try {
|
||||
if (input.directory !== null) {
|
||||
await NodeFSP.chmod(input.address, 0o600);
|
||||
}
|
||||
} catch (error) {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
throw error;
|
||||
}
|
||||
|
||||
let closed = false;
|
||||
return {
|
||||
close: async () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (const socket of sockets) socket.destroy();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
server.removeAllListeners();
|
||||
if (input.directory !== null) {
|
||||
await NodeFSP.unlink(input.address).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export class DesktopAppActivation extends Context.Service<
|
||||
DesktopAppActivation,
|
||||
{
|
||||
readonly start: Effect.Effect<void, DesktopAppActivationStartError, Scope.Scope>;
|
||||
readonly setRendererReady: (ready: boolean) => Effect.Effect<void>;
|
||||
readonly complete: (response: DesktopAppActivationResponse) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAppActivation") {}
|
||||
|
||||
const { logWarning } = makeComponentLogger("desktop-app-activation");
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const desktopEnvironment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const path = yield* Path.Path;
|
||||
const userId = yield* HostProcessUserId;
|
||||
const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());
|
||||
const address = resolveDesktopAppControlAddress({
|
||||
stateDir: path.resolve(desktopEnvironment.stateDir),
|
||||
platform: desktopEnvironment.platform,
|
||||
tempDir: NodeOS.tmpdir(),
|
||||
userId,
|
||||
joinPath: path.join,
|
||||
});
|
||||
let registeredWebContents: Electron.WebContents | null = null;
|
||||
let detachRendererListeners: (() => void) | null = null;
|
||||
|
||||
const broker = new DesktopAppActivationBroker({
|
||||
requestTimeoutMs: REQUEST_TIMEOUT_MS,
|
||||
activate: () => {
|
||||
void runPromise(
|
||||
desktopWindow.activate.pipe(
|
||||
Effect.catchCause((cause) => logWarning("failed to focus the desktop window", { cause })),
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const clearRegisteredRenderer = () => {
|
||||
detachRendererListeners?.();
|
||||
detachRendererListeners = null;
|
||||
registeredWebContents = null;
|
||||
broker.clearRenderer();
|
||||
};
|
||||
|
||||
return DesktopAppActivation.of({
|
||||
start: Effect.acquireRelease(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
startDesktopAppControlServer({
|
||||
...address,
|
||||
userId,
|
||||
handle: (request) => broker.request(request),
|
||||
cancel: (requestId) => broker.cancel(requestId),
|
||||
}),
|
||||
catch: (cause) => new DesktopAppActivationStartError({ address: address.address, cause }),
|
||||
}),
|
||||
(server) =>
|
||||
Effect.promise(() => server.close()).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logWarning("failed to close the desktop app control socket", { cause }),
|
||||
),
|
||||
Effect.ensuring(Effect.sync(() => broker.close())),
|
||||
),
|
||||
).pipe(Effect.asVoid),
|
||||
setRendererReady: Effect.fn("DesktopAppActivation.setRendererReady")(function* (ready) {
|
||||
if (!ready) {
|
||||
clearRegisteredRenderer();
|
||||
return;
|
||||
}
|
||||
const main = yield* electronWindow.main;
|
||||
if (Option.isNone(main)) return;
|
||||
const webContents = main.value.webContents;
|
||||
if (webContents.isDestroyed()) return;
|
||||
|
||||
if (registeredWebContents !== webContents) {
|
||||
clearRegisteredRenderer();
|
||||
registeredWebContents = webContents;
|
||||
const onUnavailable = () => clearRegisteredRenderer();
|
||||
const onNavigation = (
|
||||
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
|
||||
) => {
|
||||
if (event.isMainFrame && !event.isSameDocument) clearRegisteredRenderer();
|
||||
};
|
||||
webContents.on("did-start-navigation", onNavigation);
|
||||
webContents.once("destroyed", onUnavailable);
|
||||
detachRendererListeners = () => {
|
||||
webContents.removeListener("did-start-navigation", onNavigation);
|
||||
webContents.removeListener("destroyed", onUnavailable);
|
||||
};
|
||||
}
|
||||
|
||||
broker.registerRenderer((request) => {
|
||||
webContents.send(DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL, request);
|
||||
});
|
||||
}),
|
||||
complete: (response) => Effect.sync(() => broker.complete(response)),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopAppActivation, make);
|
||||
@@ -0,0 +1,130 @@
|
||||
import { ProjectId, ThreadId, type DesktopAppActivationRequest } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { DesktopAppActivationBroker } from "./DesktopAppActivationBroker.ts";
|
||||
|
||||
const request: DesktopAppActivationRequest = {
|
||||
version: 1,
|
||||
requestId: "request-1",
|
||||
type: "open-workspace",
|
||||
workspaceRoot: "/workspace/project",
|
||||
platform: "linux",
|
||||
};
|
||||
|
||||
describe("DesktopAppActivationBroker", () => {
|
||||
it("focuses immediately and waits for renderer readiness", async () => {
|
||||
const activate = vi.fn();
|
||||
const send = vi.fn();
|
||||
const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate });
|
||||
|
||||
const response = broker.request(request);
|
||||
expect(activate).toHaveBeenCalledOnce();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
|
||||
broker.registerRenderer(send);
|
||||
expect(send).toHaveBeenCalledWith(request);
|
||||
broker.complete({
|
||||
version: 1,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
await expect(response).resolves.toMatchObject({ ok: true, projectId: "project-1" });
|
||||
broker.close();
|
||||
});
|
||||
|
||||
it("fails an in-flight request when the renderer goes away", async () => {
|
||||
const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() });
|
||||
broker.registerRenderer(vi.fn());
|
||||
|
||||
const response = broker.request(request);
|
||||
broker.clearRenderer();
|
||||
|
||||
await expect(response).resolves.toMatchObject({
|
||||
ok: false,
|
||||
code: "renderer-unavailable",
|
||||
});
|
||||
broker.close();
|
||||
});
|
||||
|
||||
it("queues requests after unsubscribe until a new renderer registers", async () => {
|
||||
const previousSend = vi.fn();
|
||||
const nextSend = vi.fn();
|
||||
const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() });
|
||||
broker.registerRenderer(previousSend);
|
||||
broker.clearRenderer();
|
||||
|
||||
const response = broker.request(request);
|
||||
expect(previousSend).not.toHaveBeenCalled();
|
||||
expect(nextSend).not.toHaveBeenCalled();
|
||||
|
||||
broker.registerRenderer(nextSend);
|
||||
expect(nextSend).toHaveBeenCalledWith(request);
|
||||
broker.complete({
|
||||
version: 1,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
await expect(response).resolves.toMatchObject({ ok: true });
|
||||
broker.close();
|
||||
});
|
||||
|
||||
it("removes a queued request when its CLI connection closes", async () => {
|
||||
const send = vi.fn();
|
||||
const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() });
|
||||
|
||||
const response = broker.request(request);
|
||||
broker.cancel(request.requestId);
|
||||
broker.registerRenderer(send);
|
||||
|
||||
await expect(response).resolves.toMatchObject({ ok: false, code: "renderer-unavailable" });
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
broker.close();
|
||||
});
|
||||
|
||||
it("never sends a canceled request that was queued behind another request", async () => {
|
||||
const send = vi.fn();
|
||||
const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() });
|
||||
broker.registerRenderer(send);
|
||||
const secondRequest = { ...request, requestId: "request-2" };
|
||||
|
||||
const firstResponse = broker.request(request);
|
||||
const secondResponse = broker.request(secondRequest);
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
expect(send).toHaveBeenLastCalledWith(request);
|
||||
|
||||
broker.cancel(secondRequest.requestId);
|
||||
broker.complete({
|
||||
version: 1,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
await expect(firstResponse).resolves.toMatchObject({ ok: true });
|
||||
await expect(secondResponse).resolves.toMatchObject({ ok: false });
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
broker.close();
|
||||
});
|
||||
|
||||
it("times out a request without polling", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() });
|
||||
const response = broker.request(request);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
|
||||
await expect(response).resolves.toMatchObject({ ok: false, code: "request-timeout" });
|
||||
broker.close();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
// @effect-diagnostics globalTimers:off -- This protocol broker owns cancellable request deadlines outside the Effect runtime.
|
||||
import {
|
||||
DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
|
||||
type DesktopAppActivationFailure,
|
||||
type DesktopAppActivationRequest,
|
||||
type DesktopAppActivationResponse,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
interface PendingActivation {
|
||||
readonly request: DesktopAppActivationRequest;
|
||||
readonly resolve: (response: DesktopAppActivationResponse) => void;
|
||||
readonly timeout: ReturnType<typeof setTimeout>;
|
||||
dispatched: boolean;
|
||||
}
|
||||
|
||||
type RendererSender = (request: DesktopAppActivationRequest) => void;
|
||||
|
||||
function failure(
|
||||
requestId: string,
|
||||
code: DesktopAppActivationFailure["code"],
|
||||
message: string,
|
||||
): DesktopAppActivationFailure {
|
||||
return {
|
||||
version: DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
|
||||
requestId,
|
||||
ok: false,
|
||||
code,
|
||||
message,
|
||||
};
|
||||
}
|
||||
|
||||
/** Holds CLI requests until the real desktop renderer is ready to handle them. */
|
||||
export class DesktopAppActivationBroker {
|
||||
readonly #pending = new Map<string, PendingActivation>();
|
||||
readonly #requestTimeoutMs: number;
|
||||
readonly #activate: () => void;
|
||||
#renderer: RendererSender | null = null;
|
||||
#closed = false;
|
||||
|
||||
constructor(input: { readonly requestTimeoutMs: number; readonly activate: () => void }) {
|
||||
this.#requestTimeoutMs = input.requestTimeoutMs;
|
||||
this.#activate = input.activate;
|
||||
}
|
||||
|
||||
request(request: DesktopAppActivationRequest): Promise<DesktopAppActivationResponse> {
|
||||
if (this.#closed) {
|
||||
return Promise.resolve(
|
||||
failure(request.requestId, "renderer-unavailable", "T3 Code is shutting down."),
|
||||
);
|
||||
}
|
||||
if (this.#pending.has(request.requestId)) {
|
||||
return Promise.resolve(
|
||||
failure(request.requestId, "invalid-request", "The request id is already in use."),
|
||||
);
|
||||
}
|
||||
|
||||
const response = new Promise<DesktopAppActivationResponse>((resolve) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.#settle(
|
||||
failure(
|
||||
request.requestId,
|
||||
"request-timeout",
|
||||
"The desktop app did not finish opening the project in time.",
|
||||
),
|
||||
);
|
||||
}, this.#requestTimeoutMs);
|
||||
this.#pending.set(request.requestId, {
|
||||
request,
|
||||
resolve,
|
||||
timeout,
|
||||
dispatched: false,
|
||||
});
|
||||
});
|
||||
|
||||
this.#activate();
|
||||
this.#flush();
|
||||
return response;
|
||||
}
|
||||
|
||||
registerRenderer(send: RendererSender): void {
|
||||
this.#renderer = send;
|
||||
this.#flush();
|
||||
}
|
||||
|
||||
clearRenderer(): void {
|
||||
this.#renderer = null;
|
||||
for (const pending of this.#pending.values()) {
|
||||
if (pending.dispatched) {
|
||||
this.#settle(
|
||||
failure(
|
||||
pending.request.requestId,
|
||||
"renderer-unavailable",
|
||||
"The T3 Code window closed before it opened the project.",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
complete(response: DesktopAppActivationResponse): void {
|
||||
this.#settle(response);
|
||||
}
|
||||
|
||||
cancel(requestId: string): void {
|
||||
this.#settle(
|
||||
failure(requestId, "renderer-unavailable", "The command closed before T3 Code was ready."),
|
||||
);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#closed = true;
|
||||
this.#renderer = null;
|
||||
for (const pending of this.#pending.values()) {
|
||||
this.#settle(
|
||||
failure(pending.request.requestId, "renderer-unavailable", "T3 Code is shutting down."),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#flush(): void {
|
||||
const renderer = this.#renderer;
|
||||
if (renderer === null) return;
|
||||
if ([...this.#pending.values()].some((pending) => pending.dispatched)) return;
|
||||
|
||||
for (const pending of this.#pending.values()) {
|
||||
if (pending.dispatched) continue;
|
||||
try {
|
||||
pending.dispatched = true;
|
||||
renderer(pending.request);
|
||||
} catch {
|
||||
pending.dispatched = false;
|
||||
this.#renderer = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#settle(response: DesktopAppActivationResponse): void {
|
||||
const pending = this.#pending.get(response.requestId);
|
||||
if (!pending) return;
|
||||
clearTimeout(pending.timeout);
|
||||
this.#pending.delete(response.requestId);
|
||||
pending.resolve(response);
|
||||
this.#flush();
|
||||
}
|
||||
}
|
||||
@@ -45,12 +45,16 @@ import {
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
import * as AppActivationIpc from "./methods/appActivation.ts";
|
||||
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handle(AppActivationIpc.setReady);
|
||||
yield* ipc.handle(AppActivationIpc.complete);
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getSystemLocale);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
|
||||
@@ -9,6 +9,9 @@ export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const DESKTOP_APP_ACTIVATION_READY_CHANNEL = "desktop:app-activation-ready";
|
||||
export const DESKTOP_APP_ACTIVATION_COMPLETE_CHANNEL = "desktop:app-activation-complete";
|
||||
export const DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL = "desktop:app-activation-request";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { DesktopAppActivationResponse } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopAppActivation from "../../app/DesktopAppActivation.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const setReady = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.DESKTOP_APP_ACTIVATION_READY_CHANNEL,
|
||||
payload: Schema.Boolean,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.appActivation.setReady")(function* (ready) {
|
||||
const activation = yield* DesktopAppActivation.DesktopAppActivation;
|
||||
yield* activation.setRendererReady(ready);
|
||||
}),
|
||||
});
|
||||
|
||||
export const complete = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.DESKTOP_APP_ACTIVATION_COMPLETE_CHANNEL,
|
||||
payload: DesktopAppActivationResponse,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.appActivation.complete")(function* (response) {
|
||||
const activation = yield* DesktopAppActivation.DesktopAppActivation;
|
||||
yield* activation.complete(response);
|
||||
}),
|
||||
});
|
||||
@@ -32,6 +32,7 @@ import * as ElectronTheme from "./electron/ElectronTheme.ts";
|
||||
import * as ElectronUpdater from "./electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "./electron/ElectronWindow.ts";
|
||||
import * as DesktopApp from "./app/DesktopApp.ts";
|
||||
import * as DesktopAppActivation from "./app/DesktopAppActivation.ts";
|
||||
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopClerk from "./app/DesktopClerk.ts";
|
||||
@@ -157,6 +158,10 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
Layer.provideMerge(desktopPreviewLayer),
|
||||
);
|
||||
|
||||
const desktopAppActivationLayer = DesktopAppActivation.layer.pipe(
|
||||
Layer.provide(desktopWindowLayer),
|
||||
);
|
||||
|
||||
// Pool layer instantiates the backend factory once for the Windows
|
||||
// primary instance and exposes it via pool.primary. Consumers go through
|
||||
// the pool now; the legacy DesktopBackendManager service is gone. The
|
||||
@@ -184,6 +189,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
desktopAppActivationLayer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopLinuxUrlHandler.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
|
||||
@@ -178,6 +178,25 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
appActivation: {
|
||||
setReady: (ready) =>
|
||||
ipcRenderer.invoke(IpcChannels.DESKTOP_APP_ACTIVATION_READY_CHANNEL, ready),
|
||||
complete: (response) =>
|
||||
ipcRenderer.invoke(IpcChannels.DESKTOP_APP_ACTIVATION_COMPLETE_CHANNEL, response),
|
||||
onRequest: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
|
||||
if (typeof request !== "object" || request === null) return;
|
||||
listener(request as Parameters<typeof listener>[0]);
|
||||
};
|
||||
ipcRenderer.on(IpcChannels.DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(
|
||||
IpcChannels.DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL,
|
||||
wrappedListener,
|
||||
);
|
||||
};
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
createTab: (tabId, defaults) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, {
|
||||
|
||||
@@ -8,6 +8,7 @@ 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 { appCommand } from "./cli/app.ts";
|
||||
import { connectCommand } from "./cli/connect.ts";
|
||||
import { pairCommand } from "./cli/pair.ts";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
@@ -53,6 +54,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
Command.withSubcommands([
|
||||
startCommand,
|
||||
serveCommand,
|
||||
appCommand,
|
||||
pairCommand,
|
||||
authCommand,
|
||||
projectCommand,
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off -- The integration fixture binds the same platform socket or named pipe as the CLI.
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeNet from "node:net";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import type { DesktopAppActivationRequest } from "@t3tools/contracts";
|
||||
import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppControl";
|
||||
import {
|
||||
HostProcessPlatform,
|
||||
HostProcessUserId,
|
||||
HostProcessWorkingDirectory,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { afterEach, describe, expect, vi } from "vite-plus/test";
|
||||
|
||||
import { makeCli } from "../bin.ts";
|
||||
|
||||
vi.mock("node:os", async (importOriginal) => {
|
||||
const os = await importOriginal<typeof import("node:os")>();
|
||||
return { ...os, homedir: vi.fn(os.homedir) };
|
||||
});
|
||||
|
||||
afterEach(() => vi.mocked(NodeOS.homedir).mockReset());
|
||||
|
||||
const runCli = (args: ReadonlyArray<string>, env: Record<string, string> = {}) =>
|
||||
Command.runWith(makeCli(), { version: "0.0.0" })(args).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
NetService.layer,
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pathExists = (path: string) =>
|
||||
Effect.promise(() =>
|
||||
NodeFSP.stat(path).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
);
|
||||
|
||||
async function startFakeDesktop(input: {
|
||||
readonly baseDir: string;
|
||||
readonly stateSubdirectory?: "userdata" | "dev";
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly userId: number | undefined;
|
||||
readonly reply?: (request: DesktopAppActivationRequest) => unknown;
|
||||
}) {
|
||||
const target = resolveDesktopAppControlAddress({
|
||||
stateDir: NodePath.join(input.baseDir, input.stateSubdirectory ?? "userdata"),
|
||||
platform: input.platform,
|
||||
tempDir: NodeOS.tmpdir(),
|
||||
userId: input.userId,
|
||||
joinPath: NodePath.join,
|
||||
});
|
||||
if (target.directory !== null) {
|
||||
await NodeFSP.mkdir(target.directory, { recursive: true, mode: 0o700 });
|
||||
await NodeFSP.unlink(target.address).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
});
|
||||
}
|
||||
|
||||
const received: DesktopAppActivationRequest[] = [];
|
||||
const server = NodeNet.createServer((socket) => {
|
||||
socket.setEncoding("utf8");
|
||||
let buffer = "";
|
||||
socket.on("data", (chunk) => {
|
||||
buffer += chunk;
|
||||
const newline = buffer.indexOf("\n");
|
||||
if (newline === -1) return;
|
||||
const request = JSON.parse(buffer.slice(0, newline)) as DesktopAppActivationRequest;
|
||||
received.push(request);
|
||||
const response = input.reply
|
||||
? input.reply(request)
|
||||
: {
|
||||
version: 1,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
projectId: "project-1",
|
||||
threadId: `thread-${received.length}`,
|
||||
};
|
||||
socket.end(`${JSON.stringify(response)}\n`);
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(target.address, resolve);
|
||||
});
|
||||
|
||||
return {
|
||||
received,
|
||||
close: async () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
if (target.directory !== null) {
|
||||
await NodeFSP.unlink(target.address).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const fakeDesktop = Effect.fn(function* (
|
||||
input: Omit<Parameters<typeof startFakeDesktop>[0], "platform" | "userId">,
|
||||
) {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const userId = yield* HostProcessUserId;
|
||||
return yield* Effect.acquireRelease(
|
||||
Effect.promise(() => startFakeDesktop({ ...input, platform, userId })),
|
||||
(server) => Effect.promise(() => server.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const withTempDirectory = <A, E, R>(
|
||||
prefix: string,
|
||||
use: (root: string) => Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), prefix))),
|
||||
use,
|
||||
(root) => Effect.promise(() => NodeFSP.rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
|
||||
describe("t3 app", () => {
|
||||
it.effect("rejects SSH before it tries to reach a desktop app", () =>
|
||||
withTempDirectory("t3-app-ssh-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodePath.join(root, "missing-t3-home");
|
||||
const error = yield* runCli(["app", "--base-dir", baseDir], {
|
||||
SSH_CONNECTION: "client server",
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "DesktopAppSshUnsupportedError",
|
||||
message:
|
||||
"`t3 app` only controls a desktop app on the same machine. It cannot run over SSH.",
|
||||
});
|
||||
expect(yield* pathExists(baseDir)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects unsupported platforms without creating state", () =>
|
||||
withTempDirectory("t3-app-platform-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodePath.join(root, "missing-t3-home");
|
||||
const error = yield* runCli(["app", "--base-dir", baseDir]).pipe(
|
||||
Effect.provideService(HostProcessPlatform, "freebsd"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "DesktopAppPlatformUnsupportedError",
|
||||
platform: "freebsd",
|
||||
message: "`t3 app` is not supported on freebsd.",
|
||||
});
|
||||
expect(yield* pathExists(baseDir)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not create state when only a server or no desktop app is running", () =>
|
||||
withTempDirectory("t3-app-missing-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodePath.join(root, "missing-t3-home");
|
||||
const error = yield* runCli(["app", "--base-dir", baseDir]).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "DesktopAppUnreachableError",
|
||||
candidateAddresses: [expect.any(String)],
|
||||
workspaceRoot: yield* HostProcessWorkingDirectory,
|
||||
message: expect.stringContaining("Could not reach the T3 Code desktop app."),
|
||||
cause: { code: "ENOENT" },
|
||||
});
|
||||
expect(yield* pathExists(baseDir)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses T3CODE_HOME or --base-dir and sends the default or explicit path", () =>
|
||||
withTempDirectory("t3-app-command-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodePath.join(root, "t3-home");
|
||||
const explicitPath = NodePath.join(root, "project");
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const workingDirectory = yield* HostProcessWorkingDirectory;
|
||||
const desktop = yield* fakeDesktop({ baseDir });
|
||||
|
||||
yield* runCli(["app"], { T3CODE_HOME: baseDir });
|
||||
yield* runCli(["app", explicitPath, "--base-dir", baseDir]);
|
||||
|
||||
expect(desktop.received.map((request) => request.workspaceRoot)).toEqual([
|
||||
workingDirectory,
|
||||
explicitPath,
|
||||
]);
|
||||
expect(desktop.received.every((request) => request.platform === platform)).toBe(true);
|
||||
}).pipe(Effect.scoped),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("prefers the installed desktop app when a dev desktop is also running", () =>
|
||||
withTempDirectory("t3-app-preferred-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
vi.mocked(NodeOS.homedir).mockReturnValue(root);
|
||||
const baseDir = NodePath.join(root, ".t3");
|
||||
const desktop = yield* fakeDesktop({ baseDir });
|
||||
const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
|
||||
|
||||
yield* runCli(["app"]);
|
||||
|
||||
expect(desktop.received).toHaveLength(1);
|
||||
expect(development.received).toHaveLength(0);
|
||||
}).pipe(Effect.scoped),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("finds the dev desktop when the default desktop socket is absent", () =>
|
||||
withTempDirectory("t3-app-dev-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
vi.mocked(NodeOS.homedir).mockReturnValue(root);
|
||||
const baseDir = NodePath.join(root, ".t3");
|
||||
const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
|
||||
|
||||
yield* runCli(["app"]);
|
||||
yield* runCli(["app"], { T3CODE_HOME: " " });
|
||||
|
||||
expect(development.received).toHaveLength(2);
|
||||
expect(yield* pathExists(baseDir)).toBe(false);
|
||||
}).pipe(Effect.scoped),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("never searches a dev state directory for an explicit T3 home", () =>
|
||||
withTempDirectory("t3-app-explicit-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
vi.mocked(NodeOS.homedir).mockReturnValue(root);
|
||||
const baseDir = NodePath.join(root, ".t3");
|
||||
const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
|
||||
|
||||
const flagError = yield* runCli(["app", "--base-dir", baseDir]).pipe(Effect.flip);
|
||||
const envError = yield* runCli(["app"], { T3CODE_HOME: baseDir }).pipe(Effect.flip);
|
||||
|
||||
expect(flagError).toMatchObject({ _tag: "DesktopAppUnreachableError" });
|
||||
expect(envError).toMatchObject({ _tag: "DesktopAppUnreachableError" });
|
||||
expect(development.received).toHaveLength(0);
|
||||
}).pipe(Effect.scoped),
|
||||
),
|
||||
);
|
||||
|
||||
for (const responseKind of ["failure", "invalid"] as const) {
|
||||
it.effect(`never falls back after the default desktop sends a ${responseKind} response`, () =>
|
||||
withTempDirectory("t3-app-response-test-", (root) =>
|
||||
Effect.gen(function* () {
|
||||
vi.mocked(NodeOS.homedir).mockReturnValue(root);
|
||||
const baseDir = NodePath.join(root, ".t3");
|
||||
const desktop = yield* fakeDesktop({
|
||||
baseDir,
|
||||
reply: (request) =>
|
||||
responseKind === "failure"
|
||||
? {
|
||||
version: 1,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
code: "project-create-failed",
|
||||
message: "The project path is not available.",
|
||||
}
|
||||
: { invalid: true },
|
||||
});
|
||||
const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
|
||||
|
||||
const error = yield* runCli(["app"]).pipe(Effect.flip);
|
||||
|
||||
expect(desktop.received).toHaveLength(1);
|
||||
expect(development.received).toHaveLength(0);
|
||||
if (responseKind === "failure") {
|
||||
expect(error).toMatchObject({
|
||||
_tag: "DesktopAppRequestFailedError",
|
||||
code: "project-create-failed",
|
||||
requestId: desktop.received[0]?.requestId,
|
||||
workspaceRoot: yield* HostProcessWorkingDirectory,
|
||||
message: expect.stringContaining("project-create-failed"),
|
||||
cause: {
|
||||
ok: false,
|
||||
code: "project-create-failed",
|
||||
message: "The project path is not available.",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
expect(error).toMatchObject({
|
||||
_tag: "DesktopAppUnreachableError",
|
||||
cause: { message: "The desktop app response is invalid." },
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.scoped),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
// @effect-diagnostics globalTimers:off -- The Node socket client owns its response deadline and clears it on every completion path.
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as NodeNet from "node:net";
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import {
|
||||
DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
|
||||
DesktopAppActivationErrorCode,
|
||||
DesktopAppActivationResponse,
|
||||
type DesktopAppActivationPlatform,
|
||||
type DesktopAppActivationRequest,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppControl";
|
||||
import {
|
||||
HostProcessPlatform,
|
||||
HostProcessUserId,
|
||||
HostProcessWorkingDirectory,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Argument, Command } from "effect/unstable/cli";
|
||||
|
||||
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
|
||||
import { baseDirFlag } from "./config.ts";
|
||||
|
||||
const CLI_RESPONSE_TIMEOUT_MS = 17_000;
|
||||
const MAX_RESPONSE_BYTES = 64 * 1024;
|
||||
const isDesktopAppActivationResponse = Schema.is(DesktopAppActivationResponse);
|
||||
|
||||
export class DesktopAppSshUnsupportedError extends Schema.TaggedErrorClass<DesktopAppSshUnsupportedError>()(
|
||||
"DesktopAppSshUnsupportedError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "`t3 app` only controls a desktop app on the same machine. It cannot run over SSH.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAppPlatformUnsupportedError extends Schema.TaggedErrorClass<DesktopAppPlatformUnsupportedError>()(
|
||||
"DesktopAppPlatformUnsupportedError",
|
||||
{ platform: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `\`t3 app\` is not supported on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAppUnreachableError extends Schema.TaggedErrorClass<DesktopAppUnreachableError>()(
|
||||
"DesktopAppUnreachableError",
|
||||
{
|
||||
candidateAddresses: Schema.Array(Schema.String),
|
||||
requestId: Schema.String,
|
||||
workspaceRoot: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not reach the T3 Code desktop app. Start or update the desktop app on this machine, then run `t3 app` again. A running T3 Code server is not enough.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAppRequestFailedError extends Schema.TaggedErrorClass<DesktopAppRequestFailedError>()(
|
||||
"DesktopAppRequestFailedError",
|
||||
{
|
||||
code: DesktopAppActivationErrorCode,
|
||||
requestId: Schema.String,
|
||||
workspaceRoot: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `T3 Code could not open ${this.workspaceRoot} (${this.code}).`;
|
||||
}
|
||||
}
|
||||
|
||||
function isDesktopPlatform(platform: NodeJS.Platform): platform is DesktopAppActivationPlatform {
|
||||
return platform === "darwin" || platform === "linux" || platform === "win32";
|
||||
}
|
||||
|
||||
export function sendDesktopAppActivationRequest(input: {
|
||||
readonly address: string;
|
||||
readonly fallbackAddress?: string;
|
||||
readonly request: DesktopAppActivationRequest;
|
||||
readonly timeoutMs?: number;
|
||||
}): Promise<DesktopAppActivationResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = NodeNet.createConnection(input.address);
|
||||
socket.setEncoding("utf8");
|
||||
let buffer = "";
|
||||
let settled = false;
|
||||
let connected = false;
|
||||
|
||||
const finish = (
|
||||
result:
|
||||
| { readonly type: "success"; readonly response: DesktopAppActivationResponse }
|
||||
| { readonly type: "failure"; readonly error: Error },
|
||||
) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
socket.destroy();
|
||||
if (result.type === "success") resolve(result.response);
|
||||
else reject(result.error);
|
||||
};
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
finish({
|
||||
type: "failure",
|
||||
error: new Error("The desktop app did not respond in time."),
|
||||
});
|
||||
}, input.timeoutMs ?? CLI_RESPONSE_TIMEOUT_MS);
|
||||
|
||||
socket.once("connect", () => {
|
||||
connected = true;
|
||||
socket.write(`${JSON.stringify(input.request)}\n`);
|
||||
});
|
||||
socket.on("data", (chunk) => {
|
||||
buffer += chunk;
|
||||
if (Buffer.byteLength(buffer, "utf8") > MAX_RESPONSE_BYTES) {
|
||||
finish({ type: "failure", error: new Error("The desktop app response is too large.") });
|
||||
return;
|
||||
}
|
||||
const newline = buffer.indexOf("\n");
|
||||
if (newline === -1) return;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(buffer.slice(0, newline));
|
||||
} catch {
|
||||
finish({
|
||||
type: "failure",
|
||||
error: new Error("The desktop app response is not valid JSON."),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isDesktopAppActivationResponse(parsed)) {
|
||||
finish({ type: "failure", error: new Error("The desktop app response is invalid.") });
|
||||
return;
|
||||
}
|
||||
if (parsed.requestId !== input.request.requestId) {
|
||||
finish({
|
||||
type: "failure",
|
||||
error: new Error("The desktop app response did not match this request."),
|
||||
});
|
||||
return;
|
||||
}
|
||||
finish({ type: "success", response: parsed });
|
||||
});
|
||||
socket.once("error", (error: NodeJS.ErrnoException) => {
|
||||
if (
|
||||
!settled &&
|
||||
!connected &&
|
||||
input.fallbackAddress !== undefined &&
|
||||
(error.code === "ENOENT" || error.code === "ECONNREFUSED")
|
||||
) {
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
socket.destroy();
|
||||
resolve(
|
||||
sendDesktopAppActivationRequest({
|
||||
address: input.fallbackAddress,
|
||||
request: input.request,
|
||||
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
finish({ type: "failure", error });
|
||||
});
|
||||
socket.once("end", () => {
|
||||
finish({ type: "failure", error: new Error("The desktop app closed the connection.") });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const appEnvironment = Config.all({
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),
|
||||
sshTty: Config.string("SSH_TTY").pipe(Config.option),
|
||||
});
|
||||
|
||||
const runAppCommand = Effect.fn("cli.app")(function* (flags: {
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly workspaceRoot: Option.Option<string>;
|
||||
}) {
|
||||
const environment = yield* appEnvironment;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
if (Option.isSome(environment.sshConnection) || Option.isSome(environment.sshTty)) {
|
||||
return yield* new DesktopAppSshUnsupportedError({});
|
||||
}
|
||||
if (!isDesktopPlatform(hostPlatform)) {
|
||||
return yield* new DesktopAppPlatformUnsupportedError({ platform: hostPlatform });
|
||||
}
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const configuredBaseDir = Option.getOrUndefined(flags.baseDir) ?? environment.t3Home;
|
||||
const baseDir = yield* resolveBaseDir(configuredBaseDir);
|
||||
const allowDevFallback = Option.isNone(flags.baseDir) && !environment.t3Home?.trim();
|
||||
const rawWorkspaceRoot =
|
||||
Option.getOrUndefined(flags.workspaceRoot) ?? (yield* HostProcessWorkingDirectory);
|
||||
const workspaceRoot = path.resolve(yield* expandHomePath(rawWorkspaceRoot));
|
||||
const userId = yield* HostProcessUserId;
|
||||
const resolveAddress = (stateSubdirectory: "userdata" | "dev") =>
|
||||
resolveDesktopAppControlAddress({
|
||||
stateDir: path.join(baseDir, stateSubdirectory),
|
||||
platform: hostPlatform,
|
||||
tempDir: NodeOS.tmpdir(),
|
||||
userId,
|
||||
joinPath: path.join,
|
||||
}).address;
|
||||
const request: DesktopAppActivationRequest = {
|
||||
version: DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
|
||||
requestId: NodeCrypto.randomUUID(),
|
||||
type: "open-workspace",
|
||||
workspaceRoot,
|
||||
platform: hostPlatform,
|
||||
};
|
||||
const address = resolveAddress("userdata");
|
||||
const fallbackAddress = allowDevFallback ? resolveAddress("dev") : undefined;
|
||||
|
||||
const response = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
sendDesktopAppActivationRequest({
|
||||
address,
|
||||
...(fallbackAddress === undefined ? {} : { fallbackAddress }),
|
||||
request,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new DesktopAppUnreachableError({
|
||||
candidateAddresses: fallbackAddress === undefined ? [address] : [address, fallbackAddress],
|
||||
requestId: request.requestId,
|
||||
workspaceRoot,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
return yield* new DesktopAppRequestFailedError({
|
||||
code: response.code,
|
||||
requestId: response.requestId,
|
||||
workspaceRoot,
|
||||
cause: response,
|
||||
});
|
||||
}
|
||||
|
||||
yield* Console.log(`Opened ${workspaceRoot} in T3 Code.`);
|
||||
});
|
||||
|
||||
export const appCommand = Command.make("app", {
|
||||
baseDir: baseDirFlag,
|
||||
workspaceRoot: Argument.string("path").pipe(
|
||||
Argument.withDescription("Project directory. Default: current directory."),
|
||||
Argument.optional,
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Open a project in the running T3 Code desktop app."),
|
||||
Command.withHandler(runAppCommand),
|
||||
);
|
||||
@@ -0,0 +1,105 @@
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import type { DesktopAppActivationRequest } from "@t3tools/contracts";
|
||||
import { useEffect, useEffectEvent, useRef } from "react";
|
||||
|
||||
import { handleDesktopAppActivationRequest } from "../../desktopAppActivation";
|
||||
import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
|
||||
import { findProjectByPath, inferProjectTitleFromPath } from "../../lib/projectPaths";
|
||||
import { newProjectId } from "../../lib/utils";
|
||||
import { resolveDefaultProviderModelSelection } from "../../providerInstances";
|
||||
import { readProjects, waitForProject } from "../../state/entities";
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { projectEnvironment } from "../../state/projects";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { environmentShell } from "../../state/shell";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
export function DesktopAppActivationCoordinator() {
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
|
||||
const openThread = useNewThreadHandler();
|
||||
const queueRef = useRef(Promise.resolve());
|
||||
const activation = window.desktopBridge?.appActivation;
|
||||
const shell = useEnvironmentQuery(
|
||||
primaryEnvironment === null
|
||||
? null
|
||||
: environmentShell.stateAtom(primaryEnvironment.environmentId),
|
||||
);
|
||||
const ready =
|
||||
activation !== undefined &&
|
||||
primaryEnvironment?.connection.phase === "connected" &&
|
||||
primaryEnvironment.serverConfig !== null &&
|
||||
shell.data?.snapshot._tag === "Some";
|
||||
|
||||
const processRequest = useEffectEvent(async (request: DesktopAppActivationRequest) =>
|
||||
handleDesktopAppActivationRequest(request, {
|
||||
getTarget: () => {
|
||||
if (
|
||||
primaryEnvironment?.connection.phase !== "connected" ||
|
||||
primaryEnvironment.serverConfig === null
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
environmentId: primaryEnvironment.environmentId,
|
||||
platform: primaryEnvironment.serverConfig.environment.platform.os,
|
||||
};
|
||||
},
|
||||
findProject: (environmentId, workspaceRoot) =>
|
||||
findProjectByPath(
|
||||
readProjects().filter((project) => project.environmentId === environmentId),
|
||||
workspaceRoot,
|
||||
) ?? null,
|
||||
createProject: async (environmentId, workspaceRoot) => {
|
||||
const projectId = newProjectId();
|
||||
const providers =
|
||||
primaryEnvironment?.environmentId === environmentId
|
||||
? (primaryEnvironment.serverConfig?.providers ?? [])
|
||||
: [];
|
||||
const result = await createProject({
|
||||
environmentId,
|
||||
input: {
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(workspaceRoot),
|
||||
workspaceRoot,
|
||||
createWorkspaceRootIfMissing: false,
|
||||
defaultModelSelection: resolveDefaultProviderModelSelection(providers, null),
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
throw error instanceof Error ? error : new Error("T3 Code could not add the project.");
|
||||
}
|
||||
return projectId;
|
||||
},
|
||||
waitForProject: async (projectRef) => {
|
||||
await waitForProject(projectRef);
|
||||
},
|
||||
openThread: (projectRef) => openThread(projectRef),
|
||||
}),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || activation === undefined) return;
|
||||
|
||||
let subscribed = true;
|
||||
const unsubscribe = activation.onRequest((request) => {
|
||||
queueRef.current = queueRef.current.then(async () => {
|
||||
const response = await processRequest(request);
|
||||
await activation.complete(response);
|
||||
});
|
||||
queueRef.current = queueRef.current.catch(() => undefined);
|
||||
});
|
||||
// Skip readiness if React runs cleanup before this subscription can receive requests.
|
||||
queueMicrotask(() => {
|
||||
if (subscribed) void activation.setReady(true).catch(() => undefined);
|
||||
});
|
||||
return () => {
|
||||
subscribed = false;
|
||||
void activation.setReady(false).catch(() => undefined);
|
||||
unsubscribe();
|
||||
};
|
||||
}, [activation, ready]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
handleDesktopAppActivationRequest,
|
||||
type DesktopAppActivationDependencies,
|
||||
} from "./desktopAppActivation";
|
||||
|
||||
const environmentId = EnvironmentId.make("primary");
|
||||
const existingProjectId = ProjectId.make("project-existing");
|
||||
const createdProjectId = ProjectId.make("project-created");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const request = {
|
||||
version: 1,
|
||||
requestId: "request-1",
|
||||
type: "open-workspace",
|
||||
workspaceRoot: "/workspace/project",
|
||||
platform: "linux",
|
||||
} as const;
|
||||
|
||||
function dependencies(
|
||||
overrides: Partial<DesktopAppActivationDependencies> = {},
|
||||
): DesktopAppActivationDependencies {
|
||||
return {
|
||||
getTarget: () => ({ environmentId, platform: "linux" }),
|
||||
findProject: () => ({
|
||||
id: existingProjectId,
|
||||
environmentId,
|
||||
workspaceRoot: request.workspaceRoot,
|
||||
}),
|
||||
createProject: vi.fn(async () => createdProjectId),
|
||||
waitForProject: vi.fn(async () => undefined),
|
||||
openThread: vi.fn(async () => ({ threadId })),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("desktop app activation", () => {
|
||||
it("reuses an existing project and opens a new thread", async () => {
|
||||
const deps = dependencies();
|
||||
|
||||
const response = await handleDesktopAppActivationRequest(request, deps);
|
||||
|
||||
expect(deps.createProject).not.toHaveBeenCalled();
|
||||
expect(deps.openThread).toHaveBeenCalledWith({ environmentId, projectId: existingProjectId });
|
||||
expect(response).toEqual({
|
||||
version: 1,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
projectId: existingProjectId,
|
||||
threadId,
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for a created project before it opens the thread", async () => {
|
||||
const order: string[] = [];
|
||||
const deps = dependencies({
|
||||
findProject: () => null,
|
||||
createProject: vi.fn(async () => {
|
||||
order.push("create");
|
||||
return createdProjectId;
|
||||
}),
|
||||
waitForProject: vi.fn(async () => {
|
||||
order.push("project-event");
|
||||
}),
|
||||
openThread: vi.fn(async () => {
|
||||
order.push("open-thread");
|
||||
return { threadId };
|
||||
}),
|
||||
});
|
||||
|
||||
const response = await handleDesktopAppActivationRequest(request, deps);
|
||||
|
||||
expect(order).toEqual(["create", "project-event", "open-thread"]);
|
||||
expect(response).toMatchObject({ ok: true, projectId: createdProjectId });
|
||||
});
|
||||
|
||||
it("rejects a Windows path when the primary environment is WSL", async () => {
|
||||
const response = await handleDesktopAppActivationRequest(
|
||||
{ ...request, platform: "win32" },
|
||||
dependencies({ getTarget: () => ({ environmentId, platform: "linux" }) }),
|
||||
);
|
||||
|
||||
expect(response).toMatchObject({ ok: false, code: "platform-mismatch" });
|
||||
});
|
||||
|
||||
it("returns a project error without opening a thread", async () => {
|
||||
const openThread = vi.fn(async () => ({ threadId }));
|
||||
const response = await handleDesktopAppActivationRequest(
|
||||
request,
|
||||
dependencies({
|
||||
findProject: () => null,
|
||||
createProject: vi.fn(async () => {
|
||||
throw new Error("Project path is not available.");
|
||||
}),
|
||||
openThread,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
code: "project-create-failed",
|
||||
message: "Project path is not available.",
|
||||
});
|
||||
expect(openThread).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import type {
|
||||
DesktopAppActivationFailure,
|
||||
DesktopAppActivationRequest,
|
||||
DesktopAppActivationResponse,
|
||||
EnvironmentId,
|
||||
ExecutionEnvironmentPlatformOs,
|
||||
ProjectId,
|
||||
ScopedProjectRef,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface DesktopAppActivationProject {
|
||||
readonly id: ProjectId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly workspaceRoot: string;
|
||||
}
|
||||
|
||||
export interface DesktopAppActivationTarget {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly platform: ExecutionEnvironmentPlatformOs;
|
||||
}
|
||||
|
||||
export interface DesktopAppActivationDependencies {
|
||||
readonly getTarget: () => DesktopAppActivationTarget | null;
|
||||
readonly findProject: (
|
||||
environmentId: EnvironmentId,
|
||||
workspaceRoot: string,
|
||||
) => DesktopAppActivationProject | null;
|
||||
readonly createProject: (
|
||||
environmentId: EnvironmentId,
|
||||
workspaceRoot: string,
|
||||
) => Promise<ProjectId>;
|
||||
readonly waitForProject: (projectRef: ScopedProjectRef) => Promise<void>;
|
||||
readonly openThread: (
|
||||
projectRef: ScopedProjectRef,
|
||||
) => Promise<{ readonly threadId: ThreadId } | null>;
|
||||
}
|
||||
|
||||
function failure(
|
||||
requestId: string,
|
||||
code: DesktopAppActivationFailure["code"],
|
||||
message: string,
|
||||
): DesktopAppActivationFailure {
|
||||
return { version: 1, requestId, ok: false, code, message };
|
||||
}
|
||||
|
||||
export function desktopPlatformToEnvironmentOs(
|
||||
platform: DesktopAppActivationRequest["platform"],
|
||||
): ExecutionEnvironmentPlatformOs {
|
||||
return platform === "win32" ? "windows" : platform;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof Error && error.message.trim().length > 0 ? error.message : fallback;
|
||||
}
|
||||
|
||||
export async function handleDesktopAppActivationRequest(
|
||||
request: DesktopAppActivationRequest,
|
||||
dependencies: DesktopAppActivationDependencies,
|
||||
): Promise<DesktopAppActivationResponse> {
|
||||
const target = dependencies.getTarget();
|
||||
if (target === null) {
|
||||
return failure(
|
||||
request.requestId,
|
||||
"environment-unavailable",
|
||||
"The desktop app's primary local environment is not connected.",
|
||||
);
|
||||
}
|
||||
|
||||
const requestPlatform = desktopPlatformToEnvironmentOs(request.platform);
|
||||
if (requestPlatform !== target.platform) {
|
||||
return failure(
|
||||
request.requestId,
|
||||
"platform-mismatch",
|
||||
`The command path is for ${requestPlatform}, but the desktop app's primary environment uses ${target.platform}. Cross-platform path mapping is not supported.`,
|
||||
);
|
||||
}
|
||||
|
||||
let projectId = dependencies.findProject(target.environmentId, request.workspaceRoot)?.id ?? null;
|
||||
if (projectId === null) {
|
||||
try {
|
||||
projectId = await dependencies.createProject(target.environmentId, request.workspaceRoot);
|
||||
await dependencies.waitForProject({ environmentId: target.environmentId, projectId });
|
||||
} catch (error) {
|
||||
return failure(
|
||||
request.requestId,
|
||||
"project-create-failed",
|
||||
errorMessage(error, "T3 Code could not add the project."),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const opened = await dependencies.openThread({
|
||||
environmentId: target.environmentId,
|
||||
projectId,
|
||||
});
|
||||
if (opened === null) {
|
||||
return failure(
|
||||
request.requestId,
|
||||
"thread-open-failed",
|
||||
"T3 Code could not open a new thread for the project.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
projectId,
|
||||
threadId: opened.threadId,
|
||||
};
|
||||
} catch (error) {
|
||||
return failure(
|
||||
request.requestId,
|
||||
"thread-open-failed",
|
||||
errorMessage(error, "T3 Code could not open a new thread for the project."),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode";
|
||||
import { readThreadShell, useProjects, useThread } from "../state/entities";
|
||||
import { readProjects, readThreadShell, useProjects, useThread } from "../state/entities";
|
||||
import {
|
||||
hasExplicitComposerModelSelection,
|
||||
resolveNewDraftStartFromOrigin,
|
||||
@@ -55,7 +55,6 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef
|
||||
}
|
||||
|
||||
export function useNewThreadHandler() {
|
||||
const projects = useProjects();
|
||||
// New-thread defaults are a user preference, and the settings UI only ever
|
||||
// edits the primary environment's settings.json. Reading the target
|
||||
// environment's own settings here would silently reset remote projects to
|
||||
@@ -83,6 +82,7 @@ export function useNewThreadHandler() {
|
||||
// prepared checkout, a task to write — addresses that one rather than looking the project
|
||||
// up again and finding whichever draft it happens to hold.
|
||||
): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {
|
||||
const projects = readProjects();
|
||||
const {
|
||||
getComposerDraft,
|
||||
getDraftSessionByLogicalProjectKey,
|
||||
@@ -421,7 +421,7 @@ export function useNewThreadHandler() {
|
||||
return { draftId, threadId };
|
||||
})();
|
||||
},
|
||||
[getCurrentRouteTarget, primaryServerSettings, projectGroupingSettings, projects, router],
|
||||
[getCurrentRouteTarget, primaryServerSettings, projectGroupingSettings, router],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
|
||||
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
|
||||
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
|
||||
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
|
||||
import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
|
||||
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
|
||||
import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
|
||||
import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
|
||||
@@ -139,6 +140,7 @@ function RootRouteView() {
|
||||
<GlassAppearanceSync />
|
||||
<FontAppearanceSync />
|
||||
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
|
||||
<RelayClientInstallDialog />
|
||||
<ConnectOnboardingDialog />
|
||||
<SshPasswordPromptDialog />
|
||||
|
||||
@@ -218,6 +218,35 @@ export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
|
||||
return appAtomRegistry.get(environmentProjects.projectAtom(ref));
|
||||
}
|
||||
|
||||
export function readProjects(): ReadonlyArray<EnvironmentProject> {
|
||||
return appAtomRegistry.get(environmentProjects.projectsAtom);
|
||||
}
|
||||
|
||||
/** Resolves when the project event reaches the live client store. */
|
||||
export function waitForProject(
|
||||
ref: ScopedProjectRef,
|
||||
timeoutMs = 10_000,
|
||||
): Promise<EnvironmentProject> {
|
||||
const current = readProject(ref);
|
||||
if (current !== null) return Promise.resolve(current);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
const timeout = setTimeout(() => {
|
||||
unsubscribe?.();
|
||||
reject(new Error("The project did not appear in the desktop app."));
|
||||
}, timeoutMs);
|
||||
const finish = (project: EnvironmentProject | null) => {
|
||||
if (project === null) return;
|
||||
clearTimeout(timeout);
|
||||
unsubscribe?.();
|
||||
resolve(project);
|
||||
};
|
||||
unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
|
||||
finish(readProject(ref));
|
||||
});
|
||||
}
|
||||
|
||||
export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
|
||||
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
|
||||
}
|
||||
|
||||
@@ -17,6 +17,26 @@ npx t3@latest
|
||||
This starts the T3 Code server on your machine and opens the local web app. Use
|
||||
`npx t3@latest --help` for the full CLI reference.
|
||||
|
||||
## Open a project in the desktop app
|
||||
|
||||
When the T3 Code desktop app is running on the same machine, open the current directory with:
|
||||
|
||||
```bash
|
||||
npx t3 app
|
||||
```
|
||||
|
||||
Pass a path to open another directory:
|
||||
|
||||
```bash
|
||||
npx t3 app ../my-project
|
||||
```
|
||||
|
||||
The command adds the directory as a project when needed, focuses the desktop app, and opens a new
|
||||
thread. It does not launch the desktop app, open a browser, or start a T3 Code server. A background
|
||||
server does not count as the desktop app. The command also rejects SSH sessions because a remote
|
||||
shell cannot focus a local desktop window. The CLI package and the running desktop app must both
|
||||
include `t3 app` support.
|
||||
|
||||
## Desktop App
|
||||
|
||||
Download the latest release from
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
|
||||
export const DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION = 1 as const;
|
||||
|
||||
export const DesktopAppActivationPlatform = Schema.Literals(["darwin", "linux", "win32"]);
|
||||
export type DesktopAppActivationPlatform = typeof DesktopAppActivationPlatform.Type;
|
||||
|
||||
export const DesktopAppActivationRequest = Schema.Struct({
|
||||
version: Schema.Literal(DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION),
|
||||
requestId: TrimmedNonEmptyString,
|
||||
type: Schema.Literal("open-workspace"),
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
platform: DesktopAppActivationPlatform,
|
||||
});
|
||||
export type DesktopAppActivationRequest = typeof DesktopAppActivationRequest.Type;
|
||||
|
||||
export const DesktopAppActivationErrorCode = Schema.Literals([
|
||||
"invalid-request",
|
||||
"renderer-unavailable",
|
||||
"environment-unavailable",
|
||||
"platform-mismatch",
|
||||
"project-create-failed",
|
||||
"thread-open-failed",
|
||||
"request-timeout",
|
||||
"internal-error",
|
||||
]);
|
||||
export type DesktopAppActivationErrorCode = typeof DesktopAppActivationErrorCode.Type;
|
||||
|
||||
export const DesktopAppActivationSuccess = Schema.Struct({
|
||||
version: Schema.Literal(DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION),
|
||||
requestId: TrimmedNonEmptyString,
|
||||
ok: Schema.Literal(true),
|
||||
projectId: ProjectId,
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type DesktopAppActivationSuccess = typeof DesktopAppActivationSuccess.Type;
|
||||
|
||||
export const DesktopAppActivationFailure = Schema.Struct({
|
||||
version: Schema.Literal(DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION),
|
||||
requestId: TrimmedNonEmptyString,
|
||||
ok: Schema.Literal(false),
|
||||
code: DesktopAppActivationErrorCode,
|
||||
message: TrimmedNonEmptyString,
|
||||
});
|
||||
export type DesktopAppActivationFailure = typeof DesktopAppActivationFailure.Type;
|
||||
|
||||
export const DesktopAppActivationResponse = Schema.Union([
|
||||
DesktopAppActivationSuccess,
|
||||
DesktopAppActivationFailure,
|
||||
]);
|
||||
export type DesktopAppActivationResponse = typeof DesktopAppActivationResponse.Type;
|
||||
@@ -5,6 +5,7 @@ export * from "./environment.ts";
|
||||
export * from "./environmentHttp.ts";
|
||||
export * from "./relayClient.ts";
|
||||
export * from "./desktopBootstrap.ts";
|
||||
export * from "./desktopAppActivation.ts";
|
||||
export * from "./remoteAccess.ts";
|
||||
export * from "./ipc.ts";
|
||||
export * from "./terminal.ts";
|
||||
|
||||
@@ -101,6 +101,10 @@ import type {
|
||||
SourceControlRepositoryInfo,
|
||||
SourceControlRepositoryLookupInput,
|
||||
} from "./sourceControl.ts";
|
||||
import type {
|
||||
DesktopAppActivationRequest,
|
||||
DesktopAppActivationResponse,
|
||||
} from "./desktopAppActivation.ts";
|
||||
|
||||
export interface ContextMenuItem<T extends string = string> {
|
||||
id: T;
|
||||
@@ -1156,6 +1160,12 @@ export interface DesktopBridge {
|
||||
downloadUpdate: () => Promise<DesktopUpdateActionResult>;
|
||||
installUpdate: () => Promise<DesktopUpdateActionResult>;
|
||||
onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
|
||||
/** Present when the desktop shell accepts `t3 app` activation requests. */
|
||||
appActivation?: {
|
||||
setReady: (ready: boolean) => Promise<void>;
|
||||
complete: (response: DesktopAppActivationResponse) => Promise<void>;
|
||||
onRequest: (listener: (request: DesktopAppActivationRequest) => void) => () => void;
|
||||
};
|
||||
/**
|
||||
* Desktop-only preview surface. Present iff the renderer is hosted by the
|
||||
* Electron desktop build; web builds have `preview === undefined`.
|
||||
|
||||
@@ -235,6 +235,10 @@
|
||||
"types": "./src/usageFormat.ts",
|
||||
"import": "./src/usageFormat.ts"
|
||||
},
|
||||
"./desktopAppControl": {
|
||||
"types": "./src/desktopAppControl.ts",
|
||||
"import": "./src/desktopAppControl.ts"
|
||||
},
|
||||
"./claudeCompaction": {
|
||||
"types": "./src/claudeCompaction.ts",
|
||||
"import": "./src/claudeCompaction.ts"
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveDesktopAppControlAddress } from "./desktopAppControl.ts";
|
||||
|
||||
describe("resolveDesktopAppControlAddress", () => {
|
||||
it("keeps Unix socket paths short and separates desktop state directories", () => {
|
||||
const first = resolveDesktopAppControlAddress({
|
||||
stateDir: `/home/user/${"long/".repeat(40)}userdata`,
|
||||
platform: "linux",
|
||||
tempDir: "/tmp",
|
||||
userId: 1000,
|
||||
joinPath: (...segments) => segments.join("/"),
|
||||
});
|
||||
const second = resolveDesktopAppControlAddress({
|
||||
stateDir: "/home/user/.t3/other/userdata",
|
||||
platform: "linux",
|
||||
tempDir: "/tmp",
|
||||
userId: 1000,
|
||||
joinPath: (...segments) => segments.join("/"),
|
||||
});
|
||||
|
||||
expect(first.directory).toBe("/tmp/t3code-1000");
|
||||
expect(first.address.length).toBeLessThan(108);
|
||||
expect(first.address).not.toBe(second.address);
|
||||
});
|
||||
|
||||
it("uses a Windows named pipe", () => {
|
||||
const result = resolveDesktopAppControlAddress({
|
||||
stateDir: "C:\\Users\\user\\.t3\\userdata",
|
||||
platform: "win32",
|
||||
tempDir: "C:\\Temp",
|
||||
userId: undefined,
|
||||
joinPath: (...segments) => segments.join("\\"),
|
||||
});
|
||||
|
||||
expect(result.directory).toBeNull();
|
||||
expect(result.address).toMatch(/^\\\\\.\\pipe\\t3code-app-[a-f0-9]{24}$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
|
||||
export interface DesktopAppControlAddress {
|
||||
readonly address: string;
|
||||
readonly directory: string | null;
|
||||
}
|
||||
|
||||
function shortHash(value: string): string {
|
||||
return Array.from(sha256(new TextEncoder().encode(value)).slice(0, 12), (byte) =>
|
||||
byte.toString(16).padStart(2, "0"),
|
||||
).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the local-only socket address shared by the desktop shell and CLI.
|
||||
* The state directory is hashed so custom T3 homes cannot exceed Unix socket
|
||||
* path limits.
|
||||
*/
|
||||
export function resolveDesktopAppControlAddress(input: {
|
||||
readonly stateDir: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly tempDir: string;
|
||||
readonly userId: number | undefined;
|
||||
readonly joinPath: (...segments: readonly string[]) => string;
|
||||
}): DesktopAppControlAddress {
|
||||
const stateHash = shortHash(input.stateDir);
|
||||
if (input.platform === "win32") {
|
||||
return {
|
||||
address: `\\\\.\\pipe\\t3code-app-${stateHash}`,
|
||||
directory: null,
|
||||
};
|
||||
}
|
||||
|
||||
const userKey =
|
||||
input.userId === undefined ? shortHash(input.stateDir).slice(0, 12) : input.userId;
|
||||
const directory = input.joinPath(input.tempDir, `t3code-${userKey}`);
|
||||
return {
|
||||
address: input.joinPath(directory, `${stateHash}.sock`),
|
||||
directory,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user