Compare commits

..
63 changed files with 2841 additions and 579 deletions

No files matched your search

@@ -14,6 +14,7 @@ import {
setTailscaleServeEnabled,
} from "./methods/serverExposure.ts";
import {
acquireSshPortForward,
bootstrapSshBearerSession,
disconnectSshEnvironment,
discoverSshHosts,
@@ -21,6 +22,7 @@ import {
fetchSshEnvironmentDescriptor,
fetchSshSessionState,
issueSshWebSocketTicket,
releaseSshPortForward,
resolveSshPasswordPrompt,
} from "./methods/sshEnvironment.ts";
import {
@@ -35,6 +37,7 @@ import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
pickFolder,
setTheme,
@@ -48,6 +51,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
@@ -60,6 +64,8 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
yield* ipc.handle(disconnectSshEnvironment);
yield* ipc.handle(acquireSshPortForward);
yield* ipc.handle(releaseSshPortForward);
yield* ipc.handle(fetchSshEnvironmentDescriptor);
yield* ipc.handle(bootstrapSshBearerSession);
yield* ipc.handle(fetchSshSessionState);
+4
View File
@@ -4,6 +4,8 @@ export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
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";
@@ -22,6 +24,8 @@ export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalo
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
export const ACQUIRE_SSH_PORT_FORWARD_CHANNEL = "desktop:acquire-ssh-port-forward";
export const RELEASE_SSH_PORT_FORWARD_CHANNEL = "desktop:release-ssh-port-forward";
export const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
export const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
export const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
@@ -8,9 +8,12 @@ import * as Option from "effect/Option";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import {
acquireSshPortForward,
DesktopSshEnvironmentRequestError,
fetchSshEnvironmentDescriptor,
releaseSshPortForward,
} from "./sshEnvironment.ts";
import { DesktopSshEnvironment } from "../../ssh/DesktopSshEnvironment.ts";
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
return HttpClientResponse.fromWeb(
@@ -34,6 +37,41 @@ function makeHttpClientLayer(
}
describe("SSH environment IPC", () => {
it.effect("acquires and releases SSH port-forward leases", () => {
const calls: unknown[] = [];
const target = {
alias: "devbox",
hostname: "devbox.example.test",
username: "developer",
port: 22,
} as const;
const layer = Layer.succeed(
DesktopSshEnvironment,
DesktopSshEnvironment.of({
discoverHosts: () => Effect.succeed([]),
ensureEnvironment: () => Effect.die("unused"),
disconnectEnvironment: () => Effect.die("unused"),
acquirePortForward: (receivedTarget, remotePort) =>
Effect.sync(() => {
calls.push([receivedTarget, remotePort]);
return { leaseId: "lease-1", localPort: 42_173, remotePort };
}),
releasePortForward: (leaseId) => Effect.sync(() => void calls.push(leaseId)),
}),
);
return Effect.gen(function* () {
const acquired = yield* acquireSshPortForward.handler({ target, remotePort: 5173 });
assert.deepEqual(acquired, {
leaseId: "lease-1",
localPort: 42_173,
remotePort: 5173,
});
yield* releaseSshPortForward.handler({ leaseId: "lease-1" });
assert.deepEqual(calls, [[target, 5173], "lease-1"]);
}).pipe(Effect.provide(layer));
});
it.effect("fetches and decodes the remote environment descriptor", () => {
const requestUrls: string[] = [];
const layer = makeHttpClientLayer((request) =>
@@ -15,6 +15,9 @@ import {
DesktopSshEnvironmentEnsureResultSchema,
DesktopSshEnvironmentTargetSchema,
DesktopSshHttpBaseUrlInputSchema,
DesktopSshPortForwardAcquireInputSchema,
DesktopSshPortForwardAcquireResultSchema,
DesktopSshPortForwardReleaseInputSchema,
DesktopSshPasswordPromptCancelledType,
DesktopSshPasswordPromptResolutionInputSchema,
ExecutionEnvironmentDescriptor,
@@ -149,6 +152,38 @@ export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
}),
});
export const acquireSshPortForward = DesktopIpc.makeIpcMethod({
channel: IpcChannels.ACQUIRE_SSH_PORT_FORWARD_CHANNEL,
payload: DesktopSshPortForwardAcquireInputSchema,
result: DesktopSshPortForwardAcquireResultSchema,
handler: Effect.fn("desktop.ipc.sshEnvironment.acquirePortForward")(function* ({
target,
remotePort,
}) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
return yield* sshEnvironment.acquirePortForward(target, remotePort).pipe(
Effect.catch((error) =>
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
? Effect.succeed({
type: DesktopSshPasswordPromptCancelledType,
message: error.message,
})
: Effect.fail(error),
),
);
}),
});
export const releaseSshPortForward = DesktopIpc.makeIpcMethod({
channel: IpcChannels.RELEASE_SSH_PORT_FORWARD_CHANNEL,
payload: DesktopSshPortForwardReleaseInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.sshEnvironment.releasePortForward")(function* ({ leaseId }) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
yield* sshEnvironment.releasePortForward(leaseId);
}),
});
export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
payload: DesktopSshHttpBaseUrlInputSchema,
+21 -1
View File
@@ -1,10 +1,14 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import { getLocalEnvironmentBootstraps } from "./window.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "wsl.exe",
@@ -126,3 +130,19 @@ describe("getLocalEnvironmentBootstraps", () => {
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
});
});
describe("getWindowFullscreenState", () => {
it.effect("reads the current native window state", () => {
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
return Effect.gen(function* () {
assert.isTrue(yield* getWindowFullscreenState.handler());
}).pipe(
Effect.provide(
Layer.mock(ElectronWindow.ElectronWindow)({
currentMainOrFirst: Effect.succeed(Option.some(window)),
}),
),
);
});
});
+10
View File
@@ -55,6 +55,16 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const window = yield* electronWindow.currentMainOrFirst;
return Option.isSome(window) && window.value.isFullScreen();
}),
});
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
+25 -3
View File
@@ -11,7 +11,7 @@ import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
function unwrapEnsureSshEnvironmentResult(result: unknown) {
function unwrapSshPasswordPromptResult<T>(result: unknown): T {
if (
typeof result === "object" &&
result !== null &&
@@ -24,7 +24,7 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) {
: "SSH authentication cancelled.";
throw new Error(message);
}
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
return result as T;
}
contextBridge.exposeInMainWorld("desktopBridge", {
@@ -53,7 +53,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
unwrapSshPasswordPromptResult<Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>>(
await ipcRenderer.invoke(IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL, {
target,
...(options === undefined ? {} : { options }),
@@ -61,6 +61,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
),
disconnectSshEnvironment: (target) =>
ipcRenderer.invoke(IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
acquireSshPortForward: async (target, remotePort) =>
unwrapSshPasswordPromptResult<Awaited<ReturnType<DesktopBridge["acquireSshPortForward"]>>>(
await ipcRenderer.invoke(IpcChannels.ACQUIRE_SSH_PORT_FORWARD_CHANNEL, {
target,
remotePort,
}),
),
releaseSshPortForward: (leaseId) =>
ipcRenderer.invoke(IpcChannels.RELEASE_SSH_PORT_FORWARD_CHANNEL, { leaseId }),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
ipcRenderer.invoke(IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, { httpBaseUrl }),
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
@@ -116,6 +125,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
};
},
getWindowFullscreenState: () =>
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
onWindowFullscreenStateChange: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
if (typeof fullscreen !== "boolean") return;
listener(fullscreen);
};
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
};
},
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) =>
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
@@ -61,6 +61,11 @@ export class DesktopSshEnvironment extends Context.Service<
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
readonly acquirePortForward: (
target: DesktopSshEnvironmentTarget,
remotePort: number,
) => Effect.Effect<SshTunnel.SshPortForwardLease, DesktopSshEnvironmentOperationError>;
readonly releasePortForward: (leaseId: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
@@ -152,6 +157,16 @@ export const make = Effect.gen(function* () {
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
),
acquirePortForward: (target, remotePort) =>
manager
.acquirePortForward(target, remotePort)
.pipe(
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.acquirePortForward"),
),
releasePortForward: (leaseId) =>
manager.releasePortForward(leaseId).pipe(Effect.withSpan("desktop.ssh.releasePortForward")),
});
});
+38 -2
View File
@@ -28,7 +28,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -46,6 +46,7 @@ const environmentInput = {
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
function makeFakeBrowserWindow() {
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
@@ -66,10 +67,13 @@ function makeFakeBrowserWindow() {
close: vi.fn(),
focus: vi.fn(),
isDestroyed: vi.fn(() => false),
isFullScreen: vi.fn(() => false),
isMinimized: vi.fn(() => false),
isVisible: vi.fn(() => true),
loadURL: vi.fn(() => Promise.resolve()),
on: vi.fn(),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
windowListeners.set(eventName, listener);
}),
once: vi.fn(),
restore: vi.fn(),
setBackgroundColor: vi.fn(),
@@ -88,6 +92,7 @@ function makeFakeBrowserWindow() {
send: webContents.send,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
windowListeners,
};
}
@@ -338,6 +343,37 @@ describe("DesktopWindow", () => {
}),
);
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
if (!enterFullscreen || !leaveFullscreen) {
return yield* Effect.die("fullscreen listeners were not registered");
}
enterFullscreen();
leaveFullscreen();
assert.deepEqual(fakeWindow.send.mock.calls, [
[WINDOW_FULLSCREEN_STATE_CHANNEL, true],
[WINDOW_FULLSCREEN_STATE_CHANNEL, false],
]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+10 -1
View File
@@ -15,7 +15,7 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
const TITLEBAR_HEIGHT = 40;
@@ -365,6 +365,15 @@ export const make = Effect.gen(function* () {
window.setTitle(environment.displayName);
});
if (environment.platform === "darwin") {
window.on("enter-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
});
window.on("leave-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
});
}
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
@@ -75,6 +75,7 @@ const backendConfigurationLayer = Layer.succeed(
);
const netLayer = Layer.succeed(NetService.NetService, {
hasListenerOnHost: () => Effect.succeed(false),
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(41773),
+7
View File
@@ -161,6 +161,13 @@ const capabilitiesLayer = Layer.effectContext(
}),
),
disconnect: () => Effect.void,
forwardPort: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
}),
),
);
@@ -0,0 +1,189 @@
import { describe, expect, it } from "vite-plus/test";
import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
const TYPESCRIPT_FILE: NativeReviewDiffFile = {
id: "file-1",
path: "example.ts",
language: "typescript",
additions: 0,
deletions: 0,
};
function makeLine(
input: Pick<NativeReviewDiffRow, "id" | "content" | "change" | "oldLineNumber" | "newLineNumber">,
): NativeReviewDiffRow {
return {
kind: "line",
fileId: TYPESCRIPT_FILE.id,
...input,
};
}
function makeHunk(id: string): NativeReviewDiffRow {
return {
kind: "hunk",
id,
fileId: TYPESCRIPT_FILE.id,
text: "@@",
};
}
function highlight(
rows: ReadonlyArray<NativeReviewDiffRow>,
alreadyHighlightedRowIds?: ReadonlySet<string>,
) {
return highlightNativeReviewDiffVisibleRows({
rows,
files: [TYPESCRIPT_FILE],
scheme: "dark",
engine: "javascript",
firstRowIndex: 0,
lastRowIndex: rows.length - 1,
overscanRows: 0,
maxRows: 100,
alreadyHighlightedRowIds,
});
}
describe("highlightNativeReviewDiffVisibleRows", () => {
it("does not carry grammar state across hunk boundaries", async () => {
const exportRow = makeLine({
id: "export-row",
content: "export async function run() {}",
change: "add",
oldLineNumber: null,
newLineNumber: 100,
});
const rows = [
makeHunk("hunk-1"),
makeLine({
id: "import-open",
content: "import {",
change: "context",
oldLineNumber: 1,
newLineNumber: 1,
}),
makeLine({
id: "import-entry",
content: " Model,",
change: "context",
oldLineNumber: 2,
newLineNumber: 2,
}),
makeHunk("hunk-2"),
exportRow,
];
const [highlighted, standalone] = await Promise.all([
highlight(rows),
highlight([makeHunk("standalone-hunk"), exportRow]),
]);
expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
});
it("keeps grammar state across inline comment rows", async () => {
const openingRow = makeLine({
id: "template-open",
content: "const message = `open",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
});
const closingRow = makeLine({
id: "template-close",
content: "closed`;",
change: "add",
oldLineNumber: null,
newLineNumber: 2,
});
const trailingRow = makeLine({
id: "trailing-row",
content: "export const answer = 42;",
change: "add",
oldLineNumber: null,
newLineNumber: 3,
});
const commentRow: NativeReviewDiffRow = {
kind: "comment",
id: "comment-1",
fileId: TYPESCRIPT_FILE.id,
commentText: "Review note",
};
const [withComment, contiguous] = await Promise.all([
highlight([openingRow, commentRow, closingRow, trailingRow]),
highlight([openingRow, closingRow, trailingRow]),
]);
expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
});
it("does not join unhighlighted rows across cached gaps", async () => {
const trailingRow = makeLine({
id: "trailing-row",
content: "export const answer = 42;",
change: "add",
oldLineNumber: null,
newLineNumber: 3,
});
const rows = [
makeLine({
id: "template-open",
content: "const message = `open",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
}),
makeLine({
id: "template-close",
content: "closed`;",
change: "add",
oldLineNumber: null,
newLineNumber: 2,
}),
trailingRow,
];
const [highlighted, standalone] = await Promise.all([
highlight(rows, new Set(["template-close"])),
highlight([trailingRow]),
]);
expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
standalone.tokensByRowId[trailingRow.id],
);
});
it("keeps deletion grammar state out of addition rows", async () => {
const additionRow = makeLine({
id: "addition-row",
content: "export const answer = 42;",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
});
const rows = [
makeLine({
id: "deletion-row",
content: "const removed = `open",
change: "delete",
oldLineNumber: 1,
newLineNumber: null,
}),
additionRow,
];
const [highlighted, standalone] = await Promise.all([
highlight(rows),
highlight([additionRow]),
]);
expect(highlighted.tokensByRowId[additionRow.id]).toEqual(
standalone.tokensByRowId[additionRow.id],
);
});
});
@@ -56,6 +56,11 @@ interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
readonly content: string;
}
interface IndexedNativeReviewDiffLineRow {
readonly row: NativeReviewDiffLineRow;
readonly rowIndex: number;
}
export interface NativeReviewDiffTokenChunk {
readonly chunkIndex: number;
readonly fileId: string;
@@ -308,6 +313,58 @@ function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDi
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
}
function hasConsecutiveLineNumbers(
previous: number | null | undefined,
next: number | null | undefined,
): boolean {
return typeof previous === "number" && typeof next === "number" && next === previous + 1;
}
function hasOnlyCommentRowsBetween(
rows: ReadonlyArray<NativeReviewDiffRow>,
previousRowIndex: number,
nextRowIndex: number,
): boolean {
for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
if (rows[rowIndex]?.kind !== "comment") {
return false;
}
}
return true;
}
function canShareGrammarContext(
previous: IndexedNativeReviewDiffLineRow,
next: IndexedNativeReviewDiffLineRow,
rows: ReadonlyArray<NativeReviewDiffRow>,
): boolean {
if (
next.row.fileId !== previous.row.fileId ||
!hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
) {
return false;
}
if (previous.row.change === "delete" || next.row.change === "delete") {
return (
previous.row.change !== "add" &&
next.row.change !== "add" &&
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
);
}
if (previous.row.change === "add" || next.row.change === "add") {
return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
}
return (
previous.row.change === "context" &&
next.row.change === "context" &&
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
);
}
function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
for (const row of rows) {
@@ -360,7 +417,7 @@ export async function highlightNativeReviewDiffVisibleRows(
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
const selectedRows: NativeReviewDiffLineRow[] = [];
const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
for (
let rowIndex = startIndex;
@@ -374,12 +431,12 @@ export async function highlightNativeReviewDiffVisibleRows(
!input.alreadyHighlightedRowIds?.has(row.id) &&
fileMap.has(row.fileId)
) {
selectedRows.push(row);
selectedRows.push({ row, rowIndex });
}
}
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
let segmentRows: NativeReviewDiffLineRow[] = [];
let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
let segmentFile: NativeReviewDiffFile | undefined;
const flushSegment = () => {
@@ -389,27 +446,34 @@ export async function highlightNativeReviewDiffVisibleRows(
return;
}
const code = segmentRows.map((row) => row.content).join("\n");
const code = segmentRows.map(({ row }) => row.content).join("\n");
const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
segmentRows.forEach((row, rowIndex) => {
segmentRows.forEach(({ row }, rowIndex) => {
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
});
segmentRows = [];
segmentFile = undefined;
};
for (const row of selectedRows) {
for (const selectedRow of selectedRows) {
const { row } = selectedRow;
const file = fileMap.get(row.fileId);
if (!file) {
continue;
}
if (segmentFile && segmentFile.id !== file.id) {
const previousRow = segmentRows.at(-1);
if (
segmentFile &&
(segmentFile.id !== file.id ||
(previousRow !== undefined &&
!canShareGrammarContext(previousRow, selectedRow, input.rows)))
) {
flushSegment();
}
segmentFile = file;
segmentRows.push(row);
segmentRows.push(selectedRow);
}
flushSegment();
+7 -11
View File
@@ -74,9 +74,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
});
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertSome(payload, {
mode: "desktop",
});
@@ -102,7 +100,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
try {
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
timeoutMs: 100,
}).pipe(Effect.provideService(HostProcessPlatform, "linux"));
assertSome(payload, {
mode: "desktop",
@@ -127,7 +125,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
openSyncInterceptor.errorCode = "EIO";
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
timeoutMs: 100,
}).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.flip);
assert.instanceOf(error, BootstrapInputStreamOpenError);
@@ -151,9 +149,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
const fd = NodeFS.openSync("/dev/null", "r");
NodeFS.closeSync(fd);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
});
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertNone(payload);
}),
);
@@ -168,7 +164,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
fstatSyncInterceptor.failFd = fd;
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
timeoutMs: 100,
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapFdStatError);
@@ -192,7 +188,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
timeoutMs: 100,
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapEnvelopeDecodeError);
@@ -231,7 +227,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
);
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
timeoutMs: 100,
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
+3 -4
View File
@@ -4,7 +4,6 @@ import * as NodeNet from "node:net";
import * as NodeReadline from "node:readline";
import type * as NodeStream from "node:stream";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
@@ -76,7 +75,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
schema: Schema.Codec<A, I>,
fd: number,
options?: {
timeout?: Duration.Input;
timeoutMs?: number;
},
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
const fdReady = yield* isFdReady(fd);
@@ -84,7 +83,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
const stream = yield* makeBootstrapInputStream(fd);
const timeout = options?.timeout ?? Duration.seconds(1);
const timeoutMs = options?.timeoutMs ?? 1000;
return yield* Effect.callback<
Option.Option<A>,
@@ -143,7 +142,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
input.once("close", handleClose);
return Effect.sync(cleanup);
}).pipe(Effect.timeoutOption(timeout), Effect.map(Option.flatten));
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
});
const isUnavailableBootstrapFdError = Predicate.compose(
@@ -6,6 +6,7 @@ import type {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
import * as Effect from "effect/Effect";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
@@ -71,6 +72,30 @@ export function requireProjectAbsent(input: {
);
}
export function requireActiveProjectWorkspaceRootAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly workspaceRoot: string;
readonly exceptProjectId?: ProjectId;
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);
const existingProject = input.readModel.projects.find(
(project) =>
project.deletedAt === null &&
normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&
project.id !== input.exceptProjectId,
);
if (existingProject === undefined) {
return Effect.void;
}
return Effect.fail(
invariantError(
input.command.type,
`Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,
),
);
}
export function requireThread(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
@@ -94,6 +94,117 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
}),
);
it.effect("rejects project.create for an active workspace root that already exists", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const readModel = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-existing"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-existing"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const failure = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "project.create",
commandId: CommandId.make("cmd-project-create-duplicate-root"),
projectId: asProjectId("project-duplicate-root"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project/",
createdAt: now,
},
readModel,
}),
);
expect(failure.message).toContain(
"Active project 'project-existing' already exists for workspace root '/tmp/project'.",
);
}),
);
it.effect("rejects project.meta.update when moving onto another active workspace root", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withFirstProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create-first"),
aggregateKind: "project",
aggregateId: asProjectId("project-first"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-first"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-first"),
metadata: {},
payload: {
projectId: asProjectId("project-first"),
title: "First",
workspaceRoot: "/tmp/project-first",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const readModel = yield* projectEvent(withFirstProject, {
sequence: 2,
eventId: asEventId("evt-project-create-second"),
aggregateKind: "project",
aggregateId: asProjectId("project-second"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-second"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-second"),
metadata: {},
payload: {
projectId: asProjectId("project-second"),
title: "Second",
workspaceRoot: "/tmp/project-second",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const failure = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-update-duplicate-root"),
projectId: asProjectId("project-second"),
workspaceRoot: "/tmp/project-first",
},
readModel,
}),
);
expect(failure.message).toContain(
"Active project 'project-first' already exists for workspace root '/tmp/project-first'.",
);
}),
);
it.effect("emits user message and turn-start-requested events for thread.turn.start", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
+15
View File
@@ -12,6 +12,7 @@ import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
listThreadsByProjectId,
requireActiveProjectWorkspaceRootAbsent,
requireProject,
requireProjectAbsent,
requireThread,
@@ -111,6 +112,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
return {
...(yield* withEventBase({
@@ -138,6 +145,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
if (command.workspaceRoot !== undefined) {
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -35,6 +35,7 @@ const makeProbeFailureLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"
Layer.mergeAll(
Layer.succeed(ProcessRunner.ProcessRunner, { run }),
Layer.succeed(Net.NetService, {
hasListenerOnHost: () => Effect.succeed(false),
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(40_000),
@@ -974,8 +974,13 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "request.opened" && !interrupted) {
if (event.type === "request.opened" && event.requestId && !interrupted) {
interrupted = true;
yield* adapter.respondToRequest(
threadId,
ApprovalRequestId.make(String(event.requestId)),
"cancel",
);
yield* adapter.interruptTurn(threadId);
return;
}
@@ -1030,15 +1035,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
entry.result.outcome !== null &&
"outcome" in entry.result.outcome &&
entry.result.outcome.outcome === "cancelled";
const cancelRequests = yield* waitForJsonLogMatch(
requestLogPath,
(entry) => entry.method === "session/cancel",
);
const approvalResponses = yield* waitForJsonLogMatch(
requestLogPath,
isCancelledApprovalResponse,
);
assert.isTrue(cancelRequests.some((entry) => entry.method === "session/cancel"));
assert.isTrue(approvalResponses.some(isCancelledApprovalResponse));
yield* adapter.stopSession(threadId);
@@ -1,10 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, describe, expect } from "@effect/vitest";
import { it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -74,24 +73,6 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
it.effect("limits previews while preserving the full file byte length", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const cwd = yield* makeTempDir;
const contents = "a".repeat(1024 * 1024 + 1);
yield* writeTextFile(cwd, "large.txt", contents);
const result = yield* workspaceFileSystem.readFile({
cwd,
relativePath: "large.txt",
});
assert.strictEqual(result.contents.length, 1024 * 1024);
assert.strictEqual(result.byteLength, contents.length);
assert.strictEqual(result.truncated, true);
}),
);
it.effect("rejects reads outside the workspace root", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -196,25 +177,16 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "missing.txt" })
.pipe(Effect.flip);
assert.instanceOf(error, WorkspaceFileSystem.WorkspaceFileSystemOperationError);
assert.deepEqual(
{
workspaceRoot: error.workspaceRoot,
relativePath: error.relativePath,
resolvedPath: error.resolvedPath,
operationPath: error.operationPath,
operation: error.operation,
},
{
workspaceRoot: cwd,
relativePath: "missing.txt",
resolvedPath,
operationPath: resolvedPath,
operation: "realpath-target",
},
);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.strictEqual(error.cause.reason._tag, "NotFound");
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFileSystemOperationError);
expect(error).toMatchObject({
workspaceRoot: cwd,
relativePath: "missing.txt",
resolvedPath,
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
}),
);
});
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -6,6 +7,8 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -137,32 +140,30 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
),
);
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
),
);
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -177,24 +178,24 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
),
);
const stat = yield* file.stat.pipe(
Effect.mapError(
(cause) =>
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -203,22 +204,20 @@ export const make = Effect.gen(function* () {
operation: "stat",
cause,
}),
),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const byteLength = Number(stat.size);
const bytesToRead = Math.min(byteLength, PROJECT_READ_FILE_MAX_BYTES);
const buffer = new Uint8Array(bytesToRead);
const bytesRead = yield* file.read(buffer).pipe(
Effect.mapError(
(cause) =>
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -227,24 +226,36 @@ export const make = Effect.gen(function* () {
operation: "read",
cause,
}),
),
);
const fileBytes = buffer.subarray(0, Number(bytesRead));
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated: byteLength > PROJECT_READ_FILE_MAX_BYTES,
};
}),
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
);
});
@@ -1,81 +0,0 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const readPreparedConnection = vi.fn();
vi.mock("~/state/session", () => ({ readPreparedConnection }));
describe("browser target resolver", () => {
beforeEach(() => readPreparedConnection.mockReset());
it("maps environment ports onto a private network host", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.1.25:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "environment-port",
port: 5173,
path: "/dashboard",
}),
).toEqual({
requestedUrl: "http://localhost:5173/dashboard",
resolvedUrl: "http://192.168.1.25:5173/dashboard",
resolutionKind: "direct-private-network",
environmentId: "environment-1",
});
});
it("refuses public relay hosts until the authenticated gateway exists", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://relay.example.com" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(() =>
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "environment-port",
port: 5173,
}),
).toThrow(/authenticated preview gateway/);
});
it("normalizes schemeless localhost server-picker values", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://localhost:3773" });
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "localhost:5173")).toBe(
"http://localhost:5173/",
);
expect(
resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "0.0.0.0:3000/app"),
).toBe("http://localhost:3000/app");
});
it("preserves localhost server-picker values when the prepared base is 127.0.0.1", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.1:3773" });
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(
resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "localhost:5173/app?x=1#top"),
).toBe("http://localhost:5173/app?x=1#top");
});
it("normalizes public URLs without treating them as environment ports", async () => {
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "example.com/app")).toBe(
"https://example.com/app",
);
});
it("supports private IPv6 environment hosts", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "environment-port",
port: 5173,
path: "/app?mode=test",
}).resolvedUrl,
).toBe("http://[::1]:5173/app?mode=test");
});
it("leaves malformed input for the normal navigation error path", async () => {
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), " ")).toBe(" ");
});
});
+105 -70
View File
@@ -1,92 +1,127 @@
import {
EnvironmentPortRouter,
type EnvironmentPortRouteRequest,
} from "@t3tools/client-runtime/preview";
import {
createRuntimeCommand,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type {
BrowserNavigationTarget,
EnvironmentId,
PreviewUrlResolution,
} from "@t3tools/contracts";
import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
import { connectionAtomRuntime } from "~/connection/runtime";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { readPreparedConnection } from "~/state/session";
const isPrivateNetworkHost = (host: string): boolean => {
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
if (normalized === "localhost" || normalized === "::1" || normalized.endsWith(".local")) {
return true;
}
if (normalized.endsWith(".ts.net")) return true;
const parts = normalized.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false;
return (
parts[0] === 10 ||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
parts[0] === 127 ||
(parts[0] === 169 && parts[1] === 254)
);
};
interface AcquiredRoute {
readonly resolution: PreviewUrlResolution;
readonly scope: Scope.Closeable;
}
const isLocalLoopbackHost = (host: string): boolean => {
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
};
export interface BrowserNavigationRoute {
readonly resolution: PreviewUrlResolution;
readonly commit: (tabId: string) => Promise<void>;
readonly release: () => Promise<void>;
}
export function resolveBrowserNavigationTarget(
const activeRoutes = new Map<string, Scope.Closeable>();
const closeRouteScope = (scope: Scope.Closeable): Promise<void> =>
Effect.runPromise(Scope.close(scope, Exit.void));
const acquireRouteCommand = createRuntimeCommand(connectionAtomRuntime, {
label: "preview route acquisition",
execute: ({ connection, target }: EnvironmentPortRouteRequest) =>
Effect.gen(function* () {
const scope = yield* Scope.make();
const resolution = yield* EnvironmentPortRouter.pipe(
Effect.flatMap((router) => router.acquire({ connection, target })),
Scope.provide(scope),
Effect.onError(() => Scope.close(scope, Exit.void)),
);
return { resolution, scope } satisfies AcquiredRoute;
}),
});
export async function acquireBrowserNavigationTarget(
environmentId: EnvironmentId,
target: BrowserNavigationTarget,
): PreviewUrlResolution {
if (target.kind === "url") {
return {
requestedUrl: target.url,
resolvedUrl: target.url,
resolutionKind: "direct",
environmentId,
};
}
): Promise<BrowserNavigationRoute> {
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
const environmentUrl = new URL(connection.httpBaseUrl);
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
throw new Error(
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
);
if (connection === null) {
throw new Error(`Environment ${environmentId} is not connected.`);
}
const protocol = target.protocol ?? "http";
const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
const requestedUrl = `${protocol}://localhost:${target.port}${path}`;
const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
const resolvedHost = normalizedEnvironmentHost.includes(":")
? `[${normalizedEnvironmentHost}]`
: normalizedEnvironmentHost;
const resolved = new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
const result = await acquireRouteCommand.run(appAtomRegistry, { connection, target });
if (result._tag === "Failure") {
throw squashAtomCommandFailure(result);
}
const acquired = result.value;
let ownership: "pending" | "committed" | "released" = "pending";
return {
requestedUrl,
resolvedUrl: resolved.toString(),
resolutionKind:
normalizedEnvironmentHost === "localhost" || normalizedEnvironmentHost === "127.0.0.1"
? "direct"
: "direct-private-network",
environmentId,
resolution: acquired.resolution,
commit: async (tabId) => {
if (ownership !== "pending") return;
ownership = "committed";
const previous = activeRoutes.get(tabId);
if (acquired.resolution.resolutionKind === "ssh-forward") {
activeRoutes.set(tabId, acquired.scope);
} else {
activeRoutes.delete(tabId);
await closeRouteScope(acquired.scope);
}
if (previous !== undefined && previous !== acquired.scope) {
await closeRouteScope(previous);
}
},
release: async () => {
if (ownership !== "pending") return;
ownership = "released";
await closeRouteScope(acquired.scope);
},
};
}
export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string {
export async function acquireDiscoveredServerRoute(
environmentId: EnvironmentId,
rawUrl: string,
): Promise<BrowserNavigationRoute> {
let url = rawUrl;
try {
const normalizedUrl = normalizePreviewUrl(rawUrl);
const parsed = new URL(normalizedUrl);
if (!isLoopbackHost(parsed.hostname)) return normalizedUrl;
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
const environmentUrl = new URL(connection.httpBaseUrl);
if (parsed.hostname !== "0.0.0.0" && isLocalLoopbackHost(environmentUrl.hostname)) {
return normalizedUrl;
}
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
return resolveBrowserNavigationTarget(environmentId, {
kind: "environment-port",
port,
protocol: parsed.protocol === "https:" ? "https" : "http",
path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
}).resolvedUrl;
url = normalizePreviewUrl(rawUrl);
} catch {
return rawUrl;
// Keep malformed input on the preview's normal navigation error path.
}
return acquireBrowserNavigationTarget(environmentId, { kind: "url", url });
}
export async function releaseBrowserNavigationRoute(tabId: string): Promise<void> {
const scope = activeRoutes.get(tabId);
if (scope === undefined) return;
activeRoutes.delete(tabId);
await closeRouteScope(scope);
}
export async function withBrowserNavigationRoute<A>(
route: BrowserNavigationRoute | undefined,
use: () => Promise<A>,
): Promise<A> {
try {
return await use();
} finally {
await route?.release();
}
}
export async function resetBrowserNavigationRoutesForTests(): Promise<void> {
const scopes = [...activeRoutes.values()];
activeRoutes.clear();
await Promise.all(scopes.map(closeRouteScope));
}
+26 -2
View File
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { useEffect, type CSSProperties, type ReactNode } from "react";
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
@@ -55,11 +55,35 @@ function SidebarControl() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
return isMacosDesktop && typeof getWindowFullscreenState === "function"
? getWindowFullscreenState()
: false;
});
const macosWindowControlsStyle =
isElectron && isMacPlatform(navigator.platform)
isMacosDesktop && !isWindowFullscreen
? ({ "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } as CSSProperties)
: undefined;
useEffect(() => {
if (!isMacosDesktop) return;
const bridge = window.desktopBridge;
if (!bridge) return;
const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
if (
typeof getWindowFullscreenState !== "function" ||
typeof onWindowFullscreenStateChange !== "function"
) {
return;
}
const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
setIsWindowFullscreen(getWindowFullscreenState());
return unsubscribe;
}, [isMacosDesktop]);
useEffect(() => {
const onMenuAction = window.desktopBridge?.onMenuAction;
if (typeof onMenuAction !== "function") {
+22 -5
View File
@@ -32,7 +32,7 @@ import React, {
useState,
type ReactNode,
} from "react";
import type { Components } from "react-markdown";
import type { Components, Options as ReactMarkdownOptions } from "react-markdown";
import ReactMarkdown from "react-markdown";
import { defaultUrlTransform } from "react-markdown";
import rehypeRaw from "rehype-raw";
@@ -60,6 +60,7 @@ import {
serializeTableElementToCsv,
serializeTableElementToMarkdown,
} from "../markdown-clipboard";
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
import {
normalizeMarkdownLinkDestination,
resolveMarkdownFileLinkMeta,
@@ -164,6 +165,24 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
},
} satisfies Parameters<typeof rehypeSanitize>[0];
const CHAT_MARKDOWN_REMARK_PLUGINS = [
remarkGfm,
remarkNormalizeListItemIndentation,
remarkPreserveCodeMeta,
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
remarkGfm,
remarkNormalizeListItemIndentation,
remarkBreaks,
remarkPreserveCodeMeta,
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
rehypeRaw,
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
function extractFenceLanguage(className: string | undefined): string {
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
const raw = match?.[1] ?? "text";
@@ -1545,11 +1564,9 @@ function ChatMarkdown({
>
<ReactMarkdown
remarkPlugins={
lineBreaks
? [remarkGfm, remarkBreaks, remarkPreserveCodeMeta]
: [remarkGfm, remarkPreserveCodeMeta]
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
}
rehypePlugins={[rehypeRaw, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA]]}
rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
components={markdownComponents}
urlTransform={markdownUrlTransform}
>
+2 -1
View File
@@ -3183,8 +3183,9 @@ export default function Sidebar() {
return buildPhysicalToLogicalProjectKeyMap({
projects: orderedProjects,
settings: projectGroupingSettings,
primaryEnvironmentId,
});
}, [orderedProjects, projectGroupingSettings]);
}, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]);
const projectPhysicalKeyByScopedRef = useMemo(
() =>
new Map(
@@ -1,5 +1,6 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
type EnvironmentConnectionPresentation,
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
@@ -10,7 +11,7 @@ import {
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { type ReactNode, useCallback, useEffect, useState } from "react";
import { environmentCatalog } from "~/connection/catalog";
import { cn } from "~/lib/utils";
@@ -22,6 +23,12 @@ import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRo
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
import { toastManager } from "../ui/toast";
import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
export interface SavedCloudEnvironmentConnection {
readonly environmentId: EnvironmentId;
readonly connection: EnvironmentConnectionPresentation;
}
export function RemoteEnvironmentRowsSkeleton() {
return (
@@ -40,19 +47,19 @@ export function RemoteEnvironmentRowsSkeleton() {
/**
* The user's T3 Connect environments from relay discovery, each with a
* Connect button. The primary environment is always excluded; already-saved
* environments are hidden unless `showSavedAsConnected` renders them as
* connected instead (used by onboarding, where the full device mesh should be
* visible).
* environments are hidden unless `showSavedEnvironments` renders them with
* their live connection state (used by onboarding, where the full device mesh
* should be visible).
*/
export function CloudEnvironmentConnectRows({
primaryEnvironmentId,
savedEnvironmentIds,
showSavedAsConnected = false,
savedEnvironments,
showSavedEnvironments = false,
empty = null,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
readonly showSavedAsConnected?: boolean;
readonly savedEnvironments: ReadonlyArray<SavedCloudEnvironmentConnection>;
readonly showSavedEnvironments?: boolean;
readonly empty?: ReactNode;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
@@ -77,7 +84,9 @@ export function CloudEnvironmentConnectRows({
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
const savedById = new Map(
savedEnvironments.map((environment) => [environment.environmentId, environment]),
);
useEffect(() => {
void refreshRelayEnvironments();
@@ -90,8 +99,8 @@ export function CloudEnvironmentConnectRows({
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Connect.`,
title: "Environment added",
description: `Connecting to ${environment.label} through T3 Connect.`,
});
return;
}
@@ -121,10 +130,10 @@ export function CloudEnvironmentConnectRows({
const visibleEnvironments = [...environmentsState.environments.values()].filter(
({ environment }) =>
environment.environmentId !== primaryEnvironmentId &&
(showSavedAsConnected || !savedIds.has(environment.environmentId)),
(showSavedEnvironments || !savedById.has(environment.environmentId)),
);
const standalone = showSavedAsConnected || savedEnvironmentIds.length === 0;
const standalone = showSavedEnvironments || savedEnvironments.length === 0;
if (
standalone &&
@@ -163,31 +172,57 @@ export function CloudEnvironmentConnectRows({
}
return visibleEnvironments.map(({ environment, availability, error }) => {
const alreadyConnected = savedIds.has(environment.environmentId);
const savedEnvironment = savedById.get(environment.environmentId);
const savedConnection = savedEnvironment
? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
: null;
const dotClassName = savedConnection
? savedConnection.tone === "connected"
? "bg-success"
: savedConnection.tone === "connecting"
? "bg-warning"
: savedConnection.tone === "error"
? "bg-destructive"
: "bg-muted-foreground/35"
: availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35";
const statusText = savedConnection
? savedConnection.statusText
: availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable");
return (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName={
availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35"
dotClassName={dotClassName}
pingClassName={
savedConnection?.tone === "connecting" ||
(savedConnection === null && availability === "checking")
? "bg-warning/60 duration-2000"
: null
}
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
tooltipText={
availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
savedConnection
? savedConnection.statusText
: availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
}
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
@@ -195,21 +230,19 @@ export function CloudEnvironmentConnectRows({
<p
className={cn(
"mt-1 truncate text-xs",
availability === "error" ? "text-destructive" : "text-muted-foreground",
savedConnection?.tone === "error" ||
(savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||
(savedConnection === null && availability === "error")
? "text-destructive"
: "text-muted-foreground",
)}
>
{availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
{statusText}
</p>
</div>
{alreadyConnected ? (
{savedConnection ? (
<Button size="sm" variant="outline" disabled>
Connected
{savedConnection.buttonLabel}
</Button>
) : (
<Button
@@ -1,7 +1,7 @@
import { useAuth } from "@clerk/react";
import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
import { CheckIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import {
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
@@ -411,20 +411,16 @@ function OnboardingToggleRow({
function DevicesStep() {
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const savedEnvironmentIds = useMemo(
() =>
environments
.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget")
.map((environment) => environment.environmentId),
[environments],
const savedEnvironments = environments.filter(
(environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
);
return (
<div className="overflow-hidden rounded-lg border">
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
savedEnvironmentIds={savedEnvironmentIds}
showSavedAsConnected
savedEnvironments={savedEnvironments}
showSavedEnvironments
empty={
<p className="px-4 py-6 text-center text-sm text-muted-foreground">
No other environments are published to your account yet. Publish one from another device
@@ -0,0 +1,55 @@
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import { describe, expect, it } from "vite-plus/test";
import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
function connection(
phase: EnvironmentConnectionPresentation["phase"],
error: string | null = null,
): EnvironmentConnectionPresentation {
return { phase, error, traceId: null };
}
describe("saved cloud environment connection presentation", () => {
it("only labels a live connection as connected", () => {
expect(presentSavedCloudEnvironmentConnection(connection("connected"))).toEqual({
buttonLabel: "Connected",
statusText: "Connected",
tone: "connected",
});
expect(presentSavedCloudEnvironmentConnection(connection("connecting"))).toEqual({
buttonLabel: "Connecting…",
statusText: "Connecting...",
tone: "connecting",
});
});
it("surfaces a failed attempt while the supervisor reconnects", () => {
expect(
presentSavedCloudEnvironmentConnection(
connection("reconnecting", "Relay environment endpoint is unavailable."),
),
).toEqual({
buttonLabel: "Reconnecting…",
statusText:
"Failed to connect. Reconnecting... Reason: Relay environment endpoint is unavailable.",
tone: "connecting",
});
});
it.each([
["error", "Connection failed", "Connection failed. Reason: Access denied.", "error"],
["offline", "Offline", "Offline", "idle"],
["available", "Not connected", "Available", "idle"],
] as const)(
"presents %s without claiming the environment is connected",
(phase, buttonLabel, statusText, tone) => {
expect(
presentSavedCloudEnvironmentConnection(
connection(phase, phase === "error" ? "Access denied." : null),
),
).toEqual({ buttonLabel, statusText, tone });
},
);
});
@@ -0,0 +1,58 @@
import {
connectionStatusText,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
export interface SavedCloudEnvironmentConnectionPresentation {
readonly buttonLabel: string;
readonly statusText: string;
readonly tone: "connected" | "connecting" | "error" | "idle";
}
/**
* Present the live supervisor state for an environment that is already in the
* connection catalog. Catalog membership only means the environment is saved;
* it does not mean the connection attempt succeeded.
*/
export function presentSavedCloudEnvironmentConnection(
connection: EnvironmentConnectionPresentation,
): SavedCloudEnvironmentConnectionPresentation {
switch (connection.phase) {
case "connected":
return {
buttonLabel: "Connected",
statusText: connectionStatusText(connection),
tone: "connected",
};
case "connecting":
return {
buttonLabel: "Connecting…",
statusText: connectionStatusText(connection),
tone: "connecting",
};
case "reconnecting":
return {
buttonLabel: "Reconnecting…",
statusText: connectionStatusText(connection),
tone: "connecting",
};
case "error":
return {
buttonLabel: "Connection failed",
statusText: connectionStatusText(connection),
tone: "error",
};
case "offline":
return {
buttonLabel: "Offline",
statusText: connectionStatusText(connection),
tone: "idle",
};
case "available":
return {
buttonLabel: "Not connected",
statusText: connectionStatusText(connection),
tone: "idle",
};
}
}
@@ -28,7 +28,10 @@ import {
updatePreviewServerSnapshot,
} from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
import {
acquireBrowserNavigationTarget,
withBrowserNavigationRoute,
} from "~/browser/browserTargetResolver";
import {
readActiveBrowserRecordingTabId,
startBrowserRecording,
@@ -343,79 +346,89 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
return await currentStatus(threadRef, tabId);
case "open": {
const input = request.input as PreviewAutomationOpenInput;
let activeTabId = resolvePreviewAutomationOpenTab(
state,
request.tabId,
input.reuseExistingTab ?? true,
);
let activeSnapshot = activeTabId
? (state.sessions[activeTabId] ?? state.snapshot ?? undefined)
const route = input.url
? await acquireBrowserNavigationTarget(environmentId, {
kind: "url",
url: input.url,
})
: undefined;
const reusedExistingTab = activeTabId !== null;
tabId = activeTabId;
if (!activeTabId) {
const result = await open({
environmentId,
input: {
threadId: request.threadId,
...(input.url ? { url: input.url } : {}),
},
});
if (result._tag === "Failure") {
return raiseAtomCommandFailure(result);
}
const snapshot = result.value;
applyPreviewServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
activeSnapshot = snapshot;
const resolvedInputUrl = route?.resolution.resolvedUrl;
return await withBrowserNavigationRoute(route, async () => {
let activeTabId = resolvePreviewAutomationOpenTab(
state,
request.tabId,
input.reuseExistingTab ?? true,
);
let activeSnapshot = activeTabId
? (state.sessions[activeTabId] ?? state.snapshot ?? undefined)
: undefined;
const reusedExistingTab = activeTabId !== null;
tabId = activeTabId;
}
if (input.show ?? true) {
useRightPanelStore.getState().openBrowser(threadRef, activeTabId);
}
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
await waitForDesktopOverlay(
threadRef,
request.requestId,
activeTabId,
request.timeoutMs,
);
}
if (reusedExistingTab && input.url && previewBridge) {
const resolution = resolveBrowserNavigationTarget(environmentId, {
kind: "url",
url: input.url,
});
await previewBridge.navigate(activeTabId, resolution.resolvedUrl);
await waitForNavigationReadiness(
threadRef,
request.requestId,
activeTabId,
"load",
request.timeoutMs,
);
}
return await currentStatus(threadRef, activeTabId);
if (!activeTabId) {
const result = await open({
environmentId,
input: {
threadId: request.threadId,
...(resolvedInputUrl ? { url: resolvedInputUrl } : {}),
},
});
if (result._tag === "Failure") {
return raiseAtomCommandFailure(result);
}
const snapshot = result.value;
applyPreviewServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
activeSnapshot = snapshot;
tabId = activeTabId;
await route?.commit(activeTabId);
}
if (input.show ?? true) {
useRightPanelStore.getState().openBrowser(threadRef, activeTabId);
}
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
await waitForDesktopOverlay(
threadRef,
request.requestId,
activeTabId,
request.timeoutMs,
);
}
if (reusedExistingTab && resolvedInputUrl && previewBridge) {
await previewBridge.navigate(activeTabId, resolvedInputUrl);
await route?.commit(activeTabId);
await waitForNavigationReadiness(
threadRef,
request.requestId,
activeTabId,
"load",
request.timeoutMs,
);
}
return await currentStatus(threadRef, activeTabId);
});
}
case "navigate": {
const ready = await requireReadyTab();
const input = request.input as PreviewAutomationNavigateInput;
const resolution = resolveBrowserNavigationTarget(
const route = await acquireBrowserNavigationTarget(
environmentId,
input.target ?? {
kind: "url",
url: input.url!,
},
);
await ready.bridge.navigate(ready.tabId, resolution.resolvedUrl);
await waitForNavigationReadiness(
threadRef,
request.requestId,
ready.tabId,
input.readiness ?? "load",
input.timeoutMs ?? request.timeoutMs,
);
return await currentStatus(threadRef, ready.tabId);
return await withBrowserNavigationRoute(route, async () => {
await ready.bridge.navigate(ready.tabId, route.resolution.resolvedUrl);
await route.commit(ready.tabId);
await waitForNavigationReadiness(
threadRef,
request.requestId,
ready.tabId,
input.readiness ?? "load",
input.timeoutMs ?? request.timeoutMs,
);
return await currentStatus(threadRef, ready.tabId);
});
}
case "resize": {
const ready = await requireReadyTab();
+24 -14
View File
@@ -17,7 +17,10 @@ import {
updatePreviewServerSnapshot,
useThreadPreviewState,
} from "~/previewStateStore";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import {
acquireDiscoveredServerRoute,
withBrowserNavigationRoute,
} from "~/browser/browserTargetResolver";
import { useEnvironment, useEnvironmentHttpBaseUrl } from "~/state/environments";
import { previewEnvironment } from "~/state/preview";
import { useAtomCommand } from "~/state/use-atom-command";
@@ -115,19 +118,26 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
const handleSubmitUrl = useCallback(
async (next: string) => {
try {
const resolvedUrl = resolveDiscoveredServerUrl(threadRef.environmentId, next);
if (tabId && previewBridge) {
// Drive the webview imperatively; `usePreviewBridge` mirrors the
// resolved URL back to the server so other clients stay in sync.
await previewBridge.navigate(tabId, resolvedUrl);
rememberPreviewUrl(threadRef, resolvedUrl);
} else {
await openPreviewSession({
openPreview: open,
threadRef,
url: resolvedUrl,
});
}
const route = await acquireDiscoveredServerRoute(threadRef.environmentId, next);
await withBrowserNavigationRoute(route, async () => {
const resolvedUrl = route.resolution.resolvedUrl;
if (tabId && previewBridge) {
// Drive the webview imperatively; `usePreviewBridge` mirrors the
// resolved URL back to the server so other clients stay in sync.
await previewBridge.navigate(tabId, resolvedUrl);
rememberPreviewUrl(threadRef, resolvedUrl);
await route.commit(tabId);
} else {
const result = await openPreviewSession({
openPreview: open,
threadRef,
url: resolvedUrl,
});
if (result._tag === "Success") {
await route.commit(result.value.tabId);
}
}
});
} catch {
// Server-side `failed` event renders the unreachable view.
}
@@ -7,6 +7,10 @@ import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const releaseBrowserNavigationRoute = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock("~/browser/browserTargetResolver", () => ({ releaseBrowserNavigationRoute }));
import {
applyPreviewServerSnapshot,
readThreadPreviewState,
@@ -33,7 +37,10 @@ const snapshot: PreviewSessionSnapshot = {
updatedAt: "2026-06-18T19:00:00.000Z",
};
beforeEach(resetPreviewStateForTests);
beforeEach(() => {
resetPreviewStateForTests();
releaseBrowserNavigationRoute.mockClear();
});
describe("closePreviewSession", () => {
it("suppresses stale server snapshots while the close is in flight", async () => {
@@ -60,6 +67,7 @@ describe("closePreviewSession", () => {
finishClose?.();
await closing;
expect(closePreview).toHaveBeenCalledWith({ threadId: "thread-1", tabId: "tab-1" });
expect(releaseBrowserNavigationRoute).toHaveBeenCalledWith("tab-1");
});
it("restores the last snapshot when the server close fails", async () => {
@@ -75,5 +83,6 @@ describe("closePreviewSession", () => {
expect(result._tag).toBe("Failure");
expect(readThreadPreviewState(threadRef).snapshot).toEqual(snapshot);
expect(readThreadPreviewState(threadRef).sessions).toEqual({ [snapshot.tabId]: snapshot });
expect(releaseBrowserNavigationRoute).not.toHaveBeenCalled();
});
});
@@ -7,6 +7,7 @@ import type {
} from "@t3tools/contracts";
import { beginPreviewSessionClose, cancelPreviewSessionClose } from "~/previewStateStore";
import { releaseBrowserNavigationRoute } from "~/browser/browserTargetResolver";
interface ClosePreviewSessionInput<E> {
readonly closePreview: (input: {
@@ -32,6 +33,8 @@ export async function closePreviewSession<E>(
});
if (result._tag === "Failure") {
cancelPreviewSessionClose(input.threadRef, input.snapshot, input.tabId);
} else {
await releaseBrowserNavigationRoute(input.tabId);
}
return result;
}
@@ -0,0 +1,94 @@
import type { PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import { AsyncResult } from "effect/unstable/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({
acquireDiscoveredServerRoute: vi.fn(),
commit: vi.fn(async () => undefined),
release: vi.fn(async () => undefined),
openBrowser: vi.fn(),
openPreviewSession: vi.fn(),
}));
vi.mock("~/browser/browserTargetResolver", () => ({
acquireDiscoveredServerRoute: mocks.acquireDiscoveredServerRoute,
}));
vi.mock("~/rightPanelStore", () => ({
useRightPanelStore: { getState: () => ({ openBrowser: mocks.openBrowser }) },
}));
vi.mock("./openPreviewSession", () => ({ openPreviewSession: mocks.openPreviewSession }));
import { openDiscoveredPort } from "./openDiscoveredPort";
const threadRef = {
environmentId: "environment-1",
threadId: "thread-1",
} as ScopedThreadRef;
const snapshot = {
threadId: threadRef.threadId,
tabId: "tab-1",
navStatus: { _tag: "Success", url: "http://127.0.0.1:42173/", title: "App" },
canGoBack: false,
canGoForward: false,
updatedAt: "2026-07-16T00:00:00.000Z",
} satisfies PreviewSessionSnapshot;
describe("openDiscoveredPort", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.acquireDiscoveredServerRoute.mockResolvedValue({
resolution: { resolvedUrl: "http://127.0.0.1:42173/" },
commit: mocks.commit,
release: mocks.release,
});
mocks.openPreviewSession.mockResolvedValue(AsyncResult.success(snapshot));
});
it("holds the route through preview creation and transfers it to the new tab", async () => {
const result = await openDiscoveredPort({
threadRef,
port: {
host: "localhost",
port: 5173,
url: "http://localhost:5173/",
processName: null,
pid: null,
terminal: null,
},
openPreview: vi.fn(),
});
expect(result._tag).toBe("Success");
expect(mocks.acquireDiscoveredServerRoute).toHaveBeenCalledWith(
threadRef.environmentId,
"http://localhost:5173/",
);
expect(mocks.openPreviewSession).toHaveBeenCalledWith(
expect.objectContaining({ url: "http://127.0.0.1:42173/" }),
);
expect(mocks.commit).toHaveBeenCalledWith("tab-1");
expect(mocks.release).toHaveBeenCalledOnce();
expect(mocks.openBrowser).toHaveBeenCalledWith(threadRef, "tab-1");
});
it("reports route acquisition failures as command failures", async () => {
mocks.acquireDiscoveredServerRoute.mockRejectedValueOnce(new Error("forward failed"));
const result = await openDiscoveredPort({
threadRef,
port: {
host: "localhost",
port: 5173,
url: "http://localhost:5173/",
processName: null,
pid: null,
terminal: null,
},
openPreview: vi.fn(),
});
expect(result._tag).toBe("Failure");
expect(mocks.openPreviewSession).not.toHaveBeenCalled();
});
});
@@ -3,8 +3,10 @@ import {
mapAtomCommandResult,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { acquireDiscoveredServerRoute } from "~/browser/browserTargetResolver";
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
import { useRightPanelStore } from "~/rightPanelStore";
import { openPreviewSession } from "./openPreviewSession";
@@ -14,13 +16,24 @@ export async function openDiscoveredPort<E>(input: {
readonly port: DiscoveredLocalServer;
readonly openPreview: OpenPreviewMutation<E>;
}): Promise<AtomCommandResult<void, E>> {
const resolvedUrl = resolveDiscoveredServerUrl(input.threadRef.environmentId, input.port.url);
const result = await openPreviewSession({
openPreview: input.openPreview,
threadRef: input.threadRef,
url: resolvedUrl,
});
return mapAtomCommandResult(result, (snapshot) => {
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
try {
const route = await acquireDiscoveredServerRoute(input.threadRef.environmentId, input.port.url);
try {
const result = await openPreviewSession({
openPreview: input.openPreview,
threadRef: input.threadRef,
url: route.resolution.resolvedUrl,
});
if (result._tag === "Success") {
await route.commit(result.value.tabId);
}
return mapAtomCommandResult(result, (snapshot) => {
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
} finally {
await route.release();
}
} catch (cause) {
return AsyncResult.failure(Cause.die(cause));
}
}
@@ -3,7 +3,6 @@ import { isLoopbackHost } from "@t3tools/shared/preview";
import { useMemo } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { useDiscoveredPorts } from "~/portDiscoveryState";
export interface PreviewableServer extends DiscoveredLocalServer {
@@ -33,10 +32,7 @@ export function useDiscoveredLocalServers(
return useMemo(
() =>
mergeServers({
scanner: scannerSnapshot.map((server) => ({
...server,
url: resolveDiscoveredServerUrl(input.environmentId, server.url),
})),
scanner: scannerSnapshot,
configuredUrls: input.configuredUrls ?? [],
recentlySeenUrls: input.recentlySeenUrls ?? [],
}),
@@ -1672,18 +1672,18 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
function CloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
savedEnvironments,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
readonly savedEnvironments: ReadonlyArray<EnvironmentPresentation>;
}) {
return hasCloudPublicConfig() ? (
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
savedEnvironments={savedEnvironments}
empty={<EmptyRemoteEnvironments />}
/>
) : savedEnvironmentIds.length === 0 ? (
) : savedEnvironments.length === 0 ? (
<EmptyRemoteEnvironments cloudEnabled={false} />
) : null;
}
@@ -1713,10 +1713,6 @@ export function ConnectionsSettings() {
.toSorted((left, right) => left.label.localeCompare(right.label)),
[environments],
);
const savedEnvironmentIds = useMemo(
() => savedEnvironments.map((environment) => environment.environmentId),
[savedEnvironments],
);
const savedDesktopSshEnvironmentsByAlias = useMemo(
() =>
savedEnvironments.reduce<Record<string, EnvironmentPresentation>>(
@@ -3363,7 +3359,7 @@ export function ConnectionsSettings() {
))}
<CloudRemoteEnvironmentRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
savedEnvironments={savedEnvironments}
/>
</SettingsSection>
</SettingsPageContainer>
+28
View File
@@ -272,6 +272,34 @@ const capabilitiesLayer = Layer.effectContext(
}),
});
}),
forwardPort: Effect.fn("web.connectionPlatform.ssh.forwardPort")(function* (input) {
const bridge = window.desktopBridge;
if (bridge === undefined) {
return yield* new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH port forwarding is only available in the desktop app.",
});
}
const lease = yield* Effect.acquireRelease(
Effect.tryPromise({
try: () => bridge.acquireSshPortForward(input.target, input.remotePort),
catch: sshPreparationError,
}),
(acquired) =>
Effect.tryPromise(() => bridge.releaseSshPortForward(acquired.leaseId)).pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not release SSH preview port forward.").pipe(
Effect.annotateLogs({
leaseId: acquired.leaseId,
remotePort: acquired.remotePort,
cause,
}),
),
),
),
);
return { localPort: lease.localPort };
}),
});
return Context.make(CloudSession, cloudSession).pipe(
+121
View File
@@ -7,6 +7,10 @@ import {
derivePhysicalProjectKey,
resolveProjectGroupingMode,
} from "./logicalProject";
import {
buildPhysicalToLogicalProjectKeyMap,
buildSidebarProjectSnapshots,
} from "./sidebarProjectGrouping";
import type { Project } from "./types";
const primaryEnvironmentId = EnvironmentId.make("env-primary");
@@ -119,4 +123,121 @@ describe("environment grouping", () => {
}),
).toBe("separate");
});
it("dedupes stale project rows with the same environment and workspace path", () => {
const duplicate = makeProject({
id: ProjectId.make("project-duplicate"),
workspaceRoot: "/tmp/shared-repo/",
repositoryIdentity,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const primary = makeProject({
id: ProjectId.make("project-primary"),
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const remote = makeProject({
id: ProjectId.make("project-remote"),
environmentId: remoteEnvironmentId,
workspaceRoot: "/tmp/shared-repo",
repositoryIdentity,
});
const snapshots = buildSidebarProjectSnapshots({
projects: [primary, duplicate, remote],
settings: defaultGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) =>
environmentId === remoteEnvironmentId ? "remote" : "primary",
});
expect(snapshots).toHaveLength(1);
expect(snapshots[0]?.groupedProjectCount).toBe(2);
expect(snapshots[0]?.memberProjects.map((project) => project.id)).toEqual([
primary.id,
remote.id,
]);
});
it("prefers the fresher project row when duplicate stale rows are ordered first", () => {
const staleDuplicate = makeProject({
id: ProjectId.make("project-stale"),
workspaceRoot: "/tmp/shared-repo/",
repositoryIdentity,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const canonical = makeProject({
id: ProjectId.make("project-canonical"),
workspaceRoot: "/tmp/shared-repo",
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const snapshots = buildSidebarProjectSnapshots({
projects: [staleDuplicate, canonical],
settings: defaultGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: () => "primary",
});
expect(snapshots).toHaveLength(1);
expect(snapshots[0]?.memberProjects.map((project) => project.id)).toEqual([canonical.id]);
expect(snapshots[0]?.id).toBe(canonical.id);
});
it("dedupes stale project rows before logical grouping", () => {
const staleWithoutRepositoryIdentity = makeProject({
id: ProjectId.make("project-stale"),
repositoryIdentity: null,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const canonical = makeProject({
id: ProjectId.make("project-canonical"),
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const remote = makeProject({
id: ProjectId.make("project-remote"),
environmentId: remoteEnvironmentId,
repositoryIdentity,
});
const snapshots = buildSidebarProjectSnapshots({
projects: [staleWithoutRepositoryIdentity, canonical, remote],
settings: defaultGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) =>
environmentId === remoteEnvironmentId ? "remote" : "primary",
});
expect(snapshots).toHaveLength(1);
expect(snapshots[0]?.projectKey).toBe(repositoryIdentity.canonicalKey);
expect(snapshots[0]?.memberProjects.map((project) => project.id)).toEqual([
canonical.id,
remote.id,
]);
});
it("routes duplicate physical project keys to the winning logical group", () => {
const staleWithoutRepositoryIdentity = makeProject({
id: ProjectId.make("project-stale"),
repositoryIdentity: null,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const canonical = makeProject({
id: ProjectId.make("project-canonical"),
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const physicalToLogicalKey = buildPhysicalToLogicalProjectKeyMap({
projects: [staleWithoutRepositoryIdentity, canonical],
settings: defaultGroupingSettings,
primaryEnvironmentId,
});
expect(physicalToLogicalKey.get(derivePhysicalProjectKey(staleWithoutRepositoryIdentity))).toBe(
repositoryIdentity.canonicalKey,
);
});
});
@@ -0,0 +1,82 @@
import { renderToStaticMarkup } from "react-dom/server";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { describe, expect, it } from "vite-plus/test";
import { remarkNormalizeListItemIndentation } from "./markdown-list-indentation";
function renderMarkdown(markdown: string): string {
return renderToStaticMarkup(
<ReactMarkdown remarkPlugins={[remarkGfm, remarkNormalizeListItemIndentation]}>
{markdown}
</ReactMarkdown>,
);
}
describe("remarkNormalizeListItemIndentation", () => {
it("renders same-line over-indented list content as list text", () => {
const html = renderMarkdown(`why did you do this?
- for (const step of rest.steps) {
- if (step.request.body) {
- step.request.body = "<redacted>";
- }
- }`);
expect(html).not.toContain("<pre>");
expect(html).toContain("<li>for (const step of rest.steps) {</li>");
expect(html).toContain("<li>if (step.request.body) {</li>");
expect(html).toContain("<li>step.request.body = &quot;&lt;redacted&gt;&quot;;</li>");
});
it("parses inline markdown in recovered list content", () => {
const html = renderMarkdown(
"- **important** [docs](https://example.com) use `inline code`, not ~~plain text~~",
);
expect(html).toContain("<strong>important</strong>");
expect(html).toContain('<a href="https://example.com">docs</a>');
expect(html).toContain("<code>inline code</code>");
expect(html).toContain("<del>plain text</del>");
expect(html).not.toContain("**important**");
});
it("preserves every recovered block separated by blank lines", () => {
const html = renderMarkdown(`- **first block**
[second block](https://example.com)`);
expect(html).toContain("<strong>first block</strong>");
expect(html).toContain('<a href="https://example.com">second block</a>');
});
it("recursively normalizes lists in recovered tail blocks", () => {
const html = renderMarkdown(`- first block
- nested block`);
expect(html).not.toContain("<pre>");
expect(html).toContain("<li>nested block</li>");
});
it("preserves fenced code blocks within list items", () => {
const html = renderMarkdown(`- \`\`\`ts
const value = 1;
\`\`\``);
expect(html).toContain('<pre><code class="language-ts">const value = 1;');
});
it("preserves indented code blocks that start below a list marker", () => {
const html = renderMarkdown(`-
const value = 1;`);
expect(html).toContain("<pre><code>const value = 1;");
});
it("preserves same-line code blocks without excess indentation", () => {
const html = renderMarkdown("- const value = 1;");
expect(html).toContain("<pre><code>const value = 1;");
});
});
+143
View File
@@ -0,0 +1,143 @@
interface MarkdownPosition {
readonly start?: {
readonly line?: number;
readonly offset?: number;
};
}
interface MarkdownAstNode {
readonly type: string;
readonly value?: unknown;
readonly position?: MarkdownPosition;
children?: MarkdownAstNode[];
}
interface MarkdownFile {
readonly value?: unknown;
}
interface MarkdownParser {
parse(markdown: string): unknown;
}
interface RecoveredMarkdown {
readonly blocks: MarkdownAstNode[];
readonly source: string;
}
const INLINE_PARSE_PREFIX = "t3-markdown-inline-prefix:";
function isSameLineOverIndentedCode(
node: MarkdownAstNode,
parent: MarkdownAstNode | undefined,
markdown: string,
): boolean {
if (
node.type !== "code" ||
parent?.type !== "listItem" ||
typeof node.value !== "string" ||
!/^[\t ]/.test(node.value)
) {
return false;
}
const nodeStart = node.position?.start;
const parentStart = parent.position?.start;
if (
nodeStart?.line === undefined ||
nodeStart.offset === undefined ||
parentStart?.line === undefined ||
nodeStart.line !== parentStart.line
) {
return false;
}
const sourceCharacter = markdown[nodeStart.offset];
return sourceCharacter !== "`" && sourceCharacter !== "~";
}
function parseRecoveredMarkdown(value: string, parser: MarkdownParser): RecoveredMarkdown {
// A text prefix forces block-looking input into a paragraph while preserving
// the processor's configured inline extensions (for example, GFM syntax).
// Later root children are kept as blocks so blank-line-separated content is
// never discarded.
const source = `${INLINE_PARSE_PREFIX}${value}`;
const document = parser.parse(source) as MarkdownAstNode;
const blocks = document.children;
const paragraph = blocks?.[0];
const children = paragraph?.type === "paragraph" ? paragraph.children : undefined;
const first = children?.[0];
if (
!blocks ||
!children ||
first?.type !== "text" ||
typeof first.value !== "string" ||
!first.value.startsWith(INLINE_PARSE_PREFIX)
) {
return { blocks: [{ type: "text", value }], source };
}
const firstValue = first.value.slice(INLINE_PARSE_PREFIX.length);
return {
blocks: [
{
...paragraph,
type: "paragraph",
children: [...(firstValue ? [{ ...first, value: firstValue }] : []), ...children.slice(1)],
},
...blocks.slice(1),
],
source,
};
}
function blocksFromIndentedCode(node: MarkdownAstNode, parser: MarkdownParser): RecoveredMarkdown {
const value = typeof node.value === "string" ? node.value.trim() : "";
const recovered = parseRecoveredMarkdown(value, parser);
const first = recovered.blocks[0];
return {
...recovered,
blocks:
first && node.position
? [{ ...first, position: node.position }, ...recovered.blocks.slice(1)]
: recovered.blocks,
};
}
/**
* CommonMark treats four or more spaces after a list marker as an indented
* code block. In chat output, excessive spacing is commonly accidental
* alignment such as `- text`, which otherwise produces a full code card
* for every bullet. Only normalize blocks that retain excess indentation and
* start on the marker's own line; explicit fences and conventional indented
* blocks remain code.
*/
function attachListItemIndentationNormalizer(this: MarkdownParser) {
return (tree: MarkdownAstNode, file: MarkdownFile) => {
if (typeof file.value !== "string") {
return;
}
const markdown = file.value;
const visit = (node: MarkdownAstNode, source: string) => {
if (!node.children) {
return;
}
node.children = node.children.flatMap((child) => {
if (isSameLineOverIndentedCode(child, node, source)) {
const recovered = blocksFromIndentedCode(child, this);
for (const block of recovered.blocks) {
visit(block, recovered.source);
}
return recovered.blocks;
}
visit(child, source);
return [child];
});
};
visit(tree, markdown);
};
}
export const remarkNormalizeListItemIndentation = attachListItemIndentationNormalizer;
+71 -10
View File
@@ -31,16 +31,77 @@ export interface SidebarProjectSnapshot extends Project {
remoteEnvironmentLabels: readonly string[];
}
interface SidebarProjectGroupCandidate {
readonly logicalKey: string;
readonly project: Project;
}
function getProjectFreshnessTime(project: Project): number {
const updatedAtTime = Date.parse(project.updatedAt);
if (Number.isFinite(updatedAtTime)) {
return updatedAtTime;
}
const createdAtTime = Date.parse(project.createdAt);
return Number.isFinite(createdAtTime) ? createdAtTime : 0;
}
function shouldReplaceDuplicateMember(input: {
existingMember: Project;
candidateMember: Project;
primaryEnvironmentId: EnvironmentId | null;
}): boolean {
if (
input.primaryEnvironmentId !== null &&
input.existingMember.environmentId !== input.primaryEnvironmentId &&
input.candidateMember.environmentId === input.primaryEnvironmentId
) {
return true;
}
const existingFreshness = getProjectFreshnessTime(input.existingMember);
const candidateFreshness = getProjectFreshnessTime(input.candidateMember);
if (candidateFreshness !== existingFreshness) {
return candidateFreshness > existingFreshness;
}
return input.candidateMember.id > input.existingMember.id;
}
function collectProjectWinnersByPhysicalKey(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
}): Map<string, SidebarProjectGroupCandidate> {
const winnersByPhysicalKey = new Map<string, SidebarProjectGroupCandidate>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
const physicalProjectKey = derivePhysicalProjectKey(project);
const existing = winnersByPhysicalKey.get(physicalProjectKey);
if (!existing) {
winnersByPhysicalKey.set(physicalProjectKey, { logicalKey, project });
continue;
}
if (
shouldReplaceDuplicateMember({
existingMember: existing.project,
candidateMember: project,
primaryEnvironmentId: input.primaryEnvironmentId,
})
) {
winnersByPhysicalKey.set(physicalProjectKey, { logicalKey, project });
}
}
return winnersByPhysicalKey;
}
export function buildPhysicalToLogicalProjectKeyMap(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
}): Map<string, string> {
const mapping = new Map<string, string>();
for (const project of input.projects) {
mapping.set(
derivePhysicalProjectKey(project),
deriveLogicalProjectKeyFromSettings(project, input.settings),
);
for (const [physicalProjectKey, winner] of collectProjectWinnersByPhysicalKey(input)) {
mapping.set(physicalProjectKey, winner.logicalKey);
}
return mapping;
}
@@ -56,17 +117,17 @@ export function buildSidebarProjectSnapshots(input: {
// legacy behavior.
isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean;
}): SidebarProjectSnapshot[] {
const winnersByPhysicalKey = collectProjectWinnersByPhysicalKey(input);
const groupedMembers = new Map<string, SidebarProjectGroupMember[]>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
for (const { logicalKey, project } of winnersByPhysicalKey.values()) {
const member: SidebarProjectGroupMember = {
...project,
physicalProjectKey: derivePhysicalProjectKey(project),
environmentLabel: input.resolveEnvironmentLabel(project.environmentId),
};
const existing = groupedMembers.get(logicalKey);
if (existing) {
existing.push(member);
const existingMembers = groupedMembers.get(logicalKey);
if (existingMembers) {
existingMembers.push(member);
} else {
groupedMembers.set(logicalKey, [member]);
}
+4
View File
@@ -35,6 +35,10 @@
"types": "./src/platform/index.ts",
"default": "./src/platform/index.ts"
},
"./preview": {
"types": "./src/preview/index.ts",
"default": "./src/preview/index.ts"
},
"./relay": {
"types": "./src/relay/index.ts",
"default": "./src/relay/index.ts"
@@ -10,6 +10,7 @@ import * as PlatformConnectionSource from "../platform/source.ts";
import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import * as RpcSession from "../rpc/session.ts";
import { EnvironmentPortRouter } from "../preview/router.ts";
const resolverLayer = ConnectionResolver.layer.pipe(
Layer.provide(RemoteEnvironmentAuthorization.layer),
@@ -27,6 +28,7 @@ const connectionServicesLayer = Layer.mergeAll(
registryLayer,
RelayEnvironmentDiscovery.layer,
onboardingLayer,
EnvironmentPortRouter.layer,
);
const connectionStartupLayer = Layer.effectDiscard(
@@ -234,6 +234,7 @@ describe("connection onboarding", () => {
}),
prepare: () => Effect.die("unused"),
disconnect: () => Effect.die("unused"),
forwardPort: () => Effect.die("unused"),
}),
),
);
@@ -330,6 +330,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
provision: () => Effect.die(new Error("SSH provisioning is not used.")),
prepare: () => Effect.die(new Error("SSH preparation is not used.")),
disconnect: (target) => Ref.update(disconnectedSshTargets, (current) => [...current, target]),
forwardPort: () => Effect.die(new Error("SSH port forwarding is not used.")),
});
const driver = ConnectionDriver.ConnectionDriver.of({
connect: (entry, reportProgress) =>
@@ -159,6 +159,7 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
bearerToken: "ssh-bearer",
})),
disconnect: () => Effect.void,
forwardPort: () => Effect.die("unused"),
});
const dependencies = Layer.mergeAll(
@@ -8,6 +8,7 @@ import {
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Option from "effect/Option";
import type * as Scope from "effect/Scope";
import type { ConnectionAttemptError } from "../connection/model.ts";
@@ -21,6 +22,10 @@ export interface ProvisionedSshEnvironment extends PreparedSshEnvironment {
readonly label: string;
}
export interface PreparedSshPortForward {
readonly localPort: number;
}
export class CloudSession extends Context.Service<
CloudSession,
{
@@ -64,5 +69,9 @@ export class SshEnvironmentGateway extends Context.Service<
readonly disconnect: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, ConnectionAttemptError>;
readonly forwardPort: (input: {
readonly target: DesktopSshEnvironmentTarget;
readonly remotePort: number;
}) => Effect.Effect<PreparedSshPortForward, ConnectionAttemptError, Scope.Scope>;
}
>()("@t3tools/client-runtime/platform/capabilities/SshEnvironmentGateway") {}
@@ -0,0 +1 @@
export * from "./router.ts";
@@ -0,0 +1,249 @@
import { assert, describe, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import {
PrimaryConnectionTarget,
RelayConnectionTarget,
SshConnectionTarget,
type PreparedConnection,
} from "../connection/model.ts";
import { SshConnectionProfile } from "../connection/catalog.ts";
import { ConnectionProfileStore } from "../connection/profileStore.ts";
import { SshEnvironmentGateway } from "../platform/capabilities.ts";
import { EnvironmentPortRouter } from "./router.ts";
const environmentId = EnvironmentId.make("environment-1");
const sshTarget = {
alias: "devbox",
hostname: "devbox.example.test",
username: "developer",
port: 22,
} as const;
const primaryConnection = (httpBaseUrl: string): PreparedConnection => ({
environmentId,
label: "Environment",
httpBaseUrl,
socketUrl: "ws://example.test",
httpAuthorization: null,
target: new PrimaryConnectionTarget({
environmentId,
label: "Environment",
httpBaseUrl,
wsBaseUrl: "ws://example.test",
}),
});
const sshConnection: PreparedConnection = {
environmentId,
label: "SSH environment",
httpBaseUrl: "http://127.0.0.1:3773",
socketUrl: "ws://127.0.0.1:3773",
httpAuthorization: null,
target: new SshConnectionTarget({
environmentId,
label: "SSH environment",
connectionId: "ssh:environment-1",
}),
};
const sshProfile = new SshConnectionProfile({
connectionId: "ssh:environment-1",
environmentId,
label: "SSH environment",
target: sshTarget,
});
const routerLayer = (options?: {
readonly profile?: SshConnectionProfile;
readonly forwardPort?: SshEnvironmentGateway["Service"]["forwardPort"];
}) =>
EnvironmentPortRouter.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(
ConnectionProfileStore,
ConnectionProfileStore.of({
get: () => Effect.succeed(Option.fromUndefinedOr(options?.profile)),
put: () => Effect.void,
remove: () => Effect.void,
}),
),
Layer.succeed(
SshEnvironmentGateway,
SshEnvironmentGateway.of({
provision: () => Effect.die("unused"),
prepare: () => Effect.die("unused"),
disconnect: () => Effect.void,
forwardPort: options?.forwardPort ?? (() => Effect.die("unused")),
}),
),
),
),
);
describe("EnvironmentPortRouter", () => {
it.effect("maps environment ports onto a private network host", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: primaryConnection("http://192.168.1.25:3773"),
target: { kind: "environment-port", port: 5173, path: "/dashboard" },
});
assert.deepStrictEqual(resolution, {
requestedUrl: "http://localhost:5173/dashboard",
resolvedUrl: "http://192.168.1.25:5173/dashboard",
resolutionKind: "direct-private-network",
environmentId,
});
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("keeps localhost navigation local for a local environment", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: primaryConnection("http://127.0.0.1:3773"),
target: { kind: "url", url: "localhost:3000/app" },
});
assert.deepStrictEqual(resolution, {
requestedUrl: "localhost:3000/app",
resolvedUrl: "localhost:3000/app",
resolutionKind: "direct",
environmentId,
});
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("maps localhost URLs onto remote Tailscale hosts", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: primaryConnection("http://100.65.180.100:3773"),
target: {
kind: "url",
url: "http://localhost:5173/dashboard?mode=test#results",
},
});
assert.equal(
resolution.resolvedUrl,
"http://100.65.180.100:5173/dashboard?mode=test#results",
);
assert.equal(resolution.resolutionKind, "direct-private-network");
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("preserves credentials when mapping onto private IPv6 hosts", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: primaryConnection("http://[fd7a:115c:a1e0::53]:3773"),
target: {
kind: "url",
url: "http://user:p%40ss@localhost:5173/dashboard?mode=test#results",
},
});
assert.equal(
resolution.resolvedUrl,
"http://user:p%40ss@[fd7a:115c:a1e0::53]:5173/dashboard?mode=test#results",
);
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("maps wildcard loopback URLs back to localhost for a local environment", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: primaryConnection("http://localhost:3773"),
target: { kind: "url", url: "http://0.0.0.0:3000/app" },
});
assert.equal(resolution.resolvedUrl, "http://localhost:3000/app");
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("recognizes the full IPv4 loopback range on environment endpoints", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: primaryConnection("http://127.0.0.2:3773"),
target: { kind: "url", url: "http://localhost:3000/app" },
});
assert.equal(resolution.resolvedUrl, "http://localhost:3000/app");
assert.equal(resolution.resolutionKind, "direct");
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("preserves malformed input for the preview navigation error path", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: primaryConnection("http://127.0.0.1:3773"),
target: { kind: "url", url: " " },
});
assert.equal(resolution.resolvedUrl, " ");
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("acquires and releases an SSH forward within the caller scope", () => {
let releases = 0;
const forwardPort: SshEnvironmentGateway["Service"]["forwardPort"] = (input) =>
Effect.acquireRelease(
Effect.sync(() => {
assert.deepStrictEqual(input, { target: sshTarget, remotePort: 5173 });
return { localPort: 42_173 };
}),
() => Effect.sync(() => releases++),
);
return Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* Effect.scoped(
router.acquire({
connection: sshConnection,
target: {
kind: "url",
url: "http://user:p%40ss@localhost:5173/dashboard?mode=test#results",
},
}),
);
assert.equal(
resolution.resolvedUrl,
"http://user:p%[email protected]:42173/dashboard?mode=test#results",
);
assert.equal(resolution.resolutionKind, "ssh-forward");
assert.equal(releases, 1);
}).pipe(Effect.provide(routerLayer({ profile: sshProfile, forwardPort })));
});
it.effect("reports T3 Connect environment ports as unsupported", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const exit = yield* Effect.exit(
router.acquire({
connection: {
...primaryConnection("https://relay.example.test"),
target: new RelayConnectionTarget({ environmentId, label: "Relay" }),
},
target: { kind: "environment-port", port: 5173 },
}),
);
assert(exit._tag === "Failure");
assert.include(String(exit.cause), "T3 Connect preview forwarding is not supported yet");
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
it.effect("leaves ordinary public URLs outside environment routing", () =>
Effect.gen(function* () {
const router = yield* EnvironmentPortRouter;
const resolution = yield* router.acquire({
connection: sshConnection,
target: { kind: "url", url: "https://example.com/app" },
});
assert.equal(resolution.resolvedUrl, "https://example.com/app");
assert.equal(resolution.resolutionKind, "direct");
}).pipe(Effect.provide(routerLayer()), Effect.scoped),
);
});
@@ -0,0 +1,270 @@
import {
type BrowserNavigationTarget,
EnvironmentId,
type PreviewUrlResolution,
} from "@t3tools/contracts";
import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
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 Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import { SshEnvironmentGateway } from "../platform/capabilities.ts";
import { ConnectionProfileStore } from "../connection/profileStore.ts";
import type { ConnectionAttemptError, PreparedConnection } from "../connection/model.ts";
export class EnvironmentPortRoutingError extends Schema.TaggedErrorClass<EnvironmentPortRoutingError>()(
"EnvironmentPortRoutingError",
{
environmentId: EnvironmentId,
reason: Schema.Literals(["configuration", "unsupported"]),
detail: Schema.String,
},
) {
override get message(): string {
return this.detail;
}
}
export interface EnvironmentPortRouteRequest {
readonly connection: PreparedConnection;
readonly target: BrowserNavigationTarget;
}
type EnvironmentPortTarget = Extract<
BrowserNavigationTarget,
{ readonly kind: "environment-port" }
>;
const normalizeHostname = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, "");
const parseIpv4Address = (host: string): readonly number[] | null => {
const parts = normalizeHostname(host).split(".").map(Number);
return parts.length === 4 &&
parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)
? parts
: null;
};
const isLocalLoopbackHost = (host: string): boolean => {
const normalized = normalizeHostname(host);
if (normalized === "localhost" || normalized === "::1") return true;
return parseIpv4Address(normalized)?.[0] === 127;
};
const isPrivateNetworkHost = (host: string): boolean => {
const normalized = normalizeHostname(host);
if (isLocalLoopbackHost(normalized) || normalized.endsWith(".local")) return true;
if (normalized.endsWith(".ts.net")) return true;
const parts = parseIpv4Address(normalized);
if (parts) {
return (
parts[0] === 10 ||
(parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
(parts[0] === 169 && parts[1] === 254)
);
}
const firstIpv6Token = normalized.split(":", 1)[0] ?? "";
if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false;
const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16);
return (
Number.isInteger(firstIpv6Hextet) &&
((firstIpv6Hextet & 0xfe00) === 0xfc00 || (firstIpv6Hextet & 0xffc0) === 0xfe80)
);
};
const resolvedHost = (hostname: string): string => {
const normalized = normalizeHostname(hostname);
return normalized.includes(":") ? `[${normalized}]` : normalized;
};
const parsePreviewUrl = (rawUrl: string): URL | null => {
try {
return new URL(normalizePreviewUrl(rawUrl));
} catch {
return null;
}
};
const resolveOnHost = (input: {
readonly environmentId: EnvironmentId;
readonly target: EnvironmentPortTarget;
readonly hostname: string;
readonly resolutionKind: PreviewUrlResolution["resolutionKind"];
readonly requestedUrl?: string;
readonly sourceUrl?: URL;
}): PreviewUrlResolution => {
const protocol = input.target.protocol ?? "http";
const path = input.target.path?.startsWith("/")
? input.target.path
: `/${input.target.path ?? ""}`;
const host = resolvedHost(input.hostname);
const resolved = input.sourceUrl
? new URL(input.sourceUrl)
: new URL(path, `${protocol}://${host}:${input.target.port}`);
if (input.sourceUrl) {
resolved.hostname = host;
resolved.port = String(input.target.port);
}
return {
requestedUrl: input.requestedUrl ?? `${protocol}://localhost:${input.target.port}${path}`,
resolvedUrl: resolved.toString(),
resolutionKind: input.resolutionKind,
environmentId: input.environmentId,
};
};
export class EnvironmentPortRouter extends Context.Service<
EnvironmentPortRouter,
{
readonly acquire: (
request: EnvironmentPortRouteRequest,
) => Effect.Effect<
PreviewUrlResolution,
ConnectionAttemptError | EnvironmentPortRoutingError,
Scope.Scope
>;
}
>()("@t3tools/client-runtime/preview/router/EnvironmentPortRouter") {
static readonly layer = Layer.effect(
EnvironmentPortRouter,
Effect.gen(function* () {
const ssh = yield* SshEnvironmentGateway;
const profiles = yield* ConnectionProfileStore;
const acquireEnvironmentPort = Effect.fn("EnvironmentPortRouter.acquireEnvironmentPort")(
function* (input: {
readonly connection: PreparedConnection;
readonly target: EnvironmentPortTarget;
readonly requestedUrl?: string;
readonly sourceUrl?: URL;
}) {
const environmentId = input.connection.environmentId;
if (input.connection.target._tag === "RelayConnectionTarget") {
return yield* new EnvironmentPortRoutingError({
environmentId,
reason: "unsupported",
detail:
"This environment port needs the planned authenticated preview gateway; T3 Connect preview forwarding is not supported yet.",
});
}
if (input.connection.target._tag === "SshConnectionTarget") {
const sshTarget = input.connection.target;
const profile = yield* profiles.get(sshTarget.connectionId).pipe(
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new EnvironmentPortRoutingError({
environmentId,
reason: "configuration",
detail: `SSH connection profile ${sshTarget.connectionId} is unavailable.`,
}),
),
onSome: Effect.succeed,
}),
),
);
if (profile._tag !== "SshConnectionProfile") {
return yield* new EnvironmentPortRoutingError({
environmentId,
reason: "configuration",
detail: `Connection profile ${sshTarget.connectionId} is not an SSH profile.`,
});
}
const forward = yield* ssh.forwardPort({
target: profile.target,
remotePort: input.target.port,
});
return resolveOnHost({
...input,
target: { ...input.target, port: forward.localPort },
requestedUrl:
input.requestedUrl ??
`${input.target.protocol ?? "http"}://localhost:${input.target.port}${
input.target.path?.startsWith("/")
? input.target.path
: `/${input.target.path ?? ""}`
}`,
environmentId,
hostname: "127.0.0.1",
resolutionKind: "ssh-forward",
});
}
const environmentUrl = yield* Effect.try({
try: () => new URL(input.connection.httpBaseUrl),
catch: () =>
new EnvironmentPortRoutingError({
environmentId,
reason: "configuration",
detail: "The environment connection URL is invalid.",
}),
});
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
return yield* new EnvironmentPortRoutingError({
environmentId,
reason: "unsupported",
detail:
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
});
}
return resolveOnHost({
...input,
environmentId,
hostname: environmentUrl.hostname,
resolutionKind: isLocalLoopbackHost(environmentUrl.hostname)
? "direct"
: "direct-private-network",
});
},
);
const acquire = Effect.fn("EnvironmentPortRouter.acquire")(function* (
request: EnvironmentPortRouteRequest,
) {
const environmentId = request.connection.environmentId;
if (request.target.kind === "url") {
const parsed = parsePreviewUrl(request.target.url);
if (parsed && isLoopbackHost(parsed.hostname)) {
const environmentUrl = new URL(request.connection.httpBaseUrl);
if (
parsed.hostname === "0.0.0.0" ||
request.connection.target._tag === "SshConnectionTarget" ||
!isLocalLoopbackHost(environmentUrl.hostname)
) {
return yield* acquireEnvironmentPort({
connection: request.connection,
target: {
kind: "environment-port",
port: Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)),
protocol: parsed.protocol === "https:" ? "https" : "http",
path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
},
requestedUrl: request.target.url,
sourceUrl: parsed,
});
}
}
return {
requestedUrl: request.target.url,
resolvedUrl: request.target.url,
resolutionKind: "direct" as const,
environmentId,
};
}
return yield* acquireEnvironmentPort({
connection: request.connection,
target: request.target,
});
});
return EnvironmentPortRouter.of({ acquire });
}),
);
}
+5 -31
View File
@@ -3,16 +3,16 @@ import {
isUncPath,
isWindowsAbsolutePath,
isWindowsDrivePath,
normalizeProjectPathForComparison,
normalizeProjectPathForDispatch,
} from "@t3tools/shared/path";
export { normalizeProjectPathForComparison, normalizeProjectPathForDispatch };
const isWindowsPlatform = (platform: string): boolean => {
return /^win(dows)?/i.test(platform);
};
function isRootPath(value: string): boolean {
return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]?$/.test(value);
}
function getAbsolutePathKind(value: string): "unix" | "windows" | null {
if (isWindowsDrivePath(value) || isUncPath(value)) {
return "windows";
@@ -23,20 +23,6 @@ function getAbsolutePathKind(value: string): "unix" | "windows" | null {
return null;
}
function trimTrailingPathSeparators(value: string): string {
if (value.length === 0 || isRootPath(value)) {
return value;
}
const trimmed =
getAbsolutePathKind(value) === "unix"
? value.replace(/\/+$/g, "")
: value.replace(/[\\/]+$/g, "");
if (trimmed.length === 0) {
return value;
}
return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
}
function preferredPathSeparator(value: string): "/" | "\\" {
const absolutePathKind = getAbsolutePathKind(value);
if (absolutePathKind === "windows") return "\\";
@@ -108,10 +94,6 @@ export function isUnsupportedWindowsProjectPath(value: string, platform: string)
return isWindowsAbsolutePath(value) && !isWindowsPlatform(platform);
}
export function normalizeProjectPathForDispatch(value: string): string {
return trimTrailingPathSeparators(value.trim());
}
export function resolveProjectPathForDispatch(value: string, cwd?: string | null): string {
const trimmedValue = value.trim();
if (!isExplicitRelativePath(trimmedValue) || !cwd) {
@@ -139,14 +121,6 @@ export function resolveProjectPathForDispatch(value: string, cwd?: string | null
);
}
export function normalizeProjectPathForComparison(value: string): string {
const normalized = normalizeProjectPathForDispatch(value);
if (isWindowsDrivePath(normalized) || normalized.startsWith("\\\\")) {
return normalized.replaceAll("/", "\\").toLowerCase();
}
return normalized;
}
export function findProjectByPath<T extends { workspaceRoot?: string; cwd?: string }>(
projects: ReadonlyArray<T>,
candidatePath: string,
@@ -198,7 +172,7 @@ export function ensureBrowseDirectoryPath(currentPath: string): string {
}
export function getBrowseParentPath(currentPath: string): string | null {
const trimmed = trimTrailingPathSeparators(currentPath);
const trimmed = normalizeProjectPathForDispatch(currentPath);
const absolutePath = splitAbsolutePath(trimmed);
if (absolutePath) {
if (absolutePath.segments.length === 0) return null;
+33
View File
@@ -367,6 +367,32 @@ export const DesktopSshEnvironmentEnsureResultSchema = Schema.Union([
DesktopSshPasswordPromptCancelledResultSchema,
]);
export interface DesktopSshPortForward {
leaseId: string;
localPort: number;
remotePort: number;
}
export const DesktopSshPortForwardSchema = Schema.Struct({
leaseId: Schema.String,
localPort: Schema.Number,
remotePort: Schema.Number,
});
export const DesktopSshPortForwardAcquireInputSchema = Schema.Struct({
target: DesktopSshEnvironmentTargetSchema,
remotePort: Schema.Number,
});
export const DesktopSshPortForwardAcquireResultSchema = Schema.Union([
DesktopSshPortForwardSchema,
DesktopSshPasswordPromptCancelledResultSchema,
]);
export const DesktopSshPortForwardReleaseInputSchema = Schema.Struct({
leaseId: Schema.String,
});
export const DesktopSshHttpBaseUrlInputSchema = Schema.Struct({
httpBaseUrl: Schema.String,
});
@@ -962,6 +988,11 @@ export interface DesktopBridge {
options?: { issuePairingToken?: boolean },
) => Promise<DesktopSshEnvironmentBootstrap>;
disconnectSshEnvironment: (target: DesktopSshEnvironmentTarget) => Promise<void>;
acquireSshPortForward: (
target: DesktopSshEnvironmentTarget,
remotePort: number,
) => Promise<DesktopSshPortForward>;
releaseSshPortForward: (leaseId: string) => Promise<void>;
fetchSshEnvironmentDescriptor: (httpBaseUrl: string) => Promise<ExecutionEnvironmentDescriptor>;
bootstrapSshBearerSession: (
httpBaseUrl: string,
@@ -994,6 +1025,8 @@ export interface DesktopBridge {
) => Promise<T | null>;
openExternal: (url: string) => Promise<boolean>;
onMenuAction: (listener: (action: string) => void) => () => void;
getWindowFullscreenState: () => boolean;
onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;
getUpdateState: () => Promise<DesktopUpdateState>;
setUpdateChannel: (channel: DesktopUpdateChannel) => Promise<DesktopUpdateState>;
checkForUpdate: () => Promise<DesktopUpdateCheckResult>;
+1 -1
View File
@@ -851,7 +851,7 @@ export type PreviewAutomationError = typeof PreviewAutomationError.Type;
export const PreviewUrlResolution = Schema.Struct({
requestedUrl: Schema.String,
resolvedUrl: Schema.String,
resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
resolutionKind: Schema.Literals(["direct", "direct-private-network", "ssh-forward"]),
environmentId: EnvironmentId,
});
export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;
+12
View File
@@ -71,6 +71,18 @@ it.layer(NetService.layer)("NetService", (it) => {
),
);
it.effect("hasListenerOnHost detects an occupied TCP port", () =>
Effect.acquireUseRelease(
openServer("127.0.0.1"),
(server) =>
Effect.gen(function* () {
const net = yield* NetService.NetService;
assert.equal(yield* net.hasListenerOnHost(getPort(server), "127.0.0.1"), true);
}),
closeServer,
),
);
it.effect("findAvailablePort returns preferred when it is free", () =>
Effect.gen(function* () {
const net = yield* NetService.NetService;
+6
View File
@@ -29,6 +29,11 @@ const closeServer = (server: NodeNet.Server) => {
};
export interface NetServiceShape {
/**
* Returns true when a TCP client can connect to {host, port}.
*/
readonly hasListenerOnHost: (port: number, host: string) => Effect.Effect<boolean>;
/**
* Returns true when a TCP server can bind to {host, port}.
*/
@@ -181,6 +186,7 @@ export const make = () => {
});
return {
hasListenerOnHost,
canListenOnHost,
isPortAvailableOnLoopback,
reserveLoopbackPort,
+29
View File
@@ -20,3 +20,32 @@ export function isExplicitRelativePath(value: string): boolean {
value.startsWith("..\\")
);
}
function isRootPath(value: string): boolean {
return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]?$/.test(value);
}
function trimTrailingPathSeparators(value: string): string {
if (value.length === 0 || isRootPath(value)) {
return value;
}
const trimmed = value.startsWith("/")
? value.replace(/\/+$/g, "")
: value.replace(/[\\/]+$/g, "");
if (trimmed.length === 0) {
return value;
}
return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
}
export function normalizeProjectPathForDispatch(value: string): string {
return trimTrailingPathSeparators(value.trim());
}
export function normalizeProjectPathForComparison(value: string): string {
const normalized = normalizeProjectPathForDispatch(value);
if (isWindowsDrivePath(normalized) || isUncPath(normalized)) {
return normalized.replaceAll("/", "\\").toLowerCase();
}
return normalized;
}
+62
View File
@@ -78,6 +78,7 @@ const testHttpClient = HttpClient.make((request) =>
const hangingHttpClient = HttpClient.make(() => Effect.never);
const testNetService = NetService.NetService.of({
hasListenerOnHost: () => Effect.succeed(true),
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(41_773),
@@ -392,4 +393,65 @@ describe("ssh tunnel scripts", () => {
assert.equal(tunnelKillCount, 1);
}).pipe(Effect.provide(layer), Effect.scoped);
});
it.effect("reference-counts shared preview port forwards", () => {
let tunnelSpawnCount = 0;
let tunnelKillCount = 0;
const forwardArgs: ReadonlyArray<string>[] = [];
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
const args = commandArgs(command);
if (args.includes("-N")) {
tunnelSpawnCount += 1;
forwardArgs.push(args);
return makeRunningProcess(() => {
tunnelKillCount += 1;
});
}
return makeSuccessfulProcess("\n");
}),
);
const layer = Layer.mergeAll(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(HttpClient.HttpClient, testHttpClient),
Layer.succeed(NetService.NetService, testNetService),
SshPasswordPrompt.disabledLayer,
SshEnvironmentManager.layer(),
);
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
return Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
const [first, second] = yield* Effect.all(
[manager.acquirePortForward(target, 5173), manager.acquirePortForward(target, 5173)],
{ concurrency: "unbounded" },
);
assert.equal(first.localPort, second.localPort);
assert.notEqual(first.leaseId, second.leaseId);
assert.equal(tunnelSpawnCount, 1);
assert.include(forwardArgs[0] ?? [], "127.0.0.1:41773:127.0.0.1:5173");
yield* manager.releasePortForward(first.leaseId);
assert.equal(tunnelKillCount, 0);
yield* manager.releasePortForward(second.leaseId);
assert.equal(tunnelKillCount, 1);
const third = yield* manager.acquirePortForward(target, 5173);
assert.equal(tunnelSpawnCount, 2);
yield* manager.disconnectEnvironment(target);
assert.equal(tunnelKillCount, 2);
yield* manager.releasePortForward(third.leaseId);
assert.equal(tunnelKillCount, 2);
}).pipe(Effect.provide(layer), Effect.scoped);
});
});
+393 -79
View File
@@ -11,12 +11,14 @@ import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
@@ -80,6 +82,21 @@ interface SshTunnelEntry {
readonly scope: Scope.Scope;
}
interface SshPortForwardEntry extends SshTunnelEntry {
readonly connectionKey: string;
readonly leases: Set<string>;
}
interface PendingSshPortForward {
readonly deferred: Deferred.Deferred<SshPortForwardEntry, SshEnvironmentEffectError>;
}
export interface SshPortForwardLease {
readonly leaseId: string;
readonly localPort: number;
readonly remotePort: number;
}
type SshEnvironmentEffectContext =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
@@ -150,6 +167,11 @@ export interface SshEnvironmentManagerShape {
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, SshEnvironmentEffectError, SshEnvironmentEffectContext>;
readonly acquirePortForward: (
target: DesktopSshEnvironmentTarget,
remotePort: number,
) => Effect.Effect<SshPortForwardLease, SshEnvironmentEffectError, SshEnvironmentEffectContext>;
readonly releasePortForward: (leaseId: string) => Effect.Effect<void>;
}
const RemoteLaunchResult = Schema.Struct({
@@ -917,6 +939,27 @@ const reserveLocalTunnelPort = Effect.fn("ssh/tunnel.reserveLocalTunnelPort")(fu
return yield* net.reserveLoopbackPort();
});
const waitForTcpForwardReady = Effect.fn("ssh/tunnel.waitForTcpForwardReady")(function* (
localPort: number,
) {
const net = yield* NetService.NetService;
const retryPolicy = Schedule.spaced(Duration.millis(50)).pipe(
Schedule.take(Math.ceil(SSH_READY_TIMEOUT_MS / 50)),
);
yield* net.hasListenerOnHost(localPort, "127.0.0.1").pipe(
Effect.flatMap((ready) =>
ready
? Effect.void
: Effect.fail(
new SshReadinessError({
message: `SSH port forward on 127.0.0.1:${localPort} did not become ready.`,
}),
),
),
Effect.retry(retryPolicy),
);
});
const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: {
readonly key: string;
readonly resolvedTarget: DesktopSshEnvironmentTarget;
@@ -926,6 +969,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
readonly wsBaseUrl: string;
readonly authOptions: SshAuthOptions;
readonly remoteServerKind: "external" | "managed" | null;
readonly readiness: "http" | "tcp";
}): Effect.fn.Return<
SshTunnelEntry,
SshCommandError | SshInvalidTargetError | SshReadinessError,
@@ -969,7 +1013,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
"-n",
"-N",
"-L",
`${input.localPort}:127.0.0.1:${input.remotePort}`,
`127.0.0.1:${input.localPort}:127.0.0.1:${input.remotePort}`,
hostSpec,
];
const sshCommand = yield* resolveSshCommand;
@@ -1068,74 +1112,87 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
}).pipe(Effect.andThen(Effect.fail(error)));
}),
);
yield* Effect.raceFirst(
waitForHttpReady({
baseUrl: input.httpBaseUrl,
timeoutMs: SSH_READY_TIMEOUT_MS,
}),
exitFailure,
).pipe(
Effect.tap(() =>
Effect.logInfo("ssh.tunnel.ready", {
...sshTargetLogFields(input.resolvedTarget),
command: tunnelCommand,
pid: child.pid,
localPort: input.localPort,
remotePort: input.remotePort,
httpBaseUrl: input.httpBaseUrl,
}),
),
Effect.tapError((cause) =>
Effect.gen(function* () {
const net = yield* NetService.NetService;
const processRunningExit = yield* Effect.exit(child.isRunning);
const localPortAvailableExit = yield* Effect.exit(
net.canListenOnHost(input.localPort, "127.0.0.1"),
);
const remoteLogTailExit = yield* Effect.exit(
readRemoteServerLogTail(input.resolvedTarget, input.authOptions),
);
const processRunning = Exit.isSuccess(processRunningExit) ? processRunningExit.value : null;
const localPortAvailable = Exit.isSuccess(localPortAvailableExit)
? localPortAvailableExit.value
: null;
const remoteLogTail = Exit.isSuccess(remoteLogTailExit)
? remoteLogTailExit.value || null
: null;
yield* Effect.logWarning("ssh.tunnel.ready.failed", {
const observeReadiness = <R>(
readiness: Effect.Effect<void, SshCommandError | SshReadinessError, R>,
) =>
readiness.pipe(
Effect.tap(() =>
Effect.logInfo("ssh.tunnel.ready", {
...sshTargetLogFields(input.resolvedTarget),
command: tunnelCommand,
pid: child.pid,
processRunning,
...(Exit.isSuccess(processRunningExit)
? {}
: { processRunningError: processRunningExit.cause }),
localPort: input.localPort,
localPortListening: localPortAvailable === null ? null : !localPortAvailable,
remotePort: input.remotePort,
httpBaseUrl: input.httpBaseUrl,
...(Exit.isSuccess(localPortAvailableExit)
? {}
: { localPortProbeError: localPortAvailableExit.cause }),
...(remoteLogTail === null ? {} : { remoteLogTail }),
...(Exit.isSuccess(remoteLogTailExit)
? {}
: { remoteLogTailError: remoteLogTailExit.cause }),
cause,
});
}),
),
Effect.onExit((exit) =>
Exit.isSuccess(exit)
? Effect.void
: child
.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
})
.pipe(Effect.ignore),
),
);
}),
),
Effect.tapError((cause) =>
Effect.gen(function* () {
const net = yield* NetService.NetService;
const processRunningExit = yield* Effect.exit(child.isRunning);
const localPortAvailableExit = yield* Effect.exit(
net.canListenOnHost(input.localPort, "127.0.0.1"),
);
const remoteLogTailExit =
input.readiness === "http"
? yield* Effect.exit(readRemoteServerLogTail(input.resolvedTarget, input.authOptions))
: Exit.succeed("");
const processRunning = Exit.isSuccess(processRunningExit)
? processRunningExit.value
: null;
const localPortAvailable = Exit.isSuccess(localPortAvailableExit)
? localPortAvailableExit.value
: null;
const remoteLogTail = Exit.isSuccess(remoteLogTailExit)
? remoteLogTailExit.value || null
: null;
yield* Effect.logWarning("ssh.tunnel.ready.failed", {
...sshTargetLogFields(input.resolvedTarget),
command: tunnelCommand,
pid: child.pid,
processRunning,
...(Exit.isSuccess(processRunningExit)
? {}
: { processRunningError: processRunningExit.cause }),
localPort: input.localPort,
localPortListening: localPortAvailable === null ? null : !localPortAvailable,
remotePort: input.remotePort,
httpBaseUrl: input.httpBaseUrl,
...(Exit.isSuccess(localPortAvailableExit)
? {}
: { localPortProbeError: localPortAvailableExit.cause }),
...(remoteLogTail === null ? {} : { remoteLogTail }),
...(Exit.isSuccess(remoteLogTailExit)
? {}
: { remoteLogTailError: remoteLogTailExit.cause }),
cause,
});
}),
),
Effect.onExit((exit) =>
Exit.isSuccess(exit)
? Effect.void
: child
.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
})
.pipe(Effect.ignore),
),
);
if (input.readiness === "http") {
yield* observeReadiness(
Effect.raceFirst(
waitForHttpReady({
baseUrl: input.httpBaseUrl,
timeoutMs: SSH_READY_TIMEOUT_MS,
}),
exitFailure,
),
);
} else {
yield* observeReadiness(Effect.raceFirst(waitForTcpForwardReady(input.localPort), exitFailure));
}
return tunnelEntry;
});
@@ -1148,6 +1205,10 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
string,
Deferred.Deferred<SshTunnelEntry, SshEnvironmentEffectError>
>();
const portForwards = new Map<string, SshPortForwardEntry>();
const pendingPortForwards = new Map<string, PendingSshPortForward>();
const portForwardLeases = new Map<string, SshPortForwardEntry>();
let nextPortForwardLeaseId = 0;
const authSecrets = new Map<string, string>();
const closeTunnelEntry = Effect.fn("ssh/tunnel.closeTunnelEntry")(function* (
@@ -1180,11 +1241,60 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
yield* Deferred.fail(pending, makeSshTunnelCancelledError(target)).pipe(Effect.ignore);
});
const closePortForwardEntry = Effect.fn("ssh/tunnel.closePortForwardEntry")(function* (
entry: SshPortForwardEntry,
) {
yield* Effect.logDebug("ssh.portForward.close.start", {
...sshTargetLogFields(entry.target),
key: entry.key,
localPort: entry.localPort,
remotePort: entry.remotePort,
leases: entry.leases.size,
});
if (portForwards.get(entry.key) === entry) {
portForwards.delete(entry.key);
}
for (const leaseId of entry.leases) {
portForwardLeases.delete(leaseId);
}
entry.leases.clear();
yield* Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
yield* Effect.logInfo("ssh.portForward.close.succeeded", {
...sshTargetLogFields(entry.target),
key: entry.key,
localPort: entry.localPort,
remotePort: entry.remotePort,
});
});
const cancelPendingPortForward = Effect.fn("ssh/tunnel.cancelPendingPortForward")(function* (
key: string,
target: DesktopSshEnvironmentTarget,
) {
const pending = pendingPortForwards.get(key);
if (!pending) {
return;
}
pendingPortForwards.delete(key);
yield* Deferred.fail(pending.deferred, makeSshTunnelCancelledError(target)).pipe(Effect.ignore);
});
yield* Scope.addFinalizer(
managerScope,
Effect.sync(() => [...tunnels.values()]).pipe(
Effect.flatMap((entries) =>
Effect.forEach(entries, closeTunnelEntry, { concurrency: "unbounded" }),
Effect.sync(() => ({
tunnels: [...tunnels.values()],
portForwards: [...portForwards.values()],
})).pipe(
Effect.flatMap(({ tunnels: tunnelEntries, portForwards: portForwardEntries }) =>
Effect.all(
[
Effect.forEach(tunnelEntries, closeTunnelEntry, { concurrency: "unbounded" }),
Effect.forEach(portForwardEntries, closePortForwardEntry, {
concurrency: "unbounded",
}),
],
{ concurrency: "unbounded" },
),
),
Effect.ignore,
),
@@ -1301,6 +1411,17 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
});
});
const resolveManagerTarget = Effect.fn("ssh/tunnel.resolveManagerTarget")(function* (
target: DesktopSshEnvironmentTarget,
) {
const baseResolved = yield* resolveSshTarget(target.alias || target.hostname);
return {
...baseResolved,
...(target.username !== null ? { username: target.username } : {}),
...(target.port !== null ? { port: target.port } : {}),
} satisfies DesktopSshEnvironmentTarget;
});
const createTunnelEntry = Effect.fn("ssh/tunnel.ensureTunnelEntry.create")(function* (input: {
readonly key: string;
readonly resolvedTarget: DesktopSshEnvironmentTarget;
@@ -1347,6 +1468,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
wsBaseUrl,
authOptions,
remoteServerKind: remoteLaunch.remoteServerKind,
readiness: "http",
}).pipe(Effect.provideService(Scope.Scope, entryScope)),
}).pipe(
Effect.onExit((exit) =>
@@ -1486,6 +1608,186 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
);
});
const createPortForwardEntry = Effect.fn("ssh/tunnel.portForward.create")(function* (input: {
readonly key: string;
readonly connectionKey: string;
readonly resolvedTarget: DesktopSshEnvironmentTarget;
readonly remotePort: number;
}): Effect.fn.Return<
SshPortForwardEntry,
SshEnvironmentEffectError,
SshEnvironmentEffectContext
> {
const localPort = yield* reserveLocalTunnelPort();
const httpBaseUrl = `http://127.0.0.1:${localPort}/`;
const wsBaseUrl = `ws://127.0.0.1:${localPort}/`;
const entryScope = yield* Scope.make("sequential");
const tunnelEntry = yield* runWithSshAuth({
key: input.connectionKey,
target: input.resolvedTarget,
operation: (authOptions) =>
startSshTunnel({
key: input.key,
resolvedTarget: input.resolvedTarget,
remotePort: input.remotePort,
localPort,
httpBaseUrl,
wsBaseUrl,
authOptions,
remoteServerKind: null,
readiness: "tcp",
}).pipe(Effect.provideService(Scope.Scope, entryScope)),
}).pipe(
Effect.onExit((exit) =>
Exit.isSuccess(exit) ? Effect.void : Scope.close(entryScope, Exit.void).pipe(Effect.ignore),
),
);
const entry: SshPortForwardEntry = {
...tunnelEntry,
connectionKey: input.connectionKey,
leases: new Set(),
};
yield* Scope.addFinalizer(
entryScope,
Effect.gen(function* () {
if (portForwards.get(entry.key) === entry) {
portForwards.delete(entry.key);
}
for (const leaseId of entry.leases) {
portForwardLeases.delete(leaseId);
}
entry.leases.clear();
yield* entry.process
.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
})
.pipe(Effect.ignore);
}),
);
yield* Effect.logInfo("ssh.portForward.create.succeeded", {
...sshTargetLogFields(entry.target),
key: entry.key,
localPort: entry.localPort,
remotePort: entry.remotePort,
});
return entry;
});
const ensurePortForwardEntry = Effect.fn("ssh/tunnel.portForward.ensure")(function* (input: {
readonly key: string;
readonly connectionKey: string;
readonly resolvedTarget: DesktopSshEnvironmentTarget;
readonly remotePort: number;
}): Effect.fn.Return<
SshPortForwardEntry,
SshEnvironmentEffectError,
SshEnvironmentEffectContext
> {
const existing = portForwards.get(input.key);
if (existing !== undefined) {
const running = yield* existing.process.isRunning.pipe(Effect.orElseSucceed(() => false));
if (running) {
return existing;
}
yield* closePortForwardEntry(existing);
}
const pending = pendingPortForwards.get(input.key);
if (pending !== undefined) {
return yield* Deferred.await(pending.deferred);
}
const deferred = yield* Deferred.make<SshPortForwardEntry, SshEnvironmentEffectError>();
const pendingEntry: PendingSshPortForward = {
deferred,
};
pendingPortForwards.set(input.key, pendingEntry);
return yield* createPortForwardEntry(input).pipe(
Effect.flatMap((entry) => {
if (pendingPortForwards.get(input.key) !== pendingEntry) {
return closePortForwardEntry(entry).pipe(
Effect.andThen(Effect.fail(makeSshTunnelCancelledError(input.resolvedTarget))),
);
}
portForwards.set(input.key, entry);
return Effect.succeed(entry);
}),
Effect.tapError((cause) =>
Effect.logWarning("ssh.portForward.create.failed", {
...sshTargetLogFields(input.resolvedTarget),
key: input.key,
remotePort: input.remotePort,
cause,
}),
),
Effect.onExit((exit) =>
Effect.sync(() => {
if (pendingPortForwards.get(input.key) === pendingEntry) {
pendingPortForwards.delete(input.key);
}
}).pipe(Effect.andThen(Deferred.done(deferred, exit))),
),
);
});
const acquirePortForward = Effect.fn("ssh/tunnel.acquirePortForward")(function* (
target: DesktopSshEnvironmentTarget,
remotePort: number,
): Effect.fn.Return<SshPortForwardLease, SshEnvironmentEffectError, SshEnvironmentEffectContext> {
if (!Number.isInteger(remotePort) || remotePort < 1 || remotePort > 65_535) {
return yield* new SshInvalidTargetError({
message: `Invalid remote SSH port: ${remotePort}.`,
});
}
const resolvedTarget = yield* resolveManagerTarget(target);
const connectionKey = targetConnectionKey(resolvedTarget);
const key = `${connectionKey}\0${remotePort}`;
const entry = yield* ensurePortForwardEntry({
key,
connectionKey,
resolvedTarget,
remotePort,
});
nextPortForwardLeaseId += 1;
const leaseId = `ssh-port-forward-${nextPortForwardLeaseId}`;
entry.leases.add(leaseId);
portForwardLeases.set(leaseId, entry);
yield* Effect.logInfo("ssh.portForward.acquired", {
...sshTargetLogFields(entry.target),
leaseId,
localPort: entry.localPort,
remotePort: entry.remotePort,
references: entry.leases.size,
});
return {
leaseId,
localPort: entry.localPort,
remotePort: entry.remotePort,
};
});
const releasePortForward = Effect.fn("ssh/tunnel.releasePortForward")(function* (
leaseId: string,
) {
const entry = portForwardLeases.get(leaseId);
if (entry === undefined) {
return;
}
portForwardLeases.delete(leaseId);
entry.leases.delete(leaseId);
yield* Effect.logInfo("ssh.portForward.released", {
...sshTargetLogFields(entry.target),
leaseId,
localPort: entry.localPort,
remotePort: entry.remotePort,
references: entry.leases.size,
});
if (entry.leases.size === 0) {
yield* closePortForwardEntry(entry);
}
});
const ensureEnvironment = Effect.fn("ssh/tunnel.ensureEnvironment")(function* (
target: DesktopSshEnvironmentTarget,
requestOptions?: { readonly issuePairingToken?: boolean },
@@ -1498,12 +1800,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
...sshTargetLogFields(target),
issuePairingToken: requestOptions?.issuePairingToken === true,
});
const baseResolved = yield* resolveSshTarget(target.alias || target.hostname);
const resolvedTarget: DesktopSshEnvironmentTarget = {
...baseResolved,
...(target.username !== null ? { username: target.username } : {}),
...(target.port !== null ? { port: target.port } : {}),
};
const resolvedTarget = yield* resolveManagerTarget(target);
const key = targetConnectionKey(resolvedTarget);
yield* Effect.logDebug("ssh.environment.target.resolved", {
...sshTargetLogFields(resolvedTarget),
@@ -1554,20 +1851,32 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
target: DesktopSshEnvironmentTarget,
): Effect.fn.Return<void, SshEnvironmentEffectError, SshEnvironmentEffectContext> {
yield* Effect.logInfo("ssh.environment.disconnect.start", sshTargetLogFields(target));
const baseResolved = yield* resolveSshTarget(target.alias || target.hostname);
const resolvedTarget: DesktopSshEnvironmentTarget = {
...baseResolved,
...(target.username !== null ? { username: target.username } : {}),
...(target.port !== null ? { port: target.port } : {}),
};
const resolvedTarget = yield* resolveManagerTarget(target);
const key = targetConnectionKey(resolvedTarget);
const forwardEntries = [...portForwards.values()].filter(
(entry) => entry.connectionKey === key,
);
const pendingForwardKeys = [...pendingPortForwards.keys()].filter((forwardKey) =>
forwardKey.startsWith(`${key}\0`),
);
const entry = tunnels.get(key) ?? null;
yield* Effect.logDebug("ssh.environment.disconnect.targetResolved", {
...sshTargetLogFields(resolvedTarget),
key,
hasTunnel: entry !== null,
hasPendingTunnel: pendingTunnelEntries.has(key),
portForwards: forwardEntries.length,
pendingPortForwards: pendingForwardKeys.length,
});
yield* Effect.forEach(forwardEntries, closePortForwardEntry, {
concurrency: "unbounded",
discard: true,
});
yield* Effect.forEach(
pendingForwardKeys,
(forwardKey) => cancelPendingPortForward(forwardKey, resolvedTarget),
{ concurrency: "unbounded", discard: true },
);
if (entry !== null) {
yield* closeTunnelEntry(entry);
}
@@ -1585,7 +1894,12 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
});
});
return SshEnvironmentManager.of({ ensureEnvironment, disconnectEnvironment });
return SshEnvironmentManager.of({
ensureEnvironment,
disconnectEnvironment,
acquirePortForward,
releasePortForward,
});
});
/**
+1
View File
@@ -24,6 +24,7 @@ import {
const emptyConfigLayer = ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }));
const netServiceLayer = Layer.succeed(NetService.NetService, {
hasListenerOnHost: () => Effect.succeed(false),
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(49_152),