Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge b948600014 Fix DPoP JWK type re-export
Co-authored-by: Julius Marminge <[email protected]>
2026-06-10 16:14:46 +00:00
Cursor AgentandJulius Marminge 23175df03a Preserve DPoP header private key rejection
Co-authored-by: Julius Marminge <[email protected]>
2026-06-10 16:13:23 +00:00
Cursor AgentandJulius Marminge 5b24144370 Refine DPoP verification Effect patterns
Co-authored-by: Julius Marminge <[email protected]>
2026-06-10 16:11:19 +00:00
335 changed files with 6573 additions and 32202 deletions

No files matched your search

+1 -4
View File
@@ -20,16 +20,13 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
"electron-updater": "^6.6.2"
},
"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)"
@@ -1,40 +0,0 @@
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);
+5 -13
View File
@@ -1,13 +1,8 @@
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,
resolveElectronLaunchCommand,
} from "./electron-launcher.mjs";
import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
@@ -34,8 +29,6 @@ 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,
@@ -60,7 +53,7 @@ const expectedExits = new WeakSet();
const watchers = [];
function killChildTreeByPid(pid, signal) {
if (hostPlatform === "win32" || typeof pid !== "number") {
if (process.platform === "win32" || typeof pid !== "number") {
return;
}
@@ -68,7 +61,7 @@ function killChildTreeByPid(pid, signal) {
}
function cleanupStaleDevApps() {
if (hostPlatform === "win32") {
if (process.platform === "win32") {
return;
}
@@ -86,8 +79,7 @@ function startApp() {
const launchArgs = devProtocolClient
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = spawn(electronCommand.electronPath, electronCommand.args, {
const app = spawn(resolveElectronPath(), launchArgs, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
@@ -197,7 +189,7 @@ function startWatchers() {
}
function killChildTree(signal) {
if (hostPlatform === "win32") {
if (process.platform === "win32") {
return;
}
+4 -44
View File
@@ -14,7 +14,6 @@ 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";
@@ -31,11 +30,9 @@ 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 = 11;
const LAUNCHER_VERSION = 10;
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);
@@ -298,11 +295,7 @@ function buildMacLauncher(electronBinaryPath) {
}
rmSync(targetAppBundlePath, { recursive: true, force: 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 });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
@@ -314,54 +307,21 @@ 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 (hostPlatform !== "darwin") {
if (process.platform !== "darwin") {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
export function resolveElectronLaunchCommand(args = []) {
const electronPath = resolveElectronPath();
return {
electronPath,
args: [...resolveLinuxSandboxArgs(electronPath), ...args],
};
}
export function resolveDevProtocolClient() {
if (hostPlatform !== "darwin" || !isDevelopment) {
if (process.platform !== "darwin" || !isDevelopment) {
return null;
}
@@ -1,17 +1,13 @@
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { arch, platform, tmpdir } from "node:os";
import { 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 (hostPlatform) {
switch (process.platform) {
case "darwin":
return "Electron.app/Contents/MacOS/Electron";
case "freebsd":
@@ -21,12 +17,12 @@ function getPlatformPath() {
case "win32":
return "electron.exe";
default:
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
}
}
function ensureExecutable(filePath) {
if (hostPlatform !== "win32") {
if (process.platform !== "win32") {
chmodSync(filePath, 0o755);
}
}
@@ -43,7 +39,7 @@ function repairPathFile(electronDir, platformPath) {
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [join(electronDir, "dist", platformPath)];
if (hostPlatform === "darwin") {
if (process.platform === "darwin") {
paths.push(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
@@ -62,7 +58,7 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
}
function isMachO(filePath) {
if (hostPlatform !== "darwin") {
if (process.platform !== "darwin") {
return true;
}
@@ -80,7 +76,7 @@ function missingRuntimePaths(electronDir, platformPath) {
}
function invalidRuntimePaths(electronDir, platformPath) {
if (hostPlatform !== "darwin") {
if (process.platform !== "darwin") {
return [];
}
@@ -115,16 +111,16 @@ function runChecked(command, args) {
function installElectronRuntime(electronDir, version) {
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
try {
runChecked("curl", [
"-fsSL",
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
"-o",
zipPath,
]);
if (hostPlatform === "darwin") {
if (process.platform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
} else {
runChecked("python3", [
+2 -3
View File
@@ -1,16 +1,15 @@
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 electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(electronBin, [mainJs], {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
+2 -3
View File
@@ -1,12 +1,11 @@
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+1 -1
View File
@@ -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))) {
+1 -1
View File
@@ -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 && environment.platform === "darwin" && ext === "png") {
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem
.exists(developmentDockIconPath)
@@ -59,7 +59,6 @@ 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");
@@ -90,7 +89,6 @@ 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,7 +49,6 @@ export interface DesktopEnvironmentShape {
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
@@ -184,7 +183,6 @@ 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"),
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.catch(() => Effect.succeed<string | null>(null)),
);
const dnsName =
input.statusJson === undefined
+94 -99
View File
@@ -5,7 +5,6 @@ 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;
@@ -80,113 +79,109 @@ 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.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();
}
export const layer = Layer.sync(ElectronMenu, () => {
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (process.platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
};
}
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return destructiveMenuIconCache;
};
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;
}
}
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
template.push(itemOption);
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
return template;
};
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;
}
}
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()));
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;
}
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
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);
}),
});
}),
);
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);
}),
});
});
+1 -3
View File
@@ -6,7 +6,6 @@ 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;
@@ -38,7 +37,6 @@ 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(
@@ -100,7 +98,7 @@ const make = Effect.gen(function* () {
window.show();
}
if (platform === "darwin") {
if (process.platform === "darwin") {
Electron.app.focus({ steal: true });
}
+2 -7
View File
@@ -48,11 +48,9 @@ import {
setTheme,
showContextMenu,
} from "./methods/window.ts";
import * as PreviewIpc from "./methods/preview.ts";
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
export const installDesktopIpcHandlers = Effect.gen(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
@@ -94,7 +92,4 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(downloadUpdate);
yield* ipc.handle(installUpdate);
yield* ipc.handle(checkForUpdate);
for (const previewMethod of PreviewIpc.methods) {
yield* ipc.handle(previewMethod);
}
});
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
-35
View File
@@ -39,38 +39,3 @@ 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";
@@ -1,54 +0,0 @@
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();
},
),
);
});
-377
View File
@@ -1,377 +0,0 @@
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;
+3 -16
View File
@@ -9,7 +9,6 @@ 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" };
@@ -45,8 +44,6 @@ 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(
@@ -54,13 +51,11 @@ 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,
processArch,
platform: process.platform,
processArch: process.arch,
...metadata,
});
}),
@@ -132,15 +127,7 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
Layer.provideMerge(desktopFoundationLayer),
);
const desktopPreviewLayer = PreviewManager.layer.pipe(
Layer.provideMerge(PreviewBrowserSession.layer),
Layer.provideMerge(desktopFoundationLayer),
);
const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopServerExposureLayer),
Layer.provideMerge(desktopPreviewLayer),
);
const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
+1 -99
View File
@@ -1,9 +1,4 @@
import type {
DesktopBridge,
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import type { DesktopBridge } from "@t3tools/contracts";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
@@ -146,97 +141,4 @@ 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);
-1
View File
@@ -1 +0,0 @@
import "./preview/PickPreload.ts";
-68
View File
@@ -1,68 +0,0 @@
@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;
}
@@ -1,3 +0,0 @@
// 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
@@ -1,83 +0,0 @@
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)),
);
});
-107
View File
@@ -1,107 +0,0 @@
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);
@@ -1,6 +0,0 @@
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";
-374
View File
@@ -1,374 +0,0 @@
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
@@ -1,46 +0,0 @@
/**
* 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 };
}
@@ -1,86 +0,0 @@
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
@@ -1,201 +0,0 @@
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);
});
});
@@ -1,146 +0,0 @@
/**
* 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;
}
@@ -1,26 +0,0 @@
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');
}),
);
});
@@ -1,90 +0,0 @@
// @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;
})()`;
});
@@ -1,78 +0,0 @@
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/);
});
});
@@ -1,42 +0,0 @@
/**
* 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,17 +8,6 @@ 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";
@@ -29,7 +18,6 @@ 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",
@@ -167,12 +155,6 @@ 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 -37
View File
@@ -11,7 +11,6 @@ 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";
@@ -37,8 +36,7 @@ type DesktopWindowRuntimeServices =
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
| ElectronWindow.ElectronWindow
| PreviewManager.PreviewManager;
| ElectronWindow.ElectronWindow;
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
"DesktopWindowDevServerUrlMissingError",
@@ -50,8 +48,7 @@ export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
export type DesktopWindowError =
| DesktopWindowDevServerUrlMissingError
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
| ElectronWindow.ElectronWindowCreateError;
export interface DesktopWindowShape {
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
@@ -82,10 +79,9 @@ function resolveDesktopDevServerUrl(
function getIconOption(
iconPaths: DesktopAssets.DesktopIconPaths,
platform: NodeJS.Platform,
): { icon: string } | Record<string, never> {
if (platform === "darwin") return {}; // macOS uses .icns from app bundle
const ext = platform === "win32" ? "ico" : "png";
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
const ext = process.platform === "win32" ? "ico" : "png";
return Option.match(iconPaths[ext], {
onNone: () => ({}),
onSome: (icon) => ({ icon }),
@@ -107,11 +103,8 @@ export function isSameOriginRendererNavigation(input: {
}
}
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
): WindowTitleBarOptions {
if (platform === "darwin") {
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
if (process.platform === "darwin") {
return {
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
@@ -131,7 +124,6 @@ function getWindowTitleBarOptions(
function syncWindowAppearance(
window: Electron.BrowserWindow,
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
): Effect.Effect<void> {
return Effect.sync(() => {
if (window.isDestroyed()) {
@@ -139,7 +131,7 @@ function syncWindowAppearance(
}
window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors));
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform);
const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors);
if (typeof titleBarOverlay === "object") {
window.setTitleBarOverlay(titleBarOverlay);
}
@@ -170,7 +162,6 @@ 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>();
@@ -179,12 +170,11 @@ 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, environment.platform);
const iconOption = getIconOption(iconPaths);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
const window = yield* electronWindow.create({
width: 1100,
@@ -196,31 +186,15 @@ const make = Effect.gen(function* () {
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
...iconOption,
title: environment.displayName,
...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform),
...getWindowTitleBarOptions(shouldUseDarkColors),
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();
@@ -323,7 +297,7 @@ const make = Effect.gen(function* () {
});
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
if (environment.platform === "linux") {
if (process.platform === "linux") {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => {
@@ -413,7 +387,7 @@ const make = Effect.gen(function* () {
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
syncWindowAppearance(window, shouldUseDarkColors, environment.platform),
syncWindowAppearance(window, shouldUseDarkColors),
);
}).pipe(Effect.withSpan("desktop.window.syncAppearance")),
});
+3 -14
View File
@@ -14,18 +14,17 @@ export default defineConfig({
run: {
tasks: {
build: {
command: "node scripts/build-preview-annotation-css.mjs && vp pack",
command: "vp pack",
dependsOn: ["t3#build"],
cache: false,
},
dev: {
command:
"node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
command: "cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
dependsOn: ["t3#build"],
cache: false,
},
"dev:bundle": {
command: "node scripts/build-preview-annotation-css.mjs && vp pack --watch",
command: "vp pack --watch",
cache: false,
},
"dev:electron": {
@@ -57,15 +56,5 @@ 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/"),
},
},
],
});
+7 -2
View File
@@ -1,4 +1,4 @@
import { useAuth, useUser } from "@clerk/expo";
import { useAuth, useUser, useUserProfileModal } from "@clerk/expo";
import * as Notifications from "expo-notifications";
import { Link, Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
@@ -68,6 +68,7 @@ function ConfiguredSettingsRouteScreen() {
const { push } = useRouter();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal();
const { savedConnectionsById } = useRemoteEnvironmentState();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
@@ -265,11 +266,15 @@ function ConfiguredSettingsRouteScreen() {
push("/settings/waitlist");
return;
}
if (isUserProfileModalAvailable) {
void presentUserProfile();
return;
}
Alert.alert(
"T3 Cloud unavailable",
"Native T3 Cloud account management is not available in this build.",
);
}, [isLoaded, isSignedIn, push]);
}, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, push]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
+1 -1
View File
@@ -22,7 +22,7 @@
"test": "vp test run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
-5
View File
@@ -22,7 +22,6 @@ const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION ===
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
const permissionOptionIds = {
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
@@ -365,10 +364,6 @@ const program = Effect.gen(function* () {
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
+3 -5
View File
@@ -18,7 +18,6 @@ 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 {
@@ -176,7 +175,6 @@ const buildCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
shell: false,
}),
);
@@ -292,15 +290,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(spawnCommand.command, spawnCommand.args, {
ChildProcess.make("vp", ["pm", ...args], {
cwd: repoRoot,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
shell: spawnCommand.shell,
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
);
}),
@@ -3,8 +3,6 @@ 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 };
@@ -130,10 +128,9 @@ class JsonRpcChild {
closed = false;
constructor(bin: string, args: string[], cwd: string) {
const spawnCommand = Effect.runSync(resolveSpawnCommand(bin, args));
this.child = spawn(spawnCommand.command, spawnCommand.args, {
this.child = spawn(bin, args, {
cwd,
shell: spawnCommand.shell,
shell: process.platform === "win32",
stdio: ["pipe", "pipe", "pipe"],
env: process.env,
});
-150
View File
@@ -1,150 +0,0 @@
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)),
);
});
-287
View File
@@ -1,287 +0,0 @@
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;
});
+2
View File
@@ -1,6 +1,8 @@
// @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")) {
+11 -6
View File
@@ -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 { it } from "@effect/vitest";
import { assert, it } from "@effect/vitest";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
import * as Duration from "effect/Duration";
@@ -11,9 +11,8 @@ 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 } from "./bootstrap.ts";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
import { assertNone, assertSome } from "@effect/vitest/utils";
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
@@ -42,6 +41,14 @@ 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;
@@ -82,9 +89,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
try {
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
}).pipe(Effect.provideService(HostProcessPlatform, "linux"));
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertSome(payload, {
mode: "desktop",
});
+32 -33
View File
@@ -11,7 +11,6 @@ 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;
@@ -111,39 +110,36 @@ const isFdReady = (fd: number) =>
);
const makeBootstrapInputStream = (fd: number) =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.try<Readable, BootstrapError>({
try: () => {
const fdPath = resolveFdPath(fd, platform);
if (fdPath === undefined) {
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);
}
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);
}
return makeDirectBootstrapStream(fd);
}
throw error;
}
},
catch: (error) =>
new BootstrapError({
message: "Failed to duplicate bootstrap fd.",
cause: error,
}),
});
throw error;
}
},
catch: (error) =>
new BootstrapError({
message: "Failed to duplicate bootstrap fd.",
cause: error,
}),
});
const makeDirectBootstrapStream = (fd: number): Readable => {
@@ -169,7 +165,10 @@ const isBootstrapFdPathDuplicationError = Predicate.compose(
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
);
function resolveFdPath(fd: number, platform: NodeJS.Platform): string | undefined {
export function resolveFdPath(
fd: number,
platform: NodeJS.Platform = process.platform,
): string | undefined {
if (platform === "linux") {
return `/proc/self/fd/${fd}`;
}
+1 -1
View File
@@ -1,4 +1,4 @@
import * as NodeOS from "node:os";
import NodeOS from "node:os";
import { assert, expect, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
-22
View File
@@ -1,22 +0,0 @@
import { assert, it } from "@effect/vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts";
it("returns the selected Codex service tier id", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [
{ id: "serviceTier", value: "flex" },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "flex");
});
it("keeps legacy persisted fast mode selections working", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "fastMode", value: true },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "fast");
});
-14
View File
@@ -1,14 +0,0 @@
import type { ModelSelection } from "@t3tools/contracts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
export function getCodexServiceTierOptionValue(
modelSelection: ModelSelection | null | undefined,
): string | undefined {
return (
getModelSelectionStringOptionValue(modelSelection, "serviceTier") ??
(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined)
);
}
@@ -4,7 +4,6 @@ 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";
@@ -278,9 +277,6 @@ 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(),
@@ -373,10 +369,8 @@ function readWindowsProcessRows(): Effect.Effect<
);
}
export const readProcessRows = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
});
export const readProcessRows = (platform = process.platform) =>
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
export function aggregateProcessDiagnostics(input: {
readonly serverPid: number;
@@ -393,7 +387,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(
@@ -413,7 +407,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,5 +1,4 @@
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";
@@ -12,8 +11,8 @@ import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/Serv
import packageJson from "../../../package.json" with { type: "json" };
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
switch (platform) {
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
switch (process.platform) {
case "darwin":
return "darwin";
case "linux":
@@ -25,10 +24,8 @@ function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["
}
}
function platformArch(
architecture: NodeJS.Architecture,
): ExecutionEnvironmentDescriptor["platform"]["arch"] {
switch (architecture) {
function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
switch (process.arch) {
case "arm64":
return "arm64";
case "x64":
@@ -43,8 +40,6 @@ 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
@@ -85,8 +80,8 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
environmentId,
label,
platform: {
os: platformOs(hostPlatform),
arch: platformArch(hostArchitecture),
os: platformOs(),
arch: platformArch(),
},
serverVersion: packageJson.version,
capabilities: {
@@ -2,7 +2,6 @@ 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";
@@ -29,16 +28,6 @@ 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();
@@ -49,7 +38,9 @@ describe("resolveServerEnvironmentLabel", () => {
Effect.gen(function* () {
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "macbook-pro")));
platform: "win32",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("macbook-pro");
}),
@@ -70,7 +61,9 @@ describe("resolveServerEnvironmentLabel", () => {
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("Julius's MacBook Pro");
expect(runMock).toHaveBeenCalledWith(
@@ -87,7 +80,9 @@ describe("resolveServerEnvironmentLabel", () => {
Effect.gen(function* () {
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(LinuxMachineInfoLayer, "linux", "buildbox")));
platform: "linux",
hostname: "buildbox",
}).pipe(Effect.provide(LinuxMachineInfoLayer));
expect(result).toBe("Build Agent 01");
expect(runMock).not.toHaveBeenCalled();
@@ -109,7 +104,9 @@ describe("resolveServerEnvironmentLabel", () => {
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", "runner-01")));
platform: "linux",
hostname: "runner-01",
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("CI Runner");
expect(runMock).toHaveBeenCalledWith(
@@ -126,7 +123,9 @@ describe("resolveServerEnvironmentLabel", () => {
Effect.gen(function* () {
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "JULIUS-LAPTOP")));
platform: "win32",
hostname: "JULIUS-LAPTOP",
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("JULIUS-LAPTOP");
}),
@@ -146,7 +145,9 @@ describe("resolveServerEnvironmentLabel", () => {
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("macbook-pro");
}),
@@ -167,7 +168,9 @@ describe("resolveServerEnvironmentLabel", () => {
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", " ")));
platform: "linux",
hostname: " ",
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("t3code");
}),
@@ -1,4 +1,5 @@
import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as OS from "node:os";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -7,6 +8,8 @@ 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 {
@@ -66,8 +69,9 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
return normalizeLabel(result.value.stdout);
});
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* () {
const platform = yield* HostProcessPlatform;
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
platform: NodeJS.Platform,
) {
if (platform === "darwin") {
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
}
@@ -90,12 +94,13 @@ const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function*
export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
input: ResolveServerEnvironmentLabelInput,
) {
const friendlyHostLabel = yield* resolveFriendlyHostLabel();
const platform = input.platform ?? process.platform;
const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
if (friendlyHostLabel) {
return friendlyHostLabel;
}
const hostname = normalizeLabel(yield* HostProcessHostname);
const hostname = normalizeLabel(input.hostname ?? OS.hostname());
if (hostname) {
return hostname;
}
+1 -1
View File
@@ -747,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetailsRemote(cwd)
.statusDetails(cwd)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
if (details === null || !details.isRepo) {
return null;
+91 -30
View File
@@ -24,13 +24,15 @@ import {
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import { resolveStaticDir, ServerConfig } from "./config.ts";
import {
ASSET_ROUTE_PREFIX,
FALLBACK_PROJECT_FAVICON_SVG,
resolveAsset,
} from "./assets/AssetAccess.ts";
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { resolveAttachmentPathById } from "./attachmentStore.ts";
import { resolveStaticDir, ServerConfig } from "./config.ts";
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
annotateEnvironmentRequest,
@@ -41,6 +43,8 @@ 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"]);
@@ -165,50 +169,107 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
),
);
export const assetRouteLayer = HttpRouter.add(
export const attachmentsRouteLayer = HttpRouter.add(
"GET",
`${ASSET_ROUTE_PREFIX}/*`,
`${ATTACHMENTS_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 suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
if (separatorIndex <= 0) {
return HttpServerResponse.text("Not Found", { status: 404 });
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 asset = yield* resolveAsset(
suffix.slice(0, separatorIndex),
suffix.slice(separatorIndex + 1),
);
if (!asset) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (asset.kind === "project-favicon-fallback") {
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
status: 200,
contentType: "image/svg+xml",
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
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,
});
}
return yield* HttpServerResponse.file(asset.path, {
const fileSystem = yield* FileSystem.FileSystem;
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
if (!fileInfo || fileInfo.type !== "File") {
return HttpServerResponse.text("Not Found", { status: 404 });
}
return yield* HttpServerResponse.file(filePath, {
status: 200,
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
"Cache-Control": "public, max-age=31536000, immutable",
},
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
}),
}).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 });
}
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) {
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
status: 200,
contentType: "image/svg+xml",
headers: {
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
},
});
}
return yield* HttpServerResponse.file(faviconFilePath, {
status: 200,
headers: {
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
},
}).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(
-2
View File
@@ -205,8 +205,6 @@ 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");
}),
-165
View File
@@ -1,165 +0,0 @@
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)),
);
-191
View File
@@ -1,191 +0,0 @@
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),
);
@@ -1,33 +0,0 @@
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;
});
-28
View File
@@ -1,28 +0,0 @@
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();
}
@@ -1,68 +0,0 @@
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();
}),
);
-207
View File
@@ -1,207 +0,0 @@
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,
};
@@ -1,89 +0,0 @@
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 } });
}),
),
);
@@ -1,309 +0,0 @@
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,
};
@@ -1,63 +0,0 @@
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);
@@ -1,37 +0,0 @@
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);
}
}
});
@@ -1,196 +0,0 @@
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);
@@ -1232,227 +1232,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("keeps the turn running across interim assistant messages until the session ends", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-lifecycle");
const turnId = TurnId.make("turn-lifecycle-1");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-tl1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-tl1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-lifecycle"),
title: "Turn lifecycle",
modelSelection: {
instanceId: ProviderInstanceId.make("claude"),
model: "claude-opus",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: CommandId.make("cmd-tl2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl2"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: "2026-01-01T00:00:01.000Z",
},
},
});
// Interim assistant message completes mid-turn (commentary between
// tool calls) — the turn must stay running and unsettled.
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.make("evt-tl3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:05.000Z",
commandId: CommandId.make("cmd-tl3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl3"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-tl-interim"),
role: "assistant",
text: "interim commentary",
turnId,
streaming: false,
createdAt: "2026-01-01T00:00:05.000Z",
updatedAt: "2026-01-01T00:00:05.000Z",
},
});
yield* projectionPipeline.bootstrap;
const runningRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]);
// The session leaving "running" is the turn-end signal.
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:01:00.000Z",
commandId: CommandId.make("cmd-tl4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl4"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "ready",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-01-01T00:01:00.000Z",
},
},
});
yield* projectionPipeline.bootstrap;
const settledRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
}),
);
it.effect("settles a superseded running turn when a new turn becomes active", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-supersede");
const oldTurnId = TurnId.make("turn-superseded");
const newTurnId = TurnId.make("turn-steer");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-ts1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-ts1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-ts1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-supersede"),
title: "Turn supersede",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "big-pickle",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) =>
eventStore.append({
type: "thread.session-set",
eventId: EventId.make(eventId),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: updatedAt,
commandId: CommandId.make(`cmd-${eventId}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-${eventId}`),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "opencode",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt,
},
},
});
yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z");
// A steer: a new turn becomes active without the provider ever
// completing the previous one.
yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z");
yield* projectionPipeline.bootstrap;
const rows = yield* sql<{
readonly turnId: string;
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT turn_id AS "turnId", state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
ORDER BY requested_at
`;
assert.deepEqual(rows, [
{ turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" },
{ turnId: newTurnId, state: "running", completedAt: null },
]);
}),
);
it.effect("keeps accumulated assistant text when completion payload text is empty", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -1877,142 +1656,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("clears stale pending user input from projected shell summaries", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-stale-user-input-1"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-stale-user-input"),
occurredAt: "2026-02-26T12:35:00.000Z",
commandId: CommandId.make("cmd-stale-user-input-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-1"),
metadata: {},
payload: {
projectId: ProjectId.make("project-stale-user-input"),
title: "Project Stale User Input",
workspaceRoot: "/tmp/project-stale-user-input",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-02-26T12:35:00.000Z",
updatedAt: "2026-02-26T12:35:00.000Z",
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-stale-user-input-2"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:01.000Z",
commandId: CommandId.make("cmd-stale-user-input-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-2"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
projectId: ProjectId.make("project-stale-user-input"),
title: "Thread Stale User Input",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-26T12:35:01.000Z",
updatedAt: "2026-02-26T12:35:01.000Z",
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-stale-user-input-3"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:02.000Z",
commandId: CommandId.make("cmd-stale-user-input-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-3"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
requestId: "user-input-request-stale-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
turnId: null,
createdAt: "2026-02-26T12:35:02.000Z",
},
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-stale-user-input-4"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:03.000Z",
commandId: CommandId.make("cmd-stale-user-input-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-4"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-failed"),
tone: "error",
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
payload: {
requestId: "user-input-request-stale-1",
detail:
"Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1",
},
turnId: null,
createdAt: "2026-02-26T12:35:03.000Z",
},
},
});
const threadRows = yield* sql<{
readonly pendingUserInputCount: number;
}>`
SELECT pending_user_input_count AS "pendingUserInputCount"
FROM projection_threads
WHERE thread_id = 'thread-stale-user-input'
`;
assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]);
}),
);
it.effect("ignores non-stale provider approval response failures", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -2,7 +2,6 @@ import {
ApprovalRequestId,
type ChatAttachment,
type OrchestrationEvent,
type OrchestrationSessionStatus,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -70,29 +69,6 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
type ProjectorName =
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
/**
* Turn state to settle still-running turns with when their session leaves the
* "running" status, or null while the session is (re)starting or running and
* turns must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSessionStatus,
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
interface ProjectorDefinition {
readonly name: ProjectorName;
readonly apply: (
@@ -165,9 +141,7 @@ function derivePendingUserInputCountFromActivities(
activity.kind === "provider.user-input.respond.failed" &&
detail !== null &&
(detail.includes("stale pending user-input request") ||
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request"))
detail.includes("unknown pending user-input request"))
) {
openRequestIds.delete(requestId);
}
@@ -1025,57 +999,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
case "thread.session-set": {
const turnId = event.payload.session.activeTurnId;
if (turnId === null || event.payload.session.status !== "running") {
// Leaving the "running" session status is the turn-end signal:
// settle still-running turns so their duration reflects the whole
// turn rather than the last assistant message.
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
if (settledTurnState === null) {
return;
}
const existingTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
existingTurns.filter((turn) => turn.turnId !== null && turn.state === "running"),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
return;
}
// A new active turn supersedes any still-running turn on the same
// thread — steering can open a new turn without the provider ever
// completing the previous one.
const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
otherRunningTurns.filter(
(turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: "completed",
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId,
@@ -1154,19 +1080,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (event.payload.turnId === null || event.payload.role !== "assistant") {
return;
}
// A completed assistant message only settles the turn once the
// session is no longer running it — providers may emit several
// assistant messages per turn (commentary between tool calls), and
// the turn must stay unsettled until the provider reports turn end
// (projected as thread.session-set leaving the "running" status).
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1175,16 +1088,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.messageId,
state: settlesTurn
? existingTurn.value.state === "interrupted"
state: event.payload.streaming
? existingTurn.value.state
: existingTurn.value.state === "interrupted"
? "interrupted"
: existingTurn.value.state === "error"
? "error"
: "completed"
: existingTurn.value.state,
completedAt: settlesTurn
? (existingTurn.value.completedAt ?? event.payload.updatedAt)
: existingTurn.value.completedAt,
: "completed",
completedAt: event.payload.streaming
? existingTurn.value.completedAt
: (existingTurn.value.completedAt ?? event.payload.updatedAt),
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
});
@@ -1197,10 +1110,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: settlesTurn ? "completed" : "running",
state: event.payload.streaming ? "running" : "completed",
requestedAt: event.payload.createdAt,
startedAt: event.payload.createdAt,
completedAt: settlesTurn ? event.payload.updatedAt : null,
completedAt: event.payload.streaming ? null : event.payload.updatedAt,
checkpointTurnCount: null,
checkpointRef: null,
checkpointStatus: null,
@@ -1247,15 +1160,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
case "thread.turn-diff-completed": {
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1271,7 +1175,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.assistantMessageId,
state: turnStillRunning ? existingTurn.value.state : nextState,
state: nextState,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
checkpointStatus: event.payload.status,
@@ -1289,7 +1193,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: turnStillRunning ? "running" : nextState,
state: nextState,
requestedAt: event.payload.completedAt,
startedAt: event.payload.completedAt,
completedAt: event.payload.completedAt,
@@ -1943,7 +1943,7 @@ describe("ProviderCommandReactor", () => {
expect(resolvedActivity).toBeUndefined();
});
it("surfaces non-resumable provider user-input callbacks as stale failures", async () => {
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.respondToUserInput.mockImplementation(() =>
@@ -1951,7 +1951,7 @@ describe("ProviderCommandReactor", () => {
new ProviderAdapterRequestError({
provider: ProviderDriverKind.make("claudeAgent"),
method: "item/tool/respondToUserInput",
detail: "Unknown pending Codex user input request: user-input-request-1",
detail: "Unknown pending user-input request: user-input-request-1",
}),
),
);
@@ -141,19 +141,9 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request")
);
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
const message = Cause.pretty(cause).toLowerCase();
return (
message.includes("unknown pending user-input request") ||
message.includes("unknown pending user input request") ||
message.includes("unknown pending codex user input request")
);
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
}
function stalePendingRequestDetail(
@@ -1117,39 +1117,39 @@ describe("ProviderRuntimeIngestion", () => {
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
Effect.andThen(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
),
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
@@ -1260,92 +1260,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
});
it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => {
// Steering a running turn: the server requests a new turn while the old
// one is still active, and providers like opencode open the new turn
// without ever completing the superseded one. The new turn.started must
// replace the active turn instead of being rejected as stale.
const harness = await createHarness();
const threadId = asThreadId("thread-1");
const oldTurnId = asTurnId("turn-steered-over");
const newTurnId = asTurnId("turn-from-steer");
const createdAt = "2026-01-01T00:00:00.000Z";
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: oldTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-steered-over"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: oldTurnId,
});
await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId,
2_000,
threadId,
);
// The steer: a user-requested turn start while the old turn still runs.
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-steer"),
threadId,
message: {
messageId: asMessageId("msg-steer"),
role: "user",
text: "actually, do 15 instead",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt,
}),
);
// The provider session tracks the new turn before emitting turn.started
// (sendTurn updates the session first).
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: newTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-from-steer"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: newTurnId,
});
const threadAfterSteer = await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId,
2_000,
threadId,
);
expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.state).toBe("running");
});
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
@@ -1226,22 +1226,6 @@ const make = Effect.gen(function* () {
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
// A turn.started that conflicts with the active turn is legitimate when
// the server itself has a turn start pending for this thread AND the
// provider session already tracks the event's turn as its active turn:
// steering a running turn makes some providers (e.g. opencode) open a
// new turn without ever completing the superseded one. A stale
// turn.started for some other turn id still gets rejected.
const conflictingTurnStartIsPendingTurnStart =
event.type === "turn.started" && conflictsWithActiveTurn
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
Option.isSome(
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
}),
)
: false;
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
@@ -1253,7 +1237,7 @@ const make = Effect.gen(function* () {
case "thread.started":
return true;
case "turn.started":
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
return !conflictsWithActiveTurn;
case "turn.completed":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
+23 -62
View File
@@ -267,76 +267,37 @@ describe("orchestration projector", () => {
),
);
const settledAt = "2026-02-23T08:01:00.000Z";
const [afterRunning, afterReady] = await Effect.runPromise(
Effect.flatMap(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
const afterRunning = await Effect.runPromise(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
threadId: "thread-1",
session: {
threadId: "thread-1",
session: {
threadId: "thread-1",
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
},
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
},
}),
),
(running) =>
Effect.map(
projectEvent(
running,
makeEvent({
sequence: 3,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: settledAt,
commandId: "cmd-ready",
payload: {
threadId: "thread-1",
session: {
threadId: "thread-1",
status: "ready",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: settledAt,
},
},
}),
),
(ready) => [running, ready] as const,
),
},
}),
),
);
const thread = afterRunning.threads[0];
expect(thread?.latestTurn?.turnId).toBe("turn-1");
expect(thread?.session?.status).toBe("running");
// Leaving the "running" session status settles the running turn with the
// session timestamp as the turn end.
const settledThread = afterReady.threads[0];
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
expect(settledThread?.latestTurn?.state).toBe("completed");
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
});
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
+15 -59
View File
@@ -38,29 +38,6 @@ function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error"
return "completed" as const;
}
/**
* Turn state to settle a still-running latest turn with when its session
* leaves the "running" status, or null while the session is (re)starting or
* running and the turn must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSession["status"],
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: ThreadId,
@@ -461,9 +438,6 @@ export function projectEvent(
"session",
);
// Leaving the "running" session status is the turn-end signal: settle
// a still-running latest turn so its duration reflects the whole turn.
const settledTurnState = settledTurnStateForSessionStatus(session.status);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -487,18 +461,7 @@ export function projectEvent(
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn !== null &&
thread.latestTurn.state === "running" &&
settledTurnState !== null
? {
...thread.latestTurn,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: session.updatedAt,
}
: thread.latestTurn,
: thread.latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -581,31 +544,24 @@ export function projectEvent(
.toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
.slice(-MAX_THREAD_CHECKPOINTS);
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const turnStillRunning =
thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
checkpoints,
latestTurn: turnStillRunning
? thread.latestTurn
: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
latestTurn: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
updatedAt: event.occurredAt,
}),
};
+66 -54
View File
@@ -1,15 +1,21 @@
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as NodeOS from "node:os";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
import {
readPathFromLoginShell,
readEnvironmentFromWindowsShell,
resolveWindowsEnvironment,
type CommandAvailabilityOptions,
type WindowsShellEnvironmentReader,
listLoginShellCandidates,
mergePathEntries,
readPathFromLoginShell,
readPathFromLaunchctl,
resolveWindowsEnvironment,
} from "@t3tools/shared/shell";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as NodeOS from "node:os";
type WindowsCommandAvailabilityChecker = (
command: string,
options?: CommandAvailabilityOptions,
) => boolean;
function logPathHydrationWarning(message: string, error?: unknown): void {
process.stderr.write(
@@ -17,60 +23,66 @@ function logPathHydrationWarning(message: string, error?: unknown): void {
);
}
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);
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;
}
if (shellPath) break;
}
if (platform !== "darwin" && platform !== "linux") return;
const launchctlPath = platform === "darwin" && !shellPath ? readPathFromLaunchctl() : undefined;
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
if (mergedPath) {
env.PATH = mergedPath;
}
}
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);
}
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;
if (shellPath) {
break;
}
}
return;
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);
}
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;
-260
View File
@@ -1,260 +0,0 @@
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"]);
}),
);
});
-362
View File
@@ -1,362 +0,0 @@
/**
* 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);
@@ -1,89 +0,0 @@
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);
}),
);
});
-363
View File
@@ -1,363 +0,0 @@
/**
* 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);
+758 -120
View File
@@ -1,7 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import { assertSuccess } from "@effect/vitest/utils";
import * as Crypto from "effect/Crypto";
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";
@@ -9,9 +11,24 @@ import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import { ExternalLauncher, layer as ExternalLauncherLive } from "./externalLauncher.ts";
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);
}
function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
return ChildProcessSpawner.makeHandle({
@@ -32,135 +49,756 @@ function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
});
}
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);
}),
),
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"],
});
}),
);
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("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("launches the default browser through the platform command", () => {
let spawned: ChildProcess.StandardCommand | undefined;
let didUnref = false;
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher;
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);
yield* launcher.launchBrowser("https://example.com/some path");
const result = yield* resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "zed" }, "linux", {
PATH: dir,
});
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;
},
}),
),
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.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 maps default browser launchers by platform", () => {
const target = "https://example.com/some path?name=o'hara";
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",
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'",
),
]);
assert.deepEqual(windows.options, {
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
});
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("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;
});
}),
});
}).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;
},
}),
),
);
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)),
);
const result = yield* launchBrowser("https://example.com").pipe(
Effect.provide(spawnerLayer),
Effect.result,
);
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");
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);
}),
);
});
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" },
}),
),
);
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)"];
assert.equal(editors.includes("vscode"), true);
assert.equal(editors.includes("file-manager"), true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
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;
});
}),
});
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: "" } }))),
);
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, []);
});
});
+37 -103
View File
@@ -12,16 +12,12 @@ import {
type EditorId,
type LaunchEditorInput,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Config from "effect/Config";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
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";
// ==============================
@@ -30,6 +26,8 @@ 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>;
@@ -63,36 +61,6 @@ 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]) {
@@ -141,17 +109,17 @@ function resolveEditorArgs(
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
}
const resolveAvailableCommand = Effect.fn("externalLauncher.resolveAvailableCommand")(function* (
function resolveAvailableCommand(
commands: ReadonlyArray<string>,
env: NodeJS.ProcessEnv,
): Effect.fn.Return<Option.Option<string>, never, FileSystem.FileSystem | Path.Path> {
options: CommandAvailabilityOptions = {},
): Option.Option<string> {
for (const command of commands) {
if (yield* isCommandAvailable(command, { env })) {
if (isCommandAvailable(command, options)) {
return Option.some(command);
}
}
return Option.none();
});
}
function encodeUtf16LeBase64(input: string): string {
const bytes = new Uint8Array(input.length * 2);
@@ -167,7 +135,7 @@ function escapePowerShellStringLiteral(input: string): string {
return `'${input.replaceAll("'", "''")}'`;
}
function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
function resolvePowerShellPath(env: NodeJS.ProcessEnv = process.env): string {
return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
}
@@ -177,7 +145,7 @@ function resolveWslPowerShellPath(): string {
function shouldUseWindowsBrowserFromWsl(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv = {},
env: NodeJS.ProcessEnv = process.env,
): boolean {
return (
platform === "linux" &&
@@ -216,10 +184,10 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
}
}
function buildBrowserLaunch(
export function resolveBrowserLaunch(
target: string,
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv = {},
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ProcessLaunch {
if (platform === "darwin") {
return {
@@ -244,49 +212,34 @@ function buildBrowserLaunch(
};
}
const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): Effect.fn.Return<ReadonlyArray<EditorId>, never, FileSystem.FileSystem | Path.Path> {
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.commands === null) {
const command = fileManagerCommandForPlatform(platform);
if (yield* isCommandAvailable(command, { env })) {
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
continue;
}
const command = yield* resolveAvailableCommand(editor.commands, env);
const command = resolveAvailableCommand(editor.commands, { platform, 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.
*/
@@ -311,11 +264,11 @@ export class ExternalLauncher extends Context.Service<ExternalLauncher, External
// Implementations
// ==============================
const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
input: LaunchEditorInput,
): Effect.fn.Return<EditorLaunch, ExternalLauncherError, FileSystem.FileSystem | Path.Path> {
const platform = yield* HostProcessPlatform;
const env = yield* readCommandLookupEnv;
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<EditorLaunch, ExternalLauncherError> {
yield* Effect.annotateCurrentSpan({
"externalLauncher.editor": input.editor,
"externalLauncher.cwd": input.cwd,
@@ -328,7 +281,7 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
if (editorDef.commands) {
const command = Option.getOrElse(
yield* resolveAvailableCommand(editorDef.commands, env),
resolveAvailableCommand(editorDef.commands, { platform, env }),
() => editorDef.commands[0],
);
return {
@@ -359,35 +312,29 @@ const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
);
});
const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
export const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
target: string,
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
const launch = yield* resolveBrowserLaunch(target);
return yield* launchAndUnref(launch, "Browser auto-open failed");
return yield* launchAndUnref(resolveBrowserLaunch(target), "Browser auto-open failed");
});
const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
launch: EditorLaunch,
): Effect.fn.Return<
void,
ExternalLauncherError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const env = yield* readCommandLookupEnv;
if (!(yield* isCommandAvailable(launch.command, { env }))) {
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
if (!isCommandAvailable(launch.command)) {
return yield* new ExternalLauncherError({
message: `Editor command not found: ${launch.command}`,
});
}
const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
const isWin32 = process.platform === "win32";
yield* launchAndUnref(
{
command: spawnCommand.command,
args: spawnCommand.args,
command: launch.command,
args: isWin32 ? launch.args.map((arg) => `"${arg}"`) : [...launch.args],
options: {
detached: true,
shell: spawnCommand.shell,
shell: isWin32,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
@@ -399,29 +346,16 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu
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) =>
provideCommandResolutionServices(
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
launchEditorProcess(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
launchEditorProcess(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
),
} satisfies ExternalLauncherShape;
+16 -52
View File
@@ -8,8 +8,6 @@ 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,
@@ -23,9 +21,6 @@ import {
type ChildProcessCommand = {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly options: {
readonly shell?: boolean | string;
};
};
// Accesses private properties of ChildProcessCommand for testing purposes
@@ -73,6 +68,7 @@ const runWith =
Effect.flatMap((runner) =>
runner.run({
...input,
shell: input.shell ?? false,
}),
),
Effect.provide(
@@ -127,44 +123,6 @@ 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) })));
@@ -322,13 +280,19 @@ describe("runProcess", () => {
});
describe("isWindowsCommandNotFound", () => {
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);
}),
);
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 });
}
});
});
+9 -19
View File
@@ -8,8 +8,6 @@ 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,
@@ -26,6 +24,7 @@ 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.
@@ -110,14 +109,11 @@ function hasWindowsCommandNotFoundMessage(output: string): boolean {
return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
}
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);
},
);
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
if (process.platform !== "win32") return false;
if (code === 9009) return true;
return hasWindowsCommandNotFoundMessage(stderr);
}
const collectText = Effect.fn("processRunner.collectText")(function* (input: {
readonly command: string;
@@ -235,24 +231,18 @@ 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(spawnCommand.command, spawnCommand.args, {
ChildProcess.make(input.command, [...input.args], {
...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
...(input.env !== undefined
? {
env: input.env,
extendEnv,
extendEnv: true,
}
: {}),
shell: spawnCommand.shell,
...(input.shell !== undefined ? { shell: input.shell } : {}),
}),
)
.pipe(
@@ -7,10 +7,9 @@ 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.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(ProjectFaviconResolverLive),
Layer.provideMerge(NodeServices.layer),
);
@@ -7,7 +7,6 @@ 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 = [
@@ -62,32 +61,28 @@ 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 = (href: string): string[] => {
const resolveIconHref = (projectCwd: string, href: string): string[] => {
const clean = href.replace(/^\//, "");
return [path.join("public", clean), clean];
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));
};
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
projectCwd: string,
relativeCandidates: ReadonlyArray<string>,
candidates: ReadonlyArray<string>,
): Effect.fn.Return<string | null> {
for (const relativePath of relativeCandidates) {
const candidate = yield* workspacePaths
.resolveRelativePathWithinRoot({
workspaceRoot: projectCwd,
relativePath,
})
.pipe(Effect.orElseSucceed(() => null));
if (!candidate) {
for (const candidate of candidates) {
if (!isPathWithinProject(projectCwd, candidate)) {
continue;
}
const stats = yield* fileSystem
.stat(candidate.absolutePath)
.pipe(Effect.orElseSucceed(() => null));
const stats = yield* fileSystem.stat(candidate).pipe(Effect.orElseSucceed(() => null));
if (stats?.type === "File") {
return candidate.absolutePath;
return candidate;
}
}
return null;
@@ -96,31 +91,18 @@ 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 existing = yield* findExistingFile(projectCwd, [candidate]);
const resolved = path.join(cwd, candidate);
const existing = yield* findExistingFile(cwd, [resolved]);
if (existing) {
return existing;
}
}
for (const sourceFile of ICON_SOURCE_FILES) {
const sourcePath = yield* workspacePaths
.resolveRelativePathWithinRoot({
workspaceRoot: projectCwd,
relativePath: sourceFile,
})
.pipe(Effect.orElseSucceed(() => null));
if (!sourcePath) {
continue;
}
const sourcePath = path.join(cwd, sourceFile);
const source = yield* fileSystem
.readFileString(sourcePath.absolutePath)
.readFileString(sourcePath)
.pipe(Effect.orElseSucceed(() => null));
if (!source) {
continue;
@@ -129,7 +111,7 @@ export const makeProjectFaviconResolver = Effect.gen(function* () {
if (!href) {
continue;
}
const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));
const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href));
if (existing) {
return existing;
}
@@ -89,8 +89,6 @@ 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,14 +1,3 @@
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.
@@ -129,7 +118,6 @@ 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
@@ -143,5 +131,4 @@ 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,14 +16,13 @@ export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function
export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function* (
config: Pick<ClaudeSettings, "homePath">,
baseEnv?: NodeJS.ProcessEnv,
baseEnv: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
const resolvedBaseEnv = baseEnv ?? process.env;
const homePath = config.homePath.trim();
if (homePath.length === 0) return resolvedBaseEnv;
if (homePath.length === 0) return baseEnv;
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return {
...resolvedBaseEnv,
...baseEnv,
HOME: resolvedHomePath,
};
});
@@ -890,73 +890,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.takeUntil(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runCollect, Effect.forkChild);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "run 5 commands",
attachments: [],
});
// Steer: a second sendTurn while the turn is still running continues
// the same turn — the message is queued into the live agent loop.
const steeredTurn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "actually run 15",
attachments: [],
});
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
harness.query.emit({
type: "assistant",
session_id: "sdk-session-steer",
uuid: "assistant-steer-1",
parent_tool_use_id: null,
message: {
id: "assistant-message-steer-1",
content: [{ type: "text", text: "Adjusting to 15." }],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-steer",
uuid: "result-steer-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
// One turn boundary for the whole run: the steer produced no
// turn.completed/turn.started pair.
assert.equal(turnStartedEvents.length, 1);
assert.equal(String(turnStartedEvents[0]?.turnId), String(turn.turnId));
assert.equal(turnCompletedEvents.length, 1);
assert.equal(String(turnCompletedEvents[0]?.turnId), String(turn.turnId));
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => {
const harness = makeHarness();
return Effect.gen(function* () {
+167 -641
View File
@@ -14,7 +14,6 @@ import {
type PermissionResult,
type PermissionUpdate,
type SDKMessage,
type SDKControlGetContextUsageResponse,
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
@@ -30,7 +29,6 @@ import {
type ProviderApprovalDecision,
ProviderDriverKind,
ProviderInstanceId,
type ModelSelection,
ProviderItemId,
type ProviderRuntimeEvent,
type ProviderRuntimeTurnStatus,
@@ -69,7 +67,6 @@ 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,
@@ -123,13 +120,6 @@ interface ClaudeResumeState {
interface ClaudeTurnState {
readonly turnId: TurnId;
readonly startedAt: string;
/**
* True for turns auto-started by assistant output arriving without an
* active turn (background agent/subagent responses between user prompts).
* Synthetic turns are auto-closed by the next sendTurn; real turns are
* steered instead (the queued message continues the same turn).
*/
readonly synthetic?: boolean;
readonly items: Array<unknown>;
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
@@ -169,13 +159,6 @@ interface ToolInFlight {
readonly lastEmittedInputFingerprint?: string;
}
interface ClaudeTaskState {
readonly id: string;
subject: string;
status: PlanStep["status"];
readonly blockedBy: Set<string>;
}
interface ClaudeSessionContext {
session: ProviderSession;
readonly promptQueue: Queue.Queue<PromptQueueItem>;
@@ -192,11 +175,9 @@ interface ClaudeSessionContext {
items: Array<unknown>;
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
readonly claudeTasks: Map<string, ClaudeTaskState>;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
lastKnownTotalProcessedTokens: number | undefined;
lastAssistantUuid: string | undefined;
lastThreadStartedId: string | undefined;
stopped: boolean;
@@ -207,7 +188,6 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly setModel: (model?: string) => Promise<void>;
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;
readonly close: () => void;
}
@@ -357,220 +337,60 @@ function maxClaudeContextWindowFromModelUsage(
return maxContextWindow;
}
function selectedClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): number | undefined {
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value >= 0
? Math.round(value)
: undefined;
}
function finitePositiveInteger(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value > 0
? Math.round(value)
: undefined;
}
function claudeUsageInputTokens(usage: Record<string, unknown>): number {
return (
(finiteNonNegativeInteger(usage.input_tokens) ?? 0) +
(finiteNonNegativeInteger(usage.cache_creation_input_tokens) ?? 0) +
(finiteNonNegativeInteger(usage.cache_read_input_tokens) ?? 0)
);
}
function claudeUsageOutputTokens(usage: Record<string, unknown>): number {
return finiteNonNegativeInteger(usage.output_tokens) ?? 0;
}
function lastClaudeUsageIteration(
value: Record<string, unknown>,
): Record<string, unknown> | undefined {
const iterations = Array.isArray(value.iterations) ? value.iterations : [];
return iterations.findLast(
(iteration): iteration is Record<string, unknown> =>
iteration !== null && typeof iteration === "object" && !Array.isArray(iteration),
);
}
function claudeTotalProcessedTokens(value: unknown): number | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return undefined;
}
const usage = value as Record<string, unknown>;
const explicitTotal = finiteNonNegativeInteger(usage.total_tokens);
if (explicitTotal !== undefined && explicitTotal > 0) {
return explicitTotal;
}
const total = claudeUsageInputTokens(usage) + claudeUsageOutputTokens(usage);
return total > 0 ? total : undefined;
}
function makeClaudeTokenUsageSnapshot(input: {
readonly activeTokens: number;
readonly inputTokens?: number;
readonly outputTokens?: number;
readonly contextWindow?: number;
readonly totalProcessedTokens?: number;
readonly lastUsedTokens?: number;
readonly compactsAutomatically?: boolean;
}): ThreadTokenUsageSnapshot | undefined {
const activeTokens = finiteNonNegativeInteger(input.activeTokens);
if (activeTokens === undefined || activeTokens <= 0) {
return undefined;
}
const maxTokens = finitePositiveInteger(input.contextWindow);
const usedTokens = maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens;
const lastUsedTokens =
finiteNonNegativeInteger(input.lastUsedTokens) ??
(maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens);
const totalProcessedTokens = finiteNonNegativeInteger(input.totalProcessedTokens);
const inputTokens = finiteNonNegativeInteger(input.inputTokens);
const outputTokens = finiteNonNegativeInteger(input.outputTokens);
return {
usedTokens,
lastUsedTokens,
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
? { totalProcessedTokens }
: {}),
...(inputTokens !== undefined && inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens !== undefined && outputTokens > 0 ? { outputTokens } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
...(input.compactsAutomatically !== undefined
? { compactsAutomatically: input.compactsAutomatically }
: {}),
};
}
function normalizeClaudeActiveTokenUsage(
function normalizeClaudeTokenUsage(
value: unknown,
contextWindow?: number,
totalProcessedTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const usage = value as Record<string, unknown>;
const activeUsage = lastClaudeUsageIteration(usage) ?? usage;
const inputTokens = claudeUsageInputTokens(activeUsage);
const outputTokens = claudeUsageOutputTokens(activeUsage);
const activeTokens = claudeTotalProcessedTokens(activeUsage) ?? inputTokens + outputTokens;
if (activeTokens <= 0) {
const inputTokens =
(typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens)
? usage.input_tokens
: 0) +
(typeof usage.cache_creation_input_tokens === "number" &&
Number.isFinite(usage.cache_creation_input_tokens)
? usage.cache_creation_input_tokens
: 0) +
(typeof usage.cache_read_input_tokens === "number" &&
Number.isFinite(usage.cache_read_input_tokens)
? usage.cache_read_input_tokens
: 0);
const outputTokens =
typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)
? usage.output_tokens
: 0;
const derivedTotalProcessedTokens = inputTokens + outputTokens;
const totalProcessedTokens =
(typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens)
? usage.total_tokens
: undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined);
if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) {
return undefined;
}
return makeClaudeTokenUsageSnapshot({
activeTokens,
inputTokens,
outputTokens,
...(contextWindow !== undefined ? { contextWindow } : {}),
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
});
}
const maxTokens =
typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
? contextWindow
: undefined;
const usedTokens =
maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens;
function normalizeClaudeContextUsageApiSnapshot(
value: SDKControlGetContextUsageResponse,
totalProcessedTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
return makeClaudeTokenUsageSnapshot({
activeTokens: value.totalTokens,
contextWindow: value.maxTokens,
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
compactsAutomatically: value.isAutoCompactEnabled,
});
}
function compactBoundaryTokenUsageSnapshot(
message: Record<string, unknown>,
contextWindow?: number,
totalProcessedTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
const metadata = message.compact_metadata;
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
return undefined;
}
const compactMetadata = metadata as Record<string, unknown>;
const postTokens = finiteNonNegativeInteger(compactMetadata.post_tokens);
if (postTokens === undefined || postTokens <= 0) {
return undefined;
}
const preTokens = finiteNonNegativeInteger(compactMetadata.pre_tokens);
return makeClaudeTokenUsageSnapshot({
activeTokens: postTokens,
...(preTokens !== undefined ? { lastUsedTokens: preTokens } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
});
}
function normalizeClaudeTaskProgressTokenUsage(
value: unknown,
context: ClaudeSessionContext,
): ThreadTokenUsageSnapshot | undefined {
const totalTokens = claudeTotalProcessedTokens(value);
if (totalTokens === undefined || totalTokens <= 0) {
return undefined;
}
const lastUsedTokens = context.lastKnownTokenUsage?.usedTokens;
const activeTokens =
lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens;
if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) {
return undefined;
}
const usage = value as Record<string, unknown>;
const snapshot = makeClaudeTokenUsageSnapshot({
activeTokens,
...(context.lastKnownContextWindow !== undefined
? { contextWindow: context.lastKnownContextWindow }
: {}),
totalProcessedTokens: Math.max(
totalTokens,
context.lastKnownTotalProcessedTokens ?? totalTokens,
),
});
if (!snapshot) {
return undefined;
}
const toolUses = finiteNonNegativeInteger(usage.tool_uses);
const durationMs = finiteNonNegativeInteger(usage.duration_ms);
return {
...snapshot,
...(toolUses !== undefined ? { toolUses } : {}),
...(durationMs !== undefined ? { durationMs } : {}),
usedTokens,
lastUsedTokens: usedTokens,
...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}),
...(inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens > 0 ? { outputTokens } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses)
? { toolUses: usage.tool_uses }
: {}),
...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms)
? { durationMs: usage.duration_ms }
: {}),
};
}
@@ -719,140 +539,6 @@ function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep
}));
}
function isClaudeTaskTool(toolName: string): boolean {
return toolName === "TaskCreate" || toolName === "TaskUpdate" || toolName === "TaskList";
}
function normalizeClaudeTaskStatus(value: unknown): PlanStep["status"] {
return value === "completed" ? "completed" : value === "in_progress" ? "inProgress" : "pending";
}
function readString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function readStringArray(value: unknown): Array<string> {
return Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0)
: [];
}
function readClaudeToolUseResult(message: SDKMessage): Record<string, unknown> | undefined {
if (message.type !== "user") {
return undefined;
}
const result = (message as { readonly tool_use_result?: unknown }).tool_use_result;
return result !== null && typeof result === "object" && !Array.isArray(result)
? (result as Record<string, unknown>)
: undefined;
}
function readClaudeTaskFromResult(
result: Record<string, unknown> | undefined,
): Record<string, unknown> | undefined {
const task = result?.task;
return task !== null && typeof task === "object" && !Array.isArray(task)
? (task as Record<string, unknown>)
: undefined;
}
function applyClaudeTaskToolResult(
tasks: Map<string, ClaudeTaskState>,
tool: ToolInFlight,
result: Record<string, unknown> | undefined,
): boolean {
if (!isClaudeTaskTool(tool.toolName)) {
return false;
}
let changed = false;
if (tool.toolName === "TaskList") {
const resultTasks = result?.tasks;
if (!Array.isArray(resultTasks)) {
return false;
}
tasks.clear();
for (const entry of resultTasks) {
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
continue;
}
const task = entry as Record<string, unknown>;
const id = readString(task.id);
const subject = readString(task.subject);
if (!id || !subject) {
continue;
}
tasks.set(id, {
id,
subject,
status: normalizeClaudeTaskStatus(task.status),
blockedBy: new Set(readStringArray(task.blockedBy)),
});
}
return tasks.size > 0;
}
if (tool.toolName === "TaskCreate") {
const resultTask = readClaudeTaskFromResult(result);
const id = readString(resultTask?.id);
const subject = readString(resultTask?.subject) ?? readString(tool.input.subject);
if (!id || !subject) {
return false;
}
tasks.set(id, {
id,
subject,
status: normalizeClaudeTaskStatus(tool.input.status),
blockedBy: new Set(readStringArray(tool.input.blockedBy)),
});
return true;
}
const taskId = readString(tool.input.taskId) ?? readString(result?.taskId);
if (!taskId) {
return false;
}
const task = tasks.get(taskId);
if (!task) {
return false;
}
const subject = readString(tool.input.subject);
if (subject && task.subject !== subject) {
task.subject = subject;
changed = true;
}
if (typeof tool.input.status === "string") {
const status = normalizeClaudeTaskStatus(tool.input.status);
if (task.status !== status) {
task.status = status;
changed = true;
}
}
for (const dependency of readStringArray(tool.input.addBlockedBy)) {
if (!task.blockedBy.has(dependency)) {
task.blockedBy.add(dependency);
changed = true;
}
}
for (const dependency of readStringArray(tool.input.removeBlockedBy)) {
if (task.blockedBy.delete(dependency)) {
changed = true;
}
}
return changed;
}
function planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep[] {
return Array.from(tasks.values()).map((task) => {
const blockedBy = Array.from(task.blockedBy);
const blockedSuffix = blockedBy.length > 0 ? ` (blocked by #${blockedBy.join(", #")})` : "";
return {
step: `${task.subject}${blockedSuffix}`,
status: task.status,
};
});
}
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
const commandValue = input.command ?? input.cmd;
const command = typeof commandValue === "string" ? commandValue : undefined;
@@ -1752,70 +1438,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
});
const emitThreadTokenUsage = Effect.fn("emitThreadTokenUsage")(function* (
context: ClaudeSessionContext,
usage: ThreadTokenUsageSnapshot | undefined,
options?: {
readonly rawMethod?: string;
readonly rawPayload?: unknown;
},
) {
if (!usage) {
return;
}
context.lastKnownTokenUsage = usage;
context.lastKnownTotalProcessedTokens =
usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens;
const turnState = context.turnState;
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(turnState ? { turnId: turnState.turnId } : {}),
payload: {
usage,
},
providerRefs: nativeProviderRefs(context),
...(options?.rawMethod || options?.rawPayload
? {
raw: {
source: "claude.sdk.message" as const,
...(options.rawMethod ? { method: options.rawMethod } : {}),
payload: options.rawPayload,
},
}
: {}),
});
});
const queryCurrentContextUsage = Effect.fn("queryCurrentContextUsage")(function* (
context: ClaudeSessionContext,
totalProcessedTokens?: number,
) {
if (!context.query.getContextUsage) {
return undefined;
}
const usage = yield* Effect.promise(async () => {
try {
return await context.query.getContextUsage?.();
} catch {
return undefined;
}
});
if (!usage) {
return undefined;
}
context.lastKnownContextWindow = usage.maxTokens;
return normalizeClaudeContextUsageApiSnapshot(usage, totalProcessedTokens);
});
const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* (
context: ClaudeSessionContext,
input: {
@@ -1863,42 +1485,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
});
const emitClaudeTaskPlanUpdated = Effect.fn("emitClaudeTaskPlanUpdated")(function* (
context: ClaudeSessionContext,
input: {
readonly toolUseId: string;
readonly rawMethod: string;
readonly rawPayload: unknown;
},
) {
const plan = planStepsFromClaudeTasks(context.claudeTasks);
if (plan.length === 0) {
return;
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.plan.updated",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
payload: {
explanation: "Claude Tasks",
plan,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: input.toolUseId,
}),
raw: {
source: "claude.sdk.message",
method: input.rawMethod,
payload: input.rawPayload,
},
});
});
const completeTurn = Effect.fn("completeTurn")(function* (
context: ClaudeSessionContext,
status: ProviderRuntimeTurnStatus,
@@ -1910,77 +1496,51 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
context.lastKnownContextWindow = resultContextWindow;
}
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
const accumulatedTotalProcessedTokens = claudeTotalProcessedTokens(result?.usage);
if (accumulatedTotalProcessedTokens !== undefined) {
context.lastKnownTotalProcessedTokens = accumulatedTotalProcessedTokens;
}
const contextUsageSnapshot = yield* queryCurrentContextUsage(
context,
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
// The SDK result.usage contains *accumulated* totals across all API calls
// (input_tokens, cache_read_input_tokens, etc. summed over every request).
// This does NOT represent the current context window size.
// Instead, use the last known context-window-accurate usage from task_progress
// events and treat the accumulated total as totalProcessedTokens.
const accumulatedSnapshot = normalizeClaudeTokenUsage(
result?.usage,
resultContextWindow ?? context.lastKnownContextWindow,
);
const resultUsageRecord =
result?.usage && typeof result.usage === "object" && !Array.isArray(result.usage)
? (result.usage as Record<string, unknown>)
: undefined;
const hasResultUsageIteration =
resultUsageRecord !== undefined && lastClaudeUsageIteration(resultUsageRecord) !== undefined;
const resultHasActiveUsage =
resultUsageRecord !== undefined &&
(hasResultUsageIteration ||
claudeUsageInputTokens(resultUsageRecord) + claudeUsageOutputTokens(resultUsageRecord) > 0);
const resultTotalOnly =
resultUsageRecord !== undefined &&
!resultHasActiveUsage &&
claudeTotalProcessedTokens(resultUsageRecord) !== undefined;
const resultIterationSnapshot = resultUsageRecord
? normalizeClaudeActiveTokenUsage(
resultUsageRecord,
maxTokens,
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
)
: undefined;
const accumulatedTotalProcessedTokens =
accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens;
const lastGoodUsage = context.lastKnownTokenUsage;
const usageSnapshot: ThreadTokenUsageSnapshot | undefined =
contextUsageSnapshot ??
(resultTotalOnly && lastGoodUsage
? {
...lastGoodUsage,
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
? { maxTokens }
: {}),
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
: {}),
}
: resultIterationSnapshot) ??
(lastGoodUsage
? {
...lastGoodUsage,
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
? { maxTokens }
: {}),
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
: {}),
}
: undefined);
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
? {
...lastGoodUsage,
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
? { maxTokens }
: {}),
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
: {}),
}
: accumulatedSnapshot;
const turnState = context.turnState;
if (!turnState) {
yield* emitThreadTokenUsage(context, usageSnapshot, {
rawMethod: "claude/result",
rawPayload: result ?? { status },
});
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
payload: {
usage: usageSnapshot,
},
providerRefs: {},
});
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
@@ -2051,10 +1611,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
items: [...turnState.items],
});
yield* emitThreadTokenUsage(context, usageSnapshot, {
rawMethod: "claude/result",
rawPayload: result ?? { status },
});
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
turnId: turnState.turnId,
payload: {
usage: usageSnapshot,
},
providerRefs: nativeProviderRefs(context),
});
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
@@ -2099,23 +1670,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const { event } = message;
if (event.type === "message_delta") {
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
return;
}
const snapshot = normalizeClaudeActiveTokenUsage(
event.usage,
context.lastKnownContextWindow,
context.lastKnownTotalProcessedTokens,
);
yield* emitThreadTokenUsage(context, snapshot, {
rawMethod: "claude/stream_event/message_delta",
rawPayload: message,
});
return;
}
if (event.type === "content_block_delta") {
if (
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
@@ -2378,7 +1932,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const [index, tool] = toolEntry;
const itemStatus = toolResult.isError ? "failed" : "completed";
const toolUseResult = readClaudeToolUseResult(message);
const toolData = {
toolName: tool.toolName,
input: tool.input,
@@ -2463,17 +2016,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
if (
!toolResult.isError &&
applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)
) {
yield* emitClaudeTaskPlanUpdated(context, {
toolUseId: tool.itemId,
rawMethod: "claude/user",
rawPayload: message,
});
}
context.inFlightTools.delete(index);
}
});
@@ -2494,7 +2036,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
context.turnState = {
turnId,
startedAt,
synthetic: true,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
@@ -2630,18 +2171,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
return;
case "compact_boundary":
yield* emitThreadTokenUsage(
context,
compactBoundaryTokenUsageSnapshot(
message as unknown as Record<string, unknown>,
context.lastKnownContextWindow,
context.lastKnownTotalProcessedTokens,
),
{
rawMethod: "claude/system/compact_boundary",
rawPayload: message,
},
);
yield* offerRuntimeEvent({
...base,
type: "thread.state.changed",
@@ -2700,14 +2229,25 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
return;
case "task_progress":
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
{
rawMethod: "claude/system/task_progress",
rawPayload: message,
},
);
if (message.usage) {
const normalizedUsage = normalizeClaudeTokenUsage(
message.usage,
context.lastKnownContextWindow,
);
if (normalizedUsage) {
context.lastKnownTokenUsage = normalizedUsage;
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: usageStamp.eventId,
createdAt: usageStamp.createdAt,
type: "thread.token-usage.updated",
payload: {
usage: normalizedUsage,
},
});
}
}
yield* offerRuntimeEvent({
...base,
type: "task.progress",
@@ -2721,14 +2261,25 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
return;
case "task_notification":
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
{
rawMethod: "claude/system/task_notification",
rawPayload: message,
},
);
if (message.usage) {
const normalizedUsage = normalizeClaudeTokenUsage(
message.usage,
context.lastKnownContextWindow,
);
if (normalizedUsage) {
context.lastKnownTokenUsage = normalizedUsage;
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: usageStamp.eventId,
createdAt: usageStamp.createdAt,
type: "thread.token-usage.updated",
payload: {
usage: normalizedUsage,
},
});
}
}
yield* offerRuntimeEvent({
...base,
type: "task.completed",
@@ -3118,7 +2669,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const inFlightTools = new Map<number, ToolInFlight>();
const claudeTasks = new Map<string, ClaudeTaskState>();
const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
@@ -3419,7 +2969,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const caps = getClaudeModelCapabilities(modelSelection?.model);
const descriptors = getProviderOptionDescriptors({ caps });
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
const initialContextWindow = selectedClaudeContextWindow(modelSelection);
const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort");
const effort = resolveClaudeEffort(caps, rawEffort) ?? null;
const fastModeSupported = descriptors.some(
@@ -3446,7 +2995,6 @@ 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 } : {}),
@@ -3472,19 +3020,6 @@ 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({
@@ -3559,11 +3094,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
pendingUserInputs,
turns: [],
inFlightTools,
claudeTasks,
turnState: undefined,
lastKnownContextWindow: initialContextWindow,
lastKnownContextWindow: undefined,
lastKnownTokenUsage: undefined,
lastKnownTotalProcessedTokens: undefined,
lastAssistantUuid: resumeState?.resumeSessionAt,
lastThreadStartedId: undefined,
stopped: false,
@@ -3652,14 +3185,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
? input.modelSelection
: undefined;
// A sendTurn while a real turn is running is a steer: the message is
// queued into the live SDK agent loop and the work continues as the same
// turn — no synthetic turn boundary. Stale synthetic turns (from
// background agent responses between user prompts) are auto-closed
// instead, so they don't block the user's next turn.
const steeringTurnState =
context.turnState && context.turnState.synthetic !== true ? context.turnState : null;
if (context.turnState && steeringTurnState === null) {
if (context.turnState) {
// Auto-close a stale synthetic turn (from background agent responses
// between user prompts) to prevent blocking the user's next turn.
yield* completeTurn(context, "completed");
}
@@ -3694,39 +3222,37 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);
if (steeringTurnState === null) {
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
nextSyntheticAssistantBlockIndex: -1,
};
const turnId = TurnId.make(yield* randomUUIDv4);
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
nextSyntheticAssistantBlockIndex: -1,
};
const updatedAt = yield* nowIso;
context.turnState = turnState;
context.session = {
...context.session,
status: "running",
activeTurnId: turnId,
updatedAt,
};
const updatedAt = yield* nowIso;
context.turnState = turnState;
context.session = {
...context.session,
status: "running",
activeTurnId: turnId,
updatedAt,
};
const turnStartedStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.started",
eventId: turnStartedStamp.eventId,
provider: PROVIDER,
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: modelSelection?.model ? { model: modelSelection.model } : {},
providerRefs: {},
});
}
const turnStartedStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.started",
eventId: turnStartedStamp.eventId,
provider: PROVIDER,
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: modelSelection?.model ? { model: modelSelection.model } : {},
providerRefs: {},
});
const message = yield* buildUserMessageEffect(input, {
fileSystem,
@@ -18,7 +18,6 @@ import {
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
query as claudeQuery,
@@ -109,6 +108,14 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
@@ -135,6 +142,14 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
@@ -548,7 +563,7 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
*/
const probeClaudeCapabilities = (
claudeSettings: ClaudeSettings,
environment?: NodeJS.ProcessEnv,
environment: NodeJS.ProcessEnv = process.env,
) => {
const abort = new AbortController();
return Effect.gen(function* () {
@@ -604,15 +619,12 @@ const probeClaudeCapabilities = (
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
claudeSettings: ClaudeSettings,
args: ReadonlyArray<string>,
environment?: NodeJS.ProcessEnv,
environment: NodeJS.ProcessEnv = process.env,
) {
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
env: claudeEnvironment,
});
const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
env: claudeEnvironment,
shell: spawnCommand.shell,
shell: process.platform === "win32",
});
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
@@ -622,13 +634,12 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
resolveCapabilities?: (
claudeSettings: ClaudeSettings,
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
environment?: NodeJS.ProcessEnv,
environment: NodeJS.ProcessEnv = process.env,
): 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,
@@ -653,11 +664,10 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const versionProbe = yield* runClaudeCommand(
claudeSettings,
["--version"],
resolvedEnvironment,
).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);
const versionProbe = yield* runClaudeCommand(claudeSettings, ["--version"], environment).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
@@ -271,7 +271,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "serviceTier", value: "priority" },
{ id: "fastMode", value: true },
]),
runtimeMode: "full-access",
});
@@ -281,7 +281,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
cwd: process.cwd(),
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "priority",
serviceTier: "fast",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
@@ -344,7 +344,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "serviceTier", value: "priority" },
{ id: "fastMode", value: true },
]),
attachments: [],
}),
@@ -354,7 +354,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "priority",
serviceTier: "fast",
});
}),
);
@@ -398,7 +398,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
"gpt-5.3-codex",
[
{ id: "reasoningEffort", value: "high" },
{ id: "serviceTier", value: "flex" },
{ id: "fastMode", value: true },
],
),
attachments: [],
@@ -409,7 +409,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "flex",
serviceTier: "fast",
});
}).pipe(Effect.provide(customLayer));
});
@@ -491,64 +491,6 @@ 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();
+12 -30
View File
@@ -37,9 +37,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexErrors from "effect-codex-app-server/errors";
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 {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import {
ProviderAdapterRequestError,
@@ -235,10 +236,7 @@ function toCanonicalItemType(raw: string | undefined | null): CanonicalItemType
return "unknown";
}
function itemTitle(itemType: CanonicalItemType, item?: CodexLifecycleItem): string | undefined {
if (itemType === "mcp_tool_call" && item?.type === "mcpToolCall") {
return `${item.server} · ${item.tool}`;
}
function itemTitle(itemType: CanonicalItemType): string | undefined {
switch (itemType) {
case "assistant_message":
return "Assistant message";
@@ -479,7 +477,7 @@ function mapItemLifecycle(
payload: {
itemType,
...(status ? { status } : {}),
...(itemTitle(itemType, item) ? { title: itemTitle(itemType, item) } : {}),
...(itemTitle(itemType) ? { title: itemTitle(itemType) } : {}),
...(detail ? { detail } : {}),
...(event.payload !== undefined ? { data: event.payload } : {}),
},
@@ -1382,11 +1380,6 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
providerInstanceId: boundInstanceId,
@@ -1401,20 +1394,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
...(input.modelSelection?.instanceId === boundInstanceId
? { 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"',
],
}
...(input.modelSelection?.instanceId === boundInstanceId &&
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
? { serviceTier: "fast" }
: {}),
};
const sessionScope = yield* Scope.make("sequential");
@@ -1531,9 +1513,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
: undefined;
const serviceTier =
const fastMode =
input.modelSelection?.instanceId === boundInstanceId
? getCodexServiceTierOptionValue(input.modelSelection)
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
: undefined;
return yield* session.runtime
.sendTurn({
@@ -1546,7 +1528,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,
}
: {}),
...(serviceTier ? { serviceTier } : {}),
...(fastMode === true ? { serviceTier: "fast" } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
})
@@ -1,104 +0,0 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: [],
defaultReasoningEffort: "super-high",
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
defaultServiceTier: "flex",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
name: "Flex",
description: "Lower-cost asynchronous routing.",
},
],
supportedReasoningEfforts: [
{
description: "Maximum reasoning",
reasoningEffort: "super-high",
},
],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: [{ id: "super-high", label: "super-high", isDefault: true }],
currentValue: "super-high",
},
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard" },
{
id: "priority",
label: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
label: "Flex",
description: "Lower-cost asynchronous routing.",
isDefault: true,
},
],
currentValue: "flex",
},
]);
});
it("uses standard routing when the catalog has no default service tier", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: ["fast"],
defaultReasoningEffort: "medium",
defaultServiceTier: null,
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "1.5x speed, increased usage",
},
],
supportedReasoningEfforts: [],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard", isDefault: true },
{
id: "priority",
label: "Fast",
description: "1.5x speed, increased usage",
},
],
currentValue: "default",
},
]);
});
Loaded 100 of 335 files, more files were not shown because too many files have changed in this diff. Show more