Compare commits

..
Author SHA1 Message Date
8ea45f447c feat(web): split composer traits into per-descriptor pickers, rename Fast Mode to Speed
Ported from #2451.

Co-authored-by: ss <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-09 16:27:29 -07:00
328 changed files with 6245 additions and 35037 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);
+2 -7
View File
@@ -2,11 +2,7 @@ import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
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();
@@ -83,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",
@@ -307,31 +307,6 @@ function buildMacLauncher(electronBinaryPath) {
return targetBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
if (process.platform !== "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();
@@ -345,14 +320,6 @@ export function resolveElectronPath() {
return buildMacLauncher(electronBinaryPath);
}
export function resolveElectronLaunchCommand(args = []) {
const electronPath = resolveElectronPath();
return {
electronPath,
args: [...resolveLinuxSandboxArgs(electronPath), ...args],
};
}
export function resolveDevProtocolClient() {
if (process.platform !== "darwin" || !isDevelopment) {
return null;
+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))) {
@@ -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
@@ -44,12 +44,6 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
continue;
}
// Header items are decorative section labels for the web fallback only —
// Electron's native menu has no equivalent affordance, so we skip them.
if (sourceItem.header === true) {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
+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;
+1 -11
View File
@@ -44,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(
@@ -129,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"),
}),
),
),
);
+2 -23
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>;
@@ -165,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>();
@@ -174,7 +170,6 @@ 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;
@@ -197,25 +192,9 @@ const make = Effect.gen(function* () {
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();
+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/"),
},
},
],
});
@@ -0,0 +1,53 @@
---
interface Props {
class?: string;
idPrefix: string;
}
const { class: className, idPrefix } = Astro.props;
---
<svg
class={className}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 295"
aria-hidden="true"
>
<defs>
<linearGradient id={`${idPrefix}0`} x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}6`} x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}8`} x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%">
<stop offset="0%" stop-color="#FFF" stop-opacity=".8" />
<stop offset="100%" stop-color="#FFF" stop-opacity="0" />
</linearGradient>
<linearGradient id={`${idPrefix}c`} x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}e`} x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}i`} x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
</defs>
<g fill="none">
<path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905" />
<path fill={`url(#${idPrefix}6)`} d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903" />
<path fill={`url(#${idPrefix}8)`} d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293" />
<path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z" />
<path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z" />
<path fill={`url(#${idPrefix}c)`} stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)" />
<path fill={`url(#${idPrefix}e)`} stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)" />
<path fill={`url(#${idPrefix}i)`} stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)" />
<path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255" />
</g>
</svg>
+1 -1
View File
@@ -47,7 +47,7 @@ import { RELEASES_URL } from "../lib/releases";
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.36.333.292.2Line truncated
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
+4 -4
View File
@@ -1,5 +1,6 @@
---
import Layout from "../layouts/Layout.astro";
import TuxIcon from "../components/TuxIcon.astro";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -52,7 +53,7 @@ const mobileEndorsementRows = [
>
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="hero-linux-" />
<span id="download-label">Download for macOS</span>
</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
@@ -359,8 +360,7 @@ const mobileEndorsementRows = [
<a id="cta-download-btn" class="btn btn-primary btn-lg" href="https://github.com/pingdotgg/t3code/releases">
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="cta-linux-" />
<span id="cta-download-label">Download for macOS</span>
</a>
<a class="btn btn-ghost btn-lg" href="/download">Windows · Linux · other</a>
@@ -548,7 +548,7 @@ const mobileEndorsementRows = [
:global([data-platform="mac"]) .dl-icon--apple { display: block; }
:global([data-platform="win"]) .dl-icon--windows { display: block; }
:global([data-platform="linux"]) .dl-icon--linux { display: block; }
:global(html:not([data-platform])) .dl-icon--apple { display: block; }
:global(:not([data-platform])) .dl-icon--apple { display: block; }
/* Floating harness marks */
.hero-float {
+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">
@@ -10,7 +10,7 @@ import type {
import {
detectComposerTrigger,
replaceTextRange,
serializeComposerFileLink,
serializeComposerMentionPath,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import { TextInputWrapper } from "expo-paste-input";
@@ -419,7 +419,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
let replacement = "";
if (item.type === "path") {
replacement = `${serializeComposerFileLink(item.path)} `;
replacement = `@${serializeComposerMentionPath(item.path)} `;
} else if (item.type === "skill") {
replacement = `$${item.skill.name} `;
} else if (item.type === "slash-command") {
+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";
-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")) {
-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)
);
}
+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,
}),
};
-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);
-267
View File
@@ -1,267 +0,0 @@
import * as net from "node:net";
import { it as effectIt } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import * as Net from "@t3tools/shared/Net";
import { Effect, Layer } from "effect";
import { describe, expect, it } from "vite-plus/test";
import { ProcessRunner } from "../processRunner.ts";
import * as PortScanner from "./PortScanner.ts";
const { parseLsofOutput, parsePortFromLsofName, parseWindowsListenerOutput, serversEqual } =
PortScanner.__testing;
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)),
);
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 windowsPlatform = Effect.acquireRelease(
Effect.sync(() => {
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
return originalPlatform;
}),
(originalPlatform) =>
Effect.sync(() => {
Object.defineProperty(process, "platform", {
value: originalPlatform,
configurable: true,
});
}),
);
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),
);
describe("parsePortFromLsofName", () => {
it("parses *:port", () => {
expect(parsePortFromLsofName("*:5173")).toBe(5173);
});
it("parses 127.0.0.1:port", () => {
expect(parsePortFromLsofName("127.0.0.1:5173")).toBe(5173);
});
it("parses localhost:port", () => {
expect(parsePortFromLsofName("localhost:5173")).toBe(5173);
});
it("parses [::1]:port", () => {
expect(parsePortFromLsofName("[::1]:5173")).toBe(5173);
});
it("ignores non-local hosts", () => {
expect(parsePortFromLsofName("192.168.1.10:5173")).toBeNull();
});
it("strips trailing description", () => {
expect(parsePortFromLsofName("*:5173 (LISTEN)")).toBe(5173);
});
it("rejects garbage", () => {
expect(parsePortFromLsofName("")).toBeNull();
expect(parsePortFromLsofName("not-a-port")).toBeNull();
expect(parsePortFromLsofName("*:0")).toBeNull();
expect(parsePortFromLsofName("*:99999")).toBeNull();
});
});
describe("parseLsofOutput", () => {
it("parses a typical lsof -F pcn output", () => {
const sample = [
"p12345",
"cnode",
"n*:5173",
"p67890",
"cnext-server",
"n127.0.0.1:3000",
"n127.0.0.1:9229", // node debug port too — same process
"p13579",
"cChrome",
"n192.168.1.10:443", // not local — ignored
].join("\n");
const servers = parseLsofOutput(sample);
expect(servers).toEqual([
{
host: "localhost",
port: 3000,
url: "http://localhost:3000",
processName: "next-server",
pid: 67890,
terminal: null,
},
{
host: "localhost",
port: 5173,
url: "http://localhost:5173",
processName: "node",
pid: 12345,
terminal: null,
},
{
host: "localhost",
port: 9229,
url: "http://localhost:9229",
processName: "next-server",
pid: 67890,
terminal: null,
},
]);
});
it("handles empty input", () => {
expect(parseLsofOutput("")).toEqual([]);
});
it("dedupes by host:port", () => {
const sample = ["p1", "cnode", "n*:5173", "n127.0.0.1:5173"].join("\n");
const servers = parseLsofOutput(sample);
expect(servers).toHaveLength(1);
expect(servers[0]?.port).toBe(5173);
});
it("attributes listeners to a registered terminal process", () => {
const servers = parseLsofOutput(
["p12345", "cnode", "n*:5173"].join("\n"),
new Map([
[
12345,
{
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
},
],
]),
);
expect(servers[0]?.terminal).toEqual({
threadId: "thread-1",
terminalId: "terminal-1",
});
});
});
describe("serversEqual", () => {
const a = {
host: "localhost",
port: 5173,
url: "http://localhost:5173",
processName: "node",
pid: 1,
terminal: null,
};
it("returns true for identical lists", () => {
expect(serversEqual([a], [{ ...a }])).toBe(true);
});
it("returns false for different lengths", () => {
expect(serversEqual([a], [])).toBe(false);
});
it("returns false for different processName", () => {
expect(serversEqual([a], [{ ...a, processName: "other" }])).toBe(false);
});
});
describe("parseWindowsListenerOutput", () => {
it("parses and attributes PowerShell listener records", () => {
const servers = parseWindowsListenerOutput(
"0.0.0.0|5173|12345|node",
new Map([
[
12345,
{
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
},
],
]),
);
expect(servers).toEqual([
{
host: "localhost",
port: 5173,
url: "http://localhost:5173",
processName: "node",
pid: 12345,
terminal: {
threadId: "thread-1",
terminalId: "terminal-1",
},
},
]);
});
});
/**
* Integration tests against a real TCP listener. We force the Windows code
* path (TCP-probe fallback) by monkey-patching `process.platform` for the
* duration of the test so we don't depend 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* () {
yield* windowsPlatform;
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* () {
yield* windowsPlatform;
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);
}),
);
});
-369
View File
@@ -1,369 +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 * 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 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 (process.platform === "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);
/** Exposed for tests. */
export const __testing = {
parseLsofOutput,
parsePortFromLsofName,
parseWindowsListenerOutput,
serversEqual,
};
@@ -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;
}
@@ -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>`;
@@ -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,
@@ -108,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" },
],
}),
],
}),
},
@@ -134,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" },
],
}),
],
}),
},
@@ -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",
},
]);
});
@@ -17,7 +17,6 @@ import type {
ServerProvider,
ServerProviderState,
ModelCapabilities,
ProviderOptionDescriptor,
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
@@ -45,7 +44,7 @@ export interface CodexAppServerProviderSnapshot {
readonly skills: ReadonlyArray<ServerProviderSkill>;
}
const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
none: "None",
minimal: "Minimal",
low: "Low",
@@ -54,12 +53,6 @@ const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
xhigh: "Extra High",
};
const DEFAULT_SERVICE_TIER_ID = "default";
function reasoningEffortLabel(reasoningEffort: string): string {
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
}
function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
if (!account) return undefined;
if (account.type === "apiKey") return "OpenAI API Key";
@@ -100,71 +93,46 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"])
return account.email;
}
export function mapCodexModelCapabilities(
function mapCodexModelCapabilities(
model: CodexSchema.V2ModelListResponse__Model,
): ModelCapabilities {
const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
reasoningEffort === model.defaultReasoningEffort
? {
id: reasoningEffort,
label: reasoningEffortLabel(reasoningEffort),
label: REASONING_EFFORT_LABELS[reasoningEffort],
isDefault: true,
}
: {
id: reasoningEffort,
label: reasoningEffortLabel(reasoningEffort),
label: REASONING_EFFORT_LABELS[reasoningEffort],
},
);
const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
const serviceTiers =
model.serviceTiers && model.serviceTiers.length > 0
? model.serviceTiers
: (model.additionalSpeedTiers ?? []).map((id) => ({
id,
name: id === "fast" ? "Fast" : id,
description: "",
}));
const catalogDefaultServiceTier = serviceTiers.some(
(tier) => tier.id === model.defaultServiceTier,
)
? model.defaultServiceTier
: null;
const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
const optionDescriptors: ProviderOptionDescriptor[] = [];
if (reasoningOptions.length > 0) {
optionDescriptors.push({
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
});
}
if (serviceTiers.length > 0) {
optionDescriptors.push({
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{
id: DEFAULT_SERVICE_TIER_ID,
label: "Standard",
...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
},
...serviceTiers.map((tier) => ({
id: tier.id,
label: tier.name,
...(tier.description ? { description: tier.description } : {}),
...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
})),
],
currentValue: defaultServiceTier,
});
}
const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
return createModelCapabilities({
optionDescriptors,
optionDescriptors: [
...(reasoningOptions.length > 0
? [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select" as const,
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
},
]
: []),
...(supportsFastMode
? [
{
id: "fastMode",
label: "Fast Mode",
type: "boolean" as const,
},
]
: []),
],
});
}
@@ -13,7 +13,6 @@ import {
} from "../CodexDeveloperInstructions.ts";
import {
buildTurnStartParams,
hasConfiguredMcpServer,
isRecoverableThreadResumeError,
openCodexThread,
} from "./CodexSessionRuntime.ts";
@@ -150,31 +149,6 @@ describe("buildTurnStartParams", () => {
});
});
describe("T3 browser developer instructions", () => {
it("prefers the product-native preview tools in both collaboration modes", () => {
for (const instructions of [
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
]) {
assert.match(instructions, /t3-code/);
assert.match(instructions, /preview_status/);
assert.match(instructions, /preview_open/);
assert.match(instructions, /Do not switch to global browser skills/);
}
});
});
describe("hasConfiguredMcpServer", () => {
it("detects inline Codex MCP configuration arguments", () => {
assert.equal(hasConfiguredMcpServer(undefined), false);
assert.equal(hasConfiguredMcpServer(["--model", "gpt-5.4"]), false);
assert.equal(
hasConfiguredMcpServer(["-c", 'mcp_servers.t3-code.url="http://127.0.0.1/mcp"']),
true,
);
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches missing thread errors", () => {
assert.equal(
@@ -62,10 +62,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"does not exist",
];
export function hasConfiguredMcpServer(appServerArgs: ReadonlyArray<string> | undefined): boolean {
return appServerArgs?.some((argument) => argument.includes("mcp_servers.")) === true;
}
export const CodexResumeCursorSchema = Schema.Struct({
threadId: Schema.String,
});
@@ -107,7 +103,6 @@ export interface CodexSessionRuntimeOptions {
readonly model?: string;
readonly serviceTier?: CodexServiceTier | undefined;
readonly resumeCursor?: CodexResumeCursor;
readonly appServerArgs?: ReadonlyArray<string>;
}
export interface CodexSessionRuntimeSendTurnInput {
@@ -725,7 +720,7 @@ export const makeCodexSessionRuntime = (
};
const child = yield* spawner
.spawn(
ChildProcess.make(options.binaryPath, ["app-server", ...(options.appServerArgs ?? [])], {
ChildProcess.make(options.binaryPath, ["app-server"], {
cwd: options.cwd,
env,
forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,
@@ -1260,15 +1255,6 @@ export const makeCodexSessionRuntime = (
sendTurn: (input) =>
Effect.gen(function* () {
const providerThreadId = yield* readProviderThreadId;
if (hasConfiguredMcpServer(options.appServerArgs)) {
yield* client.request("config/mcpServer/reload", undefined).pipe(
Effect.catch((cause) =>
Effect.logWarning("Failed to refresh Codex MCP tool catalog before turn.", {
cause,
}),
),
);
}
const normalizedModel = normalizeCodexModelSlug(
input.model ?? (yield* Ref.get(sessionRef)).model,
);
@@ -13,7 +13,6 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { createModelSelection } from "@t3tools/shared/model";
import {
@@ -233,82 +232,6 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-steer-thread");
// Keep the first prompt in flight long enough for the steer to land.
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_PROMPT_DELAY_MS: "1500" }),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.takeUntil((event) => event.type === "turn.completed"),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const firstTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "run 5 commands",
attachments: [],
})
.pipe(Effect.forkChild);
// Poll until the first prompt is in flight — sendTurn binds the active
// turn id before prompting. The mock agent runs on the real clock, so
// each TestClock.adjust just provides the scheduler hops for its stdio
// responses to land.
yield* Effect.gen(function* () {
for (let attempt = 0; attempt < 200; attempt += 1) {
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
if (session?.activeTurnId !== undefined) {
return;
}
yield* TestClock.adjust("10 millis");
}
throw new Error("Timed out waiting for the first prompt to be in flight.");
});
// Steer: a second sendTurn while the first prompt is still in flight
// continues the same turn.
const steeredTurn = yield* adapter.sendTurn({
threadId,
input: "actually run 15",
attachments: [],
});
const firstTurn = yield* Fiber.join(firstTurnFiber);
assert.equal(String(steeredTurn.turnId), String(firstTurn.turnId));
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 superseded first prompt
// resolving must not settle the merged turn.
assert.equal(turnStartedEvents.length, 1);
assert.equal(String(turnStartedEvents[0]?.turnId), String(firstTurn.turnId));
assert.equal(turnCompletedEvents.length, 1);
assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurn.turnId));
yield* adapter.stopSession(threadId);
}),
);
it.effect("closes the ACP child process when a session stops", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
+105 -160
View File
@@ -42,7 +42,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -133,10 +132,6 @@ interface CursorSessionContext {
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
stopped: boolean;
}
@@ -531,7 +526,6 @@ export function makeCursorAdapter(
? yield* options.resolveSettings
: cursorSettings;
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const acp = yield* makeCursorAcpRuntime({
cursorSettings: effectiveCursorSettings,
...(options?.environment ? { environment: options.environment } : {}),
@@ -539,23 +533,6 @@ export function makeCursorAdapter(
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...(mcpSession
? {
mcpServers: [
{
type: "http" as const,
name: "t3-code",
url: mcpSession.endpoint,
headers: [
{
name: "Authorization",
value: mcpSession.authorizationHeader,
},
],
},
],
}
: {}),
...acpNativeLoggers,
}).pipe(
Effect.provideService(Scope.Scope, sessionScope),
@@ -777,7 +754,6 @@ export function makeCursorAdapter(
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
promptsInFlight: 0,
stopped: false,
};
@@ -906,152 +882,121 @@ export function makeCursorAdapter(
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
// A sendTurn while a prompt is in flight is a steer: the agent folds
// the new prompt into the ongoing work, so the active turn id is
// reused instead of opening a new turn.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; the matching
// decrement is the `ensuring` below.
ctx.promptsInFlight += 1;
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
runtime: ctx.acp,
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
return yield* Effect.gen(function* () {
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
runtime: ctx.acp,
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: { model: resolvedModel },
});
if (steeringTurnId === undefined) {
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: { model: resolvedModel },
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
if (input.input?.trim()) {
promptParts.push({ type: "text", text: input.input.trim() });
}
if (input.attachments && input.attachments.length > 0) {
for (const attachment of input.attachments) {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
}
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
if (input.input?.trim()) {
promptParts.push({ type: "text", text: input.input.trim() });
}
if (input.attachments && input.attachments.length > 0) {
for (const attachment of input.attachments) {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
promptParts.push({
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
}
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
const result = yield* ctx.acp
.prompt({
prompt: promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
if (turnRecord) {
turnRecord.items.push({ prompt: promptParts, result });
} else {
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
model: resolvedModel,
};
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another is
// in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
promptParts.push({
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
});
}
}
return {
threadId: input.threadId,
turnId,
resumeCursor: ctx.session.resumeCursor,
};
}).pipe(
Effect.ensuring(
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
const result = yield* ctx.acp
.prompt({
prompt: promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
model: resolvedModel,
};
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
return {
threadId: input.threadId,
turnId,
resumeCursor: ctx.session.resumeCursor,
};
});
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
+135 -208
View File
@@ -33,7 +33,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -108,10 +107,6 @@ interface GrokSessionContext {
turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
currentModelId: string | undefined;
stopped: boolean;
}
@@ -375,7 +370,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
threadId: input.threadId,
});
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const acp = yield* makeGrokAcpRuntime({
grokSettings,
...(options?.environment ? { environment: options.environment } : {}),
@@ -383,23 +377,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...(mcpSession
? {
mcpServers: [
{
type: "http" as const,
name: "t3-code",
url: mcpSession.endpoint,
headers: [
{
name: "Authorization",
value: mcpSession.authorizationHeader,
},
],
},
],
}
: {}),
...acpNativeLoggers,
}).pipe(
Effect.provideService(Scope.Scope, sessionScope),
@@ -578,7 +555,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
promptsInFlight: 0,
currentModelId: boundModelId,
stopped: false,
};
@@ -688,199 +664,150 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
// A sendTurn while a prompt is in flight is a steer: the agent
// folds the new prompt into the ongoing work, so the active turn
// id is reused instead of opening a new turn.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; decremented on
// preparation failure here, and after the prompt below otherwise.
ctx.promptsInFlight += 1;
return yield* Effect.gen(function* () {
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(
input.attachments ?? [],
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(input.attachments ?? [], (attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
if (steeringTurnId === undefined) {
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
}
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}).pipe(
Effect.tapCause(() =>
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}),
);
return yield* Effect.gen(function* () {
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
ctx.turns = existingTurnRecord
? ctx.turns.map((turn) =>
turn.id === prepared.turnId
? {
...turn,
items: [...turn.items, { prompt: prepared.promptParts, result }],
}
: turn,
)
: [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another
// is in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
}
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
const liveCtx = sessions.get(input.threadId);
if (liveCtx) {
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
}
}),
),
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
ctx.turns = [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
);
});
@@ -395,85 +395,6 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-steer");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run 5 commands",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
// Steer: OpenCode queues the prompt into the busy session, so the
// active turn id is reused instead of opening a new turn.
const steeredTurn = yield* adapter.sendTurn({
threadId,
input: "actually run 15",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
assert.equal(session?.status, "running");
assert.equal(String(session?.activeTurnId), String(turn.turnId));
assert.equal(runtimeMock.state.promptCalls.length, 2);
}),
);
it.effect("keeps the running turn when a steer prompt fails", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-steer-failure");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run 5 commands",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
runtimeMock.state.promptAsyncError = new Error("steer failed");
const error = yield* adapter
.sendTurn({
threadId,
input: "actually run 15",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
})
.pipe(Effect.flip);
// The original turn keeps running — only the steer prompt failed.
assert.equal(error._tag, "ProviderAdapterRequestError");
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
assert.equal(session?.status, "running");
assert.equal(String(session?.activeTurnId), String(turn.turnId));
}),
);
it.effect("passes agent and variant options for the adapter's bound custom instance id", () => {
const instanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
@@ -26,7 +26,6 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import {
ProviderAdapterProcessError,
@@ -1054,22 +1053,6 @@ export function makeOpenCodeAdapter(
directory,
...(server.external && serverPassword ? { serverPassword } : {}),
});
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
if (mcpSession && !server.external) {
yield* runOpenCodeSdk("mcp.add", () =>
client.mcp.add({
name: "t3-code",
config: {
type: "remote",
url: mcpSession.endpoint,
headers: {
Authorization: mcpSession.authorizationHeader,
},
oauth: false,
},
}),
);
}
const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
client.session.create({
title: `T3 Code ${input.threadId}`,
@@ -1168,11 +1151,7 @@ export function makeOpenCodeAdapter(
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const context = ensureSessionContext(sessions, input.threadId);
// A sendTurn while a turn is active is a steer: OpenCode queues the
// prompt into the busy session and the work continues as one turn, so
// the active turn id is reused instead of opening a new turn.
const steeringTurnId = context.activeTurnId;
const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
const modelSelection =
input.modelSelection ??
(context.session.model
@@ -1227,16 +1206,14 @@ export function makeOpenCodeAdapter(
{ clearLastError: true },
);
if (steeringTurnId === undefined) {
yield* emit({
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
type: "turn.started",
payload: {
model: modelSelection?.model ?? context.session.model,
...(variant ? { effort: variant } : {}),
},
});
}
yield* emit({
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
type: "turn.started",
payload: {
model: modelSelection?.model ?? context.session.model,
...(variant ? { effort: variant } : {}),
},
});
yield* runOpenCodeSdk("session.promptAsync", () =>
context.client.session.promptAsync({
@@ -1248,38 +1225,35 @@ export function makeOpenCodeAdapter(
}),
).pipe(
Effect.mapError(toRequestError),
// On failure of a fresh turn: clear active-turn state, flip the
// session back to ready with lastError set, emit turn.aborted, then
// let the typed error propagate. We don't need to rebuild the error
// here — `toRequestError` already produced the right shape. A failed
// steer leaves the still-running original turn untouched.
// On failure: clear active-turn state, flip the session back to ready
// with lastError set, emit turn.aborted, then let the typed error
// propagate. We don't need to rebuild the error here — `toRequestError`
// already produced the right shape.
Effect.tapError((requestError) =>
steeringTurnId !== undefined
? Effect.void
: Effect.gen(function* () {
context.activeTurnId = undefined;
context.activeAgent = undefined;
context.activeVariant = undefined;
yield* updateProviderSession(
context,
{
status: "ready",
model: modelSelection?.model ?? context.session.model,
lastError: requestError.detail,
},
{ clearActiveTurnId: true },
);
yield* emit({
...(yield* buildEventBase({
threadId: input.threadId,
turnId,
})),
type: "turn.aborted",
payload: {
reason: requestError.detail,
},
});
}),
Effect.gen(function* () {
context.activeTurnId = undefined;
context.activeAgent = undefined;
context.activeVariant = undefined;
yield* updateProviderSession(
context,
{
status: "ready",
model: modelSelection?.model ?? context.session.model,
lastError: requestError.detail,
},
{ clearActiveTurnId: true },
);
yield* emit({
...(yield* buildEventBase({
threadId: input.threadId,
turnId,
})),
type: "turn.aborted",
payload: {
reason: requestError.detail,
},
});
}),
),
);
@@ -594,77 +594,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
]);
});
it.effect("does not run provider probes during layer construction", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
const codexInstanceId = ProviderInstanceId.make("codex");
const initialProvider = {
instanceId: codexInstanceId,
driver: codexDriver,
status: "warning",
enabled: true,
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-06-10T00:00:00.000Z",
version: null,
message: "Checking Codex provider status.",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshCalls = yield* Ref.make(0);
const instance = {
instanceId: codexInstanceId,
driverKind: codexDriver,
continuationIdentity: {
driverKind: codexDriver,
continuationKey: "codex:instance:codex",
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: codexDriver,
packageName: null,
}),
getSnapshot: Effect.succeed(initialProvider),
refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(
Effect.andThen(Effect.never),
),
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
});
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-background-refresh-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]);
assert.strictEqual(yield* Ref.get(refreshCalls), 0);
}).pipe(Effect.provide(runtimeServices));
}),
);
it("persists merged provider snapshots for the providers that were refreshed", () => {
const previousProviders = [
{
@@ -1113,17 +1042,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
let providers = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
"error";
attempts += 1
) {
yield* Effect.yieldNow;
providers = yield* registry.getProviders;
}
const providers = yield* registry.getProviders;
const codexPersonal = providers.find(
(provider) => provider.instanceId === "codex_personal",
);
@@ -1153,7 +1072,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// instance and rebuild it so a fresh probe runs with the new binary.
// This test drives the real settings stream → registry reconcile →
// aggregator sync pipeline and asserts that `getProviders` reflects
// the new background probe's outcome.
// the new probe's outcome. If `syncLiveSources` stops awaiting the
// rebuilt instance's refresh (previous bug mode), the aggregator
// keeps the old snapshot and this test fails.
//
it.effect("re-probes when settings change the codex binaryPath", () =>
Effect.gen(function* () {
@@ -1203,18 +1124,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// the two probe runs is `checkedAt` — each probe stamps a
// fresh DateTime, so we capture it and assert it advances
// after the settings mutation.
let initialProviders = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
initialProviders.find((provider) => provider.instanceId === "codex")?.status !==
"error";
attempts += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
initialProviders = yield* registry.getProviders;
}
const initialProviders = yield* registry.getProviders;
const initialCodex = initialProviders.find(
(provider) => provider.instanceId === "codex",
);
@@ -1234,8 +1144,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// envelope changed because `binaryPath` differs → `entryEqual`
// is false). The registry's `Stream.runForEach(
// instanceRegistry.streamChanges, () => syncLiveSources)`
// fires `syncLiveSources`, which subscribes and launches a fresh
// background refresh on the rebuilt instance.
// fires `syncLiveSources`, which subscribes + awaits a fresh
// refresh on the rebuilt instance.
yield* serverSettings.updateSettings({
providers: {
codex: { enabled: true, binaryPath: secondMissing },
@@ -1248,11 +1158,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
for (let attempts = 0; attempts < 60; attempts += 1) {
const providers = yield* registry.getProviders;
const codex = providers.find((provider) => provider.instanceId === "codex");
if (
codex !== undefined &&
codex.status === "error" &&
codex.checkedAt !== initialCheckedAt
) {
if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {
return providers;
}
yield* TestClock.adjust("50 millis");
@@ -492,15 +492,16 @@ export const ProviderRegistryLive = Layer.effect(
* - subscribe to each newly-added or rebuilt instance's
* `streamChanges` (so periodic + enrichment refreshes land in
* `providersRef`);
* - read each newly-added/rebuilt instance's current snapshot after
* subscribing, closing the race with its independently-running
* background startup probe;
* - force-refresh each newly-added/rebuilt instance and feed the
* result directly into `providersRef`, bypassing the PubSub
* attachment race that otherwise drops the initial probe;
* - prune `providersRef` of instances that no longer exist.
*
* Provider refreshes are owned by each managed provider and never run
* on this layer's construction path. Consumers see cached or pending
* snapshots immediately, then receive live probe results through the
* already-attached change stream.
* Initial refreshes are awaited in parallel rather than forked, so
* callers (layer build; `streamChanges` watcher) see fully-probed
* state on return. This matters for layer build in particular:
* consumers reading `getProviders` immediately after layer build
* expect the probe to have already landed.
*
* Per-instance subscription fibers are not tracked explicitly. When
* a rebuilt instance's old child scope closes, its PubSub shuts
@@ -542,31 +543,27 @@ export const ProviderRegistryLive = Layer.effect(
}
// Fork long-lived subscriptions to each new/rebuilt instance's
// change stream before reading its current snapshot. If the
// driver's own initial probe finishes during this sync, either
// the current read or the active subscriber observes the result.
// change stream BEFORE kicking off refreshes — if the driver's
// own initial probe (line 140 in `makeManagedServerProvider`)
// wins the refreshSemaphore race, its PubSub publish must land
// in an active subscriber or the result is dropped.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
yield* Stream.runForEach(source.streamChanges, (provider) =>
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
).pipe(Effect.forkScoped);
}
yield* Effect.yieldNow;
// Snapshot current state without starting a probe. Managed providers
// launch their startup refresh independently, so this closes the
// subscription race without putting external work on the registry
// or HTTP server construction path.
// Force-refresh every new/rebuilt instance in parallel and wait
// for them all to complete. The refresh's result is piped
// directly into `syncProvider`, so `providersRef` is populated
// deterministically by the time this block returns — regardless
// of PubSub subscription timing. Failures are logged and
// swallowed so one bad driver can't wedge the whole registry.
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
yield* correlateSnapshotWithSource(source, provider).pipe(
Effect.flatMap(syncProvider),
);
}).pipe(Effect.ignoreCause({ log: true })),
refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
yield* upsertProviders(unavailableProviders, {
@@ -657,9 +654,9 @@ export const ProviderRegistryLive = Layer.effect(
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
const instanceChanges = yield* instanceRegistry.subscribeChanges;
// Initial sync attaches subscriptions and snapshots current state for
// every instance present at boot. Provider probes are already running in
// their managed background fibers and never block this layer.
// Initial sync: subscribe + kick off refreshes for every instance
// present at boot. Run synchronously so consumers pulling immediately
// after the layer build see the correct aggregator state.
yield* syncLiveSources;
// React to registry mutations — instance added / removed / rebuilt.
// `Stream.fromSubscription` builds a stream over the pre-acquired
@@ -56,8 +56,6 @@ import {
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
const isModelSelection = Schema.is(ModelSelection);
/**
@@ -214,18 +212,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const directory = yield* ProviderSessionDirectory;
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
Effect.tap((credential) =>
credential
? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))
: Effect.void,
),
);
const clearMcpSession = (threadId: ThreadId) =>
McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
);
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Effect.succeed(event).pipe(
@@ -397,20 +383,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
yield* prepareMcpSession(input.binding.threadId, bindingInstanceId);
const resumed = yield* adapter
.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
providerInstanceId: bindingInstanceId,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
})
.pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
providerInstanceId: bindingInstanceId,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
if (resumed.provider !== adapter.provider) {
yield* clearMcpSession(input.binding.threadId);
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
@@ -590,18 +572,14 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
"provider.cwd.effective": effectiveCwd ?? "",
});
const adapter = yield* registry.getByInstance(resolvedInstanceId);
yield* prepareMcpSession(threadId, resolvedInstanceId);
const session = yield* adapter
.startSession({
...input,
providerInstanceId: resolvedInstanceId,
...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
})
.pipe(Effect.onError(() => clearMcpSession(threadId)));
const session = yield* adapter.startSession({
...input,
providerInstanceId: resolvedInstanceId,
...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
if (session.provider !== adapter.provider) {
yield* clearMcpSession(threadId);
return yield* toValidationError(
"ProviderService.startSession",
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
@@ -849,7 +827,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
if (routed.isActive) {
yield* routed.adapter.stopSession(routed.threadId);
}
yield* clearMcpSession(input.threadId);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
@@ -1021,8 +998,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
),
).pipe(Effect.asVoid);
yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
McpProviderSession.clearAllMcpProviderSessions();
const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
yield* Effect.forEach(bindings, (binding) =>
Effect.gen(function* () {
@@ -47,7 +47,6 @@ export interface AcpSessionRuntimeOptions {
readonly version: string;
};
readonly authMethodId: string;
readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
readonly protocolLogging?: {
readonly logIncoming?: boolean;
@@ -401,7 +400,7 @@ const makeAcpSessionRuntime = (
const loadPayload = {
sessionId: options.resumeSessionId,
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
mcpServers: [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const resumed = yield* runLoggedRequest(
"session/load",
@@ -414,7 +413,7 @@ const makeAcpSessionRuntime = (
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
@@ -427,7 +426,7 @@ const makeAcpSessionRuntime = (
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
@@ -129,7 +129,6 @@ describe("makeManagedServerProvider", () => {
Effect.forkChild,
);
yield* Effect.yieldNow;
assert.strictEqual(yield* Ref.get(checkCalls), 1);
yield* Deferred.succeed(releaseCheck, undefined);
@@ -152,7 +152,11 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return {
maintenanceCapabilities: input.maintenanceCapabilities,
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
+168 -28
View File
@@ -20,7 +20,6 @@ import {
type OrchestrationCommand,
type OrchestrationEvent,
ORCHESTRATION_WS_METHODS,
type PreviewEvent,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
@@ -49,7 +48,6 @@ import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -71,6 +69,7 @@ const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
import type { ServerConfigShape } from "./config.ts";
import { deriveServerPaths, ServerConfig } from "./config.ts";
import { makeRoutesLayer } from "./server.ts";
import { resolveAttachmentRelativePath } from "./attachmentPaths.ts";
import {
CheckpointDiffQuery,
type CheckpointDiffQueryShape,
@@ -98,8 +97,6 @@ import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./server
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import {
BrowserTraceCollector,
type BrowserTraceCollectorShape,
@@ -515,7 +512,7 @@ const buildAppUnderTest = (options?: {
Layer.provide(WorkspacePathsLive),
Layer.provide(workspaceEntriesLayer),
),
ProjectFaviconResolverLive.pipe(Layer.provide(WorkspacePathsLive)),
ProjectFaviconResolverLive,
);
const gitWorkflowLayer = GitWorkflowService.layer.pipe(
Layer.provideMerge(vcsDriverRegistryLayer),
@@ -666,29 +663,6 @@ const buildAppUnderTest = (options?: {
...options?.layers?.terminalManager,
}),
),
Layer.provide(
Layer.mergeAll(
Layer.mock(PreviewManager.PreviewManager)({
open: () => Effect.die("PreviewManager not stubbed in this test"),
navigate: () => Effect.die("PreviewManager not stubbed in this test"),
reportStatus: () => Effect.void,
refresh: () => Effect.void,
close: () => Effect.void,
list: () => Effect.succeed({ sessions: [] }),
events: Stream.empty,
subscribeEvents: Effect.flatMap(PubSub.unbounded<PreviewEvent>(), (pubsub) =>
PubSub.subscribe(pubsub),
),
}),
Layer.mock(PortScanner.PortDiscovery)({
scan: () => Effect.succeed([]),
subscribe: () => Effect.void,
retain: Effect.void,
registerTerminalProcesses: () => Effect.void,
unregisterTerminal: () => Effect.void,
}),
),
),
Layer.provide(
Layer.mock(OrchestrationEngineService)({
readEvents: () => Stream.empty,
@@ -1278,6 +1252,61 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves project favicon requests before the dev URL redirect", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const projectDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-router-project-favicon-",
});
yield* fileSystem.writeFileString(
path.join(projectDir, "favicon.svg"),
"<svg>router-project-favicon</svg>",
);
yield* buildAppUnderTest({
config: { devUrl: new URL("http://127.0.0.1:5173") },
});
const response = yield* HttpClient.get(
`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`,
{
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
},
},
);
assert.equal(response.status, 200);
assert.equal(yield* response.text, "<svg>router-project-favicon</svg>");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves the fallback project favicon when no icon exists", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const projectDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-router-project-favicon-fallback-",
});
yield* buildAppUnderTest({
config: { devUrl: new URL("http://127.0.0.1:5173") },
});
const response = yield* HttpClient.get(
`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`,
{
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
},
},
);
assert.equal(response.status, 200);
assert.include(yield* response.text, 'data-fallback="project-favicon"');
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves the public environment descriptor without requiring auth", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -3139,10 +3168,28 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
});
const wsTicketBody = (yield* wsTicketResponse.json) as { readonly ticket: string };
const faviconResponse = yield* HttpClient.get("/api/project-favicon?cwd=/tmp", {
headers: {
authorization: `Bearer ${tokenBody.access_token ?? ""}`,
},
});
const faviconBody = (yield* faviconResponse.json) as {
readonly _tag: string;
readonly code: string;
readonly requiredScope: string;
readonly traceId: string;
};
assert.equal(overbroadPairingResponse.status, 403);
assert.equal(overbroadPairingBody.requiredScope, "orchestration:read");
assert.equal(pairingResponse.status, 200);
assert.equal(wsTicketResponse.status, 200);
assert.equal(faviconResponse.status, 403);
assert.equal(faviconBody._tag, "EnvironmentScopeRequiredError");
assert.equal(faviconBody.code, "insufficient_scope");
assert.equal(faviconBody.requiredScope, "orchestration:read");
assert.equal(typeof faviconBody.traceId, "string");
const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`;
const rpcError = yield* Effect.flip(
Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))),
@@ -3686,6 +3733,29 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"does not accept session tokens via query parameters on authenticated HTTP routes",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const projectDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-router-project-favicon-query-token-",
});
yield* buildAppUnderTest();
const { cookie } = yield* bootstrapBrowserSession();
assert.isDefined(cookie);
const sessionToken = extractSessionTokenFromSetCookie(cookie ?? "");
const response = yield* HttpClient.get(
`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}&token=${encodeURIComponent(sessionToken)}`,
);
assert.equal(response.status, 401);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("accepts websocket rpc handshake with a bootstrapped browser session cookie", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -3756,6 +3826,60 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves attachment files from state dir", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId = "thread-11111111-1111-4111-8111-111111111111";
const config = yield* buildAppUnderTest();
const attachmentPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath: `${attachmentId}.bin`,
});
assert.isNotNull(attachmentPath, "Attachment path should be resolvable");
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true });
yield* fileSystem.writeFileString(attachmentPath, "attachment-ok");
const response = yield* HttpClient.get(`/attachments/${attachmentId}`, {
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
},
});
assert.equal(response.status, 200);
assert.equal(yield* response.text, "attachment-ok");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves attachment files for URL-encoded paths", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* buildAppUnderTest();
const attachmentPath = resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath: "thread%20folder/message%20folder/file%20name.png",
});
assert.isNotNull(attachmentPath, "Attachment path should be resolvable");
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true });
yield* fileSystem.writeFileString(attachmentPath, "attachment-encoded-ok");
const response = yield* HttpClient.get(
"/attachments/thread%20folder/message%20folder/file%20name.png",
{
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
},
},
);
assert.equal(response.status, 200);
assert.equal(yield* response.text, "attachment-encoded-ok");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("proxies browser OTLP trace exports through the server", () =>
Effect.gen(function* () {
const upstreamRequests: Array<{
@@ -4045,6 +4169,22 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("returns 404 for missing attachment id lookups", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const response = yield* HttpClient.get(
"/attachments/missing-11111111-1111-4111-8111-111111111111",
{
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
},
},
);
assert.equal(response.status, 404);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc server.upsertKeybinding", () =>
Effect.gen(function* () {
const rule: KeybindingRule = {
+16 -44
View File
@@ -6,8 +6,9 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { ServerConfig } from "./config.ts";
import {
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
assetRouteLayer,
projectFaviconRouteLayer,
serverEnvironmentHttpApiLayer,
staticAndDevRouteLayer,
browserApiCorsLayer,
@@ -34,11 +35,6 @@ import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as ProcessRunner from "./processRunner.ts";
import * as GitManager from "./git/GitManager.ts";
import { KeybindingsLive } from "./keybindings.ts";
import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup.ts";
@@ -91,12 +87,6 @@ import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
// already closes the websocket gracefully. Do not add an artificial drain before
// those finalizers get a chance to run.
const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
if (typeof Bun !== "undefined") {
@@ -126,7 +116,6 @@ const HttpServerLive = Layer.unwrap(
return BunHttpServer.layer({
port: config.port,
...(config.host ? { hostname: config.host } : {}),
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
});
} else {
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
@@ -136,7 +125,6 @@ const HttpServerLive = Layer.unwrap(
return NodeHttpServer.layer(NodeHttp.createServer, {
host: config.host,
port: config.port,
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
});
}
}),
@@ -235,17 +223,7 @@ const CheckpointingLayerLive = Layer.empty.pipe(
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
);
const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
const TerminalLayerLive = TerminalManagerLive.pipe(
Layer.provide(PtyAdapterLive),
Layer.provide(PortScannerLayerLive),
);
const PreviewLayerLive = Layer.empty.pipe(
Layer.provideMerge(PreviewManager.layer),
Layer.provideMerge(PortScannerLayerLive),
);
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
@@ -263,10 +241,6 @@ const WorkspaceLayerLive = Layer.mergeAll(
WorkspaceFileSystemLayerLive,
);
const ProjectFaviconResolverLayerLive = ProjectFaviconResolverLive.pipe(
Layer.provide(WorkspacePathsLive),
);
const AuthLayerLive = EnvironmentAuth.layer.pipe(
Layer.provideMerge(PersistenceLayerLive),
Layer.provide(ServerSecretStore.layer),
@@ -292,7 +266,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(VcsLayerLive),
Layer.provideMerge(ProviderRuntimeLayerLive),
Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
Layer.provideMerge(TerminalLayerLive),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(KeybindingsLive),
Layer.provideMerge(ProviderRegistryLive),
@@ -316,7 +290,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(OpenCodeRuntimeLive),
Layer.provideMerge(ServerSettingsLive),
Layer.provideMerge(WorkspaceLayerLive),
Layer.provideMerge(ProjectFaviconResolverLayerLive),
Layer.provideMerge(ProjectFaviconResolverLive),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerEnvironmentLive),
Layer.provideMerge(AuthLayerLive),
@@ -345,20 +319,18 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
);
export const makeRoutesLayer = Layer.mergeAll(
Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(authHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
),
otlpTracesProxyRouteLayer,
assetRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(authHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
),
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
).pipe(Layer.provide(browserApiCorsLayer));
export const makeServerLayer = Layer.unwrap(
Loaded 100 of 328 files, more files were not shown because too many files have changed in this diff. Show more