Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e371cc280b | ||
|
|
1690e15f58 | ||
|
|
477795697d | ||
|
|
a23b83314e | ||
|
|
ce90563709 | ||
|
|
31e68229d6 | ||
|
|
1db585878e | ||
|
|
56e57de947 | ||
|
|
3a0623f1cd | ||
|
|
cd91ec75f3 | ||
|
|
d4ba9e9618 | ||
|
|
c1792bc9a6 | ||
|
|
1b4317ec35 | ||
|
|
f452d63fef | ||
|
|
18a49abcec | ||
|
|
85d5df6256 | ||
|
|
b5b769dddf | ||
|
|
3c7862edd7 | ||
|
|
d8fe3d72c8 | ||
|
|
70ec39ae80 | ||
|
|
3d9e8dea7d | ||
|
|
f7c422d581 | ||
|
|
dd739c880d | ||
|
|
6c6740e381 | ||
|
|
29150b5736 | ||
|
|
07c6d70b91 | ||
|
|
50bc18b208 | ||
|
|
63d42a5e58 | ||
|
|
9b43123ba2 | ||
|
|
17fb0e4a9a | ||
|
|
43e8bbd7ae | ||
|
|
52c77c1ec4 | ||
|
|
d6eb386e3d |
No files matched your search
@@ -20,13 +20,16 @@
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"electron": "41.5.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron-updater": "^6.6.2",
|
||||
"playwright-core": "1.60.0",
|
||||
"react-grab": "^0.1.32"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"electron-builder": "26.8.1",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { compile } from "tailwindcss";
|
||||
|
||||
const directory = dirname(fileURLToPath(import.meta.url));
|
||||
const appRoot = join(directory, "..");
|
||||
const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
|
||||
const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
|
||||
const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
|
||||
const require = createRequire(import.meta.url);
|
||||
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
|
||||
|
||||
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
|
||||
readFile(sourcePath, "utf8"),
|
||||
readFile(preloadPath, "utf8"),
|
||||
readFile(join(tailwindRoot, "theme.css"), "utf8"),
|
||||
readFile(join(tailwindRoot, "preflight.css"), "utf8"),
|
||||
]);
|
||||
|
||||
const candidates = new Set(
|
||||
Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
|
||||
);
|
||||
const compilerInput = [
|
||||
themeSource,
|
||||
preflightSource,
|
||||
annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
|
||||
].join("\n");
|
||||
const compiler = await compile(compilerInput, { base: appRoot });
|
||||
const css = compiler.build([...candidates]);
|
||||
const encodedCss = `'${css
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("'", "\\'")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\n", "\\n")}'`;
|
||||
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
|
||||
|
||||
await writeFile(outputPath, moduleSource);
|
||||
@@ -1,8 +1,13 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import {
|
||||
desktopDir,
|
||||
resolveDevProtocolClient,
|
||||
resolveElectronLaunchCommand,
|
||||
} from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
@@ -29,6 +34,8 @@ const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
@@ -53,7 +60,7 @@ const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
if (hostPlatform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -61,7 +68,7 @@ function killChildTreeByPid(pid, signal) {
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -79,7 +86,8 @@ function startApp() {
|
||||
const launchArgs = devProtocolClient
|
||||
? electronArgs
|
||||
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
|
||||
const app = spawn(resolveElectronPath(), launchArgs, {
|
||||
const electronCommand = resolveElectronLaunchCommand(launchArgs);
|
||||
const app = spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
@@ -189,7 +197,7 @@ function startWatchers() {
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
|
||||
@@ -30,9 +31,11 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 10;
|
||||
const LAUNCHER_VERSION = 11;
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
function resolveDevelopmentProtocolCallbackPort() {
|
||||
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
|
||||
@@ -295,7 +298,11 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
// verbatimSymlinks keeps the framework's relative symlinks intact
|
||||
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
|
||||
// rewrites them to absolute paths into node_modules, which escape the
|
||||
// bundle and crash sandboxed helper processes (icudtl.dat not found).
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
@@ -307,21 +314,54 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
if (hostPlatform !== "linux") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const sandboxPath = join(dirname(electronBinaryPath), "chrome-sandbox");
|
||||
try {
|
||||
const sandboxStat = statSync(sandboxPath);
|
||||
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
console.warn(
|
||||
"[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
|
||||
);
|
||||
return ["--no-sandbox"];
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
ensureElectronRuntime();
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
|
||||
export function resolveElectronLaunchCommand(args = []) {
|
||||
const electronPath = resolveElectronPath();
|
||||
return {
|
||||
electronPath,
|
||||
args: [...resolveLinuxSandboxArgs(electronPath), ...args],
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (process.platform !== "darwin" || !isDevelopment) {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { arch, platform, tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostPlatform = platform();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostArch = arch();
|
||||
|
||||
function getPlatformPath() {
|
||||
switch (process.platform) {
|
||||
switch (hostPlatform) {
|
||||
case "darwin":
|
||||
return "Electron.app/Contents/MacOS/Electron";
|
||||
case "freebsd":
|
||||
@@ -17,12 +21,12 @@ function getPlatformPath() {
|
||||
case "win32":
|
||||
return "electron.exe";
|
||||
default:
|
||||
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
|
||||
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureExecutable(filePath) {
|
||||
if (process.platform !== "win32") {
|
||||
if (hostPlatform !== "win32") {
|
||||
chmodSync(filePath, 0o755);
|
||||
}
|
||||
}
|
||||
@@ -39,7 +43,7 @@ function repairPathFile(electronDir, platformPath) {
|
||||
function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
const paths = [join(electronDir, "dist", platformPath)];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
paths.push(
|
||||
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
join(
|
||||
@@ -58,7 +62,7 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function isMachO(filePath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -76,7 +80,7 @@ function missingRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function invalidRuntimePaths(electronDir, platformPath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -111,16 +115,16 @@ function runChecked(command, args) {
|
||||
|
||||
function installElectronRuntime(electronDir, version) {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
|
||||
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
|
||||
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
|
||||
try {
|
||||
runChecked("curl", [
|
||||
"-fsSL",
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
|
||||
"-o",
|
||||
zipPath,
|
||||
]);
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
|
||||
} else {
|
||||
runChecked("python3", [
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
const child = spawn(electronBin, [mainJs], {
|
||||
const electronCommand = resolveElectronLaunchCommand([mainJs]);
|
||||
const child = spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
|
||||
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
|
||||
const child = spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -176,7 +176,7 @@ const bootstrap = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
yield* installDesktopIpcHandlers;
|
||||
yield* installDesktopIpcHandlers();
|
||||
yield* logBootstrapInfo("bootstrap ipc handlers registered");
|
||||
|
||||
if (!(yield* Ref.get(state.quitting))) {
|
||||
|
||||
@@ -49,7 +49,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem
|
||||
.exists(developmentDockIconPath)
|
||||
|
||||
@@ -59,6 +59,7 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
@@ -89,6 +90,7 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.isDevelopment, false);
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -49,6 +49,7 @@ export interface DesktopEnvironmentShape {
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
@@ -183,6 +184,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
|
||||
serverSettingsPath: path.join(stateDir, "settings.json"),
|
||||
logDir: path.join(stateDir, "logs"),
|
||||
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
|
||||
rootDir,
|
||||
appRoot,
|
||||
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export interface ElectronMenuPosition {
|
||||
readonly x: number;
|
||||
@@ -79,109 +80,113 @@ const normalizePosition = (
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
|
||||
export const layer = Layer.sync(ElectronMenu, () => {
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
export const layer = Layer.effect(
|
||||
ElectronMenu,
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (process.platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
return destructiveMenuIconCache;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
}
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
return destructiveMenuIconCache;
|
||||
};
|
||||
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
complete: (selectedItemId: Option.Option<string>) => void,
|
||||
): Electron.MenuItemConstructorOptions[] => {
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
const itemOption: Electron.MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children, complete);
|
||||
} else {
|
||||
itemOption.click = () => complete(Option.some(item.id));
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (Option.isSome(destructiveIcon)) {
|
||||
itemOption.icon = destructiveIcon.value;
|
||||
}
|
||||
}
|
||||
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
return template;
|
||||
};
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
if (normalizedItems.length === 0) {
|
||||
resume(Effect.succeed(Option.none()));
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
});
|
||||
let completed = false;
|
||||
const complete = (selectedItemId: Option.Option<string>) => {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -6,6 +6,7 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
|
||||
readonly cause: unknown;
|
||||
@@ -37,6 +38,7 @@ export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWind
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
@@ -98,7 +100,7 @@ const make = Effect.gen(function* () {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
|
||||
@@ -48,9 +48,11 @@ import {
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
@@ -92,4 +94,7 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
yield* ipc.handle(downloadUpdate);
|
||||
yield* ipc.handle(installUpdate);
|
||||
yield* ipc.handle(checkForUpdate);
|
||||
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
|
||||
for (const previewMethod of PreviewIpc.methods) {
|
||||
yield* ipc.handle(previewMethod);
|
||||
}
|
||||
});
|
||||
@@ -39,3 +39,38 @@ export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mod
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
|
||||
export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate";
|
||||
export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back";
|
||||
export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward";
|
||||
export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh";
|
||||
export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
|
||||
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
|
||||
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
|
||||
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
|
||||
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
|
||||
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
|
||||
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
|
||||
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
|
||||
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
|
||||
export const PREVIEW_REVEAL_ARTIFACT_CHANNEL = "desktop:preview-reveal-artifact";
|
||||
export const PREVIEW_COPY_ARTIFACT_CHANNEL = "desktop:preview-copy-artifact";
|
||||
export const PREVIEW_AUTOMATION_STATUS_CHANNEL = "desktop:preview-automation-status";
|
||||
export const PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL = "desktop:preview-automation-snapshot";
|
||||
export const PREVIEW_AUTOMATION_CLICK_CHANNEL = "desktop:preview-automation-click";
|
||||
export const PREVIEW_AUTOMATION_TYPE_CHANNEL = "desktop:preview-automation-type";
|
||||
export const PREVIEW_AUTOMATION_PRESS_CHANNEL = "desktop:preview-automation-press";
|
||||
export const PREVIEW_AUTOMATION_SCROLL_CHANNEL = "desktop:preview-automation-scroll";
|
||||
export const PREVIEW_AUTOMATION_EVALUATE_CHANNEL = "desktop:preview-automation-evaluate";
|
||||
export const PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL = "desktop:preview-automation-wait-for";
|
||||
export const PREVIEW_RECORDING_START_CHANNEL = "desktop:preview-recording-start";
|
||||
export const PREVIEW_RECORDING_STOP_CHANNEL = "desktop:preview-recording-stop";
|
||||
export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
|
||||
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
|
||||
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
|
||||
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
|
||||
@@ -0,0 +1,54 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import * as PreviewIpc from "./preview.ts";
|
||||
|
||||
const { fromPartition } = vi.hoisted(() => ({
|
||||
fromPartition: vi.fn(() => {
|
||||
throw new Error("Session can only be received when app is ready");
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
BrowserWindow: {
|
||||
getAllWindows: vi.fn(() => []),
|
||||
},
|
||||
session: {
|
||||
fromPartition,
|
||||
},
|
||||
webContents: {
|
||||
fromId: vi.fn(() => null),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("preview IPC methods", () => {
|
||||
beforeEach(() => {
|
||||
fromPartition.mockClear();
|
||||
});
|
||||
|
||||
it("does not access the Electron session while the module loads", async () => {
|
||||
await expect(import("./preview.ts")).resolves.toBeDefined();
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
|
||||
Effect.map(
|
||||
PreviewIpc.registerWebview
|
||||
.handler({ tabId: "tab-1", webContentsId: 0 })
|
||||
.pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
|
||||
(exit) => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Cause.findErrorOption(exit.cause);
|
||||
expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,377 @@
|
||||
import {
|
||||
DesktopPreviewAnnotationThemeInputSchema,
|
||||
DesktopPreviewArtifactInputSchema,
|
||||
DesktopPreviewAutomationClickInputSchema,
|
||||
DesktopPreviewAutomationEvaluateInputSchema,
|
||||
DesktopPreviewAutomationPressInputSchema,
|
||||
DesktopPreviewAutomationScrollInputSchema,
|
||||
DesktopPreviewAutomationTypeInputSchema,
|
||||
DesktopPreviewAutomationWaitForInputSchema,
|
||||
DesktopPreviewConfigInputSchema,
|
||||
DesktopPreviewNavigateInputSchema,
|
||||
DesktopPreviewRecordingArtifactSchema,
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { BrowserWindow } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(channel, ...args);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const installPreviewEventForwarding = Effect.fn(
|
||||
"desktop.ipc.preview.installEventForwarding",
|
||||
)(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.subscribeStateChanges((tabId, state) => {
|
||||
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
|
||||
});
|
||||
yield* manager.subscribeRecordingFrames((frame) => {
|
||||
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
|
||||
});
|
||||
yield* manager.subscribePointerEvents((event) => {
|
||||
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
|
||||
});
|
||||
});
|
||||
|
||||
export const createTab = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.createTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const closeTab = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.closeTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const registerWebview = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
|
||||
payload: DesktopPreviewRegisterWebviewInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.registerWebview(tabId, webContentsId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const navigate = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
|
||||
payload: DesktopPreviewNavigateInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.navigate(tabId, url);
|
||||
}),
|
||||
});
|
||||
|
||||
const tabMethod = (
|
||||
channel: string,
|
||||
name: string,
|
||||
invoke: (
|
||||
manager: PreviewManager.PreviewManagerShape,
|
||||
tabId: string,
|
||||
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
|
||||
) =>
|
||||
makeIpcMethod({
|
||||
channel,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn(name)(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* invoke(manager, tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const goBack = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_BACK_CHANNEL,
|
||||
"desktop.ipc.preview.goBack",
|
||||
(manager, tabId) => manager.goBack(tabId),
|
||||
);
|
||||
export const goForward = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
|
||||
"desktop.ipc.preview.goForward",
|
||||
(manager, tabId) => manager.goForward(tabId),
|
||||
);
|
||||
export const refresh = tabMethod(
|
||||
IpcChannels.PREVIEW_REFRESH_CHANNEL,
|
||||
"desktop.ipc.preview.refresh",
|
||||
(manager, tabId) => manager.refresh(tabId),
|
||||
);
|
||||
export const zoomIn = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
|
||||
"desktop.ipc.preview.zoomIn",
|
||||
(manager, tabId) => manager.zoomIn(tabId),
|
||||
);
|
||||
export const zoomOut = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
|
||||
"desktop.ipc.preview.zoomOut",
|
||||
(manager, tabId) => manager.zoomOut(tabId),
|
||||
);
|
||||
export const resetZoom = tabMethod(
|
||||
IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
|
||||
"desktop.ipc.preview.resetZoom",
|
||||
(manager, tabId) => manager.resetZoom(tabId),
|
||||
);
|
||||
export const hardReload = tabMethod(
|
||||
IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
(manager, tabId) => manager.openDevTools(tabId),
|
||||
);
|
||||
export const cancelPickElement = tabMethod(
|
||||
IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
|
||||
"desktop.ipc.preview.cancelPickElement",
|
||||
(manager, tabId) => manager.cancelPickElement(tabId),
|
||||
);
|
||||
export const startRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
|
||||
"desktop.ipc.preview.startRecording",
|
||||
(manager, tabId) => manager.startRecording(tabId),
|
||||
);
|
||||
export const stopRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
|
||||
"desktop.ipc.preview.stopRecording",
|
||||
(manager, tabId) => manager.stopRecording(tabId),
|
||||
);
|
||||
|
||||
export const clearCookies = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCookies();
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCache = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCache();
|
||||
}),
|
||||
});
|
||||
|
||||
export const getPreviewConfig = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
|
||||
payload: DesktopPreviewConfigInputSchema,
|
||||
result: DesktopPreviewWebviewConfigSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.getBrowserSession(environmentId);
|
||||
return {
|
||||
partition: yield* manager.getBrowserPartition(environmentId),
|
||||
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
|
||||
preloadUrl: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
export const setAnnotationTheme = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
|
||||
payload: DesktopPreviewAnnotationThemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setAnnotationTheme(theme);
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickElement = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const captureScreenshot = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: DesktopPreviewScreenshotArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.captureScreenshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const revealArtifact = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.revealArtifact(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const copyArtifactToClipboard = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.copyArtifactToClipboard(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationStatus = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationStatus,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationStatus(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationSnapshot = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationSnapshot,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationSnapshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationClick = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
|
||||
payload: DesktopPreviewAutomationClickInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationClick(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationType = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationTypeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationType(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationPress = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
|
||||
payload: DesktopPreviewAutomationPressInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationPress(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationScroll = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
|
||||
payload: DesktopPreviewAutomationScrollInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationScroll(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationEvaluate = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationEvaluateInputSchema,
|
||||
result: Schema.Unknown,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationEvaluate(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationWaitFor = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
|
||||
payload: DesktopPreviewAutomationWaitForInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationWaitFor(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const saveRecording = makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
|
||||
payload: DesktopPreviewRecordingSaveInputSchema,
|
||||
result: DesktopPreviewRecordingArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.saveRecording(tabId, mimeType, data);
|
||||
}),
|
||||
});
|
||||
|
||||
export const methods = [
|
||||
createTab,
|
||||
closeTab,
|
||||
registerWebview,
|
||||
navigate,
|
||||
goBack,
|
||||
goForward,
|
||||
refresh,
|
||||
zoomIn,
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
getPreviewConfig,
|
||||
setAnnotationTheme,
|
||||
pickElement,
|
||||
cancelPickElement,
|
||||
captureScreenshot,
|
||||
revealArtifact,
|
||||
copyArtifactToClipboard,
|
||||
automationStatus,
|
||||
automationSnapshot,
|
||||
automationClick,
|
||||
automationType,
|
||||
automationPress,
|
||||
automationScroll,
|
||||
automationEvaluate,
|
||||
automationWaitFor,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
saveRecording,
|
||||
] as const;
|
||||
@@ -9,6 +9,7 @@ import * as Option from "effect/Option";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import serverPackageJson from "../../server/package.json" with { type: "json" };
|
||||
@@ -44,6 +45,8 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
@@ -51,11 +54,13 @@ const desktopEnvironmentLayer = Layer.unwrap(
|
||||
const metadata = yield* Effect.service(ElectronApp.ElectronApp).pipe(
|
||||
Effect.flatMap((app) => app.metadata),
|
||||
);
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const processArch = yield* HostProcessArchitecture;
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: __dirname,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
platform,
|
||||
processArch,
|
||||
...metadata,
|
||||
});
|
||||
}),
|
||||
@@ -127,7 +132,15 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
|
||||
const desktopPreviewLayer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(PreviewBrowserSession.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
Layer.provideMerge(desktopServerExposureLayer),
|
||||
Layer.provideMerge(desktopPreviewLayer),
|
||||
);
|
||||
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import type {
|
||||
DesktopBridge,
|
||||
DesktopPreviewPointerEvent,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewTabState,
|
||||
} from "@t3tools/contracts";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
|
||||
import * as IpcChannels from "./ipc/channels.ts";
|
||||
@@ -141,4 +146,97 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
preview: {
|
||||
createTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, { tabId }),
|
||||
closeTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, { tabId }),
|
||||
registerWebview: (tabId, webContentsId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, { tabId, webContentsId }),
|
||||
navigate: (tabId, url) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, { tabId, url }),
|
||||
goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }),
|
||||
goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }),
|
||||
refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }),
|
||||
zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }),
|
||||
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
|
||||
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
|
||||
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
|
||||
openDevTools: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
|
||||
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
|
||||
clearCache: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL),
|
||||
getPreviewConfig: (environmentId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId }),
|
||||
setAnnotationTheme: (theme) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
|
||||
pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }),
|
||||
cancelPickElement: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, { tabId }),
|
||||
captureScreenshot: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, { tabId }),
|
||||
revealArtifact: (path) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, { path }),
|
||||
copyArtifactToClipboard: (path) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, { path }),
|
||||
recording: {
|
||||
startScreencast: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_START_CHANNEL, { tabId }),
|
||||
stopScreencast: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL, { tabId }),
|
||||
save: (tabId, mimeType, data) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, {
|
||||
tabId,
|
||||
mimeType,
|
||||
data,
|
||||
}),
|
||||
onFrame: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, frame: unknown) => {
|
||||
if (typeof frame !== "object" || frame === null) return;
|
||||
listener(frame as DesktopPreviewRecordingFrame);
|
||||
};
|
||||
ipcRenderer.on(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
|
||||
},
|
||||
},
|
||||
automation: {
|
||||
status: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, { tabId }),
|
||||
snapshot: (tabId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL, { tabId }),
|
||||
click: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL, { tabId, input }),
|
||||
type: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL, { tabId, input }),
|
||||
press: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL, { tabId, input }),
|
||||
scroll: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL, { tabId, input }),
|
||||
evaluate: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL, { tabId, input }),
|
||||
waitFor: (tabId, input) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL, { tabId, input }),
|
||||
},
|
||||
onStateChange: (listener) => {
|
||||
const wrappedListener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
tabId: unknown,
|
||||
state: unknown,
|
||||
) => {
|
||||
if (typeof tabId !== "string" || typeof state !== "object" || state === null) return;
|
||||
listener(tabId, state as DesktopPreviewTabState);
|
||||
};
|
||||
ipcRenderer.on(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
|
||||
},
|
||||
onPointerEvent: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, pointerEvent: unknown) => {
|
||||
if (typeof pointerEvent !== "object" || pointerEvent === null) return;
|
||||
listener(pointerEvent as DesktopPreviewPointerEvent);
|
||||
};
|
||||
ipcRenderer.on(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
|
||||
},
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
@@ -0,0 +1 @@
|
||||
import "./preview/PickPreload.ts";
|
||||
@@ -0,0 +1,68 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme inline {
|
||||
--font-sans: var(--t3-font-sans);
|
||||
--font-mono: var(--t3-font-mono);
|
||||
--color-background: var(--t3-background);
|
||||
--color-foreground: var(--t3-foreground);
|
||||
--color-popover: var(--t3-popover);
|
||||
--color-popover-foreground: var(--t3-popover-foreground);
|
||||
--color-primary: var(--t3-primary);
|
||||
--color-primary-foreground: var(--t3-primary-foreground);
|
||||
--color-muted: var(--t3-muted);
|
||||
--color-muted-foreground: var(--t3-muted-foreground);
|
||||
--color-accent: var(--t3-accent);
|
||||
--color-accent-foreground: var(--t3-accent-foreground);
|
||||
--color-border: var(--t3-border);
|
||||
--color-input: var(--t3-input);
|
||||
--color-ring: var(--t3-ring);
|
||||
--radius-sm: calc(var(--t3-radius) - 4px);
|
||||
--radius-md: calc(var(--t3-radius) - 2px);
|
||||
--radius-lg: var(--t3-radius);
|
||||
--radius-xl: calc(var(--t3-radius) + 4px);
|
||||
--radius-2xl: calc(var(--t3-radius) + 8px);
|
||||
}
|
||||
|
||||
:host {
|
||||
--t3-font-sans:
|
||||
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
|
||||
sans-serif;
|
||||
--t3-font-mono:
|
||||
"SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;
|
||||
--t3-radius: 0.625rem;
|
||||
--t3-background: white;
|
||||
--t3-foreground: oklch(0.269 0 0);
|
||||
--t3-popover: white;
|
||||
--t3-popover-foreground: oklch(0.269 0 0);
|
||||
--t3-primary: oklch(0.488 0.217 264);
|
||||
--t3-primary-foreground: white;
|
||||
--t3-muted: rgb(0 0 0 / 4%);
|
||||
--t3-muted-foreground: oklch(0.556 0 0);
|
||||
--t3-accent: rgb(0 0 0 / 4%);
|
||||
--t3-accent-foreground: oklch(0.269 0 0);
|
||||
--t3-border: rgb(0 0 0 / 8%);
|
||||
--t3-input: rgb(0 0 0 / 10%);
|
||||
--t3-ring: oklch(0.488 0.217 264);
|
||||
color: var(--t3-foreground);
|
||||
font-family: var(--t3-font-sans);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
border-color: var(--t3-border);
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
select:focus-visible,
|
||||
textarea:focus-visible {
|
||||
outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.
|
||||
export const previewAnnotationStyles =
|
||||
'/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: calc(var(--spacing) * 0);\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);Line truncated
|
||||
@@ -0,0 +1,83 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
fromPartition: vi.fn(),
|
||||
sessions: new Map<
|
||||
string,
|
||||
{
|
||||
readonly clearCache: ReturnType<typeof vi.fn>;
|
||||
readonly clearStorageData: ReturnType<typeof vi.fn>;
|
||||
readonly getUserAgent: ReturnType<typeof vi.fn>;
|
||||
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
|
||||
readonly setUserAgent: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
session: {
|
||||
fromPartition,
|
||||
},
|
||||
}));
|
||||
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
|
||||
const layer = BrowserSession.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
describe("BrowserSession", () => {
|
||||
beforeEach(() => {
|
||||
sessions.clear();
|
||||
fromPartition.mockReset();
|
||||
fromPartition.mockImplementation((partition: string) => {
|
||||
const browserSession = {
|
||||
clearCache: vi.fn(() => Promise.resolve()),
|
||||
clearStorageData: vi.fn(() => Promise.resolve()),
|
||||
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
|
||||
setPermissionRequestHandler: vi.fn(),
|
||||
setUserAgent: vi.fn(),
|
||||
};
|
||||
sessions.set(partition, browserSession);
|
||||
return browserSession;
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("derives deterministic partitions and memoizes sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
|
||||
const partition = yield* browserSessions.getPartition("scope-a");
|
||||
const first = yield* browserSessions.getSession("scope-a");
|
||||
const second = yield* browserSessions.getSession("scope-a");
|
||||
|
||||
assert.strictEqual(partition, "persist:t3code-preview-f051bb2c68cb7b2fe969");
|
||||
assert.strictEqual(first, second);
|
||||
assert.strictEqual(fromPartition.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("clears storage and cache for every created session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
yield* browserSessions.getSession("scope-b");
|
||||
|
||||
yield* browserSessions.clearCookies();
|
||||
yield* browserSessions.clearCache();
|
||||
|
||||
assert.strictEqual(sessions.size, 2);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
|
||||
assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
|
||||
{
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { Session } from "electron";
|
||||
import { session } from "electron";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface BrowserSessionShape {
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
}
|
||||
|
||||
export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
|
||||
"@t3tools/desktop/preview/BrowserSession",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
|
||||
const digest = yield* crypto
|
||||
.digest("SHA-256", new TextEncoder().encode(scope))
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
|
||||
);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
});
|
||||
|
||||
const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
|
||||
const partition = yield* getPartition(scope);
|
||||
return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
|
||||
const existing = sessions.get(partition);
|
||||
if (existing) return Effect.succeed([existing, sessions] as const);
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const browserSession = session.fromPartition(partition);
|
||||
const userAgent = browserSession
|
||||
.getUserAgent()
|
||||
.replace(/Electron\/[\d.]+ /, "")
|
||||
.replace(/\s*t3code\/[\d.]+/, "");
|
||||
browserSession.setUserAgent(userAgent);
|
||||
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
|
||||
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
|
||||
callback(allowed.includes(permission));
|
||||
});
|
||||
const next = new Map(sessions);
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
},
|
||||
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
return BrowserSession.of({
|
||||
getPartition,
|
||||
isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
|
||||
getSession,
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
browserSession.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
}),
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
Effect.tryPromise({
|
||||
try: () => browserSession.clearCache(),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
}),
|
||||
});
|
||||
}).pipe(Effect.withSpan("BrowserSession.make"));
|
||||
|
||||
export const layer = Layer.effect(BrowserSession, make);
|
||||
@@ -0,0 +1,6 @@
|
||||
export const START_PICK_CHANNEL = "preview:start-pick";
|
||||
export const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
|
||||
export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
|
||||
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
|
||||
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
|
||||
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
|
||||
@@ -0,0 +1,374 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { beforeEach, describe, expect, vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn(() => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
writeImage,
|
||||
},
|
||||
nativeImage: {
|
||||
createFromPath,
|
||||
},
|
||||
shell: {
|
||||
showItemInFolder,
|
||||
},
|
||||
session: {
|
||||
fromPartition: vi.fn(),
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
},
|
||||
}));
|
||||
|
||||
const browserSessionLayer = Layer.succeed(
|
||||
BrowserSession.BrowserSession,
|
||||
BrowserSession.BrowserSession.of({
|
||||
getPartition: () => Effect.succeed("persist:t3code-preview-test"),
|
||||
isPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getSession: () => Effect.die("unexpected getSession"),
|
||||
clearCookies: () => Effect.void,
|
||||
clearCache: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
|
||||
const environmentLayer = Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape),
|
||||
);
|
||||
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: (path) =>
|
||||
Effect.sync(() => {
|
||||
mkdir(path);
|
||||
}),
|
||||
writeFile: (path, data) =>
|
||||
Effect.sync(() => {
|
||||
writeFile(path, data);
|
||||
}),
|
||||
});
|
||||
|
||||
const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(browserSessionLayer),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
);
|
||||
|
||||
const withManager = <A>(
|
||||
use: (
|
||||
manager: PreviewManager.PreviewManagerShape,
|
||||
) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* use(manager);
|
||||
}).pipe(Effect.provide(layer), Effect.scoped);
|
||||
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
writeImage.mockClear();
|
||||
createFromPath.mockClear();
|
||||
webviewSend.mockClear();
|
||||
});
|
||||
|
||||
effectIt.effect("reports an unregistered webview as temporarily unavailable", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
expect(yield* manager.automationStatus("tab_1")).toEqual({
|
||||
available: false,
|
||||
visible: true,
|
||||
tabId: "tab_1",
|
||||
url: null,
|
||||
title: null,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
|
||||
expect(yield* manager.automationStatus("tab_1")).toEqual({
|
||||
available: false,
|
||||
visible: true,
|
||||
tabId: "tab_1",
|
||||
url: null,
|
||||
title: null,
|
||||
loading: false,
|
||||
});
|
||||
expect(fromId).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const png = Buffer.from("preview-png");
|
||||
const capturePage = vi.fn(async () => ({ toPNG: () => png }));
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com:8443/path?query=value",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
capturePage,
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
expect(webviewSend).toHaveBeenCalledWith(
|
||||
"preview:annotation-theme",
|
||||
expect.objectContaining({
|
||||
colorScheme: "light",
|
||||
primary: "oklch(0.488 0.217 264)",
|
||||
}),
|
||||
);
|
||||
|
||||
const artifact = yield* manager.captureScreenshot("tab_1");
|
||||
|
||||
expect(capturePage).toHaveBeenCalledOnce();
|
||||
expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts");
|
||||
expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
|
||||
expect(artifact).toMatchObject({
|
||||
tabId: "tab_1",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: png.byteLength,
|
||||
});
|
||||
expect(artifact.path).toMatch(
|
||||
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
yield* manager.revealArtifact("/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png");
|
||||
|
||||
expect(showItemInFolder).toHaveBeenCalledWith(
|
||||
"/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png",
|
||||
);
|
||||
const exit = yield* Effect.exit(manager.revealArtifact("/tmp/t3/dev/settings.json"));
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error.cause).toMatchObject({
|
||||
message: "Preview artifact path is outside the configured artifact directory.",
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("copies screenshot artifacts to the system clipboard", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
|
||||
|
||||
yield* manager.copyArtifactToClipboard(artifactPath);
|
||||
|
||||
expect(createFromPath).toHaveBeenCalledWith(artifactPath);
|
||||
expect(writeImage).toHaveBeenCalledOnce();
|
||||
const exit = yield* Effect.exit(
|
||||
manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json"),
|
||||
);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error.cause).toMatchObject({
|
||||
message: "Preview artifact path is outside the configured artifact directory.",
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emits the resolved pointer target before dispatching an automation click", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const activity: string[] = [];
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (method === "Runtime.evaluate") {
|
||||
return {
|
||||
result: {
|
||||
value: { width: 800, height: 600 },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "Input.dispatchMouseEvent" && params?.type === "mousePressed") {
|
||||
activity.push("mousePressed");
|
||||
humanInput?.({}, { kind: "pointer", x: params.x, y: params.y, button: 0 });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const click = yield* manager
|
||||
.automationClick("tab_1", { x: 120, y: 80 })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* TestClock.adjust(200);
|
||||
yield* Fiber.join(click);
|
||||
|
||||
expect(activity).toEqual(["move", "click", "mousePressed"]);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
|
||||
type: "mousePressed",
|
||||
x: 120,
|
||||
y: 80,
|
||||
button: "left",
|
||||
clickCount: 1,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
|
||||
type: "mouseReleased",
|
||||
x: 120,
|
||||
y: 80,
|
||||
button: "left",
|
||||
clickCount: 1,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string) => {
|
||||
if (method === "Runtime.evaluate") {
|
||||
return {
|
||||
result: {
|
||||
value: { width: 800, height: 600 },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "Input.dispatchMouseEvent") {
|
||||
humanInput?.({}, { kind: "pointer", x: 400, y: 300, button: 0 });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
|
||||
const click = yield* manager
|
||||
.automationClick("tab_1", { x: 120, y: 80 })
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
yield* TestClock.adjust(200);
|
||||
const exit = yield* Fiber.await(click);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error.cause).toMatchObject({
|
||||
name: "PreviewAutomationControlInterruptedError",
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Pure clamp/flip math for the floating label that follows the cursor while
|
||||
* the user is picking an element in the in-app browser. Lives in its own
|
||||
* electron-free module so the geometry can be unit-tested without spinning
|
||||
* up an Electron preload context (`PickPreload.ts` itself imports
|
||||
* `electron` and `react-grab/primitives`, which can't load under vitest).
|
||||
*
|
||||
* - Horizontally pins the label to `targetLeft`, clamped into
|
||||
* `[VIEWPORT_MARGIN, viewportWidth - labelWidth - VIEWPORT_MARGIN]`.
|
||||
* - Vertically prefers above the target. If the label would overflow the
|
||||
* top, flips below; if THAT also overflows the bottom, pins to the
|
||||
* bottom margin (better to overlap the highlight than disappear).
|
||||
*/
|
||||
|
||||
/** Distance in CSS pixels between the highlight and the floating label. */
|
||||
export const LABEL_GAP = 4;
|
||||
/** Minimum padding the label keeps from any viewport edge. */
|
||||
export const VIEWPORT_MARGIN = 4;
|
||||
|
||||
export function computeLabelPosition(input: {
|
||||
targetLeft: number;
|
||||
targetTop: number;
|
||||
targetBottom: number;
|
||||
labelWidth: number;
|
||||
labelHeight: number;
|
||||
viewportWidth: number;
|
||||
viewportHeight: number;
|
||||
}): { x: number; y: number } {
|
||||
const { targetLeft, targetTop, targetBottom, labelWidth, labelHeight } = input;
|
||||
const { viewportWidth, viewportHeight } = input;
|
||||
|
||||
let x = targetLeft;
|
||||
const maxX = viewportWidth - labelWidth - VIEWPORT_MARGIN;
|
||||
if (x > maxX) x = maxX;
|
||||
if (x < VIEWPORT_MARGIN) x = VIEWPORT_MARGIN;
|
||||
|
||||
let y = targetTop - labelHeight - LABEL_GAP;
|
||||
if (y < VIEWPORT_MARGIN) {
|
||||
y = targetBottom + LABEL_GAP;
|
||||
if (y + labelHeight > viewportHeight - VIEWPORT_MARGIN) {
|
||||
y = Math.max(VIEWPORT_MARGIN, viewportHeight - labelHeight - VIEWPORT_MARGIN);
|
||||
}
|
||||
}
|
||||
|
||||
return { x, y };
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { computeLabelPosition } from "./PickLabelPosition.ts";
|
||||
|
||||
const VIEWPORT = { viewportWidth: 1280, viewportHeight: 800 };
|
||||
|
||||
describe("computeLabelPosition", () => {
|
||||
it("anchors to the element's top-left when there's room above and to the right", () => {
|
||||
const { x, y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 200,
|
||||
targetTop: 200,
|
||||
targetBottom: 240,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
expect(x).toBe(200);
|
||||
// 200 (top) - 18 (height) - 4 (gap)
|
||||
expect(y).toBe(200 - 18 - 4);
|
||||
});
|
||||
|
||||
it("clamps left edge so the label stays inside the viewport", () => {
|
||||
const { x } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: -50,
|
||||
targetTop: 200,
|
||||
targetBottom: 240,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
expect(x).toBe(4);
|
||||
});
|
||||
|
||||
it("clamps right edge when the label would overflow the viewport (the bug we shipped)", () => {
|
||||
const { x } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 1240,
|
||||
targetTop: 200,
|
||||
targetBottom: 240,
|
||||
labelWidth: 200,
|
||||
labelHeight: 18,
|
||||
});
|
||||
// viewportWidth (1280) - labelWidth (200) - margin (4) = 1076
|
||||
expect(x).toBe(1076);
|
||||
});
|
||||
|
||||
it("flips the label below the element when there's no room above", () => {
|
||||
const { y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 200,
|
||||
targetTop: 4,
|
||||
targetBottom: 44,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
// labelY = 4 - 18 - 4 = -18 → flip → 44 + 4 = 48
|
||||
expect(y).toBe(48);
|
||||
});
|
||||
|
||||
it("pins to the bottom margin when the element fills the viewport (no room above OR below)", () => {
|
||||
const { y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: 200,
|
||||
targetTop: 0,
|
||||
targetBottom: 800,
|
||||
labelWidth: 120,
|
||||
labelHeight: 18,
|
||||
});
|
||||
// Above overflows top → flip below = 800 + 4 = 804 → also overflows
|
||||
// bottom → pin to viewportHeight - labelHeight - margin = 778.
|
||||
expect(y).toBe(800 - 18 - 4);
|
||||
});
|
||||
|
||||
it("never returns a negative coordinate", () => {
|
||||
const { x, y } = computeLabelPosition({
|
||||
...VIEWPORT,
|
||||
targetLeft: -1000,
|
||||
targetTop: -1000,
|
||||
targetBottom: -900,
|
||||
labelWidth: 5000,
|
||||
labelHeight: 5000,
|
||||
});
|
||||
expect(x).toBeGreaterThanOrEqual(0);
|
||||
expect(y).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,201 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isPickedElementPayload, isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
|
||||
function validPayload(overrides?: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
pageUrl: "https://example.com/",
|
||||
pageTitle: "Example",
|
||||
tagName: "button",
|
||||
selector: "button.submit",
|
||||
htmlPreview: "<button>Save</button>",
|
||||
componentName: "SubmitButton",
|
||||
source: {
|
||||
functionName: "SubmitButton",
|
||||
fileName: "/repo/src/Button.tsx",
|
||||
lineNumber: 12,
|
||||
columnNumber: 5,
|
||||
},
|
||||
stack: [
|
||||
{
|
||||
functionName: "SubmitButton",
|
||||
fileName: "/repo/src/Button.tsx",
|
||||
lineNumber: 12,
|
||||
columnNumber: 5,
|
||||
},
|
||||
],
|
||||
styles: ".submit { color: white; }",
|
||||
pickedAt: "2026-05-03T18:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("isPickedElementPayload", () => {
|
||||
it("accepts a complete, well-typed payload", () => {
|
||||
expect(isPickedElementPayload(validPayload())).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts nullable string fields when null", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({ pageTitle: null, selector: null, componentName: null, source: null }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts an empty stack array", () => {
|
||||
expect(isPickedElementPayload(validPayload({ stack: [] }))).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts stack frames with null fields", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
stack: [
|
||||
{
|
||||
functionName: null,
|
||||
fileName: null,
|
||||
lineNumber: null,
|
||||
columnNumber: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects null and primitive inputs", () => {
|
||||
expect(isPickedElementPayload(null)).toBe(false);
|
||||
expect(isPickedElementPayload(undefined)).toBe(false);
|
||||
expect(isPickedElementPayload("string")).toBe(false);
|
||||
expect(isPickedElementPayload(42)).toBe(false);
|
||||
expect(isPickedElementPayload([])).toBe(false);
|
||||
});
|
||||
|
||||
it.each<[string, Record<string, unknown>]>([
|
||||
["missing pageUrl", validPayload({ pageUrl: undefined })],
|
||||
["wrong-type pageUrl", validPayload({ pageUrl: 123 })],
|
||||
["missing tagName", validPayload({ tagName: undefined })],
|
||||
["missing htmlPreview", validPayload({ htmlPreview: undefined })],
|
||||
["missing styles", validPayload({ styles: undefined })],
|
||||
["missing pickedAt", validPayload({ pickedAt: undefined })],
|
||||
["wrong-type pageTitle", validPayload({ pageTitle: 99 })],
|
||||
["wrong-type selector", validPayload({ selector: 99 })],
|
||||
["wrong-type componentName", validPayload({ componentName: 99 })],
|
||||
])("rejects payloads with %s", (_label, value) => {
|
||||
expect(isPickedElementPayload(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed source frames", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
source: {
|
||||
functionName: 0,
|
||||
fileName: null,
|
||||
lineNumber: null,
|
||||
columnNumber: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects non-finite numeric line/column numbers", () => {
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
source: {
|
||||
functionName: null,
|
||||
fileName: null,
|
||||
lineNumber: Number.POSITIVE_INFINITY,
|
||||
columnNumber: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPickedElementPayload(
|
||||
validPayload({
|
||||
source: {
|
||||
functionName: null,
|
||||
fileName: null,
|
||||
lineNumber: Number.NaN,
|
||||
columnNumber: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed stack arrays", () => {
|
||||
expect(isPickedElementPayload(validPayload({ stack: "not-an-array" }))).toBe(false);
|
||||
expect(isPickedElementPayload(validPayload({ stack: [{ bogus: true }] }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function validAnnotation(overrides?: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
id: "annotation_1",
|
||||
pageUrl: "https://example.com/",
|
||||
pageTitle: "Example",
|
||||
comment: "Make this clearer",
|
||||
elements: [
|
||||
{
|
||||
id: "element_1",
|
||||
element: validPayload(),
|
||||
rect: { x: 10, y: 20, width: 100, height: 40 },
|
||||
},
|
||||
],
|
||||
regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
|
||||
strokes: [
|
||||
{
|
||||
id: "stroke_1",
|
||||
color: "#7c3aed",
|
||||
width: 4,
|
||||
points: [
|
||||
{ x: 10, y: 10 },
|
||||
{ x: 20, y: 20 },
|
||||
],
|
||||
bounds: { x: 6, y: 6, width: 18, height: 18 },
|
||||
},
|
||||
],
|
||||
styleChanges: [
|
||||
{
|
||||
targetId: "element_1",
|
||||
selector: "button.submit",
|
||||
property: "opacity",
|
||||
previousValue: "1",
|
||||
value: "0.5",
|
||||
},
|
||||
],
|
||||
screenshot: null,
|
||||
createdAt: "2026-06-11T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("isPreviewAnnotationPayload", () => {
|
||||
it("accepts a structured annotation draft before screenshot capture", () => {
|
||||
expect(isPreviewAnnotationPayload(validAnnotation())).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects screenshots supplied by the guest preload", () => {
|
||||
expect(isPreviewAnnotationPayload(validAnnotation({ screenshot: { dataUrl: "bad" } }))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects malformed geometry and nested element payloads", () => {
|
||||
expect(
|
||||
isPreviewAnnotationPayload(
|
||||
validAnnotation({ regions: [{ id: "region_1", rect: { x: 0, y: 0, width: "wide" } }] }),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPreviewAnnotationPayload(
|
||||
validAnnotation({ elements: [{ id: "element_1", element: {}, rect: {} }] }),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Strict structural validator for `PickedElementPayload` messages received
|
||||
* from the in-page picker preload (`apps/desktop/src/preview/PickPreload.ts`)
|
||||
* via `wc.ipc`. Lives in its own electron-free module so the validator is
|
||||
* trivially unit-testable.
|
||||
*
|
||||
* Validation must be tight: downstream `normalizeElementContextSelection`
|
||||
* calls `.trim()` on incoming strings, so a malformed payload (preload bug,
|
||||
* future schema mismatch, malicious page that intercepts the preload's IPC
|
||||
* channel via prototype pollution) would otherwise throw deep in the
|
||||
* renderer and the chip silently never appears.
|
||||
*/
|
||||
import type { PickedElementPayload, PreviewAnnotationPayload } from "@t3tools/contracts";
|
||||
|
||||
function isStringOrNull(value: unknown): value is string | null {
|
||||
return value === null || typeof value === "string";
|
||||
}
|
||||
|
||||
function isFiniteNumberOrNull(value: unknown): value is number | null {
|
||||
return value === null || (typeof value === "number" && Number.isFinite(value));
|
||||
}
|
||||
|
||||
function isPickedStackFrame(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const frame = value as Record<string, unknown>;
|
||||
return (
|
||||
isStringOrNull(frame["functionName"]) &&
|
||||
isStringOrNull(frame["fileName"]) &&
|
||||
isFiniteNumberOrNull(frame["lineNumber"]) &&
|
||||
isFiniteNumberOrNull(frame["columnNumber"])
|
||||
);
|
||||
}
|
||||
|
||||
export function isPickedElementPayload(value: unknown): value is PickedElementPayload {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const c = value as Record<string, unknown>;
|
||||
if (typeof c["pageUrl"] !== "string") return false;
|
||||
if (typeof c["tagName"] !== "string") return false;
|
||||
if (typeof c["htmlPreview"] !== "string") return false;
|
||||
if (typeof c["styles"] !== "string") return false;
|
||||
if (typeof c["pickedAt"] !== "string") return false;
|
||||
if (!isStringOrNull(c["pageTitle"])) return false;
|
||||
if (!isStringOrNull(c["selector"])) return false;
|
||||
if (!isStringOrNull(c["componentName"])) return false;
|
||||
if (c["source"] !== null && !isPickedStackFrame(c["source"])) return false;
|
||||
if (!Array.isArray(c["stack"])) return false;
|
||||
if (!c["stack"].every(isPickedStackFrame)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function isRect(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const rect = value as Record<string, unknown>;
|
||||
return ["x", "y", "width", "height"].every(
|
||||
(key) => typeof rect[key] === "number" && Number.isFinite(rect[key]),
|
||||
);
|
||||
}
|
||||
|
||||
function isPoint(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const point = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof point["x"] === "number" &&
|
||||
Number.isFinite(point["x"]) &&
|
||||
typeof point["y"] === "number" &&
|
||||
Number.isFinite(point["y"])
|
||||
);
|
||||
}
|
||||
|
||||
export function isPreviewAnnotationPayload(value: unknown): value is PreviewAnnotationPayload {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const annotation = value as Record<string, unknown>;
|
||||
if (typeof annotation["id"] !== "string") return false;
|
||||
if (typeof annotation["pageUrl"] !== "string") return false;
|
||||
if (!isStringOrNull(annotation["pageTitle"])) return false;
|
||||
if (typeof annotation["comment"] !== "string") return false;
|
||||
if (typeof annotation["createdAt"] !== "string") return false;
|
||||
if (annotation["screenshot"] !== null) return false;
|
||||
|
||||
const elements = annotation["elements"];
|
||||
if (!Array.isArray(elements)) return false;
|
||||
if (
|
||||
!elements.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const target = entry as Record<string, unknown>;
|
||||
return (
|
||||
typeof target["id"] === "string" &&
|
||||
isPickedElementPayload(target["element"]) &&
|
||||
isRect(target["rect"])
|
||||
);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const regions = annotation["regions"];
|
||||
if (!Array.isArray(regions)) return false;
|
||||
if (
|
||||
!regions.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const target = entry as Record<string, unknown>;
|
||||
return typeof target["id"] === "string" && isRect(target["rect"]);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const strokes = annotation["strokes"];
|
||||
if (!Array.isArray(strokes)) return false;
|
||||
if (
|
||||
!strokes.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const target = entry as Record<string, unknown>;
|
||||
return (
|
||||
typeof target["id"] === "string" &&
|
||||
typeof target["color"] === "string" &&
|
||||
typeof target["width"] === "number" &&
|
||||
Number.isFinite(target["width"]) &&
|
||||
Array.isArray(target["points"]) &&
|
||||
target["points"].every(isPoint) &&
|
||||
isRect(target["bounds"])
|
||||
);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const styleChanges = annotation["styleChanges"];
|
||||
if (!Array.isArray(styleChanges)) return false;
|
||||
if (
|
||||
!styleChanges.every((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
const change = entry as Record<string, unknown>;
|
||||
return (
|
||||
typeof change["targetId"] === "string" &&
|
||||
isStringOrNull(change["selector"]) &&
|
||||
typeof change["property"] === "string" &&
|
||||
typeof change["previousValue"] === "string" &&
|
||||
typeof change["value"] === "string"
|
||||
);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
playwrightInjectedRuntimeInstallExpression,
|
||||
playwrightInjectedRuntimeSource,
|
||||
} from "./PlaywrightInjectedRuntime.ts";
|
||||
|
||||
describe("playwright injected runtime", () => {
|
||||
effectIt.effect("extracts the pinned runtime from playwright-core", () =>
|
||||
Effect.gen(function* () {
|
||||
const source = yield* playwrightInjectedRuntimeSource();
|
||||
expect(source.length).toBeGreaterThan(100_000);
|
||||
expect(source).toContain("InjectedScript");
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("builds an idempotent install expression", () =>
|
||||
Effect.gen(function* () {
|
||||
const expression = yield* playwrightInjectedRuntimeInstallExpression();
|
||||
expect(expression).toContain("__t3PlaywrightInjected");
|
||||
expect(expression).toContain('testIdAttributeName":"data-testid');
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { runInNewContext } from "node:vm";
|
||||
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
|
||||
"PlaywrightInjectedRuntimeError",
|
||||
)<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Playwright injected runtime operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
const fail = (operation: string, cause: unknown) =>
|
||||
new PlaywrightInjectedRuntimeError({ operation, cause });
|
||||
|
||||
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
|
||||
function* () {
|
||||
const packageJsonPath = yield* Effect.try({
|
||||
try: () => require.resolve("playwright-core/package.json"),
|
||||
catch: (cause) => fail("resolvePackage", cause),
|
||||
});
|
||||
const coreBundle = yield* Effect.tryPromise({
|
||||
try: () => readFile(join(dirname(packageJsonPath), "lib/coreBundle.js"), "utf8"),
|
||||
catch: (cause) => fail("readCoreBundle", cause),
|
||||
});
|
||||
const marker = "source3 = ";
|
||||
const start = coreBundle.indexOf(marker);
|
||||
if (start < 0) {
|
||||
return yield* fail(
|
||||
"findSourceMarker",
|
||||
new Error("Playwright injected runtime marker was not found."),
|
||||
);
|
||||
}
|
||||
const literalStart = start + marker.length;
|
||||
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
|
||||
if (literalEnd < 0) {
|
||||
return yield* fail(
|
||||
"findSourceTerminator",
|
||||
new Error("Playwright injected runtime terminator was not found."),
|
||||
);
|
||||
}
|
||||
const literal = coreBundle.slice(literalStart, literalEnd);
|
||||
const source = yield* Effect.try({
|
||||
try: () => runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
|
||||
catch: (cause) => fail("evaluateSourceLiteral", cause),
|
||||
});
|
||||
if (typeof source !== "string" || source.length < 100_000) {
|
||||
return yield* fail(
|
||||
"validateSource",
|
||||
new Error("Playwright injected runtime extraction returned invalid source."),
|
||||
);
|
||||
}
|
||||
return source;
|
||||
},
|
||||
);
|
||||
|
||||
export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
|
||||
"PlaywrightInjectedRuntime.installExpression",
|
||||
)(function* () {
|
||||
const source = yield* playwrightInjectedRuntimeSource();
|
||||
const options = yield* encodeUnknownJson({
|
||||
isUnderTest: false,
|
||||
sdkLanguage: "javascript",
|
||||
testIdAttributeName: "data-testid",
|
||||
stableRafCount: 1,
|
||||
browserName: "chromium",
|
||||
shouldPrependErrorPrefix: false,
|
||||
isUtilityWorld: false,
|
||||
customEngines: [],
|
||||
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
|
||||
return `(() => {
|
||||
if (globalThis.__t3PlaywrightInjected) return true;
|
||||
const module = { exports: {} };
|
||||
${source}
|
||||
globalThis.__t3PlaywrightInjected = new (module.exports.InjectedScript())(globalThis, ${options});
|
||||
return true;
|
||||
})()`;
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "./WebviewPreferences.ts";
|
||||
|
||||
/**
|
||||
* Mirrors Electron's webview attribute parser closely enough to catch the
|
||||
* regressions we've already hit:
|
||||
*
|
||||
* - whitespace inside the comma-separated list silently drops keys (so
|
||||
* `" sandbox=true"` becomes an unknown key and Electron falls back to
|
||||
* defaults — re-opening the Node-leak window we closed),
|
||||
* - non-`true`/`false` values (`"yes"`, `"no"`, etc.) are kept as truthy
|
||||
* strings and assigned to a boolean preference, which silently flips
|
||||
* `contextIsolation=no` to ENABLED (then react-grab can't see the React
|
||||
* DevTools hook and componentName resolution always returns null).
|
||||
*
|
||||
* The actual Electron parser does roughly:
|
||||
*
|
||||
* for (const pair of webpreferences.split(',')) {
|
||||
* const [key, value] = pair.split('=');
|
||||
* prefs[key] = value; // value left as a string
|
||||
* }
|
||||
*
|
||||
* then later coerces booleans via `Boolean(value)`. Replicating that here
|
||||
* keeps the test independent of Electron internals while still failing if
|
||||
* we accidentally ship `"contextIsolation=no"` again.
|
||||
*/
|
||||
function parseWebPreferences(input: string): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const pair of input.split(",")) {
|
||||
if (pair !== pair.trim()) {
|
||||
// Electron's parser doesn't trim; surface the bug as undefined-key.
|
||||
out[pair] = pair.split("=")[1];
|
||||
continue;
|
||||
}
|
||||
const [key, value] = pair.split("=");
|
||||
if (!key) continue;
|
||||
out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("PREVIEW_WEBVIEW_PREFERENCES", () => {
|
||||
const parsed = parseWebPreferences(PREVIEW_WEBVIEW_PREFERENCES);
|
||||
|
||||
it("contains exactly the three security-critical keys", () => {
|
||||
expect(Object.keys(parsed).toSorted()).toEqual(
|
||||
["contextIsolation", "nodeIntegration", "sandbox"].toSorted(),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses canonical JS-boolean string literals (not yes/no, on/off, 1/0)", () => {
|
||||
// `value="no"` is a TRUTHY string when assigned to webPreferences.X — so
|
||||
// `contextIsolation="no"` would silently leave isolation ENABLED. Lock
|
||||
// the values to `"true"` / `"false"` so the parser does the right thing.
|
||||
for (const value of Object.values(parsed)) {
|
||||
expect(value).toMatch(/^(true|false)$/);
|
||||
}
|
||||
});
|
||||
|
||||
it("disables context isolation (so react-grab can see the page's React DevTools hook)", () => {
|
||||
expect(parsed["contextIsolation"]).toBe("false");
|
||||
});
|
||||
|
||||
it("keeps the renderer sandbox enabled (so the page cannot reach Node APIs)", () => {
|
||||
expect(parsed["sandbox"]).toBe("true");
|
||||
});
|
||||
|
||||
it("disables nodeIntegration (defense in depth — page never gets Node)", () => {
|
||||
expect(parsed["nodeIntegration"]).toBe("false");
|
||||
});
|
||||
|
||||
it("contains no whitespace (Electron's parser does not trim)", () => {
|
||||
// Electron splits on `,` without trimming, so any whitespace would turn
|
||||
// a key into an unknown one and silently drop the security flag.
|
||||
expect(PREVIEW_WEBVIEW_PREFERENCES).not.toMatch(/\s/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* webPreferences override applied to every preview `<webview>` element via
|
||||
* its `webpreferences="..."` attribute. Single source of truth so all guest
|
||||
* surfaces inherit the same security posture.
|
||||
*
|
||||
* Lives in its own electron-free module so the value is unit-testable
|
||||
* without importing `Manager.ts` (which transitively imports
|
||||
* `electron` and blows up under vitest).
|
||||
*
|
||||
* - `contextIsolation=false`: the picker preload needs to share `globalThis`
|
||||
* with the page so react-grab/bippy can read the React DevTools hook
|
||||
* (`__REACT_DEVTOOLS_GLOBAL_HOOK__`) and resolve component names. Without
|
||||
* this every pick comes back with `componentName: null` even on dev React
|
||||
* apps.
|
||||
* - `sandbox=true`: keeps the OS-level renderer sandbox enabled. Critical
|
||||
* when paired with `contextIsolation=false` — without sandbox, the preload
|
||||
* has full Node access (`require`, `fs`, `child_process`, ...) and that
|
||||
* `require` would land on the page's shared `globalThis`, giving any
|
||||
* third-party page in the preview full Node + IPC access to the host.
|
||||
* In sandboxed mode Electron still synthesizes the `electron` module for
|
||||
* the preload's `import { ipcRenderer }` line, but no Node globals leak.
|
||||
* - `nodeIntegration=false`: pinned for clarity (the page itself never gets
|
||||
* Node access).
|
||||
*
|
||||
* Format notes (locked down by `WebviewPreferences.test.ts`):
|
||||
* - Whitespace-free. Electron's webpreferences parser splits on `,` and
|
||||
* does not trim, so a leading space would turn a key into an unknown one
|
||||
* and silently drop it.
|
||||
* - Values are JS-boolean strings (`true`/`false`) — `yes`/`no` are not
|
||||
* special-cased by the parser; `value="no"` becomes the truthy STRING
|
||||
* `"no"` when assigned to a boolean webPreferences key. Most critically,
|
||||
* `contextIsolation="no"` is truthy → contextIsolation stays ENABLED →
|
||||
* react-grab can't see the React DevTools hook.
|
||||
*
|
||||
* Defense in depth: `apps/desktop/src/main.ts` also runs a
|
||||
* `will-attach-webview` handler that force-sets `sandbox: true` and
|
||||
* `nodeIntegration*: false` on the actual webPreferences object, gated on
|
||||
* the preview partition, so even if this string is ever wrong, the
|
||||
* security-critical flags can't regress on preview tabs.
|
||||
*/
|
||||
export const PREVIEW_WEBVIEW_PREFERENCES =
|
||||
"contextIsolation=false,sandbox=true,nodeIntegration=false";
|
||||
@@ -8,6 +8,17 @@ import * as Ref from "effect/Ref";
|
||||
import type * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("electron", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("electron")>()),
|
||||
session: {
|
||||
fromPartition: vi.fn(() => ({
|
||||
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/1.2.3"),
|
||||
setPermissionRequestHandler: vi.fn(),
|
||||
setUserAgent: vi.fn(),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
@@ -18,6 +29,7 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
|
||||
const environmentInput = {
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
@@ -155,6 +167,12 @@ function makeTestLayer(input: {
|
||||
} satisfies ElectronShell.ElectronShellShape),
|
||||
electronThemeLayer,
|
||||
electronWindowLayer,
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
getBrowserSession: () => Effect.succeed({} as Electron.Session),
|
||||
setMainWindow: () => Effect.void,
|
||||
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
@@ -36,7 +37,8 @@ type DesktopWindowRuntimeServices =
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
| ElectronWindow.ElectronWindow;
|
||||
| ElectronWindow.ElectronWindow
|
||||
| PreviewManager.PreviewManager;
|
||||
|
||||
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
|
||||
"DesktopWindowDevServerUrlMissingError",
|
||||
@@ -48,7 +50,8 @@ export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
|
||||
|
||||
export type DesktopWindowError =
|
||||
| DesktopWindowDevServerUrlMissingError
|
||||
| ElectronWindow.ElectronWindowCreateError;
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
export interface DesktopWindowShape {
|
||||
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
@@ -79,9 +82,10 @@ function resolveDesktopDevServerUrl(
|
||||
|
||||
function getIconOption(
|
||||
iconPaths: DesktopAssets.DesktopIconPaths,
|
||||
platform: NodeJS.Platform,
|
||||
): { icon: string } | Record<string, never> {
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
if (platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = platform === "win32" ? "ico" : "png";
|
||||
return Option.match(iconPaths[ext], {
|
||||
onNone: () => ({}),
|
||||
onSome: (icon) => ({ icon }),
|
||||
@@ -103,8 +107,11 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): WindowTitleBarOptions {
|
||||
if (platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
@@ -124,6 +131,7 @@ function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarO
|
||||
function syncWindowAppearance(
|
||||
window: Electron.BrowserWindow,
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
@@ -131,7 +139,7 @@ function syncWindowAppearance(
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors);
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
@@ -162,6 +170,7 @@ const make = Effect.gen(function* () {
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
@@ -170,11 +179,12 @@ const make = Effect.gen(function* () {
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
|
||||
backendHttpUrl: URL,
|
||||
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
|
||||
yield* previewManager.getBrowserSession();
|
||||
const applicationUrl = environment.isDevelopment
|
||||
? yield* resolveDesktopDevServerUrl(environment)
|
||||
: backendHttpUrl.href;
|
||||
const iconPaths = yield* assets.iconPaths;
|
||||
const iconOption = getIconOption(iconPaths);
|
||||
const iconOption = getIconOption(iconPaths, environment.platform);
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
const window = yield* electronWindow.create({
|
||||
width: 1100,
|
||||
@@ -186,15 +196,31 @@ const make = Effect.gen(function* () {
|
||||
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
|
||||
...iconOption,
|
||||
title: environment.displayName,
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors),
|
||||
...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
|
||||
webPreferences: {
|
||||
preload: environment.preloadPath,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
webviewTag: true,
|
||||
},
|
||||
});
|
||||
|
||||
yield* previewManager.setMainWindow(window);
|
||||
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
|
||||
if (
|
||||
typeof params.partition !== "string" ||
|
||||
!previewManager.isBrowserPartition(params.partition)
|
||||
) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
webPreferences.sandbox = true;
|
||||
webPreferences.nodeIntegration = false;
|
||||
webPreferences.nodeIntegrationInSubFrames = false;
|
||||
webPreferences.contextIsolation = false;
|
||||
});
|
||||
|
||||
window.webContents.on("context-menu", (event, params) => {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -297,7 +323,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
|
||||
if (process.platform === "linux") {
|
||||
if (environment.platform === "linux") {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => {
|
||||
@@ -387,7 +413,7 @@ const make = Effect.gen(function* () {
|
||||
syncAppearance: Effect.gen(function* () {
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
yield* electronWindow.syncAllAppearance((window) =>
|
||||
syncWindowAppearance(window, shouldUseDarkColors),
|
||||
syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.window.syncAppearance")),
|
||||
});
|
||||
|
||||
@@ -14,17 +14,18 @@ export default defineConfig({
|
||||
run: {
|
||||
tasks: {
|
||||
build: {
|
||||
command: "vp pack",
|
||||
command: "node scripts/build-preview-annotation-css.mjs && vp pack",
|
||||
dependsOn: ["t3#build"],
|
||||
cache: false,
|
||||
},
|
||||
dev: {
|
||||
command: "cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
|
||||
command:
|
||||
"node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
|
||||
dependsOn: ["t3#build"],
|
||||
cache: false,
|
||||
},
|
||||
"dev:bundle": {
|
||||
command: "vp pack --watch",
|
||||
command: "node scripts/build-preview-annotation-css.mjs && vp pack --watch",
|
||||
cache: false,
|
||||
},
|
||||
"dev:electron": {
|
||||
@@ -56,5 +57,15 @@ export default defineConfig({
|
||||
define: publicConfigDefine,
|
||||
entry: ["src/preload.ts"],
|
||||
},
|
||||
{
|
||||
format: "cjs",
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".cjs" }),
|
||||
entry: ["src/preview-pick-preload.ts"],
|
||||
deps: {
|
||||
alwaysBundle: (id) => id === "react-grab" || id.startsWith("react-grab/"),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
import { fromYaml } from "@t3tools/shared/schemaYaml";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
interface PackageJson {
|
||||
@@ -175,6 +176,7 @@ const buildCmd = Command.make(
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
shell: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -290,15 +292,15 @@ const publishCmd = Command.make(
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = createVpPmPublishArgs(config);
|
||||
const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
|
||||
|
||||
yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("vp", ["pm", ...args], {
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
cwd: repoRoot,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims.
|
||||
shell: process.platform === "win32",
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -3,6 +3,8 @@ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import process from "node:process";
|
||||
import readline from "node:readline";
|
||||
import * as NodeTimers from "node:timers";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
type JsonPrimitive = null | boolean | number | string;
|
||||
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
@@ -128,9 +130,10 @@ class JsonRpcChild {
|
||||
closed = false;
|
||||
|
||||
constructor(bin: string, args: string[], cwd: string) {
|
||||
this.child = spawn(bin, args, {
|
||||
const spawnCommand = Effect.runSync(resolveSpawnCommand(bin, args));
|
||||
this.child = spawn(spawnCommand.command, spawnCommand.args, {
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
shell: spawnCommand.shell,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } 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 ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { ProjectFaviconResolverLive } from "../project/Layers/ProjectFaviconResolver.ts";
|
||||
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
|
||||
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
|
||||
|
||||
const configLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-asset-access-test-",
|
||||
});
|
||||
const testLayer = Layer.mergeAll(
|
||||
configLayer,
|
||||
WorkspacePathsLive,
|
||||
ProjectFaviconResolverLive.pipe(Layer.provide(WorkspacePathsLive)),
|
||||
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
describe("AssetAccess", () => {
|
||||
it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-workspace-",
|
||||
});
|
||||
const htmlPath = path.join(root, "report.html");
|
||||
const cssPath = path.join(root, "report.css");
|
||||
yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
|
||||
yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
|
||||
yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: htmlPath,
|
||||
},
|
||||
workspaceRoot: root,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
expect(yield* resolveAsset(token, "report.html")).toEqual({
|
||||
kind: "file",
|
||||
path: htmlPath,
|
||||
});
|
||||
expect(yield* resolveAsset(token, "report.css")).toEqual({
|
||||
kind: "file",
|
||||
path: cssPath,
|
||||
});
|
||||
expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
|
||||
expect(yield* resolveAsset(token, ".env")).toBeNull();
|
||||
expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects workspace files outside the authorized root", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-root-",
|
||||
});
|
||||
const outside = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-outside-",
|
||||
});
|
||||
const htmlPath = path.join(outside, "report.html");
|
||||
yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: htmlPath,
|
||||
},
|
||||
workspaceRoot: root,
|
||||
}).pipe(Effect.flip);
|
||||
expect(error.message).toContain("relative to the project root");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues exact attachment capabilities by attachment id", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001";
|
||||
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "attachment", attachmentId },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues project favicon capabilities with a signed fallback", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-",
|
||||
});
|
||||
const faviconPath = path.join(root, "favicon.svg");
|
||||
yield* fileSystem.writeFileString(faviconPath, "<svg />");
|
||||
|
||||
const faviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const faviconSeparatorIndex = faviconSuffix.indexOf("/");
|
||||
expect(
|
||||
yield* resolveAsset(
|
||||
faviconSuffix.slice(0, faviconSeparatorIndex),
|
||||
faviconSuffix.slice(faviconSeparatorIndex + 1),
|
||||
),
|
||||
).toEqual({ kind: "file", path: faviconPath });
|
||||
|
||||
yield* fileSystem.remove(faviconPath);
|
||||
const fallbackResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
|
||||
expect(
|
||||
yield* resolveAsset(
|
||||
fallbackSuffix.slice(0, fallbackSeparatorIndex),
|
||||
fallbackSuffix.slice(fallbackSeparatorIndex + 1),
|
||||
),
|
||||
).toEqual({ kind: "project-favicon-fallback" });
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,287 @@
|
||||
import type { AssetResource } from "@t3tools/contracts";
|
||||
import { AssetAccessError } from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../auth/utils.ts";
|
||||
import { ServerSecretStore } from "../auth/ServerSecretStore.ts";
|
||||
import { resolveAttachmentPathById } from "../attachmentStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { ProjectFaviconResolver } from "../project/Services/ProjectFaviconResolver.ts";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
|
||||
|
||||
export const ASSET_ROUTE_PREFIX = "/api/assets";
|
||||
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
const SIGNING_SECRET_NAME = "asset-access-signing-key";
|
||||
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
const PREVIEWABLE_EXTENSIONS = new Set([".htm", ".html", ".pdf"]);
|
||||
const PREVIEW_ASSET_EXTENSIONS = new Set([
|
||||
...PREVIEWABLE_EXTENSIONS,
|
||||
".avif",
|
||||
".css",
|
||||
".gif",
|
||||
".ico",
|
||||
".jpeg",
|
||||
".jpg",
|
||||
".js",
|
||||
".mjs",
|
||||
".otf",
|
||||
".png",
|
||||
".svg",
|
||||
".ttf",
|
||||
".webp",
|
||||
".woff",
|
||||
".woff2",
|
||||
]);
|
||||
|
||||
const AssetClaimsSchema = Schema.Union([
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("workspace-file"),
|
||||
workspaceRoot: Schema.String,
|
||||
baseRelativePath: Schema.String,
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("attachment"),
|
||||
attachmentId: Schema.String,
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("project-favicon"),
|
||||
workspaceRoot: Schema.String,
|
||||
relativePath: Schema.NullOr(Schema.String),
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
]);
|
||||
type AssetClaims = typeof AssetClaimsSchema.Type;
|
||||
|
||||
const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
|
||||
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
|
||||
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
|
||||
|
||||
export type ResolvedAsset =
|
||||
| { readonly kind: "file"; readonly path: string }
|
||||
| { readonly kind: "project-favicon-fallback" };
|
||||
|
||||
function decodeClaims(encodedPayload: string): AssetClaims | null {
|
||||
try {
|
||||
return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeRelativePath(value: string): string | null {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const failAccess = (message: string, cause?: unknown) =>
|
||||
new AssetAccessError({ message, ...(cause === undefined ? {} : { cause }) });
|
||||
|
||||
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
|
||||
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot(input)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!resolved) return null;
|
||||
|
||||
const [canonicalRoot, canonicalFile] = yield* Effect.all([
|
||||
fileSystem.realPath(input.workspaceRoot).pipe(Effect.orElseSucceed(() => null)),
|
||||
fileSystem.realPath(resolved.absolutePath).pipe(Effect.orElseSucceed(() => null)),
|
||||
]);
|
||||
if (!canonicalRoot || !canonicalFile) return null;
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const relative = path.relative(canonicalRoot, canonicalFile);
|
||||
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
|
||||
|
||||
const info = yield* fileSystem.stat(canonicalFile).pipe(Effect.orElseSucceed(() => null));
|
||||
return info?.type === "File" ? canonicalFile : null;
|
||||
},
|
||||
);
|
||||
|
||||
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
|
||||
readonly resource: AssetResource;
|
||||
readonly workspaceRoot?: string;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
let claims: AssetClaims;
|
||||
let fileName: string;
|
||||
|
||||
switch (input.resource._tag) {
|
||||
case "workspace-file": {
|
||||
if (!input.workspaceRoot) {
|
||||
return yield* failAccess("Workspace context was not found.");
|
||||
}
|
||||
const workspaceRoot = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const relativePath = path.isAbsolute(input.resource.path)
|
||||
? path.relative(workspaceRoot, input.resource.path)
|
||||
: input.resource.path;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
if (!PREVIEWABLE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
|
||||
return yield* failAccess("Only HTML and PDF files can open in the browser.");
|
||||
}
|
||||
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot,
|
||||
relativePath: resolved.relativePath,
|
||||
});
|
||||
if (!canonicalFile) {
|
||||
return yield* failAccess("Workspace asset was not found.");
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "workspace-file",
|
||||
workspaceRoot: yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
|
||||
baseRelativePath: path.dirname(resolved.relativePath),
|
||||
expiresAt,
|
||||
};
|
||||
fileName = path.basename(resolved.relativePath);
|
||||
break;
|
||||
}
|
||||
case "attachment": {
|
||||
const config = yield* ServerConfig;
|
||||
const attachmentPath = resolveAttachmentPathById({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentId: input.resource.attachmentId,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* failAccess("Attachment was not found.");
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "attachment",
|
||||
attachmentId: input.resource.attachmentId,
|
||||
expiresAt,
|
||||
};
|
||||
fileName = path.basename(attachmentPath);
|
||||
break;
|
||||
}
|
||||
case "project-favicon": {
|
||||
const workspaceRoot = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.resource.cwd)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const faviconResolver = yield* ProjectFaviconResolver;
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
if (
|
||||
relativePath &&
|
||||
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }))
|
||||
) {
|
||||
return yield* failAccess("Project favicon was not found.");
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "project-favicon",
|
||||
workspaceRoot: yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
|
||||
relativePath,
|
||||
expiresAt,
|
||||
};
|
||||
fileName = relativePath ? path.basename(relativePath) : "favicon.svg";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const signingSecret = yield* secretStore
|
||||
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
|
||||
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
|
||||
return {
|
||||
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
|
||||
expiresAt,
|
||||
};
|
||||
});
|
||||
|
||||
export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
token: string,
|
||||
relativePath: string,
|
||||
) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) return null;
|
||||
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const signingSecret = yield* secretStore
|
||||
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!signingSecret) return null;
|
||||
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
|
||||
|
||||
const claims = decodeClaims(encodedPayload);
|
||||
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
|
||||
|
||||
if (claims.kind === "attachment") {
|
||||
const config = yield* ServerConfig;
|
||||
const attachmentPath = resolveAttachmentPathById({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentId: claims.attachmentId,
|
||||
});
|
||||
if (!attachmentPath) return null;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const info = yield* fileSystem.stat(attachmentPath).pipe(Effect.orElseSucceed(() => null));
|
||||
return info?.type === "File"
|
||||
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
if (claims.kind === "project-favicon") {
|
||||
if (claims.relativePath === null) {
|
||||
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
|
||||
}
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
|
||||
}
|
||||
|
||||
const decodedPath = decodeRelativePath(relativePath);
|
||||
if (decodedPath === null) return null;
|
||||
const path = yield* Path.Path;
|
||||
const segments = decodedPath.split(/[\\/]/);
|
||||
if (
|
||||
decodedPath.length === 0 ||
|
||||
decodedPath.includes("\0") ||
|
||||
segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
|
||||
!PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const joinedRelativePath =
|
||||
claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
|
||||
const workspaceFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: joinedRelativePath,
|
||||
});
|
||||
return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
|
||||
});
|
||||
@@ -1,8 +1,6 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import NodePath from "node:path";
|
||||
|
||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||
|
||||
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
|
||||
const normalized = NodePath.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as NFS from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -11,8 +11,9 @@ import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { vi } from "vite-plus/test";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
|
||||
import { readBootstrapEnvelope } from "./bootstrap.ts";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
@@ -41,14 +42,6 @@ const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
||||
const encodeTestEnvelopeSchema = Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema));
|
||||
|
||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
it.effect("uses platform-specific fd paths", () =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
|
||||
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
|
||||
assert.equal(resolveFdPath(3, "win32"), undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads a bootstrap envelope from a provided fd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -89,7 +82,9 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
|
||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
||||
try {
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||
timeoutMs: 100,
|
||||
}).pipe(Effect.provideService(HostProcessPlatform, "linux"));
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as Predicate from "effect/Predicate";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
||||
readonly message: string;
|
||||
@@ -110,36 +111,39 @@ const isFdReady = (fd: number) =>
|
||||
);
|
||||
|
||||
const makeBootstrapInputStream = (fd: number) =>
|
||||
Effect.try<Readable, BootstrapError>({
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd);
|
||||
if (fdPath === undefined) {
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
|
||||
let streamFd: number | undefined;
|
||||
try {
|
||||
streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isBootstrapFdPathDuplicationError(error)) {
|
||||
if (streamFd !== undefined) {
|
||||
NFS.closeSync(streamFd);
|
||||
}
|
||||
Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* Effect.try<Readable, BootstrapError>({
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd, platform);
|
||||
if (fdPath === undefined) {
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to duplicate bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
|
||||
let streamFd: number | undefined;
|
||||
try {
|
||||
streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isBootstrapFdPathDuplicationError(error)) {
|
||||
if (streamFd !== undefined) {
|
||||
NFS.closeSync(streamFd);
|
||||
}
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to duplicate bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
const makeDirectBootstrapStream = (fd: number): Readable => {
|
||||
@@ -165,10 +169,7 @@ const isBootstrapFdPathDuplicationError = Predicate.compose(
|
||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
||||
);
|
||||
|
||||
export function resolveFdPath(
|
||||
fd: number,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string | undefined {
|
||||
function resolveFdPath(fd: number, platform: NodeJS.Platform): string | undefined {
|
||||
if (platform === "linux") {
|
||||
return `/proc/self/fd/${fd}`;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import NodeOS from "node:os";
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import { assert, expect, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
ServerProcessSignal,
|
||||
ServerSignalProcessResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -277,6 +278,9 @@ const runProcess = Effect.fn("runProcess")(
|
||||
readonly errorMessage: string;
|
||||
}) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
|
||||
// shell mode would re-tokenize the PowerShell `-Command` payload (which
|
||||
// contains pipes) before PowerShell ever sees it.
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd: process.cwd(),
|
||||
@@ -369,8 +373,10 @@ function readWindowsProcessRows(): Effect.Effect<
|
||||
);
|
||||
}
|
||||
|
||||
export const readProcessRows = (platform = process.platform) =>
|
||||
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
export const readProcessRows = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
});
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
readonly serverPid: number;
|
||||
@@ -387,7 +393,7 @@ function assertDescendantPid(
|
||||
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
|
||||
}
|
||||
|
||||
return readProcessRows().pipe(
|
||||
return readProcessRows.pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
|
||||
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
|
||||
@@ -407,7 +413,7 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
|
||||
const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows().pipe(
|
||||
const rows = yield* readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
return makeResult({ serverPid: process.pid, rows, readAt });
|
||||
|
||||
@@ -252,7 +252,7 @@ export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
|
||||
const rows = yield* readProcessRows().pipe(
|
||||
const rows = yield* readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const samples = collectMonitoredSamples({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -11,8 +12,8 @@ import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/Serv
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||
switch (process.platform) {
|
||||
function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "darwin";
|
||||
case "linux":
|
||||
@@ -24,8 +25,10 @@ function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||
}
|
||||
}
|
||||
|
||||
function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
|
||||
switch (process.arch) {
|
||||
function platformArch(
|
||||
architecture: NodeJS.Architecture,
|
||||
): ExecutionEnvironmentDescriptor["platform"]["arch"] {
|
||||
switch (architecture) {
|
||||
case "arm64":
|
||||
return "arm64";
|
||||
case "x64":
|
||||
@@ -40,6 +43,8 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const hostArchitecture = yield* HostProcessArchitecture;
|
||||
|
||||
const readPersistedEnvironmentId = Effect.gen(function* () {
|
||||
const exists = yield* fileSystem
|
||||
@@ -80,8 +85,8 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
environmentId,
|
||||
label,
|
||||
platform: {
|
||||
os: platformOs(),
|
||||
arch: platformArch(),
|
||||
os: platformOs(hostPlatform),
|
||||
arch: platformArch(hostArchitecture),
|
||||
},
|
||||
serverVersion: packageJson.version,
|
||||
capabilities: {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import { ProcessRunner, ProcessSpawnError, type ProcessRunnerShape } from "../../processRunner.ts";
|
||||
@@ -28,6 +29,16 @@ const LinuxMachineInfoLayer = Layer.merge(
|
||||
: Effect.succeed(""),
|
||||
}),
|
||||
);
|
||||
const withHostPlatform = <ROut, E, RIn>(
|
||||
layer: Layer.Layer<ROut, E, RIn>,
|
||||
platform: NodeJS.Platform,
|
||||
hostname: string,
|
||||
) =>
|
||||
Layer.mergeAll(
|
||||
layer,
|
||||
Layer.succeed(HostProcessPlatform, platform),
|
||||
Layer.succeed(HostProcessHostname, hostname),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
runMock.mockReset();
|
||||
@@ -38,9 +49,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "macbook-pro")));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
@@ -61,9 +70,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
|
||||
|
||||
expect(result).toBe("Julius's MacBook Pro");
|
||||
expect(runMock).toHaveBeenCalledWith(
|
||||
@@ -80,9 +87,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "buildbox",
|
||||
}).pipe(Effect.provide(LinuxMachineInfoLayer));
|
||||
}).pipe(Effect.provide(withHostPlatform(LinuxMachineInfoLayer, "linux", "buildbox")));
|
||||
|
||||
expect(result).toBe("Build Agent 01");
|
||||
expect(runMock).not.toHaveBeenCalled();
|
||||
@@ -104,9 +109,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "runner-01",
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", "runner-01")));
|
||||
|
||||
expect(result).toBe("CI Runner");
|
||||
expect(runMock).toHaveBeenCalledWith(
|
||||
@@ -123,9 +126,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "JULIUS-LAPTOP",
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "JULIUS-LAPTOP")));
|
||||
|
||||
expect(result).toBe("JULIUS-LAPTOP");
|
||||
}),
|
||||
@@ -145,9 +146,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
@@ -168,9 +167,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: " ",
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", " ")));
|
||||
|
||||
expect(result).toBe("t3code");
|
||||
}),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as OS from "node:os";
|
||||
|
||||
import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -8,8 +7,6 @@ import { ProcessRunner } from "../../processRunner.ts";
|
||||
|
||||
interface ResolveServerEnvironmentLabelInput {
|
||||
readonly cwdBaseName: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly hostname?: string | null;
|
||||
}
|
||||
|
||||
function normalizeLabel(value: string | null | undefined): string | null {
|
||||
@@ -69,9 +66,8 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
return normalizeLabel(result.value.stdout);
|
||||
});
|
||||
|
||||
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
|
||||
platform: NodeJS.Platform,
|
||||
) {
|
||||
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
if (platform === "darwin") {
|
||||
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
|
||||
}
|
||||
@@ -94,13 +90,12 @@ const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function*
|
||||
export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
|
||||
input: ResolveServerEnvironmentLabelInput,
|
||||
) {
|
||||
const platform = input.platform ?? process.platform;
|
||||
const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
|
||||
const friendlyHostLabel = yield* resolveFriendlyHostLabel();
|
||||
if (friendlyHostLabel) {
|
||||
return friendlyHostLabel;
|
||||
}
|
||||
|
||||
const hostname = normalizeLabel(input.hostname ?? OS.hostname());
|
||||
const hostname = normalizeLabel(yield* HostProcessHostname);
|
||||
if (hostname) {
|
||||
return hostname;
|
||||
}
|
||||
|
||||
+22
-83
@@ -24,15 +24,13 @@ import {
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths.ts";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||
import { resolveStaticDir, ServerConfig } from "./config.ts";
|
||||
import {
|
||||
ASSET_ROUTE_PREFIX,
|
||||
FALLBACK_PROJECT_FAVICON_SVG,
|
||||
resolveAsset,
|
||||
} from "./assets/AssetAccess.ts";
|
||||
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import {
|
||||
annotateEnvironmentRequest,
|
||||
@@ -43,8 +41,6 @@ import {
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
|
||||
|
||||
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
|
||||
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
|
||||
@@ -169,107 +165,50 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
),
|
||||
);
|
||||
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
export const assetRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
||||
`${ASSET_ROUTE_PREFIX}/*`,
|
||||
Effect.gen(function* () {
|
||||
yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
return HttpServerResponse.text("Invalid attachment path", { status: 400 });
|
||||
}
|
||||
|
||||
const isIdLookup =
|
||||
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||
const filePath = isIdLookup
|
||||
? resolveAttachmentPathById({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentId: normalizedRelativePath,
|
||||
})
|
||||
: resolveAttachmentRelativePath({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
relativePath: normalizedRelativePath,
|
||||
});
|
||||
if (!filePath) {
|
||||
return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
|
||||
status: isIdLookup ? 404 : 400,
|
||||
});
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
if (separatorIndex <= 0) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(filePath, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
const asset = yield* resolveAsset(
|
||||
suffix.slice(0, separatorIndex),
|
||||
suffix.slice(separatorIndex + 1),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
|
||||
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
||||
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const projectFaviconRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/project-favicon",
|
||||
Effect.gen(function* () {
|
||||
yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
if (!asset) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
const projectCwd = url.value.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
|
||||
}
|
||||
|
||||
const faviconResolver = yield* ProjectFaviconResolver;
|
||||
const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
|
||||
if (!faviconFilePath) {
|
||||
if (asset.kind === "project-favicon-fallback") {
|
||||
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
|
||||
status: 200,
|
||||
contentType: "image/svg+xml",
|
||||
headers: {
|
||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(faviconFilePath, {
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
|
||||
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
||||
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
|
||||
@@ -205,6 +205,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
|
||||
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { McpSchema, McpServer } from "effect/unstable/ai";
|
||||
import { HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as McpHttpServer from "./McpHttpServer.ts";
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-mcp-test");
|
||||
const threadId = ThreadId.make("thread-mcp-test");
|
||||
const tabId = PreviewTabId.make("tab-mcp-test");
|
||||
const invocation = {
|
||||
environmentId,
|
||||
threadId,
|
||||
providerSessionId: "provider-session-mcp-test",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
const client = McpSchema.McpServerClient.of({
|
||||
clientId: 1,
|
||||
initializePayload: {
|
||||
protocolVersion: "2025-03-26",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "mcp-test", version: "1.0.0" },
|
||||
},
|
||||
getClient: Effect.die("unused"),
|
||||
});
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
|
||||
HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
|
||||
);
|
||||
expect(notificationResponse.status).toBe(202);
|
||||
|
||||
const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
|
||||
HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
|
||||
);
|
||||
expect(resultResponse.status).toBe(200);
|
||||
});
|
||||
|
||||
it.effect("registers annotated tools and preserves authenticated request context", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect("mcp-test-client");
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
|
||||
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
|
||||
expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
|
||||
|
||||
const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
|
||||
expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
|
||||
expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
|
||||
|
||||
const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
|
||||
expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
|
||||
expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
|
||||
expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
|
||||
|
||||
const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
|
||||
expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
|
||||
expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
|
||||
|
||||
const status = yield* server
|
||||
.callTool({ name: "preview_status", arguments: {} })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(status.isError).toBe(false);
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
available: true,
|
||||
tabId,
|
||||
});
|
||||
|
||||
const malformed = yield* server
|
||||
.callTool({ name: "preview_click", arguments: { selector: "" } })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(malformed.isError).toBe(true);
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: {} })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(snapshot.isError).toBe(false);
|
||||
expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
|
||||
expect(snapshot.structuredContent).toMatchObject({
|
||||
screenshot: { mimeType: "image/png", width: 10, height: 5 },
|
||||
});
|
||||
|
||||
const press = yield* server
|
||||
.callTool({ name: "preview_press", arguments: { key: "Enter" } })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(press.isError).toBe(false);
|
||||
expect(press.structuredContent).toBeNull();
|
||||
expect(press.content).toEqual([{ type: "text", text: "null" }]);
|
||||
}),
|
||||
).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
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 Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type * as Types from "effect/Types";
|
||||
import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
import {
|
||||
PreviewSnapshotToolkitHandlersLive,
|
||||
PreviewStandardToolkitHandlersLive,
|
||||
} from "./toolkits/preview/handlers.ts";
|
||||
import {
|
||||
PreviewSnapshotTool,
|
||||
PreviewSnapshotToolkit,
|
||||
PreviewStandardToolkit,
|
||||
} from "./toolkits/preview/tools.ts";
|
||||
|
||||
const unauthorized = HttpServerResponse.jsonUnsafe(
|
||||
{
|
||||
error: "invalid_mcp_credential",
|
||||
message: "A valid provider-scoped MCP bearer credential is required.",
|
||||
},
|
||||
{
|
||||
status: 401,
|
||||
headers: {
|
||||
"cache-control": "no-store",
|
||||
"www-authenticate": "Bearer",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
type AuthenticatedHttpEffect = Effect.Effect<
|
||||
HttpServerResponse.HttpServerResponse,
|
||||
Types.unhandled,
|
||||
McpInvocationContext.McpInvocationContext
|
||||
>;
|
||||
|
||||
type McpAuthMiddleware = (
|
||||
httpEffect: AuthenticatedHttpEffect,
|
||||
) => Effect.Effect<
|
||||
HttpServerResponse.HttpServerResponse,
|
||||
Types.unhandled,
|
||||
HttpServerRequest.HttpServerRequest
|
||||
>;
|
||||
|
||||
export const normalizeMcpHttpResponse = (
|
||||
response: HttpServerResponse.HttpServerResponse,
|
||||
): HttpServerResponse.HttpServerResponse => {
|
||||
const bodyIsEmpty =
|
||||
response.body._tag === "Empty" ||
|
||||
(response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
|
||||
(response.body._tag === "Raw" && response.body.contentLength === 0);
|
||||
return response.status === 200 && bodyIsEmpty
|
||||
? HttpServerResponse.setStatus(response, 202)
|
||||
: response;
|
||||
};
|
||||
|
||||
const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
|
||||
Effect.map(
|
||||
(registry): McpAuthMiddleware =>
|
||||
Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const authorization = request.headers.authorization;
|
||||
const token =
|
||||
authorization?.startsWith("Bearer ") === true
|
||||
? authorization.slice("Bearer ".length).trim()
|
||||
: "";
|
||||
const invocation = yield* registry.resolve(token);
|
||||
if (!invocation) return unauthorized;
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.map(normalizeMcpHttpResponse),
|
||||
);
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
|
||||
);
|
||||
|
||||
const McpAuthMiddlewareLive = HttpRouter.middleware<{
|
||||
provides: McpInvocationContext.McpInvocationContext;
|
||||
}>()(makeMcpAuthMiddleware).layer;
|
||||
|
||||
const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const built = yield* PreviewSnapshotToolkit;
|
||||
const tool = PreviewSnapshotTool;
|
||||
yield* server.addTool({
|
||||
tool: new McpSchema.Tool({
|
||||
name: tool.name,
|
||||
description: Tool.getDescription(tool),
|
||||
inputSchema: Tool.getJsonSchema(tool),
|
||||
annotations: {
|
||||
...Context.getOption(tool.annotations, Tool.Title).pipe(
|
||||
Option.map((title) => ({ title })),
|
||||
Option.getOrUndefined,
|
||||
),
|
||||
readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
|
||||
destructiveHint: Context.get(tool.annotations, Tool.Destructive),
|
||||
idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
|
||||
openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
|
||||
},
|
||||
}),
|
||||
annotations: tool.annotations,
|
||||
handle: (payload) =>
|
||||
Effect.withFiber((fiber) => {
|
||||
const invocation = Context.getUnsafe(
|
||||
fiber.context,
|
||||
McpInvocationContext.McpInvocationContext,
|
||||
);
|
||||
return built.handle("preview_snapshot", payload).pipe(
|
||||
Stream.unwrap,
|
||||
Stream.run(Sink.last()),
|
||||
Effect.flatMap(Effect.fromOption),
|
||||
Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.matchCause({
|
||||
onFailure: (cause) =>
|
||||
new McpSchema.CallToolResult({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: Cause.pretty(cause) }],
|
||||
}),
|
||||
onSuccess: ({ encodedResult }) => {
|
||||
const snapshot = encodedResult as {
|
||||
readonly screenshot: {
|
||||
readonly mimeType: "image/png";
|
||||
readonly data: string;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
};
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
const { screenshot, ...page } = snapshot;
|
||||
const metadata = {
|
||||
...page,
|
||||
screenshot: {
|
||||
mimeType: screenshot.mimeType,
|
||||
width: screenshot.width,
|
||||
height: screenshot.height,
|
||||
},
|
||||
};
|
||||
return new McpSchema.CallToolResult({
|
||||
isError: false,
|
||||
structuredContent: metadata,
|
||||
content: [
|
||||
{ type: "text", text: JSON.stringify(metadata) },
|
||||
{
|
||||
type: "image",
|
||||
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
|
||||
mimeType: screenshot.mimeType,
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
const PreviewStandardToolkitRegistrationLive = McpServer.toolkit(PreviewStandardToolkit).pipe(
|
||||
Layer.provide(PreviewStandardToolkitHandlersLive),
|
||||
);
|
||||
|
||||
const PreviewSnapshotRegistrationLive = Layer.effectDiscard(registerPreviewSnapshot()).pipe(
|
||||
Layer.provide(PreviewSnapshotToolkitHandlersLive),
|
||||
);
|
||||
|
||||
export const PreviewToolkitRegistrationLive = Layer.mergeAll(
|
||||
PreviewStandardToolkitRegistrationLive,
|
||||
PreviewSnapshotRegistrationLive,
|
||||
);
|
||||
|
||||
const McpTransportLive = McpServer.layerHttp({
|
||||
name: "T3 Code",
|
||||
version: packageJson.version,
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export type McpCapability = "preview";
|
||||
|
||||
export interface McpInvocationScope {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerSessionId: string;
|
||||
readonly providerInstanceId: ProviderInstanceId;
|
||||
readonly capabilities: ReadonlySet<McpCapability>;
|
||||
readonly issuedAt: number;
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
export class McpInvocationContext extends Context.Service<
|
||||
McpInvocationContext,
|
||||
McpInvocationScope
|
||||
>()("t3/mcp/McpInvocationContext") {}
|
||||
|
||||
export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
|
||||
capability: McpCapability,
|
||||
) {
|
||||
const invocation = yield* McpInvocationContext;
|
||||
if (!invocation.capabilities.has(capability)) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: `MCP credential does not grant the ${capability} capability.`,
|
||||
});
|
||||
}
|
||||
return invocation;
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export interface McpProviderSessionConfig {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerSessionId: string;
|
||||
readonly providerInstanceId: ProviderInstanceId;
|
||||
readonly endpoint: string;
|
||||
readonly authorizationHeader: string;
|
||||
}
|
||||
|
||||
const sessionsByThread = new Map<ThreadId, McpProviderSessionConfig>();
|
||||
|
||||
export function setMcpProviderSession(config: McpProviderSessionConfig): void {
|
||||
sessionsByThread.set(config.threadId, config);
|
||||
}
|
||||
|
||||
export function readMcpProviderSession(threadId: ThreadId): McpProviderSessionConfig | undefined {
|
||||
return sessionsByThread.get(threadId);
|
||||
}
|
||||
|
||||
export function clearMcpProviderSession(threadId: ThreadId): void {
|
||||
sessionsByThread.delete(threadId);
|
||||
}
|
||||
|
||||
export function clearAllMcpProviderSessions(): void {
|
||||
sessionsByThread.clear();
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { HttpServer } from "effect/unstable/http";
|
||||
|
||||
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
|
||||
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const fakeHttpServer = HttpServer.HttpServer.of({
|
||||
address: { _tag: "TcpAddress", hostname: "127.0.0.1", port: 43123 },
|
||||
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
|
||||
});
|
||||
const fakeEnvironment = ServerEnvironment.of({
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.die("unused"),
|
||||
});
|
||||
|
||||
const makeRegistry = (now: () => number) =>
|
||||
McpSessionRegistry.__testing
|
||||
.make({
|
||||
now,
|
||||
idleTimeoutMs: 100,
|
||||
maximumLifetimeMs: 1_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
|
||||
Effect.provideService(ServerEnvironment, fakeEnvironment),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.effect("stores only a token hash, resolves the bearer token, and revokes by thread", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const issued = yield* registry.issue({
|
||||
threadId,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
expect(issued.config.endpoint).toBe("http://127.0.0.1:43123/mcp");
|
||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
expect(token.length).toBeGreaterThan(20);
|
||||
|
||||
const resolved = yield* registry.resolve(token);
|
||||
expect(resolved?.threadId).toBe(threadId);
|
||||
|
||||
yield* registry.revokeThread(threadId);
|
||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||
|
||||
timestamp += 2_000;
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("expires credentials after inactivity", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
const issued = yield* registry.issue({
|
||||
threadId: ThreadId.make("thread-2"),
|
||||
providerInstanceId: ProviderInstanceId.make("claude"),
|
||||
});
|
||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
timestamp += 101;
|
||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,207 @@
|
||||
import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import { HttpServer } from "effect/unstable/http";
|
||||
|
||||
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
import * as McpProviderSession from "./McpProviderSession.ts";
|
||||
|
||||
export interface McpCredentialRequest {
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerInstanceId: ProviderInstanceId;
|
||||
}
|
||||
|
||||
export interface McpIssuedCredential {
|
||||
readonly config: McpProviderSession.McpProviderSessionConfig;
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
export interface McpSessionRegistryShape {
|
||||
readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
|
||||
readonly resolve: (
|
||||
rawToken: string,
|
||||
) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
|
||||
readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
|
||||
readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
|
||||
readonly revokeAll: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class McpSessionRegistry extends Context.Service<
|
||||
McpSessionRegistry,
|
||||
McpSessionRegistryShape
|
||||
>()("t3/mcp/McpSessionRegistry") {}
|
||||
|
||||
interface CredentialRecord {
|
||||
readonly tokenHash: string;
|
||||
readonly scope: McpInvocationContext.McpInvocationScope;
|
||||
readonly lastUsedAt: number;
|
||||
}
|
||||
|
||||
interface RegistryState {
|
||||
readonly records: ReadonlyMap<string, CredentialRecord>;
|
||||
}
|
||||
|
||||
export interface McpSessionRegistryOptions {
|
||||
readonly idleTimeoutMs?: number;
|
||||
readonly maximumLifetimeMs?: number;
|
||||
readonly now?: () => number;
|
||||
}
|
||||
|
||||
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
|
||||
const DEFAULT_MAXIMUM_LIFETIME_MS = 8 * 60 * 60 * 1_000;
|
||||
|
||||
const bytesToHex = (bytes: Uint8Array): string =>
|
||||
Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
|
||||
const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
|
||||
|
||||
const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
options: McpSessionRegistryOptions = {},
|
||||
) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const environment = yield* ServerEnvironment;
|
||||
const environmentId = yield* environment.getEnvironmentId;
|
||||
const httpServer = yield* HttpServer.HttpServer;
|
||||
const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
|
||||
const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
|
||||
const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
||||
const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
|
||||
const endpoint =
|
||||
httpServer.address._tag === "TcpAddress"
|
||||
? `http://127.0.0.1:${httpServer.address.port}/mcp`
|
||||
: "http://127.0.0.1/mcp";
|
||||
|
||||
const hashToken = (token: string) =>
|
||||
crypto
|
||||
.digest("SHA-256", new TextEncoder().encode(token))
|
||||
.pipe(Effect.map(bytesToHex), Effect.orDie);
|
||||
|
||||
const pruneExpired = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
|
||||
const next = new Map(
|
||||
Array.from(records).filter(
|
||||
([, record]) =>
|
||||
timestamp <= record.scope.expiresAt && timestamp - record.lastUsedAt <= idleTimeoutMs,
|
||||
),
|
||||
);
|
||||
return next.size === records.size ? records : next;
|
||||
};
|
||||
|
||||
const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
|
||||
function* (request) {
|
||||
const issuedAt = yield* currentTimeMillis;
|
||||
const providerSessionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
|
||||
const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
|
||||
const tokenHash = yield* hashToken(rawToken);
|
||||
const expiresAt = issuedAt + maximumLifetimeMs;
|
||||
const scope: McpInvocationContext.McpInvocationScope = {
|
||||
environmentId,
|
||||
threadId: ThreadId.make(request.threadId),
|
||||
providerSessionId,
|
||||
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
|
||||
capabilities: new Set(["preview"]),
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
};
|
||||
yield* SynchronizedRef.update(state, ({ records }) => {
|
||||
const next = new Map(pruneExpired(records, issuedAt));
|
||||
next.set(tokenHash, { tokenHash, scope, lastUsedAt: issuedAt });
|
||||
return { records: next };
|
||||
});
|
||||
return {
|
||||
config: {
|
||||
environmentId,
|
||||
threadId: scope.threadId,
|
||||
providerSessionId,
|
||||
providerInstanceId: scope.providerInstanceId,
|
||||
endpoint,
|
||||
authorizationHeader: `Bearer ${rawToken}`,
|
||||
},
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve")(
|
||||
function* (rawToken) {
|
||||
if (rawToken.length === 0) return undefined;
|
||||
const tokenHash = yield* hashToken(rawToken);
|
||||
const timestamp = yield* currentTimeMillis;
|
||||
return yield* SynchronizedRef.modify(state, ({ records }) => {
|
||||
const current = pruneExpired(records, timestamp);
|
||||
const record = current.get(tokenHash);
|
||||
if (!record) return [undefined, { records: current }] as const;
|
||||
const next = new Map(current);
|
||||
next.set(tokenHash, { ...record, lastUsedAt: timestamp });
|
||||
return [record.scope, { records: next }] as const;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
|
||||
SynchronizedRef.update(state, ({ records }) => ({
|
||||
records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
|
||||
}));
|
||||
|
||||
return McpSessionRegistry.of({
|
||||
issue,
|
||||
resolve,
|
||||
revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
|
||||
function* (providerSessionId) {
|
||||
yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);
|
||||
},
|
||||
),
|
||||
revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
|
||||
yield* revokeWhere((record) => record.scope.threadId === threadId);
|
||||
}),
|
||||
revokeAll: SynchronizedRef.set(state, { records: new Map() }),
|
||||
});
|
||||
});
|
||||
|
||||
let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
|
||||
|
||||
const make = Effect.acquireRelease(
|
||||
makeWithOptions().pipe(
|
||||
Effect.tap((registry) =>
|
||||
Effect.sync(() => {
|
||||
activeMcpSessionRegistry = registry;
|
||||
}),
|
||||
),
|
||||
),
|
||||
(registry) =>
|
||||
Effect.sync(() => {
|
||||
if (activeMcpSessionRegistry === registry) {
|
||||
activeMcpSessionRegistry = undefined;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const layer: Layer.Layer<
|
||||
McpSessionRegistry,
|
||||
never,
|
||||
Crypto.Crypto | ServerEnvironment | HttpServer.HttpServer
|
||||
> = Layer.effect(McpSessionRegistry, make);
|
||||
|
||||
export const issueActiveMcpCredential = (
|
||||
request: McpCredentialRequest,
|
||||
): Effect.Effect<McpIssuedCredential | undefined> =>
|
||||
activeMcpSessionRegistry
|
||||
? activeMcpSessionRegistry
|
||||
.revokeThread(request.threadId)
|
||||
.pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
|
||||
: Effect.sync((): McpIssuedCredential | undefined => undefined);
|
||||
|
||||
export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
|
||||
activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
|
||||
|
||||
export const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
|
||||
activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
|
||||
|
||||
/** Exposed for tests. */
|
||||
export const __testing = {
|
||||
make: makeWithOptions,
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
|
||||
const scope = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
providerSessionId: "provider-session-1",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
it.effect("routes a request to the focused owner and correlates its response", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const requests = yield* broker.connect("client-1");
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: { available: true },
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
tabId: null,
|
||||
visible: false,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const result = yield* broker.invoke<{ available: boolean }>({
|
||||
scope,
|
||||
operation: "open",
|
||||
input: {},
|
||||
});
|
||||
|
||||
expect(result).toEqual({ available: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const requests = yield* broker.connect("client-hidden");
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "client-hidden",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
tabId: "tab-hidden",
|
||||
visible: false,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,309 @@
|
||||
import {
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnavailableError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationResponse,
|
||||
type PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
|
||||
export interface PreviewAutomationInvokeInput {
|
||||
readonly scope: McpInvocationContext.McpInvocationScope;
|
||||
readonly operation: PreviewAutomationOperation;
|
||||
readonly input: unknown;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationBrokerShape {
|
||||
readonly connect: (clientId: string) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (clientId: string) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly invoke: <A = unknown>(
|
||||
request: PreviewAutomationInvokeInput,
|
||||
) => Effect.Effect<A, PreviewAutomationError>;
|
||||
}
|
||||
|
||||
export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
PreviewAutomationBrokerShape
|
||||
>()("t3/mcp/PreviewAutomationBroker") {}
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly queue: Queue.Queue<
|
||||
Parameters<PreviewAutomationBrokerShape["respond"]>[0] extends never
|
||||
? never
|
||||
: import("@t3tools/contracts").PreviewAutomationRequest
|
||||
>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
readonly clientId: string;
|
||||
readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;
|
||||
}
|
||||
|
||||
interface BrokerState {
|
||||
readonly clients: ReadonlyMap<string, ClientConnection>;
|
||||
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
|
||||
readonly pending: ReadonlyMap<string, PendingRequest>;
|
||||
readonly requestSequence: number;
|
||||
}
|
||||
|
||||
const makeResponseError = (
|
||||
error: NonNullable<PreviewAutomationResponse["error"]>,
|
||||
): PreviewAutomationError => {
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({ message: error.message });
|
||||
case "PreviewAutomationUnsupportedClientError":
|
||||
return new PreviewAutomationUnsupportedClientError({ message: error.message });
|
||||
case "PreviewAutomationTabNotFoundError":
|
||||
return new PreviewAutomationTabNotFoundError({ message: error.message });
|
||||
case "PreviewAutomationTimeoutError":
|
||||
return new PreviewAutomationTimeoutError({ message: error.message });
|
||||
case "PreviewAutomationControlInterruptedError":
|
||||
return new PreviewAutomationControlInterruptedError({ message: error.message });
|
||||
case "PreviewAutomationInvalidSelectorError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
return new PreviewAutomationInvalidSelectorError({
|
||||
message: error.message,
|
||||
selector:
|
||||
detail && "selector" in detail && typeof detail.selector === "string"
|
||||
? detail.selector
|
||||
: "",
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationResultTooLargeError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
return new PreviewAutomationResultTooLargeError({
|
||||
message: error.message,
|
||||
maximumBytes:
|
||||
detail && "maximumBytes" in detail && typeof detail.maximumBytes === "number"
|
||||
? detail.maximumBytes
|
||||
: 64_000,
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationUnavailableError":
|
||||
return new PreviewAutomationUnavailableError({ message: error.message });
|
||||
default:
|
||||
return new PreviewAutomationExecutionError({
|
||||
message: error.message,
|
||||
detail: error.detail,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
owners: new Map(),
|
||||
pending: new Map(),
|
||||
requestSequence: 0,
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
) {
|
||||
const toFail = yield* SynchronizedRef.modify(state, (current) => {
|
||||
if (current.clients.get(clientId)?.queue !== queue) {
|
||||
return [[] as ReadonlyArray<PendingRequest>, current] as const;
|
||||
}
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
clients.delete(clientId);
|
||||
owners.delete(clientId);
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.clientId === clientId) {
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
}
|
||||
return [disconnected, { ...current, clients, owners, pending }] as const;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
toFail,
|
||||
({ deferred }) =>
|
||||
Deferred.fail(
|
||||
deferred,
|
||||
new PreviewAutomationUnavailableError({
|
||||
message: "The preview automation client disconnected.",
|
||||
}),
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* Queue.shutdown(queue);
|
||||
});
|
||||
|
||||
const connect: PreviewAutomationBrokerShape["connect"] = Effect.fn(
|
||||
"PreviewAutomationBroker.connect",
|
||||
)(function* (clientId) {
|
||||
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
|
||||
const previous = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
clients.set(clientId, { clientId, queue });
|
||||
return [current.clients.get(clientId), { ...current, clients }] as const;
|
||||
});
|
||||
if (previous) yield* disconnect(clientId, previous.queue);
|
||||
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
|
||||
});
|
||||
|
||||
const reportOwner: PreviewAutomationBrokerShape["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const owners = new Map(current.owners);
|
||||
owners.set(owner.clientId, owner);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
const clearOwner: PreviewAutomationBrokerShape["clearOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.clearOwner",
|
||||
)(function* (clientId) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const owners = new Map(current.owners);
|
||||
owners.delete(clientId);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
const respond: PreviewAutomationBrokerShape["respond"] = Effect.fn(
|
||||
"PreviewAutomationBroker.respond",
|
||||
)(function* (response) {
|
||||
const pending = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const entry = current.pending.get(response.requestId);
|
||||
if (!entry) return [undefined, current] as const;
|
||||
const next = new Map(current.pending);
|
||||
next.delete(response.requestId);
|
||||
return [entry, { ...current, pending: next }] as const;
|
||||
});
|
||||
if (!pending) return;
|
||||
if (response.ok) {
|
||||
yield* Deferred.succeed(pending.deferred, response.result);
|
||||
} else {
|
||||
yield* Deferred.fail(
|
||||
pending.deferred,
|
||||
response.error
|
||||
? makeResponseError(response.error)
|
||||
: new PreviewAutomationExecutionError({
|
||||
message: "Preview automation failed without an error payload.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
|
||||
input: Parameters<PreviewAutomationBrokerShape["invoke"]>[0],
|
||||
): Effect.fn.Return<A, PreviewAutomationError> {
|
||||
const current = yield* SynchronizedRef.get(state);
|
||||
const candidates = Array.from(current.owners.values())
|
||||
.filter(
|
||||
(owner) =>
|
||||
owner.environmentId === input.scope.environmentId &&
|
||||
owner.threadId === input.scope.threadId &&
|
||||
owner.supportsAutomation,
|
||||
)
|
||||
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
|
||||
const owner = candidates[0];
|
||||
if (!owner) {
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
message: "No desktop browser host is available for this thread.",
|
||||
});
|
||||
}
|
||||
const connection = current.clients.get(owner.clientId);
|
||||
if (!connection) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: "The browser host is not connected.",
|
||||
});
|
||||
}
|
||||
if (
|
||||
input.operation !== "open" &&
|
||||
input.operation !== "status" &&
|
||||
!owner.tabId &&
|
||||
!input.tabId
|
||||
) {
|
||||
return yield* new PreviewAutomationTabNotFoundError({
|
||||
message: "The browser host does not have an active tab.",
|
||||
});
|
||||
}
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const requestId = yield* SynchronizedRef.modify(state, (next) => {
|
||||
const requestId = `preview-${next.requestSequence}`;
|
||||
const pending = new Map(next.pending);
|
||||
pending.set(requestId, { clientId: owner.clientId, deferred });
|
||||
return [requestId, { ...next, pending, requestSequence: next.requestSequence + 1 }] as const;
|
||||
});
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
pending.delete(requestId);
|
||||
return { ...next, pending };
|
||||
});
|
||||
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: input.tabId ?? owner.tabId ?? undefined,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
});
|
||||
if (!offered) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: "The preview automation client is no longer accepting requests.",
|
||||
});
|
||||
}
|
||||
const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(timeoutMs));
|
||||
return yield* Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new PreviewAutomationTimeoutError({
|
||||
message: `Preview automation timed out after ${timeoutMs}ms.`,
|
||||
}),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value as A),
|
||||
});
|
||||
});
|
||||
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
|
||||
/** Exposed for tests. */
|
||||
export const __testing = {
|
||||
make,
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
|
||||
import { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from "./tools.ts";
|
||||
|
||||
const invoke = Effect.fn("PreviewToolkit.invoke")(function* <A>(
|
||||
operation: PreviewAutomationOperation,
|
||||
input: unknown,
|
||||
timeoutMs?: number,
|
||||
): Effect.fn.Return<
|
||||
A,
|
||||
import("@t3tools/contracts").PreviewAutomationError,
|
||||
McpInvocationContext.McpInvocationContext | PreviewAutomationBroker.PreviewAutomationBroker
|
||||
> {
|
||||
const scope = yield* McpInvocationContext.requireMcpCapability("preview");
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
return yield* broker.invoke<A>({
|
||||
scope,
|
||||
operation,
|
||||
input,
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
});
|
||||
});
|
||||
|
||||
const handlers = {
|
||||
preview_status: () => invoke<PreviewAutomationStatus>("status", {}),
|
||||
preview_open: (input) =>
|
||||
invoke<PreviewAutomationStatus>("open", {
|
||||
...input,
|
||||
show: input.show ?? true,
|
||||
reuseExistingTab: input.reuseExistingTab ?? true,
|
||||
}),
|
||||
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
|
||||
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_press: (input) => invoke<void>("press", input).pipe(Effect.as(null)),
|
||||
preview_scroll: (input) => invoke<void>("scroll", input).pipe(Effect.as(null)),
|
||||
preview_evaluate: (input) =>
|
||||
invoke<unknown>("evaluate", input).pipe(Effect.map((result) => result ?? null)),
|
||||
preview_wait_for: (input) =>
|
||||
invoke<void>("waitFor", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_recording_start: () => invoke<PreviewAutomationRecordingStatus>("recordingStart", {}),
|
||||
preview_recording_stop: () => invoke<PreviewAutomationRecordingArtifact>("recordingStop", {}),
|
||||
} satisfies Parameters<typeof PreviewToolkit.toLayer>[0];
|
||||
|
||||
const { preview_snapshot, ...standardHandlers } = handlers;
|
||||
|
||||
export const PreviewStandardToolkitHandlersLive = PreviewStandardToolkit.toLayer(standardHandlers);
|
||||
|
||||
export const PreviewSnapshotToolkitHandlersLive = PreviewSnapshotToolkit.toLayer({
|
||||
preview_snapshot,
|
||||
});
|
||||
|
||||
export const PreviewToolkitHandlersLive = PreviewToolkit.toLayer(handlers);
|
||||
@@ -0,0 +1,37 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Tool } from "effect/unstable/ai";
|
||||
|
||||
import { PreviewToolkit } from "./tools.ts";
|
||||
|
||||
const schemaHasDescription = (schema: unknown): boolean => {
|
||||
if (!schema || typeof schema !== "object") return false;
|
||||
const record = schema as Record<string, unknown>;
|
||||
if (typeof record.description === "string" && record.description.length > 0) return true;
|
||||
return [record.anyOf, record.oneOf, record.allOf]
|
||||
.filter(Array.isArray)
|
||||
.some((members) => members.some(schemaHasDescription));
|
||||
};
|
||||
|
||||
it("exports provider-compatible object schemas with described parameters", () => {
|
||||
for (const tool of Object.values(PreviewToolkit.tools)) {
|
||||
const schema = Tool.getJsonSchema(tool) as {
|
||||
readonly type?: unknown;
|
||||
readonly properties?: Readonly<Record<string, unknown>>;
|
||||
readonly anyOf?: unknown;
|
||||
readonly oneOf?: unknown;
|
||||
};
|
||||
expect(
|
||||
tool.description?.length ?? 0,
|
||||
`${tool.name} should have a useful description`,
|
||||
).toBeGreaterThan(40);
|
||||
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
|
||||
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
|
||||
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
|
||||
for (const [field, fieldSchema] of Object.entries(schema.properties ?? {})) {
|
||||
expect(
|
||||
schemaHasDescription(fieldSchema),
|
||||
`${tool.name}.${field} should explain what data the agent must pass`,
|
||||
).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import {
|
||||
PreviewAutomationClickInput,
|
||||
PreviewAutomationError,
|
||||
PreviewAutomationEvaluateInput,
|
||||
PreviewAutomationNavigateInput,
|
||||
PreviewAutomationOpenInput,
|
||||
PreviewAutomationPressInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Tool, Toolkit } from "effect/unstable/ai";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
|
||||
|
||||
const dependencies = [
|
||||
McpInvocationContext.McpInvocationContext,
|
||||
PreviewAutomationBroker.PreviewAutomationBroker,
|
||||
];
|
||||
|
||||
const browserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;
|
||||
|
||||
const safeBrowserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
browserTool(tool).annotate(Tool.Destructive, false) as T;
|
||||
|
||||
const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
safeBrowserTool(tool).annotate(Tool.Readonly, true).annotate(Tool.Idempotent, true) as T;
|
||||
|
||||
export const PreviewStatusTool = Tool.make("preview_status", {
|
||||
description:
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Get preview status")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true);
|
||||
|
||||
export const PreviewOpenTool = browserTool(
|
||||
Tool.make("preview_open", {
|
||||
description:
|
||||
"Show and initialize the browser preview for the scoped thread, optionally reusing its current tab and navigating to a URL.",
|
||||
parameters: PreviewAutomationOpenInput,
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Open browser preview")
|
||||
.annotate(Tool.Destructive, false),
|
||||
);
|
||||
|
||||
export const PreviewNavigateTool = safeBrowserTool(
|
||||
Tool.make("preview_navigate", {
|
||||
description:
|
||||
"Navigate the active collaborative browser tab. Pass {url:'https://t3.chat'} for a website, or {target:{kind:'environment-port',port:5173}} for a dev server in the current environment. Exactly one of url or target is required. Defaults to waiting for page loading to stop.",
|
||||
parameters: PreviewAutomationNavigateInput,
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Navigate browser preview"),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
"Inspect the current page before interacting. Returns URL/title/loading state, visible text, semantic interactive elements with reusable selectors and coordinates, accessibility data, recent console/network failures, action history, and a PNG screenshot.",
|
||||
success: PreviewAutomationSnapshot,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Inspect browser page"),
|
||||
);
|
||||
|
||||
export const PreviewClickTool = browserTool(
|
||||
Tool.make("preview_click", {
|
||||
description:
|
||||
"Click exactly one page target. Prefer locator with a Playwright selector such as role=button[name='Send']; selector accepts legacy CSS; x and y are viewport CSS pixels and must be supplied together. Call preview_snapshot first when the target is unknown.",
|
||||
parameters: PreviewAutomationClickInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Click preview page"),
|
||||
);
|
||||
|
||||
export const PreviewTypeTool = browserTool(
|
||||
Tool.make("preview_type", {
|
||||
description:
|
||||
"Insert literal text into one input. Prefer locator with a Playwright role/text selector; selector accepts legacy CSS. If neither is supplied, types into the currently focused element. Set clear=true to replace existing text.",
|
||||
parameters: PreviewAutomationTypeInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Type into preview page"),
|
||||
);
|
||||
|
||||
export const PreviewPressTool = browserTool(
|
||||
Tool.make("preview_press", {
|
||||
description:
|
||||
"Press one keyboard key in the active page, for example {key:'Enter'}, {key:'Escape'}, or {key:'a',modifiers:['Meta']}. This targets the page's current focus.",
|
||||
parameters: PreviewAutomationPressInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Press key in preview page"),
|
||||
);
|
||||
|
||||
export const PreviewScrollTool = safeBrowserTool(
|
||||
Tool.make("preview_scroll", {
|
||||
description:
|
||||
"Scroll by CSS pixels. Positive deltaY scrolls down and positive deltaX scrolls right. Without locator/selector it scrolls the viewport; otherwise it scrolls that container. At least one delta is required.",
|
||||
parameters: PreviewAutomationScrollInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Scroll preview page"),
|
||||
);
|
||||
|
||||
export const PreviewEvaluateTool = browserTool(
|
||||
Tool.make("preview_evaluate", {
|
||||
description:
|
||||
"Evaluate a JavaScript expression in the page's main frame and return a serializable result up to 64 KB. Prefer preview_snapshot and semantic click/type/wait tools; use this for inspection or interactions those tools cannot express. The expression may mutate page state.",
|
||||
parameters: PreviewAutomationEvaluateInput,
|
||||
success: Schema.Unknown,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Evaluate JavaScript in preview"),
|
||||
);
|
||||
|
||||
export const PreviewWaitForTool = readonlyBrowserTool(
|
||||
Tool.make("preview_wait_for", {
|
||||
description:
|
||||
"Wait until all supplied conditions match: a Playwright locator, legacy CSS selector, visible-text substring, and/or URL substring. Provide at least one condition. Defaults to 15 seconds, maximum 60 seconds.",
|
||||
parameters: PreviewAutomationWaitForInput,
|
||||
success: Schema.Null,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Wait for preview page condition"),
|
||||
);
|
||||
|
||||
export const PreviewRecordingStartTool = safeBrowserTool(
|
||||
Tool.make("preview_recording_start", {
|
||||
description:
|
||||
"Start recording the active collaborative browser tab while keeping it interactive for both agent and human use.",
|
||||
success: PreviewAutomationRecordingStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Start browser recording"),
|
||||
);
|
||||
|
||||
export const PreviewRecordingStopTool = safeBrowserTool(
|
||||
Tool.make("preview_recording_stop", {
|
||||
description: "Stop the active browser recording and save it as a local evidence artifact.",
|
||||
success: PreviewAutomationRecordingArtifact,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
}).annotate(Tool.Title, "Stop browser recording"),
|
||||
);
|
||||
|
||||
export const PreviewToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
PreviewScrollTool,
|
||||
PreviewEvaluateTool,
|
||||
PreviewWaitForTool,
|
||||
PreviewRecordingStartTool,
|
||||
PreviewRecordingStopTool,
|
||||
);
|
||||
|
||||
export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
PreviewScrollTool,
|
||||
PreviewEvaluateTool,
|
||||
PreviewWaitForTool,
|
||||
PreviewRecordingStartTool,
|
||||
PreviewRecordingStopTool,
|
||||
);
|
||||
|
||||
export const PreviewSnapshotToolkit = Toolkit.make(PreviewSnapshotTool);
|
||||
+56
-68
@@ -1,21 +1,15 @@
|
||||
import * as NodeOS from "node:os";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Path from "effect/Path";
|
||||
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import {
|
||||
readPathFromLoginShell,
|
||||
readEnvironmentFromWindowsShell,
|
||||
resolveWindowsEnvironment,
|
||||
type CommandAvailabilityOptions,
|
||||
type WindowsShellEnvironmentReader,
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLoginShell,
|
||||
readPathFromLaunchctl,
|
||||
resolveWindowsEnvironment,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
type WindowsCommandAvailabilityChecker = (
|
||||
command: string,
|
||||
options?: CommandAvailabilityOptions,
|
||||
) => boolean;
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
function logPathHydrationWarning(message: string, error?: unknown): void {
|
||||
process.stderr.write(
|
||||
@@ -23,67 +17,61 @@ function logPathHydrationWarning(message: string, error?: unknown): void {
|
||||
);
|
||||
}
|
||||
|
||||
export function fixPath(
|
||||
options: {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
readWindowsEnvironment?: WindowsShellEnvironmentReader;
|
||||
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const logWarning = options.logWarning ?? logPathHydrationWarning;
|
||||
const readPath = options.readPath ?? readPathFromLoginShell;
|
||||
|
||||
try {
|
||||
if (platform === "win32") {
|
||||
const repairedEnvironment = resolveWindowsEnvironment(env, {
|
||||
readEnvironment: options.readWindowsEnvironment ?? readEnvironmentFromWindowsShell,
|
||||
...(options.isWindowsCommandAvailable
|
||||
? { commandAvailable: options.isWindowsCommandAvailable }
|
||||
: {}),
|
||||
});
|
||||
for (const [key, value] of Object.entries(repairedEnvironment)) {
|
||||
if (value !== undefined) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
return;
|
||||
function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void {
|
||||
let shellPath: string | undefined;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL)) {
|
||||
try {
|
||||
shellPath = readPathFromLoginShell(shell);
|
||||
} catch (error) {
|
||||
logPathHydrationWarning(`Failed to read PATH from login shell ${shell}.`, error);
|
||||
}
|
||||
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
if (shellPath) break;
|
||||
}
|
||||
|
||||
let shellPath: string | undefined;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
shellPath = readPath(shell);
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read PATH from login shell ${shell}.`, error);
|
||||
}
|
||||
|
||||
if (shellPath) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellPath
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to hydrate PATH from the user environment.", error);
|
||||
const launchctlPath = platform === "darwin" && !shellPath ? readPathFromLaunchctl() : undefined;
|
||||
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
}
|
||||
|
||||
export const fixPath = Effect.fn("fixPath")(function* (): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const env = yield* HostProcessEnvironment;
|
||||
|
||||
if (platform === "win32") {
|
||||
const repairedEnvironment = yield* resolveWindowsEnvironment(env).pipe(
|
||||
Effect.catchDefect((defect) =>
|
||||
Effect.sync(() => {
|
||||
logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
|
||||
return {} as Partial<NodeJS.ProcessEnv>;
|
||||
}),
|
||||
),
|
||||
);
|
||||
for (const [key, value] of Object.entries(repairedEnvironment)) {
|
||||
if (value !== undefined) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
yield* Effect.sync(() => hydratePosixPath(env, platform)).pipe(
|
||||
Effect.catchDefect((defect) =>
|
||||
Effect.sync(() => {
|
||||
logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
export const expandHomePath = Effect.fn(function* (input: string) {
|
||||
const { join } = yield* Path.Path;
|
||||
if (input === "~") {
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { it } from "@effect/vitest";
|
||||
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
|
||||
import { Effect, PubSub } from "effect";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const DRAIN_LIMIT = 100;
|
||||
|
||||
interface EventCollector {
|
||||
/** Drain everything published since the last call (or since subscribe). */
|
||||
readonly drain: Effect.Effect<ReadonlyArray<PreviewEvent>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Each `it.effect` shares the live PreviewManager layer across the whole
|
||||
* `it.layer` block, so tests that assert per-thread counts must use a unique
|
||||
* thread id to avoid bleeding state from earlier tests.
|
||||
*/
|
||||
let nextThreadId = 0;
|
||||
const freshThreadId = () => ThreadId.make(`thread-${++nextThreadId}`);
|
||||
|
||||
/**
|
||||
* Subscribe to the manager's event stream BEFORE the test publishes. We
|
||||
* use `subscribeEvents` (synchronous PubSub.subscribe under the hood) so
|
||||
* no event can land between subscribe and the consumer drain.
|
||||
*/
|
||||
const collectEvents = Effect.gen(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const subscription = yield* manager.subscribeEvents;
|
||||
const collector: EventCollector = {
|
||||
drain: PubSub.takeUpTo(subscription, DRAIN_LIMIT),
|
||||
};
|
||||
return collector;
|
||||
}).pipe(Effect.withSpan("preview.test.collectEvents"));
|
||||
|
||||
it.layer(PreviewManager.layer)("PreviewManager", (it) => {
|
||||
it.effect("opens a session and emits opened with normalized URL", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
|
||||
const snapshot = yield* manager.open({ threadId, url: "localhost:5173" });
|
||||
expect(snapshot.tabId.startsWith("tab_")).toBe(true);
|
||||
expect(snapshot.navStatus._tag).toBe("Loading");
|
||||
if (snapshot.navStatus._tag === "Loading") {
|
||||
expect(snapshot.navStatus.url).toBe("http://localhost:5173/");
|
||||
}
|
||||
|
||||
const events = yield* collector.drain;
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("opened");
|
||||
if (events[0]?.type === "opened") {
|
||||
expect(events[0].tabId).toBe(snapshot.tabId);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("opens an Idle tab when no URL is supplied", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const snapshot = yield* manager.open({ threadId });
|
||||
expect(snapshot.navStatus._tag).toBe("Idle");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("treats bare hosts as https", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const snapshot = yield* manager.open({ threadId, url: "example.com" });
|
||||
if (snapshot.navStatus._tag === "Loading") {
|
||||
expect(snapshot.navStatus.url).toBe("https://example.com/");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects empty URL with PreviewInvalidUrlError", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const error = yield* Effect.flip(manager.open({ threadId, url: " " }));
|
||||
expect(error._tag).toBe("PreviewInvalidUrlError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("navigate updates snapshot and emits navigated", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
|
||||
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
const snapshot = yield* manager.navigate({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
url: "http://localhost:5173/about",
|
||||
resolvedTitle: "About",
|
||||
});
|
||||
|
||||
expect(snapshot.navStatus._tag).toBe("Success");
|
||||
if (snapshot.navStatus._tag === "Success") {
|
||||
expect(snapshot.navStatus.url).toBe("http://localhost:5173/about");
|
||||
expect(snapshot.navStatus.title).toBe("About");
|
||||
}
|
||||
const events = yield* collector.drain;
|
||||
expect(events.map((e) => e.type)).toEqual(["opened", "navigated"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("navigate fails for unknown tab", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const error = yield* Effect.flip(
|
||||
manager.navigate({
|
||||
threadId,
|
||||
tabId: "tab_missing",
|
||||
url: "http://localhost:5173",
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("PreviewSessionLookupError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reportStatus emits failed for LoadFailed nav", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
|
||||
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
yield* manager.reportStatus({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
navStatus: {
|
||||
_tag: "LoadFailed",
|
||||
url: "http://localhost:5173",
|
||||
title: "",
|
||||
code: -105,
|
||||
description: "ERR_NAME_NOT_RESOLVED",
|
||||
},
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
});
|
||||
|
||||
const events = yield* collector.drain;
|
||||
const failed = events.find((e) => e.type === "failed");
|
||||
expect(failed?.type).toBe("failed");
|
||||
if (failed?.type === "failed") {
|
||||
expect(failed.code).toBe(-105);
|
||||
expect(failed.description).toBe("ERR_NAME_NOT_RESOLVED");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("close removes the session and emits closed", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
|
||||
yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
yield* manager.close({ threadId });
|
||||
|
||||
const result = yield* manager.list({ threadId });
|
||||
expect(result.sessions).toHaveLength(0);
|
||||
const events = yield* collector.drain;
|
||||
const closed = events.find((e) => e.type === "closed");
|
||||
expect(closed?.type).toBe("closed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("close is idempotent for unknown threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.close({ threadId });
|
||||
const result = yield* manager.list({ threadId });
|
||||
expect(result.sessions).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("list returns every snapshot for the thread sorted by updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const first = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
const second = yield* manager.open({ threadId, url: "http://localhost:3000" });
|
||||
const result = yield* manager.list({ threadId });
|
||||
expect(result.sessions).toHaveLength(2);
|
||||
const ids = result.sessions.map((s) => s.tabId);
|
||||
expect(ids).toContain(first.tabId);
|
||||
expect(ids).toContain(second.tabId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("open creates an independent tab on every call", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
|
||||
const a = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
const b = yield* manager.open({ threadId, url: "http://localhost:3000/path" });
|
||||
|
||||
expect(a.tabId).not.toBe(b.tabId);
|
||||
const list = yield* manager.list({ threadId });
|
||||
expect(list.sessions).toHaveLength(2);
|
||||
|
||||
const events = yield* collector.drain;
|
||||
expect(events.map((e) => e.type)).toEqual(["opened", "opened"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("close with mismatching tabId is a no-op", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
yield* manager.close({ threadId, tabId: "tab_missing" });
|
||||
|
||||
const list = yield* manager.list({ threadId });
|
||||
expect(list.sessions).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("close with explicit tabId removes only that tab", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const a = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
const b = yield* manager.open({ threadId, url: "http://localhost:3000" });
|
||||
|
||||
yield* manager.close({ threadId, tabId: a.tabId });
|
||||
|
||||
const list = yield* manager.list({ threadId });
|
||||
expect(list.sessions.map((s) => s.tabId)).toEqual([b.tabId]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("multiple subscribers receive every event independently", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const aSub = yield* manager.subscribeEvents;
|
||||
const bSub = yield* manager.subscribeEvents;
|
||||
|
||||
yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
yield* manager.open({ threadId, url: "http://localhost:3000" });
|
||||
|
||||
const aEvents = yield* PubSub.takeUpTo(aSub, DRAIN_LIMIT);
|
||||
const bEvents = yield* PubSub.takeUpTo(bSub, DRAIN_LIMIT);
|
||||
expect(aEvents.map((e) => e.type)).toEqual(["opened", "opened"]);
|
||||
expect(bEvents.map((e) => e.type)).toEqual(["opened", "opened"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,362 @@
|
||||
/**
|
||||
* In-memory PreviewManager implementation.
|
||||
*
|
||||
* Sessions are keyed by `(threadId, tabId)`; a single thread can host
|
||||
* multiple tabs (browser-style). `open` always creates a new tab — tab
|
||||
* lifecycle is owned by the renderer.
|
||||
*
|
||||
* Events are published via Effect's `PubSub`, so subscriber failures are
|
||||
* isolated from the publishing call (a closed WS subscriber queue cannot
|
||||
* fail an in-progress `navigate()`).
|
||||
*/
|
||||
import {
|
||||
type PreviewCloseInput,
|
||||
type PreviewEvent,
|
||||
type PreviewError,
|
||||
PreviewInvalidUrlError,
|
||||
type PreviewListInput,
|
||||
type PreviewListResult,
|
||||
type PreviewNavigateInput,
|
||||
type PreviewOpenInput,
|
||||
type PreviewRefreshInput,
|
||||
type PreviewReportStatusInput,
|
||||
PreviewSessionLookupError,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
newPreviewTabId,
|
||||
normalizePreviewUrl,
|
||||
PreviewUrlNormalizationError,
|
||||
} from "@t3tools/shared/preview";
|
||||
import {
|
||||
Context,
|
||||
DateTime,
|
||||
Effect,
|
||||
Layer,
|
||||
PubSub,
|
||||
type Scope,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
|
||||
export interface PreviewManagerShape {
|
||||
readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly navigate: (
|
||||
input: PreviewNavigateInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
|
||||
readonly events: Stream.Stream<PreviewEvent>;
|
||||
readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
|
||||
"t3/preview/Manager/PreviewManager",
|
||||
) {}
|
||||
|
||||
interface PreviewSessionState {
|
||||
readonly threadId: string;
|
||||
readonly tabId: string;
|
||||
readonly snapshot: PreviewSessionSnapshot;
|
||||
}
|
||||
|
||||
interface ManagerState {
|
||||
/** All sessions across every thread, keyed by `${threadId}\u0000${tabId}`. */
|
||||
readonly sessions: ReadonlyMap<string, PreviewSessionState>;
|
||||
}
|
||||
|
||||
const initialState: ManagerState = { sessions: new Map() };
|
||||
|
||||
const compositeKey = (threadId: string, tabId: string): string => `${threadId}\u0000${tabId}`;
|
||||
|
||||
const sessionsForThread = (
|
||||
state: ManagerState,
|
||||
threadId: string,
|
||||
): ReadonlyArray<PreviewSessionState> => {
|
||||
const out: PreviewSessionState[] = [];
|
||||
for (const session of state.sessions.values()) {
|
||||
if (session.threadId === threadId) out.push(session);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
|
||||
Effect.try({
|
||||
try: () => normalizePreviewUrl(rawUrl),
|
||||
catch: (cause) =>
|
||||
new PreviewInvalidUrlError({
|
||||
rawUrl,
|
||||
detail:
|
||||
cause instanceof PreviewUrlNormalizationError
|
||||
? cause.detail
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: String(cause),
|
||||
}),
|
||||
});
|
||||
|
||||
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
|
||||
const buildLoadingSnapshot = (input: {
|
||||
readonly threadId: string;
|
||||
readonly tabId: string;
|
||||
readonly url: string;
|
||||
readonly title: string;
|
||||
readonly updatedAt: string;
|
||||
}): PreviewSessionSnapshot => ({
|
||||
threadId: input.threadId,
|
||||
tabId: input.tabId,
|
||||
navStatus: { _tag: "Loading", url: input.url, title: input.title },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
const buildIdleSnapshot = (input: {
|
||||
readonly threadId: string;
|
||||
readonly tabId: string;
|
||||
readonly updatedAt: string;
|
||||
}): PreviewSessionSnapshot => ({
|
||||
threadId: input.threadId,
|
||||
tabId: input.tabId,
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* PreviewManagerMake() {
|
||||
const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
|
||||
// Unbounded PubSub is fine here — events are tiny and we don't want to
|
||||
// block publishers if a subscriber is slow. WS clients backpressure on
|
||||
// their own queues downstream.
|
||||
const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
|
||||
const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
|
||||
|
||||
/**
|
||||
* Atomic read-modify-write over the session for `(threadId, tabId)`. The
|
||||
* mutator runs under the SynchronizedRef so concurrent writers cannot
|
||||
* interleave. Lookup failures travel through the modify result so both
|
||||
* branches yield the same `[A, S]` shape `modifyEffect` requires.
|
||||
*
|
||||
* The event is published INSIDE the lock so observers see events in the
|
||||
* same order as the underlying state transitions. Publishing an unbounded
|
||||
* PubSub is non-blocking, so this is cheap.
|
||||
*/
|
||||
const mutateExistingSession = <R, E>(
|
||||
threadId: string,
|
||||
tabId: string,
|
||||
mutator: (
|
||||
session: PreviewSessionState,
|
||||
) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEvent | null; result: R }, E>,
|
||||
): Effect.Effect<R, E | PreviewSessionLookupError> => {
|
||||
type ModifyResult =
|
||||
| { kind: "fail"; error: PreviewSessionLookupError }
|
||||
| { kind: "ok"; result: R };
|
||||
|
||||
return SynchronizedRef.modifyEffect(stateRef, (state) => {
|
||||
const session = state.sessions.get(compositeKey(threadId, tabId));
|
||||
if (!session) {
|
||||
return Effect.succeed([
|
||||
{ kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
|
||||
state,
|
||||
] as readonly [ModifyResult, ManagerState]);
|
||||
}
|
||||
return mutator(session).pipe(
|
||||
Effect.flatMap(
|
||||
Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
|
||||
if (emit) yield* PubSub.publish(eventsPubSub, emit);
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(compositeKey(threadId, tabId), next);
|
||||
return [{ kind: "ok", result } as ModifyResult, { sessions }] as readonly [
|
||||
ModifyResult,
|
||||
ManagerState,
|
||||
];
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.flatMap((modify) =>
|
||||
modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const open: PreviewManagerShape["open"] = Effect.fn("PreviewManager.open")(function* (input) {
|
||||
const tabId = newPreviewTabId();
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot = input.url
|
||||
? buildLoadingSnapshot({
|
||||
threadId: input.threadId,
|
||||
tabId,
|
||||
url: yield* normalizeUrl(input.url),
|
||||
title: "",
|
||||
updatedAt,
|
||||
})
|
||||
: buildIdleSnapshot({ threadId: input.threadId, tabId, updatedAt });
|
||||
yield* SynchronizedRef.update(stateRef, (state) => {
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(compositeKey(input.threadId, tabId), {
|
||||
threadId: input.threadId,
|
||||
tabId,
|
||||
snapshot,
|
||||
});
|
||||
return { sessions };
|
||||
});
|
||||
yield* PubSub.publish(eventsPubSub, {
|
||||
type: "opened",
|
||||
threadId: input.threadId,
|
||||
tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
});
|
||||
return snapshot;
|
||||
});
|
||||
|
||||
const navigate: PreviewManagerShape["navigate"] = Effect.fn("PreviewManager.navigate")(
|
||||
function* (input) {
|
||||
const url = yield* normalizeUrl(input.url);
|
||||
return yield* mutateExistingSession(
|
||||
input.threadId,
|
||||
input.tabId,
|
||||
Effect.fn("PreviewManager.navigateSession")(function* (session) {
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const previousTitle =
|
||||
session.snapshot.navStatus._tag === "Idle" ? "" : session.snapshot.navStatus.title;
|
||||
const resolvedTitle = input.resolvedTitle ?? previousTitle;
|
||||
const snapshot: PreviewSessionSnapshot = {
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
navStatus: { _tag: "Success", url, title: resolvedTitle },
|
||||
canGoBack: session.snapshot.canGoBack,
|
||||
canGoForward: session.snapshot.canGoForward,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
next: { ...session, snapshot },
|
||||
emit: {
|
||||
type: "navigated",
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
},
|
||||
result: snapshot,
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const reportStatus: PreviewManagerShape["reportStatus"] = Effect.fn(
|
||||
"PreviewManager.reportStatus",
|
||||
)(function* (input) {
|
||||
yield* mutateExistingSession(
|
||||
input.threadId,
|
||||
input.tabId,
|
||||
Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot: PreviewSessionSnapshot = {
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
navStatus: input.navStatus,
|
||||
canGoBack: input.canGoBack,
|
||||
canGoForward: input.canGoForward,
|
||||
updatedAt,
|
||||
};
|
||||
const emit: PreviewEvent =
|
||||
input.navStatus._tag === "LoadFailed"
|
||||
? {
|
||||
type: "failed",
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
url: input.navStatus.url,
|
||||
title: input.navStatus.title,
|
||||
code: input.navStatus.code,
|
||||
description: input.navStatus.description,
|
||||
}
|
||||
: {
|
||||
type: "navigated",
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
};
|
||||
return {
|
||||
next: { ...session, snapshot },
|
||||
emit,
|
||||
result: undefined as void,
|
||||
};
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const refresh: PreviewManagerShape["refresh"] = Effect.fn("PreviewManager.refresh")(
|
||||
function* (input) {
|
||||
// Verify the session exists; the desktop bridge handles the actual reload
|
||||
// and will report progress back via `reportStatus`. No event emitted.
|
||||
yield* mutateExistingSession(input.threadId, input.tabId, (session) =>
|
||||
Effect.succeed({ next: session, emit: null, result: undefined as void }),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const close: PreviewManagerShape["close"] = Effect.fn("PreviewManager.close")(function* (input) {
|
||||
const createdAt = yield* currentIsoTimestamp;
|
||||
const events = yield* SynchronizedRef.modify(stateRef, (state) => {
|
||||
const eventsToEmit: PreviewEvent[] = [];
|
||||
const sessions = new Map(state.sessions);
|
||||
const targets = input.tabId
|
||||
? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
|
||||
(entry): entry is PreviewSessionState => entry !== undefined,
|
||||
)
|
||||
: sessionsForThread(state, input.threadId);
|
||||
for (const target of targets) {
|
||||
sessions.delete(compositeKey(target.threadId, target.tabId));
|
||||
eventsToEmit.push({
|
||||
type: "closed",
|
||||
threadId: target.threadId,
|
||||
tabId: target.tabId,
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
if (eventsToEmit.length === 0) {
|
||||
return [eventsToEmit, state] as const;
|
||||
}
|
||||
return [eventsToEmit, { sessions }] as const;
|
||||
});
|
||||
if (events.length > 0) {
|
||||
yield* Effect.forEach(events, (event) => PubSub.publish(eventsPubSub, event), {
|
||||
discard: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const list: PreviewManagerShape["list"] = Effect.fn("PreviewManager.list")(function* (input) {
|
||||
return yield* SynchronizedRef.get(stateRef).pipe(
|
||||
Effect.map(
|
||||
(state): PreviewListResult => ({
|
||||
sessions: sessionsForThread(state, input.threadId)
|
||||
.map((s) => s.snapshot)
|
||||
.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
refresh,
|
||||
close,
|
||||
list,
|
||||
events,
|
||||
subscribeEvents: PubSub.subscribe(eventsPubSub),
|
||||
} satisfies PreviewManagerShape;
|
||||
}).pipe(Effect.withSpan("PreviewManager.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewManager, make);
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as net from "node:net";
|
||||
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Net from "@t3tools/shared/Net";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import { ProcessRunner } from "../processRunner.ts";
|
||||
import * as PortScanner from "./PortScanner.ts";
|
||||
const TestProcessRunner = Layer.succeed(ProcessRunner, {
|
||||
run: () => Effect.die("ProcessRunner should not be used by Windows TCP probe tests"),
|
||||
});
|
||||
const TestPortDiscoveryLive = PortScanner.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(TestProcessRunner, Net.layer, Layer.succeed(HostProcessPlatform, "win32")),
|
||||
),
|
||||
);
|
||||
|
||||
const openServer = (port: number): Effect.Effect<net.Server | null> =>
|
||||
Effect.callback((resume) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", () => {
|
||||
resume(Effect.succeed(null));
|
||||
});
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
resume(Effect.succeed(server));
|
||||
});
|
||||
return Effect.sync(() => {
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
|
||||
const closeServer = (server: net.Server): Effect.Effect<void> =>
|
||||
Effect.callback((resume) => {
|
||||
server.close(() => resume(Effect.void));
|
||||
});
|
||||
|
||||
const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
|
||||
ports: ReadonlyArray<number>,
|
||||
) {
|
||||
for (const port of ports) {
|
||||
const server = yield* openServer(port);
|
||||
if (server !== null) return { port, server };
|
||||
}
|
||||
return yield* Effect.die(
|
||||
new Error("No common development port was available for the preview scanner test"),
|
||||
);
|
||||
});
|
||||
|
||||
const commonDevServer = Effect.acquireRelease(
|
||||
openCommonDevServer(PortScanner.COMMON_DEV_PORTS),
|
||||
({ server }) => closeServer(server),
|
||||
);
|
||||
|
||||
/**
|
||||
* Integration tests against a real TCP listener. We provide the Windows host
|
||||
* platform so the tests exercise the TCP-probe fallback without depending on
|
||||
* `lsof` being installed.
|
||||
*/
|
||||
effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fallback)", (it) => {
|
||||
it.effect(
|
||||
"scan() returns a server we just opened on a curated dev port",
|
||||
Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
|
||||
const { port } = yield* commonDevServer;
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
const result = yield* scanner.scan();
|
||||
const found = result.find((server) => server.port === port);
|
||||
expect(found).toBeDefined();
|
||||
expect(found?.host).toBe("localhost");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"retain drives an immediate broadcast to subscribers",
|
||||
Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
|
||||
const { port } = yield* commonDevServer;
|
||||
const received: number[] = [];
|
||||
const scanner = yield* PortScanner.PortDiscovery;
|
||||
yield* scanner.subscribe((servers) =>
|
||||
Effect.sync(() => {
|
||||
for (const server of servers) received.push(server.port);
|
||||
}),
|
||||
);
|
||||
yield* scanner.retain;
|
||||
expect(received).toContain(port);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,363 @@
|
||||
/**
|
||||
* In-process PortScanner implementation.
|
||||
*
|
||||
* macOS/Linux: parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn` (-F output is a
|
||||
* stable line-prefixed field format; this is the only `lsof` flag set we rely
|
||||
* on).
|
||||
*
|
||||
* Windows / lsof missing: checks a curated list of common dev ports through
|
||||
* the shared Net service.
|
||||
*
|
||||
* Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
|
||||
* polls forever, but each tick is a no-op when the retain count is zero.
|
||||
*/
|
||||
import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Net from "@t3tools/shared/Net";
|
||||
import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
|
||||
import { Cause, Context, Duration, Effect, Layer, Ref, Schedule, Scope } from "effect";
|
||||
|
||||
import { ProcessRunner } from "../processRunner.ts";
|
||||
|
||||
export interface PortDiscoveryShape {
|
||||
readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
|
||||
readonly subscribe: (
|
||||
listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly retain: Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly registerTerminalProcesses: (input: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
readonly processIds: ReadonlyArray<number>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly unregisterTerminal: (input: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
}) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class PortDiscovery extends Context.Service<PortDiscovery, PortDiscoveryShape>()(
|
||||
"t3/preview/PortScanner/PortDiscovery",
|
||||
) {}
|
||||
|
||||
export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
|
||||
3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,
|
||||
]);
|
||||
|
||||
const POLL_INTERVAL = Duration.seconds(3);
|
||||
const LSOF_TIMEOUT_MS = 5_000;
|
||||
const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
|
||||
|
||||
type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
|
||||
|
||||
interface ScannerState {
|
||||
readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
|
||||
readonly listeners: ReadonlySet<Listener>;
|
||||
readonly terminalProcesses: ReadonlyMap<
|
||||
string,
|
||||
{
|
||||
readonly owner: TerminalProcessOwner;
|
||||
readonly processIds: ReadonlySet<number>;
|
||||
}
|
||||
>;
|
||||
readonly retainCount: number;
|
||||
}
|
||||
|
||||
interface TerminalProcessOwner {
|
||||
readonly threadId: ThreadId;
|
||||
readonly terminalId: string;
|
||||
}
|
||||
|
||||
const terminalOwnerKey = (owner: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
}): string => `${owner.threadId}\u0000${owner.terminalId}`;
|
||||
|
||||
const parseLsofOutput = (
|
||||
raw: string,
|
||||
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
|
||||
): ReadonlyArray<DiscoveredLocalServer> => {
|
||||
const seen = new Map<string, DiscoveredLocalServer>();
|
||||
let pid: number | null = null;
|
||||
let processName: string | null = null;
|
||||
|
||||
for (const line of raw.split("\n")) {
|
||||
if (line.length === 0) continue;
|
||||
const tag = line.charAt(0);
|
||||
const value = line.slice(1);
|
||||
if (tag === "p") {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
processName = null;
|
||||
continue;
|
||||
}
|
||||
if (tag === "c") {
|
||||
processName = value.trim() || null;
|
||||
continue;
|
||||
}
|
||||
if (tag === "n") {
|
||||
const portMatch = parsePortFromLsofName(value);
|
||||
if (portMatch == null) continue;
|
||||
const url = `http://localhost:${portMatch}`;
|
||||
const key = `localhost:${portMatch}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.set(key, {
|
||||
host: "localhost",
|
||||
port: portMatch,
|
||||
url,
|
||||
processName,
|
||||
pid,
|
||||
terminal: pid === null ? null : (terminalByProcessId.get(pid) ?? null),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
|
||||
};
|
||||
|
||||
const parsePortFromLsofName = (name: string): number | null => {
|
||||
// Examples: "*:5173", "127.0.0.1:5173", "[::1]:5173", "localhost:5173",
|
||||
// "192.168.1.10:5173 (LISTEN)" — we only care if the host part is local.
|
||||
const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
|
||||
if (trimmed.length === 0) return null;
|
||||
const lastColon = trimmed.lastIndexOf(":");
|
||||
if (lastColon < 0) return null;
|
||||
const hostPart = trimmed.slice(0, lastColon);
|
||||
const portPart = trimmed.slice(lastColon + 1);
|
||||
if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
|
||||
const port = Number.parseInt(portPart, 10);
|
||||
if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
|
||||
return port;
|
||||
};
|
||||
|
||||
const parseWindowsListenerOutput = (
|
||||
raw: string,
|
||||
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
|
||||
): ReadonlyArray<DiscoveredLocalServer> => {
|
||||
const seen = new Map<number, DiscoveredLocalServer>();
|
||||
for (const line of raw.split(/\r?\n/g)) {
|
||||
const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4);
|
||||
const host = hostRaw?.trim() ?? "";
|
||||
if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue;
|
||||
const port = Number(portRaw);
|
||||
const pid = Number(pidRaw);
|
||||
if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;
|
||||
const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;
|
||||
if (seen.has(port)) continue;
|
||||
seen.set(port, {
|
||||
host: "localhost",
|
||||
port,
|
||||
url: `http://localhost:${port}`,
|
||||
processName: processNameRaw?.trim() || null,
|
||||
pid: normalizedPid,
|
||||
terminal: normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null),
|
||||
});
|
||||
}
|
||||
return [...seen.values()].toSorted((left, right) => left.port - right.port);
|
||||
};
|
||||
|
||||
const serversEqual = (
|
||||
left: ReadonlyArray<DiscoveredLocalServer>,
|
||||
right: ReadonlyArray<DiscoveredLocalServer>,
|
||||
): boolean => {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
const a = left[i];
|
||||
const b = right[i];
|
||||
if (!a || !b) return false;
|
||||
if (
|
||||
a.host !== b.host ||
|
||||
a.port !== b.port ||
|
||||
a.url !== b.url ||
|
||||
a.processName !== b.processName ||
|
||||
a.pid !== b.pid ||
|
||||
a.terminal?.threadId !== b.terminal?.threadId ||
|
||||
a.terminal?.terminalId !== b.terminal?.terminalId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
const net = yield* Net.NetService;
|
||||
const processRunner = yield* ProcessRunner;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const stateRef = yield* Ref.make<ScannerState>({
|
||||
lastSnapshot: [],
|
||||
listeners: new Set(),
|
||||
terminalProcesses: new Map(),
|
||||
retainCount: 0,
|
||||
});
|
||||
|
||||
const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
|
||||
const results = yield* Effect.forEach(
|
||||
COMMON_DEV_PORTS,
|
||||
(port) =>
|
||||
net.isPortAvailableOnLoopback(port).pipe(
|
||||
Effect.map((available) => ({
|
||||
port,
|
||||
listening: !available,
|
||||
})),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return results
|
||||
.filter((result) => result.listening)
|
||||
.map<DiscoveredLocalServer>((result) => ({
|
||||
host: "localhost",
|
||||
port: result.port,
|
||||
url: `http://localhost:${result.port}`,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
}));
|
||||
});
|
||||
|
||||
const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
|
||||
const state = yield* Ref.get(stateRef);
|
||||
const terminalByProcessId = new Map<number, TerminalProcessOwner>();
|
||||
for (const registration of state.terminalProcesses.values()) {
|
||||
for (const processId of registration.processIds) {
|
||||
terminalByProcessId.set(processId, registration.owner);
|
||||
}
|
||||
}
|
||||
if (hostPlatform === "win32") {
|
||||
const command =
|
||||
'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
|
||||
const listeners = yield* processRunner
|
||||
.run({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
|
||||
maxOutputBytes: 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
|
||||
Effect.catchCause(() => Effect.succeed(null)),
|
||||
);
|
||||
if (listeners !== null) return listeners;
|
||||
return yield* probeCommonPorts();
|
||||
}
|
||||
const lsofResult = yield* processRunner
|
||||
.run({
|
||||
command: "lsof",
|
||||
args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
|
||||
timeout: Duration.millis(LSOF_TIMEOUT_MS),
|
||||
maxOutputBytes: 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
|
||||
Effect.catchCause(() => Effect.succeed(null)),
|
||||
);
|
||||
if (lsofResult !== null) return lsofResult;
|
||||
return yield* probeCommonPorts();
|
||||
});
|
||||
|
||||
const broadcast = Effect.fn("PortDiscovery.broadcast")(function* (
|
||||
servers: ReadonlyArray<DiscoveredLocalServer>,
|
||||
) {
|
||||
const listeners = (yield* Ref.get(stateRef)).listeners;
|
||||
yield* Effect.forEach(listeners, (listener) => listener(servers), { discard: true });
|
||||
});
|
||||
|
||||
const pollTick = Effect.fn("PortDiscovery.pollTick")(
|
||||
function* () {
|
||||
if ((yield* Ref.get(stateRef)).retainCount <= 0) return;
|
||||
const next = yield* scanOnce();
|
||||
const changed = yield* Ref.modify(stateRef, (state) =>
|
||||
serversEqual(state.lastSnapshot, next)
|
||||
? [false, state]
|
||||
: [true, { ...state, lastSnapshot: next }],
|
||||
);
|
||||
if (changed) yield* broadcast(next);
|
||||
},
|
||||
Effect.catchCause((cause: Cause.Cause<never>) =>
|
||||
Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
|
||||
),
|
||||
);
|
||||
|
||||
// Single layer-scoped polling fiber. Ticks are no-ops when no client is
|
||||
// currently retained, so the cost is one Ref.get every POLL_INTERVAL.
|
||||
yield* Effect.forkScoped(pollTick().pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
|
||||
|
||||
const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
|
||||
const wasIdle = yield* Ref.modify(stateRef, (state) => [
|
||||
state.retainCount === 0,
|
||||
{ ...state, retainCount: state.retainCount + 1 },
|
||||
]);
|
||||
if (wasIdle) {
|
||||
// Run an immediate scan + broadcast so the new retainer doesn't have
|
||||
// to wait up to POLL_INTERVAL for the first emission.
|
||||
yield* pollTick();
|
||||
}
|
||||
});
|
||||
|
||||
const retain: PortDiscoveryShape["retain"] = Effect.acquireRelease(acquireRetention(), () =>
|
||||
Ref.update(stateRef, (state) => ({
|
||||
...state,
|
||||
retainCount: Math.max(0, state.retainCount - 1),
|
||||
})),
|
||||
);
|
||||
|
||||
const subscribe: PortDiscoveryShape["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
|
||||
(listener) =>
|
||||
Effect.acquireRelease(
|
||||
Ref.update(stateRef, (state) => ({
|
||||
...state,
|
||||
listeners: new Set([...state.listeners, listener]),
|
||||
})),
|
||||
() =>
|
||||
Ref.update(stateRef, (state) => {
|
||||
const listeners = new Set(state.listeners);
|
||||
listeners.delete(listener);
|
||||
return { ...state, listeners };
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const registerTerminalProcesses: PortDiscoveryShape["registerTerminalProcesses"] = Effect.fn(
|
||||
"PortDiscovery.registerTerminalProcesses",
|
||||
)(function* (input) {
|
||||
const owner = {
|
||||
threadId: ThreadId.make(input.threadId),
|
||||
terminalId: input.terminalId,
|
||||
};
|
||||
const processIds = new Set(
|
||||
input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
|
||||
);
|
||||
yield* Ref.update(stateRef, (state) => {
|
||||
const terminalProcesses = new Map(state.terminalProcesses);
|
||||
const key = terminalOwnerKey(owner);
|
||||
if (processIds.size === 0) {
|
||||
terminalProcesses.delete(key);
|
||||
} else {
|
||||
terminalProcesses.set(key, { owner, processIds });
|
||||
}
|
||||
return { ...state, terminalProcesses };
|
||||
});
|
||||
});
|
||||
|
||||
const unregisterTerminal: PortDiscoveryShape["unregisterTerminal"] = Effect.fn(
|
||||
"PortDiscovery.unregisterTerminal",
|
||||
)(function* (input) {
|
||||
yield* Ref.update(stateRef, (state) => {
|
||||
const terminalProcesses = new Map(state.terminalProcesses);
|
||||
terminalProcesses.delete(terminalOwnerKey(input));
|
||||
return { ...state, terminalProcesses };
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
scan: scanOnce,
|
||||
subscribe,
|
||||
retain,
|
||||
registerTerminalProcesses,
|
||||
unregisterTerminal,
|
||||
} satisfies PortDiscoveryShape;
|
||||
}).pipe(Effect.withSpan("PortDiscovery.make"));
|
||||
|
||||
export const layer = Layer.effect(PortDiscovery, make);
|
||||
@@ -1,9 +1,7 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -11,24 +9,9 @@ import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchBrowser,
|
||||
launchEditorProcess,
|
||||
resolveAvailableEditors,
|
||||
resolveBrowserLaunch,
|
||||
resolveEditorLaunch,
|
||||
} from "./externalLauncher.ts";
|
||||
|
||||
function encodeUtf16LeBase64(input: string): string {
|
||||
const bytes = new Uint8Array(input.length * 2);
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
const code = input.charCodeAt(index);
|
||||
bytes[index * 2] = code & 0xff;
|
||||
bytes[index * 2 + 1] = code >>> 8;
|
||||
}
|
||||
return Encoding.encodeBase64(bytes);
|
||||
}
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
|
||||
import { ExternalLauncher, layer as ExternalLauncherLive } from "./externalLauncher.ts";
|
||||
|
||||
function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
@@ -49,756 +32,135 @@ function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
Effect.gen(function* () {
|
||||
const antigravityLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "antigravity" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(antigravityLaunch, {
|
||||
command: "agy",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const traeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "trae" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(traeLaunch, {
|
||||
command: "trae",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const kiroLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLaunch, {
|
||||
command: "kiro",
|
||||
args: ["ide", "/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLaunch, {
|
||||
command: "code-insiders",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLaunch, {
|
||||
command: "codium",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const ideaLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "idea" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(ideaLaunch, {
|
||||
command: "idea",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const aquaLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLaunch, {
|
||||
command: "aqua",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const clionLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLaunch, {
|
||||
command: "clion",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const datagripLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLaunch, {
|
||||
command: "datagrip",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const dataspellLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLaunch, {
|
||||
command: "dataspell",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const golandLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLaunch, {
|
||||
command: "goland",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const phpstormLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLaunch, {
|
||||
command: "phpstorm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const pycharmLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLaunch, {
|
||||
command: "pycharm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const riderLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLaunch, {
|
||||
command: "rider",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const rubymineLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLaunch, {
|
||||
command: "rubymine",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const rustroverLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLaunch, {
|
||||
command: "rustrover",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const webstormLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "webstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(webstormLaunch, {
|
||||
command: "webstorm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies launch-style-specific navigation arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
|
||||
});
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const traeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "trae" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(traeLineAndColumn, {
|
||||
command: "trae",
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(zedLineOnly, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/AGENTS.md:48"],
|
||||
});
|
||||
|
||||
const ideaLineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(ideaLineOnly, {
|
||||
command: "idea",
|
||||
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
|
||||
});
|
||||
|
||||
const ideaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "idea" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(ideaLineAndColumn, {
|
||||
command: "idea",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const aquaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLineAndColumn, {
|
||||
command: "aqua",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const clionLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLineAndColumn, {
|
||||
command: "clion",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const datagripLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLineAndColumn, {
|
||||
command: "datagrip",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const dataspellLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLineAndColumn, {
|
||||
command: "dataspell",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const golandLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLineAndColumn, {
|
||||
command: "goland",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const phpstormLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLineAndColumn, {
|
||||
command: "phpstorm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const pycharmLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLineAndColumn, {
|
||||
command: "pycharm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const riderLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLineAndColumn, {
|
||||
command: "rider",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const rubymineLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLineAndColumn, {
|
||||
command: "rubymine",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const rustroverLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLineAndColumn, {
|
||||
command: "rustrover",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const webstormLineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "webstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(webstormLineOnly, {
|
||||
command: "webstorm",
|
||||
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to zeditor when zed is not installed", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
|
||||
yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
|
||||
|
||||
const result = yield* resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "zed" }, "linux", {
|
||||
PATH: dir,
|
||||
});
|
||||
|
||||
assert.deepEqual(result, {
|
||||
command: "zeditor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the primary command when no alias is installed", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "zed" }, "linux", {
|
||||
PATH: "",
|
||||
});
|
||||
assert.deepEqual(result, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps file-manager editor to OS open commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
"win32",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
args: ["C:\\workspace"],
|
||||
});
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"linux",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolveBrowserLaunch maps default browser launchers by platform", () => {
|
||||
const target = "https://example.com/some path?name=o'hara";
|
||||
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").command, "open");
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").args, [target]);
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").options, {
|
||||
detached: true,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).command, "xdg-open");
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).args, [target]);
|
||||
|
||||
const windows = resolveBrowserLaunch(target, "win32", {
|
||||
SYSTEMROOT: "C:\\Windows",
|
||||
});
|
||||
assert.equal(windows.command, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
|
||||
assert.deepEqual(windows.args, [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
encodeUtf16LeBase64(
|
||||
"$ProgressPreference = 'SilentlyContinue'; Start 'https://example.com/some path?name=o''hara'",
|
||||
const testLayer = (input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env?: Record<string, string>;
|
||||
readonly resolveExecutable?: (command: string) => string | undefined;
|
||||
readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
|
||||
readonly onUnref?: () => void;
|
||||
}) => {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(ChildProcess.isStandardCommand(command), true);
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
throw new Error("Expected a standard command");
|
||||
}
|
||||
input.onSpawn?.(command);
|
||||
return makeMockDetachedHandle(input.onUnref);
|
||||
}),
|
||||
),
|
||||
]);
|
||||
assert.deepEqual(windows.options, {
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
);
|
||||
|
||||
return Layer.mergeAll(
|
||||
ExternalLauncherLive.pipe(Layer.provide(Layer.merge(NodeServices.layer, spawnerLayer))),
|
||||
Layer.succeed(HostProcessPlatform, input.platform),
|
||||
Layer.succeed(
|
||||
SpawnExecutableResolution,
|
||||
(command) => input.resolveExecutable?.(command) ?? command,
|
||||
),
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
|
||||
);
|
||||
};
|
||||
|
||||
it.effect("launches the default browser through the platform command", () => {
|
||||
let spawned: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
return Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
|
||||
yield* launcher.launchBrowser("https://example.com/some path");
|
||||
|
||||
assert.ok(spawned);
|
||||
assert.equal(spawned.command, "xdg-open");
|
||||
assert.deepEqual(spawned.args, ["https://example.com/some path"]);
|
||||
assert.equal(spawned.options.detached, true);
|
||||
assert.equal(didUnref, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
platform: "linux",
|
||||
onSpawn: (command) => {
|
||||
spawned = command;
|
||||
},
|
||||
onUnref: () => {
|
||||
didUnref = true;
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolveBrowserLaunch opens through Windows from WSL when not remote", () => {
|
||||
const launch = resolveBrowserLaunch("https://example.com", "linux", {
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
});
|
||||
assert.equal(launch.command, "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
assert.equal(launch.options.detached, true);
|
||||
});
|
||||
it.effect("launches an installed editor with platform-safe arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
|
||||
|
||||
it("resolveBrowserLaunch keeps xdg-open for WSL over SSH", () => {
|
||||
const launch = resolveBrowserLaunch("https://example.com", "linux", {
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
SSH_CONNECTION: "client server",
|
||||
});
|
||||
assert.equal(launch.command, "xdg-open");
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchBrowser", (it) => {
|
||||
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(ChildProcess.isStandardCommand(command), true);
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
throw new Error("Expected a standard command");
|
||||
}
|
||||
spawnedCommand = command;
|
||||
return makeMockDetachedHandle(() => {
|
||||
didUnref = true;
|
||||
});
|
||||
}),
|
||||
let spawned: ChildProcess.StandardCommand | undefined;
|
||||
yield* Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
yield* launcher.launchEditor({
|
||||
editor: "vscode",
|
||||
cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
platform: "win32",
|
||||
env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
|
||||
resolveExecutable: (command) =>
|
||||
command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
|
||||
onSpawn: (command) => {
|
||||
spawned = command;
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* launchBrowser("https://example.com").pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
Effect.result,
|
||||
);
|
||||
assert.ok(spawned);
|
||||
assert.equal(spawned.command, '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"');
|
||||
assert.deepEqual(spawned.args, [
|
||||
'^"--goto^"',
|
||||
'^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
|
||||
]);
|
||||
assert.equal(spawned.options.shell, true);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
assertSuccess(result, undefined);
|
||||
assert.ok(spawnedCommand);
|
||||
const expectedLaunch = resolveBrowserLaunch("https://example.com");
|
||||
assert.equal(spawnedCommand.command, expectedLaunch.command);
|
||||
assert.deepEqual(spawnedCommand.args, expectedLaunch.args);
|
||||
assert.deepEqual(spawnedCommand.options, expectedLaunch.options);
|
||||
assert.equal(didUnref, true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
it.effect("discovers editors through the service API", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
|
||||
yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
|
||||
|
||||
it.layer(NodeServices.layer)("launchEditorProcess", (it) => {
|
||||
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
const expectedArgs = ["-e", "process.exit(0)"];
|
||||
const editors = yield* Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
return yield* launcher.resolveAvailableEditors();
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
platform: "win32",
|
||||
env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(ChildProcess.isStandardCommand(command), true);
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
throw new Error("Expected a standard command");
|
||||
}
|
||||
spawnedCommand = command;
|
||||
return makeMockDetachedHandle(() => {
|
||||
didUnref = true;
|
||||
});
|
||||
}),
|
||||
});
|
||||
assert.equal(editors.includes("vscode"), true);
|
||||
assert.equal(editors.includes("file-manager"), true);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const result = yield* launchEditorProcess({
|
||||
command: process.execPath,
|
||||
args: expectedArgs,
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
|
||||
assertSuccess(result, undefined);
|
||||
assert.ok(spawnedCommand);
|
||||
assert.equal(spawnedCommand.command, process.execPath);
|
||||
assert.deepEqual(
|
||||
spawnedCommand.args,
|
||||
process.platform === "win32" ? expectedArgs.map((arg) => `"${arg}"`) : expectedArgs,
|
||||
);
|
||||
assert.deepEqual(spawnedCommand.options, {
|
||||
detached: true,
|
||||
shell: process.platform === "win32",
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
assert.equal(didUnref, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects when command does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {});
|
||||
const result = yield* launchEditorProcess({
|
||||
command: `t3code-no-such-command-${yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
)}`,
|
||||
args: [],
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
it.effect("resolves win32 commands with PATHEXT", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it("returns false when a command is not on PATH", () => {
|
||||
const env = {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
});
|
||||
|
||||
it.effect("does not treat bare files without executable extension as available on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
|
||||
const env = {
|
||||
PATH: `${firstDir};${secondDir}`,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
it.effect("returns installed editors for command launches", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "aqua.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "clion.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "datagrip.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "dataspell.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "goland.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "phpstorm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "pycharm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rider.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rubymine.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rustrover.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "webstorm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, [
|
||||
"trae",
|
||||
"kiro",
|
||||
"vscode-insiders",
|
||||
"vscodium",
|
||||
"aqua",
|
||||
"clion",
|
||||
"datagrip",
|
||||
"dataspell",
|
||||
"goland",
|
||||
"phpstorm",
|
||||
"pycharm",
|
||||
"rider",
|
||||
"rubymine",
|
||||
"rustrover",
|
||||
"webstorm",
|
||||
"file-manager",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes zed when only the zeditor command is installed", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
|
||||
yield* fs.writeFileString(path.join(dir, "xdg-open"), "#!/bin/sh\nexit 0\n");
|
||||
yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
|
||||
yield* fs.chmod(path.join(dir, "xdg-open"), 0o755);
|
||||
|
||||
const editors = resolveAvailableEditors("linux", {
|
||||
PATH: dir,
|
||||
});
|
||||
assert.deepEqual(editors, ["zed", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it("omits file-manager when the platform opener is unavailable", () => {
|
||||
const editors = resolveAvailableEditors("linux", {
|
||||
PATH: "",
|
||||
});
|
||||
assert.deepEqual(editors, []);
|
||||
});
|
||||
});
|
||||
it.effect("rejects unknown editors through the service API", () =>
|
||||
Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
const result = yield* launcher
|
||||
.launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" })
|
||||
.pipe(Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}).pipe(Effect.provide(testLayer({ platform: "linux", env: { PATH: "" } }))),
|
||||
);
|
||||
@@ -12,12 +12,16 @@ import {
|
||||
type EditorId,
|
||||
type LaunchEditorInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
// ==============================
|
||||
@@ -26,8 +30,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
export { ExternalLauncherError };
|
||||
export type { LaunchEditorInput };
|
||||
export { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -61,6 +63,36 @@ const DETACHED_IGNORE_STDIO_OPTIONS = {
|
||||
stderr: "ignore",
|
||||
} as const satisfies ChildProcess.CommandOptions;
|
||||
|
||||
const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
|
||||
Object.fromEntries(
|
||||
Object.entries(input).flatMap(([key, value]) =>
|
||||
Option.match(value, {
|
||||
onNone: () => [],
|
||||
onSome: (resolved) => [[key, resolved]],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const BrowserLaunchEnvConfig = Config.all({
|
||||
SYSTEMROOT: Config.string("SYSTEMROOT").pipe(Config.option),
|
||||
windir: Config.string("windir").pipe(Config.option),
|
||||
WSL_DISTRO_NAME: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
|
||||
WSL_INTEROP: Config.string("WSL_INTEROP").pipe(Config.option),
|
||||
SSH_CONNECTION: Config.string("SSH_CONNECTION").pipe(Config.option),
|
||||
SSH_TTY: Config.string("SSH_TTY").pipe(Config.option),
|
||||
container: Config.string("container").pipe(Config.option),
|
||||
}).pipe(Config.map(compactEnv));
|
||||
|
||||
const CommandLookupEnvConfig = Config.all({
|
||||
PATH: Config.string("PATH").pipe(Config.option),
|
||||
Path: Config.string("Path").pipe(Config.option),
|
||||
path: Config.string("path").pipe(Config.option),
|
||||
PATHEXT: Config.string("PATHEXT").pipe(Config.option),
|
||||
}).pipe(Config.map(compactEnv));
|
||||
|
||||
const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
|
||||
const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
|
||||
|
||||
function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
|
||||
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
|
||||
if (!match?.[1] || !match[2]) {
|
||||
@@ -109,17 +141,17 @@ function resolveEditorArgs(
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
const resolveAvailableCommand = Effect.fn("externalLauncher.resolveAvailableCommand")(function* (
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): Option.Option<string> {
|
||||
env: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<Option.Option<string>, never, FileSystem.FileSystem | Path.Path> {
|
||||
for (const command of commands) {
|
||||
if (isCommandAvailable(command, options)) {
|
||||
if (yield* isCommandAvailable(command, { env })) {
|
||||
return Option.some(command);
|
||||
}
|
||||
}
|
||||
return Option.none();
|
||||
}
|
||||
});
|
||||
|
||||
function encodeUtf16LeBase64(input: string): string {
|
||||
const bytes = new Uint8Array(input.length * 2);
|
||||
@@ -135,7 +167,7 @@ function escapePowerShellStringLiteral(input: string): string {
|
||||
return `'${input.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
function resolvePowerShellPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
|
||||
return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
|
||||
}
|
||||
|
||||
@@ -145,7 +177,7 @@ function resolveWslPowerShellPath(): string {
|
||||
|
||||
function shouldUseWindowsBrowserFromWsl(
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
env: NodeJS.ProcessEnv = {},
|
||||
): boolean {
|
||||
return (
|
||||
platform === "linux" &&
|
||||
@@ -184,10 +216,10 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveBrowserLaunch(
|
||||
function buildBrowserLaunch(
|
||||
target: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv = {},
|
||||
): ProcessLaunch {
|
||||
if (platform === "darwin") {
|
||||
return {
|
||||
@@ -212,34 +244,49 @@ export function resolveBrowserLaunch(
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ReadonlyArray<EditorId>, never, FileSystem.FileSystem | Path.Path> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
if (editor.commands === null) {
|
||||
const command = fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
if (yield* isCommandAvailable(command, { env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const command = resolveAvailableCommand(editor.commands, { platform, env });
|
||||
const command = yield* resolveAvailableCommand(editor.commands, env);
|
||||
if (Option.isSome(command)) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
});
|
||||
|
||||
const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
|
||||
target: string,
|
||||
) {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const env = yield* readBrowserLaunchEnv;
|
||||
return buildBrowserLaunch(target, platform, env);
|
||||
});
|
||||
|
||||
const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const env = yield* readCommandLookupEnv;
|
||||
return yield* buildAvailableEditors(platform, env);
|
||||
});
|
||||
|
||||
/**
|
||||
* ExternalLauncherShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface ExternalLauncherShape {
|
||||
readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
|
||||
/**
|
||||
* Launch a URL target in the default browser.
|
||||
*/
|
||||
@@ -264,11 +311,11 @@ export class ExternalLauncher extends Context.Service<ExternalLauncher, External
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
input: LaunchEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<EditorLaunch, ExternalLauncherError> {
|
||||
): Effect.fn.Return<EditorLaunch, ExternalLauncherError, FileSystem.FileSystem | Path.Path> {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const env = yield* readCommandLookupEnv;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"externalLauncher.editor": input.editor,
|
||||
"externalLauncher.cwd": input.cwd,
|
||||
@@ -281,7 +328,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
|
||||
if (editorDef.commands) {
|
||||
const command = Option.getOrElse(
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }),
|
||||
yield* resolveAvailableCommand(editorDef.commands, env),
|
||||
() => editorDef.commands[0],
|
||||
);
|
||||
return {
|
||||
@@ -312,29 +359,35 @@ const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
export const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
|
||||
const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
|
||||
target: string,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
return yield* launchAndUnref(resolveBrowserLaunch(target), "Browser auto-open failed");
|
||||
const launch = yield* resolveBrowserLaunch(target);
|
||||
return yield* launchAndUnref(launch, "Browser auto-open failed");
|
||||
});
|
||||
|
||||
export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
|
||||
const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
|
||||
launch: EditorLaunch,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
ExternalLauncherError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const env = yield* readCommandLookupEnv;
|
||||
if (!(yield* isCommandAvailable(launch.command, { env }))) {
|
||||
return yield* new ExternalLauncherError({
|
||||
message: `Editor command not found: ${launch.command}`,
|
||||
});
|
||||
}
|
||||
|
||||
const isWin32 = process.platform === "win32";
|
||||
const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
|
||||
yield* launchAndUnref(
|
||||
{
|
||||
command: launch.command,
|
||||
args: isWin32 ? launch.args.map((arg) => `"${arg}"`) : [...launch.args],
|
||||
command: spawnCommand.command,
|
||||
args: spawnCommand.args,
|
||||
options: {
|
||||
detached: true,
|
||||
shell: isWin32,
|
||||
shell: spawnCommand.shell,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
@@ -346,16 +399,29 @@ export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProce
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const provideCommandResolutionServices = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
|
||||
) =>
|
||||
effect.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
return {
|
||||
resolveAvailableEditors: () => provideCommandResolutionServices(resolveAvailableEditors()),
|
||||
launchBrowser: (target) =>
|
||||
launchBrowser(target).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
launchEditor: (input) =>
|
||||
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
|
||||
launchEditorProcess(launch).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
provideCommandResolutionServices(
|
||||
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
|
||||
launchEditorProcess(launch).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
),
|
||||
),
|
||||
} satisfies ExternalLauncherShape;
|
||||
|
||||
@@ -8,6 +8,8 @@ import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
|
||||
|
||||
import {
|
||||
isWindowsCommandNotFound,
|
||||
@@ -21,6 +23,9 @@ import {
|
||||
type ChildProcessCommand = {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: {
|
||||
readonly shell?: boolean | string;
|
||||
};
|
||||
};
|
||||
|
||||
// Accesses private properties of ChildProcessCommand for testing purposes
|
||||
@@ -68,7 +73,6 @@ const runWith =
|
||||
Effect.flatMap((runner) =>
|
||||
runner.run({
|
||||
...input,
|
||||
shell: input.shell ?? false,
|
||||
}),
|
||||
),
|
||||
Effect.provide(
|
||||
@@ -123,6 +127,44 @@ describe("runProcess", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("resolves and escapes Windows command shims before spawning", () => {
|
||||
const spawner = makeSpawner((command) =>
|
||||
Effect.sync(() => {
|
||||
expect(command.command).toBe('^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"');
|
||||
expect(command.args).toEqual([
|
||||
'^"repos^"',
|
||||
'^"pr^"',
|
||||
'^"list^"',
|
||||
'^"--source-branch^"',
|
||||
'^"feature^ ^&^ release^"',
|
||||
]);
|
||||
expect(command.options.shell).toBe(true);
|
||||
return makeHandle({ stdout: "[]" });
|
||||
}),
|
||||
);
|
||||
|
||||
return runWith(spawner)({
|
||||
command: "az",
|
||||
args: ["repos", "pr", "list", "--source-branch", "feature & release"],
|
||||
env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
|
||||
}).pipe(
|
||||
Effect.provideService(HostProcessPlatform, "win32"),
|
||||
Effect.provideService(HostProcessEnvironment, {
|
||||
PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
}),
|
||||
Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
|
||||
env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
|
||||
env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
|
||||
? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
|
||||
: undefined,
|
||||
),
|
||||
Effect.map((result) => {
|
||||
expect(result.stdout).toBe("[]");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails when output exceeds max buffer in default mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
|
||||
@@ -280,19 +322,13 @@ describe("runProcess", () => {
|
||||
});
|
||||
|
||||
describe("isWindowsCommandNotFound", () => {
|
||||
it("matches the localized German cmd.exe error text", () => {
|
||||
const originalPlatform = process.platform;
|
||||
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
|
||||
|
||||
try {
|
||||
expect(
|
||||
isWindowsCommandNotFound(
|
||||
1,
|
||||
"wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", { value: originalPlatform, configurable: true });
|
||||
}
|
||||
});
|
||||
it.effect("matches the localized German cmd.exe error text", () =>
|
||||
Effect.gen(function* () {
|
||||
const isCommandNotFound = yield* isWindowsCommandNotFound(
|
||||
1,
|
||||
"wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
|
||||
).pipe(Effect.provideService(HostProcessPlatform, "win32"));
|
||||
expect(isCommandNotFound).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import {
|
||||
collectUint8StreamText,
|
||||
type CollectedUint8StreamText,
|
||||
@@ -24,7 +26,6 @@ export interface ProcessRunInput {
|
||||
readonly maxOutputBytes?: number | undefined;
|
||||
readonly outputMode?: "error" | "truncate" | undefined;
|
||||
readonly truncatedMarker?: string | undefined;
|
||||
readonly shell?: boolean | string | undefined;
|
||||
/**
|
||||
* On timeout, return a synthetic timedOut result.
|
||||
* Partial stdout/stderr are not preserved.
|
||||
@@ -109,11 +110,14 @@ function hasWindowsCommandNotFoundMessage(output: string): boolean {
|
||||
return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
|
||||
}
|
||||
|
||||
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return hasWindowsCommandNotFoundMessage(stderr);
|
||||
}
|
||||
export const isWindowsCommandNotFound = Effect.fn("processRunner.isWindowsCommandNotFound")(
|
||||
function* (code: number | null, stderr: string) {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
if (platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return hasWindowsCommandNotFoundMessage(stderr);
|
||||
},
|
||||
);
|
||||
|
||||
const collectText = Effect.fn("processRunner.collectText")(function* (input: {
|
||||
readonly command: string;
|
||||
@@ -231,18 +235,24 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const outputMode = input.outputMode ?? "error";
|
||||
const truncatedMarker = input.truncatedMarker ?? "";
|
||||
const extendEnv = input.env !== undefined;
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
input.command,
|
||||
input.args,
|
||||
input.env === undefined ? {} : { env: input.env, extendEnv },
|
||||
);
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.command, [...input.args], {
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
|
||||
...(input.env !== undefined
|
||||
? {
|
||||
env: input.env,
|
||||
extendEnv: true,
|
||||
extendEnv,
|
||||
}
|
||||
: {}),
|
||||
...(input.shell !== undefined ? { shell: input.shell } : {}),
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
|
||||
@@ -7,9 +7,10 @@ import * as Path from "effect/Path";
|
||||
|
||||
import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts";
|
||||
import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts";
|
||||
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ProjectFaviconResolver,
|
||||
type ProjectFaviconResolverShape,
|
||||
} from "../Services/ProjectFaviconResolver.ts";
|
||||
import { WorkspacePaths } from "../../workspace/Services/WorkspacePaths.ts";
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
@@ -61,28 +62,32 @@ function extractIconHref(source: string): string | null {
|
||||
export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
|
||||
const resolveIconHref = (projectCwd: string, href: string): string[] => {
|
||||
const resolveIconHref = (href: string): string[] => {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
};
|
||||
|
||||
const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
return [path.join("public", clean), clean];
|
||||
};
|
||||
|
||||
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
|
||||
projectCwd: string,
|
||||
candidates: ReadonlyArray<string>,
|
||||
relativeCandidates: ReadonlyArray<string>,
|
||||
): Effect.fn.Return<string | null> {
|
||||
for (const candidate of candidates) {
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
for (const relativePath of relativeCandidates) {
|
||||
const candidate = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: projectCwd,
|
||||
relativePath,
|
||||
})
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!candidate) {
|
||||
continue;
|
||||
}
|
||||
const stats = yield* fileSystem.stat(candidate).pipe(Effect.orElseSucceed(() => null));
|
||||
const stats = yield* fileSystem
|
||||
.stat(candidate.absolutePath)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (stats?.type === "File") {
|
||||
return candidate;
|
||||
return candidate.absolutePath;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -91,18 +96,31 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn(
|
||||
"ProjectFaviconResolver.resolvePath",
|
||||
)(function* (cwd: string): Effect.fn.Return<string | null> {
|
||||
const projectCwd = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(cwd)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!projectCwd) {
|
||||
return null;
|
||||
}
|
||||
for (const candidate of FAVICON_CANDIDATES) {
|
||||
const resolved = path.join(cwd, candidate);
|
||||
const existing = yield* findExistingFile(cwd, [resolved]);
|
||||
const existing = yield* findExistingFile(projectCwd, [candidate]);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sourceFile of ICON_SOURCE_FILES) {
|
||||
const sourcePath = path.join(cwd, sourceFile);
|
||||
const sourcePath = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: projectCwd,
|
||||
relativePath: sourceFile,
|
||||
})
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!sourcePath) {
|
||||
continue;
|
||||
}
|
||||
const source = yield* fileSystem
|
||||
.readFileString(sourcePath)
|
||||
.readFileString(sourcePath.absolutePath)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!source) {
|
||||
continue;
|
||||
@@ -111,7 +129,7 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
if (!href) {
|
||||
continue;
|
||||
}
|
||||
const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href));
|
||||
const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
@@ -89,6 +89,8 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("resolveRepositoryIdentityCa
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
let cacheKey = cwd;
|
||||
|
||||
// git is a real executable on every platform — no cmd.exe shell mode, which
|
||||
// would split paths containing spaces during cmd's re-tokenization.
|
||||
const topLevelResult = yield* processRunner
|
||||
.run({
|
||||
command: "git",
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
const T3_CODE_BROWSER_TOOL_INSTRUCTIONS = `
|
||||
|
||||
## T3 Code collaborative browser
|
||||
|
||||
You are running inside T3 Code. The \`t3-code\` MCP server is the product-native collaborative browser shared with the user. When it exposes \`preview_*\` tools, prefer those tools for browser navigation, inspection, interaction, screenshots, and recordings.
|
||||
|
||||
For browser work, first call \`preview_status\`. If no automation-capable preview is attached, call \`preview_open\` before concluding that the browser is unavailable. Then use \`preview_navigate\`, \`preview_snapshot\`, and the focused interaction tools. Prefer snapshot-provided locators over coordinates.
|
||||
|
||||
Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable.
|
||||
`;
|
||||
|
||||
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
||||
|
||||
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
||||
@@ -118,6 +129,7 @@ plan content should be human and agent digestible. The final plan must be plan-o
|
||||
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
|
||||
|
||||
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
|
||||
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
|
||||
</collaboration_mode>`;
|
||||
|
||||
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
|
||||
@@ -131,4 +143,5 @@ Your active mode changes only when new developer instructions with a different \
|
||||
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
|
||||
|
||||
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
|
||||
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
|
||||
</collaboration_mode>`;
|
||||
@@ -16,13 +16,14 @@ export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function
|
||||
|
||||
export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function* (
|
||||
config: Pick<ClaudeSettings, "homePath">,
|
||||
baseEnv: NodeJS.ProcessEnv = process.env,
|
||||
baseEnv?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
|
||||
const resolvedBaseEnv = baseEnv ?? process.env;
|
||||
const homePath = config.homePath.trim();
|
||||
if (homePath.length === 0) return baseEnv;
|
||||
if (homePath.length === 0) return resolvedBaseEnv;
|
||||
const resolvedHomePath = yield* resolveClaudeHomePath(config);
|
||||
return {
|
||||
...baseEnv,
|
||||
...resolvedBaseEnv,
|
||||
HOME: resolvedHomePath,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -69,6 +69,7 @@ import * as Stream from "effect/Stream";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
|
||||
import {
|
||||
getClaudeModelCapabilities,
|
||||
@@ -3445,6 +3446,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(ultracode ? { ultracode: true } : {}),
|
||||
};
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(apiModelId ? { model: apiModelId } : {}),
|
||||
@@ -3470,6 +3472,19 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
env: claudeEnvironment,
|
||||
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
|
||||
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
|
||||
...(mcpSession
|
||||
? {
|
||||
mcpServers: {
|
||||
"t3-code": {
|
||||
type: "http",
|
||||
url: mcpSession.endpoint,
|
||||
headers: {
|
||||
Authorization: mcpSession.authorizationHeader,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
getProviderOptionCurrentValue,
|
||||
getProviderOptionDescriptors,
|
||||
} from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import { compareSemverVersions } from "@t3tools/shared/semver";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
@@ -547,7 +548,7 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
|
||||
*/
|
||||
const probeClaudeCapabilities = (
|
||||
claudeSettings: ClaudeSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) => {
|
||||
const abort = new AbortController();
|
||||
return Effect.gen(function* () {
|
||||
@@ -603,12 +604,15 @@ const probeClaudeCapabilities = (
|
||||
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
|
||||
claudeSettings: ClaudeSettings,
|
||||
args: ReadonlyArray<string>,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
|
||||
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
|
||||
const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
|
||||
env: claudeEnvironment,
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
env: claudeEnvironment,
|
||||
shell: spawnCommand.shell,
|
||||
});
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
});
|
||||
@@ -618,12 +622,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
resolveCapabilities?: (
|
||||
claudeSettings: ClaudeSettings,
|
||||
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Path.Path
|
||||
> {
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const allModels = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
@@ -648,10 +653,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runClaudeCommand(claudeSettings, ["--version"], environment).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
const versionProbe = yield* runClaudeCommand(
|
||||
claudeSettings,
|
||||
["--version"],
|
||||
resolvedEnvironment,
|
||||
).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
|
||||
@@ -491,6 +491,64 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("labels MCP lifecycle entries with server and tool names", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
yield* runtime.emit({
|
||||
id: asEventId("evt-mcp-complete"),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "item/completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("mcp_1"),
|
||||
payload: {
|
||||
completedAtMs: 1_778_000_000_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: "mcp_1",
|
||||
server: "t3-code",
|
||||
tool: "preview_status",
|
||||
arguments: {},
|
||||
durationMs: 12,
|
||||
error: null,
|
||||
result: { content: [{ type: "text", text: "attached" }] },
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
});
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some" || firstEvent.value.type !== "item.completed") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.payload.itemType, "mcp_tool_call");
|
||||
assert.equal(firstEvent.value.payload.title, "t3-code · preview_status");
|
||||
assert.deepStrictEqual(firstEvent.value.payload.data, {
|
||||
completedAtMs: 1_778_000_000_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: "mcp_1",
|
||||
server: "t3-code",
|
||||
tool: "preview_status",
|
||||
arguments: {},
|
||||
durationMs: 12,
|
||||
error: null,
|
||||
result: { content: [{ type: "text", text: "attached" }] },
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
|
||||
@@ -39,6 +39,7 @@ import * as EffectCodexSchema from "effect-codex-app-server/schema";
|
||||
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
|
||||
import {
|
||||
ProviderAdapterRequestError,
|
||||
@@ -234,7 +235,10 @@ function toCanonicalItemType(raw: string | undefined | null): CanonicalItemType
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function itemTitle(itemType: CanonicalItemType): string | undefined {
|
||||
function itemTitle(itemType: CanonicalItemType, item?: CodexLifecycleItem): string | undefined {
|
||||
if (itemType === "mcp_tool_call" && item?.type === "mcpToolCall") {
|
||||
return `${item.server} · ${item.tool}`;
|
||||
}
|
||||
switch (itemType) {
|
||||
case "assistant_message":
|
||||
return "Assistant message";
|
||||
@@ -475,7 +479,7 @@ function mapItemLifecycle(
|
||||
payload: {
|
||||
itemType,
|
||||
...(status ? { status } : {}),
|
||||
...(itemTitle(itemType) ? { title: itemTitle(itemType) } : {}),
|
||||
...(itemTitle(itemType, item) ? { title: itemTitle(itemType, item) } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
...(event.payload !== undefined ? { data: event.payload } : {}),
|
||||
},
|
||||
@@ -1382,6 +1386,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? getCodexServiceTierOptionValue(input.modelSelection)
|
||||
: undefined;
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
const runtimeInput: CodexSessionRuntimeOptions = {
|
||||
threadId: input.threadId,
|
||||
providerInstanceId: boundInstanceId,
|
||||
@@ -1397,6 +1402,20 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(serviceTier ? { serviceTier } : {}),
|
||||
...(mcpSession
|
||||
? {
|
||||
environment: {
|
||||
...(options?.environment ?? process.env),
|
||||
T3_MCP_BEARER_TOKEN: mcpSession.authorizationHeader.replace(/^Bearer\s+/, ""),
|
||||
},
|
||||
appServerArgs: [
|
||||
"-c",
|
||||
`mcp_servers.t3-code.url=${mcpSession.endpoint}`,
|
||||
"-c",
|
||||
'mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"',
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
|
||||
@@ -7,7 +7,7 @@ import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Types from "effect/Types";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as CodexClient from "effect-codex-app-server/client";
|
||||
import * as CodexSchema from "effect-codex-app-server/schema";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import {
|
||||
AUTH_PROBE_TIMEOUT_MS,
|
||||
buildServerProvider,
|
||||
@@ -33,6 +34,8 @@ import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
|
||||
|
||||
const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
|
||||
|
||||
const CODEX_PRESENTATION = {
|
||||
displayName: "Codex",
|
||||
showInteractionModeToggle: true,
|
||||
@@ -292,17 +295,35 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
|
||||
// "CODEX_HOME points to '~/.codex_work', but that path does not exist".
|
||||
// Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.
|
||||
const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
|
||||
const clientContext = yield* Layer.build(
|
||||
CodexClient.layerCommand({
|
||||
command: input.binaryPath,
|
||||
args: ["app-server"],
|
||||
cwd: input.cwd,
|
||||
env: {
|
||||
...(input.environment ?? process.env),
|
||||
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const environment = {
|
||||
...input.environment,
|
||||
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
|
||||
};
|
||||
const spawnCommand = yield* resolveSpawnCommand(input.binaryPath, ["app-server"], {
|
||||
env: environment,
|
||||
extendEnv: true,
|
||||
});
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
cwd: input.cwd,
|
||||
env: environment,
|
||||
extendEnv: true,
|
||||
forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CodexErrors.CodexAppServerSpawnError({
|
||||
command: `${input.binaryPath} app-server`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
|
||||
const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
|
||||
Effect.provide(clientContext),
|
||||
);
|
||||
@@ -449,12 +470,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
CodexErrors.CodexAppServerError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
> = probeCodexAppServerProvider,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
ServerSettingsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const emptyModels = emptyCodexModelsFromSettings(codexSettings);
|
||||
|
||||
@@ -480,7 +502,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
homePath: codexSettings.homePath,
|
||||
cwd: process.cwd(),
|
||||
customModels: codexSettings.customModels,
|
||||
environment,
|
||||
environment: resolvedEnvironment,
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "../CodexDeveloperInstructions.ts";
|
||||
import {
|
||||
buildTurnStartParams,
|
||||
hasConfiguredMcpServer,
|
||||
isRecoverableThreadResumeError,
|
||||
openCodexThread,
|
||||
} from "./CodexSessionRuntime.ts";
|
||||
@@ -149,6 +150,31 @@ describe("buildTurnStartParams", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("T3 browser developer instructions", () => {
|
||||
it("prefers the product-native preview tools in both collaboration modes", () => {
|
||||
for (const instructions of [
|
||||
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
]) {
|
||||
assert.match(instructions, /t3-code/);
|
||||
assert.match(instructions, /preview_status/);
|
||||
assert.match(instructions, /preview_open/);
|
||||
assert.match(instructions, /Do not switch to global browser skills/);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasConfiguredMcpServer", () => {
|
||||
it("detects inline Codex MCP configuration arguments", () => {
|
||||
assert.equal(hasConfiguredMcpServer(undefined), false);
|
||||
assert.equal(hasConfiguredMcpServer(["--model", "gpt-5.4"]), false);
|
||||
assert.equal(
|
||||
hasConfiguredMcpServer(["-c", 'mcp_servers.t3-code.url="http://127.0.0.1/mcp"']),
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRecoverableThreadResumeError", () => {
|
||||
it("matches missing thread errors", () => {
|
||||
assert.equal(
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -62,6 +63,10 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"does not exist",
|
||||
];
|
||||
|
||||
export function hasConfiguredMcpServer(appServerArgs: ReadonlyArray<string> | undefined): boolean {
|
||||
return appServerArgs?.some((argument) => argument.includes("mcp_servers.")) === true;
|
||||
}
|
||||
|
||||
export const CodexResumeCursorSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
});
|
||||
@@ -103,6 +108,7 @@ export interface CodexSessionRuntimeOptions {
|
||||
readonly model?: string;
|
||||
readonly serviceTier?: CodexServiceTier | undefined;
|
||||
readonly resumeCursor?: CodexResumeCursor;
|
||||
readonly appServerArgs?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface CodexSessionRuntimeSendTurnInput {
|
||||
@@ -715,16 +721,23 @@ export const makeCodexSessionRuntime = (
|
||||
// `CODEX_HOME=~/.codex_work` reach codex as an absolute path.
|
||||
const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined;
|
||||
const env = {
|
||||
...(options.environment ?? process.env),
|
||||
...options.environment,
|
||||
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
|
||||
};
|
||||
const extendEnv = options.environment === undefined;
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
options.binaryPath,
|
||||
["app-server", ...(options.appServerArgs ?? [])],
|
||||
{ env, extendEnv },
|
||||
);
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(options.binaryPath, ["app-server"], {
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
cwd: options.cwd,
|
||||
env,
|
||||
extendEnv,
|
||||
forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,
|
||||
shell: process.platform === "win32",
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -1255,6 +1268,15 @@ export const makeCodexSessionRuntime = (
|
||||
sendTurn: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const providerThreadId = yield* readProviderThreadId;
|
||||
if (hasConfiguredMcpServer(options.appServerArgs)) {
|
||||
yield* client.request("config/mcpServer/reload", undefined).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to refresh Codex MCP tool catalog before turn.", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
const normalizedModel = normalizeCodexModelSlug(
|
||||
input.model ?? (yield* Ref.get(sessionRef)).model,
|
||||
);
|
||||
|
||||
@@ -42,6 +42,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
@@ -530,6 +531,7 @@ export function makeCursorAdapter(
|
||||
? yield* options.resolveSettings
|
||||
: cursorSettings;
|
||||
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
const acp = yield* makeCursorAcpRuntime({
|
||||
cursorSettings: effectiveCursorSettings,
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
@@ -537,6 +539,23 @@ export function makeCursorAdapter(
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...(mcpSession
|
||||
? {
|
||||
mcpServers: [
|
||||
{
|
||||
type: "http" as const,
|
||||
name: "t3-code",
|
||||
url: mcpSession.endpoint,
|
||||
headers: [
|
||||
{
|
||||
name: "Authorization",
|
||||
value: mcpSession.authorizationHeader,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
getProviderOptionBooleanSelectionValue,
|
||||
getProviderOptionStringSelectionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
|
||||
import {
|
||||
buildBooleanOptionDescriptor,
|
||||
@@ -394,7 +395,7 @@ function buildCursorDiscoveredModelsFromAvailableModelsResponse(
|
||||
|
||||
const makeCursorAcpProbeRuntime = (
|
||||
cursorSettings: CursorSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
@@ -407,7 +408,7 @@ const makeCursorAcpProbeRuntime = (
|
||||
"acp",
|
||||
],
|
||||
cwd: process.cwd(),
|
||||
env: environment,
|
||||
...(environment ? { env: environment } : {}),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
|
||||
@@ -421,7 +422,7 @@ const makeCursorAcpProbeRuntime = (
|
||||
const withCursorAcpProbeRuntime = <A, E, R>(
|
||||
cursorSettings: CursorSettings,
|
||||
useRuntime: (acp: AcpSessionRuntime["Service"]) => Effect.Effect<A, E, R>,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) =>
|
||||
makeCursorAcpProbeRuntime(cursorSettings, environment).pipe(
|
||||
Effect.flatMap(useRuntime),
|
||||
@@ -542,7 +543,7 @@ export function resolveCursorAcpConfigUpdates(
|
||||
|
||||
const discoverCursorModelsViaListAvailableModels = (
|
||||
cursorSettings: CursorSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) =>
|
||||
withCursorAcpProbeRuntime(
|
||||
cursorSettings,
|
||||
@@ -558,7 +559,7 @@ const discoverCursorModelsViaListAvailableModels = (
|
||||
|
||||
export const discoverCursorModelsViaAcp = (
|
||||
cursorSettings: CursorSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) => discoverCursorModelsViaListAvailableModels(cursorSettings, environment);
|
||||
|
||||
export function getCursorFallbackModels(
|
||||
@@ -927,13 +928,18 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult
|
||||
const runCursorCommand = (
|
||||
cursorSettings: CursorSettings,
|
||||
args: ReadonlyArray<string>,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(cursorSettings.binaryPath, [...args], {
|
||||
env: environment,
|
||||
shell: process.platform === "win32",
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
cursorSettings.binaryPath,
|
||||
args,
|
||||
environment ? { env: environment } : {},
|
||||
);
|
||||
const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
...(environment ? { env: environment } : { extendEnv: true }),
|
||||
shell: spawnCommand.shell,
|
||||
});
|
||||
|
||||
const child = yield* spawner.spawn(command);
|
||||
@@ -949,10 +955,7 @@ const runCursorCommand = (
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const runCursorAboutCommand = (
|
||||
cursorSettings: CursorSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) =>
|
||||
const runCursorAboutCommand = (cursorSettings: CursorSettings, environment?: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const jsonResult = yield* runCursorCommand(
|
||||
cursorSettings,
|
||||
@@ -967,7 +970,7 @@ const runCursorAboutCommand = (
|
||||
|
||||
export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* (
|
||||
cursorSettings: CursorSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
|
||||
@@ -33,6 +33,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
@@ -374,6 +375,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
threadId: input.threadId,
|
||||
});
|
||||
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
const acp = yield* makeGrokAcpRuntime({
|
||||
grokSettings,
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
@@ -381,6 +383,23 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...(mcpSession
|
||||
? {
|
||||
mcpServers: [
|
||||
{
|
||||
type: "http" as const,
|
||||
name: "t3-code",
|
||||
url: mcpSession.endpoint,
|
||||
headers: [
|
||||
{
|
||||
name: "Authorization",
|
||||
value: mcpSession.authorizationHeader,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
|
||||
@@ -15,6 +15,7 @@ import * as Result from "effect/Result";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -149,16 +150,20 @@ const discoverGrokModelsViaAcp = (
|
||||
const runGrokVersionCommand = (
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) => {
|
||||
const command = grokSettings.binaryPath || "grok";
|
||||
return spawnAndCollect(
|
||||
command,
|
||||
ChildProcess.make(command, ["--version"], {
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const command = grokSettings.binaryPath || "grok";
|
||||
const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
|
||||
env: environment,
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
};
|
||||
});
|
||||
return yield* spawnAndCollect(
|
||||
command,
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
env: environment,
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
|
||||
grokSettings: GrokSettings,
|
||||
|
||||
@@ -26,6 +26,7 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -1053,6 +1054,22 @@ export function makeOpenCodeAdapter(
|
||||
directory,
|
||||
...(server.external && serverPassword ? { serverPassword } : {}),
|
||||
});
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
if (mcpSession && !server.external) {
|
||||
yield* runOpenCodeSdk("mcp.add", () =>
|
||||
client.mcp.add({
|
||||
name: "t3-code",
|
||||
config: {
|
||||
type: "remote",
|
||||
url: mcpSession.endpoint,
|
||||
headers: {
|
||||
Authorization: mcpSession.authorizationHeader,
|
||||
},
|
||||
oauth: false,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
|
||||
client.session.create({
|
||||
title: `T3 Code ${input.threadId}`,
|
||||
|
||||
@@ -301,9 +301,10 @@ export const makePendingOpenCodeProvider = (
|
||||
export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
|
||||
openCodeSettings: OpenCodeSettings,
|
||||
cwd: string,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const customModels = openCodeSettings.customModels;
|
||||
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
|
||||
@@ -364,7 +365,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
.runOpenCodeCommand({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
args: ["--version"],
|
||||
environment,
|
||||
environment: resolvedEnvironment,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
@@ -413,7 +414,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
const server = yield* openCodeRuntime.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
environment,
|
||||
environment: resolvedEnvironment,
|
||||
});
|
||||
return yield* openCodeRuntime.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
|
||||
@@ -1039,7 +1039,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
|
||||
// This test intentionally avoids `mockCommandSpawnerLayer` so the real
|
||||
// `probeCodexAppServerProvider` path runs — including the full
|
||||
// `codex app-server` RPC handshake via `CodexClient.layerCommand`.
|
||||
// `codex app-server` RPC handshake via `CodexClient.layerChildProcess`.
|
||||
// We point `binaryPath` at a name that cannot exist on any machine so
|
||||
// the real `ChildProcessSpawner` deterministically returns ENOENT; the
|
||||
// probe wraps that as `CodexAppServerSpawnError` and
|
||||
@@ -1159,6 +1159,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
Effect.gen(function* () {
|
||||
const firstMissing = `t3code_codex_first_`;
|
||||
const secondMissing = `t3code_codex_second_`;
|
||||
const spawnedCommands: Array<string> = [];
|
||||
const serverSettings = yield* makeMutableServerSettingsService(
|
||||
decodeServerSettings(
|
||||
deepMerge(encodedDefaultServerSettings, {
|
||||
@@ -1185,10 +1186,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// `it.live` does not inherit layers from the outer `it.layer`
|
||||
// wrapper, so provide `NodeServices.layer` inline. This is the
|
||||
// same real `ChildProcessSpawner` + `FileSystem` + `Path`
|
||||
// services that production uses.
|
||||
Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
|
||||
ChildProcessSpawner.make((command) => {
|
||||
spawnedCommands.push((command as { readonly command: string }).command);
|
||||
return spawner.spawn(command);
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
@@ -1199,10 +1202,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
const registry = yield* ProviderRegistry;
|
||||
// Boot-time probe: the default codex instance is enabled with
|
||||
// `firstMissing`, so the real spawner yields ENOENT and the
|
||||
// snapshot should be `status: "error"`. What *distinguishes*
|
||||
// the two probe runs is `checkedAt` — each probe stamps a
|
||||
// fresh DateTime, so we capture it and assert it advances
|
||||
// after the settings mutation.
|
||||
// snapshot should be `status: "error"`.
|
||||
let initialProviders = yield* registry.getProviders;
|
||||
for (
|
||||
let attempts = 0;
|
||||
@@ -1220,13 +1220,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
);
|
||||
assert.strictEqual(initialCodex?.status, "error");
|
||||
assert.strictEqual(initialCodex?.installed, false);
|
||||
const initialCheckedAt = initialCodex?.checkedAt;
|
||||
assert.notStrictEqual(initialCheckedAt, undefined);
|
||||
|
||||
// The rebuilt instance may re-probe synchronously during the
|
||||
// settings update. Advance the TestClock first so `checkedAt`
|
||||
// can safely act as the fresh-probe marker this assertion uses.
|
||||
yield* TestClock.adjust("1 second");
|
||||
assert.deepStrictEqual(spawnedCommands, [firstMissing]);
|
||||
|
||||
// Drive a settings change. The Hydration layer's
|
||||
// `SettingsWatcherLive` consumes this via `streamChanges`,
|
||||
@@ -1242,8 +1236,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
},
|
||||
});
|
||||
|
||||
// Poll with TestClock until `checkedAt` advances or we hit a
|
||||
// generous virtual 3-second ceiling.
|
||||
// Poll until the injected process boundary observes the new
|
||||
// executable. This verifies the public settings-to-probe behavior
|
||||
// without depending on timestamps assigned by TestClock.
|
||||
const refreshed = yield* Effect.gen(function* () {
|
||||
for (let attempts = 0; attempts < 60; attempts += 1) {
|
||||
const providers = yield* registry.getProviders;
|
||||
@@ -1251,7 +1246,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
if (
|
||||
codex !== undefined &&
|
||||
codex.status === "error" &&
|
||||
codex.checkedAt !== initialCheckedAt
|
||||
spawnedCommands.includes(secondMissing)
|
||||
) {
|
||||
return providers;
|
||||
}
|
||||
@@ -1262,11 +1257,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
});
|
||||
|
||||
const reprobedCodex = refreshed.find((provider) => provider.instanceId === "codex");
|
||||
assert.notStrictEqual(
|
||||
reprobedCodex?.checkedAt,
|
||||
initialCheckedAt,
|
||||
"Expected a fresh probe after settings change, got the stale snapshot",
|
||||
);
|
||||
assert.deepStrictEqual(spawnedCommands, [firstMissing, secondMissing]);
|
||||
assert.strictEqual(reprobedCodex?.status, "error");
|
||||
assert.strictEqual(reprobedCodex?.installed, false);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
|
||||
@@ -56,6 +56,8 @@ import {
|
||||
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
|
||||
/**
|
||||
@@ -212,6 +214,18 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
|
||||
McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
|
||||
Effect.tap((credential) =>
|
||||
credential
|
||||
? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
const clearMcpSession = (threadId: ThreadId) =>
|
||||
McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
|
||||
Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
|
||||
);
|
||||
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Effect.succeed(event).pipe(
|
||||
@@ -383,16 +397,20 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
providerInstanceId: bindingInstanceId,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
});
|
||||
yield* prepareMcpSession(input.binding.threadId, bindingInstanceId);
|
||||
const resumed = yield* adapter
|
||||
.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
providerInstanceId: bindingInstanceId,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
})
|
||||
.pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
|
||||
if (resumed.provider !== adapter.provider) {
|
||||
yield* clearMcpSession(input.binding.threadId);
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
@@ -572,14 +590,18 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
"provider.cwd.effective": effectiveCwd ?? "",
|
||||
});
|
||||
const adapter = yield* registry.getByInstance(resolvedInstanceId);
|
||||
const session = yield* adapter.startSession({
|
||||
...input,
|
||||
providerInstanceId: resolvedInstanceId,
|
||||
...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
|
||||
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
|
||||
});
|
||||
yield* prepareMcpSession(threadId, resolvedInstanceId);
|
||||
const session = yield* adapter
|
||||
.startSession({
|
||||
...input,
|
||||
providerInstanceId: resolvedInstanceId,
|
||||
...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
|
||||
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
|
||||
})
|
||||
.pipe(Effect.onError(() => clearMcpSession(threadId)));
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
yield* clearMcpSession(threadId);
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
@@ -827,6 +849,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
if (routed.isActive) {
|
||||
yield* routed.adapter.stopSession(routed.threadId);
|
||||
}
|
||||
yield* clearMcpSession(input.threadId);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
@@ -998,6 +1021,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
|
||||
McpProviderSession.clearAllMcpProviderSessions();
|
||||
const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
|
||||
yield* Effect.forEach(bindings, (binding) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as EffectAcpClient from "effect-acp/client";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
|
||||
import {
|
||||
collectSessionConfigOptionValues,
|
||||
@@ -47,6 +48,7 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly version: string;
|
||||
};
|
||||
readonly authMethodId: string;
|
||||
readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
|
||||
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
|
||||
readonly protocolLogging?: {
|
||||
readonly logIncoming?: boolean;
|
||||
@@ -200,12 +202,17 @@ const makeAcpSessionRuntime = (
|
||||
),
|
||||
);
|
||||
|
||||
const spawnCommand = yield* resolveSpawnCommand(
|
||||
options.spawn.command,
|
||||
options.spawn.args,
|
||||
options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {},
|
||||
);
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(options.spawn.command, [...options.spawn.args], {
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
|
||||
...(options.spawn.env ? { env: { ...process.env, ...options.spawn.env } } : {}),
|
||||
shell: process.platform === "win32",
|
||||
...(options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {}),
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -400,7 +407,7 @@ const makeAcpSessionRuntime = (
|
||||
const loadPayload = {
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
@@ -413,7 +420,7 @@ const makeAcpSessionRuntime = (
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
@@ -426,7 +433,7 @@ const makeAcpSessionRuntime = (
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
|
||||
@@ -31,6 +31,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { collectStreamAsString } from "./providerSnapshot.ts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
|
||||
const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
|
||||
|
||||
@@ -276,13 +278,17 @@ function ensureRuntimeError(
|
||||
const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const netService = yield* NetService.NetService;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
|
||||
resolveSpawnCommand(command, args, env ? { env } : {});
|
||||
|
||||
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.binaryPath, [...input.args], {
|
||||
shell: process.platform === "win32",
|
||||
env: input.environment ?? process.env,
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
shell: spawnCommand.shell,
|
||||
...(input.environment ? { env: input.environment } : { extendEnv: true }),
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, code] = yield* Effect.all(
|
||||
@@ -290,7 +296,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const exitCode = Number(code);
|
||||
if (isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: `spawn ${input.binaryPath} ENOENT`,
|
||||
@@ -334,16 +340,18 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
));
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
|
||||
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
|
||||
const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.binaryPath, args, {
|
||||
detached: process.platform !== "win32",
|
||||
shell: process.platform === "win32",
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
detached: hostPlatform !== "win32",
|
||||
shell: spawnCommand.shell,
|
||||
env: {
|
||||
...(input.environment ?? process.env),
|
||||
...input.environment,
|
||||
OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
|
||||
},
|
||||
extendEnv: input.environment === undefined,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -359,7 +367,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
|
||||
process.platform === "win32"
|
||||
hostPlatform === "win32"
|
||||
? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
|
||||
: Effect.sync(() => {
|
||||
try {
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import { afterEach, expect, it } from "@effect/vitest";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import os from "node:os";
|
||||
import * as NodeOS from "node:os";
|
||||
import path from "node:path";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
createProviderVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
ProviderVersionCache,
|
||||
resolveLatestProviderVersion,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
@@ -21,7 +24,7 @@ const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const makeTempDir = (name: string) =>
|
||||
Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.map((id) => path.join(os.tmpdir(), `${name}-${id}`)),
|
||||
Effect.map((id) => path.join(NodeOS.tmpdir(), `${name}-${id}`)),
|
||||
);
|
||||
const isNativeTestCommandPath =
|
||||
(expectedPathSegment: string) =>
|
||||
@@ -65,11 +68,33 @@ const staticToolUpdate = makeStaticProviderMaintenanceResolver(
|
||||
}),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
it.effect("reads cached versions through the injectable cache reference", () =>
|
||||
resolveLatestProviderVersion(packageToolUpdate.resolve()).pipe(
|
||||
Effect.provideService(
|
||||
ProviderVersionCache,
|
||||
new Map([
|
||||
[
|
||||
"@example/package-tool",
|
||||
{
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
version: "9.9.9",
|
||||
},
|
||||
],
|
||||
]),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() =>
|
||||
Effect.die("cached provider version should not make an HTTP request"),
|
||||
),
|
||||
),
|
||||
Effect.map((version) => {
|
||||
expect(version).toBe("9.9.9");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it("marks providers with unknown current versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
@@ -144,15 +169,17 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
writeFileSync(packageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(packageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
|
||||
packageToolUpdate,
|
||||
{
|
||||
binaryPath: "package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: vitePlusBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
},
|
||||
).pipe(Effect.provideService(HostProcessPlatform, "darwin"));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
@@ -177,16 +204,18 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
mkdirSync(bunBinDir, { recursive: true });
|
||||
writeFileSync(path.join(bunBinDir, "native-package-tool.exe"), "MZ");
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
|
||||
nativePackageToolUpdate,
|
||||
{
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: bunBinDir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
},
|
||||
).pipe(Effect.provideService(HostProcessPlatform, "win32"));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
@@ -213,15 +242,17 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
|
||||
scopedPackageToolUpdate,
|
||||
{
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: pnpmHomeDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
},
|
||||
).pipe(Effect.provideService(HostProcessPlatform, "darwin"));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
@@ -241,7 +272,6 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
@@ -272,15 +302,17 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
writeFileSync(nativePackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(nativePackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
|
||||
nativePackageToolUpdate,
|
||||
{
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
},
|
||||
).pipe(Effect.provideService(HostProcessPlatform, "darwin"));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
@@ -307,15 +339,17 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
|
||||
scopedPackageToolUpdate,
|
||||
{
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
},
|
||||
).pipe(Effect.provideService(HostProcessPlatform, "darwin"));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
@@ -335,7 +369,6 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
@@ -359,7 +392,6 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
@@ -401,7 +433,6 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
@@ -449,7 +480,6 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
@@ -475,7 +505,6 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "C:\\Tools\\package-tool\\package-tool.exe",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { compareSemverVersions } from "@t3tools/shared/semver";
|
||||
import { resolveCommandPath } from "@t3tools/shared/shell";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -16,6 +18,25 @@ const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
|
||||
const LATEST_VERSION_TIMEOUT_MS = 4_000;
|
||||
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
|
||||
|
||||
const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
|
||||
Object.fromEntries(
|
||||
Object.entries(input).flatMap(([key, value]) =>
|
||||
Option.match(value, {
|
||||
onNone: () => [],
|
||||
onSome: (resolved) => [[key, resolved]],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const CommandLookupEnvConfig = Config.all({
|
||||
PATH: Config.string("PATH").pipe(Config.option),
|
||||
Path: Config.string("Path").pipe(Config.option),
|
||||
path: Config.string("path").pipe(Config.option),
|
||||
PATHEXT: Config.string("PATHEXT").pipe(Config.option),
|
||||
}).pipe(Config.map(compactEnv));
|
||||
|
||||
const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
|
||||
|
||||
export interface ProviderMaintenanceCapabilities {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
@@ -32,7 +53,7 @@ export interface ProviderMaintenanceCommandAction {
|
||||
export interface ProviderMaintenanceCapabilityResolutionOptions {
|
||||
readonly binaryPath?: string | null;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly resolvedCommandPath?: string | null;
|
||||
readonly realCommandPath?: string | null;
|
||||
}
|
||||
|
||||
@@ -54,20 +75,21 @@ export interface PackageManagedProviderMaintenanceDefinition {
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface LatestVersionCacheEntry {
|
||||
export interface ProviderVersionCacheEntry {
|
||||
readonly expiresAt: number;
|
||||
readonly version: string | null;
|
||||
}
|
||||
|
||||
const latestVersionCache = new Map<string, LatestVersionCacheEntry>();
|
||||
export const ProviderVersionCache = Context.Reference<Map<string, ProviderVersionCacheEntry>>(
|
||||
"@t3tools/server/providerMaintenance/ProviderVersionCache",
|
||||
{
|
||||
defaultValue: () => new Map(),
|
||||
},
|
||||
);
|
||||
const NpmLatestVersionResponse = Schema.Struct({
|
||||
version: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export function clearLatestProviderVersionCacheForTests(): void {
|
||||
latestVersionCache.clear();
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
@@ -251,10 +273,7 @@ export function resolvePackageManagedProviderMaintenance(
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
options?.resolvedCommandPath ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
|
||||
if (resolvedCommandPath) {
|
||||
const commandPaths = [
|
||||
@@ -335,11 +354,11 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const env = options?.env ?? (yield* readCommandLookupEnv);
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
(yield* resolveCommandPath(binaryPath, { env }).pipe(
|
||||
Effect.catchTag("CommandResolutionError", () => Effect.succeed(null)),
|
||||
)) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
if (!resolvedCommandPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
@@ -350,6 +369,8 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
.pipe(Effect.orElseSucceed(() => resolvedCommandPath));
|
||||
return resolver.resolve({
|
||||
...options,
|
||||
env,
|
||||
resolvedCommandPath,
|
||||
realCommandPath,
|
||||
});
|
||||
});
|
||||
@@ -430,6 +451,7 @@ export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVers
|
||||
return null;
|
||||
}
|
||||
|
||||
const latestVersionCache = yield* ProviderVersionCache;
|
||||
const cached = latestVersionCache.get(packageName);
|
||||
const now = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
if (cached && cached.expiresAt > now) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, it, assert } from "@effect/vitest";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
@@ -21,8 +21,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
ProviderVersionCache,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
|
||||
@@ -35,10 +35,6 @@ const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor");
|
||||
const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities {
|
||||
if (provider === CURSOR_DRIVER) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
@@ -202,7 +198,12 @@ const makeTestRunner = (registry: ProviderRegistryShape) =>
|
||||
Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe(
|
||||
Effect.provide(
|
||||
ProviderMaintenanceRunner.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ProviderRegistry, registry)),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ProviderRegistry, registry),
|
||||
Layer.succeed(ProviderVersionCache, new Map()),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -75,7 +75,7 @@ export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Comman
|
||||
);
|
||||
|
||||
const result: CommandResult = { stdout, stderr, code: exitCode };
|
||||
if (isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
return yield* new ProviderCommandExecutionError({ message: `spawn ${binaryPath} ENOENT` });
|
||||
}
|
||||
return result;
|
||||
|
||||
Loaded 100 of 287 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user