Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b74682d59 | ||
|
|
0beb4f5e15 | ||
|
|
792e19fc26 | ||
|
|
4e10a99aa9 | ||
|
|
1d1d67c4bd | ||
|
|
94eedd7c77 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.21",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -18,8 +18,7 @@
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"electron": "40.9.3",
|
||||
"electron-updater": "^6.6.2",
|
||||
"jsonc-parser": "^3.3.1"
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
|
||||
@@ -52,7 +52,6 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
@@ -64,7 +63,6 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
themePreference: { mode: "system" },
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
|
||||
@@ -30,7 +30,6 @@ import type {
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
DesktopWindowThemeColors,
|
||||
} from "@t3tools/contracts";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
|
||||
@@ -85,21 +84,12 @@ import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runti
|
||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
import {
|
||||
discoverEditorColorThemes,
|
||||
getEditorThemePreferences,
|
||||
loadEditorColorTheme,
|
||||
} from "./vscodeThemeDiscovery.ts";
|
||||
|
||||
syncShellEnvironment();
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
|
||||
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
|
||||
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
|
||||
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
@@ -128,7 +118,6 @@ const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
|
||||
const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
|
||||
const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
let windowThemeColors: DesktopWindowThemeColors | null = null;
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
// Dev-only SSH launcher override. Set this to an absolute path on the SSH host
|
||||
@@ -509,20 +498,6 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function getSafeWindowThemeColors(rawInput: unknown): DesktopWindowThemeColors | null {
|
||||
if (typeof rawInput !== "object" || rawInput === null || Array.isArray(rawInput)) return null;
|
||||
const input = rawInput as Record<string, unknown>;
|
||||
if (typeof input.backgroundColor !== "string" || input.backgroundColor.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
backgroundColor: input.backgroundColor,
|
||||
titleBarColor: typeof input.titleBarColor === "string" ? input.titleBarColor : undefined,
|
||||
titleBarSymbolColor:
|
||||
typeof input.titleBarSymbolColor === "string" ? input.titleBarSymbolColor : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
@@ -1843,26 +1818,6 @@ function registerIpcHandlers(): void {
|
||||
nativeTheme.themeSource = theme;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(DISCOVER_COLOR_THEMES_CHANNEL);
|
||||
ipcMain.handle(DISCOVER_COLOR_THEMES_CHANNEL, async () => discoverEditorColorThemes());
|
||||
|
||||
ipcMain.removeHandler(LOAD_COLOR_THEME_CHANNEL);
|
||||
ipcMain.handle(LOAD_COLOR_THEME_CHANNEL, async (_event, rawThemeId: unknown) => {
|
||||
if (typeof rawThemeId !== "string") return null;
|
||||
return loadEditorColorTheme(rawThemeId);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_EDITOR_THEME_PREFERENCES_CHANNEL);
|
||||
ipcMain.handle(GET_EDITOR_THEME_PREFERENCES_CHANNEL, async () => getEditorThemePreferences());
|
||||
|
||||
ipcMain.removeHandler(SET_WINDOW_THEME_COLORS_CHANNEL);
|
||||
ipcMain.handle(SET_WINDOW_THEME_COLORS_CHANNEL, async (_event, rawInput: unknown) => {
|
||||
const input = getSafeWindowThemeColors(rawInput);
|
||||
if (!input) return;
|
||||
windowThemeColors = input;
|
||||
syncAllWindowAppearance();
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
@@ -2034,9 +1989,7 @@ function getIconOption(): { icon: string } | Record<string, never> {
|
||||
}
|
||||
|
||||
function getInitialWindowBackgroundColor(): string {
|
||||
return (
|
||||
windowThemeColors?.backgroundColor ?? (nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff")
|
||||
);
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
@@ -2050,13 +2003,11 @@ function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: windowThemeColors?.titleBarColor ?? TITLEBAR_COLOR,
|
||||
color: TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor:
|
||||
windowThemeColors?.titleBarSymbolColor ??
|
||||
(nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR),
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,10 +4,6 @@ import type { DesktopBridge } from "@t3tools/contracts";
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
|
||||
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
|
||||
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
|
||||
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
@@ -118,11 +114,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
||||
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
discoverColorThemes: () => ipcRenderer.invoke(DISCOVER_COLOR_THEMES_CHANNEL),
|
||||
loadColorTheme: (themeId) => ipcRenderer.invoke(LOAD_COLOR_THEME_CHANNEL, themeId),
|
||||
getEditorThemePreferences: () => ipcRenderer.invoke(GET_EDITOR_THEME_PREFERENCES_CHANNEL),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
setWindowThemeColors: (input) => ipcRenderer.invoke(SET_WINDOW_THEME_COLORS_CHANNEL, input),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
discoverEditorColorThemes,
|
||||
getEditorThemePreferences,
|
||||
loadEditorColorTheme,
|
||||
resolveEditorRoots,
|
||||
} from "./vscodeThemeDiscovery.ts";
|
||||
|
||||
let tempDir = "";
|
||||
|
||||
function writeJson(filePath: string, value: unknown) {
|
||||
FS.mkdirSync(Path.dirname(filePath), { recursive: true });
|
||||
FS.writeFileSync(filePath, JSON.stringify(value, null, 2));
|
||||
}
|
||||
|
||||
describe("vscodeThemeDiscovery", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-vscode-themes-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
FS.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("discovers contributed themes and ignores unsafe paths", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
publisher: "GitHub",
|
||||
displayName: "GitHub Theme",
|
||||
contributes: {
|
||||
themes: [
|
||||
{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" },
|
||||
{ label: "Escaped", uiTheme: "vs", path: "../escaped.json" },
|
||||
],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
colors: { "editor.background": "#0d1117" },
|
||||
});
|
||||
|
||||
expect(discoverEditorColorThemes(roots)).toMatchObject([
|
||||
{
|
||||
source: "vscode",
|
||||
label: "GitHub Dark Default",
|
||||
kind: "dark",
|
||||
publisher: "GitHub",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads JSONC settings overrides into the resolved app theme", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
contributes: {
|
||||
themes: [{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" }],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
semanticHighlighting: true,
|
||||
colors: {
|
||||
"editor.background": "#0d1117",
|
||||
"editor.foreground": "#e6edf3",
|
||||
},
|
||||
tokenColors: [],
|
||||
});
|
||||
FS.mkdirSync(Path.dirname(vscodeRoot.settingsPath), { recursive: true });
|
||||
FS.writeFileSync(
|
||||
vscodeRoot.settingsPath,
|
||||
`{
|
||||
"workbench.colorTheme": "GitHub Dark Default",
|
||||
"workbench.colorCustomizations": {
|
||||
"button.background": "#238636",
|
||||
"[GitHub Dark Default]": {
|
||||
"sideBar.background": "#010409"
|
||||
}
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
expect(preferences[0]?.colorTheme).toBe("GitHub Dark Default");
|
||||
|
||||
const themeId = discoverEditorColorThemes(roots)[0]?.id;
|
||||
expect(themeId).toBeTruthy();
|
||||
const resolved = themeId ? loadEditorColorTheme(themeId, roots) : null;
|
||||
|
||||
expect(resolved?.colors["button.background"]).toBe("#238636");
|
||||
expect(resolved?.colors["sideBar.background"]).toBe("#010409");
|
||||
expect(resolved?.appVariables["--primary"]).toBe("#238636");
|
||||
});
|
||||
});
|
||||
@@ -1,284 +0,0 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { parse as parseJsonc } from "jsonc-parser";
|
||||
import type {
|
||||
DiscoveredColorTheme,
|
||||
EditorThemePreference,
|
||||
EditorThemeSource,
|
||||
ResolvedColorTheme,
|
||||
ThemeKind,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
mapVscodeColorsToAppVariables,
|
||||
normalizeCssColor,
|
||||
normalizeThemeColors,
|
||||
} from "@t3tools/shared/themeMapping";
|
||||
|
||||
interface EditorRoot {
|
||||
readonly source: EditorThemeSource;
|
||||
readonly extensionsPath: string;
|
||||
readonly settingsPath: string;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function kindFromUiTheme(uiTheme: unknown): ThemeKind {
|
||||
if (uiTheme === "hc-light") return "high-contrast-light";
|
||||
if (uiTheme === "hc-black") return "high-contrast-dark";
|
||||
if (uiTheme === "vs") return "light";
|
||||
return "dark";
|
||||
}
|
||||
|
||||
function readJsonOrJsoncFile(filePath: string): unknown | null {
|
||||
try {
|
||||
return parseJsonc(FS.readFileSync(filePath, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeResolveChild(root: string, relativePath: string): string | null {
|
||||
const resolved = Path.resolve(root, relativePath);
|
||||
const normalizedRoot = Path.resolve(root);
|
||||
if (resolved === normalizedRoot || resolved.startsWith(`${normalizedRoot}${Path.sep}`)) {
|
||||
return resolved;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveEditorRoots(input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly homedir: string;
|
||||
readonly appData?: string;
|
||||
}): readonly EditorRoot[] {
|
||||
const home = input.homedir;
|
||||
if (input.platform === "win32") {
|
||||
const appData = input.appData ?? Path.join(home, "AppData", "Roaming");
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(appData, "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (input.platform === "darwin") {
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code - Insiders",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Cursor",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function resolveDefaultEditorRoots() {
|
||||
const input: { platform: NodeJS.Platform; homedir: string; appData?: string } = {
|
||||
platform: process.platform,
|
||||
homedir: OS.homedir(),
|
||||
};
|
||||
if (process.env.APPDATA) input.appData = process.env.APPDATA;
|
||||
return resolveEditorRoots(input);
|
||||
}
|
||||
|
||||
function readEditorSettings(settingsPath: string): Record<string, unknown> {
|
||||
const parsed = readJsonOrJsoncFile(settingsPath);
|
||||
return isObject(parsed) ? parsed : {};
|
||||
}
|
||||
|
||||
export function getEditorThemePreferences(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly EditorThemePreference[] {
|
||||
return roots.map((root) => {
|
||||
const settings = readEditorSettings(root.settingsPath);
|
||||
const customizations = settings["workbench.colorCustomizations"];
|
||||
return {
|
||||
source: root.source,
|
||||
colorTheme:
|
||||
typeof settings["workbench.colorTheme"] === "string"
|
||||
? settings["workbench.colorTheme"]
|
||||
: null,
|
||||
preferredLightColorTheme:
|
||||
typeof settings["workbench.preferredLightColorTheme"] === "string"
|
||||
? settings["workbench.preferredLightColorTheme"]
|
||||
: null,
|
||||
preferredDarkColorTheme:
|
||||
typeof settings["workbench.preferredDarkColorTheme"] === "string"
|
||||
? settings["workbench.preferredDarkColorTheme"]
|
||||
: null,
|
||||
autoDetectColorScheme: settings["window.autoDetectColorScheme"] === true,
|
||||
workbenchColorCustomizations: isObject(customizations) ? customizations : {},
|
||||
editorTokenColorCustomizations: settings["editor.tokenColorCustomizations"],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function discoverEditorColorThemes(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly DiscoveredColorTheme[] {
|
||||
const themes: DiscoveredColorTheme[] = [];
|
||||
|
||||
for (const root of roots) {
|
||||
if (!FS.existsSync(root.extensionsPath)) continue;
|
||||
|
||||
for (const entry of FS.readdirSync(root.extensionsPath, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
|
||||
const extensionDir = Path.join(root.extensionsPath, entry.name);
|
||||
const packagePath = Path.join(extensionDir, "package.json");
|
||||
const packageJson = readJsonOrJsoncFile(packagePath);
|
||||
if (!isObject(packageJson)) continue;
|
||||
|
||||
const contributes = packageJson.contributes;
|
||||
const contributedThemes = isObject(contributes) ? contributes.themes : null;
|
||||
if (!Array.isArray(contributedThemes)) continue;
|
||||
|
||||
for (const theme of contributedThemes) {
|
||||
if (!isObject(theme) || typeof theme.label !== "string" || typeof theme.path !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const themePath = safeResolveChild(extensionDir, theme.path);
|
||||
if (!themePath || !FS.existsSync(themePath)) continue;
|
||||
|
||||
themes.push({
|
||||
id: `${root.source}:${entry.name}:${theme.label}`,
|
||||
source: root.source,
|
||||
extensionId: entry.name,
|
||||
extensionDisplayName:
|
||||
typeof packageJson.displayName === "string" ? packageJson.displayName : undefined,
|
||||
label: theme.label,
|
||||
kind: kindFromUiTheme(theme.uiTheme),
|
||||
themePath,
|
||||
packagePath,
|
||||
publisher: typeof packageJson.publisher === "string" ? packageJson.publisher : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return themes.toSorted((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
function mergeWorkbenchOverrides(input: {
|
||||
readonly themeLabel: string;
|
||||
readonly themeColors: Record<string, string>;
|
||||
readonly customizations: Record<string, unknown>;
|
||||
}) {
|
||||
const next = { ...input.themeColors };
|
||||
|
||||
for (const [key, rawValue] of Object.entries(input.customizations)) {
|
||||
if (key.startsWith("[") && key.endsWith("]")) continue;
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
|
||||
const scoped = input.customizations[`[${input.themeLabel}]`];
|
||||
if (isObject(scoped)) {
|
||||
for (const [key, rawValue] of Object.entries(scoped)) {
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function loadEditorColorTheme(
|
||||
themeId: string,
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): ResolvedColorTheme | null {
|
||||
const themes = discoverEditorColorThemes(roots);
|
||||
const theme = themes.find((entry) => entry.id === themeId);
|
||||
if (!theme) return null;
|
||||
|
||||
const rawTheme = readJsonOrJsoncFile(theme.themePath);
|
||||
if (!isObject(rawTheme)) return null;
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
const preference = preferences.find((entry) => entry.source === theme.source);
|
||||
const colors = mergeWorkbenchOverrides({
|
||||
themeLabel: theme.label,
|
||||
themeColors: normalizeThemeColors(rawTheme.colors),
|
||||
customizations: preference?.workbenchColorCustomizations ?? {},
|
||||
});
|
||||
|
||||
return {
|
||||
id: theme.id,
|
||||
label: theme.label,
|
||||
source: theme.source,
|
||||
kind: theme.kind,
|
||||
colors,
|
||||
tokenColors: rawTheme.tokenColors ?? [],
|
||||
semanticHighlighting:
|
||||
typeof rawTheme.semanticHighlighting === "boolean"
|
||||
? rawTheme.semanticHighlighting
|
||||
: undefined,
|
||||
semanticTokenColors: rawTheme.semanticTokenColors,
|
||||
appVariables: mapVscodeColorsToAppVariables({ kind: theme.kind, colors }),
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.21",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -19,6 +19,7 @@
|
||||
"build": "node scripts/cli.ts build",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
@@ -29,7 +30,7 @@
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
|
||||
+5
-16
@@ -5,24 +5,13 @@ import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { cli } from "./cli.ts";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { authCommand } from "./cli/auth.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) => runServerCommand(flags)),
|
||||
Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
@@ -86,13 +86,10 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
@@ -166,13 +163,10 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
@@ -214,13 +208,10 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
|
||||
@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { deriveServerPaths } from "../config.ts";
|
||||
import { resolveServerConfig } from "./config.ts";
|
||||
import { deriveServerPaths } from "./config.ts";
|
||||
import { resolveServerConfig } from "./cli.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
@@ -15,8 +15,9 @@ import * as CliError from "effect/unstable/cli/CliError";
|
||||
import * as TestConsole from "effect/testing/TestConsole";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./bin.ts";
|
||||
import { cli } from "./cli.ts";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
@@ -148,7 +149,7 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Ef
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
@@ -315,8 +316,8 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const addedProject = readModel.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,243 +0,0 @@
|
||||
import { AuthSessionId } from "@t3tools/contracts";
|
||||
import { Console, Effect, Layer, Option, References } from "effect";
|
||||
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
|
||||
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
|
||||
import {
|
||||
formatIssuedPairingCredential,
|
||||
formatIssuedSession,
|
||||
formatPairingCredentialList,
|
||||
formatSessionList,
|
||||
} from "../cliAuthFormat.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import {
|
||||
authLocationFlags,
|
||||
type CliAuthLocationFlags,
|
||||
DurationFromString,
|
||||
resolveCliAuthConfig,
|
||||
} from "./config.ts";
|
||||
|
||||
const runWithAuthControlPlane = <A, E>(
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
|
||||
options?: {
|
||||
readonly quietLogs?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
|
||||
return yield* Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
return yield* run(authControlPlane);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const ttlFlag = Flag.string("ttl").pipe(
|
||||
Flag.withSchema(DurationFromString),
|
||||
Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const jsonFlag = Flag.boolean("json").pipe(
|
||||
Flag.withDescription("Emit JSON instead of human-readable output."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
|
||||
Flag.withDescription("Role for the issued bearer session."),
|
||||
Flag.withDefault("owner"),
|
||||
);
|
||||
|
||||
const labelFlag = Flag.string("label").pipe(
|
||||
Flag.withDescription("Optional human-readable label."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const subjectFlag = Flag.string("subject").pipe(
|
||||
Flag.withDescription("Optional session subject."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const baseUrlFlag = Flag.string("base-url").pipe(
|
||||
Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const tokenOnlyFlag = Flag.boolean("token-only").pipe(
|
||||
Flag.withDescription("Print only the issued bearer token."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const pairingCreateCommand = Command.make("create", {
|
||||
...authLocationFlags,
|
||||
ttl: ttlFlag,
|
||||
label: labelFlag,
|
||||
baseUrl: baseUrlFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Issue a new client pairing token."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* authControlPlane.createPairingLink({
|
||||
role: "client",
|
||||
subject: "one-time-token",
|
||||
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
|
||||
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
|
||||
});
|
||||
const output = formatIssuedPairingCredential(issued, {
|
||||
json: flags.json,
|
||||
...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingListCommand = Command.make("list", {
|
||||
...authLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List active client pairing tokens without revealing their secrets."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
|
||||
yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingRevokeCommand = Command.make("revoke", {
|
||||
...authLocationFlags,
|
||||
id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke an active client pairing token."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(flags, (authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const revoked = yield* authControlPlane.revokePairingLink(flags.id);
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked pairing credential ${flags.id}.\n`
|
||||
: `No active pairing credential found for ${flags.id}.\n`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingCommand = Command.make("pairing").pipe(
|
||||
Command.withDescription("Manage one-time client pairing tokens."),
|
||||
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
|
||||
);
|
||||
|
||||
const sessionIssueCommand = Command.make("issue", {
|
||||
...authLocationFlags,
|
||||
ttl: ttlFlag,
|
||||
role: sessionRoleFlag,
|
||||
label: labelFlag,
|
||||
subject: subjectFlag,
|
||||
tokenOnly: tokenOnlyFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Issue a bearer session token for headless or remote clients."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* authControlPlane.issueSession({
|
||||
role: flags.role,
|
||||
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
|
||||
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
|
||||
...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
|
||||
});
|
||||
yield* Console.log(
|
||||
formatIssuedSession(issued, {
|
||||
json: flags.json,
|
||||
tokenOnly: flags.tokenOnly,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json || flags.tokenOnly,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionListCommand = Command.make("list", {
|
||||
...authLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List active sessions without revealing bearer tokens."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* authControlPlane.listSessions();
|
||||
yield* Console.log(formatSessionList(sessions, { json: flags.json }));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionRevokeCommand = Command.make("revoke", {
|
||||
...authLocationFlags,
|
||||
sessionId: Argument.string("session-id").pipe(
|
||||
Argument.withDescription("Session id to revoke."),
|
||||
Argument.withSchema(AuthSessionId),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke an active session."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(flags, (authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked session ${flags.sessionId}.\n`
|
||||
: `No active session found for ${flags.sessionId}.\n`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionCommand = Command.make("session").pipe(
|
||||
Command.withDescription("Manage bearer sessions."),
|
||||
Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
|
||||
);
|
||||
|
||||
export const authCommand = Command.make("auth").pipe(
|
||||
Command.withDescription("Manage the local auth control plane for headless deployments."),
|
||||
Command.withSubcommands([pairingCommand, sessionCommand]),
|
||||
);
|
||||
@@ -1,490 +0,0 @@
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import {
|
||||
Config,
|
||||
Duration,
|
||||
Effect,
|
||||
FileSystem,
|
||||
LogLevel,
|
||||
Option,
|
||||
Path,
|
||||
Schema,
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
} from "effect";
|
||||
import { Argument, Flag } from "effect/unstable/cli";
|
||||
|
||||
import { readBootstrapEnvelope } from "../bootstrap.ts";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
ensureServerDirectories,
|
||||
resolveStaticDir,
|
||||
RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
type StartupPresentation,
|
||||
} from "../config.ts";
|
||||
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
|
||||
|
||||
export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(RuntimeMode),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
desktopBootstrapToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optional(PortSchema),
|
||||
otlpTracesUrl: Schema.optional(Schema.String),
|
||||
otlpMetricsUrl: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const baseDirFlag = Flag.string("base-dir").pipe(
|
||||
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
export const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
export const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
|
||||
Flag.withDescription(
|
||||
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
export const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const EnvServerConfig = Config.all({
|
||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
||||
traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
|
||||
traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
|
||||
traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
|
||||
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
|
||||
Config.withDefault(10_000),
|
||||
),
|
||||
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
|
||||
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
export interface CliServerFlags {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly cwd: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
readonly tailscaleServeEnabled: Option.Option<boolean>;
|
||||
readonly tailscaleServePort: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface CliAuthLocationFlags {
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly devUrl?: Option.Option<URL>;
|
||||
}
|
||||
|
||||
export const sharedServerLocationFlags = {
|
||||
baseDir: baseDirFlag,
|
||||
devUrl: devUrlFlag,
|
||||
} as const;
|
||||
|
||||
export const projectLocationFlags = {
|
||||
baseDir: baseDirFlag,
|
||||
} as const;
|
||||
|
||||
export const sharedServerCommandFlags = {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
baseDir: baseDirFlag,
|
||||
cwd: Argument.string("cwd").pipe(
|
||||
Argument.withDescription(
|
||||
"Working directory for provider sessions (defaults to the current directory).",
|
||||
),
|
||||
Argument.optional,
|
||||
),
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
tailscaleServeEnabled: tailscaleServeFlag,
|
||||
tailscaleServePort: tailscaleServePortFlag,
|
||||
} as const;
|
||||
|
||||
export const authLocationFlags = sharedServerLocationFlags;
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
|
||||
}
|
||||
|
||||
const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
|
||||
return parsePersistedServerObservabilitySettings(raw);
|
||||
});
|
||||
|
||||
export const resolveServerConfig = (
|
||||
flags: CliServerFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
options?: {
|
||||
readonly startupPresentation?: StartupPresentation;
|
||||
readonly forceAutoBootstrapProjectFromCwd?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const env = yield* EnvServerConfig;
|
||||
const normalizedFlags = {
|
||||
mode: flags.mode ?? Option.none(),
|
||||
port: flags.port ?? Option.none(),
|
||||
host: flags.host ?? Option.none(),
|
||||
baseDir: flags.baseDir ?? Option.none(),
|
||||
cwd: flags.cwd ?? Option.none(),
|
||||
devUrl: flags.devUrl ?? Option.none(),
|
||||
noBrowser: flags.noBrowser ?? Option.none(),
|
||||
bootstrapFd: flags.bootstrapFd ?? Option.none(),
|
||||
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
|
||||
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
|
||||
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
|
||||
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
|
||||
} satisfies CliServerFlags;
|
||||
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.fromUndefinedOr(bootstrap?.mode),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.fromUndefinedOr(bootstrap?.port),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.fromUndefinedOr(bootstrap?.devUrl),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.fromUndefinedOr(bootstrap?.t3Home),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
|
||||
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
|
||||
yield* fs.makeDirectory(cwd, { recursive: true });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
yield* ensureServerDirectories(derivedPaths);
|
||||
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
|
||||
derivedPaths.settingsPath,
|
||||
);
|
||||
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
|
||||
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
|
||||
const startupPresentation = options?.startupPresentation ?? "browser";
|
||||
const isHeadlessStartup = startupPresentation === "headless";
|
||||
const noBrowser = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
isHeadlessStartup ? Option.some(true) : Option.none(),
|
||||
normalizedFlags.noBrowser,
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.fromUndefinedOr(bootstrap?.noBrowser),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
);
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
|
||||
isHeadlessStartup ? Option.some(false) : Option.none(),
|
||||
normalizedFlags.autoBootstrapProjectFromCwd,
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
() => mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.logWebSocketEvents,
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
);
|
||||
const tailscaleServeEnabled = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.tailscaleServeEnabled,
|
||||
Option.fromUndefinedOr(env.tailscaleServeEnabled),
|
||||
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
|
||||
),
|
||||
() => false,
|
||||
);
|
||||
const tailscaleServePort = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.tailscaleServePort,
|
||||
Option.fromUndefinedOr(env.tailscaleServePort),
|
||||
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
|
||||
),
|
||||
() => 443,
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.fromUndefinedOr(bootstrap?.host),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
logLevel,
|
||||
traceMinLevel: env.traceMinLevel,
|
||||
traceTimingEnabled: env.traceTimingEnabled,
|
||||
traceBatchWindowMs: env.traceBatchWindowMs,
|
||||
traceMaxBytes: env.traceMaxBytes,
|
||||
traceMaxFiles: env.traceMaxFiles,
|
||||
otlpTracesUrl:
|
||||
env.otlpTracesUrl ??
|
||||
bootstrap?.otlpTracesUrl ??
|
||||
persistedObservabilitySettings.otlpTracesUrl,
|
||||
otlpMetricsUrl:
|
||||
env.otlpMetricsUrl ??
|
||||
bootstrap?.otlpMetricsUrl ??
|
||||
persistedObservabilitySettings.otlpMetricsUrl,
|
||||
otlpExportIntervalMs: env.otlpExportIntervalMs,
|
||||
otlpServiceName: env.otlpServiceName,
|
||||
mode,
|
||||
port,
|
||||
cwd,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
serverTracePath,
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
tailscaleServePort,
|
||||
};
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
export const resolveCliAuthConfig = (
|
||||
flags: CliAuthLocationFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
) =>
|
||||
resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: flags.baseDir,
|
||||
cwd: Option.none(),
|
||||
devUrl: flags.devUrl ?? Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
cliLogLevel,
|
||||
);
|
||||
|
||||
const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
|
||||
|
||||
const parseDurationInput = (value: string): Duration.Duration | null => {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
const shorthand = DurationShorthandPattern.exec(trimmed);
|
||||
const normalizedInput = shorthand?.groups
|
||||
? (() => {
|
||||
const amountText = shorthand.groups.value;
|
||||
const unitText = shorthand.groups.unit;
|
||||
if (typeof amountText !== "string" || typeof unitText !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const amount = Number.parseInt(amountText, 10);
|
||||
if (!Number.isFinite(amount)) return null;
|
||||
|
||||
switch (unitText.toLowerCase()) {
|
||||
case "ms":
|
||||
return `${amount} millis`;
|
||||
case "s":
|
||||
return `${amount} seconds`;
|
||||
case "m":
|
||||
return `${amount} minutes`;
|
||||
case "h":
|
||||
return `${amount} hours`;
|
||||
case "d":
|
||||
return `${amount} days`;
|
||||
case "w":
|
||||
return `${amount} weeks`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})()
|
||||
: (trimmed as Duration.Input);
|
||||
|
||||
if (normalizedInput === null) return null;
|
||||
|
||||
const decoded = Duration.fromInput(normalizedInput as Duration.Input);
|
||||
return Option.isSome(decoded) ? decoded.value : null;
|
||||
};
|
||||
|
||||
export const DurationFromString = Schema.String.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.Duration,
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (value) => {
|
||||
const duration = parseDurationInput(value);
|
||||
if (duration !== null) {
|
||||
return Effect.succeed(duration);
|
||||
}
|
||||
return Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
|
||||
}),
|
||||
);
|
||||
},
|
||||
encode: (duration) => Effect.succeed(Duration.format(duration)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,434 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
OrchestrationReadModel,
|
||||
ProjectId,
|
||||
type ClientOrchestrationCommand,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Console,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
References,
|
||||
Schema,
|
||||
} from "effect";
|
||||
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
HttpClientRequest,
|
||||
HttpClientResponse,
|
||||
} from "effect/unstable/http";
|
||||
|
||||
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
|
||||
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
|
||||
import { ServerConfig, type ServerConfigShape } from "../config.ts";
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { getAutoBootstrapDefaultModelSelection } from "../serverRuntimeStartup.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "../serverRuntimeState.ts";
|
||||
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
|
||||
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
type ProjectMutationTarget = {
|
||||
readonly id: ProjectId;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
};
|
||||
|
||||
type ProjectCommandExecutionMode = "live" | "offline";
|
||||
type ProjectCliDispatchCommand = Extract<
|
||||
ClientOrchestrationCommand,
|
||||
{ type: "project.create" | "project.meta.update" | "project.delete" }
|
||||
>;
|
||||
|
||||
const ProjectCliRuntimeLive = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
OrchestrationLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
),
|
||||
);
|
||||
|
||||
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
|
||||
const OrchestrationHttpErrorResponse = Schema.Struct({
|
||||
error: Schema.String,
|
||||
});
|
||||
|
||||
const withProjectCliSessionToken = <A, E, R>(
|
||||
authControlPlane: AuthControlPlaneShape,
|
||||
run: (token: string) => Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.acquireUseRelease(
|
||||
authControlPlane.issueSession({
|
||||
role: "owner",
|
||||
label: "t3 project cli",
|
||||
}),
|
||||
(issued) => run(issued.token),
|
||||
(issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
|
||||
);
|
||||
|
||||
const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
|
||||
|
||||
const runLiveServerRequest = <A, E extends Error, R>(
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const response = yield* httpClient.execute(request);
|
||||
return yield* handle(response);
|
||||
}).pipe(withProjectCliLiveServerTimeout);
|
||||
|
||||
const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
|
||||
HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
|
||||
|
||||
const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
|
||||
HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
|
||||
Effect.map((body) => body.error),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.map((body) => {
|
||||
if (typeof body === "string" && body.trim().length > 0) {
|
||||
return body;
|
||||
}
|
||||
return `Server request failed with status ${response.status}.`;
|
||||
}),
|
||||
);
|
||||
|
||||
const normalizeWorkspaceRootForProjectCommand = Effect.fn(
|
||||
"normalizeWorkspaceRootForProjectCommand",
|
||||
)(function* (workspaceRoot: string) {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
|
||||
});
|
||||
|
||||
const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
workspaceRoot: string,
|
||||
explicitTitle?: string,
|
||||
) {
|
||||
if (explicitTitle !== undefined) {
|
||||
const trimmed = explicitTitle.trim();
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* Effect.fail(new Error("Project title cannot be empty."));
|
||||
}
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const basename = path.basename(workspaceRoot).trim();
|
||||
return basename.length > 0 ? basename : "project";
|
||||
});
|
||||
|
||||
const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly identifier: string;
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* Effect.fail(new Error("Project identifier cannot be empty."));
|
||||
}
|
||||
|
||||
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
|
||||
const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
|
||||
if (exactIdMatch) {
|
||||
return {
|
||||
id: exactIdMatch.id,
|
||||
title: exactIdMatch.title,
|
||||
workspaceRoot: exactIdMatch.workspaceRoot,
|
||||
} satisfies ProjectMutationTarget;
|
||||
}
|
||||
|
||||
const normalizedWorkspaceRootResult = yield* Effect.exit(
|
||||
normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
|
||||
);
|
||||
const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
|
||||
? normalizedWorkspaceRootResult.value
|
||||
: null;
|
||||
|
||||
const exactWorkspaceMatch =
|
||||
normalizedWorkspaceRoot === null
|
||||
? undefined
|
||||
: activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
|
||||
}
|
||||
|
||||
return {
|
||||
id: resolved.id,
|
||||
title: resolved.title,
|
||||
workspaceRoot: resolved.workspaceRoot,
|
||||
} satisfies ProjectMutationTarget;
|
||||
});
|
||||
|
||||
const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
runLiveServerRequest(
|
||||
HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(bearerToken),
|
||||
),
|
||||
HttpClientResponse.matchStatus({
|
||||
"2xx": decodeOrchestrationReadModelResponse,
|
||||
orElse: (response) =>
|
||||
readErrorMessageFromResponse(response).pipe(
|
||||
Effect.flatMap((message) => Effect.fail(new Error(message))),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
origin: string,
|
||||
bearerToken: string,
|
||||
command: ProjectCliDispatchCommand,
|
||||
) =>
|
||||
HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(bearerToken),
|
||||
HttpClientRequest.bodyJson(command),
|
||||
Effect.flatMap((request) =>
|
||||
runLiveServerRequest(
|
||||
request,
|
||||
HttpClientResponse.matchStatus({
|
||||
"2xx": () => Effect.void,
|
||||
orElse: (response) =>
|
||||
readErrorMessageFromResponse(response).pipe(
|
||||
Effect.flatMap((message) => Effect.fail(new Error(message))),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
});
|
||||
|
||||
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
|
||||
function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
|
||||
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
|
||||
if (Option.isNone(runtimeState)) {
|
||||
return Option.none<{ readonly origin: string }>();
|
||||
}
|
||||
|
||||
const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
|
||||
fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
|
||||
Effect.as({
|
||||
origin: runtimeState.value.origin,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const attempted = yield* Effect.exit(attempt);
|
||||
if (Exit.isSuccess(attempted)) {
|
||||
return Option.some(attempted.value);
|
||||
}
|
||||
|
||||
yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
|
||||
return Option.none<{ readonly origin: string }>();
|
||||
},
|
||||
);
|
||||
|
||||
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
readonly mode: ProjectCommandExecutionMode;
|
||||
}) => Effect.Effect<
|
||||
string,
|
||||
Error,
|
||||
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
|
||||
>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = config.logLevel;
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
|
||||
|
||||
if (Option.isSome(liveMode)) {
|
||||
return yield* withProjectCliSessionToken(authControlPlane, (token) =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
|
||||
const output = yield* run({
|
||||
snapshot,
|
||||
dispatch: (command) =>
|
||||
dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
|
||||
mode: "live",
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const snapshot = yield* getOfflineSnapshot();
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const output = yield* run({
|
||||
snapshot,
|
||||
dispatch: (command) => orchestrationEngine.dispatch(command),
|
||||
mode: "offline",
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}).pipe(Effect.provide(offlineRuntimeLayer));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const projectAddCommand = Command.make("add", {
|
||||
...projectLocationFlags,
|
||||
workspaceRoot: Argument.string("path").pipe(
|
||||
Argument.withDescription("Workspace root to add as a project."),
|
||||
),
|
||||
title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
|
||||
}).pipe(
|
||||
Command.withDescription("Add a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectAddMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
|
||||
const existingProject = snapshot.projects.find(
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* Effect.fail(
|
||||
new Error(`An active project already exists for '${workspaceRoot}'.`),
|
||||
);
|
||||
}
|
||||
|
||||
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
|
||||
const projectId = ProjectId.make(crypto.randomUUID());
|
||||
yield* dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const projectRemoveCommand = Command.make("remove", {
|
||||
...projectLocationFlags,
|
||||
project: Argument.string("project").pipe(
|
||||
Argument.withDescription("Project id or workspace root to remove."),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Remove a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectRemoveMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const project = yield* findActiveProjectTarget({
|
||||
snapshot,
|
||||
identifier: flags.project,
|
||||
});
|
||||
yield* dispatch({
|
||||
type: "project.delete",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const projectRenameCommand = Command.make("rename", {
|
||||
...projectLocationFlags,
|
||||
project: Argument.string("project").pipe(
|
||||
Argument.withDescription("Project id or workspace root to rename."),
|
||||
),
|
||||
title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
|
||||
}).pipe(
|
||||
Command.withDescription("Rename a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectRenameMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const project = yield* findActiveProjectTarget({
|
||||
snapshot,
|
||||
identifier: flags.project,
|
||||
});
|
||||
const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
|
||||
if (nextTitle === project.title) {
|
||||
return `Project ${project.id} is already named ${nextTitle}.`;
|
||||
}
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
title: nextTitle,
|
||||
});
|
||||
return `Renamed project ${project.id} to ${nextTitle}.`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const projectCommand = Command.make("project").pipe(
|
||||
Command.withDescription("Manage projects."),
|
||||
Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
|
||||
);
|
||||
@@ -1,36 +0,0 @@
|
||||
import { Effect } from "effect";
|
||||
import { Command, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import { ServerConfig, type StartupPresentation } from "../config.ts";
|
||||
import { runServer } from "../server.ts";
|
||||
import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
|
||||
|
||||
export const runServerCommand = (
|
||||
flags: CliServerFlags,
|
||||
options?: {
|
||||
readonly startupPresentation?: StartupPresentation;
|
||||
readonly forceAutoBootstrapProjectFromCwd?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveServerConfig(flags, logLevel, options);
|
||||
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
|
||||
});
|
||||
|
||||
export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) => runServerCommand(flags)),
|
||||
);
|
||||
|
||||
export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription(
|
||||
"Run the T3 Code server without opening a browser and print headless pairing details.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runServerCommand(flags, {
|
||||
startupPresentation: "headless",
|
||||
forceAutoBootstrapProjectFromCwd: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,252 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
describe("ProcessDiagnostics", () => {
|
||||
it.effect("parses POSIX ps rows with full commands", () =>
|
||||
Effect.sync(() => {
|
||||
const rows = ProcessDiagnostics.parsePosixProcessRows(
|
||||
[
|
||||
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
|
||||
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
pid: 10,
|
||||
ppid: 1,
|
||||
pgid: 10,
|
||||
status: "Ss",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1024 * 1024,
|
||||
elapsed: "01:02.03",
|
||||
command: "/usr/bin/node server.js",
|
||||
},
|
||||
{
|
||||
pid: 11,
|
||||
ppid: 10,
|
||||
pgid: 10,
|
||||
status: "S+",
|
||||
cpuPercent: 12.5,
|
||||
rssBytes: 20480 * 1024,
|
||||
elapsed: "00:04",
|
||||
command: "codex app-server --config /tmp/one two",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("aggregates only descendants of the server process", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1.5,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 3.25,
|
||||
rssBytes: 4_000,
|
||||
elapsed: "00:05",
|
||||
command: "git status",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "S",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 8_000,
|
||||
elapsed: "00:01",
|
||||
command: "unrelated",
|
||||
},
|
||||
{
|
||||
pid: 201,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 9,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:00",
|
||||
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.serverPid).toBe(100);
|
||||
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
|
||||
expect(diagnostics.processCount).toBe(2);
|
||||
expect(diagnostics.totalRssBytes).toBe(6_000);
|
||||
expect(diagnostics.totalCpuPercent).toBe(4.75);
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
|
||||
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
|
||||
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
|
||||
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves ascending sibling order for nested descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "agent",
|
||||
},
|
||||
{
|
||||
pid: 103,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-b",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-a",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queries processes through the ChildProcessSpawner service", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
commands.push({ command: childProcess.command, args: childProcess.args });
|
||||
return Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.read),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
command: "ps",
|
||||
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
pid: 4242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,461 +0,0 @@
|
||||
import type {
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessSignal,
|
||||
ServerSignalProcessResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly pgid: number | null;
|
||||
readonly status: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly elapsed: string;
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
|
||||
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
|
||||
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export interface ProcessDiagnosticsShape {
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
|
||||
"ProcessDiagnosticsError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
|
||||
return new ProcessDiagnosticsError({
|
||||
message,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
}
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNonNegativeInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNumber(value: string): number | null {
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
const rowPattern =
|
||||
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
|
||||
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
const match = rowPattern.exec(line);
|
||||
if (!match) continue;
|
||||
|
||||
const pidText = match[1];
|
||||
const ppidText = match[2];
|
||||
const pgidText = match[3];
|
||||
const status = match[4];
|
||||
const cpuText = match[5];
|
||||
const rssText = match[6];
|
||||
const elapsed = match[7];
|
||||
const command = match[8];
|
||||
if (
|
||||
pidText === undefined ||
|
||||
ppidText === undefined ||
|
||||
pgidText === undefined ||
|
||||
status === undefined ||
|
||||
cpuText === undefined ||
|
||||
rssText === undefined ||
|
||||
elapsed === undefined ||
|
||||
command === undefined
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pid = parsePositiveInt(pidText);
|
||||
const ppid = parseNonNegativeInt(ppidText);
|
||||
const pgid = Number.parseInt(pgidText, 10);
|
||||
const cpuPercent = parseNumber(cpuText);
|
||||
const rssKiB = parseNonNegativeInt(rssText);
|
||||
if (
|
||||
pid === null ||
|
||||
ppid === null ||
|
||||
!Number.isInteger(pgid) ||
|
||||
cpuPercent === null ||
|
||||
rssKiB === null ||
|
||||
!status ||
|
||||
!elapsed ||
|
||||
!command
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.push({
|
||||
pid,
|
||||
ppid,
|
||||
pgid,
|
||||
status,
|
||||
cpuPercent,
|
||||
rssBytes: rssKiB * 1024,
|
||||
elapsed,
|
||||
command,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
|
||||
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
|
||||
const commandLine =
|
||||
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
|
||||
? record.CommandLine
|
||||
: typeof record.Name === "string"
|
||||
? record.Name
|
||||
: null;
|
||||
const workingSet =
|
||||
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
|
||||
? Math.max(0, Math.round(record.WorkingSetSize))
|
||||
: 0;
|
||||
const cpuPercent =
|
||||
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
|
||||
? Math.max(0, record.PercentProcessorTime)
|
||||
: 0;
|
||||
|
||||
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
|
||||
return {
|
||||
pid,
|
||||
ppid,
|
||||
pgid: null,
|
||||
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
|
||||
cpuPercent,
|
||||
rssBytes: workingSet,
|
||||
elapsed: "",
|
||||
command: commandLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
if (output.trim().length === 0) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(output) as unknown;
|
||||
const records = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function buildDescendantEntries(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const children = childrenByParent.get(row.ppid) ?? [];
|
||||
children.push(row);
|
||||
childrenByParent.set(row.ppid, children);
|
||||
}
|
||||
|
||||
const entries: ServerProcessDiagnosticsEntry[] = [];
|
||||
const visited = new Set<number>();
|
||||
const stack = [...(childrenByParent.get(serverPid) ?? [])]
|
||||
.toSorted((left, right) => left.pid - right.pid)
|
||||
.map((row) => ({ row, depth: 0 }));
|
||||
|
||||
while (stack.length > 0) {
|
||||
const item = stack.shift();
|
||||
if (!item || visited.has(item.row.pid)) continue;
|
||||
visited.add(item.row.pid);
|
||||
|
||||
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
|
||||
(left, right) => left.pid - right.pid,
|
||||
);
|
||||
entries.push({
|
||||
pid: item.row.pid,
|
||||
ppid: item.row.ppid,
|
||||
pgid: Option.fromNullishOr(item.row.pgid),
|
||||
status: item.row.status,
|
||||
cpuPercent: item.row.cpuPercent,
|
||||
rssBytes: item.row.rssBytes,
|
||||
elapsed: item.row.elapsed || "n/a",
|
||||
command: item.row.command,
|
||||
depth: item.depth,
|
||||
childPids: children.map((child) => child.pid),
|
||||
});
|
||||
|
||||
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
if (row.ppid !== serverPid) return false;
|
||||
|
||||
const command = row.command.trim();
|
||||
return (
|
||||
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
|
||||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
|
||||
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
|
||||
);
|
||||
}
|
||||
|
||||
function makeResult(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: string;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const processes = buildDescendantEntries(rows, input.serverPid);
|
||||
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
|
||||
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
|
||||
|
||||
return {
|
||||
serverPid: input.serverPid,
|
||||
readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes,
|
||||
totalCpuPercent,
|
||||
processes,
|
||||
error: input.error ? Option.some({ message: input.error }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
interface ProcessOutput {
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(
|
||||
function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly errorMessage: string;
|
||||
}) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd: process.cwd(),
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
} satisfies ProcessOutput;
|
||||
},
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(ProcessDiagnosticsError)(cause)
|
||||
? cause
|
||||
: toProcessDiagnosticsError(input.errorMessage, cause),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function readPosixProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return runProcess({
|
||||
command: "ps",
|
||||
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function readWindowsProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const command = [
|
||||
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
|
||||
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
|
||||
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
|
||||
"};",
|
||||
"$processes | ConvertTo-Json -Compress -Depth 3",
|
||||
].join(" ");
|
||||
|
||||
return runProcess({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const readProcessRows = (platform = process.platform) =>
|
||||
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
return makeResult(input);
|
||||
}
|
||||
|
||||
function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
|
||||
}
|
||||
|
||||
return readProcessRows().pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
|
||||
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
|
||||
(entry) => entry.pid === pid,
|
||||
);
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
return makeResult({ serverPid: process.pid, rows, readAt });
|
||||
}).pipe(
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.map((readAt) =>
|
||||
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
function* (input) {
|
||||
return yield* assertDescendantPid(input.pid).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
toProcessDiagnosticsError(
|
||||
`Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(error.message),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
@@ -1,258 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
|
||||
|
||||
function ns(ms: number): string {
|
||||
return String(BigInt(ms) * 1_000_000n);
|
||||
}
|
||||
|
||||
function record(input: {
|
||||
readonly name: string;
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly startMs: number;
|
||||
readonly durationMs: number;
|
||||
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
|
||||
readonly events?: ReadonlyArray<unknown>;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
type: "effect-span",
|
||||
name: input.name,
|
||||
traceId: input.traceId,
|
||||
spanId: input.spanId,
|
||||
sampled: true,
|
||||
kind: "internal",
|
||||
startTimeUnixNano: ns(input.startMs),
|
||||
endTimeUnixNano: ns(input.startMs + input.durationMs),
|
||||
durationMs: input.durationMs,
|
||||
attributes: {},
|
||||
events: input.events ?? [],
|
||||
links: [],
|
||||
exit: input.exit ?? { _tag: "Success" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("TraceDiagnostics", () => {
|
||||
it.effect("aggregates failures, slow spans, log levels, and parse errors", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
slowSpanThresholdMs: 1_000,
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson.1",
|
||||
text: [
|
||||
record({
|
||||
name: "server.getConfig",
|
||||
traceId: "trace-a",
|
||||
spanId: "span-a",
|
||||
startMs: 1_000,
|
||||
durationMs: 50,
|
||||
}),
|
||||
"not-json",
|
||||
].join("\n"),
|
||||
},
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: [
|
||||
record({
|
||||
name: "orchestration.dispatch",
|
||||
traceId: "trace-b",
|
||||
spanId: "span-b",
|
||||
startMs: 2_000,
|
||||
durationMs: 1_500,
|
||||
exit: { _tag: "Failure", cause: "Provider crashed" },
|
||||
events: [
|
||||
{
|
||||
name: "provider failed",
|
||||
timeUnixNano: ns(3_400),
|
||||
attributes: { "effect.logLevel": "Error" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
record({
|
||||
name: "orchestration.dispatch",
|
||||
traceId: "trace-c",
|
||||
spanId: "span-c",
|
||||
startMs: 4_000,
|
||||
durationMs: 250,
|
||||
exit: { _tag: "Failure", cause: "Provider crashed" },
|
||||
}),
|
||||
record({
|
||||
name: "git.status",
|
||||
traceId: "trace-d",
|
||||
spanId: "span-d",
|
||||
startMs: 5_000,
|
||||
durationMs: 25,
|
||||
exit: { _tag: "Interrupted", cause: "Interrupted" },
|
||||
events: [
|
||||
{
|
||||
name: "status delayed",
|
||||
timeUnixNano: ns(5_010),
|
||||
attributes: { "effect.logLevel": "Warning" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
].join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 4);
|
||||
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
|
||||
assert.equal(
|
||||
Option.match(diagnostics.firstSpanAt, {
|
||||
onNone: () => null,
|
||||
onSome: DateTime.formatIso,
|
||||
}),
|
||||
"1970-01-01T00:00:01.000Z",
|
||||
);
|
||||
assert.equal(
|
||||
Option.match(diagnostics.lastSpanAt, {
|
||||
onNone: () => null,
|
||||
onSome: DateTime.formatIso,
|
||||
}),
|
||||
"1970-01-01T00:00:05.025Z",
|
||||
);
|
||||
assert.equal(diagnostics.parseErrorCount, 1);
|
||||
assert.equal(diagnostics.failureCount, 2);
|
||||
assert.equal(diagnostics.interruptionCount, 1);
|
||||
assert.equal(diagnostics.slowSpanCount, 1);
|
||||
assert.equal(diagnostics.logLevelCounts.Error, 1);
|
||||
assert.equal(diagnostics.logLevelCounts.Warning, 1);
|
||||
assert.equal(diagnostics.commonFailures[0]?.name, "orchestration.dispatch");
|
||||
assert.equal(diagnostics.commonFailures[0]?.count, 2);
|
||||
assert.equal(diagnostics.latestFailures[0]?.traceId, "trace-c");
|
||||
assert.equal(diagnostics.slowestSpans[0]?.traceId, "trace-b");
|
||||
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, "status delayed");
|
||||
assert.equal(diagnostics.topSpansByCount[0]?.name, "orchestration.dispatch");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a not-found diagnostic when no files are available", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/missing.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 0);
|
||||
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-not-found");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves full failure causes and log messages", () =>
|
||||
Effect.sync(() => {
|
||||
const longCause = `VcsProcessSpawnError: ${"missing executable ".repeat(80)}`.trim();
|
||||
const longMessage = `provider warning: ${"retrying command ".repeat(80)}`.trim();
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: record({
|
||||
name: "VcsProcess.run",
|
||||
traceId: "trace-long",
|
||||
spanId: "span-long",
|
||||
startMs: 1_000,
|
||||
durationMs: 25,
|
||||
exit: { _tag: "Failure", cause: longCause },
|
||||
events: [
|
||||
{
|
||||
name: longMessage,
|
||||
timeUnixNano: ns(1_010),
|
||||
attributes: { "effect.logLevel": "Warning" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.latestFailures[0]?.cause, longCause);
|
||||
assert.equal(diagnostics.commonFailures[0]?.cause, longCause);
|
||||
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, longMessage);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
|
||||
Effect.gen(function* () {
|
||||
const traceFilePath = "/tmp/server.trace.ndjson";
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
readFileString: (path) =>
|
||||
path === `${traceFilePath}.1`
|
||||
? Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(
|
||||
record({
|
||||
name: "server.getConfig",
|
||||
traceId: "trace-a",
|
||||
spanId: "span-a",
|
||||
startMs: 1_000,
|
||||
durationMs: 50,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
|
||||
traceFilePath,
|
||||
maxFiles: 1,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
|
||||
|
||||
assert.equal(diagnostics.recordCount, 1);
|
||||
assert.equal(
|
||||
Option.getOrElse(diagnostics.partialFailure, () => false),
|
||||
true,
|
||||
);
|
||||
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-read-failed");
|
||||
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps only the slowest span occurrences while aggregating large inputs", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: Array.from({ length: 25 }, (_, index) =>
|
||||
record({
|
||||
name: `span-${index}`,
|
||||
traceId: `trace-${index}`,
|
||||
spanId: `span-${index}`,
|
||||
startMs: index * 1_000,
|
||||
durationMs: index,
|
||||
}),
|
||||
).join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 25);
|
||||
assert.equal(diagnostics.slowestSpans.length, 10);
|
||||
assert.deepStrictEqual(
|
||||
diagnostics.slowestSpans.map((span) => span.durationMs),
|
||||
[24, 23, 22, 21, 20, 19, 18, 17, 16, 15],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,470 +0,0 @@
|
||||
import type {
|
||||
ServerTraceDiagnosticsErrorKind,
|
||||
ServerTraceDiagnosticsFailureSummary,
|
||||
ServerTraceDiagnosticsLogEvent,
|
||||
ServerTraceDiagnosticsRecentFailure,
|
||||
ServerTraceDiagnosticsResult,
|
||||
ServerTraceDiagnosticsSpanOccurrence,
|
||||
ServerTraceDiagnosticsSpanSummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
interface TraceRecordLike {
|
||||
readonly name?: unknown;
|
||||
readonly traceId?: unknown;
|
||||
readonly spanId?: unknown;
|
||||
readonly startTimeUnixNano?: unknown;
|
||||
readonly endTimeUnixNano?: unknown;
|
||||
readonly durationMs?: unknown;
|
||||
readonly exit?: unknown;
|
||||
readonly events?: unknown;
|
||||
}
|
||||
|
||||
interface TraceEventLike {
|
||||
readonly name?: unknown;
|
||||
readonly timeUnixNano?: unknown;
|
||||
readonly attributes?: unknown;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsOptions {
|
||||
readonly traceFilePath: string;
|
||||
readonly maxFiles: number;
|
||||
readonly slowSpanThresholdMs?: number;
|
||||
readonly readAt?: DateTime.Utc;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsShape {
|
||||
readonly read: (options: TraceDiagnosticsOptions) => Effect.Effect<ServerTraceDiagnosticsResult>;
|
||||
}
|
||||
|
||||
export class TraceDiagnostics extends Context.Service<TraceDiagnostics, TraceDiagnosticsShape>()(
|
||||
"t3/diagnostics/TraceDiagnostics",
|
||||
) {}
|
||||
|
||||
interface TraceDiagnosticsInput {
|
||||
readonly traceFilePath: string;
|
||||
readonly files: ReadonlyArray<{ readonly path: string; readonly text: string }>;
|
||||
readonly scannedFilePaths?: ReadonlyArray<string>;
|
||||
readonly slowSpanThresholdMs?: number;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: TraceDiagnosticsErrorSummary;
|
||||
readonly partialFailure?: boolean;
|
||||
}
|
||||
|
||||
interface TraceDiagnosticsErrorSummary {
|
||||
readonly kind: ServerTraceDiagnosticsErrorKind;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
|
||||
const TOP_LIMIT = 10;
|
||||
const RECENT_LIMIT = 20;
|
||||
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
|
||||
const backupCount = Math.max(0, Math.floor(maxFiles));
|
||||
const backups = Array.from(
|
||||
{ length: backupCount },
|
||||
(_, index) => `${traceFilePath}.${backupCount - index}`,
|
||||
);
|
||||
return [...backups, traceFilePath];
|
||||
}
|
||||
|
||||
function isRecordObject(value: unknown): value is TraceRecordLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function toStringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
function toNumberValue(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
|
||||
const text = toStringValue(value);
|
||||
if (!text) return null;
|
||||
|
||||
try {
|
||||
const millis = Number(BigInt(text) / 1_000_000n);
|
||||
if (!Number.isFinite(millis)) return null;
|
||||
return DateTime.makeUnsafe(millis);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isAfter(left: DateTime.Utc, right: DateTime.Utc): boolean {
|
||||
return DateTime.toEpochMillis(left) > DateTime.toEpochMillis(right);
|
||||
}
|
||||
|
||||
function isBefore(left: DateTime.Utc, right: DateTime.Utc): boolean {
|
||||
return DateTime.toEpochMillis(left) < DateTime.toEpochMillis(right);
|
||||
}
|
||||
|
||||
function readExitTag(exit: unknown): string | null {
|
||||
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
|
||||
return toStringValue(exit._tag);
|
||||
}
|
||||
|
||||
function readExitCause(exit: unknown): string {
|
||||
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
|
||||
return toStringValue(exit.cause)?.trim() ?? "Failure";
|
||||
}
|
||||
|
||||
function isTraceEvent(value: unknown): value is TraceEventLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
|
||||
return typeof event.attributes === "object" && event.attributes !== null
|
||||
? (event.attributes as Readonly<Record<string, unknown>>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function makeEmptyDiagnostics(input: {
|
||||
readonly traceFilePath: string;
|
||||
readonly scannedFilePaths: ReadonlyArray<string>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly slowSpanThresholdMs: number;
|
||||
readonly error?: TraceDiagnosticsErrorSummary;
|
||||
readonly partialFailure?: boolean;
|
||||
}): ServerTraceDiagnosticsResult {
|
||||
return {
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths: [...input.scannedFilePaths],
|
||||
readAt: input.readAt,
|
||||
recordCount: 0,
|
||||
parseErrorCount: 0,
|
||||
firstSpanAt: Option.none(),
|
||||
lastSpanAt: Option.none(),
|
||||
failureCount: 0,
|
||||
interruptionCount: 0,
|
||||
slowSpanThresholdMs: input.slowSpanThresholdMs,
|
||||
slowSpanCount: 0,
|
||||
logLevelCounts: {},
|
||||
topSpansByCount: [],
|
||||
slowestSpans: [],
|
||||
commonFailures: [],
|
||||
latestFailures: [],
|
||||
latestWarningAndErrorLogs: [],
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
}
|
||||
|
||||
function isNotFoundError(error: PlatformError.PlatformError): boolean {
|
||||
return error.reason._tag === "NotFound";
|
||||
}
|
||||
|
||||
function platformErrorMessage(error: PlatformError.PlatformError): string {
|
||||
return error.message || String(error);
|
||||
}
|
||||
|
||||
function insertBoundedSlowestSpan(
|
||||
slowestSpans: ServerTraceDiagnosticsSpanOccurrence[],
|
||||
span: ServerTraceDiagnosticsSpanOccurrence,
|
||||
): void {
|
||||
if (
|
||||
slowestSpans.length >= TOP_LIMIT &&
|
||||
span.durationMs <= slowestSpans[slowestSpans.length - 1]!.durationMs
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
slowestSpans.push(span);
|
||||
slowestSpans.sort((left, right) => right.durationMs - left.durationMs);
|
||||
if (slowestSpans.length > TOP_LIMIT) {
|
||||
slowestSpans.length = TOP_LIMIT;
|
||||
}
|
||||
}
|
||||
|
||||
export function aggregateTraceDiagnostics(
|
||||
input: TraceDiagnosticsInput,
|
||||
): ServerTraceDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
|
||||
if (input.files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error: input.error ?? {
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
},
|
||||
...(input.partialFailure ? { partialFailure: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
let parseErrorCount = 0;
|
||||
let recordCount = 0;
|
||||
let failureCount = 0;
|
||||
let interruptionCount = 0;
|
||||
let slowSpanCount = 0;
|
||||
let firstSpanAt: DateTime.Utc | null = null;
|
||||
let lastSpanAt: DateTime.Utc | null = null;
|
||||
|
||||
const spansByName = new Map<
|
||||
string,
|
||||
{ count: number; failureCount: number; totalDurationMs: number; maxDurationMs: number }
|
||||
>();
|
||||
const failuresByKey = new Map<string, ServerTraceDiagnosticsFailureSummary>();
|
||||
const latestFailures: ServerTraceDiagnosticsRecentFailure[] = [];
|
||||
const slowestSpans: ServerTraceDiagnosticsSpanOccurrence[] = [];
|
||||
const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];
|
||||
const logLevelCounts: Record<string, number> = {};
|
||||
|
||||
for (const file of input.files) {
|
||||
const lines = file.text.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isRecordObject(parsed)) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = toStringValue(parsed.name);
|
||||
const traceId = toStringValue(parsed.traceId);
|
||||
const spanId = toStringValue(parsed.spanId);
|
||||
const durationMs = toNumberValue(parsed.durationMs);
|
||||
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
|
||||
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
|
||||
|
||||
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
recordCount += 1;
|
||||
firstSpanAt =
|
||||
startedAt && (firstSpanAt === null || isBefore(startedAt, firstSpanAt))
|
||||
? startedAt
|
||||
: firstSpanAt;
|
||||
lastSpanAt = lastSpanAt === null || isAfter(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
|
||||
|
||||
const exitTag = readExitTag(parsed.exit);
|
||||
const isFailure = exitTag === "Failure";
|
||||
const isInterrupted = exitTag === "Interrupted";
|
||||
if (isFailure) failureCount += 1;
|
||||
if (isInterrupted) interruptionCount += 1;
|
||||
|
||||
const spanSummary = spansByName.get(name) ?? {
|
||||
count: 0,
|
||||
failureCount: 0,
|
||||
totalDurationMs: 0,
|
||||
maxDurationMs: 0,
|
||||
};
|
||||
spanSummary.count += 1;
|
||||
spanSummary.totalDurationMs += durationMs;
|
||||
spanSummary.maxDurationMs = Math.max(spanSummary.maxDurationMs, durationMs);
|
||||
if (isFailure) spanSummary.failureCount += 1;
|
||||
spansByName.set(name, spanSummary);
|
||||
|
||||
const spanItem = { name, durationMs, endedAt, traceId, spanId };
|
||||
if (durationMs >= slowSpanThresholdMs) {
|
||||
slowSpanCount += 1;
|
||||
}
|
||||
insertBoundedSlowestSpan(slowestSpans, spanItem);
|
||||
|
||||
if (isFailure) {
|
||||
const cause = readExitCause(parsed.exit);
|
||||
latestFailures.push({ ...spanItem, cause });
|
||||
|
||||
const failureKey = `${name}\0${cause}`;
|
||||
const existing = failuresByKey.get(failureKey);
|
||||
const isLatestFailure = !existing || isAfter(endedAt, existing.lastSeenAt);
|
||||
failuresByKey.set(failureKey, {
|
||||
name,
|
||||
cause,
|
||||
count: (existing?.count ?? 0) + 1,
|
||||
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
|
||||
traceId: isLatestFailure ? traceId : existing!.traceId,
|
||||
spanId: isLatestFailure ? spanId : existing!.spanId,
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(parsed.events)) {
|
||||
for (const rawEvent of parsed.events) {
|
||||
if (!isTraceEvent(rawEvent)) continue;
|
||||
const attributes = readEventAttributes(rawEvent);
|
||||
const level = toStringValue(attributes["effect.logLevel"]);
|
||||
if (!level) continue;
|
||||
|
||||
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
|
||||
const normalizedLevel = level.toLowerCase();
|
||||
if (
|
||||
normalizedLevel !== "warning" &&
|
||||
normalizedLevel !== "warn" &&
|
||||
normalizedLevel !== "error" &&
|
||||
normalizedLevel !== "fatal"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
|
||||
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
|
||||
latestWarningAndErrorLogs.push({
|
||||
spanName: name,
|
||||
level,
|
||||
message,
|
||||
seenAt,
|
||||
traceId,
|
||||
spanId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
|
||||
.map(([name, span]) => ({
|
||||
name,
|
||||
count: span.count,
|
||||
failureCount: span.failureCount,
|
||||
totalDurationMs: span.totalDurationMs,
|
||||
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
|
||||
maxDurationMs: span.maxDurationMs,
|
||||
}))
|
||||
.toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs)
|
||||
.slice(0, TOP_LIMIT);
|
||||
|
||||
return {
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
recordCount,
|
||||
parseErrorCount,
|
||||
firstSpanAt: Option.fromNullishOr(firstSpanAt),
|
||||
lastSpanAt: Option.fromNullishOr(lastSpanAt),
|
||||
failureCount,
|
||||
interruptionCount,
|
||||
slowSpanThresholdMs,
|
||||
slowSpanCount,
|
||||
logLevelCounts,
|
||||
topSpansByCount,
|
||||
slowestSpans,
|
||||
commonFailures: [...failuresByKey.values()]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
right.count - left.count ||
|
||||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
|
||||
)
|
||||
.slice(0, TOP_LIMIT),
|
||||
latestFailures: latestFailures
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
latestWarningAndErrorLogs: latestWarningAndErrorLogs
|
||||
.toSorted(
|
||||
(left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
}
|
||||
|
||||
type TraceFileReadResult =
|
||||
| { readonly _tag: "Loaded"; readonly path: string; readonly text: string }
|
||||
| { readonly _tag: "Missing"; readonly path: string }
|
||||
| { readonly _tag: "Failed"; readonly path: string; readonly message: string };
|
||||
|
||||
function readTraceFile(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
path: string,
|
||||
): Effect.Effect<TraceFileReadResult> {
|
||||
return fileSystem.readFileString(path).pipe(
|
||||
Effect.map((text) => ({ _tag: "Loaded" as const, path, text })),
|
||||
Effect.catch((error: PlatformError.PlatformError) =>
|
||||
Effect.succeed(
|
||||
isNotFoundError(error)
|
||||
? { _tag: "Missing" as const, path }
|
||||
: { _tag: "Failed" as const, path, message: platformErrorMessage(error) },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeTraceDiagnostics")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const read: TraceDiagnosticsShape["read"] = Effect.fn("TraceDiagnostics.read")(
|
||||
function* (options) {
|
||||
const readAt = options.readAt ?? (yield* DateTime.now);
|
||||
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
|
||||
const results = yield* Effect.all(
|
||||
paths.map((path) => readTraceFile(fileSystem, path)),
|
||||
{
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
const files = results.flatMap((result) =>
|
||||
result._tag === "Loaded" ? [{ path: result.path, text: result.text }] : [],
|
||||
);
|
||||
const readFailure = results.find((result) => result._tag === "Failed");
|
||||
const readFailureError = readFailure
|
||||
? ({
|
||||
kind: "trace-file-read-failed",
|
||||
message: readFailure.message.trim() || `Failed to read ${readFailure.path}.`,
|
||||
} satisfies TraceDiagnosticsErrorSummary)
|
||||
: undefined;
|
||||
|
||||
if (files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: options.traceFilePath,
|
||||
scannedFilePaths: paths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error:
|
||||
readFailureError ??
|
||||
({
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
} satisfies TraceDiagnosticsErrorSummary),
|
||||
});
|
||||
}
|
||||
|
||||
return aggregateTraceDiagnostics({
|
||||
traceFilePath: options.traceFilePath,
|
||||
files,
|
||||
scannedFilePaths: paths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return TraceDiagnostics.of({ read });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(TraceDiagnostics, make());
|
||||
|
||||
export function readTraceDiagnostics(
|
||||
options: TraceDiagnosticsOptions,
|
||||
): Effect.Effect<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {
|
||||
return Effect.gen(function* () {
|
||||
const diagnostics = yield* TraceDiagnostics;
|
||||
return yield* diagnostics.read(options);
|
||||
});
|
||||
}
|
||||
@@ -294,18 +294,6 @@ function configureRemote(
|
||||
});
|
||||
}
|
||||
|
||||
function configureVisibleRemoteUrlWithLocalRewrite(
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
visibleUrl: string,
|
||||
localRemotePath: string,
|
||||
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
|
||||
return Effect.gen(function* () {
|
||||
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, visibleUrl]);
|
||||
yield* runGit(cwd, ["config", `url.${localRemotePath}.insteadOf`, visibleUrl]);
|
||||
});
|
||||
}
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: (input) =>
|
||||
@@ -1024,12 +1012,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-488/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
"[email protected]:jasonLaster/codething-mvp.git",
|
||||
forkDir,
|
||||
);
|
||||
]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -1089,19 +1076,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"origin",
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.origin.url",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
originDir,
|
||||
);
|
||||
]);
|
||||
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"my-org/upstream",
|
||||
"ssh://[email protected]/pingdotgg/codething-mvp.git",
|
||||
upstreamDir,
|
||||
);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.my-org/upstream.url",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
]);
|
||||
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
|
||||
@@ -1876,12 +1861,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
forkDir,
|
||||
);
|
||||
]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -1939,19 +1923,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"origin",
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.origin.url",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
originDir,
|
||||
);
|
||||
]);
|
||||
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"my-org/upstream",
|
||||
"ssh://[email protected]/pingdotgg/codething-mvp.git",
|
||||
upstreamDir,
|
||||
);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.my-org/upstream.url",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
]);
|
||||
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
|
||||
@@ -2031,12 +2013,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
forkDir,
|
||||
);
|
||||
]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -2102,12 +2083,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
forkDir,
|
||||
);
|
||||
]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -2283,12 +2263,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-91/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
forkDir,
|
||||
);
|
||||
]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -3168,7 +3147,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
|
||||
fs.writeFileSync(
|
||||
path.join(repoDir, ".git", "hooks", "pre-commit"),
|
||||
'#!/bin/sh\necho "hook: start" >&2\nsleep 0.05\necho "hook: end" >&2\n',
|
||||
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
|
||||
@@ -354,7 +354,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("appends additional custom keybindings for the same command", () =>
|
||||
it.effect("replaces existing custom keybinding for the same command", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
@@ -368,55 +368,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("replaces only the targeted custom keybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+alt+r",
|
||||
command: "script.run-tests.run",
|
||||
replace: { key: "mod+r", command: "script.run-tests.run" },
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+alt+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("removes only the targeted custom keybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.removeKeybindingRule({
|
||||
key: "mod+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||
|
||||
@@ -15,8 +15,6 @@ import {
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
type ServerRemoveKeybindingInput,
|
||||
type ServerUpsertKeybindingInput,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -126,25 +124,6 @@ function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): bo
|
||||
return leftContext === rightContext;
|
||||
}
|
||||
|
||||
function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
|
||||
return input.when === undefined
|
||||
? { key: input.key, command: input.command }
|
||||
: { key: input.key, command: input.command, when: input.when };
|
||||
}
|
||||
|
||||
function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
|
||||
if (!input.replace) return null;
|
||||
return input.replace.when === undefined
|
||||
? { key: input.replace.key, command: input.replace.command }
|
||||
: { key: input.replace.key, command: input.replace.command, when: input.replace.when };
|
||||
}
|
||||
|
||||
function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
|
||||
return input.when === undefined
|
||||
? { key: input.key, command: input.command }
|
||||
: { key: input.key, command: input.command, when: input.when };
|
||||
}
|
||||
|
||||
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
|
||||
const modifiers: string[] = [];
|
||||
if (shortcut.modKey) modifiers.push("mod");
|
||||
@@ -280,14 +259,7 @@ export interface KeybindingsShape {
|
||||
* oldest entries when needed.
|
||||
*/
|
||||
readonly upsertKeybindingRule: (
|
||||
input: ServerUpsertKeybindingInput,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
|
||||
/**
|
||||
* Remove a single persisted keybinding rule by exact key/command/when match.
|
||||
*/
|
||||
readonly removeKeybindingRule: (
|
||||
input: ServerRemoveKeybindingInput,
|
||||
rule: KeybindingRule,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
}
|
||||
|
||||
@@ -644,19 +616,12 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
upsertKeybindingRule: (input) =>
|
||||
upsertKeybindingRule: (rule) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const rule = keybindingRuleFromUpsertInput(input);
|
||||
const replaceTarget = replaceTargetFromUpsertInput(input);
|
||||
const nextConfig = [
|
||||
...customConfig.filter((entry) => {
|
||||
if (replaceTarget) {
|
||||
return !isSameKeybindingRule(entry, replaceTarget);
|
||||
}
|
||||
return !isSameKeybindingRule(entry, rule);
|
||||
}),
|
||||
...customConfig.filter((entry) => entry.command !== rule.command),
|
||||
rule,
|
||||
];
|
||||
const cappedConfig =
|
||||
@@ -684,27 +649,6 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
return nextResolved;
|
||||
}),
|
||||
),
|
||||
removeKeybindingRule: (input) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const target = keybindingRuleFromRemoveInput(input);
|
||||
const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
|
||||
yield* writeConfigAtomically(nextConfig);
|
||||
const nextResolved = mergeWithDefaultKeybindings(
|
||||
compileResolvedKeybindingsConfig(nextConfig),
|
||||
);
|
||||
yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
|
||||
keybindings: nextResolved,
|
||||
issues: [],
|
||||
});
|
||||
yield* emitChange({
|
||||
keybindings: nextResolved,
|
||||
issues: [],
|
||||
});
|
||||
return nextResolved;
|
||||
}),
|
||||
),
|
||||
} satisfies KeybindingsShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { Duration, Effect, Fiber, Metric } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { Effect, Metric } from "effect";
|
||||
|
||||
import { withMetrics } from "./Metrics.ts";
|
||||
|
||||
@@ -16,18 +15,6 @@ const hasMetricSnapshot = (
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
const findHistogramSnapshot = (
|
||||
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
|
||||
id: string,
|
||||
attributes: Readonly<Record<string, string>>,
|
||||
) =>
|
||||
snapshots.find(
|
||||
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Histogram" }> =>
|
||||
snapshot.type === "Histogram" &&
|
||||
snapshot.id === id &&
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
describe("withMetrics", () => {
|
||||
it.effect("supports pipe-style usage", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -123,35 +110,4 @@ describe("withMetrics", () => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records timer durations from nanosecond clock readings", () =>
|
||||
Effect.gen(function* () {
|
||||
const duration = Duration.nanos(1_500_000n);
|
||||
const timer = Metric.timer("with_metrics_nanos_duration");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const fiber = yield* Effect.sleep(duration).pipe(
|
||||
withMetrics({
|
||||
timer,
|
||||
attributes: {
|
||||
operation: "nanos",
|
||||
},
|
||||
}),
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(duration);
|
||||
yield* Fiber.join(fiber);
|
||||
}).pipe(Effect.provide(TestClock.layer()));
|
||||
|
||||
const snapshots = yield* Metric.snapshot;
|
||||
const snapshot = findHistogramSnapshot(snapshots, "with_metrics_nanos_duration", {
|
||||
operation: "nanos",
|
||||
});
|
||||
|
||||
assert.equal(snapshot?.state.count, 1);
|
||||
assert.equal(snapshot?.state.sum, 1.5);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Clock, Duration, Effect, Exit, Metric } from "effect";
|
||||
import { Duration, Effect, Exit, Metric } from "effect";
|
||||
import { dual } from "effect/Function";
|
||||
|
||||
import {
|
||||
@@ -96,11 +96,9 @@ const withMetricsImpl = <A, E, R>(
|
||||
options: WithMetricsOptions,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
const startedAt = yield* Clock.currentTimeNanos;
|
||||
const startedAt = Date.now();
|
||||
const exit = yield* Effect.exit(effect);
|
||||
const endedAt = yield* Clock.currentTimeNanos;
|
||||
const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;
|
||||
const duration = Duration.nanos(elapsedNanos);
|
||||
const duration = Duration.millis(Math.max(0, Date.now() - startedAt));
|
||||
const baseAttributes =
|
||||
typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { Duration, Effect, Exit, Fiber, Metric, Stream, Tracer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { Effect, Exit, Metric, Stream } from "effect";
|
||||
|
||||
import {
|
||||
observeRpcEffect,
|
||||
@@ -20,44 +18,6 @@ const hasMetricSnapshot = (
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
const findHistogramSnapshot = (
|
||||
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
|
||||
id: string,
|
||||
attributes: Readonly<Record<string, string>>,
|
||||
) =>
|
||||
snapshots.find(
|
||||
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Histogram" }> =>
|
||||
snapshot.type === "Histogram" &&
|
||||
snapshot.id === id &&
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
const collectSpanNames = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<ReadonlyArray<string>, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames: Array<string> = [];
|
||||
const tracer = Tracer.make({
|
||||
span: (options) => {
|
||||
const span = new Tracer.NativeSpan(options);
|
||||
const end = span.end.bind(span);
|
||||
|
||||
span.end = (endTime, exit) => {
|
||||
end(endTime, exit);
|
||||
if (span.sampled) {
|
||||
spanNames.push(span.name);
|
||||
}
|
||||
};
|
||||
|
||||
return span;
|
||||
},
|
||||
});
|
||||
|
||||
yield* effect.pipe(Effect.withTracer(tracer));
|
||||
|
||||
return spanNames;
|
||||
});
|
||||
|
||||
describe("RpcInstrumentation", () => {
|
||||
it.effect("records success metrics for unary RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -169,37 +129,6 @@ describe("RpcInstrumentation", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records direct stream durations from nanosecond clock readings", () =>
|
||||
Effect.gen(function* () {
|
||||
const duration = Duration.nanos(1_500_000n);
|
||||
const events = yield* Effect.gen(function* () {
|
||||
const fiber = yield* Stream.runCollect(
|
||||
observeRpcStream(
|
||||
WS_METHODS.serverGetProcessDiagnostics,
|
||||
Stream.fromEffect(Effect.sleep(duration).pipe(Effect.as("ok"))),
|
||||
{
|
||||
"rpc.aggregate": "test",
|
||||
},
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(duration);
|
||||
return yield* Fiber.join(fiber);
|
||||
}).pipe(Effect.provide(TestClock.layer()));
|
||||
|
||||
assert.deepStrictEqual(Array.from(events), ["ok"]);
|
||||
|
||||
const snapshots = yield* Metric.snapshot;
|
||||
const snapshot = findHistogramSnapshot(snapshots, "t3_rpc_request_duration", {
|
||||
method: WS_METHODS.serverGetProcessDiagnostics,
|
||||
});
|
||||
|
||||
assert.equal(snapshot?.state.count, 1);
|
||||
assert.equal(snapshot?.state.sum, 1.5);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const exit = yield* Stream.runCollect(
|
||||
@@ -229,79 +158,4 @@ describe("RpcInstrumentation", () => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records spans for traced stream RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
Stream.runCollect(
|
||||
observeRpcStream(
|
||||
"rpc.instrumentation.traced.stream",
|
||||
Stream.fromEffect(
|
||||
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.traced.stream.child")),
|
||||
),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(spanNames.includes("ws.rpc.rpc.instrumentation.traced.stream"), true);
|
||||
assert.equal(spanNames.includes("rpc.instrumentation.traced.stream.child"), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create spans for disabled unary RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.disabled.unary.child")),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(spanNames, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create spans for disabled direct stream RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
Stream.runCollect(
|
||||
observeRpcStream(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
Stream.fromEffect(
|
||||
Effect.succeed("ok").pipe(
|
||||
Effect.withSpan("rpc.instrumentation.disabled.stream.child"),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(spanNames, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create spans for disabled stream effect RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
Stream.runCollect(
|
||||
observeRpcStreamEffect(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
Effect.succeed(
|
||||
Stream.fromEffect(
|
||||
Effect.succeed("ok").pipe(
|
||||
Effect.withSpan("rpc.instrumentation.disabled.stream.effect.consume"),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.withSpan("rpc.instrumentation.disabled.stream.effect.create")),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(spanNames, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,71 +1,26 @@
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { Clock, Duration, Effect, Exit, Metric, References, Stream } from "effect";
|
||||
import { Duration, Effect, Exit, Metric, Stream } from "effect";
|
||||
|
||||
import { outcomeFromExit } from "./Attributes.ts";
|
||||
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
|
||||
|
||||
const RPC_SPAN_PREFIX = "ws.rpc";
|
||||
const DEFAULT_RPC_SPAN_ATTRIBUTES = {
|
||||
"rpc.transport": "websocket",
|
||||
"rpc.system": "effect-rpc",
|
||||
} as const;
|
||||
const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
WS_METHODS.serverGetProcessDiagnostics,
|
||||
WS_METHODS.serverSignalProcess,
|
||||
]);
|
||||
|
||||
function shouldTraceRpc(method: string): boolean {
|
||||
return !RPC_METHODS_WITH_TRACING_DISABLED.has(method);
|
||||
}
|
||||
|
||||
const rpcSpanAttributes = (
|
||||
const annotateRpcSpan = (
|
||||
method: string,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Record<string, unknown> => ({
|
||||
...DEFAULT_RPC_SPAN_ATTRIBUTES,
|
||||
"rpc.method": method,
|
||||
...traceAttributes,
|
||||
});
|
||||
|
||||
const withRpcEffectTracing = <A, E, R>(
|
||||
method: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
shouldTraceRpc(method)
|
||||
? effect.pipe(
|
||||
Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
|
||||
attributes: rpcSpanAttributes(method, traceAttributes),
|
||||
}),
|
||||
)
|
||||
: effect.pipe(Effect.provideService(References.TracerEnabled, false));
|
||||
|
||||
const withRpcStreamTracing = <A, E, R>(
|
||||
method: string,
|
||||
stream: Stream.Stream<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, E, R> =>
|
||||
shouldTraceRpc(method)
|
||||
? stream.pipe(
|
||||
Stream.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
|
||||
attributes: rpcSpanAttributes(method, traceAttributes),
|
||||
}),
|
||||
)
|
||||
: stream.pipe(Stream.provideService(References.TracerEnabled, false));
|
||||
): Effect.Effect<void, never, never> =>
|
||||
Effect.annotateCurrentSpan({
|
||||
"rpc.method": method,
|
||||
...traceAttributes,
|
||||
});
|
||||
|
||||
const recordRpcStreamMetrics = <E>(
|
||||
method: string,
|
||||
startedAt: bigint,
|
||||
startedAt: number,
|
||||
exit: Exit.Exit<unknown, E>,
|
||||
): Effect.Effect<void, never, never> =>
|
||||
Effect.gen(function* () {
|
||||
const endedAt = yield* Clock.currentTimeNanos;
|
||||
const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;
|
||||
|
||||
yield* Metric.update(
|
||||
Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
|
||||
Duration.nanos(elapsedNanos),
|
||||
Duration.millis(Math.max(0, Date.now() - startedAt)),
|
||||
);
|
||||
yield* Metric.update(
|
||||
Metric.withAttributes(
|
||||
@@ -83,43 +38,43 @@ export const observeRpcEffect = <A, E, R>(
|
||||
method: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Effect.Effect<A, E, R> => {
|
||||
const instrumented = effect.pipe(
|
||||
withMetrics({
|
||||
counter: rpcRequestsTotal,
|
||||
timer: rpcRequestDuration,
|
||||
attributes: {
|
||||
method,
|
||||
},
|
||||
}),
|
||||
);
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
yield* annotateRpcSpan(method, traceAttributes);
|
||||
|
||||
return withRpcEffectTracing(method, instrumented, traceAttributes);
|
||||
};
|
||||
return yield* effect.pipe(
|
||||
withMetrics({
|
||||
counter: rpcRequestsTotal,
|
||||
timer: rpcRequestDuration,
|
||||
attributes: {
|
||||
method,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const observeRpcStream = <A, E, R>(
|
||||
method: string,
|
||||
stream: Stream.Stream<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, E, R> => {
|
||||
const instrumented = Stream.unwrap(
|
||||
): Stream.Stream<A, E, R> =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const startedAt = yield* Clock.currentTimeNanos;
|
||||
yield* annotateRpcSpan(method, traceAttributes);
|
||||
const startedAt = Date.now();
|
||||
return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
|
||||
}),
|
||||
);
|
||||
|
||||
return withRpcStreamTracing(method, instrumented, traceAttributes);
|
||||
};
|
||||
|
||||
export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
|
||||
method: string,
|
||||
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> => {
|
||||
const instrumented = Stream.unwrap(
|
||||
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const startedAt = yield* Clock.currentTimeNanos;
|
||||
yield* annotateRpcSpan(method, traceAttributes);
|
||||
const startedAt = Date.now();
|
||||
const exit = yield* Effect.exit(effect);
|
||||
|
||||
if (Exit.isFailure(exit)) {
|
||||
@@ -132,6 +87,3 @@ export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectErro
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return withRpcStreamTracing(method, instrumented, traceAttributes);
|
||||
};
|
||||
@@ -98,105 +98,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
command: "idea",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const aquaLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLaunch, {
|
||||
command: "aqua",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const clionLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLaunch, {
|
||||
command: "clion",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const datagripLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLaunch, {
|
||||
command: "datagrip",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const dataspellLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLaunch, {
|
||||
command: "dataspell",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const golandLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLaunch, {
|
||||
command: "goland",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const phpstormLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLaunch, {
|
||||
command: "phpstorm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const pycharmLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLaunch, {
|
||||
command: "pycharm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const riderLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLaunch, {
|
||||
command: "rider",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const rubymineLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLaunch, {
|
||||
command: "rubymine",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const rustroverLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLaunch, {
|
||||
command: "rustrover",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const webstormLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "webstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(webstormLaunch, {
|
||||
command: "webstorm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -306,105 +207,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
command: "idea",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const aquaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLineAndColumn, {
|
||||
command: "aqua",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const clionLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLineAndColumn, {
|
||||
command: "clion",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const datagripLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLineAndColumn, {
|
||||
command: "datagrip",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const dataspellLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLineAndColumn, {
|
||||
command: "dataspell",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const golandLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLineAndColumn, {
|
||||
command: "goland",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const phpstormLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLineAndColumn, {
|
||||
command: "phpstorm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const pycharmLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLineAndColumn, {
|
||||
command: "pycharm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const riderLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLineAndColumn, {
|
||||
command: "rider",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const rubymineLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLineAndColumn, {
|
||||
command: "rubymine",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const rustroverLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLineAndColumn, {
|
||||
command: "rustrover",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const webstormLineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "webstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(webstormLineOnly, {
|
||||
command: "webstorm",
|
||||
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -575,40 +377,12 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "aqua.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "clion.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "datagrip.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "dataspell.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "goland.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "phpstorm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "pycharm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rider.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rubymine.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rustrover.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "webstorm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, [
|
||||
"trae",
|
||||
"kiro",
|
||||
"vscode-insiders",
|
||||
"vscodium",
|
||||
"aqua",
|
||||
"clion",
|
||||
"datagrip",
|
||||
"dataspell",
|
||||
"goland",
|
||||
"phpstorm",
|
||||
"pycharm",
|
||||
"rider",
|
||||
"rubymine",
|
||||
"rustrover",
|
||||
"webstorm",
|
||||
"file-manager",
|
||||
]);
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -41,7 +41,6 @@ import {
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
@@ -133,14 +132,7 @@ function createProviderServiceHarness(
|
||||
}
|
||||
|
||||
async function waitForThread(
|
||||
readModel: () => Promise<{
|
||||
readonly threads: ReadonlyArray<{
|
||||
readonly id: ThreadId;
|
||||
readonly latestTurn: { readonly turnId: string } | null;
|
||||
readonly checkpoints: ReadonlyArray<{ readonly checkpointTurnCount: number }>;
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string }>;
|
||||
}>;
|
||||
}>,
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: {
|
||||
latestTurn: { turnId: string } | null;
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
@@ -154,8 +146,8 @@ async function waitForThread(
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
const snapshot = await readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -239,7 +231,7 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
|
||||
|
||||
describe("CheckpointReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore | ProjectionSnapshotQuery,
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -287,10 +279,6 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-reactor-test-",
|
||||
@@ -316,7 +304,6 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
const layer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
@@ -335,7 +322,6 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
|
||||
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
@@ -401,7 +387,6 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
provider,
|
||||
cwd,
|
||||
drain,
|
||||
@@ -458,7 +443,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
@@ -556,7 +541,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await harness.readModel();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
|
||||
@@ -572,7 +557,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
@@ -629,7 +614,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
@@ -674,7 +659,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 &&
|
||||
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
|
||||
@@ -809,7 +794,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
false,
|
||||
@@ -938,10 +923,7 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.checkpoints.length === 1,
|
||||
);
|
||||
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||
|
||||
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread.checkpoints).toHaveLength(1);
|
||||
@@ -1123,7 +1105,7 @@ describe("CheckpointReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"),
|
||||
);
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
@@ -67,7 +66,6 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
@@ -126,26 +124,29 @@ const make = Effect.gen(function* () {
|
||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||
threadId: ThreadId,
|
||||
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
|
||||
const sessions = yield* providerService.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
return session?.cwd
|
||||
? Option.some({ threadId: session.threadId, cwd: session.cwd })
|
||||
: Option.none();
|
||||
});
|
||||
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
const findSessionWithCwd = (
|
||||
session: (typeof sessions)[number] | undefined,
|
||||
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
|
||||
if (!session?.cwd) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some({ threadId: session.threadId, cwd: session.cwd });
|
||||
};
|
||||
|
||||
const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
|
||||
projectId: ProjectId,
|
||||
) {
|
||||
const project = yield* projectionSnapshotQuery
|
||||
.getProjectShellById(projectId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
return project ? [project] : [];
|
||||
if (thread) {
|
||||
const projectedSession = sessions.find((session) => session.threadId === thread.id);
|
||||
const fromProjected = findSessionWithCwd(projectedSession);
|
||||
if (Option.isSome(fromProjected)) {
|
||||
return fromProjected;
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||
@@ -330,7 +331,8 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
@@ -351,11 +353,10 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -406,7 +407,8 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
|
||||
threadId,
|
||||
@@ -427,11 +429,10 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -457,16 +458,16 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -539,16 +540,16 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const threadId = event.payload.threadId;
|
||||
const thread = yield* resolveThreadDetail(threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -586,7 +587,8 @@ const make = Effect.gen(function* () {
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.payload.threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
|
||||
if (!thread) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
ProviderInstanceId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -43,13 +42,9 @@ async function createOrchestrationSystem() {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-engine-test-",
|
||||
});
|
||||
const orchestrationLayer = Layer.mergeAll(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
),
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
).pipe(
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
@@ -59,10 +54,8 @@ async function createOrchestrationSystem() {
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
return {
|
||||
engine,
|
||||
readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
|
||||
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
|
||||
dispose: () => runtime.dispose(),
|
||||
};
|
||||
@@ -84,18 +77,15 @@ const hasMetricSnapshot = (
|
||||
);
|
||||
|
||||
describe("OrchestrationEngine", () => {
|
||||
it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
|
||||
let nextSequence = 8;
|
||||
const eventStore: OrchestrationEventStoreShape = {
|
||||
append: (event) =>
|
||||
Effect.sync(() => {
|
||||
const savedEvent = {
|
||||
...event,
|
||||
sequence: nextSequence,
|
||||
} as OrchestrationEvent;
|
||||
nextSequence += 1;
|
||||
return savedEvent;
|
||||
}),
|
||||
it("bootstraps the in-memory read model from persisted projections", async () => {
|
||||
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
|
||||
append: () =>
|
||||
Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "test.append",
|
||||
detail: "append should not be called during bootstrap",
|
||||
}),
|
||||
),
|
||||
readFromSequence: () => Stream.empty,
|
||||
readAll: () =>
|
||||
Stream.fail(
|
||||
@@ -150,27 +140,11 @@ describe("OrchestrationEngine", () => {
|
||||
},
|
||||
],
|
||||
};
|
||||
const commandReadModel = {
|
||||
...projectionSnapshot,
|
||||
threads: projectionSnapshot.threads.map((thread) => ({
|
||||
...thread,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
})),
|
||||
};
|
||||
let fullSnapshotReadCount = 0;
|
||||
|
||||
const layer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.succeed(commandReadModel),
|
||||
getSnapshot: () =>
|
||||
Effect.sync(() => {
|
||||
fullSnapshotReadCount += 1;
|
||||
return projectionSnapshot;
|
||||
}),
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
@@ -178,8 +152,6 @@ describe("OrchestrationEngine", () => {
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
@@ -195,7 +167,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: () => Effect.void,
|
||||
} satisfies OrchestrationProjectionPipelineShape),
|
||||
),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
@@ -203,22 +175,18 @@ describe("OrchestrationEngine", () => {
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const result = await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-bootstrap-thread-update"),
|
||||
threadId: ThreadId.make("thread-bootstrap"),
|
||||
title: "Updated Bootstrap Thread",
|
||||
}),
|
||||
);
|
||||
const readModel = await runtime.runPromise(engine.getReadModel());
|
||||
|
||||
expect(result.sequence).toBe(8);
|
||||
expect(fullSnapshotReadCount).toBe(0);
|
||||
expect(readModel.snapshotSequence).toBe(7);
|
||||
expect(readModel.projects).toHaveLength(1);
|
||||
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
|
||||
expect(readModel.threads).toHaveLength(1);
|
||||
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
|
||||
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
it("persists deterministic read models for repeated snapshot reads", async () => {
|
||||
it("returns deterministic read models for repeated reads", async () => {
|
||||
const createdAt = now();
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
@@ -272,8 +240,8 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const readModelA = await system.readModel();
|
||||
const readModelB = await system.readModel();
|
||||
const readModelA = await system.run(engine.getReadModel());
|
||||
const readModelB = await system.run(engine.getReadModel());
|
||||
expect(readModelB).toEqual(readModelA);
|
||||
await system.dispose();
|
||||
});
|
||||
@@ -324,8 +292,9 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
||||
?.archivedAt,
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).not.toBeNull();
|
||||
|
||||
await system.run(
|
||||
@@ -336,8 +305,9 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
||||
?.archivedAt,
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).toBeNull();
|
||||
|
||||
await system.dispose();
|
||||
@@ -603,7 +573,7 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const thread = (await system.readModel()).threads.find(
|
||||
const thread = (await system.run(engine.getReadModel())).threads.find(
|
||||
(entry) => entry.id === "thread-turn-diff",
|
||||
);
|
||||
expect(thread?.checkpoints).toEqual([
|
||||
@@ -731,15 +701,7 @@ describe("OrchestrationEngine", () => {
|
||||
);
|
||||
|
||||
expect(result.sequence).toBe(2);
|
||||
const eventsAfterRetry = await runtime.runPromise(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(eventsAfterRetry.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
]);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
@@ -839,6 +801,7 @@ describe("OrchestrationEngine", () => {
|
||||
"project.created",
|
||||
"thread.created",
|
||||
]);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
|
||||
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
|
||||
expect(retryResult.sequence).toBe(4);
|
||||
@@ -861,7 +824,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
it("reconciles command state when append persists but projection fails", async () => {
|
||||
it("reconciles in-memory state when append persists but projection fails", async () => {
|
||||
type StoredEvent =
|
||||
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
|
||||
? A
|
||||
@@ -893,7 +856,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailProjection &&
|
||||
event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
|
||||
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
|
||||
) {
|
||||
shouldFailProjection = false;
|
||||
return Effect.fail(
|
||||
@@ -956,22 +919,20 @@ describe("OrchestrationEngine", () => {
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-sync-fail"),
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
title: "sync-after-failed-projection",
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("projection failed");
|
||||
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-sync-retry"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("already archived");
|
||||
const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
|
||||
const updatedThread = readModelAfterFailure.threads.find(
|
||||
(thread) => thread.id === "thread-sync",
|
||||
);
|
||||
expect(readModelAfterFailure.snapshotSequence).toBe(3);
|
||||
expect(updatedThread?.title).toBe("sync-after-failed-projection");
|
||||
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
@@ -34,7 +34,6 @@ import {
|
||||
OrchestrationCommandInvariantError,
|
||||
OrchestrationCommandPreviouslyRejectedError,
|
||||
type OrchestrationDispatchError,
|
||||
type OrchestrationProjectorDecodeError,
|
||||
} from "../Errors.ts";
|
||||
import { decideOrchestrationCommand } from "../decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
||||
@@ -78,25 +77,13 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
let commandReadModel = createEmptyReadModel(new Date().toISOString());
|
||||
let readModel = createEmptyReadModel(new Date().toISOString());
|
||||
|
||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
|
||||
const projectEventsOntoReadModel = (
|
||||
baseReadModel: OrchestrationReadModel,
|
||||
events: ReadonlyArray<OrchestrationEvent>,
|
||||
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
|
||||
Effect.gen(function* () {
|
||||
let nextReadModel = baseReadModel;
|
||||
for (const event of events) {
|
||||
nextReadModel = yield* projectEvent(nextReadModel, event);
|
||||
}
|
||||
return nextReadModel;
|
||||
});
|
||||
|
||||
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
|
||||
const dispatchStartSequence = commandReadModel.snapshotSequence;
|
||||
const dispatchStartSequence = readModel.snapshotSequence;
|
||||
const processingStartedAtMs = Date.now();
|
||||
const aggregateRef = commandToAggregateRef(envelope.command);
|
||||
const baseMetricAttributes = {
|
||||
@@ -111,7 +98,11 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
|
||||
let nextReadModel = readModel;
|
||||
for (const persistedEvent of persistedEvents) {
|
||||
nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
|
||||
}
|
||||
readModel = nextReadModel;
|
||||
|
||||
for (const persistedEvent of persistedEvents) {
|
||||
yield* PubSub.publish(eventPubSub, persistedEvent);
|
||||
@@ -144,18 +135,18 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
|
||||
const eventBase = yield* decideOrchestrationCommand({
|
||||
command: envelope.command,
|
||||
readModel: commandReadModel,
|
||||
readModel,
|
||||
});
|
||||
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
|
||||
const committedCommand = yield* sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const committedEvents: OrchestrationEvent[] = [];
|
||||
let nextCommandReadModel = commandReadModel;
|
||||
let nextReadModel = readModel;
|
||||
|
||||
for (const nextEvent of eventBases) {
|
||||
const savedEvent = yield* eventStore.append(nextEvent);
|
||||
nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
|
||||
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
|
||||
yield* projectionPipeline.projectEvent(savedEvent);
|
||||
committedEvents.push(savedEvent);
|
||||
}
|
||||
@@ -181,7 +172,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
return {
|
||||
committedEvents,
|
||||
lastSequence: lastSavedEvent.sequence,
|
||||
nextCommandReadModel,
|
||||
nextReadModel,
|
||||
} as const;
|
||||
}),
|
||||
)
|
||||
@@ -193,7 +184,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
commandReadModel = committedCommand.nextCommandReadModel;
|
||||
readModel = committedCommand.nextReadModel;
|
||||
for (const [index, event] of committedCommand.committedEvents.entries()) {
|
||||
yield* PubSub.publish(eventPubSub, event);
|
||||
if (index === 0) {
|
||||
@@ -251,7 +242,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
).pipe(
|
||||
Effect.annotateLogs({
|
||||
commandId: envelope.command.commandId,
|
||||
snapshotSequence: commandReadModel.snapshotSequence,
|
||||
snapshotSequence: readModel.snapshotSequence,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -264,7 +255,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
aggregateKind: aggregateRef.aggregateKind,
|
||||
aggregateId: aggregateRef.aggregateId,
|
||||
acceptedAt: new Date().toISOString(),
|
||||
resultSequence: commandReadModel.snapshotSequence,
|
||||
resultSequence: readModel.snapshotSequence,
|
||||
status: "rejected",
|
||||
error: error.message,
|
||||
})
|
||||
@@ -279,14 +270,17 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
|
||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||
yield* Effect.forkScoped(worker);
|
||||
yield* Effect.logDebug("orchestration engine started").pipe(
|
||||
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
|
||||
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
||||
);
|
||||
|
||||
const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
|
||||
Effect.sync((): OrchestrationReadModel => readModel);
|
||||
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive);
|
||||
|
||||
@@ -298,6 +292,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
getReadModel,
|
||||
readEvents,
|
||||
dispatch,
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
|
||||
@@ -739,31 +739,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const retainedTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
let latestTurnId: ProjectionTurn["turnId"] = null;
|
||||
let latestCheckpointTurnCount = -1;
|
||||
for (let index = 0; index < retainedTurns.length; index += 1) {
|
||||
const turn = retainedTurns[index];
|
||||
if (
|
||||
!turn ||
|
||||
turn.turnId === null ||
|
||||
turn.checkpointTurnCount === null ||
|
||||
turn.checkpointTurnCount > event.payload.turnCount
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (turn.checkpointTurnCount > latestCheckpointTurnCount) {
|
||||
latestCheckpointTurnCount = turn.checkpointTurnCount;
|
||||
latestTurnId = turn.turnId;
|
||||
}
|
||||
}
|
||||
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestTurnId,
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
|
||||
@@ -12,7 +12,6 @@ import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
@@ -1030,378 +1029,4 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-03T00:00:00.000Z',
|
||||
'2026-04-03T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-running',
|
||||
'2026-04-03T00:00:04.000Z',
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-03T00:00:02.000Z',
|
||||
'2026-04-03T00:00:03.000Z',
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-1',
|
||||
'turn-running',
|
||||
'message-user-2',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'running',
|
||||
'2026-04-03T00:00:30.000Z',
|
||||
'2026-04-03T00:00:30.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
),
|
||||
(
|
||||
'thread-1',
|
||||
'turn-completed',
|
||||
'message-user-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-assistant-1',
|
||||
'completed',
|
||||
'2026-04-03T00:00:05.000Z',
|
||||
'2026-04-03T00:00:06.000Z',
|
||||
'2026-04-03T00:00:20.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
|
||||
VALUES
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 3, '2026-04-03T00:00:40.000Z'),
|
||||
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 3, '2026-04-03T00:00:40.000Z')
|
||||
`;
|
||||
|
||||
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "running");
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(shellSnapshot.threads[0]?.latestTurn?.state, "running");
|
||||
|
||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "running");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps deleted project and thread tombstones in the command read model", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-deleted',
|
||||
'Deleted Project',
|
||||
'/tmp/deleted-project',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-05T00:00:00.000Z',
|
||||
'2026-04-05T00:00:01.000Z',
|
||||
'2026-04-05T00:00:02.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-deleted',
|
||||
'project-deleted',
|
||||
'Deleted Thread',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-deleted',
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-05T00:00:03.000Z',
|
||||
'2026-04-05T00:00:04.000Z',
|
||||
NULL,
|
||||
'2026-04-05T00:00:05.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES (
|
||||
'thread-deleted',
|
||||
'turn-deleted',
|
||||
'message-deleted-user',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-deleted-assistant',
|
||||
'completed',
|
||||
'2026-04-05T00:00:04.100Z',
|
||||
'2026-04-05T00:00:04.200Z',
|
||||
'2026-04-05T00:00:04.300Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
|
||||
assert.equal(commandReadModel.projects[0]?.id, asProjectId("project-deleted"));
|
||||
assert.equal(commandReadModel.projects[0]?.deletedAt, "2026-04-05T00:00:02.000Z");
|
||||
assert.equal(commandReadModel.threads[0]?.id, ThreadId.make("thread-deleted"));
|
||||
assert.equal(commandReadModel.threads[0]?.deletedAt, "2026-04-05T00:00:05.000Z");
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
|
||||
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "completed");
|
||||
|
||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
||||
assert.equal(fullSnapshot.threads[0]?.id, ThreadId.make("thread-deleted"));
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
|
||||
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "completed");
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.projects.length, 0);
|
||||
assert.equal(shellSnapshot.threads.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"ProjectionSnapshotQuery dedupes repository identity resolution by workspace root and skips deleted projects for shell snapshots",
|
||||
() => {
|
||||
const resolveCalls: string[] = [];
|
||||
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(RepositoryIdentityResolver, {
|
||||
resolve: (cwd: string) =>
|
||||
Effect.sync(() => {
|
||||
resolveCalls.push(cwd);
|
||||
return {
|
||||
canonicalKey: `github.com/acme${cwd}`,
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: `https://github.com/acme${cwd}.git`,
|
||||
},
|
||||
rootPath: cwd,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'project-1',
|
||||
'Shared Project 1',
|
||||
'/tmp/shared-root',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-04T00:00:00.000Z',
|
||||
'2026-04-04T00:00:01.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'project-2',
|
||||
'Shared Project 2',
|
||||
'/tmp/shared-root',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-04T00:00:02.000Z',
|
||||
'2026-04-04T00:00:03.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'project-3',
|
||||
'Deleted Project',
|
||||
'/tmp/deleted-root',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-04T00:00:04.000Z',
|
||||
'2026-04-04T00:00:05.000Z',
|
||||
'2026-04-04T00:00:06.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/shared-root"]);
|
||||
assert.equal(shellSnapshot.projects.length, 2);
|
||||
assert.equal(shellSnapshot.projects[0]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
|
||||
assert.equal(shellSnapshot.projects[1]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
|
||||
|
||||
resolveCalls.length = 0;
|
||||
|
||||
const fullSnapshot = yield* snapshotQuery.getSnapshot();
|
||||
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/deleted-root", "/tmp/shared-root"]);
|
||||
assert.equal(fullSnapshot.projects.length, 3);
|
||||
assert.equal(fullSnapshot.projects[2]?.repositoryIdentity?.rootPath, "/tmp/deleted-root");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
@@ -219,20 +219,6 @@ function mapProjectShellRow(
|
||||
};
|
||||
}
|
||||
|
||||
function mapProposedPlanRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,
|
||||
): OrchestrationProposedPlan {
|
||||
return {
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -244,37 +230,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
|
||||
const repositoryIdentityResolutionConcurrency = 4;
|
||||
const resolveRepositoryIdentitiesForProjects = Effect.fn(
|
||||
"ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects",
|
||||
)(function* (
|
||||
projectRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>>,
|
||||
options?: {
|
||||
readonly includeDeleted?: boolean;
|
||||
},
|
||||
) {
|
||||
const filteredProjectRows =
|
||||
options?.includeDeleted === true
|
||||
? projectRows
|
||||
: projectRows.filter((row) => row.deletedAt === null);
|
||||
const uniqueWorkspaceRoots = [...new Set(filteredProjectRows.map((row) => row.workspaceRoot))];
|
||||
const repositoryIdentityByWorkspaceRoot = new Map(
|
||||
yield* Effect.forEach(
|
||||
uniqueWorkspaceRoots,
|
||||
(workspaceRoot) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [workspaceRoot, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
|
||||
return new Map(
|
||||
filteredProjectRows.map((row) => [
|
||||
row.projectId,
|
||||
repositoryIdentityByWorkspaceRoot.get(row.workspaceRoot) ?? null,
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
const listProjectRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
@@ -380,6 +335,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
FROM projection_thread_activities
|
||||
ORDER BY
|
||||
thread_id ASC,
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
@@ -433,46 +389,18 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.latest_turn_id IS NOT NULL
|
||||
ORDER BY turns.thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listActiveLatestTurnRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.deleted_at IS NULL
|
||||
AND threads.latest_turn_id IS NOT NULL
|
||||
ORDER BY turns.thread_id ASC
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
state,
|
||||
requested_at AS "requestedAt",
|
||||
started_at AS "startedAt",
|
||||
completed_at AS "completedAt",
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -666,6 +594,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
@@ -963,9 +892,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
|
||||
projectRows,
|
||||
{ includeDeleted: true },
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
|
||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||
@@ -1023,199 +958,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getCommandReadModel: ProjectionSnapshotQueryShape["getCommandReadModel"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:query",
|
||||
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(
|
||||
([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
Effect.sync(() => {
|
||||
let updatedAt: string | null = null;
|
||||
const projects: OrchestrationProject[] = [];
|
||||
const threads: OrchestrationThread[] = [];
|
||||
|
||||
for (let index = 0; index < projectRows.length; index += 1) {
|
||||
const row = projectRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
projects.push({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
});
|
||||
}
|
||||
for (let index = 0; index < threadRows.length; index += 1) {
|
||||
const row = threadRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (let index = 0; index < proposedPlanRows.length; index += 1) {
|
||||
const row = proposedPlanRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (let index = 0; index < sessionRows.length; index += 1) {
|
||||
const row = sessionRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (let index = 0; index < latestTurnRows.length; index += 1) {
|
||||
const row = latestTurnRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||
if (row.startedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||
}
|
||||
if (row.completedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
}
|
||||
}
|
||||
for (let index = 0; index < stateRows.length; index += 1) {
|
||||
const row = stateRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
||||
for (let index = 0; index < latestTurnRows.length; index += 1) {
|
||||
const row = latestTurnRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
latestTurnByThread.set(row.threadId, mapLatestTurn(row));
|
||||
}
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const sessionByThread = new Map<string, OrchestrationSession>();
|
||||
|
||||
for (let index = 0; index < sessionRows.length; index += 1) {
|
||||
const row = sessionRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
sessionByThread.set(row.threadId, mapSessionRow(row));
|
||||
}
|
||||
|
||||
for (let index = 0; index < proposedPlanRows.length; index += 1) {
|
||||
const row = proposedPlanRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
|
||||
threadProposedPlans.push(mapProposedPlanRow(row));
|
||||
proposedPlansByThread.set(row.threadId, threadProposedPlans);
|
||||
}
|
||||
|
||||
for (let index = 0; index < threadRows.length; index += 1) {
|
||||
const row = threadRows[index];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
threads.push({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
} satisfies OrchestrationReadModel;
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => {
|
||||
if (isPersistenceError(error)) {
|
||||
return error;
|
||||
}
|
||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getCommandReadModel:query")(error);
|
||||
}),
|
||||
);
|
||||
|
||||
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
@@ -1244,7 +986,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listActiveLatestTurnRows(undefined).pipe(
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
@@ -1288,7 +1030,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
const latestTurnByThread = new Map(
|
||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||
);
|
||||
@@ -1346,19 +1097,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshotSequence:query",
|
||||
"ProjectionSnapshotQuery.getSnapshotSequence:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((stateRows) => ({
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
})),
|
||||
);
|
||||
|
||||
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
||||
readProjectionCounts(undefined).pipe(
|
||||
Effect.mapError(
|
||||
@@ -1638,7 +1376,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
|
||||
proposedPlans: proposedPlanRows.map((row) => ({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
})),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
@@ -1676,10 +1422,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
getCommandReadModel,
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getSnapshotSequence,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
|
||||
@@ -45,7 +45,6 @@ import {
|
||||
} from "./ProviderCommandReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
@@ -80,7 +79,7 @@ async function waitFor(
|
||||
|
||||
describe("ProviderCommandReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderCommandReactor | ProjectionSnapshotQuery,
|
||||
OrchestrationEngineService | ProviderCommandReactor,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -319,13 +318,8 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
@@ -354,7 +348,6 @@ describe("ProviderCommandReactor", () => {
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
@@ -389,7 +382,6 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -439,7 +431,7 @@ describe("ProviderCommandReactor", () => {
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
@@ -484,13 +476,13 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Generated title"
|
||||
);
|
||||
});
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Generated title");
|
||||
});
|
||||
@@ -530,7 +522,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Keep this custom title");
|
||||
});
|
||||
@@ -574,14 +566,14 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Reconnect spinner resume bug"
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
||||
});
|
||||
@@ -910,7 +902,7 @@ describe("ProviderCommandReactor", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.providerName).toBe("claudeAgent");
|
||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
|
||||
@@ -1022,7 +1014,7 @@ describe("ProviderCommandReactor", () => {
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
});
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
|
||||
});
|
||||
@@ -1213,7 +1205,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
@@ -1247,7 +1239,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
@@ -1350,7 +1342,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
@@ -1360,7 +1352,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
@@ -1412,7 +1404,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1424,7 +1416,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("codex");
|
||||
@@ -1483,7 +1475,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1493,7 +1485,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(0);
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
@@ -1647,7 +1639,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1657,7 +1649,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(0);
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
@@ -1818,7 +1810,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
@@ -1826,7 +1818,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -1927,7 +1919,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
@@ -1935,7 +1927,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -1991,7 +1983,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session).not.toBeNull();
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type ModelSelection,
|
||||
type OrchestrationEvent,
|
||||
ProviderDriverKind,
|
||||
type ProjectId,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
type ProviderSession,
|
||||
@@ -23,7 +22,6 @@ import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
@@ -169,7 +167,6 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
@@ -270,16 +267,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getProjectShellById(projectId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
return readModel.threads.find((entry) => entry.id === threadId);
|
||||
});
|
||||
|
||||
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
|
||||
@@ -289,7 +279,8 @@ const make = Effect.gen(function* () {
|
||||
readonly modelSelection?: ModelSelection;
|
||||
},
|
||||
) {
|
||||
const thread = yield* resolveThread(threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||
}
|
||||
@@ -384,10 +375,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
}
|
||||
const project = yield* resolveProject(thread.projectId);
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: project ? [project] : [],
|
||||
projects: readModel.projects,
|
||||
});
|
||||
|
||||
const startProviderSession = (input?: {
|
||||
@@ -692,11 +682,10 @@ const make = Effect.gen(function* () {
|
||||
const isFirstUserMessageTurn =
|
||||
thread.messages.filter((entry) => entry.role === "user").length === 1;
|
||||
if (isFirstUserMessageTurn) {
|
||||
const project = yield* resolveProject(thread.projectId);
|
||||
const generationCwd =
|
||||
resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: project ? [project] : [],
|
||||
projects: (yield* orchestrationEngine.getReadModel()).projects,
|
||||
}) ?? process.cwd();
|
||||
const generationInput = {
|
||||
messageText: message.text,
|
||||
@@ -830,16 +819,20 @@ const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
Effect.gen(function* () {
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
|
||||
if (!isUnknownPendingApprovalRequestError(cause)) return;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -36,9 +36,11 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -152,23 +154,16 @@ function createProviderServiceHarness() {
|
||||
};
|
||||
}
|
||||
|
||||
type ProviderRuntimeTestReadModel = OrchestrationReadModel;
|
||||
type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
async function waitForThread(
|
||||
readModel: () => Promise<ProviderRuntimeTestReadModel>,
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: ProviderRuntimeTestThread) => boolean,
|
||||
timeoutMs = 2000,
|
||||
threadId: ThreadId = asThreadId("thread-1"),
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<ProviderRuntimeTestThread> => {
|
||||
const snapshot = await readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === threadId);
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -181,9 +176,16 @@ async function waitForThread(
|
||||
return poll();
|
||||
}
|
||||
|
||||
type ProviderRuntimeTestReadModel = OrchestrationReadModel;
|
||||
type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
describe("ProviderRuntimeIngestion", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery,
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -221,13 +223,8 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
@@ -236,7 +233,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
|
||||
@@ -303,7 +299,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
emit: provider.emit,
|
||||
setProviderSession: provider.setSession,
|
||||
drain,
|
||||
@@ -324,7 +319,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "running" && thread.session?.activeTurnId === "turn-1",
|
||||
);
|
||||
|
||||
@@ -342,7 +337,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -369,7 +364,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
let thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.session?.status === "running" && entry.session?.activeTurnId === null,
|
||||
);
|
||||
expect(thread.session?.status).toBe("running");
|
||||
@@ -388,7 +383,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -409,7 +404,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "stopped" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -430,7 +425,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -454,7 +449,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-midturn-lifecycle",
|
||||
@@ -476,7 +471,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await harness.readModel();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
|
||||
@@ -492,7 +487,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -529,7 +524,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-claude-placeholder",
|
||||
@@ -546,7 +541,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -565,7 +560,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
|
||||
);
|
||||
@@ -581,7 +576,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await harness.readModel();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||
@@ -597,7 +592,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -616,7 +611,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-guarded-main",
|
||||
@@ -633,7 +628,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await harness.readModel();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||
@@ -649,7 +644,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -698,7 +693,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-1" && !message.streaming,
|
||||
@@ -730,7 +725,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-no-delta" && !message.streaming,
|
||||
@@ -769,7 +764,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
|
||||
),
|
||||
@@ -824,7 +819,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
|
||||
),
|
||||
@@ -866,7 +861,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
|
||||
),
|
||||
@@ -899,7 +894,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-1:turn:turn-plan-final",
|
||||
@@ -1014,7 +1009,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1055,7 +1050,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
const sourceThreadBeforeStart = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1081,7 +1076,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadAfterStart = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1163,7 +1158,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
|
||||
2_000,
|
||||
@@ -1183,7 +1178,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1234,7 +1229,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterRejectedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
@@ -1345,7 +1340,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1406,7 +1401,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
@@ -1432,7 +1427,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-plan-buffer",
|
||||
);
|
||||
@@ -1471,7 +1466,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-1:turn:turn-plan-buffer",
|
||||
@@ -1497,7 +1492,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
|
||||
);
|
||||
@@ -1517,7 +1512,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await harness.readModel();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
midThread?.messages.some(
|
||||
@@ -1539,7 +1534,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered" && !message.streaming,
|
||||
@@ -1565,7 +1560,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-flush",
|
||||
@@ -1598,7 +1593,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-flush" &&
|
||||
@@ -1625,7 +1620,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
|
||||
@@ -1664,7 +1659,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-user-input-flush" &&
|
||||
@@ -1693,7 +1688,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
|
||||
@@ -1726,7 +1721,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
),
|
||||
@@ -1755,7 +1750,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-append",
|
||||
@@ -1788,7 +1783,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) =>
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append" &&
|
||||
@@ -1824,7 +1819,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append:segment:1" &&
|
||||
@@ -1887,7 +1882,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-request-segment",
|
||||
@@ -1920,7 +1915,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) =>
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment" &&
|
||||
@@ -1956,7 +1951,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment:segment:1" &&
|
||||
@@ -2009,7 +2004,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-streaming-mode"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-mode",
|
||||
@@ -2029,7 +2024,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const liveThread = await waitForThread(harness.readModel, (entry) =>
|
||||
const liveThread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-mode" &&
|
||||
@@ -2057,7 +2052,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const finalThread = await waitForThread(harness.readModel, (entry) =>
|
||||
const finalThread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||
@@ -2084,7 +2079,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffer-spill"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffer-spill",
|
||||
@@ -2117,7 +2112,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||
@@ -2145,7 +2140,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-complete-dedup",
|
||||
@@ -2190,7 +2185,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "ready" &&
|
||||
thread.session?.activeTurnId === null &&
|
||||
@@ -2248,7 +2243,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
@@ -2258,7 +2253,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -2300,7 +2295,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-3" &&
|
||||
@@ -2326,7 +2321,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
@@ -2371,7 +2366,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "running" &&
|
||||
entry.session?.activeTurnId === "turn-warning" &&
|
||||
@@ -2420,7 +2415,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -2513,7 +2508,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.title === "Renamed by provider" &&
|
||||
entry.activities.some(
|
||||
@@ -2600,7 +2595,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2652,7 +2647,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2702,7 +2697,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2737,7 +2732,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
|
||||
),
|
||||
@@ -2807,7 +2802,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "task.completed",
|
||||
@@ -2898,7 +2893,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.requested",
|
||||
@@ -2957,7 +2952,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-after-failure" &&
|
||||
|
||||
@@ -4,16 +4,12 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -23,9 +19,9 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderRuntimeIngestionService,
|
||||
type ProviderRuntimeIngestionShape,
|
||||
@@ -81,82 +77,6 @@ function sameId(left: string | null | undefined, right: string | null | undefine
|
||||
return left === right;
|
||||
}
|
||||
|
||||
function hasAssistantMessageForTurn(
|
||||
messages: ReadonlyArray<OrchestrationMessage>,
|
||||
turnId: TurnId,
|
||||
options?: { readonly streamingOnly?: boolean },
|
||||
): boolean {
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const message = messages[index];
|
||||
if (!message) {
|
||||
continue;
|
||||
}
|
||||
if (message.role !== "assistant" || message.turnId !== turnId) {
|
||||
continue;
|
||||
}
|
||||
if (options?.streamingOnly === true && !message.streaming) {
|
||||
continue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function findMessageById(
|
||||
messages: ReadonlyArray<OrchestrationMessage>,
|
||||
messageId: MessageId,
|
||||
): OrchestrationMessage | undefined {
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const message = messages[index];
|
||||
if (message?.id === messageId) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findProposedPlanById(
|
||||
proposedPlans: ReadonlyArray<
|
||||
Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
||||
>,
|
||||
planId: string,
|
||||
):
|
||||
| Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
||||
| undefined {
|
||||
for (let index = 0; index < proposedPlans.length; index += 1) {
|
||||
const proposedPlan = proposedPlans[index];
|
||||
if (proposedPlan?.id === planId) {
|
||||
return proposedPlan;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function hasCheckpointForTurn(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
turnId: TurnId,
|
||||
): boolean {
|
||||
for (let index = 0; index < checkpoints.length; index += 1) {
|
||||
if (checkpoints[index]?.turnId === turnId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function maxCheckpointTurnCount(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): number {
|
||||
let maxTurnCount = 0;
|
||||
for (let index = 0; index < checkpoints.length; index += 1) {
|
||||
const checkpoint = checkpoints[index];
|
||||
if (checkpoint && checkpoint.checkpointTurnCount > maxTurnCount) {
|
||||
maxTurnCount = checkpoint.checkpointTurnCount;
|
||||
}
|
||||
}
|
||||
return maxTurnCount;
|
||||
}
|
||||
|
||||
function truncateDetail(value: string, limit = 180): string {
|
||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||
}
|
||||
@@ -602,7 +522,6 @@ function runtimeEventToActivities(
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
@@ -634,16 +553,20 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
||||
});
|
||||
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadShellById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return false;
|
||||
}
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return false;
|
||||
}
|
||||
return isGitRepository(workspaceCwd);
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
|
||||
@@ -994,7 +917,7 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
|
||||
const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
@@ -1147,7 +1070,8 @@ const make = Effect.gen(function* () {
|
||||
implementationThreadId: ThreadId,
|
||||
implementedAt: string,
|
||||
) {
|
||||
const sourceThread = yield* resolveThreadDetail(sourceThreadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
|
||||
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
|
||||
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
|
||||
return;
|
||||
@@ -1172,19 +1096,10 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const thread = yield* resolveThreadShell(event.threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
if (!thread) return;
|
||||
|
||||
let loadedThreadDetail: OrchestrationThread | null | undefined;
|
||||
const getLoadedThreadDetail = () =>
|
||||
Effect.gen(function* () {
|
||||
if (loadedThreadDetail !== undefined) {
|
||||
return loadedThreadDetail;
|
||||
}
|
||||
loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;
|
||||
return loadedThreadDetail;
|
||||
});
|
||||
|
||||
const now = event.createdAt;
|
||||
const eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
@@ -1362,7 +1277,6 @@ const make = Effect.gen(function* () {
|
||||
? toTurnId(event.turnId)
|
||||
: undefined;
|
||||
if (pauseForUserTurnId) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||
@@ -1393,11 +1307,10 @@ const make = Effect.gen(function* () {
|
||||
event.type === "request.opened"
|
||||
? "assistant-delta-finalize-on-request-opened"
|
||||
: "assistant-delta-finalize-on-user-input-requested",
|
||||
hasProjectedMessage:
|
||||
detailedThread !== null &&
|
||||
hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {
|
||||
streamingOnly: true,
|
||||
}),
|
||||
hasProjectedMessage: thread.messages.some(
|
||||
(entry) =>
|
||||
entry.role === "assistant" && entry.turnId === pauseForUserTurnId && entry.streaming,
|
||||
),
|
||||
flushedMessageIds,
|
||||
});
|
||||
}
|
||||
@@ -1426,19 +1339,21 @@ const make = Effect.gen(function* () {
|
||||
: undefined;
|
||||
|
||||
if (assistantCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const activeAssistantMessageId = turnId
|
||||
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
|
||||
: Option.none<MessageId>();
|
||||
const hasAssistantMessagesForTurn =
|
||||
turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;
|
||||
turnId !== undefined
|
||||
? thread.messages.some((entry) => entry.role === "assistant" && entry.turnId === turnId)
|
||||
: false;
|
||||
const assistantMessageId = Option.getOrElse(
|
||||
activeAssistantMessageId,
|
||||
() => assistantCompletion.messageId,
|
||||
);
|
||||
const existingAssistantMessage = findMessageById(messages, assistantMessageId);
|
||||
const existingAssistantMessage = thread.messages.find(
|
||||
(entry) => entry.id === assistantMessageId,
|
||||
);
|
||||
const shouldApplyFallbackCompletionText =
|
||||
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
|
||||
|
||||
@@ -1478,11 +1393,10 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (proposedPlanCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: detailedThread?.proposedPlans ?? [],
|
||||
threadProposedPlans: thread.proposedPlans,
|
||||
planId: proposedPlanCompletion.planId,
|
||||
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
|
||||
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
|
||||
@@ -1491,9 +1405,6 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const proposedPlans = detailedThread?.proposedPlans ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
|
||||
@@ -1508,7 +1419,9 @@ const make = Effect.gen(function* () {
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete-finalize",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
||||
hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
|
||||
hasProjectedMessage: thread.messages.some(
|
||||
(entry) => entry.id === assistantMessageId,
|
||||
),
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
@@ -1518,7 +1431,7 @@ const make = Effect.gen(function* () {
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: proposedPlans,
|
||||
threadProposedPlans: thread.proposedPlans,
|
||||
planId: proposedPlanIdForTurn(thread.id, turnId),
|
||||
turnId,
|
||||
updatedAt: now,
|
||||
@@ -1570,24 +1483,21 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.diff.updated") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const checkpointContext = turnId
|
||||
? yield* projectionSnapshotQuery
|
||||
.getThreadCheckpointContext(thread.id)
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
: undefined;
|
||||
const workspaceCwd =
|
||||
checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;
|
||||
if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {
|
||||
if (turnId && (yield* isGitRepoForThread(thread.id))) {
|
||||
// Skip if a checkpoint already exists for this turn. A real
|
||||
// (non-placeholder) capture from CheckpointReactor should not
|
||||
// be clobbered, and dispatching a duplicate placeholder for the
|
||||
// same turnId would produce an unstable checkpointTurnCount.
|
||||
if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) {
|
||||
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
|
||||
// Already tracked; no-op.
|
||||
} else {
|
||||
const assistantMessageId = MessageId.make(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
(max, c) => Math.max(max, c.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: providerCommandId(event, "thread-turn-diff-complete"),
|
||||
@@ -1598,7 +1508,7 @@ const make = Effect.gen(function* () {
|
||||
status: "missing",
|
||||
files: [],
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,
|
||||
checkpointTurnCount: maxTurnCount + 1,
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
*
|
||||
* @module OrchestrationEngineService
|
||||
*/
|
||||
import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
@@ -21,6 +25,13 @@ import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
|
||||
* OrchestrationEngineShape - Service API for orchestration command and event flow.
|
||||
*/
|
||||
export interface OrchestrationEngineShape {
|
||||
/**
|
||||
* Read the current in-memory orchestration read model.
|
||||
*
|
||||
* @returns Effect containing the latest read model.
|
||||
*/
|
||||
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
|
||||
|
||||
/**
|
||||
* Replay persisted orchestration events from an exclusive sequence cursor.
|
||||
*
|
||||
@@ -59,7 +70,7 @@ export interface OrchestrationEngineShape {
|
||||
* ```ts
|
||||
* const program = Effect.gen(function* () {
|
||||
* const engine = yield* OrchestrationEngineService
|
||||
* return yield* engine.dispatch(command)
|
||||
* return yield* engine.getReadModel()
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
|
||||
@@ -28,10 +28,6 @@ export interface ProjectionSnapshotCounts {
|
||||
readonly threadCount: number;
|
||||
}
|
||||
|
||||
export interface ProjectionSnapshotSequence {
|
||||
readonly snapshotSequence: number;
|
||||
}
|
||||
|
||||
export interface ProjectionThreadCheckpointContext {
|
||||
readonly threadId: ThreadId;
|
||||
readonly projectId: ProjectId;
|
||||
@@ -44,15 +40,6 @@ export interface ProjectionThreadCheckpointContext {
|
||||
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
|
||||
*/
|
||||
export interface ProjectionSnapshotQueryShape {
|
||||
/**
|
||||
* Read the lightweight command snapshot used to bootstrap the in-memory
|
||||
* orchestration engine without hydrating message/activity/checkpoint bodies.
|
||||
*/
|
||||
readonly getCommandReadModel: () => Effect.Effect<
|
||||
OrchestrationReadModel,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read the latest orchestration projection snapshot.
|
||||
*
|
||||
@@ -72,15 +59,6 @@ export interface ProjectionSnapshotQueryShape {
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read the latest projection snapshot sequence without hydrating read-model
|
||||
* entities.
|
||||
*/
|
||||
readonly getSnapshotSequence: () => Effect.Effect<
|
||||
ProjectionSnapshotSequence,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read aggregate projection counts without hydrating the full read model.
|
||||
*/
|
||||
|
||||
@@ -41,7 +41,6 @@ import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingAppro
|
||||
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
|
||||
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
|
||||
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
|
||||
import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -82,7 +81,6 @@ export const migrationEntries = [
|
||||
[26, "CanonicalizeModelSelectionOptions", Migration0026],
|
||||
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
|
||||
[28, "ProjectionThreadSessionInstanceId", Migration0028],
|
||||
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("029_ProjectionThreadDetailOrderingIndexes", (it) => {
|
||||
it.effect("creates indexes matching thread detail ordering queries", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 28 });
|
||||
yield* runMigrations({ toMigrationInclusive: 29 });
|
||||
|
||||
const activityIndexes = yield* sql<{
|
||||
readonly seq: number;
|
||||
readonly name: string;
|
||||
readonly unique: number;
|
||||
readonly origin: string;
|
||||
readonly partial: number;
|
||||
}>`
|
||||
PRAGMA index_list(projection_thread_activities)
|
||||
`;
|
||||
assert.ok(
|
||||
activityIndexes.some(
|
||||
(index) => index.name === "idx_projection_thread_activities_thread_sequence_created_id",
|
||||
),
|
||||
);
|
||||
|
||||
const activityIndexColumns = yield* sql<{
|
||||
readonly seqno: number;
|
||||
readonly cid: number;
|
||||
readonly name: string;
|
||||
}>`
|
||||
PRAGMA index_info('idx_projection_thread_activities_thread_sequence_created_id')
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
activityIndexColumns.map((column) => column.name),
|
||||
["thread_id", "sequence", "created_at", "activity_id"],
|
||||
);
|
||||
|
||||
const messageIndexes = yield* sql<{
|
||||
readonly seq: number;
|
||||
readonly name: string;
|
||||
readonly unique: number;
|
||||
readonly origin: string;
|
||||
readonly partial: number;
|
||||
}>`
|
||||
PRAGMA index_list(projection_thread_messages)
|
||||
`;
|
||||
assert.ok(
|
||||
messageIndexes.some(
|
||||
(index) => index.name === "idx_projection_thread_messages_thread_created_id",
|
||||
),
|
||||
);
|
||||
|
||||
const messageIndexColumns = yield* sql<{
|
||||
readonly seqno: number;
|
||||
readonly cid: number;
|
||||
readonly name: string;
|
||||
}>`
|
||||
PRAGMA index_info('idx_projection_thread_messages_thread_created_id')
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
messageIndexColumns.map((column) => column.name),
|
||||
["thread_id", "created_at", "message_id"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence_created_id
|
||||
ON projection_thread_activities(thread_id, sequence, created_at, activity_id)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created_id
|
||||
ON projection_thread_messages(thread_id, created_at, message_id)
|
||||
`;
|
||||
});
|
||||
@@ -1,52 +1,53 @@
|
||||
import { ProjectId, type OrchestrationProject } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { Effect, Layer, Stream } from "effect";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
|
||||
|
||||
const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModelSelection: null,
|
||||
scripts,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
|
||||
Effect.succeed(
|
||||
workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
|
||||
),
|
||||
getProjectShellById: (projectId) =>
|
||||
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
});
|
||||
const emptySnapshot = (
|
||||
scripts: OrchestrationReadModel["projects"][number]["scripts"],
|
||||
): OrchestrationReadModel =>
|
||||
({
|
||||
snapshotSequence: 1,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModelSelection: null,
|
||||
scripts,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
providerSessions: [],
|
||||
providerStatuses: [],
|
||||
pendingApprovals: [],
|
||||
latestTurnByThreadId: {},
|
||||
}) as unknown as OrchestrationReadModel;
|
||||
|
||||
describe("ProjectSetupScriptRunner", () => {
|
||||
it("returns no-script when no setup script exists", async () => {
|
||||
const open = vi.fn();
|
||||
const write = vi.fn();
|
||||
const project = makeProject([]);
|
||||
const runner = await Effect.runPromise(
|
||||
Effect.service(ProjectSetupScriptRunner).pipe(
|
||||
Effect.provide(
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.succeed(emptySnapshot([])),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.die(new Error("unused")),
|
||||
streamDomainEvents: Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
@@ -92,20 +93,29 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
}),
|
||||
);
|
||||
const write = vi.fn(() => Effect.void);
|
||||
const project = makeProject([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]);
|
||||
const runner = await Effect.runPromise(
|
||||
Effect.service(ProjectSetupScriptRunner).pipe(
|
||||
Effect.provide(
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
getReadModel: () =>
|
||||
Effect.succeed(
|
||||
emptySnapshot([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.die(new Error("unused")),
|
||||
streamDomainEvents: Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { ProjectId } from "@t3tools/contracts";
|
||||
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import {
|
||||
type ProjectSetupScriptRunnerShape,
|
||||
@@ -10,21 +9,18 @@ import {
|
||||
} from "../Services/ProjectSetupScriptRunner.ts";
|
||||
|
||||
const makeProjectSetupScriptRunner = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
|
||||
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const project =
|
||||
(input.projectId
|
||||
? yield* projectionSnapshotQuery
|
||||
.getProjectShellById(ProjectId.make(input.projectId))
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
? readModel.projects.find((entry) => entry.id === input.projectId)
|
||||
: null) ??
|
||||
(input.projectCwd
|
||||
? yield* projectionSnapshotQuery
|
||||
.getActiveProjectByWorkspaceRoot(input.projectCwd)
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd)
|
||||
: null) ??
|
||||
null;
|
||||
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import {
|
||||
AcpRegistrySettings,
|
||||
ProviderDriverKind,
|
||||
TextGenerationError,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeGenericAcpAdapter } from "../Layers/GenericAcpAdapter.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
type ProviderInstance,
|
||||
} from "../ProviderDriver.ts";
|
||||
import {
|
||||
buildServerProvider,
|
||||
providerModelsFromSettings,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
|
||||
|
||||
export type AcpRegistryDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
|
||||
const unsupportedTextGeneration = (operation: string) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Generic ACP providers do not support git text generation yet.",
|
||||
}),
|
||||
);
|
||||
|
||||
const makeTextGeneration = () => ({
|
||||
generateCommitMessage: () => unsupportedTextGeneration("generateCommitMessage"),
|
||||
generatePrContent: () => unsupportedTextGeneration("generatePrContent"),
|
||||
generateBranchName: () => unsupportedTextGeneration("generateBranchName"),
|
||||
generateThreadTitle: () => unsupportedTextGeneration("generateThreadTitle"),
|
||||
});
|
||||
|
||||
function withIdentity(input: {
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) {
|
||||
return (snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
...snapshot,
|
||||
instanceId: input.instanceId,
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
}
|
||||
|
||||
function initialSnapshot(settings: AcpRegistrySettings): ServerProviderDraft {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const command = settings.command.trim();
|
||||
const enabled = settings.enabled && command.length > 0;
|
||||
return buildServerProvider({
|
||||
presentation: {
|
||||
displayName: "ACP Registry",
|
||||
badgeLabel: "ACP",
|
||||
showInteractionModeToggle: true,
|
||||
},
|
||||
enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[{ slug: "default", name: "Default", isCustom: false, capabilities: null }],
|
||||
DRIVER_KIND,
|
||||
settings.customModels,
|
||||
{ optionDescriptors: [] },
|
||||
),
|
||||
probe: {
|
||||
installed: enabled,
|
||||
version: null,
|
||||
status: enabled ? "ready" : "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: enabled ? "ACP provider configured." : "Configure a launch command to enable.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDriverEnv> = {
|
||||
driverKind: DRIVER_KIND,
|
||||
metadata: {
|
||||
displayName: "ACP Registry",
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: AcpRegistrySettings,
|
||||
defaultConfig: (): AcpRegistrySettings => Schema.decodeSync(AcpRegistrySettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const effectiveConfig = { ...config, enabled: enabled && config.enabled };
|
||||
const effectiveIconUrl = iconUrl ?? effectiveConfig.iconUrl;
|
||||
const processEnv = {
|
||||
...effectiveConfig.env,
|
||||
...mergeProviderInstanceEnvironment(environment),
|
||||
};
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
instanceId,
|
||||
});
|
||||
const stamp = withIdentity({
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl: effectiveIconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
|
||||
const adapter = yield* makeGenericAcpAdapter(
|
||||
{
|
||||
enabled: effectiveConfig.enabled,
|
||||
command: effectiveConfig.command || "acp",
|
||||
args: effectiveConfig.args,
|
||||
},
|
||||
{
|
||||
provider: DRIVER_KIND,
|
||||
instanceId,
|
||||
environment: processEnv,
|
||||
readyReason: "ACP session ready",
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
},
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<AcpRegistrySettings>({
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stamp(initialSnapshot(settings)),
|
||||
checkProvider: Effect.succeed(stamp(initialSnapshot(effectiveConfig))),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build ACP Registry snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl: effectiveIconUrl,
|
||||
enabled: effectiveConfig.enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
textGeneration: makeTextGeneration(),
|
||||
} satisfies ProviderInstance;
|
||||
}),
|
||||
};
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
@@ -35,43 +34,15 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.local/bin/claude") ||
|
||||
normalized.endsWith("/.local/bin/claude.exe") ||
|
||||
normalized.includes("/.local/share/claude/")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@anthropic-ai/claude-code",
|
||||
homebrewFormula: "claude-code",
|
||||
nativeUpdate: {
|
||||
executable: "claude",
|
||||
args: ["update"],
|
||||
lockKey: "claude-native",
|
||||
isCommandPath: isClaudeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -81,6 +52,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -89,6 +61,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -100,11 +73,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
},
|
||||
configSchema: ClaudeSettings,
|
||||
defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -112,15 +84,12 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
instanceId,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey,
|
||||
});
|
||||
|
||||
@@ -155,17 +124,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
@@ -188,6 +151,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
},
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
@@ -36,11 +35,6 @@ import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import {
|
||||
codexContinuationIdentity,
|
||||
materializeCodexShadowHome,
|
||||
@@ -49,12 +43,6 @@ import {
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
homebrewFormula: "codex",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
|
||||
/**
|
||||
* Services the driver needs to materialize an instance. Surfaced as the
|
||||
@@ -64,7 +52,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
export type CodexDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -80,6 +67,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -88,6 +76,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -99,10 +88,9 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
},
|
||||
configSchema: CodexSettings,
|
||||
defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
@@ -111,6 +99,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
yield* materializeCodexShadowHome(homeLayout).pipe(
|
||||
@@ -129,10 +118,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
enabled,
|
||||
homePath: homeLayout.effectiveHomePath ?? "",
|
||||
} satisfies CodexSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
|
||||
// channels at construction time — their failure modes are all on the
|
||||
@@ -156,17 +141,11 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const snapshot = yield* makeManagedServerProvider<CodexSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
@@ -186,6 +165,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -35,28 +34,13 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
}),
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -66,6 +50,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -74,6 +59,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -85,12 +71,11 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
},
|
||||
configSchema: CursorSettings,
|
||||
defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -101,13 +86,10 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeCursorAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
@@ -124,7 +106,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<CursorSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
@@ -139,10 +120,8 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
settings,
|
||||
environment: processEnv,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
@@ -163,6 +142,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
@@ -35,40 +34,13 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.opencode/bin/opencode") ||
|
||||
normalized.endsWith("/.opencode/bin/opencode.exe")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "opencode-ai",
|
||||
homebrewFormula: "anomalyco/tap/opencode",
|
||||
nativeUpdate: {
|
||||
executable: "opencode",
|
||||
args: ["upgrade"],
|
||||
lockKey: "opencode-native",
|
||||
isCommandPath: isOpenCodeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
@@ -79,6 +51,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -87,6 +60,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -98,11 +72,10 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
},
|
||||
configSchema: OpenCodeSettings,
|
||||
defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -113,13 +86,10 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
|
||||
instanceId,
|
||||
@@ -135,17 +105,11 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
@@ -165,6 +129,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
|
||||
|
||||
@@ -12,7 +12,6 @@ import type {
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
createModelCapabilities,
|
||||
@@ -30,10 +29,6 @@ import {
|
||||
type CommandResult,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("cursor");
|
||||
@@ -1221,67 +1216,42 @@ export const enrichCursorSnapshot = (input: {
|
||||
readonly settings: CursorSettings;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
const { settings, snapshot, publishSnapshot } = input;
|
||||
const stampIdentity = input.stampIdentity ?? ((value) => value);
|
||||
|
||||
const enrichVersionAdvisory = enrichProviderSnapshotWithVersionAdvisory(
|
||||
snapshot,
|
||||
input.maintenanceCapabilities,
|
||||
).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor version advisory enrichment failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.as(snapshot)),
|
||||
),
|
||||
);
|
||||
if (
|
||||
!settings.enabled ||
|
||||
snapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(snapshot)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return enrichVersionAdvisory.pipe(
|
||||
Effect.flatMap((baseSnapshot) => {
|
||||
if (
|
||||
!settings.enabled ||
|
||||
baseSnapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(baseSnapshot)
|
||||
) {
|
||||
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return discoverCursorModelCapabilitiesViaAcp(
|
||||
settings,
|
||||
baseSnapshot.models,
|
||||
input.environment,
|
||||
).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...baseSnapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
);
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...snapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: baseSnapshot.models.map((model) => model.slug),
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: snapshot.models.map((model) => model.slug),
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,745 @@
|
||||
import * as nodePath from "node:path";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderDriverKind,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeRequestId,
|
||||
type ThreadId,
|
||||
TurnId,
|
||||
EventId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DateTime,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
FileSystem,
|
||||
PubSub,
|
||||
Random,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
|
||||
import { type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpRequestResolvedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "../acp/AcpCoreRuntimeEvents.ts";
|
||||
import { makeAcpNativeLoggers } from "../acp/AcpNativeLogging.ts";
|
||||
import { parsePermissionRequest } from "../acp/AcpRuntimeModel.ts";
|
||||
import { makeGenericAcpRuntime } from "../acp/GenericAcpSupport.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { type ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
|
||||
const GENERIC_ACP_RESUME_VERSION = 1 as const;
|
||||
|
||||
export interface GenericAcpAdapterSettings {
|
||||
readonly enabled: boolean;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface GenericAcpAdapterOptions {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly instanceId: ProviderSession["providerInstanceId"];
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
readonly readyReason?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
readonly authMethodId?: string | undefined;
|
||||
readonly normalizeModel?: (model: string | null | undefined) => string;
|
||||
}
|
||||
|
||||
interface PendingApproval {
|
||||
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
|
||||
}
|
||||
|
||||
interface PendingUserInput {
|
||||
readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
|
||||
}
|
||||
|
||||
interface GenericAcpSessionContext {
|
||||
readonly threadId: ThreadId;
|
||||
session: ProviderSession;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly acp: AcpSessionRuntimeShape;
|
||||
notificationFiber: Fiber.Fiber<void, never> | undefined;
|
||||
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
|
||||
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
|
||||
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
activeTurnId: TurnId | undefined;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseGenericResume(raw: unknown): { sessionId: string } | undefined {
|
||||
if (!isRecord(raw)) return undefined;
|
||||
if (raw.schemaVersion !== GENERIC_ACP_RESUME_VERSION) return undefined;
|
||||
if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
|
||||
return { sessionId: raw.sessionId.trim() };
|
||||
}
|
||||
|
||||
function settlePendingApprovalsAsCancelled(
|
||||
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.forEach(
|
||||
pendingApprovals.values(),
|
||||
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
function settlePendingUserInputsAsEmptyAnswers(
|
||||
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.forEach(
|
||||
pendingUserInputs.values(),
|
||||
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
export function makeGenericAcpAdapter(
|
||||
settings: GenericAcpAdapterSettings,
|
||||
options: GenericAcpAdapterOptions,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const providerKind = options.provider;
|
||||
const readyReason = options.readyReason ?? "ACP session ready";
|
||||
const normalizeModel = options.normalizeModel ?? ((model) => model?.trim() || "default");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options.nativeEventLogger ??
|
||||
(options.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
|
||||
const sessions = new Map<ThreadId, GenericAcpSessionContext>();
|
||||
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
|
||||
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
|
||||
|
||||
const getThreadSemaphore = (threadId: string) =>
|
||||
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
|
||||
const existing = current.get(threadId);
|
||||
if (existing) return Effect.succeed([existing, current] as const);
|
||||
return Semaphore.make(1).pipe(
|
||||
Effect.map((semaphore) => {
|
||||
const next = new Map(current);
|
||||
next.set(threadId, semaphore);
|
||||
return [semaphore, next] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const requireSession = (
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<GenericAcpSessionContext, ProviderAdapterSessionNotFoundError> => {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({ provider: providerKind, threadId }),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(ctx);
|
||||
};
|
||||
|
||||
const stopSessionInternal = (ctx: GenericAcpSessionContext) =>
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return;
|
||||
ctx.stopped = true;
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
|
||||
if (ctx.notificationFiber) {
|
||||
yield* Fiber.interrupt(ctx.notificationFiber);
|
||||
}
|
||||
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
|
||||
sessions.delete(ctx.threadId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.exited",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
payload: { exitKind: "graceful" },
|
||||
});
|
||||
});
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== providerKind) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${providerKind}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (!input.cwd?.trim()) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: "cwd is required and must be non-empty.",
|
||||
});
|
||||
}
|
||||
|
||||
const command = settings.command.trim();
|
||||
if (!settings.enabled || command.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: "ACP command is not configured.",
|
||||
});
|
||||
}
|
||||
|
||||
const cwd = nodePath.resolve(input.cwd.trim());
|
||||
const existing = sessions.get(input.threadId);
|
||||
if (existing && !existing.stopped) {
|
||||
yield* stopSessionInternal(existing);
|
||||
}
|
||||
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
|
||||
);
|
||||
let ctx!: GenericAcpSessionContext;
|
||||
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
const resumeSessionId = parseGenericResume(input.resumeCursor)?.sessionId;
|
||||
const acp = yield* makeGenericAcpRuntime({
|
||||
spawn: {
|
||||
command,
|
||||
args: settings.args,
|
||||
cwd,
|
||||
...(options.environment ? { env: options.environment } : {}),
|
||||
},
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...(options.authMethodId ? { authMethodId: options.authMethodId } : {}),
|
||||
...(options.clientCapabilities
|
||||
? { clientCapabilities: options.clientCapabilities }
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId =
|
||||
params.options.find((option) => option.kind === "allow_always")?.optionId ??
|
||||
params.options.find((option) => option.kind === "allow_once")?.optionId;
|
||||
if (typeof autoApprovedOptionId === "string" && autoApprovedOptionId.trim()) {
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
optionId: autoApprovedOptionId.trim(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const permissionRequest = parsePermissionRequest(params);
|
||||
const requestId = ApprovalRequestId.make(crypto.randomUUID());
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
pendingApprovals.set(requestId, { decision });
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
pendingApprovals.delete(requestId);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
outcome:
|
||||
resolved === "cancel"
|
||||
? ({ outcome: "cancelled" } as const)
|
||||
: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(providerKind, input.threadId, "session/start", error),
|
||||
),
|
||||
);
|
||||
|
||||
const initialModelSelection =
|
||||
input.modelSelection?.instanceId === options.instanceId
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
if (initialModelSelection?.model) {
|
||||
const model = normalizeModel(initialModelSelection.model);
|
||||
if (model !== "default") {
|
||||
yield* acp
|
||||
.setModel(model)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(
|
||||
providerKind,
|
||||
input.threadId,
|
||||
"session/set_config_option",
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
provider: providerKind,
|
||||
providerInstanceId: options.instanceId,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
cwd,
|
||||
model: initialModelSelection?.model,
|
||||
threadId: input.threadId,
|
||||
resumeCursor: {
|
||||
schemaVersion: GENERIC_ACP_RESUME_VERSION,
|
||||
sessionId: started.sessionId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
ctx = {
|
||||
threadId: input.threadId,
|
||||
session,
|
||||
scope: sessionScope,
|
||||
acp,
|
||||
notificationFiber: undefined,
|
||||
pendingApprovals,
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
activeTurnId: undefined,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
const notificationFiber = yield* Stream.runDrain(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event._tag) {
|
||||
case "ModeChanged":
|
||||
return;
|
||||
case "AssistantItemStarted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload: event.payload,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
ctx.notificationFiber = notificationFiber;
|
||||
sessions.set(input.threadId, ctx);
|
||||
sessionScopeTransferred = true;
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { resume: started.initializeResult },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: readyReason },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: started.sessionId },
|
||||
});
|
||||
|
||||
return session;
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
const turnId = TurnId.make(crypto.randomUUID());
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === options.instanceId
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = normalizeModel(model);
|
||||
if (model !== undefined && resolvedModel !== "default") {
|
||||
yield* ctx.acp
|
||||
.setModel(resolvedModel)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(
|
||||
providerKind,
|
||||
input.threadId,
|
||||
"session/set_config_option",
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
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,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
promptParts.push({
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = yield* ctx.acp
|
||||
.prompt({ prompt: promptParts })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(providerKind, 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: providerKind,
|
||||
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: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(providerKind, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const pending = ctx.pendingApprovals.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "session/request_permission",
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.decision, decision);
|
||||
});
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
answers,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const pending = ctx.pendingUserInputs.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "elicitation/create",
|
||||
detail: `Unknown pending user-input request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.answers, answers);
|
||||
});
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
return { threadId, turns: ctx.turns };
|
||||
});
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
});
|
||||
}
|
||||
const nextLength = Math.max(0, ctx.turns.length - numTurns);
|
||||
ctx.turns.splice(nextLength);
|
||||
return { threadId, turns: ctx.turns };
|
||||
});
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* stopSessionInternal(ctx);
|
||||
}),
|
||||
);
|
||||
|
||||
const listSessions = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (ctx) => ({ ...ctx.session })));
|
||||
const hasSession = (threadId: ThreadId) =>
|
||||
Effect.sync(() => {
|
||||
const ctx = sessions.get(threadId);
|
||||
return ctx !== undefined && !ctx.stopped;
|
||||
});
|
||||
const stopAll = () => Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
|
||||
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
|
||||
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
provider: providerKind,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
} satisfies ProviderAdapterShape<ProviderAdapterError>;
|
||||
});
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { Cause, Data, Effect } from "effect";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
nonEmptyTrimmed,
|
||||
|
||||
@@ -14,7 +14,6 @@ import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -112,10 +111,6 @@ const makeFakeInstance = (
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driverKind,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
|
||||
refresh: Effect.succeed({} as unknown as ServerProvider),
|
||||
streamChanges: Stream.empty,
|
||||
|
||||
@@ -34,7 +34,6 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
@@ -45,13 +44,6 @@ import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "codex",
|
||||
@@ -97,7 +89,6 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
@@ -234,7 +225,6 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
|
||||
@@ -120,6 +120,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
reason: `Driver '${entry.driver}' is not registered in this build.`,
|
||||
}),
|
||||
};
|
||||
@@ -142,6 +143,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
|
||||
}),
|
||||
};
|
||||
@@ -161,6 +163,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
environment: entry.environment ?? [],
|
||||
enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,
|
||||
config: typedConfig,
|
||||
@@ -180,6 +183,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
@@ -27,17 +26,13 @@ import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistr
|
||||
import {
|
||||
haveProvidersChanged,
|
||||
mergeProviderSnapshot,
|
||||
mergeProviderSnapshots,
|
||||
ProviderRegistryLive,
|
||||
selectProvidersByKind,
|
||||
} from "./ProviderRegistry.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
|
||||
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
|
||||
@@ -51,13 +46,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -258,7 +246,7 @@ function makeMutableServerSettingsService(
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), TestHttpClientLive))(
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
"ProviderRegistry",
|
||||
(it) => {
|
||||
describe("checkCodexProviderStatus", () => {
|
||||
@@ -512,182 +500,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
]);
|
||||
});
|
||||
|
||||
it("persists merged provider snapshots for the providers that were refreshed", () => {
|
||||
const previousProviders = [
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("cursor"),
|
||||
driver: ProviderDriverKind.make("cursor"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
booleanDescriptor("fastMode", "Fast Mode"),
|
||||
booleanDescriptor("thinking", "Thinking"),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
const refreshedCursor = {
|
||||
...previousProviders[0],
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
|
||||
const persistedProviders = selectProvidersByKind(
|
||||
mergedProviders,
|
||||
new Set([ProviderDriverKind.make("cursor")]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(persistedProviders, [
|
||||
{
|
||||
...refreshedCursor,
|
||||
models: [...previousProviders[0].models],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("persists the merged snapshot when a live update has empty models", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorDriver = ProviderDriverKind.make("cursor");
|
||||
const cursorInstanceId = ProviderInstanceId.make("cursor");
|
||||
const initialProvider = {
|
||||
instanceId: cursorInstanceId,
|
||||
driver: cursorDriver,
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...initialProvider,
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
const changes = yield* PubSub.unbounded<ServerProvider>();
|
||||
const instance = {
|
||||
instanceId: cursorInstanceId,
|
||||
driverKind: cursorDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: cursorDriver,
|
||||
continuationKey: "cursor:instance:cursor",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cursorDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Effect.succeed(refreshedProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === cursorInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
});
|
||||
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-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: cursorInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
|
||||
...initialProvider.models,
|
||||
]);
|
||||
yield* PubSub.publish(changes, refreshedProvider);
|
||||
|
||||
let cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
|
||||
attempt += 1
|
||||
) {
|
||||
yield* Effect.sleep("10 millis");
|
||||
cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(cachedProvider, {
|
||||
...refreshedProvider,
|
||||
models: [...initialProvider.models],
|
||||
});
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the cached provider list when a manual refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
@@ -715,10 +527,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(cachedProvider),
|
||||
refresh: Effect.die(new Error("simulated refresh failure")),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -804,10 +612,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: provider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(provider),
|
||||
refresh: Effect.succeed(provider),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -944,7 +748,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
@@ -1029,7 +832,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// `it.live` does not inherit layers from the outer `it.layer`
|
||||
@@ -1134,7 +936,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -1185,7 +986,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(
|
||||
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -44,7 +43,6 @@ import {
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
|
||||
|
||||
const loadProviders = (
|
||||
@@ -61,12 +59,6 @@ const loadProviders = (
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
@@ -104,30 +96,6 @@ export const mergeProviderSnapshot = (
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
@@ -259,9 +227,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
@@ -299,21 +264,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
@@ -322,24 +272,15 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
for (const provider of nextProviders) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
@@ -349,16 +290,13 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
yield* Effect.forEach(nextProviders, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
@@ -380,45 +318,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
@@ -466,18 +365,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
@@ -585,15 +472,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
@@ -677,8 +555,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
|
||||
@@ -9,7 +9,10 @@ import {
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
@@ -89,10 +92,6 @@ function makeReadModel(
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: thread.session,
|
||||
@@ -164,6 +163,13 @@ describe("ProviderSessionReaper", () => {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const orchestrationEngine: OrchestrationEngineShape = {
|
||||
getReadModel: () => Effect.succeed(input.readModel),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => unsupported(),
|
||||
streamDomainEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
@@ -177,27 +183,7 @@ describe("ProviderSessionReaper", () => {
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.readModel.threads.find((thread) => thread.id === threadId)
|
||||
? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
|
||||
: Option.none(),
|
||||
),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Duration, Effect, Layer, Option, Schedule } from "effect";
|
||||
import { Duration, Effect, Layer, Schedule } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
ProviderSessionReaper,
|
||||
@@ -20,7 +20,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
@@ -29,6 +29,8 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
||||
|
||||
const sweep = Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
|
||||
const bindings = yield* directory.listBindings();
|
||||
const now = Date.now();
|
||||
let reapedCount = 0;
|
||||
@@ -53,9 +55,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
continue;
|
||||
}
|
||||
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(binding.threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
const thread = threadsById.get(binding.threadId);
|
||||
if (thread?.session?.activeTurnId != null) {
|
||||
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
|
||||
threadId: binding.threadId,
|
||||
|
||||
@@ -65,6 +65,7 @@ export interface ProviderInstance {
|
||||
readonly continuationIdentity: ProviderContinuationIdentity;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly enabled: boolean;
|
||||
readonly snapshot: ServerProviderShape;
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
@@ -96,6 +97,7 @@ export interface ProviderDriverCreateInput<Config> {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly environment: ProviderInstanceEnvironment;
|
||||
readonly enabled: boolean;
|
||||
readonly config: Config;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export class AcpRegistryClientError extends Schema.TaggedErrorClass<AcpRegistryClientError>()(
|
||||
"AcpRegistryClientError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
@@ -6,17 +6,9 @@
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ServerProvider,
|
||||
ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ProviderInstanceId, ProviderDriverKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export interface ProviderRegistryShape {
|
||||
/**
|
||||
@@ -47,27 +39,6 @@ export interface ProviderRegistryShape {
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve the maintenance capabilities owned by one live provider instance.
|
||||
* Falls back to manual-only capabilities when the instance is not live.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance.
|
||||
* This state is never persisted to disk. Today only update actions are
|
||||
* projected onto `ServerProvider.updateState`; install/auth actions can
|
||||
* extend this action map without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates — one emission per aggregated
|
||||
* change. The array contains the full current state.
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export interface ServerProviderShape {
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
import { Data, Effect, FileSystem, Path, Schema } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
type AcpRegistryAgent,
|
||||
type AcpRegistryInstallBinaryResult,
|
||||
type AcpRegistryListResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { collectStreamAsString } from "../providerSnapshot.ts";
|
||||
|
||||
const ACP_BINARY_INSTALLS_DIR = "acp_agents";
|
||||
const ACP_BINARY_MANIFEST_FILE = "install.json";
|
||||
|
||||
type BinaryDistributionTarget = {
|
||||
readonly archive: string;
|
||||
readonly cmd: string;
|
||||
};
|
||||
|
||||
class AcpRegistryBinaryInstallError extends Data.TaggedError("AcpRegistryBinaryInstallError")<{
|
||||
readonly detail: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const AcpBinaryInstallManifest = Schema.Struct({
|
||||
layoutVersion: Schema.Literal(2),
|
||||
agentId: Schema.String,
|
||||
version: Schema.String,
|
||||
platformKey: Schema.String,
|
||||
command: Schema.String,
|
||||
archiveUrl: Schema.String,
|
||||
});
|
||||
|
||||
type AcpBinaryInstallManifest = typeof AcpBinaryInstallManifest.Type;
|
||||
|
||||
function getAcpBinaryPlatformKey(): string {
|
||||
const os = process.platform;
|
||||
const cpu = process.arch;
|
||||
const osKey =
|
||||
os === "darwin" ? "darwin" : os === "win32" ? "windows" : os === "linux" ? "linux" : os;
|
||||
const archKey = cpu === "arm64" ? "aarch64" : cpu === "x64" ? "x86_64" : cpu;
|
||||
return `${osKey}-${archKey}`;
|
||||
}
|
||||
|
||||
function getBinaryTarget(agent: AcpRegistryAgent): BinaryDistributionTarget | null {
|
||||
const binary = agent.distribution.binary;
|
||||
if (!binary || typeof binary !== "object" || globalThis.Array.isArray(binary)) return null;
|
||||
const target = (binary as Record<string, unknown>)[getAcpBinaryPlatformKey()];
|
||||
if (!target || typeof target !== "object" || globalThis.Array.isArray(target)) return null;
|
||||
const record = target as Record<string, unknown>;
|
||||
if (typeof record.archive !== "string" || typeof record.cmd !== "string") return null;
|
||||
return { archive: record.archive, cmd: record.cmd };
|
||||
}
|
||||
|
||||
function resolveHomeDirectory(): string {
|
||||
return process.env.HOME ?? process.env.USERPROFILE ?? "";
|
||||
}
|
||||
|
||||
const normalizeArchiveCommandPath = (command: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const trimmed = command.trim();
|
||||
if (!trimmed) {
|
||||
return yield* Effect.fail(new Error("Registry binary command must not be empty."));
|
||||
}
|
||||
if (path.isAbsolute(trimmed)) {
|
||||
return yield* Effect.fail(
|
||||
new Error("Registry binary command must be a relative archive path."),
|
||||
);
|
||||
}
|
||||
const withoutLeadingDot = trimmed.replace(/^(?:\.[/\\])+/u, "");
|
||||
const parts = withoutLeadingDot
|
||||
.split(/[/\\]+/u)
|
||||
.filter((part) => part.length > 0 && part !== ".");
|
||||
if (parts.length === 0 || parts.some((part) => part === "..")) {
|
||||
return yield* Effect.fail(new Error("Registry binary command resolves outside the archive."));
|
||||
}
|
||||
return path.join(...parts);
|
||||
});
|
||||
|
||||
const resolveInstallRootFromBinaryPath = (binaryPath: string, commandRelativePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const depth = commandRelativePath.split(/[/\\]+/u).filter((part) => part.length > 0).length;
|
||||
let installRoot = binaryPath;
|
||||
for (let index = 0; index < depth; index += 1) {
|
||||
installRoot = path.dirname(installRoot);
|
||||
}
|
||||
return installRoot;
|
||||
});
|
||||
|
||||
const resolveAcpBinaryInstallPath = (
|
||||
config: { readonly stateDir: string },
|
||||
agent: AcpRegistryAgent,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const commandPath = yield* normalizeArchiveCommandPath(getBinaryTarget(agent)?.cmd ?? agent.id);
|
||||
return path.join(
|
||||
config.stateDir,
|
||||
ACP_BINARY_INSTALLS_DIR,
|
||||
agent.id,
|
||||
agent.version,
|
||||
commandPath,
|
||||
);
|
||||
});
|
||||
|
||||
const expandUserPath = (inputPath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const home = resolveHomeDirectory();
|
||||
if (!home) return inputPath;
|
||||
if (inputPath === "~") return home;
|
||||
if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) {
|
||||
return path.join(home, inputPath.slice(2));
|
||||
}
|
||||
return inputPath;
|
||||
});
|
||||
|
||||
const normalizeAcpBinaryInstallPath = (inputPath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const expanded = yield* expandUserPath(inputPath.trim());
|
||||
return path.isAbsolute(expanded) ? expanded : path.resolve(expanded);
|
||||
});
|
||||
|
||||
const displayPath = (inputPath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const home = resolveHomeDirectory();
|
||||
return home && (inputPath === home || inputPath.startsWith(`${home}${path.sep}`))
|
||||
? `~${inputPath.slice(home.length)}`
|
||||
: inputPath;
|
||||
});
|
||||
|
||||
const isPathInside = (parent: string, child: string) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const relativePath = path.relative(parent, child);
|
||||
return (
|
||||
relativePath === "" || (!relativePath.startsWith("..") && !path.isAbsolute(relativePath))
|
||||
);
|
||||
});
|
||||
|
||||
const toBinaryInstallPreview = (
|
||||
config: { readonly stateDir: string },
|
||||
agent: AcpRegistryAgent,
|
||||
target: BinaryDistributionTarget,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const defaultInstallPath = yield* resolveAcpBinaryInstallPath(config, agent);
|
||||
return {
|
||||
archiveUrl: target.archive,
|
||||
defaultInstallPath: yield* displayPath(defaultInstallPath),
|
||||
platformKey: getAcpBinaryPlatformKey(),
|
||||
command: target.cmd,
|
||||
};
|
||||
});
|
||||
|
||||
const resolveAcpBinaryManifestPath = (
|
||||
config: { readonly stateDir: string },
|
||||
agent: AcpRegistryAgent,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const installPath = yield* resolveAcpBinaryInstallPath(config, agent);
|
||||
return path.join(path.dirname(installPath), ACP_BINARY_MANIFEST_FILE);
|
||||
});
|
||||
|
||||
const readAcpBinaryManifest = (config: { readonly stateDir: string }, agent: AcpRegistryAgent) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const manifestPath = yield* resolveAcpBinaryManifestPath(config, agent);
|
||||
const raw = yield* fs.readFileString(manifestPath).pipe(Effect.option);
|
||||
if (raw._tag === "None") return null;
|
||||
const json = yield* Effect.try({
|
||||
try: () => JSON.parse(raw.value) as unknown,
|
||||
catch: () => null,
|
||||
});
|
||||
if (json === null) return null;
|
||||
const parsed = yield* Schema.decodeUnknownEffect(AcpBinaryInstallManifest)(json).pipe(
|
||||
Effect.option,
|
||||
);
|
||||
if (parsed._tag === "None") return null;
|
||||
const manifest = parsed.value;
|
||||
if (
|
||||
manifest.agentId === agent.id &&
|
||||
manifest.version === agent.version &&
|
||||
manifest.platformKey === getAcpBinaryPlatformKey() &&
|
||||
(yield* fs.exists(manifest.command))
|
||||
) {
|
||||
return manifest;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const downloadFile = (url: string, destination: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const bytes = yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Download failed with status ${response.status}`);
|
||||
}
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
},
|
||||
catch: (cause) =>
|
||||
new AcpRegistryBinaryInstallError({
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
yield* fs.writeFile(destination, bytes);
|
||||
});
|
||||
|
||||
const runArchiveCommand = (command: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(ChildProcess.make(command, [...args]));
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
if (Number(exitCode) !== 0) {
|
||||
return yield* Effect.fail(
|
||||
new Error(
|
||||
`Archive command '${command}' failed with exit code ${String(exitCode)}: ${
|
||||
stderr || stdout
|
||||
}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const extractArchive = (archivePath: string, destinationDir: string) => {
|
||||
if (archivePath.endsWith(".tar.gz") || archivePath.endsWith(".tgz")) {
|
||||
return runArchiveCommand("tar", ["-xzf", archivePath, "-C", destinationDir]);
|
||||
}
|
||||
if (archivePath.endsWith(".zip")) {
|
||||
if (process.platform === "win32") {
|
||||
return runArchiveCommand("powershell.exe", [
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"Expand-Archive",
|
||||
"-LiteralPath",
|
||||
archivePath,
|
||||
"-DestinationPath",
|
||||
destinationDir,
|
||||
"-Force",
|
||||
]);
|
||||
}
|
||||
return runArchiveCommand("unzip", ["-q", archivePath, "-d", destinationDir]);
|
||||
}
|
||||
return Effect.fail(new Error("Unsupported binary archive format."));
|
||||
};
|
||||
|
||||
function toInstallError(cause: unknown): string {
|
||||
return cause instanceof Error ? cause.message : String(cause);
|
||||
}
|
||||
|
||||
const installAcpBinaryAgent = (input: {
|
||||
readonly config: { readonly stateDir: string };
|
||||
readonly agent: AcpRegistryAgent;
|
||||
readonly installPath?: string | undefined;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const target = getBinaryTarget(input.agent);
|
||||
if (!target) {
|
||||
return yield* Effect.fail(
|
||||
new Error(`No binary is available for ${getAcpBinaryPlatformKey()}.`),
|
||||
);
|
||||
}
|
||||
const defaultInstallPath = yield* resolveAcpBinaryInstallPath(input.config, input.agent);
|
||||
const installPath = yield* normalizeAcpBinaryInstallPath(
|
||||
input.installPath?.trim() || defaultInstallPath,
|
||||
);
|
||||
const commandPath = yield* normalizeArchiveCommandPath(target.cmd);
|
||||
const installRoot = yield* resolveInstallRootFromBinaryPath(installPath, commandPath);
|
||||
if (installRoot === path.dirname(installRoot)) {
|
||||
return yield* Effect.fail(
|
||||
new Error(`Binary path is too shallow for registry command '${target.cmd}'.`),
|
||||
);
|
||||
}
|
||||
const manifestPath = yield* resolveAcpBinaryManifestPath(input.config, input.agent);
|
||||
const tempDir = yield* fs.makeTempDirectory({ prefix: "t3-acp-agent-" });
|
||||
yield* Effect.addFinalizer(() =>
|
||||
fs.remove(tempDir, { recursive: true, force: true }).pipe(Effect.ignore),
|
||||
);
|
||||
|
||||
const archivePath = path.join(
|
||||
tempDir,
|
||||
path.basename(new URL(target.archive).pathname) || "agent.archive",
|
||||
);
|
||||
const extractDir = path.join(tempDir, "extract");
|
||||
yield* fs.makeDirectory(extractDir, { recursive: true });
|
||||
yield* downloadFile(target.archive, archivePath);
|
||||
yield* extractArchive(archivePath, extractDir);
|
||||
|
||||
const extractedCommand = path.resolve(extractDir, commandPath);
|
||||
if (!(yield* isPathInside(extractDir, extractedCommand))) {
|
||||
return yield* Effect.fail(new Error("Registry binary command resolves outside the archive."));
|
||||
}
|
||||
if (!(yield* fs.exists(extractedCommand))) {
|
||||
return yield* Effect.fail(
|
||||
new Error(`Installed archive did not contain expected command '${target.cmd}'.`),
|
||||
);
|
||||
}
|
||||
yield* fs.makeDirectory(installRoot, { recursive: true });
|
||||
yield* fs.copy(extractDir, installRoot, { overwrite: true });
|
||||
if (!(yield* fs.exists(installPath))) {
|
||||
yield* fs.makeDirectory(path.dirname(installPath), { recursive: true });
|
||||
yield* fs.copyFile(extractedCommand, installPath);
|
||||
}
|
||||
if (process.platform !== "win32") {
|
||||
yield* fs.chmod(installPath, 0o755);
|
||||
}
|
||||
const manifest: AcpBinaryInstallManifest = {
|
||||
layoutVersion: 2,
|
||||
agentId: input.agent.id,
|
||||
version: input.agent.version,
|
||||
platformKey: getAcpBinaryPlatformKey(),
|
||||
command: installPath,
|
||||
archiveUrl: target.archive,
|
||||
};
|
||||
yield* fs.makeDirectory(path.dirname(manifestPath), { recursive: true });
|
||||
yield* fs.writeFileString(manifestPath, JSON.stringify(manifest, null, 2));
|
||||
return { ...target, command: installPath };
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
export const toAcpLaunchSpec = (agent: AcpRegistryAgent) =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
if (agent.distribution.npx) {
|
||||
return {
|
||||
supported: true as const,
|
||||
distributionType: "npx" as const,
|
||||
launch: {
|
||||
command: "npx",
|
||||
args: ["-y", agent.distribution.npx.package, ...(agent.distribution.npx.args ?? [])],
|
||||
env: agent.distribution.npx.env ?? {},
|
||||
},
|
||||
};
|
||||
}
|
||||
if (agent.distribution.uvx) {
|
||||
return {
|
||||
supported: true as const,
|
||||
distributionType: "uvx" as const,
|
||||
launch: {
|
||||
command: "uvx",
|
||||
args: [agent.distribution.uvx.package, ...(agent.distribution.uvx.args ?? [])],
|
||||
env: agent.distribution.uvx.env ?? {},
|
||||
},
|
||||
};
|
||||
}
|
||||
const manifest = yield* readAcpBinaryManifest(config, agent);
|
||||
const target = getBinaryTarget(agent);
|
||||
if (manifest) {
|
||||
return {
|
||||
supported: true as const,
|
||||
distributionType: "binary" as const,
|
||||
launch: {
|
||||
command: manifest.command,
|
||||
args: [],
|
||||
env: {},
|
||||
},
|
||||
...(target ? { binaryInstall: yield* toBinaryInstallPreview(config, agent, target) } : {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
supported: false as const,
|
||||
distributionType: "binaryUnsupported" as const,
|
||||
launch: null,
|
||||
...(target ? { binaryInstall: yield* toBinaryInstallPreview(config, agent, target) } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
export const listAcpRegistryAgents = (registry: {
|
||||
readonly version: string;
|
||||
readonly agents: ReadonlyArray<AcpRegistryAgent>;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const agents = yield* Effect.forEach(registry.agents, (agent) =>
|
||||
toAcpLaunchSpec(agent).pipe(
|
||||
Effect.map((resolved) => ({
|
||||
agent,
|
||||
supported: resolved.supported,
|
||||
distributionType: resolved.distributionType,
|
||||
launch: resolved.launch,
|
||||
...("binaryInstall" in resolved && resolved.binaryInstall
|
||||
? { binaryInstall: resolved.binaryInstall }
|
||||
: {}),
|
||||
})),
|
||||
),
|
||||
);
|
||||
return {
|
||||
registryVersion: registry.version,
|
||||
agents: agents.toSorted((left, right) => left.agent.name.localeCompare(right.agent.name)),
|
||||
} satisfies AcpRegistryListResult;
|
||||
});
|
||||
|
||||
export const installAcpRegistryBinaryAgent = (input: {
|
||||
readonly registry: {
|
||||
readonly agents: ReadonlyArray<AcpRegistryAgent>;
|
||||
};
|
||||
readonly agentId: string;
|
||||
readonly installPath?: string | undefined;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const agent = input.registry.agents.find((entry) => entry.id === input.agentId);
|
||||
if (!agent) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `No ACP registry agent found for '${input.agentId}'.`,
|
||||
} satisfies AcpRegistryInstallBinaryResult;
|
||||
}
|
||||
const installed = yield* installAcpBinaryAgent({
|
||||
config,
|
||||
agent,
|
||||
installPath: input.installPath,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
agent: {
|
||||
agent,
|
||||
supported: true,
|
||||
distributionType: "binary",
|
||||
binaryInstall: yield* toBinaryInstallPreview(config, agent, installed),
|
||||
launch: {
|
||||
command: installed.command,
|
||||
args: [],
|
||||
env: {},
|
||||
},
|
||||
},
|
||||
} satisfies AcpRegistryInstallBinaryResult;
|
||||
}).pipe(
|
||||
Effect.catch((cause: unknown) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
error: toInstallError(cause),
|
||||
} satisfies AcpRegistryInstallBinaryResult),
|
||||
),
|
||||
);
|
||||
@@ -33,7 +33,7 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
readonly authMethodId: string;
|
||||
readonly authMethodId?: string;
|
||||
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
|
||||
readonly protocolLogging?: {
|
||||
readonly logIncoming?: boolean;
|
||||
@@ -365,22 +365,24 @@ const makeAcpSessionRuntime = (
|
||||
acp.agent.initialize(initializePayload),
|
||||
);
|
||||
|
||||
const authenticatePayload = {
|
||||
methodId: options.authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
if (options.authMethodId) {
|
||||
const authenticatePayload = {
|
||||
methodId: options.authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
}
|
||||
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
if (options.resumeSessionId && initializeResult.agentCapabilities?.loadSession === true) {
|
||||
const loadPayload = {
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Effect, Layer, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import {
|
||||
AcpSessionRuntime,
|
||||
type AcpSessionRuntimeOptions,
|
||||
type AcpSessionRuntimeShape,
|
||||
type AcpSpawnInput,
|
||||
} from "./AcpSessionRuntime.ts";
|
||||
|
||||
export interface GenericAcpRuntimeInput extends Omit<AcpSessionRuntimeOptions, "spawn"> {
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly spawn: AcpSpawnInput;
|
||||
}
|
||||
|
||||
export const makeGenericAcpRuntime = (
|
||||
input: GenericAcpRuntimeInput,
|
||||
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer(input).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
|
||||
});
|
||||
@@ -24,6 +24,7 @@ import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
|
||||
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
|
||||
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
|
||||
import { AcpRegistryDriver, type AcpRegistryDriverEnv } from "./Drivers/AcpRegistryDriver.ts";
|
||||
import type { AnyProviderDriver } from "./ProviderDriver.ts";
|
||||
|
||||
/**
|
||||
@@ -35,7 +36,8 @@ export type BuiltInDriversEnv =
|
||||
| ClaudeDriverEnv
|
||||
| CodexDriverEnv
|
||||
| CursorDriverEnv
|
||||
| OpenCodeDriverEnv;
|
||||
| OpenCodeDriverEnv
|
||||
| AcpRegistryDriverEnv;
|
||||
|
||||
/**
|
||||
* Ordered list of built-in drivers. Order matters only for tie-breaking in
|
||||
@@ -47,4 +49,5 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
|
||||
ClaudeDriver,
|
||||
CursorDriver,
|
||||
OpenCodeDriver,
|
||||
AcpRegistryDriver,
|
||||
];
|
||||
@@ -20,20 +20,6 @@ interface TestSettings {
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
const maintenanceCapabilities = {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
packageName: "@openai/codex",
|
||||
update: {
|
||||
command: "npm install -g @openai/codex@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
} as const;
|
||||
|
||||
const initialSnapshot: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
@@ -104,7 +90,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -146,7 +131,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseInitialCheck = yield* Deferred.make<void>();
|
||||
const releaseSettingsCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Ref.get(settingsRef),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -188,7 +172,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseEnrichment = yield* Deferred.make<void>();
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -229,7 +212,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const secondCallbackReady = yield* Deferred.make<void>();
|
||||
const allowFirstRefresh = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
|
||||
@@ -13,7 +13,6 @@ interface ProviderSnapshotState {
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
@@ -144,7 +143,6 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
);
|
||||
|
||||
return {
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
|
||||
@@ -1,487 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { Effect, Random } from "effect";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
createProviderVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const makeTempDir = Effect.fn("makeTempDir")(function* (name: string) {
|
||||
const id = yield* Random.nextUUIDv4;
|
||||
return path.join(os.tmpdir(), `${name}-${id}`);
|
||||
});
|
||||
const isNativeTestCommandPath =
|
||||
(expectedPathSegment: string) =>
|
||||
(commandPath: string): boolean =>
|
||||
normalizeCommandPath(commandPath).includes(expectedPathSegment);
|
||||
const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("packageTool"),
|
||||
npmPackageName: "@example/package-tool",
|
||||
homebrewFormula: "package-tool",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("nativePackageTool"),
|
||||
npmPackageName: "@example/native-package-tool",
|
||||
homebrewFormula: "native-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "native-package-tool",
|
||||
args: ["update"],
|
||||
lockKey: "native-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
|
||||
},
|
||||
});
|
||||
const scopedPackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("scopedPackageTool"),
|
||||
npmPackageName: "@example/scoped-package-tool",
|
||||
homebrewFormula: "example/tap/scoped-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "scoped-package-tool",
|
||||
args: ["upgrade"],
|
||||
lockKey: "scoped-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.scoped-package-tool/bin/scoped-package-tool"),
|
||||
},
|
||||
});
|
||||
const staticToolUpdate = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
updateExecutable: "static-tool",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "static-tool",
|
||||
}),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
describe("providerMaintenance", () => {
|
||||
it("marks providers with unknown current versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks providers with unknown latest versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
message: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks installed providers behind latest when a newer provider version is available", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("nativePackageTool"),
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
maintenanceCapabilities: nativePackageToolUpdate.resolve(),
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
updateCommand: "npm install -g @example/native-package-tool@latest",
|
||||
canUpdate: true,
|
||||
message: "Install the update now or review provider settings.",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps update commands owned by provider maintenance capabilities", () => {
|
||||
expect(staticToolUpdate.resolve()).toEqual({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
update: {
|
||||
command: "static-tool update",
|
||||
|
||||
executable: "static-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "static-tool",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to vite-plus updates when the resolved binary lives in vite-plus global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-vite-plus-capabilities");
|
||||
const vitePlusBinDir = path.join(tempDir, ".vite-plus", "bin");
|
||||
mkdirSync(vitePlusBinDir, { recursive: true });
|
||||
const packageToolPath = path.join(vitePlusBinDir, "package-tool");
|
||||
writeFileSync(packageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(packageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: vitePlusBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "vp i -g @example/package-tool",
|
||||
|
||||
executable: "vp",
|
||||
|
||||
args: ["i", "-g", "@example/package-tool"],
|
||||
|
||||
lockKey: "vite-plus-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to bun updates when the resolved binary lives in bun's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-bun-capabilities");
|
||||
const bunBinDir = path.join(tempDir, ".bun", "bin");
|
||||
mkdirSync(bunBinDir, { recursive: true });
|
||||
writeFileSync(path.join(bunBinDir, "native-package-tool.exe"), "MZ");
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: bunBinDir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "bun i -g @example/native-package-tool@latest",
|
||||
|
||||
executable: "bun",
|
||||
|
||||
args: ["i", "-g", "@example/native-package-tool@latest"],
|
||||
|
||||
lockKey: "bun-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to pnpm updates when the resolved binary lives in pnpm's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
|
||||
const pnpmHomeDir = path.join(tempDir, ".local", "share", "pnpm");
|
||||
mkdirSync(pnpmHomeDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(pnpmHomeDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: pnpmHomeDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/scoped-package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/scoped-package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "brew upgrade package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches native-package-tool to native updates when the binary resolves through the native installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-native-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".local", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const nativePackageToolPath = path.join(nativeBinDir, "native-package-tool");
|
||||
writeFileSync(nativePackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(nativePackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "native-package-tool update",
|
||||
|
||||
executable: "native-package-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "native-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches scoped-package-tool to native upgrades when the binary resolves through the standalone installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-scoped-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".scoped-package-tool", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(nativeBinDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "scoped-package-tool upgrade",
|
||||
|
||||
executable: "scoped-package-tool",
|
||||
|
||||
args: ["upgrade"],
|
||||
|
||||
lockKey: "scoped-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches native-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade native-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "native-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("switches scoped-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade example/tap/scoped-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "example/tap/scoped-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("keeps npm updates for binaries symlinked into npm's global node_modules tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-npm-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
"lib",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "npm install -g @example/package-tool@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses Effect FileSystem realPath when detecting pnpm global symlinks", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-realpath-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
".local",
|
||||
"share",
|
||||
"pnpm",
|
||||
"global",
|
||||
"5",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("disables one-click updates for explicit custom binary paths it cannot safely map", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "C:\\Tools\\package-tool\\package-tool.exe",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,472 +0,0 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderVersionAdvisory,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveCommandPath } from "@t3tools/shared/shell";
|
||||
import { DateTime, Effect, FileSystem, Option, Schema } from "effect";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import { compareCliVersions } from "./cliVersion.ts";
|
||||
|
||||
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
|
||||
const LATEST_VERSION_TIMEOUT_MS = 4_000;
|
||||
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
|
||||
|
||||
export interface ProviderMaintenanceCapabilities {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly update: ProviderMaintenanceCommandAction | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCommandAction {
|
||||
readonly command: string;
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilityResolutionOptions {
|
||||
readonly binaryPath?: string | null;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly realCommandPath?: string | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilitiesResolver {
|
||||
readonly resolve: (
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
) => ProviderMaintenanceCapabilities;
|
||||
}
|
||||
|
||||
export interface PackageManagedProviderMaintenanceDefinition {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly npmPackageName: string;
|
||||
readonly homebrewFormula: string | null;
|
||||
readonly nativeUpdate: {
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
readonly isCommandPath: (commandPath: string) => boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface LatestVersionCacheEntry {
|
||||
readonly expiresAt: number;
|
||||
readonly version: string | null;
|
||||
}
|
||||
|
||||
const latestVersionCache = new Map<string, LatestVersionCacheEntry>();
|
||||
const NpmLatestVersionResponse = Schema.Struct({
|
||||
version: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export function clearLatestProviderVersionCacheForTests(): void {
|
||||
latestVersionCache.clear();
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
export function makeProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly updateExecutable: string | null;
|
||||
readonly updateArgs: ReadonlyArray<string>;
|
||||
readonly updateLockKey: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
const update =
|
||||
input.updateExecutable === null || input.updateLockKey === null
|
||||
? null
|
||||
: {
|
||||
command: [input.updateExecutable, ...input.updateArgs].join(" "),
|
||||
executable: input.updateExecutable,
|
||||
args: input.updateArgs,
|
||||
lockKey: input.updateLockKey,
|
||||
};
|
||||
return {
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
update,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeManualOnlyProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
updateExecutable: null,
|
||||
updateArgs: [],
|
||||
updateLockKey: null,
|
||||
});
|
||||
}
|
||||
|
||||
function makeNpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeBunGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "bun-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makePnpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "pnpm",
|
||||
updateArgs: ["add", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "pnpm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeVitePlusGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", definition.npmPackageName],
|
||||
updateLockKey: "vite-plus-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeHomebrewProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
if (!definition.homebrewFormula) {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "brew",
|
||||
updateArgs: ["upgrade", definition.homebrewFormula],
|
||||
updateLockKey: "homebrew",
|
||||
});
|
||||
}
|
||||
|
||||
function makeNativeProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities | null {
|
||||
if (!definition.nativeUpdate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: definition.nativeUpdate.executable,
|
||||
updateArgs: definition.nativeUpdate.args,
|
||||
updateLockKey: definition.nativeUpdate.lockKey,
|
||||
});
|
||||
}
|
||||
|
||||
export function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
}
|
||||
|
||||
export function normalizeCommandPath(commandPath: string): string {
|
||||
return commandPath.replaceAll("\\", "/").toLowerCase();
|
||||
}
|
||||
|
||||
function isBunGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.bun/bin/");
|
||||
}
|
||||
|
||||
function isVitePlusGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
|
||||
}
|
||||
|
||||
function isPnpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/.local/share/pnpm/") ||
|
||||
normalized.includes("/library/pnpm/") ||
|
||||
normalized.includes("/local/share/pnpm/") ||
|
||||
normalized.includes("/appdata/local/pnpm/") ||
|
||||
normalized.includes("/pnpm/global/")
|
||||
);
|
||||
}
|
||||
|
||||
function isNpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/node_modules/.bin/") ||
|
||||
normalized.includes("/lib/node_modules/") ||
|
||||
normalized.includes("/npm/node_modules/")
|
||||
);
|
||||
}
|
||||
|
||||
function isHomebrewCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/opt/homebrew/cellar/") ||
|
||||
normalized.includes("/usr/local/cellar/") ||
|
||||
normalized.includes("/homebrew/cellar/") ||
|
||||
normalized.includes("/opt/homebrew/caskroom/") ||
|
||||
normalized.includes("/usr/local/caskroom/") ||
|
||||
normalized.includes("/homebrew/caskroom/") ||
|
||||
normalized.startsWith("/opt/homebrew/bin/") ||
|
||||
normalized.startsWith("/usr/local/bin/")
|
||||
);
|
||||
}
|
||||
|
||||
export function resolvePackageManagedProviderMaintenance(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
|
||||
if (resolvedCommandPath) {
|
||||
const commandPaths = [
|
||||
resolvedCommandPath,
|
||||
...(options?.realCommandPath ? [options.realCommandPath] : []),
|
||||
];
|
||||
|
||||
const nativeUpdate = definition.nativeUpdate;
|
||||
if (
|
||||
nativeUpdate &&
|
||||
commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))
|
||||
) {
|
||||
return (
|
||||
makeNativeProviderMaintenanceCapabilities(definition) ??
|
||||
makeNpmGlobalProviderMaintenanceCapabilities(definition)
|
||||
);
|
||||
}
|
||||
if (commandPaths.some(isVitePlusGlobalCommandPath)) {
|
||||
return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isBunGlobalCommandPath)) {
|
||||
return makeBunGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isPnpmGlobalCommandPath)) {
|
||||
return makePnpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isNpmGlobalCommandPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isHomebrewCommandPath)) {
|
||||
return makeHomebrewProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasPathSeparator(binaryPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
export function makePackageManagedProviderMaintenanceResolver(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeStaticProviderMaintenanceResolver(
|
||||
capabilities: ProviderMaintenanceCapabilities,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: () => capabilities,
|
||||
};
|
||||
}
|
||||
|
||||
function makeManualProviderMaintenanceCapabilities(
|
||||
provider: ProviderDriverKind,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
"resolveProviderMaintenanceCapabilitiesEffect",
|
||||
)(function* (
|
||||
resolver: ProviderMaintenanceCapabilitiesResolver,
|
||||
options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, "realCommandPath">,
|
||||
) {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
if (!resolvedCommandPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCommandPath = yield* fileSystem
|
||||
.realPath(resolvedCommandPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(resolvedCommandPath)));
|
||||
return resolver.resolve({
|
||||
...options,
|
||||
realCommandPath,
|
||||
});
|
||||
});
|
||||
|
||||
function deriveVersionAdvisory(input: {
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion: string | null;
|
||||
}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
|
||||
if (!input.currentVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (!input.latestVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
|
||||
return {
|
||||
status: "behind_latest",
|
||||
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
|
||||
};
|
||||
}
|
||||
return { status: "current", message: null };
|
||||
}
|
||||
|
||||
export function createProviderVersionAdvisory(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion?: string | null;
|
||||
readonly checkedAt?: string | null;
|
||||
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
|
||||
}): ServerProviderVersionAdvisory {
|
||||
const capabilities =
|
||||
input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
|
||||
const latestVersion = input.latestVersion ?? null;
|
||||
const advisory = deriveVersionAdvisory({
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
});
|
||||
|
||||
return {
|
||||
status: advisory.status,
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
updateCommand: capabilities.update?.command ?? null,
|
||||
canUpdate: capabilities.update !== null,
|
||||
checkedAt: input.checkedAt ?? null,
|
||||
message: advisory.message,
|
||||
};
|
||||
}
|
||||
|
||||
const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const request = HttpClientRequest.get(
|
||||
`https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
|
||||
).pipe(HttpClientRequest.setHeader("accept", "application/json"));
|
||||
const response = yield* client.execute(request).pipe(
|
||||
Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
if (Option.isNone(response)) {
|
||||
return null;
|
||||
}
|
||||
const httpResponse = response.value;
|
||||
if (httpResponse.status < 200 || httpResponse.status >= 300) {
|
||||
return null;
|
||||
}
|
||||
const payload = yield* httpResponse.json.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
return payload ? nonEmptyString(payload.version) : null;
|
||||
});
|
||||
|
||||
export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
) {
|
||||
const packageName = maintenanceCapabilities.packageName;
|
||||
if (!packageName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cached = latestVersionCache.get(packageName);
|
||||
const now = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached.version;
|
||||
}
|
||||
|
||||
const version = yield* fetchNpmLatestVersion(packageName);
|
||||
latestVersionCache.set(packageName, {
|
||||
expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
|
||||
version,
|
||||
});
|
||||
return version;
|
||||
});
|
||||
|
||||
export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
|
||||
"enrichProviderSnapshotWithVersionAdvisory",
|
||||
)(function* (snapshot: ServerProvider, maintenanceCapabilities?: ProviderMaintenanceCapabilities) {
|
||||
const capabilities =
|
||||
maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
|
||||
if (!snapshot.enabled || !snapshot.installed || !snapshot.version) {
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
checkedAt: snapshot.checkedAt,
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const latestVersion = yield* resolveLatestProviderVersion(capabilities);
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
latestVersion,
|
||||
checkedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -1,79 +0,0 @@
|
||||
import { Effect, Ref } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
export interface ProviderMaintenanceCommandCoordinatorShape<E> {
|
||||
readonly withCommandLock: <A, R>(input: {
|
||||
readonly targetKey: string;
|
||||
readonly lockKey: string;
|
||||
readonly onQueued?: Effect.Effect<void, E, R>;
|
||||
readonly run: Effect.Effect<A, E, R>;
|
||||
}) => Effect.Effect<A, E, R>;
|
||||
}
|
||||
|
||||
export const makeProviderMaintenanceCommandCoordinator = Effect.fn(
|
||||
"makeProviderMaintenanceCommandCoordinator",
|
||||
)(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {
|
||||
const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const locksRef = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());
|
||||
|
||||
const acquireTarget = Effect.fn("acquireTarget")(function* (targetKey: string) {
|
||||
return yield* Ref.modify(runningTargetsRef, (runningTargets) => {
|
||||
if (runningTargets.has(targetKey)) {
|
||||
return [false, runningTargets] as const;
|
||||
}
|
||||
const next = new Set(runningTargets);
|
||||
next.add(targetKey);
|
||||
return [true, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const releaseTarget = (targetKey: string) =>
|
||||
Ref.update(runningTargetsRef, (runningTargets) => {
|
||||
const next = new Set(runningTargets);
|
||||
next.delete(targetKey);
|
||||
return next;
|
||||
});
|
||||
|
||||
const getLock = Effect.fn("getProviderMaintenanceCommandLock")(function* (lockKey: string) {
|
||||
const existing = (yield* Ref.get(locksRef)).get(lockKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const lock = yield* Semaphore.make(1);
|
||||
return yield* Ref.modify(locksRef, (locks) => {
|
||||
const current = locks.get(lockKey);
|
||||
if (current) {
|
||||
return [current, locks] as const;
|
||||
}
|
||||
const next = new Map(locks);
|
||||
next.set(lockKey, lock);
|
||||
return [lock, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] = ({
|
||||
targetKey,
|
||||
lockKey,
|
||||
onQueued,
|
||||
run,
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const acquired = yield* acquireTarget(targetKey);
|
||||
if (!acquired) {
|
||||
return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const lock = yield* getLock(lockKey);
|
||||
if (onQueued) {
|
||||
yield* onQueued;
|
||||
}
|
||||
return yield* lock.withPermits(1)(run);
|
||||
}).pipe(Effect.ensuring(releaseTarget(targetKey)));
|
||||
});
|
||||
|
||||
return {
|
||||
withCommandLock,
|
||||
} satisfies ProviderMaintenanceCommandCoordinatorShape<E>;
|
||||
});
|
||||
@@ -1,640 +0,0 @@
|
||||
import { afterEach, describe, it, assert } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServerProviderUpdateError } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Exit, Fiber, Layer, Ref, Schema, Sink, Stream } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex");
|
||||
const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor");
|
||||
const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities {
|
||||
if (provider === CURSOR_DRIVER) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
});
|
||||
}
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
const baseProvider: ServerProvider = {
|
||||
instanceId: CODEX_INSTANCE_ID,
|
||||
driver: CODEX_DRIVER,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const baseCursorProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: CURSOR_INSTANCE_ID,
|
||||
driver: CURSOR_DRIVER,
|
||||
};
|
||||
|
||||
const baseOpenCodeProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: OPENCODE_INSTANCE_ID,
|
||||
driver: OPENCODE_DRIVER,
|
||||
};
|
||||
|
||||
const latestVersionHttpClient = (version: string) =>
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ version }, { headers: { "content-type": "application/json" } }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: result.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
},
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeRegistry(
|
||||
initialProviders: ServerProvider | ReadonlyArray<ServerProvider> = baseProvider,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
Array.isArray(initialProviders) ? initialProviders : [initialProviders],
|
||||
);
|
||||
const updateStatesRef = yield* Ref.make<ReadonlyArray<ServerProviderUpdateState>>([]);
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn(
|
||||
"providerMaintenanceRunner.test.setProviderMaintenanceActionState",
|
||||
)(function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
const updateState = input.state;
|
||||
if (updateState) {
|
||||
yield* Ref.update(updateStatesRef, (states) => [...states, updateState]);
|
||||
}
|
||||
return yield* Ref.updateAndGet(providersRef, (providers) =>
|
||||
providers.map((candidate) => {
|
||||
if (candidate.instanceId !== input.instanceId) {
|
||||
return candidate;
|
||||
}
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = candidate;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...candidate,
|
||||
updateState,
|
||||
};
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const registry: ProviderRegistryShape = {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: () => Ref.get(providersRef),
|
||||
refreshInstance: () => Ref.get(providersRef),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(lifecycleFor(provider)),
|
||||
setProviderMaintenanceActionState,
|
||||
streamChanges: Stream.empty,
|
||||
};
|
||||
|
||||
return {
|
||||
registry,
|
||||
updateStatesRef,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const makeTestRunner = (registry: ProviderRegistryShape) =>
|
||||
Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe(
|
||||
Effect.provide(
|
||||
ProviderMaintenanceRunner.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ProviderRegistry, registry)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("providerMaintenanceRunner", () => {
|
||||
it.effect("runs the allowlisted provider update command and records success", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry, updateStatesRef } = yield* makeRegistry(baseCursorProvider);
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CURSOR_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "agent",
|
||||
args: ["update"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(updateStatesRef)).map((state) => state.status),
|
||||
["queued", "running", "succeeded"],
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("uses the resolved provider capabilities when choosing the update executable", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
versionAdvisory: {
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.0.14",
|
||||
latestVersion: "2.1.123",
|
||||
updateCommand: "bun i -g @anthropic-ai/claude-code@latest",
|
||||
canUpdate: true,
|
||||
checkedAt: "2026-04-30T12:00:00.000Z",
|
||||
message: "Update available.",
|
||||
},
|
||||
});
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: () =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: CODEX_DRIVER,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "bun-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "bun",
|
||||
args: ["i", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"runs update commands through Effect ChildProcess when no test runner is injected",
|
||||
() => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const runner = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* runner.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "npm",
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("updates a single provider instance without touching sibling instances", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const personalInstanceId = ProviderInstanceId.make("codex_personal");
|
||||
const workInstanceId = ProviderInstanceId.make("codex_work");
|
||||
const refreshedInstanceIds: Array<ProviderInstanceId> = [];
|
||||
const { registry } = yield* makeRegistry([
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: personalInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: workInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex-instance-test",
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", "@openai/codex"],
|
||||
updateLockKey: "vite-plus-global",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.tap(() => Effect.sync(() => assert.strictEqual(instanceId, personalInstanceId))),
|
||||
),
|
||||
refreshInstance: (instanceId) =>
|
||||
registry.refreshInstance(instanceId).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
refreshedInstanceIds.push(instanceId);
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider({
|
||||
provider: CODEX_DRIVER,
|
||||
instanceId: personalInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "vp",
|
||||
args: ["i", "-g", "@openai/codex"],
|
||||
},
|
||||
]);
|
||||
assert.deepStrictEqual(refreshedInstanceIds, [personalInstanceId]);
|
||||
assert.strictEqual(result.providers[0]?.instanceId, personalInstanceId);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.strictEqual(result.providers[1]?.instanceId, workInstanceId);
|
||||
assert.strictEqual(result.providers[1]?.updateState, undefined);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.124.0-alpha.3"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("records command failure output in provider update state", () =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
const updateState = result.providers[0]?.updateState;
|
||||
|
||||
assert.strictEqual(updateState?.status, "failed");
|
||||
assert.strictEqual(updateState?.message, "Update command exited with code 1.");
|
||||
assert.include(updateState?.output ?? "", "permission denied");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stderr: "permission denied", code: 1 })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks successful commands as unchanged when the refreshed provider is still outdated",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
installed: true,
|
||||
version: "0.1.0",
|
||||
});
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "unchanged");
|
||||
assert.include(result.providers[0]?.updateState?.message ?? "", "still detects");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("9.9.9"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("prevents concurrent updates for the same provider", () => {
|
||||
const startedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const started = new Promise<void>((resolve) => {
|
||||
startedLatch.resolve = resolve;
|
||||
});
|
||||
const release = new Promise<void>((resolve) => {
|
||||
releaseLatch.resolve = resolve;
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => started);
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isFailure(second), true);
|
||||
if (Exit.isFailure(second)) {
|
||||
const error = Cause.squash(second.cause);
|
||||
assert.strictEqual(Schema.is(ServerProviderUpdateError)(error), true);
|
||||
if (Schema.is(ServerProviderUpdateError)(error)) {
|
||||
assert.include(error.reason, "already running");
|
||||
}
|
||||
}
|
||||
|
||||
releaseLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => {
|
||||
startedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => release).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("serializes different providers that share the same update lock key", () => {
|
||||
const firstStartedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseFirstLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const firstStarted = new Promise<void>((resolve) => {
|
||||
firstStartedLatch.resolve = resolve;
|
||||
});
|
||||
const releaseFirst = new Promise<void>((resolve) => {
|
||||
releaseFirstLatch.resolve = resolve;
|
||||
});
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry([baseProvider, baseOpenCodeProvider]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => firstStarted);
|
||||
|
||||
const second = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped);
|
||||
let providersWhileQueued: ReadonlyArray<ServerProvider> = [];
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
providersWhileQueued = yield* registry.getProviders;
|
||||
const queuedStatus = providersWhileQueued.find(
|
||||
(provider) => provider.instanceId === OPENCODE_INSTANCE_ID,
|
||||
)?.updateState?.status;
|
||||
if (queuedStatus === "queued") {
|
||||
break;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
assert.strictEqual(
|
||||
providersWhileQueued.find((provider) => provider.instanceId === OPENCODE_INSTANCE_ID)
|
||||
?.updateState?.status,
|
||||
"queued",
|
||||
);
|
||||
|
||||
releaseFirstLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
yield* Fiber.join(second);
|
||||
assert.deepStrictEqual(calls, [
|
||||
"install -g @openai/codex@latest",
|
||||
"install -g opencode-ai@latest",
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
if (calls.length === 1) {
|
||||
firstStartedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => releaseFirst).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts arbitrary driver-provided update lock keys", () => {
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "unknown-lock-key",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"releases the running-provider marker when interrupted after queuing but before the lock run starts",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
let blockQueuedState = true;
|
||||
const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const queuedStateWritten = new Promise<void>((resolve) => {
|
||||
queuedStateWrittenLatch.resolve = resolve;
|
||||
});
|
||||
const releaseQueuedState = new Promise<void>((resolve) => {
|
||||
releaseQueuedStateLatch.resolve = resolve;
|
||||
});
|
||||
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
setProviderMaintenanceActionState: Effect.fn(
|
||||
"providerMaintenanceRunner.test.blockQueuedState",
|
||||
)(function* (input) {
|
||||
const providers = yield* registry.setProviderMaintenanceActionState(input);
|
||||
if (input.state?.status === "queued" && blockQueuedState) {
|
||||
queuedStateWrittenLatch.resolve();
|
||||
yield* Effect.promise(() => releaseQueuedState);
|
||||
}
|
||||
return providers;
|
||||
}),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => queuedStateWritten);
|
||||
blockQueuedState = false;
|
||||
|
||||
yield* Fiber.interrupt(first);
|
||||
releaseQueuedStateLatch.resolve();
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isSuccess(second), true);
|
||||
if (Exit.isSuccess(second)) {
|
||||
assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,395 +0,0 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
ServerProviderUpdateError,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdatedPayload,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Context, DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
|
||||
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
|
||||
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
const UPDATE_TIMEOUT_MS = 5 * 60_000;
|
||||
const UPDATE_OUTPUT_MAX_BYTES = 10_000;
|
||||
|
||||
export interface ProviderMaintenanceCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number | null;
|
||||
readonly timedOut: boolean;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceRunnerShape {
|
||||
readonly updateProvider: (
|
||||
target:
|
||||
| ProviderDriverKind
|
||||
| {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly instanceId?: ProviderInstanceId | undefined;
|
||||
},
|
||||
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
|
||||
}
|
||||
|
||||
export class ProviderMaintenanceRunner extends Context.Service<
|
||||
ProviderMaintenanceRunner,
|
||||
ProviderMaintenanceRunnerShape
|
||||
>()("t3/provider/ProviderMaintenanceRunner") {}
|
||||
|
||||
interface VerifiedProviderRefresh {
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
readonly verifiedProviders: ReadonlyArray<ServerProvider>;
|
||||
}
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
|
||||
function* (input: {
|
||||
readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
|
||||
function* () {
|
||||
const child = yield* input.spawner
|
||||
.spawn(ChildProcess.make(input.command, [...input.args]))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(`Failed to run update command ${input.command}: ${cause.message}`),
|
||||
),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(cause instanceof Error ? cause.message : "Update command failed to run."),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
exitCode: Number(exitCode),
|
||||
timedOut: false,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProviderMaintenanceCommandResult;
|
||||
},
|
||||
);
|
||||
|
||||
return yield* collectCommandResult().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),
|
||||
Effect.map((result) =>
|
||||
Option.match(result, {
|
||||
onSome: (value) => value,
|
||||
onNone: () =>
|
||||
({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: null,
|
||||
timedOut: true,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}) satisfies ProviderMaintenanceCommandResult,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
function trimNullable(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function truncateText(value: string, maxLength: number): string {
|
||||
return value.length <= maxLength ? value : value.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
|
||||
const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
|
||||
if (!output) {
|
||||
return null;
|
||||
}
|
||||
return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
|
||||
}
|
||||
|
||||
function failureMessage(result: ProviderMaintenanceCommandResult): string {
|
||||
if (result.timedOut) {
|
||||
return "Update timed out.";
|
||||
}
|
||||
if (result.exitCode !== null && result.exitCode !== 0) {
|
||||
return `Update command exited with code ${result.exitCode}.`;
|
||||
}
|
||||
return "Update command failed.";
|
||||
}
|
||||
|
||||
function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
|
||||
return provider?.versionAdvisory?.status === "behind_latest";
|
||||
}
|
||||
|
||||
function makeUpdateState(input: {
|
||||
readonly status: ServerProviderUpdateState["status"];
|
||||
readonly startedAt: string | null;
|
||||
readonly finishedAt: string | null;
|
||||
readonly message: string | null;
|
||||
readonly output?: string | null;
|
||||
}): ServerProviderUpdateState {
|
||||
return {
|
||||
status: input.status,
|
||||
startedAt: input.startedAt,
|
||||
finishedAt: input.finishedAt,
|
||||
message: input.message,
|
||||
output: input.output ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
|
||||
runProviderMaintenanceCommandWithSpawner({
|
||||
spawner,
|
||||
command,
|
||||
args,
|
||||
});
|
||||
const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
|
||||
makeAlreadyRunningError: () =>
|
||||
new ServerProviderUpdateError({
|
||||
provider: ProviderDriverKind.make("unknown"),
|
||||
reason: "An update is already running for this provider.",
|
||||
}),
|
||||
});
|
||||
|
||||
const verifyRefreshedProvider = (
|
||||
provider: ProviderDriverKind,
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<VerifiedProviderRefresh> =>
|
||||
providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) =>
|
||||
providers
|
||||
.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
)
|
||||
.map((candidate) => candidate.instanceId),
|
||||
),
|
||||
Effect.flatMap((instanceIds) =>
|
||||
instanceIds.length === 0
|
||||
? providerRegistry.refreshInstance(instanceId)
|
||||
: Effect.forEach(
|
||||
instanceIds,
|
||||
(instanceId) => providerRegistry.refreshInstance(instanceId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(providerRegistry.getProviders)),
|
||||
),
|
||||
Effect.flatMap((providers) => {
|
||||
const refreshedProviders = providers.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
);
|
||||
if (refreshedProviders.length === 0) {
|
||||
return Effect.succeed<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: [],
|
||||
});
|
||||
}
|
||||
return Effect.forEach(
|
||||
refreshedProviders,
|
||||
(refreshedProvider) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(
|
||||
refreshedProvider,
|
||||
maintenanceCapabilities,
|
||||
).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(
|
||||
Effect.map(
|
||||
(verifiedProviders): VerifiedProviderRefresh => ({
|
||||
providers,
|
||||
verifiedProviders,
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Provider post-update version verification failed", {
|
||||
provider,
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(
|
||||
Effect.as<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: refreshedProviders,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
|
||||
"ProviderMaintenanceRunner.updateProvider",
|
||||
)(function* (target) {
|
||||
const provider = typeof target === "string" ? target : target.provider;
|
||||
const instanceId =
|
||||
typeof target === "string"
|
||||
? defaultInstanceIdForDriver(provider)
|
||||
: (target.instanceId ?? defaultInstanceIdForDriver(provider));
|
||||
const targetKey = `instance:${instanceId}`;
|
||||
const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
|
||||
instanceId,
|
||||
provider,
|
||||
);
|
||||
const update = capabilities.update;
|
||||
if (!update) {
|
||||
return yield* new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: "This provider does not support one-click updates.",
|
||||
});
|
||||
}
|
||||
|
||||
const setUpdateState = (state: ServerProviderUpdateState | null) =>
|
||||
providerRegistry.setProviderMaintenanceActionState({
|
||||
instanceId,
|
||||
action: "update",
|
||||
state,
|
||||
});
|
||||
const setQueuedState = setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
message: "Waiting for another provider update to finish.",
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
|
||||
function* () {
|
||||
const finish = (state: ServerProviderUpdateState) =>
|
||||
setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
|
||||
const startedAtRef = yield* Ref.make<string | null>(null);
|
||||
|
||||
const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
|
||||
function* () {
|
||||
const startedAt = yield* nowIso;
|
||||
yield* Ref.set(startedAtRef, startedAt);
|
||||
yield* setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "running",
|
||||
startedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* runMaintenanceCommand(update.executable, update.args);
|
||||
const finishedAt = yield* nowIso;
|
||||
if (result.timedOut || result.exitCode !== 0) {
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: failureMessage(result),
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const { verifiedProviders } = yield* verifyRefreshedProvider(
|
||||
provider,
|
||||
capabilities,
|
||||
instanceId,
|
||||
);
|
||||
const couldNotVerify = verifiedProviders.length === 0;
|
||||
const stillOutdated =
|
||||
couldNotVerify ||
|
||||
verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: stillOutdated ? "unchanged" : "succeeded",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: couldNotVerify
|
||||
? "Update command completed, but T3 Code could not verify the provider version."
|
||||
: stillOutdated
|
||||
? "Update command completed, but T3 Code still detects an outdated provider version."
|
||||
: "Provider updated.",
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
|
||||
function* (cause: Cause.Cause<unknown>) {
|
||||
const failure = Cause.squash(cause);
|
||||
const startedAt = yield* Ref.get(startedAtRef);
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt: yield* nowIso,
|
||||
message: failure instanceof Error ? failure.message : "Update command failed.",
|
||||
output: null,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
|
||||
},
|
||||
);
|
||||
|
||||
return yield* commandCoordinator
|
||||
.withCommandLock({
|
||||
targetKey,
|
||||
lockKey: update.lockKey,
|
||||
onQueued: setQueuedState,
|
||||
run: runProviderUpdate(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(ServerProviderUpdateError)(error)
|
||||
? new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: error.reason,
|
||||
})
|
||||
: error,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return ProviderMaintenanceRunner.of({
|
||||
updateProvider,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderMaintenanceRunner, make());
|
||||
@@ -12,8 +12,6 @@ import { Effect, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)
|
||||
@@ -35,6 +33,7 @@ export interface ProviderProbeResult {
|
||||
|
||||
export interface ServerProviderPresentation {
|
||||
readonly displayName: string;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly badgeLabel?: string;
|
||||
readonly showInteractionModeToggle?: boolean;
|
||||
}
|
||||
@@ -184,7 +183,6 @@ export function buildBooleanOptionDescriptor(input: {
|
||||
}
|
||||
|
||||
export function buildServerProvider(input: {
|
||||
driver?: ProviderDriverKind;
|
||||
presentation: ServerProviderPresentation;
|
||||
enabled: boolean;
|
||||
checkedAt: string;
|
||||
@@ -193,15 +191,9 @@ export function buildServerProvider(input: {
|
||||
skills?: ReadonlyArray<ServerProviderSkill>;
|
||||
probe: ProviderProbeResult;
|
||||
}): ServerProviderDraft {
|
||||
const versionAdvisory = input.driver
|
||||
? createProviderVersionAdvisory({
|
||||
driver: input.driver,
|
||||
currentVersion: input.probe.version,
|
||||
checkedAt: input.checkedAt,
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
displayName: input.presentation.displayName,
|
||||
...(input.presentation.iconUrl ? { iconUrl: input.presentation.iconUrl } : {}),
|
||||
...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
|
||||
...(typeof input.presentation.showInteractionModeToggle === "boolean"
|
||||
? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
|
||||
@@ -216,11 +208,16 @@ export function buildServerProvider(input: {
|
||||
models: input.models,
|
||||
slashCommands: [...(input.slashCommands ?? [])],
|
||||
skills: [...(input.skills ?? [])],
|
||||
...(versionAdvisory ? { versionAdvisory } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const collectStreamAsString = <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, E> =>
|
||||
collectUint8StreamText({ stream }).pipe(Effect.map((collected) => collected.text));
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
);
|
||||
@@ -140,10 +140,8 @@ export const readProviderStatusCache = (filePath: string) =>
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) => {
|
||||
const { updateState: _updateState, ...cacheableProvider } = input.provider;
|
||||
return writeFileStringAtomically({
|
||||
}) =>
|
||||
writeFileStringAtomically({
|
||||
filePath: input.filePath,
|
||||
contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
|
||||
contents: `${JSON.stringify(input.provider, null, 2)}\n`,
|
||||
});
|
||||
};
|
||||
@@ -23,6 +23,7 @@ export interface UnavailableProviderSnapshotInput {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly displayName?: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly reason: string;
|
||||
/**
|
||||
* Optional override for `checkedAt`. Defaulted to `new Date()` so callers
|
||||
@@ -62,6 +63,7 @@ export function buildUnavailableProviderSnapshot(
|
||||
...base,
|
||||
instanceId: input.instanceId,
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
driver:
|
||||
typeof input.driverKind === "string"
|
||||
? ProviderDriverKind.make(input.driverKind)
|
||||
|
||||
@@ -80,7 +80,6 @@ import {
|
||||
ProviderRegistry,
|
||||
type ProviderRegistryShape,
|
||||
} from "./provider/Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
|
||||
@@ -114,8 +113,6 @@ import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
|
||||
const defaultProjectId = ProjectId.make("project-default");
|
||||
const defaultThreadId = ThreadId.make("thread-default");
|
||||
@@ -520,12 +517,6 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.mock(ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
refresh: () => Effect.succeed([]),
|
||||
refreshInstance: () => Effect.succeed([]),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }),
|
||||
),
|
||||
setProviderMaintenanceActionState: () => Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
...options?.layers?.providerRegistry,
|
||||
}),
|
||||
@@ -545,52 +536,6 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.open,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({
|
||||
read: Effect.succeed({
|
||||
serverPid: process.pid,
|
||||
readAt: TEST_EPOCH,
|
||||
processCount: 0,
|
||||
totalRssBytes: 0,
|
||||
totalCpuPercent: 0,
|
||||
processes: [],
|
||||
error: Option.none(),
|
||||
}),
|
||||
signal: (input) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(TraceDiagnostics.TraceDiagnostics)({
|
||||
read: () =>
|
||||
Effect.succeed({
|
||||
traceFilePath: "",
|
||||
scannedFilePaths: [],
|
||||
readAt: TEST_EPOCH,
|
||||
recordCount: 0,
|
||||
parseErrorCount: 0,
|
||||
firstSpanAt: Option.none(),
|
||||
lastSpanAt: Option.none(),
|
||||
failureCount: 0,
|
||||
interruptionCount: 0,
|
||||
slowSpanThresholdMs: 1_000,
|
||||
slowSpanCount: 0,
|
||||
logLevelCounts: {},
|
||||
topSpansByCount: [],
|
||||
slowestSpans: [],
|
||||
commonFailures: [],
|
||||
latestFailures: [],
|
||||
latestWarningAndErrorLogs: [],
|
||||
partialFailure: Option.none(),
|
||||
error: Option.none(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
@@ -614,6 +559,7 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(OrchestrationEngineService)({
|
||||
getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 0 }),
|
||||
streamDomainEvents: Stream.empty,
|
||||
@@ -622,7 +568,6 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getCommandReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
@@ -631,7 +576,6 @@ const buildAppUnderTest = (options?: {
|
||||
threads: [],
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
}),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
@@ -1966,42 +1910,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc server.removeKeybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const rule: KeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
};
|
||||
const resolved: ResolvedKeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
keybindings: {
|
||||
removeKeybindingRule: () => Effect.succeed([resolved]),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverRemoveKeybinding](rule)),
|
||||
);
|
||||
|
||||
assert.deepEqual(response.issues, []);
|
||||
assert.deepEqual(response.keybindings, [resolved]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -74,8 +74,6 @@ import {
|
||||
} from "./auth/http.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
@@ -278,8 +276,6 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
|
||||
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
|
||||
// Misc.
|
||||
Layer.provideMerge(ProcessDiagnostics.layer),
|
||||
Layer.provideMerge(TraceDiagnostics.layer),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(ServerLifecycleEventsLive),
|
||||
|
||||
@@ -77,10 +77,8 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
|
||||
yield* launchStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () =>
|
||||
Deferred.await(releaseCounts).pipe(
|
||||
Effect.as({
|
||||
@@ -131,10 +129,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () =>
|
||||
Effect.succeed(
|
||||
@@ -156,6 +152,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
@@ -183,10 +180,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
@@ -196,6 +191,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
|
||||
@@ -287,18 +287,7 @@ it.effect("expands all-state pull request listing instead of relying on Bitbucke
|
||||
|
||||
it.effect("reads repository clone URLs and default branch", () => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
branch: { name: "main" },
|
||||
name: "main",
|
||||
use_mainbranch: true,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
response: () => Response.json(repositoryJson),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
@@ -318,86 +307,6 @@ it.effect("reads repository clone URLs and default branch", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"prefers the Bitbucket branching model development branch as the default PR target",
|
||||
() => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
branch: { name: "develop" },
|
||||
name: "develop",
|
||||
use_mainbranch: false,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "develop");
|
||||
assert.deepStrictEqual(
|
||||
execute.mock.calls.map((call) => call[0].url).toSorted(),
|
||||
[
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code",
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code/branching-model",
|
||||
].toSorted(),
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to the repository main branch when the Bitbucket development branch is invalid",
|
||||
() => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
name: "develop",
|
||||
use_mainbranch: false,
|
||||
is_valid: false,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to the repository main branch when the Bitbucket branching model is unavailable",
|
||||
() => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
request.url.endsWith("/branching-model")
|
||||
? Response.json({ error: { message: "Not found" } }, { status: 404 })
|
||||
: Response.json(repositoryJson),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("creates repositories through the Bitbucket REST API", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () => Response.json(repositoryJson),
|
||||
|
||||
@@ -65,23 +65,6 @@ const RawBitbucketRepositorySchema = Schema.Struct({
|
||||
),
|
||||
});
|
||||
|
||||
const RawBitbucketBranchingModelSchema = Schema.Struct({
|
||||
development: Schema.optional(
|
||||
Schema.Struct({
|
||||
branch: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
name: Schema.optional(TrimmedNonEmptyString),
|
||||
}),
|
||||
),
|
||||
),
|
||||
is_valid: Schema.optional(Schema.Boolean),
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
use_mainbranch: Schema.optional(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const BitbucketUserSchema = Schema.Struct({
|
||||
username: Schema.optional(TrimmedNonEmptyString),
|
||||
display_name: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -233,7 +216,7 @@ function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: typeof RawBitbucketRepositorySchema.Type,
|
||||
raw: Schema.Schema.Type<typeof RawBitbucketRepositorySchema>,
|
||||
): SourceControlRepositoryCloneUrls {
|
||||
const httpClone =
|
||||
raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
|
||||
@@ -247,24 +230,6 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
function defaultChangeRequestTargetBranch(input: {
|
||||
readonly repository: typeof RawBitbucketRepositorySchema.Type;
|
||||
readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
|
||||
}): string | null {
|
||||
const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
|
||||
const development = input.branchingModel?.development;
|
||||
if (!development || development.use_mainbranch === true || development.is_valid === false) {
|
||||
return repositoryMainBranch;
|
||||
}
|
||||
|
||||
const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
|
||||
if (developmentBranch.length === 0 || developmentBranch === "null") {
|
||||
return repositoryMainBranch;
|
||||
}
|
||||
|
||||
return developmentBranch;
|
||||
}
|
||||
|
||||
function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
|
||||
const trimmed = originRemoteUrl?.trim() ?? "";
|
||||
return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
|
||||
@@ -465,32 +430,23 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
|
||||
executeJson(
|
||||
"getRepository",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
|
||||
),
|
||||
),
|
||||
RawBitbucketRepositorySchema,
|
||||
);
|
||||
|
||||
const getRepository = (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly repository?: string;
|
||||
}) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
|
||||
|
||||
const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
|
||||
executeJson(
|
||||
"getBranchingModel",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
|
||||
}) =>
|
||||
resolveRepository(input).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
executeJson(
|
||||
"getRepository",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
|
||||
),
|
||||
),
|
||||
RawBitbucketRepositorySchema,
|
||||
),
|
||||
),
|
||||
RawBitbucketBranchingModelSchema,
|
||||
);
|
||||
|
||||
const getRawPullRequestFromRepository = (
|
||||
@@ -672,22 +628,7 @@ export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
);
|
||||
}),
|
||||
getDefaultBranch: (input) =>
|
||||
resolveRepository(input).pipe(
|
||||
Effect.flatMap((locator) =>
|
||||
Effect.all(
|
||||
{
|
||||
repository: getRepositoryFromLocator(locator),
|
||||
branchingModel: getBranchingModelFromLocator(locator).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed<typeof RawBitbucketBranchingModelSchema.Type | null>(null),
|
||||
),
|
||||
),
|
||||
},
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.map(defaultChangeRequestTargetBranch),
|
||||
),
|
||||
getRepository(input).pipe(Effect.map((repository) => repository.mainbranch?.name ?? null)),
|
||||
// Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
|
||||
// an official checkout CLI. This provider-local path uses GitVcsDriver as a
|
||||
// narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
|
||||
import { collectUint8StreamText } from "./collectUint8StreamText.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
describe("collectUint8StreamText", () => {
|
||||
it.effect("collects Uint8Array chunks into decoded text", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* collectUint8StreamText({
|
||||
stream: Stream.make(encoder.encode("hello "), encoder.encode("world")),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
text: "hello world",
|
||||
bytes: 11,
|
||||
truncated: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("truncates by bytes and appends an optional marker once", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* collectUint8StreamText({
|
||||
stream: Stream.make(encoder.encode("abcdef"), encoder.encode("ghij")),
|
||||
maxBytes: 5,
|
||||
truncatedMarker: "[truncated]",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
text: "abcde[truncated]",
|
||||
bytes: 5,
|
||||
truncated: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
import { Effect, Stream } from "effect";
|
||||
|
||||
export interface CollectedUint8StreamText {
|
||||
readonly text: string;
|
||||
readonly truncated: boolean;
|
||||
readonly bytes: number;
|
||||
}
|
||||
|
||||
interface CollectState {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export const collectUint8StreamText = <E>(input: {
|
||||
readonly stream: Stream.Stream<Uint8Array, E>;
|
||||
readonly maxBytes?: number | undefined;
|
||||
readonly truncatedMarker?: string | null | undefined;
|
||||
}): Effect.Effect<CollectedUint8StreamText, E> => {
|
||||
const decoder = new TextDecoder();
|
||||
const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
|
||||
const truncatedMarker = input.truncatedMarker ?? "";
|
||||
|
||||
return input.stream.pipe(
|
||||
Stream.runFold(
|
||||
(): CollectState => ({
|
||||
text: "",
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}),
|
||||
(state, chunk): CollectState => {
|
||||
if (state.truncated) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const remainingBytes = maxBytes - state.bytes;
|
||||
if (remainingBytes <= 0) {
|
||||
return {
|
||||
...state,
|
||||
text: `${state.text}${truncatedMarker}`,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
const nextChunk =
|
||||
chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
const text = `${state.text}${decoder.decode(nextChunk, { stream: true })}`;
|
||||
const bytes = state.bytes + nextChunk.byteLength;
|
||||
const truncated = chunk.byteLength > remainingBytes;
|
||||
|
||||
return {
|
||||
text: truncated ? `${text}${truncatedMarker}` : text,
|
||||
bytes,
|
||||
truncated,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map(
|
||||
(state): CollectedUint8StreamText => ({
|
||||
text: state.truncated ? state.text : `${state.text}${decoder.decode()}`,
|
||||
bytes: state.bytes,
|
||||
truncated: state.truncated,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -238,7 +238,9 @@ const createManager = (
|
||||
...(options.subprocessPollIntervalMs !== undefined
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
: {}),
|
||||
processKillGraceMs: options.processKillGraceMs ?? 1,
|
||||
...(options.processKillGraceMs !== undefined
|
||||
? { processKillGraceMs: options.processKillGraceMs }
|
||||
: {}),
|
||||
...(options.maxRetainedInactiveSessions !== undefined
|
||||
? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions }
|
||||
: {}),
|
||||
|
||||
@@ -528,7 +528,7 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
|
||||
};
|
||||
});
|
||||
|
||||
const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
@@ -541,7 +541,7 @@ const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
let lineBuffer = "";
|
||||
let truncated = false;
|
||||
|
||||
const emitCompleteLines = Effect.fnUntraced(function* (flush: boolean) {
|
||||
const emitCompleteLines = Effect.fn("emitCompleteLines")(function* (flush: boolean) {
|
||||
let newlineIndex = lineBuffer.indexOf("\n");
|
||||
while (newlineIndex >= 0) {
|
||||
const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
|
||||
@@ -561,7 +561,7 @@ const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
}
|
||||
});
|
||||
|
||||
const processChunk = Effect.fnUntraced(function* (chunk: Uint8Array) {
|
||||
const processChunk = Effect.fn("processChunk")(function* (chunk: Uint8Array) {
|
||||
if (truncateOutputAtMaxBytes && truncated) {
|
||||
return;
|
||||
}
|
||||
@@ -602,14 +602,20 @@ const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
};
|
||||
});
|
||||
|
||||
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* () {
|
||||
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (options?: {
|
||||
executeOverride?: GitVcsDriver.GitVcsDriverShape["execute"];
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const { worktreesDir } = yield* ServerConfig;
|
||||
|
||||
const executeRaw: GitVcsDriver.GitVcsDriverShape["execute"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
let executeRaw: GitVcsDriver.GitVcsDriverShape["execute"];
|
||||
|
||||
if (options?.executeOverride) {
|
||||
executeRaw = options.executeOverride;
|
||||
} else {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
executeRaw = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
args: [...input.args],
|
||||
@@ -706,8 +712,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const execute: GitVcsDriver.GitVcsDriverShape["execute"] = (input) =>
|
||||
executeRaw(input).pipe(
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
export interface VcsProcessInput {
|
||||
readonly operation: string;
|
||||
@@ -87,12 +86,44 @@ export const collectText = Effect.fn("VcsProcess.collectText")(function* (input:
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) {
|
||||
const decoder = new TextDecoder();
|
||||
let text = "";
|
||||
let bytes = 0;
|
||||
let truncated = false;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
return yield* collectUint8StreamText({
|
||||
stream: input.stream,
|
||||
maxBytes: maxOutputBytes,
|
||||
truncatedMarker: input.truncateOutputAtMaxBytes ? OUTPUT_TRUNCATED_MARKER : null,
|
||||
});
|
||||
const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false;
|
||||
|
||||
yield* Stream.runForEach(input.stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
if (truncated) return;
|
||||
|
||||
const remainingBytes = maxOutputBytes - bytes;
|
||||
if (remainingBytes <= 0) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextChunk = chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
text += decoder.decode(nextChunk, { stream: true });
|
||||
bytes += nextChunk.byteLength;
|
||||
|
||||
if (chunk.byteLength > remainingBytes) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (!truncated) {
|
||||
text += decoder.decode();
|
||||
}
|
||||
|
||||
return { text, truncated } satisfies VcsProcessCollectedText;
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeVcsProcess")(function* () {
|
||||
|
||||
+90
-56
@@ -1,6 +1,7 @@
|
||||
import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type AuthAccessStreamEvent,
|
||||
AcpRegistryIndex,
|
||||
AuthSessionId,
|
||||
CommandId,
|
||||
EventId,
|
||||
@@ -40,7 +41,7 @@ import {
|
||||
observeRpcStreamEffect,
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import { AcpRegistryClientError } from "./provider/Services/AcpRegistryClient.ts";
|
||||
import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";
|
||||
import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts";
|
||||
@@ -55,8 +56,6 @@ import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptR
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
|
||||
import { SourceControlRepositoryService } from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
|
||||
@@ -77,6 +76,10 @@ import {
|
||||
type SessionCredentialChange,
|
||||
} from "./auth/Services/SessionCredentialService.ts";
|
||||
import { respondToAuthError } from "./auth/http.ts";
|
||||
import {
|
||||
installAcpRegistryBinaryAgent,
|
||||
listAcpRegistryAgents,
|
||||
} from "./provider/acp/AcpRegistryBinaryInstaller.ts";
|
||||
|
||||
function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -155,7 +158,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const config = yield* ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
@@ -170,7 +172,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const sourceControlRepositories = yield* SourceControlRepositoryService;
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
const serverCommandId = (tag: string) =>
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
@@ -180,6 +181,57 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(Effect.orDie),
|
||||
});
|
||||
|
||||
const loadAcpRegistryIndex = serverSettings.getSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const response = await fetch(settings.providers.acpRegistry.registryUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Registry request failed with status ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new AcpRegistryClientError({
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((raw) => Schema.decodeUnknownEffect(AcpRegistryIndex)(raw)),
|
||||
);
|
||||
|
||||
const listAcpRegistry = loadAcpRegistryIndex.pipe(
|
||||
Effect.flatMap((registry) => listAcpRegistryAgents(registry)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryClientError({
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const installAcpRegistryBinary = (input: {
|
||||
readonly agentId: string;
|
||||
readonly installPath?: string | undefined;
|
||||
}) =>
|
||||
loadAcpRegistryIndex.pipe(
|
||||
Effect.flatMap((registry) =>
|
||||
installAcpRegistryBinaryAgent({
|
||||
registry,
|
||||
agentId: input.agentId,
|
||||
installPath: input.installPath,
|
||||
}),
|
||||
),
|
||||
Effect.catch((cause: unknown) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
error: cause instanceof Error ? cause.message : String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const appendSetupScriptActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
|
||||
@@ -241,13 +293,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
return Effect.gen(function* () {
|
||||
const workspaceRoot =
|
||||
event.payload.workspaceRoot ??
|
||||
Option.match(
|
||||
yield* projectionSnapshotQuery.getProjectShellById(event.payload.projectId),
|
||||
{
|
||||
onNone: () => null,
|
||||
onSome: (project) => project.workspaceRoot,
|
||||
},
|
||||
) ??
|
||||
(yield* orchestrationEngine.getReadModel()).projects.find(
|
||||
(project) => project.id === event.payload.projectId,
|
||||
)?.workspaceRoot ??
|
||||
null;
|
||||
if (workspaceRoot === null) {
|
||||
return event;
|
||||
@@ -261,7 +309,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
repositoryIdentity,
|
||||
},
|
||||
} satisfies OrchestrationEvent;
|
||||
}).pipe(Effect.catch(() => Effect.succeed(event)));
|
||||
});
|
||||
default:
|
||||
return Effect.succeed(event);
|
||||
}
|
||||
@@ -732,16 +780,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
),
|
||||
),
|
||||
projectionSnapshotQuery.getSnapshotSequence().pipe(
|
||||
Effect.map(({ snapshotSequence }) => snapshotSequence),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration snapshot sequence",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
orchestrationEngine
|
||||
.getReadModel()
|
||||
.pipe(Effect.map((readModel) => readModel.snapshotSequence)),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadDetail)) {
|
||||
@@ -790,14 +831,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
).pipe(Effect.map((providers) => ({ providers }))),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverUpdateProvider]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpdateProvider,
|
||||
providerMaintenanceRunner.updateProvider(input),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpsertKeybinding,
|
||||
@@ -807,15 +840,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverRemoveKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverRemoveKeybinding,
|
||||
Effect.gen(function* () {
|
||||
const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
|
||||
return { keybindings: keybindingsConfig, issues: [] };
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverGetSettings]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetSettings,
|
||||
@@ -840,25 +864,32 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverGetTraceDiagnostics]: (_input) =>
|
||||
[WS_METHODS.serverListAcpRegistry]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
TraceDiagnostics.readTraceDiagnostics({
|
||||
traceFilePath: config.serverTracePath,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
}),
|
||||
WS_METHODS.serverListAcpRegistry,
|
||||
listAcpRegistry.pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("failed to list ACP registry agents", {
|
||||
error: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => ({
|
||||
registryVersion: "unavailable",
|
||||
agents: [],
|
||||
})),
|
||||
),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverInstallAcpRegistryBinary]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverInstallAcpRegistryBinary,
|
||||
installAcpRegistryBinary(input),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverGetProcessDiagnostics]: (_input) =>
|
||||
observeRpcEffect(WS_METHODS.serverGetProcessDiagnostics, processDiagnostics.read, {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.serverSignalProcess]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.sourceControlLookupRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
@@ -1184,12 +1215,15 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const session = yield* serverAuth.authenticateWebSocketUpgrade(request);
|
||||
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
|
||||
disableTracing: true,
|
||||
spanPrefix: "ws.rpc",
|
||||
spanAttributes: {
|
||||
"rpc.transport": "websocket",
|
||||
"rpc.system": "effect-rpc",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeWsRpcLayer(session.sessionId).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(
|
||||
SourceControlDiscoveryLayer.layer.pipe(
|
||||
Layer.provide(
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.21",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"prepare": "effect-language-service patch",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
@@ -22,7 +23,7 @@
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
|
||||
@@ -1,25 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
const HEIGHT_TRANSITION_FALLBACK_MS = 250;
|
||||
import { type ReactNode, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [heightState, setHeightState] = useState<{
|
||||
readonly height: number | null;
|
||||
readonly isClipping: boolean;
|
||||
}>({ height: null, isClipping: false });
|
||||
|
||||
useEffect(() => {
|
||||
if (!heightState.isClipping) return;
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
setHeightState((currentState) =>
|
||||
currentState.isClipping ? { ...currentState, isClipping: false } : currentState,
|
||||
);
|
||||
}, HEIGHT_TRANSITION_FALLBACK_MS);
|
||||
return () => window.clearTimeout(timeoutId);
|
||||
}, [heightState.height, heightState.isClipping]);
|
||||
const [height, setHeight] = useState<number | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = contentRef.current;
|
||||
@@ -29,13 +14,7 @@ export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
|
||||
|
||||
const updateHeight = () => {
|
||||
const nextHeight = Math.ceil(element.scrollHeight || element.getBoundingClientRect().height);
|
||||
setHeightState((currentState) => {
|
||||
if (currentState.height === nextHeight) return currentState;
|
||||
return {
|
||||
height: nextHeight,
|
||||
isClipping: currentState.height !== null,
|
||||
};
|
||||
});
|
||||
setHeight((currentHeight) => (currentHeight === nextHeight ? currentHeight : nextHeight));
|
||||
};
|
||||
const cancelPendingFrames = () => {
|
||||
if (firstFrameId !== null) {
|
||||
@@ -71,19 +50,8 @@ export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="animated-height"
|
||||
className="transition-[height] duration-200 ease-out motion-reduce:transition-none"
|
||||
style={
|
||||
heightState.height === null
|
||||
? undefined
|
||||
: { height: heightState.height, overflow: heightState.isClipping ? "hidden" : "visible" }
|
||||
}
|
||||
onTransitionEnd={(event) => {
|
||||
if (event.target !== event.currentTarget || event.propertyName !== "height") return;
|
||||
setHeightState((currentState) =>
|
||||
currentState.isClipping ? { ...currentState, isClipping: false } : currentState,
|
||||
);
|
||||
}}
|
||||
className="overflow-hidden transition-[height] duration-200 ease-out motion-reduce:transition-none"
|
||||
style={height === null ? undefined : { height }}
|
||||
>
|
||||
<div ref={contentRef}>{children}</div>
|
||||
</div>
|
||||
|
||||
@@ -65,7 +65,7 @@ describe("ChatMarkdown", () => {
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "PermissionRule.ts · L1" });
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}:1`);
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}#L1`);
|
||||
|
||||
await link.click();
|
||||
|
||||
@@ -87,7 +87,7 @@ describe("ChatMarkdown", () => {
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "PermissionRule.ts · L1:C7" });
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}:1:7`);
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}#L1C7`);
|
||||
|
||||
await link.click();
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
import React, {
|
||||
Children,
|
||||
Suspense,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
memo,
|
||||
useEffect,
|
||||
@@ -20,18 +22,35 @@ import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { resolveSyntaxThemeName } from "../lib/syntaxTheme";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
normalizeMarkdownLinkDestination,
|
||||
resolveMarkdownFileLinkMeta,
|
||||
rewriteMarkdownFileUriHref,
|
||||
} from "../markdown-links";
|
||||
import { resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref } from "../markdown-links";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
{ fallback: ReactNode; children: ReactNode },
|
||||
{ hasError: boolean }
|
||||
> {
|
||||
constructor(props: { fallback: ReactNode; children: ReactNode }) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
override render() {
|
||||
if (this.state.hasError) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
@@ -46,26 +65,12 @@ const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
const unsupportedHighlightLanguages = new Set<string>();
|
||||
const HIGHLIGHT_LANGUAGE_ALIASES: Readonly<Record<string, string>> = {
|
||||
baml: "text",
|
||||
gitignore: "ini",
|
||||
plaintext: "text",
|
||||
txt: "text",
|
||||
};
|
||||
|
||||
function normalizeHighlightLanguage(language: string): string {
|
||||
const normalizedLanguage = language.trim().toLowerCase();
|
||||
if (!normalizedLanguage) {
|
||||
return "text";
|
||||
}
|
||||
return HIGHLIGHT_LANGUAGE_ALIASES[normalizedLanguage] ?? normalizedLanguage;
|
||||
}
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
const raw = match?.[1] ?? "text";
|
||||
return normalizeHighlightLanguage(raw);
|
||||
// Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
|
||||
return raw === "gitignore" ? "ini" : raw;
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
@@ -103,7 +108,7 @@ function extractCodeBlock(
|
||||
};
|
||||
}
|
||||
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: string): string {
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||
}
|
||||
|
||||
@@ -111,71 +116,27 @@ function estimateHighlightedSize(html: string, code: string): number {
|
||||
return Math.max(html.length * 2, code.length * 3);
|
||||
}
|
||||
|
||||
function getHighlighterPromise(language: string, themeName: string): Promise<DiffsHighlighter> {
|
||||
const highlighterLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
|
||||
const cacheKey = `${highlighterLanguage}:${themeName}`;
|
||||
const cached = highlighterPromiseCache.get(cacheKey);
|
||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
const cached = highlighterPromiseCache.get(language);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = getSharedHighlighter({
|
||||
themes: [themeName],
|
||||
langs: [highlighterLanguage as SupportedLanguages],
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
}).catch((err) => {
|
||||
highlighterPromiseCache.delete(cacheKey);
|
||||
if (highlighterLanguage === "text") {
|
||||
highlighterPromiseCache.delete(language);
|
||||
if (language === "text") {
|
||||
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
||||
throw err;
|
||||
}
|
||||
// Language not supported by Shiki — fall back to "text"
|
||||
unsupportedHighlightLanguages.add(highlighterLanguage);
|
||||
return getHighlighterPromise("text", themeName);
|
||||
return getHighlighterPromise("text");
|
||||
});
|
||||
highlighterPromiseCache.set(cacheKey, promise);
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function renderHighlightedHtml(
|
||||
highlighter: DiffsHighlighter,
|
||||
code: string,
|
||||
language: string,
|
||||
themeName: string,
|
||||
): string {
|
||||
const highlightLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
|
||||
try {
|
||||
return highlighter.codeToHtml(code, {
|
||||
lang: highlightLanguage as SupportedLanguages,
|
||||
theme: themeName,
|
||||
});
|
||||
} catch (error) {
|
||||
if (highlightLanguage === "text") {
|
||||
throw error;
|
||||
}
|
||||
unsupportedHighlightLanguages.add(highlightLanguage);
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleHighlightWork(callback: () => void): () => void {
|
||||
if (typeof window === "undefined") {
|
||||
callback();
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const idleWindow = window as Window & {
|
||||
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
|
||||
cancelIdleCallback?: (handle: number) => void;
|
||||
};
|
||||
|
||||
if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {
|
||||
const idleHandle = idleWindow.requestIdleCallback(callback, { timeout: 1500 });
|
||||
return () => idleWindow.cancelIdleCallback?.(idleHandle);
|
||||
}
|
||||
|
||||
const timeoutHandle = window.setTimeout(callback, 0);
|
||||
return () => window.clearTimeout(timeoutHandle);
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
@@ -224,94 +185,59 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
|
||||
);
|
||||
}
|
||||
|
||||
interface ShikiCodeBlockProps {
|
||||
interface SuspenseShikiCodeBlockProps {
|
||||
className: string | undefined;
|
||||
code: string;
|
||||
themeName: string;
|
||||
themeName: DiffThemeName;
|
||||
isStreaming: boolean;
|
||||
fallback: ReactNode;
|
||||
}
|
||||
|
||||
type HighlightedCodeState = {
|
||||
cacheKey: string;
|
||||
html: string;
|
||||
};
|
||||
|
||||
function ShikiCodeBlock({
|
||||
function SuspenseShikiCodeBlock({
|
||||
className,
|
||||
code,
|
||||
themeName,
|
||||
isStreaming,
|
||||
fallback,
|
||||
}: ShikiCodeBlockProps) {
|
||||
}: SuspenseShikiCodeBlockProps) {
|
||||
const language = extractFenceLanguage(className);
|
||||
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||
const [highlightedCode, setHighlightedCode] = useState<HighlightedCodeState | null>(() => {
|
||||
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
|
||||
return cachedHighlightedHtml == null ? null : { cacheKey, html: cachedHighlightedHtml };
|
||||
});
|
||||
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (isStreaming) {
|
||||
setHighlightedCode(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const cachedHighlightedHtml = highlightedCodeCache.get(cacheKey);
|
||||
if (cachedHighlightedHtml != null) {
|
||||
setHighlightedCode({ cacheKey, html: cachedHighlightedHtml });
|
||||
return;
|
||||
}
|
||||
|
||||
let isCancelled = false;
|
||||
let cancelHighlightWork: (() => void) | null = null;
|
||||
setHighlightedCode(null);
|
||||
|
||||
void getHighlighterPromise(language, themeName)
|
||||
.then((highlighter) => {
|
||||
if (isCancelled) return;
|
||||
cancelHighlightWork = scheduleHighlightWork(() => {
|
||||
if (isCancelled) return;
|
||||
let highlightedHtml: string;
|
||||
try {
|
||||
highlightedHtml = renderHighlightedHtml(highlighter, code, language, themeName);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (isCancelled) return;
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
setHighlightedCode({ cacheKey, html: highlightedHtml });
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (!isCancelled) {
|
||||
setHighlightedCode(null);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
cancelHighlightWork?.();
|
||||
};
|
||||
}, [cacheKey, code, isStreaming, language, themeName]);
|
||||
|
||||
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
|
||||
const activeHighlightedHtml =
|
||||
cachedHighlightedHtml ?? (highlightedCode?.cacheKey === cacheKey ? highlightedCode.html : null);
|
||||
|
||||
if (activeHighlightedHtml == null) {
|
||||
return <>{fallback}</>;
|
||||
if (cachedHighlightedHtml != null) {
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(() => {
|
||||
try {
|
||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
||||
} catch (error) {
|
||||
// Log highlighting failures for debugging while falling back to plain text
|
||||
console.warn(
|
||||
`Code highlighting failed for language "${language}", falling back to plain text.`,
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
// If highlighting fails for this language, render as plain text
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}, [code, highlighter, language, themeName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
}
|
||||
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: activeHighlightedHtml }}
|
||||
/>
|
||||
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -402,8 +328,7 @@ function extractMarkdownLinkHrefs(text: string): string[] {
|
||||
}
|
||||
|
||||
function normalizeMarkdownLinkHrefKey(href: string): string {
|
||||
const normalizedHref = normalizeMarkdownLinkDestination(href);
|
||||
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
|
||||
return rewriteMarkdownFileUriHref(href.trim()) ?? href.trim();
|
||||
}
|
||||
|
||||
const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
@@ -552,11 +477,8 @@ function areMarkdownFileLinkPropsEqual(
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme, resolvedColorTheme } = useTheme();
|
||||
const codeBlockThemeName = useMemo(
|
||||
() => resolveSyntaxThemeName({ resolvedTheme, resolvedColorTheme }),
|
||||
[resolvedColorTheme, resolvedTheme],
|
||||
);
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownFileLinkMetaByHref = useMemo(() => {
|
||||
const metaByHref = new Map<
|
||||
string,
|
||||
@@ -601,7 +523,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
|
||||
return (
|
||||
<MarkdownFileLink
|
||||
href={fileLinkMeta.targetPath}
|
||||
href={href ?? fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
filePath={fileLinkMeta.filePath}
|
||||
@@ -619,19 +541,22 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<ShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={codeBlockThemeName}
|
||||
isStreaming={isStreaming}
|
||||
fallback={<pre {...props}>{children}</pre>}
|
||||
/>
|
||||
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</CodeHighlightErrorBoundary>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[
|
||||
codeBlockThemeName,
|
||||
diffThemeName,
|
||||
fileLinkParentSuffixByPath,
|
||||
isStreaming,
|
||||
markdownFileLinkMetaByHref,
|
||||
|
||||
@@ -116,7 +116,7 @@ import {
|
||||
} from "~/projectScripts";
|
||||
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { useProjectGroupingSettings, useSettings } from "../hooks/useSettings";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
|
||||
@@ -941,7 +941,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
},
|
||||
[],
|
||||
);
|
||||
const projectGroupingSettings = useProjectGroupingSettings();
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const logicalProjectEnvironments = useMemo(() => {
|
||||
if (!activeProject) return [];
|
||||
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
Columns2Icon,
|
||||
@@ -30,7 +29,7 @@ import { resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveSyntaxThemeName } from "../lib/syntaxTheme";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { selectProjectByRef, useStore } from "../store";
|
||||
import { createThreadSelectorByRef } from "../storeSelectors";
|
||||
@@ -162,21 +161,6 @@ function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
|
||||
switch (fileDiff.type) {
|
||||
case "new":
|
||||
return "text-[var(--diffs-addition-base)]";
|
||||
case "deleted":
|
||||
return "text-[var(--diffs-deletion-base)]";
|
||||
case "change":
|
||||
case "rename-pure":
|
||||
case "rename-changed":
|
||||
return "text-[var(--diffs-modified-base)]";
|
||||
default:
|
||||
return "text-muted-foreground/80";
|
||||
}
|
||||
}
|
||||
|
||||
interface DiffPanelProps {
|
||||
mode?: DiffPanelMode;
|
||||
}
|
||||
@@ -185,18 +169,11 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme, resolvedColorTheme } = useTheme();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const diffThemeName = useMemo(
|
||||
() => resolveSyntaxThemeName({ resolvedTheme, resolvedColorTheme }),
|
||||
[resolvedColorTheme, resolvedTheme],
|
||||
);
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
const [collapsedDiffFileKeys, setCollapsedDiffFileKeys] = useState<ReadonlySet<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const previousDiffOpenRef = useRef(false);
|
||||
@@ -325,8 +302,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const hasResolvedPatch = typeof selectedPatch === "string";
|
||||
const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
|
||||
const renderablePatch = useMemo(
|
||||
() => getRenderablePatch(selectedPatch, `diff-panel:${diffThemeName}`),
|
||||
[diffThemeName, selectedPatch],
|
||||
() => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
|
||||
[resolvedTheme, selectedPatch],
|
||||
);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
@@ -340,19 +317,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
);
|
||||
}, [renderablePatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (renderableFiles.length === 0) {
|
||||
setCollapsedDiffFileKeys((current) => (current.size === 0 ? current : new Set()));
|
||||
return;
|
||||
}
|
||||
|
||||
const visibleFileKeys = new Set(renderableFiles.map(buildFileDiffRenderKey));
|
||||
setCollapsedDiffFileKeys((current) => {
|
||||
const next = new Set([...current].filter((fileKey) => visibleFileKeys.has(fileKey)));
|
||||
return next.size === current.size ? current : next;
|
||||
});
|
||||
}, [renderableFiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (diffOpen && !previousDiffOpenRef.current) {
|
||||
setDiffWordWrap(settings.diffWordWrap);
|
||||
@@ -382,17 +346,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
},
|
||||
[activeCwd],
|
||||
);
|
||||
const toggleDiffFileCollapsed = useCallback((fileKey: string) => {
|
||||
setCollapsedDiffFileKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(fileKey)) {
|
||||
next.delete(fileKey);
|
||||
} else {
|
||||
next.add(fileKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!activeThread) return;
|
||||
@@ -666,13 +619,12 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
{renderableFiles.map((fileDiff) => {
|
||||
const filePath = resolveFileDiffPath(fileDiff);
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${diffThemeName}`;
|
||||
const collapsed = collapsedDiffFileKeys.has(fileKey);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
return (
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file group/diff-file mb-2 rounded-md first:mt-2 last:mb-0"
|
||||
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
@@ -686,34 +638,11 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
renderHeaderPrefix={() => (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
|
||||
getDiffCollapseIconClassName(fileDiff),
|
||||
)}
|
||||
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
|
||||
aria-expanded={!collapsed}
|
||||
title={collapsed ? "Expand diff" : "Collapse diff"}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleDiffFileCollapsed(fileKey);
|
||||
}}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRightIcon className="size-4" />
|
||||
) : (
|
||||
<ChevronDownIcon className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
options={{
|
||||
collapsed,
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
overflow: diffWordWrap ? "wrap" : "scroll",
|
||||
theme: diffThemeName,
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
}}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { DiffsThemeNames } from "@pierre/diffs";
|
||||
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveSyntaxThemeName } from "../lib/syntaxTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffsThemeNames }) {
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -30,11 +29,8 @@ function DiffWorkerThemeSync({ themeName }: { themeName: DiffsThemeNames }) {
|
||||
}
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const { resolvedTheme, resolvedColorTheme } = useTheme();
|
||||
const diffThemeName = useMemo(
|
||||
() => resolveSyntaxThemeName({ resolvedTheme, resolvedColorTheme }),
|
||||
[resolvedColorTheme, resolvedTheme],
|
||||
);
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores =
|
||||
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { type SVGProps, useId } from "react";
|
||||
import { type SVGProps, useId } from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||
@@ -635,6 +635,107 @@ export const AntigravityIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const IntelliJIdeaIcon: Icon = (props) => {
|
||||
const id = useId();
|
||||
const gradientAId = `${id}-idea-a`;
|
||||
const gradientBId = `${id}-idea-b`;
|
||||
const gradientCId = `${id}-idea-c`;
|
||||
const gradientDId = `${id}-idea-d`;
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 70 70" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="0.7898"
|
||||
y1="40.0893"
|
||||
x2="33.3172"
|
||||
y2="40.0893"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0.2581" stopColor="#F97A12" />
|
||||
<stop offset="0.4591" stopColor="#B07B58" />
|
||||
<stop offset="0.7241" stopColor="#577BAE" />
|
||||
<stop offset="0.9105" stopColor="#1E7CE5" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="25.7674"
|
||||
y1="24.88"
|
||||
x2="79.424"
|
||||
y2="54.57"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#F97A12" />
|
||||
<stop offset="0.07179946" stopColor="#CB7A3E" />
|
||||
<stop offset="0.1541" stopColor="#9E7B6A" />
|
||||
<stop offset="0.242" stopColor="#757B91" />
|
||||
<stop offset="0.3344" stopColor="#537BB1" />
|
||||
<stop offset="0.4324" stopColor="#387CCC" />
|
||||
<stop offset="0.5381" stopColor="#237CE0" />
|
||||
<stop offset="0.6552" stopColor="#147CEF" />
|
||||
<stop offset="0.7925" stopColor="#0B7CF7" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientCId}
|
||||
x1="63.2277"
|
||||
y1="42.9153"
|
||||
x2="48.2903"
|
||||
y2="-1.7191"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#FE315D" />
|
||||
<stop offset="0.07840246" stopColor="#CB417E" />
|
||||
<stop offset="0.1601" stopColor="#9E4E9B" />
|
||||
<stop offset="0.2474" stopColor="#755BB4" />
|
||||
<stop offset="0.3392" stopColor="#5365CA" />
|
||||
<stop offset="0.4365" stopColor="#386DDB" />
|
||||
<stop offset="0.5414" stopColor="#2374E9" />
|
||||
<stop offset="0.6576" stopColor="#1478F3" />
|
||||
<stop offset="0.794" stopColor="#0B7BF8" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientDId}
|
||||
x1="10.7204"
|
||||
y1="16.473"
|
||||
x2="55.5237"
|
||||
y2="90.58"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#FE315D" />
|
||||
<stop offset="0.04023279" stopColor="#F63462" />
|
||||
<stop offset="0.1037" stopColor="#DF3A71" />
|
||||
<stop offset="0.1667" stopColor="#C24383" />
|
||||
<stop offset="0.2912" stopColor="#AD4A91" />
|
||||
<stop offset="0.5498" stopColor="#755BB4" />
|
||||
<stop offset="0.9175" stopColor="#1D76ED" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<polygon points="17.7,54.6 0.8,41.2 9.2,25.6 33.3,35" fill={`url(#${gradientAId})`} />
|
||||
<path
|
||||
d="M70 18.7 68.7 59.2 41.8 70 25.6 59.6 49.3 35 38.9 12.3 48.2 1.1Z"
|
||||
fill={`url(#${gradientBId})`}
|
||||
/>
|
||||
<polygon points="70,18.7 48.7,43.9 38.9,12.3 48.2,1.1" fill={`url(#${gradientCId})`} />
|
||||
<path
|
||||
d="M33.7 58.1 5.6 68.3 10.1 52.5 16 33.1 0 27.7 10.1 0 32.1 2.7 53.7 27.4Z"
|
||||
fill={`url(#${gradientDId})`}
|
||||
/>
|
||||
<rect x="13.7" y="13.5" width="43.2" height="43.2" fill="#000" />
|
||||
<rect x="17.7" y="48.6" width="16.2" height="2.7" fill="#fff" />
|
||||
<path d="M29.4 22.4v-3.3h-9v3.3h2.6v11.3h-2.6V37h9v-3.3h-2.5V22.4h2.5Z" fill="#fff" />
|
||||
<path
|
||||
d="M38 37.3c-1.4 0-2.6-.3-3.5-.8-.9-.5-1.7-1.2-2.3-1.9l2.5-2.8c.5.6 1 1 1.5 1.3.5.3 1.1.5 1.7.5.7 0 1.3-.2 1.8-.7.4-.5.6-1.2.6-2.3V19.1h4v11.7c0 1.1-.1 2-.4 2.8-.3.8-.7 1.4-1.3 2-.5.5-1.2 1-2 1.2-.8.3-1.6.5-2.6.5Z"
|
||||
fill="#fff"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const OpenCodeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clipPath="url(#opencode__clip0_1311_94969)">
|
||||
|
||||
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user